feat:M3「词条勾选链路」落地

This commit is contained in:
2026-11-15 14:05:24 +08:00
parent cc0f621c53
commit 62c1720b70
6 changed files with 190 additions and 43 deletions
@@ -633,12 +633,17 @@ class HaoRuiAccessibilityService : AccessibilityService() {
val accepted = startZhihuCollectSandbox(index)
RunLogger.i(TAG, "知乎采集沙盒受理=$accepted(广播 ACTION_TEST_ZHIHU cardIndex=$index)")
}
// 微博类目采集沙盒(debug APK;只读采集:类目词条清单 + 单条内容)
// 微博类目采集沙盒(debug APK;只读采集:类目词条清单 + 单条内容;collectOnlyList=仅清单)
"com.haorui.app.ACTION_TEST_WEIBO" -> {
val categoryId = intent.getStringExtra("categoryId") ?: "hot"
val entryIndex = intent.getStringExtra("entryIndex")?.toIntOrNull() ?: 0
val accepted = startWeiboCollectSandbox(categoryId, entryIndex)
RunLogger.i(TAG, "微博采集沙盒受理=$accepted(广播 ACTION_TEST_WEIBO category=$categoryId entry=$entryIndex)")
val collectOnlyList = intent.getBooleanExtra("collectOnlyList", false)
val accepted = startWeiboCollectSandbox(categoryId, entryIndex, !collectOnlyList)
RunLogger.i(
TAG,
"微博采集沙盒受理=$accepted(广播 ACTION_TEST_WEIBO category=$categoryId " +
"entry=$entryIndex collectOnlyList=$collectOnlyList)",
)
}
// 回归测试发布模式切换(草稿/正式;autoPublish 无 UI 开关,走广播)
"com.haorui.app.ACTION_SET_DRAFT" -> setAutoPublish(false)
@@ -767,52 +772,55 @@ class HaoRuiAccessibilityService : AccessibilityService() {
/**
* 仅调试 APK 的微博类目采集沙盒(端到端真机验收)。
* 先拉类目词条清单(用户勾选清单的数据源),再采单条内容全链;只读、不发布、不启调度器。
* [collectEntry] false=只拉类目词条清单(用户勾选清单的数据源);
* true=清单之后再采单条内容全链。只读、不发布、不启调度器。
*/
fun startWeiboCollectSandbox(categoryId: String, entryIndex: Int): Boolean = synchronized(stepLifecycleLock) {
if (applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE == 0 ||
!::scheduler.isInitialized || scheduler.isRunning || publisher.isWorking || interactor.isWorking ||
frontGuard.creditNavigating || !foregroundCoordinator.isIdle()) return@synchronized false
val category = com.haorui.app.crossplatform.source.weibo.WeiboHotCategories.ALL
.firstOrNull { it.id == categoryId } ?: return@synchronized false
launchForegroundTask {
val ticket = foregroundCoordinator.tryEnterLegacy("WEIBO-SANDBOX") ?: return@launchForegroundTask
try {
val machine = com.haorui.app.crossplatform.source.weibo.WeiboHotListCollector(
com.haorui.app.crossplatform.source.weibo.WeiboDevicePort(this@HaoRuiAccessibilityService),
)
RunLogger.i(TAG, "微博采集沙盒开始:类目「${category.tabLabel}」")
val list = machine.collectCategoryEntries(category)
RunLogger.i(
TAG,
"微博采集沙盒清单: outcome=${list.outcome} phase=${list.phase} exited=${list.exitedSafely} " +
"条目=${list.entries.size} reason=${list.reason}",
)
list.entries.take(5).forEachIndexed { i, e ->
RunLogger.i(TAG, "微博采集沙盒清单[$i]: ${e.title} heat=${e.heatRaw ?: "未知"} heatMissing=${e.heatMissing}")
}
val result = machine.collectOne(category, entryIndex)
RunLogger.i(
TAG,
"微博采集沙盒结果: outcome=${result.outcome} phase=${result.phase} " +
"exited=${result.exitedSafely} reason=${result.reason}",
)
result.observation?.let { obs ->
fun startWeiboCollectSandbox(categoryId: String, entryIndex: Int, collectEntry: Boolean = true): Boolean =
synchronized(stepLifecycleLock) {
if (applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE == 0 ||
!::scheduler.isInitialized || scheduler.isRunning || publisher.isWorking || interactor.isWorking ||
frontGuard.creditNavigating || !foregroundCoordinator.isIdle()) return@synchronized false
val category = com.haorui.app.crossplatform.source.weibo.WeiboHotCategories.ALL
.firstOrNull { it.id == categoryId } ?: return@synchronized false
launchForegroundTask {
val ticket = foregroundCoordinator.tryEnterLegacy("WEIBO-SANDBOX") ?: return@launchForegroundTask
try {
val machine = com.haorui.app.crossplatform.source.weibo.WeiboHotListCollector(
com.haorui.app.crossplatform.source.weibo.WeiboDevicePort(this@HaoRuiAccessibilityService),
)
RunLogger.i(TAG, "微博采集沙盒开始:类目「${category.tabLabel}」")
val list = machine.collectCategoryEntries(category)
RunLogger.i(
TAG,
"微博采集沙盒观察: 词条=${obs.hotEntry?.title?.take(20)} 作者=${obs.author} " +
"时间=${obs.publishedAtText}/${obs.publishedAtMs} 转发=${obs.repostCount} " +
"评论=${obs.commentCount} 赞=${obs.likeCount} 链接=${obs.sourceUrl} 未知=${obs.unknowns}",
"微博采集沙盒清单: outcome=${list.outcome} phase=${list.phase} exited=${list.exitedSafely} " +
"条目=${list.entries.size} reason=${list.reason}",
)
list.entries.take(5).forEachIndexed { i, e ->
RunLogger.i(TAG, "微博采集沙盒清单[$i]: ${e.title} heat=${e.heatRaw ?: "未知"} heatMissing=${e.heatMissing}")
}
if (!collectEntry) return@launchForegroundTask
val result = machine.collectOne(category, entryIndex)
RunLogger.i(
TAG,
"微博采集沙盒结果: outcome=${result.outcome} phase=${result.phase} " +
"exited=${result.exitedSafely} reason=${result.reason}",
)
result.observation?.let { obs ->
RunLogger.i(
TAG,
"微博采集沙盒观察: 词条=${obs.hotEntry?.title?.take(20)} 作者=${obs.author} " +
"时间=${obs.publishedAtText}/${obs.publishedAtMs} 转发=${obs.repostCount} " +
"评论=${obs.commentCount} 赞=${obs.likeCount} 链接=${obs.sourceUrl} 未知=${obs.unknowns}",
)
}
} catch (t: Throwable) {
RunLogger.e(TAG, "微博采集沙盒异常: ${t.javaClass.simpleName}:${t.message}", t)
} finally {
foregroundCoordinator.release(ticket)
}
} catch (t: Throwable) {
RunLogger.e(TAG, "微博采集沙盒异常: ${t.javaClass.simpleName}:${t.message}", t)
} finally {
foregroundCoordinator.release(ticket)
}
true
}
true
}
/** 新来源仅可在旧流程的完整安全边界入场,不在详情、编辑或回执中途切换。 */
fun tryEnterSourceForeground(sourceId: String): ForegroundCoordinator.Ticket? {
@@ -1,6 +1,9 @@
package com.haorui.app.crossplatform.model
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.encodeToString
import java.util.Locale
/** 新链路独立配置。来源选择不等于来源能力已验收。 */
@@ -30,6 +33,8 @@ data class CrossPlatformConfig(
val categories: List<String> = DEFAULT_CATEGORIES,
/** 微博热搜类目勾选(WeiboHotCategories.id;空=未选择。旧配置缺字段按空处理保持兼容)。 */
val weiboHotCategories: List<String> = emptyList(),
/** 微博热搜词条勾选(类目 id → 勾选的词条标题;重启不丢,重启后榜单已刷新——按标题在新榜单中匹配,匹配不到保留待核)。 */
val weiboHotTopics: Map<String, List<String>> = emptyMap(),
) {
fun normalized(): CrossPlatformConfig {
val maximumDuration = videoMaxSeconds.coerceIn(20, 4000)
@@ -48,6 +53,9 @@ data class CrossPlatformConfig(
fansMax = fansMax.coerceIn(0, 1_000_000_000),
categories = categories.map { it.trim() }.filter { it in CATEGORY_CATALOGUE }.distinct(),
weiboHotCategories = weiboHotCategories.map { it.trim() }.filter { it in WEIBO_CATEGORY_IDS }.distinct(),
weiboHotTopics = weiboHotTopics.entries
.filter { it.key.trim() in WEIBO_CATEGORY_IDS }
.associate { it.key.trim() to it.value.map { t -> t.trim() }.filter { t -> t.isNotEmpty() }.distinct() },
)
}
@@ -96,6 +104,7 @@ object CrossPlatformConfigCodec {
"fans_gate_enabled" to c.fansGateEnabled.toString(), "fans_max" to c.fansMax.toString(),
"categories" to c.categories.joinToString("|"),
"weibo_hot_categories" to c.weiboHotCategories.joinToString("|"),
"weibo_hot_topics" to kotlinx.serialization.json.Json.encodeToString(c.weiboHotTopics),
).mapKeys { (key, _) -> PREFIX + key }
}
@@ -131,6 +140,11 @@ object CrossPlatformConfigCodec {
categories = value("categories")?.split('|') ?: d.categories,
weiboHotCategories = value("weibo_hot_categories")?.split('|')?.filter { it.isNotBlank() }
?: d.weiboHotCategories,
weiboHotTopics = value("weibo_hot_topics")?.let { raw ->
runCatching {
kotlinx.serialization.json.Json.decodeFromString<Map<String, List<String>>>(raw)
}.getOrDefault(d.weiboHotTopics)
} ?: d.weiboHotTopics,
).normalized()
return if (validEncoding) decoded else decoded.copy(enabled = false, mode = CrossPlatformConfig.MODE_DRY_RUN)
}
@@ -1,5 +1,6 @@
package com.haorui.app.crossplatform.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
@@ -397,6 +398,8 @@ fun TopicsScreen(config: AppConfig, tasks: List<CrossPublishTask>, loaded: Boole
)
}
Text("分类:${config.crossPlatform.categories.joinToString("、").ifBlank { "未选择" }} · ${config.crossPlatform.maxAgeHours} 小时内", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
// 微博热搜词条清单:按已选类目拉取真机榜单 → 勾选词条 → 持久化到配置(勾选后系统按所选词条采集)
WeiboHotTopicPicker(config, onConfigChange)
when {
loadError != null -> StatusBanner("本地任务读取失败:$loadError", StatusLevel.BAD)
!loaded -> EmptyPanel("正在读取本地候选", "请稍候")
@@ -408,6 +411,95 @@ fun TopicsScreen(config: AppConfig, tasks: List<CrossPublishTask>, loaded: Boole
selected?.let { prior -> TaskPreview(tasks.firstOrNull { it.id == prior.id } ?: prior) { selected = null } }
}
/**
* 微博热搜词条勾选器(用户口径:用户选什么,系统采什么发什么)。
* 数据流:按已选类目经广播拉真机榜单(ACTION_TEST_WEIBO collectOnlyList)→ 服务日志落词条 →
* 用户核对日志标题后填入下方勾选——
* ⚠️ 当前为过渡实现:采集窗口期间 UI 无法直接读服务内存,先以日志中转;
* 自动化直读将在采集执行接线时替换。勾选与持久化是真实的。
*/
@Composable
private fun WeiboHotTopicPicker(config: AppConfig, onConfigChange: (AppConfig) -> Unit) {
val context = LocalContext.current
var expandedCategory by remember { mutableStateOf<String?>(null) }
var newTopicDraft by remember { mutableStateOf("") }
val topics = config.crossPlatform.weiboHotTopics
val categories = com.haorui.app.crossplatform.source.weibo.WeiboHotCategories.ALL
val selectedCategoryIds: Set<String> = config.crossPlatform.weiboHotCategories.toSet()
Section(title = "微博热搜词条勾选", tag = "选什么采什么",
help = "按上方所选类目,把要采集的词条标题加入勾选;勾选持久化,采集执行时按标题在榜单中匹配") {
if (selectedCategoryIds.isEmpty()) {
FieldHelp("请先在上方「微博热搜类目」选择至少一个类型")
} else {
categories.filter { it.id in selectedCategoryIds }.forEach { category ->
val checked = topics[category.id].orEmpty()
// 类目折叠行:点击展开该类目的词条勾选明细
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp)
.clickable { expandedCategory = if (expandedCategory == category.id) null else category.id },
verticalAlignment = Alignment.CenterVertically,
) {
Icon(Icons.Filled.ChevronRight, contentDescription = null,
modifier = Modifier.padding(end = 6.dp))
Text(
text = "${category.tabLabel}(已勾选 ${checked.size} 条)",
style = MaterialTheme.typography.bodyMedium,
fontWeight = if (checked.isNotEmpty()) FontWeight.SemiBold else FontWeight.Normal,
)
}
if (expandedCategory == category.id) {
checked.forEach { title ->
Row(verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(start = 20.dp)) {
Text(title, style = MaterialTheme.typography.bodySmall, modifier = Modifier.weight(1f))
TextButton(onClick = {
val next = checked - title
onConfigChange(config.copy(crossPlatform = config.crossPlatform.copy(
weiboHotTopics = (topics - category.id) + if (next.isEmpty()) emptyMap()
else mapOf(category.id to next),
)))
}) { Text("移除") }
}
}
Row(verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(start = 20.dp, top = 4.dp)) {
OutlinedTextField(
value = newTopicDraft,
onValueChange = { newTopicDraft = it },
placeholder = { Text("输入词条标题") },
singleLine = true,
modifier = Modifier.weight(1f),
)
Button(
onClick = {
val title = newTopicDraft.trim()
if (title.isNotEmpty()) {
onConfigChange(config.copy(crossPlatform = config.crossPlatform.copy(
weiboHotTopics = topics + mapOf(category.id to (checked + title).distinct()),
)))
newTopicDraft = ""
}
},
modifier = Modifier.padding(start = 8.dp),
) { Text("添加") }
}
}
}
TextButton(onClick = {
// 拉取最新榜单(debug APK;只读拉清单,不采单条)——结果落在服务日志,供核对标题后填入
selectedCategoryIds.forEach { id ->
val intent = android.content.Intent("com.haorui.app.ACTION_TEST_WEIBO")
.setPackage(context.packageName)
.putExtra("categoryId", id)
.putExtra("collectOnlyList", true)
context.sendBroadcast(intent)
}
}) { Text("拉取所选类目的最新榜单(结果见服务日志)") }
FieldHelp("勾选与持久化为真实配置;自动化按标题匹配新榜单,匹配不到的词条保留待核。")
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun CrossTasksScreen(tasks: List<CrossPublishTask>, loaded: Boolean, loadError: String?, onNavigate: (String) -> Unit) {
@@ -163,4 +163,36 @@ class CrossPlatformConfigTest {
assertEquals(listOf("tech", "hot"), config.weiboHotCategories)
assertTrue(CrossPlatformConfig().weiboHotCategories.isEmpty())
}
@Test fun weiboTopicSelectionSurvivesJsonAndFlatRoundTrip() {
val expected = CrossPlatformConfig(
weiboHotCategories = listOf("hot", "tech"),
weiboHotTopics = mapOf("hot" to listOf("BLG夺冠", "和合共生"), "tech" to listOf("Gemini压谁谁输")),
)
val fromJson = json.decodeFromString(CrossPlatformConfig.serializer(),
json.encodeToString(CrossPlatformConfig.serializer(), expected)).normalized()
val fromFlat = CrossPlatformConfigCodec.fromFlatMap(CrossPlatformConfigCodec.toFlatMap(expected))
assertEquals(expected, fromJson)
assertEquals(expected, fromFlat)
}
@Test fun weiboTopicNormalizationDropsUnknownCategoryKeysAndBlankTitles() {
val config = CrossPlatformConfig(
weiboHotTopics = mapOf(
"hot" to listOf(" 正常词条 ", "", "正常词条", " "),
"未核验类目" to listOf("不该保留"),
),
).normalized()
assertEquals(mapOf("hot" to listOf("正常词条")), config.weiboHotTopics)
assertTrue(CrossPlatformConfig().weiboHotTopics.isEmpty())
}
@Test fun malformedWeiboTopicJsonFallsBackToEmptyWithoutDisablingModule() {
val config = CrossPlatformConfigCodec.fromFlatMap(mapOf(
"cross_platform_enabled" to "true",
"cross_platform_weibo_hot_topics" to "{不是JSON",
))
assertTrue(config.enabled)
assertTrue(config.weiboHotTopics.isEmpty())
}
}