Compare commits

..
2 Commits
Author SHA1 Message Date
Henry 62c1720b70 feat:M3「词条勾选链路」落地 2026-11-15 14:05:24 +08:00
Henry cc0f621c53 feat:M2 微博端到端采集验收——完整通过 2026-11-15 13:19:22 +08:00
38 changed files with 3944 additions and 6 deletions
@@ -415,6 +415,10 @@ class HaoRuiAccessibilityService : AccessibilityService() {
// 自有素材草稿回归(debug APK):vivo 真机 activity intent 投递不稳,广播为可靠入口 // 自有素材草稿回归(debug APK):vivo 真机 activity intent 投递不稳,广播为可靠入口
addAction("com.haorui.app.ACTION_TEST_DRAFT") addAction("com.haorui.app.ACTION_TEST_DRAFT")
addAction("com.haorui.app.ACTION_TEST_DRAFT_INVALID") addAction("com.haorui.app.ACTION_TEST_DRAFT_INVALID")
// 知乎单候选采集沙盒(debug APK,端到端真机验收)
addAction("com.haorui.app.ACTION_TEST_ZHIHU")
// 微博类目采集沙盒(debug APK:类目词条清单 + 单条内容全链)
addAction("com.haorui.app.ACTION_TEST_WEIBO")
// 回归测试:发布模式切换(草稿/正式) // 回归测试:发布模式切换(草稿/正式)
addAction("com.haorui.app.ACTION_SET_DRAFT") addAction("com.haorui.app.ACTION_SET_DRAFT")
addAction("com.haorui.app.ACTION_SET_PUBLISH") addAction("com.haorui.app.ACTION_SET_PUBLISH")
@@ -623,6 +627,24 @@ class HaoRuiAccessibilityService : AccessibilityService() {
val accepted = startDraftSandbox(path, intent.action == "com.haorui.app.ACTION_TEST_DRAFT_INVALID") val accepted = startDraftSandbox(path, intent.action == "com.haorui.app.ACTION_TEST_DRAFT_INVALID")
RunLogger.i(TAG, "自有素材草稿回归受理=$accepted(广播 ${intent.action})") RunLogger.i(TAG, "自有素材草稿回归受理=$accepted(广播 ${intent.action})")
} }
// 知乎单候选采集沙盒(debug APK;只读采集,端到端真机验收)
"com.haorui.app.ACTION_TEST_ZHIHU" -> {
val index = intent.getStringExtra("cardIndex")?.toIntOrNull() ?: 0
val accepted = startZhihuCollectSandbox(index)
RunLogger.i(TAG, "知乎采集沙盒受理=$accepted(广播 ACTION_TEST_ZHIHU cardIndex=$index)")
}
// 微博类目采集沙盒(debug APK;只读采集:类目词条清单 + 单条内容;collectOnlyList=仅清单)
"com.haorui.app.ACTION_TEST_WEIBO" -> {
val categoryId = intent.getStringExtra("categoryId") ?: "hot"
val entryIndex = intent.getStringExtra("entryIndex")?.toIntOrNull() ?: 0
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 开关,走广播) // 回归测试发布模式切换(草稿/正式;autoPublish 无 UI 开关,走广播)
"com.haorui.app.ACTION_SET_DRAFT" -> setAutoPublish(false) "com.haorui.app.ACTION_SET_DRAFT" -> setAutoPublish(false)
"com.haorui.app.ACTION_SET_PUBLISH" -> setAutoPublish(true) "com.haorui.app.ACTION_SET_PUBLISH" -> setAutoPublish(true)
@@ -709,6 +731,97 @@ class HaoRuiAccessibilityService : AccessibilityService() {
accepted accepted
} }
/**
* 仅调试 APK 的知乎单候选采集沙盒(端到端真机验收)。
* 只读采集、不发布、不启动调度器——WATCHDOG(恢复链)不运行,
* 不会把知乎页面当异常拉回头条;前台只持 legacy 票据独占。
*/
fun startZhihuCollectSandbox(cardIndex: 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
launchForegroundTask {
val ticket = foregroundCoordinator.tryEnterLegacy("ZHIHU-SANDBOX") ?: return@launchForegroundTask
try {
val machine = com.haorui.app.crossplatform.source.zhihu.ZhihuHotListCollector(
com.haorui.app.crossplatform.source.zhihu.ZhihuDevicePort(this@HaoRuiAccessibilityService),
)
RunLogger.i(TAG, "知乎采集沙盒开始:卡片 $cardIndex")
val result = machine.collectOne(cardIndex)
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(24)} 热度=${obs.hotEntry.heatRaw} " +
"排名=${obs.hotEntry.rank} 链接=${obs.sourceUrl} 发布时间=${obs.publishedAtMs} " +
"未知=${obs.unknowns}",
)
}
} catch (t: Throwable) {
RunLogger.e(TAG, "知乎采集沙盒异常: ${t.javaClass.simpleName}:${t.message}", t)
} finally {
foregroundCoordinator.release(ticket)
}
}
true
}
/**
* 仅调试 APK 的微博类目采集沙盒(端到端真机验收)。
* [collectEntry] false=只拉类目词条清单(用户勾选清单的数据源);
* true=清单之后再采单条内容全链。只读、不发布、不启调度器。
*/
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,
"微博采集沙盒清单: 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)
}
}
true
}
/** 新来源仅可在旧流程的完整安全边界入场,不在详情、编辑或回执中途切换。 */ /** 新来源仅可在旧流程的完整安全边界入场,不在详情、编辑或回执中途切换。 */
fun tryEnterSourceForeground(sourceId: String): ForegroundCoordinator.Ticket? { fun tryEnterSourceForeground(sourceId: String): ForegroundCoordinator.Ticket? {
if (currentCrossRunGeneration() == null) return null if (currentCrossRunGeneration() == null) return null
@@ -1,6 +1,9 @@
package com.haorui.app.crossplatform.model package com.haorui.app.crossplatform.model
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.encodeToString
import java.util.Locale import java.util.Locale
/** 新链路独立配置。来源选择不等于来源能力已验收。 */ /** 新链路独立配置。来源选择不等于来源能力已验收。 */
@@ -28,6 +31,10 @@ data class CrossPlatformConfig(
val fansGateEnabled: Boolean = false, val fansGateEnabled: Boolean = false,
val fansMax: Int = 500_000, val fansMax: Int = 500_000,
val categories: List<String> = DEFAULT_CATEGORIES, val categories: List<String> = DEFAULT_CATEGORIES,
/** 微博热搜类目勾选(WeiboHotCategories.id;空=未选择。旧配置缺字段按空处理保持兼容)。 */
val weiboHotCategories: List<String> = emptyList(),
/** 微博热搜词条勾选(类目 id → 勾选的词条标题;重启不丢,重启后榜单已刷新——按标题在新榜单中匹配,匹配不到保留待核)。 */
val weiboHotTopics: Map<String, List<String>> = emptyMap(),
) { ) {
fun normalized(): CrossPlatformConfig { fun normalized(): CrossPlatformConfig {
val maximumDuration = videoMaxSeconds.coerceIn(20, 4000) val maximumDuration = videoMaxSeconds.coerceIn(20, 4000)
@@ -45,6 +52,10 @@ data class CrossPlatformConfig(
likesMin = likesMin.coerceIn(0, 1_000_000_000), likesMin = likesMin.coerceIn(0, 1_000_000_000),
fansMax = fansMax.coerceIn(0, 1_000_000_000), fansMax = fansMax.coerceIn(0, 1_000_000_000),
categories = categories.map { it.trim() }.filter { it in CATEGORY_CATALOGUE }.distinct(), 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() },
) )
} }
@@ -66,6 +77,9 @@ data class CrossPlatformConfig(
"文化历史", "宠物", "家居", "健康科普", "影视娱乐", "游戏", "财经", "文化历史", "宠物", "家居", "健康科普", "影视娱乐", "游戏", "财经",
) )
val CATEGORIES = CATEGORY_CATALOGUE val CATEGORIES = CATEGORY_CATALOGUE
/** 微博热搜类目合法 id(见 WeiboHotCategories,2026-11-14 e2 实测清单)。 */
private val WEIBO_CATEGORY_IDS: Set<String> =
com.haorui.app.crossplatform.source.weibo.WeiboHotCategories.ALL.map { it.id }.toSet()
} }
} }
@@ -89,6 +103,8 @@ object CrossPlatformConfigCodec {
"likes_gate_enabled" to c.likesGateEnabled.toString(), "likes_min" to c.likesMin.toString(), "likes_gate_enabled" to c.likesGateEnabled.toString(), "likes_min" to c.likesMin.toString(),
"fans_gate_enabled" to c.fansGateEnabled.toString(), "fans_max" to c.fansMax.toString(), "fans_gate_enabled" to c.fansGateEnabled.toString(), "fans_max" to c.fansMax.toString(),
"categories" to c.categories.joinToString("|"), "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 } ).mapKeys { (key, _) -> PREFIX + key }
} }
@@ -122,6 +138,13 @@ object CrossPlatformConfigCodec {
likesGateEnabled = b("likes_gate_enabled", d.likesGateEnabled), likesMin = i("likes_min", d.likesMin), likesGateEnabled = b("likes_gate_enabled", d.likesGateEnabled), likesMin = i("likes_min", d.likesMin),
fansGateEnabled = b("fans_gate_enabled", d.fansGateEnabled), fansMax = i("fans_max", d.fansMax), fansGateEnabled = b("fans_gate_enabled", d.fansGateEnabled), fansMax = i("fans_max", d.fansMax),
categories = value("categories")?.split('|') ?: d.categories, 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() ).normalized()
return if (validEncoding) decoded else decoded.copy(enabled = false, mode = CrossPlatformConfig.MODE_DRY_RUN) return if (validEncoding) decoded else decoded.copy(enabled = false, mode = CrossPlatformConfig.MODE_DRY_RUN)
} }
@@ -0,0 +1,75 @@
package com.haorui.app.crossplatform.source
/**
* 来源页面的中立节点树。
*
* 同一棵树同时服务两个输入端:真机无障碍树(运行时)与 uiautomator XML 页面样本(测试/取证),
* 使采集解析器可以在 JVM 上按真实页面样本验收,不必起真机。
* 只读属性,不做任何点击决策;坐标兜底必须绑定页面指纹,禁止盲点。
*/
data class SourceBounds(val left: Int, val top: Int, val right: Int, val bottom: Int) {
val centerX: Int get() = (left + right) / 2
val centerY: Int get() = (top + bottom) / 2
companion object {
private val PATTERN = Regex("\\[(-?\\d+),(-?\\d+)]\\[(-?\\d+),(-?\\d+)]")
/** 解析 uiautomator 的 `bounds="[l,t][r,b]"`;格式不符返回 null,不猜测。 */
fun parse(raw: String?): SourceBounds? {
val text = raw?.trim().orEmpty()
val match = PATTERN.matchEntire(text) ?: return null
val (left, top, right, bottom) = match.destructured
return SourceBounds(left.toInt(), top.toInt(), right.toInt(), bottom.toInt())
}
}
}
data class SourceNode(
val id: String = "",
val text: String = "",
val description: String = "",
val className: String = "",
val clickable: Boolean = false,
val bounds: SourceBounds? = null,
val children: List<SourceNode> = emptyList(),
) {
/** 先序遍历(含自身)。 */
fun selfAndDescendants(): List<SourceNode> = buildList {
add(this@SourceNode)
children.forEach { addAll(it.selfAndDescendants()) }
}
fun findAll(predicate: (SourceNode) -> Boolean): List<SourceNode> =
selfAndDescendants().filter(predicate)
/** 精确匹配完整 resource-id 的第一个节点(不做后缀模糊,避免 ranking_no 误吞 ranking_no_img)。 */
fun firstById(resourceId: String): SourceNode? =
selfAndDescendants().firstOrNull { it.id == resourceId }
fun allById(resourceId: String): List<SourceNode> =
selfAndDescendants().filter { it.id == resourceId }
/**
* 把散落在不同子树的字段聚成“卡片/条目”:返回子树同时包含全部指定 id 的**最深**节点。
* 用于热榜卡片(trend_layout 组)、回答条目(shortContainerTemplateView 组)等成组解析,
* 防止字段与邻近条目串组(同名标题不同内容、迟到节点混入等场景)。
*/
fun deepestGroupsContaining(vararg ids: String): List<SourceNode> {
val wanted = ids.toSet()
val groups = mutableListOf<SourceNode>()
fun subtreeHas(node: SourceNode, id: String): Boolean =
node.selfAndDescendants().any { it.id == id }
fun walk(node: SourceNode) {
val qualifies = wanted.all { subtreeHas(node, it) }
if (qualifies && node.children.none { child -> wanted.all { subtreeHas(child, it) } }) {
groups += node
return
}
node.children.forEach(::walk)
}
walk(this)
return groups
}
}
@@ -0,0 +1,38 @@
package com.haorui.app.crossplatform.source
import android.graphics.Rect
import android.view.accessibility.AccessibilityNodeInfo
/**
* 真机无障碍节点树 → 中立 [SourceNode] 树。
*
* 与 [SourceNodeXml](uiautomator 样本)产出同一棵树,采集解析器即可
* “样本在 JVM 验收、真机同一套解析”。只读转换:不缓存节点、不做点击决策,
* 调用方用完即可让原 AccessibilityNodeInfo 回收。
*/
object SourceNodeAccessibility {
/** 转换整棵树;[maxDepth] 防异常深层嵌套,超出的子树截断为空。 */
fun from(node: AccessibilityNodeInfo, depth: Int = 0, maxDepth: Int = 40): SourceNode {
val rect = Rect()
node.getBoundsInScreen(rect)
val children = if (depth >= maxDepth) emptyList() else buildList {
for (i in 0 until node.childCount) {
val child = node.getChild(i) ?: continue
try {
add(from(child, depth + 1, maxDepth))
} finally {
runCatching { child.recycle() }
}
}
}
return SourceNode(
id = node.viewIdResourceName.orEmpty(),
text = node.text?.toString().orEmpty(),
description = node.contentDescription?.toString().orEmpty(),
className = node.className?.toString().orEmpty(),
clickable = node.isClickable,
bounds = SourceBounds(rect.left, rect.top, rect.right, rect.bottom),
children = children,
)
}
}
@@ -0,0 +1,63 @@
package com.haorui.app.crossplatform.source
import java.io.StringReader
import javax.xml.parsers.DocumentBuilderFactory
import org.xml.sax.InputSource
/**
* uiautomator dump XML → [SourceNode]。
*
* 仅服务于页面样本(测试/取证留存的 dump),属性映射固定为
* resource-id / text / content-desc / class / clickable / bounds;
* 解析失败抛 [IllegalArgumentException],不静默返回空树,避免样本损坏被当作“页面无节点”。
*/
object SourceNodeXml {
fun parse(xml: String): SourceNode {
val factory = DocumentBuilderFactory.newInstance()
// 禁用 DTD/外部实体,样本是本地数据,不需要实体解析,同时避免 XXE。
runCatching { factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) }
runCatching { factory.setFeature("http://xml.org/sax/features/external-general-entities", false) }
runCatching { factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false) }
val document = try {
factory.newDocumentBuilder().parse(InputSource(StringReader(xml)))
} catch (error: Exception) {
throw IllegalArgumentException("页面样本 XML 解析失败:${error.javaClass.simpleName}", error)
}
val roots = document.getElementsByTagName("node")
if (roots.length == 0) throw IllegalArgumentException("页面样本 XML 中没有 node 节点")
// dump 的根 node 就是整棵屏幕树;若出现多个顶层 node,包一层虚拟根统一返回。
val parsed = mutableListOf<SourceNode>()
for (index in 0 until roots.length) {
val element = roots.item(index) as? org.w3c.dom.Element ?: continue
if (element.parentNode?.nodeName == "node") continue
parsed += fromElement(element)
}
return when (parsed.size) {
1 -> parsed.single()
else -> SourceNode(children = parsed)
}
}
/** 供真机适配复用:把任意具名属性的节点转换为 [SourceNode](属性缺失即空值,不推断)。 */
fun fromElement(element: org.w3c.dom.Element): SourceNode {
fun attr(name: String): String = element.getAttribute(name).orEmpty()
val children = mutableListOf<SourceNode>()
val childNodes = element.childNodes
for (index in 0 until childNodes.length) {
val child = childNodes.item(index)
if (child is org.w3c.dom.Element && child.nodeName == "node") children += fromElement(child)
}
return SourceNode(
id = attr("resource-id"),
text = attr("text"),
description = attr("content-desc"),
className = attr("class"),
clickable = attr("clickable") == "true",
bounds = SourceBounds.parse(attr("bounds")),
children = children,
)
}
/** 便捷入口:从字节数组样本加载(取证文件读入后调用)。 */
fun parse(bytes: ByteArray): SourceNode = parse(String(bytes, Charsets.UTF_8))
}
@@ -0,0 +1,629 @@
package com.haorui.app.crossplatform.source.weibo
import android.graphics.Bitmap
import android.os.SystemClock
import android.view.accessibility.AccessibilityNodeInfo
import com.haorui.app.automation.ClipboardBridge
import com.haorui.app.automation.HaoRuiAccessibilityService
import com.haorui.app.automation.NodeLocator
import com.haorui.app.automation.RunLogger
import com.haorui.app.crossplatform.source.SourceNode
import com.haorui.app.crossplatform.source.SourceNodeAccessibility
/**
* 微博采集真机驱动([WeiboHotListCollector.Port] 实现,2026-11-14 e2/e3 取证口径)。
*
* 锚点依据选择器可用性报告:底部“发现”、发现页“更多热搜”、榜单 Tab 文本、
* 话题页 `contentTextView`(自绘正文)/`mblogHeadtitle`、详情顶栏右上无名「⋯」
* ([954,135][1044,225] 区 ImageView,点后以面板标题“分享”核验)、
* 分享面板第 3 行横滑区“复制链接”、“取消”关闭。
*
* 详情页作者/发布时间为自绘文本:readPostOcrLines 用应用自身 OCR 管线取行文本。
* 复制链接读取:剪贴板快速路径(本机受限)+ 微博搜索框 ACTION_PASTE 兜底——全程不切 App。
*/
internal class WeiboDevicePort(
private val service: HaoRuiAccessibilityService,
) : WeiboHotListCollector.Port {
private companion object {
const val TAG = "Weibo-Port"
const val WEIBO_PKG = "com.sina.weibo"
const val WAIT_STEP_MS = 400L
}
// ── 基础工具 ─────────────────────────────────────────────
private fun log(message: String) = RunLogger.i(TAG, message)
private fun tree(): SourceNode? = service.root()?.let { SourceNodeAccessibility.from(it) }
private fun waitTree(timeoutMs: Long, until: (SourceNode) -> Boolean): Boolean {
val deadline = SystemClock.elapsedRealtime() + timeoutMs
while (SystemClock.elapsedRealtime() < deadline) {
val t = tree()
if (t != null && until(t)) return true
Thread.sleep(WAIT_STEP_MS)
}
return false
}
private fun tapText(text: String, timeoutMs: Long = 4_000L): Boolean {
val deadline = SystemClock.elapsedRealtime() + timeoutMs
while (SystemClock.elapsedRealtime() < deadline) {
val node = NodeLocator.byText(service.root(), text) ?: NodeLocator.byDesc(service.root(), text)
if (node != null) {
try {
if (kotlinx.coroutines.runBlocking { service.gestures.tapNode(node) }) return true
} finally {
runCatching { node.recycle() }
}
}
Thread.sleep(WAIT_STEP_MS)
}
log("未找到可点击目标「$text」")
return false
}
private fun findInTree(root: SourceNode, predicate: (SourceNode) -> Boolean): SourceNode? =
root.selfAndDescendants().firstOrNull(predicate)
/** 节点可读标签:text 优先、desc 兜底(微博图标+文字按钮多走 desc 渲染,e25 实测)。 */
private fun labelOf(node: SourceNode): String =
node.text.trim().takeIf { it.isNotEmpty() } ?: node.description.trim()
private fun liveFindByClass(root: AccessibilityNodeInfo?, suffix: String): AccessibilityNodeInfo? {
if (root == null) return null
if (root.className?.toString()?.endsWith(suffix) == true) return root
for (i in 0 until root.childCount) {
val child = root.getChild(i) ?: continue
val found = liveFindByClass(child, suffix)
if (found != null) {
if (found !== child) runCatching { child.recycle() }
return found
}
runCatching { child.recycle() }
}
return null
}
/** 收集活树中全部匹配 resource-id 的节点(供无文本控件按序定位)。 */
private fun allById(root: AccessibilityNodeInfo?, id: String): List<AccessibilityNodeInfo> {
val result = mutableListOf<AccessibilityNodeInfo>()
fun walk(node: AccessibilityNodeInfo) {
if (node.viewIdResourceName == id) result.add(AccessibilityNodeInfo.obtain(node))
for (i in 0 until node.childCount) {
val child = node.getChild(i) ?: continue
try {
walk(child)
} finally {
runCatching { child.recycle() }
}
}
}
if (root != null) walk(root)
return result
}
// ── Port 实现 ────────────────────────────────────────────
/** 前台就绪探测:单次有界遍历同时找 拒绝项/底栏首页/底栏发现(大页面逐目标遍历会吃光预算,e7 实测)。
* 底栏节点按区域过滤(y≥1800),避免正文里的“首页”字样误判误点(e8 实测)。 */
private class ForegroundProbe {
var refuse: AccessibilityNodeInfo? = null
var homeNode: AccessibilityNodeInfo? = null
var discover = false
val ready: Boolean get() = homeNode != null && discover
val done: Boolean get() = ready || refuse != null
}
private fun probeForeground(root: AccessibilityNodeInfo, budget: Int = 2_000): ForegroundProbe {
val probe = ForegroundProbe()
var visited = 0
val rect = android.graphics.Rect()
fun walk(node: AccessibilityNodeInfo) {
if (probe.done || visited++ > budget) return
// 底栏 Tab 可能走 content-desc 渲染(微博样本无 text=首页 节点,e10 实测):text 与 desc 都认
val label = node.text?.toString()?.takeIf { it.isNotEmpty() }
?: node.contentDescription?.toString()?.takeIf { it.isNotEmpty() }
when (label) {
"不了,谢谢" -> if (probe.refuse == null) probe.refuse = AccessibilityNodeInfo.obtain(node)
"首页" -> if (probe.homeNode == null) {
runCatching { node.getBoundsInScreen(rect) }
if (rect.top >= 1800) probe.homeNode = AccessibilityNodeInfo.obtain(node)
}
"发现" -> {
runCatching { node.getBoundsInScreen(rect) }
if (rect.top >= 1800) probe.discover = true
}
}
for (i in 0 until node.childCount) {
if (probe.done) return
val child = node.getChild(i) ?: continue
try {
walk(child)
} finally {
runCatching { child.recycle() }
}
}
}
walk(root)
return probe
}
/** 活树有界查找 resource-id(榜单页就绪判定用;避免 SourceNode 全树转换的高开销)。 */
private fun liveHasId(root: AccessibilityNodeInfo, id: String, budget: Int = 2_000): Boolean {
var visited = 0
fun walk(node: AccessibilityNodeInfo): Boolean {
if (visited++ > budget) return false
if (node.viewIdResourceName == id) return true
for (i in 0 until node.childCount) {
val child = node.getChild(i) ?: continue
val found = try {
walk(child)
} finally {
runCatching { child.recycle() }
}
if (found) return true
}
return false
}
return walk(root)
}
override fun ensureAppForeground(): Boolean {
val deadline = SystemClock.elapsedRealtime() + 30_000
var backs = 0
while (SystemClock.elapsedRealtime() < deadline) {
// 掉出 App(BACK 过头/被切走):立即重拉,不干等
if (service.currentPackage() != WEIBO_PKG) {
service.launchApp(WEIBO_PKG)
Thread.sleep(1_000)
continue
}
val root = service.root()
if (root == null) {
Thread.sleep(WAIT_STEP_MS)
continue
}
val probe = probeForeground(root)
val refuse = probe.refuse
val homeNode = probe.homeNode
try {
if (refuse != null) {
// 评分/营销弹窗:只点拒绝项(e2 实测“不了,谢谢”),不点好评/吐槽
runCatching { kotlinx.coroutines.runBlocking { service.gestures.tapNode(refuse) } }
Thread.sleep(WAIT_STEP_MS)
continue
}
// 就绪=底栏主 Tab(首页+发现同在)**或已在热搜榜**(search_item_text 锚点;
// 榜单页无底栏,e20 实测把它当残留收拢会搅乱页面)
if (probe.ready) return true
if (liveHasId(root, "com.sina.weibo:id/search_item_text")) return true
if (homeNode != null) {
// 有底栏“首页”但缺“发现”(过渡态):点底栏首页直达
runCatching { kotlinx.coroutines.runBlocking { service.gestures.tapNode(homeNode) } }
Thread.sleep(1_000)
continue
}
} finally {
runCatching { refuse?.recycle() }
runCatching { homeNode?.recycle() }
}
// 无底栏=子页/弹层残留:BACK 收拢(有上限;每轮留 1s 页面过渡)
if (backs < 4) {
backs++
val ok = service.gestures.back()
log("残留页面收拢:第 $backs 次返回(dispatch=$ok)")
Thread.sleep(1_000)
continue
}
Thread.sleep(WAIT_STEP_MS)
}
log("进入前台失败;页面采样=${tree()?.selfAndDescendants()?.map { it.text }?.filter { it.isNotBlank() }?.take(6)}")
return false
}
private fun tapTextContains(fragment: String, timeoutMs: Long = 4_000L): Boolean {
val deadline = SystemClock.elapsedRealtime() + timeoutMs
while (SystemClock.elapsedRealtime() < deadline) {
val root = service.root()
val node = NodeLocator.byTextContains(root, fragment) ?: NodeLocator.byDescContains(root, fragment)
if (node != null) {
try {
if (kotlinx.coroutines.runBlocking { service.gestures.tapNode(node) }) return true
} finally {
runCatching { node.recycle() }
}
}
Thread.sleep(WAIT_STEP_MS)
}
log("未找到可点击目标(包含)「$fragment」")
return false
}
/** 底栏 Tab 点击:活树有界遍历,只认屏幕底部区(y≥1800)的 text/desc——正文里的同名词条不能点(e12 实测误点跑偏)。 */
private fun tapBottomNav(text: String, timeoutMs: Long = 4_000L): Boolean {
val deadline = SystemClock.elapsedRealtime() + timeoutMs
val rect = android.graphics.Rect()
while (SystemClock.elapsedRealtime() < deadline) {
val root = service.root()
if (root != null) {
var target: AccessibilityNodeInfo? = null
var visited = 0
fun walk(node: AccessibilityNodeInfo) {
if (target != null || visited++ > 2_000) return
val label = node.text?.toString()?.takeIf { it.isNotEmpty() }
?: node.contentDescription?.toString()?.takeIf { it.isNotEmpty() }
if (label == text) {
runCatching { node.getBoundsInScreen(rect) }
if (rect.top >= 1800) {
target = AccessibilityNodeInfo.obtain(node)
return
}
}
for (i in 0 until node.childCount) {
if (target != null) return
val child = node.getChild(i) ?: continue
try {
walk(child)
} finally {
runCatching { child.recycle() }
}
}
}
walk(root)
val found = target
if (found != null) {
try {
runCatching { found.getBoundsInScreen(rect) }
val ok = kotlinx.coroutines.runBlocking {
service.gestures.tapAt(rect.centerX(), rect.centerY(), retry = false)
}
if (ok) return true
} finally {
runCatching { found.recycle() }
}
}
}
Thread.sleep(WAIT_STEP_MS)
}
log("未找到底栏目标「$text」")
return false
}
override fun openHotSearch(): Boolean {
// 幂等入口:已在热搜榜(search_item_text Tab 行)直接过——e20 实测清单阶段后
// 第二阶段重复走发现页会在页面状态差异下点击失效
if (waitTree(1_500) { t -> t.findAll { it.id == "com.sina.weibo:id/search_item_text" }.isNotEmpty() }) return true
// 首页底部“发现”(底栏锚点,禁用无过滤的文本点击)→ 发现页“更多热搜”→
// 热搜榜(就绪标志=search_item_text Tab 行锚点;“我的”tab 提示语是“热搜雷达”、
// “热搜”tab 是“实时热点”,不按提示语判)
if (!tapBottomNav("发现")) {
log("OPEN_HOT_SEARCH 失败子步:底栏“发现”未点到")
return false
}
if (!waitTree(8_000) { t ->
t.findAll {
it.text.contains("更多热搜") || it.description.contains("更多热搜")
}.isNotEmpty()
}
) {
log("OPEN_HOT_SEARCH 失败子步:发现页“更多热搜”未出现")
return false
}
// “更多热搜”入口(e4 dump 核验):热搜预览块是一个大 View(clickable,desc=全部词条拼接
// 且以“更多热搜”结尾,bounds [0,389][1080,935]),按钮无独立节点——
// 核验块特征后点块内右下“更多热搜”文字位置(相对坐标:块宽 68%、底-72px,与实测点 (732,863) 吻合)。
// e19 实测同码在不同页面状态下偶发不跳转:每次重新取块并点击、验证跳转,最多 3 轮。
repeat(3) { attempt ->
var blockBounds: com.haorui.app.crossplatform.source.SourceBounds? = null
val deadlineInner = SystemClock.elapsedRealtime() + 5_000
while (blockBounds == null && SystemClock.elapsedRealtime() < deadlineInner) {
blockBounds = tree()?.selfAndDescendants()?.firstOrNull { n ->
n.clickable && n.description.trim().endsWith("更多热搜")
}?.bounds
if (blockBounds == null) Thread.sleep(WAIT_STEP_MS)
}
val b = blockBounds
if (b != null && kotlinx.coroutines.runBlocking {
service.gestures.tapAt(b.left + (b.right - b.left) * 68 / 100, b.bottom - 72, retry = false)
}
) {
log("更多热搜入口点击(第 ${attempt + 1} 轮,块 bounds=$b)")
if (waitTree(6_000) { t -> t.findAll { it.id == "com.sina.weibo:id/search_item_text" }.isNotEmpty() }) return true
} else {
log("更多热搜入口未找到或点击未派发(第 ${attempt + 1} 轮)")
}
}
log("OPEN_HOT_SEARCH 失败子步:三轮点击后热搜榜 Tab 行锚点未出现;采样=${tree()?.selfAndDescendants()?.map { it.text }?.filter { it.isNotBlank() }?.take(6)}")
return false
}
override fun switchCategory(tabLabel: String): Boolean {
// Tab 文本锚点;点击后以“解析器读得出榜单行”为就绪条件(未加载完不算)
if (!tapText(tabLabel)) return false
return waitTree(8_000) { t -> WeiboHotSearchParser.parse(t).isNotEmpty() }
}
override fun readListTree(): SourceNode = tree() ?: SourceNode()
override fun openTopic(index: Int): Boolean {
val entries = WeiboHotSearchParser.parse(readListTree())
val title = entries.getOrNull(index)?.title ?: return false
val deadline = SystemClock.elapsedRealtime() + 4_000
var tapped = false
while (!tapped && SystemClock.elapsedRealtime() < deadline) {
val node = NodeLocator.byText(service.root(), title)
if (node != null) {
try {
tapped = kotlinx.coroutines.runBlocking { service.gestures.tapNode(node) }
} finally {
runCatching { node.recycle() }
}
}
if (!tapped) Thread.sleep(WAIT_STEP_MS)
}
if (!tapped) return false
return waitTree(6_000) { t -> t.findAll { it.text.contains("阅读量") || it.text.contains("讨论量") }.isNotEmpty() }
}
override fun readTopicTree(): SourceNode = tree() ?: SourceNode()
override fun openPost(index: Int): Boolean {
// 话题页博文卡正文为自绘 View(contentTextView,text 空):按 id 收集取第 index 个
val deadline = SystemClock.elapsedRealtime() + 4_000
var tapped = false
while (!tapped && SystemClock.elapsedRealtime() < deadline) {
val nodes = allById(service.root(), "com.sina.weibo:id/contentTextView")
val target = nodes.getOrNull(index)
if (target != null) {
try {
tapped = kotlinx.coroutines.runBlocking { service.gestures.tapNode(target) }
} finally {
nodes.forEach { runCatching { it.recycle() } }
}
}
if (!tapped) Thread.sleep(WAIT_STEP_MS)
}
if (!tapped) return false
// 详情页就绪:顶栏右上组(听/⋯ 所在容器,e3 核验 id)
return waitTree(6_000) { t ->
t.findAll { it.id == "com.sina.weibo:id/detail_activity_header_right_group" }.isNotEmpty()
}
}
override fun readPostTree(): SourceNode = tree() ?: SourceNode()
/** 详情页作者/发布时间为自绘:走应用自身 OCR 管线取行文本(与草稿回执同管线)。 */
override fun readPostOcrLines(): List<String> {
val bitmap: Bitmap = kotlinx.coroutines.runBlocking {
com.haorui.app.ocr.ScreenCapturer(service).capture()
} ?: return emptyList()
return try {
val blocks = kotlinx.coroutines.runBlocking { com.haorui.app.ocr.OcrProcessor.recognize(bitmap) }
blocks.flatMap { it.lines }.map { it.text.trim() }.filter { it.isNotEmpty() }
} finally {
bitmap.recycle()
}
}
/**
* 定位底部“分享”按钮的**可点击祖先** bounds。
* e4-03 dump 实锤:按钮文字节点 text="分享" 但 **bounds=[0,0][0,0]**(文字坐标为空,实节点是父容器——
* 与头条底栏“我的”同坑);因此找到标签后回退到链路上最近的可点击祖先再点击。
*/
private fun liveFindShareAnchor(root: AccessibilityNodeInfo, budget: Int = 8_000): android.graphics.Rect? {
var visited = 0
val rect = android.graphics.Rect()
fun walk(node: AccessibilityNodeInfo, clickableAncestor: android.graphics.Rect?): android.graphics.Rect? {
if (visited++ > budget) return null
runCatching { node.getBoundsInScreen(rect) }
val selfClickable = node.isClickable && rect.width() > 0
val anchor = if (selfClickable) android.graphics.Rect(rect) else clickableAncestor
val label = node.text?.toString()?.replace('\u00A0', ' ')?.trim()?.takeIf { it.isNotEmpty() }
?: node.contentDescription?.toString()?.replace('\u00A0', ' ')?.trim().orEmpty()
// e30:标签可能带不换行空格等隐形字符,contains 容错;y>1900 祖先约束排除顶栏同名
if (label.contains("分享") && anchor != null && anchor.top > 1900) return anchor
for (i in 0 until node.childCount) {
val child = node.getChild(i) ?: continue
val found = try {
walk(child, anchor)
} finally {
runCatching { child.recycle() }
}
if (found != null) return found
}
return null
}
return walk(root, null)
}
/** 右上图标(layout B 分享箭头 / layout A 「⋯」):clickable、x>850、y∈40..280;
* 排除“关注/回关/已关注”与“听”(带文字标签的功能钮),其余(无标签或标签含“分享”)均可点。 */
private fun liveFindTopRightIcon(root: AccessibilityNodeInfo, budget: Int = 2_000): android.graphics.Rect? {
var visited = 0
val rect = android.graphics.Rect()
fun walk(node: AccessibilityNodeInfo): android.graphics.Rect? {
if (visited++ > budget) return null
runCatching { node.getBoundsInScreen(rect) }
val label = node.text?.toString()?.replace('\u00A0', ' ')?.trim()?.takeIf { it.isNotEmpty() }
?: node.contentDescription?.toString()?.replace('\u00A0', ' ')?.trim().orEmpty()
if (node.isClickable && rect.width() > 0 && rect.left > 850 && rect.top in 40..280 &&
!label.contains("关注") && !label.contains("听")
) return android.graphics.Rect(rect)
for (i in 0 until node.childCount) {
val child = node.getChild(i) ?: continue
val found = try {
walk(child)
} finally {
runCatching { child.recycle() }
}
if (found != null) return found
}
return null
}
return walk(root)
}
override fun openShareMenu(): Boolean {
// 双布局锚点(e1/e3/e4 取证):layout A 置顶详情=底栏“分享”(文字节点坐标空→点可点击祖先);
// layout B 普通详情=右上无名图标(分享箭头/⋯)。面板就绪标志=“取消”(面板独有)。
repeat(2) { attempt ->
val root = service.root()
val bottom = root?.let { liveFindShareAnchor(it) }
val topRight = root?.let { liveFindTopRightIcon(it) }
val anchor = bottom ?: topRight
log("分享入口定位(第 ${attempt + 1} 轮):底栏祖先=$bottom 右上图标=$topRight")
if (anchor != null && kotlinx.coroutines.runBlocking {
service.gestures.tapAt(anchor.centerX(), anchor.centerY(), retry = false)
} && waitTree(4_000) { t -> t.findAll { labelOf(it) == "取消" }.isNotEmpty() }
) return true
}
log("openShareMenu 失败:两布局锚点点击后面板均未弹出")
return false
}
/** 面板横滑行的原生滚动:找下部可滚容器执行 ACTION_SCROLL_FORWARD(手势横滑易被面板误判为拖拽关闭,e35)。 */
private fun liveScrollPanelRow(): Boolean {
val root = service.root() ?: return false
var visited = 0
val rect = android.graphics.Rect()
fun walk(node: AccessibilityNodeInfo): AccessibilityNodeInfo? {
if (visited++ > 4_000) return null
runCatching { node.getBoundsInScreen(rect) }
if (node.isScrollable && rect.top > 1400) return AccessibilityNodeInfo.obtain(node)
for (i in 0 until node.childCount) {
val child = node.getChild(i) ?: continue
val found = try {
walk(child)
} finally {
runCatching { child.recycle() }
}
if (found != null) return found
}
return null
}
val target = walk(root) ?: return false
return try {
runCatching { target.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD) }.getOrDefault(false)
} finally {
runCatching { target.recycle() }
}
}
override fun copyShareLink(): String? {
// 复制链接在面板第 3 行横滑区(e3-08 取证):找不到就滚动该行;
// 优先无障碍原生滚动(ACTION_SCROLL_FORWARD),失败退化为横滑手势
var copied = false
val deadline = SystemClock.elapsedRealtime() + 20_000
while (!copied && SystemClock.elapsedRealtime() < deadline) {
// 面板节点在树深处,NodeLocator 深遍历找不到(e31/e32);离屏节点坐标退化在屏外(e33 实测
// bounds=[1080,*][1080,*] 零宽=横滑区未滚动位置)——只点**在屏可见**节点,找不到则横滑重试
val target = tree()?.selfAndDescendants()?.firstOrNull { n ->
val b = n.bounds
(n.text.contains("复制链接") || n.description.contains("复制链接")) &&
b != null && b.right > b.left && b.left >= 0 && b.right <= 1080 && b.top > 1500
}
val b = target?.bounds
if (b != null && kotlinx.coroutines.runBlocking {
service.gestures.tapAt(b.centerX, b.centerY, retry = false)
}
) {
copied = true
log("复制链接点击:bounds=$b")
}
if (!copied) {
val scrolled = liveScrollPanelRow()
log("面板行滚动重试:ACTION_SCROLL_FORWARD=$scrolled")
if (!scrolled) {
kotlinx.coroutines.runBlocking { service.gestures.swipe(0.85f, 0.78f, 0.25f, 0.78f) }
}
Thread.sleep(1_200) // 滚动后留足渲染与树更新时间
}
}
if (!copied) {
log("复制链接未找到(面板横滑重试后仍无)")
return null
}
Thread.sleep(800)
val quick = runCatching {
ClipboardBridge.readFromClipboard(service) { log("剪贴板诊断: $it") }
}.getOrNull()
if (!quick.isNullOrBlank() && quick.contains("weibo")) return quick.trim()
log("剪贴板不可读,走搜索框粘贴取证")
return readLinkViaSearchBox()
}
/** 本机兜底:微博搜索框 ACTION_PASTE → 读文本 → 清空 → 返回(与知乎同管线,不切 App)。 */
private fun readLinkViaSearchBox(): String? {
repeat(3) {
if (tree()?.findAll { it.text.contains("更多热搜") }?.isNotEmpty() == true) return@repeat
service.gestures.back()
}
// 发现页搜索入口:搜索框(占位文本“大家正在搜:…”/“猜你想搜”)——按钮文本实测为“搜索,”带尾标点
// (e1-03 dump),exact 匹配不稳;点框体进搜索页(手动取证同款路径,y<400 区域约束)
val searchBox = run {
val deadlineInner = SystemClock.elapsedRealtime() + 4_000
var node: SourceNode? = null
while (node == null && SystemClock.elapsedRealtime() < deadlineInner) {
node = tree()?.selfAndDescendants()?.firstOrNull { n ->
(n.text.contains("大家正在搜") || n.text.contains("猜你想搜")) &&
n.bounds != null && n.bounds!!.right > n.bounds!!.left && n.bounds!!.top < 400
}
if (node == null) Thread.sleep(WAIT_STEP_MS)
}
node
}
val searchBounds = searchBox?.bounds
if (searchBounds == null || !kotlinx.coroutines.runBlocking {
service.gestures.tapAt(searchBounds.centerX, searchBounds.centerY, retry = false)
}
) {
log("搜索框未定位(readLinkViaSearchBox)")
return null
}
if (!waitTree(5_000) { t -> findInTree(t) { n -> n.className.endsWith("EditText") } != null }) return null
val pasted = run {
val liveInput = liveFindByClass(service.root(), "EditText") ?: return@run false
try {
runCatching { liveInput.performAction(AccessibilityNodeInfo.ACTION_PASTE) }.getOrDefault(false)
} finally {
runCatching { liveInput.recycle() }
}
}
if (!pasted) {
log("搜索框 ACTION_PASTE 未被接受")
return null
}
Thread.sleep(500)
val link = tree()?.let { t -> findInTree(t) { n -> n.className.endsWith("EditText") } }?.text?.trim().orEmpty()
val clearInput = liveFindByClass(service.root(), "EditText")
if (clearInput != null) {
try {
kotlinx.coroutines.runBlocking { service.gestures.setText(clearInput, "") }
} finally {
runCatching { clearInput.recycle() }
}
}
service.gestures.back()
return link.takeIf { it.contains("weibo") }
}
override fun leaveShareMenu(): Boolean {
// 面板在场标志=“取消”按钮(面板独有;底栏也有“分享”文本,不能用它判面板开合)
if (waitTree(1_200) { t -> t.findAll { labelOf(it) == "取消" }.isEmpty() }) return true
if (tapText("取消", timeoutMs = 2_000)) {
return waitTree(3_000) { t -> t.findAll { labelOf(it) == "取消" }.isEmpty() }
}
service.gestures.back()
return waitTree(3_000) { t -> t.findAll { labelOf(it) == "取消" }.isEmpty() }
}
override fun backToHotList(): Boolean {
// 最多三次返回:详情 → 话题 → 热搜榜(就绪=search_item_text Tab 行锚点)
repeat(3) {
if (waitTree(1_500) { t -> t.findAll { it.id == "com.sina.weibo:id/search_item_text" }.isNotEmpty() }) return true
service.gestures.back()
}
return waitTree(3_000) { t -> t.findAll { it.id == "com.sina.weibo:id/search_item_text" }.isNotEmpty() }
}
}
@@ -0,0 +1,192 @@
package com.haorui.app.crossplatform.source.weibo
import com.haorui.app.crossplatform.source.SourceNode
/**
* 微博单类目采集状态机(骨架,2026-11-14 e2 取证口径)。
*
* 产品口径(用户定):用户在热点候选页下拉勾选类目 → 按类目切微博热搜 Tab 拉榜单
* → 词条清单展示/确认 → 采该话题代表性博文 → 图文/视频生成 → 发头条。
*
* 约束(跨平台自动发布设计 + 知乎经验):
* - 一次候选完成才让出前台,失败都走 EXIT 安全退出;
* - 缺失字段保留未知(进 unknowns),不从行序、图标或无关文本推断;
* - 排名/热新爆标签为图片渲染,rank/label 恒未知;
* - 分享链接必须与当前候选配对后才作身份,未核验形态拒绝。
*
* 真机驱动通过 [Port] 接入;未完成真机适配前不注册任何能力,入口由 SourceRegistry 门控拦截。
*/
class WeiboHotListCollector(
private val port: Port,
private val nowMs: () -> Long = System::currentTimeMillis,
) {
/** 真机驱动接口:每个方法都是一次页面操作,实现方负责可见性核对,禁止盲点。 */
interface Port {
fun ensureAppForeground(): Boolean
fun openHotSearch(): Boolean
fun switchCategory(tabLabel: String): Boolean
fun readListTree(): SourceNode
fun openTopic(index: Int): Boolean
fun readTopicTree(): SourceNode
fun openPost(index: Int): Boolean
fun readPostTree(): SourceNode
/** 详情页自绘区域的 OCR 文本行(作者/发布时间只在 OCR 行里,e3 实测)。 */
fun readPostOcrLines(): List<String>
fun openShareMenu(): Boolean
fun copyShareLink(): String?
fun leaveShareMenu(): Boolean
fun backToHotList(): Boolean
}
enum class Phase {
OPEN_APP, OPEN_HOT_SEARCH, SWITCH_CATEGORY, READ_LIST,
OPEN_TOPIC, READ_TOPIC, OPEN_POST, READ_POST, COPY_SHARE_LINK,
SAVE_OBSERVATION, EXIT, DONE, FAILED,
}
/** 类目词条清单结果:entries 为该类目榜单快照(用户勾选/确认的数据源)。 */
data class ListResult(
val outcome: String,
val phase: Phase,
val entries: List<WeiboHotEntry> = emptyList(),
val reason: String = "",
val exitedSafely: Boolean = false,
)
/** 单条内容采集结果;失败相位即 [phase],观察到的未知字段进 unknowns。 */
data class Result(
val outcome: String,
val phase: Phase,
val observation: WeiboPostObservation? = null,
val reason: String = "",
val exitedSafely: Boolean = false,
)
/** 运行代际:停止/重启后递增,迟到的观察不得混入新代际。 */
var runGeneration: Long = 0
var phase: Phase = Phase.OPEN_APP
private set
/** 拉取 [category] 的榜单词条清单(OPEN_APP→…→READ_LIST→EXIT)。 */
fun collectCategoryEntries(category: WeiboHotCategory): ListResult {
var entries: List<WeiboHotEntry> = emptyList()
var failure: String? = null
var failedAt: Phase? = null
var exitedSafely = false
try {
phase = Phase.OPEN_APP
if (!port.ensureAppForeground()) fail("微博未能进入前台")
phase = Phase.OPEN_HOT_SEARCH
if (!port.openHotSearch()) fail("热搜榜入口未打开")
phase = Phase.SWITCH_CATEGORY
if (!port.switchCategory(category.tabLabel)) fail("类目「${category.tabLabel}」未切换成功")
phase = Phase.READ_LIST
entries = WeiboHotSearchParser.parse(port.readListTree())
if (entries.isEmpty()) fail("类目「${category.tabLabel}」榜单为空或结构未核验")
} catch (stop: StopRequest) {
failure = stop.message
failedAt = phase
} finally {
phase = Phase.EXIT
exitedSafely = runCatching { port.backToHotList() }.getOrDefault(false)
}
return ListResult(
outcome = if (failure == null) "已取得" else "失败",
phase = failedAt ?: Phase.DONE,
entries = entries,
reason = failure.orEmpty(),
exitedSafely = exitedSafely,
)
}
/**
* 采集类目榜单第 [entryIndex] 条话题的第 [postIndex] 条代表性博文。
* 话题页无发布时间时保留未知;分享链接经 [ZhihuShareLinkParser] 之外的独立核验(待 URL 形态取证后接入)。
*/
fun collectOne(category: WeiboHotCategory, entryIndex: Int, postIndex: Int = 0): Result {
var observation: WeiboPostObservation? = null
var failure: String? = null
var failedAt: Phase? = null
var exitedSafely = false
try {
phase = Phase.OPEN_APP
if (!port.ensureAppForeground()) fail("微博未能进入前台")
phase = Phase.OPEN_HOT_SEARCH
if (!port.openHotSearch()) fail("热搜榜入口未打开")
phase = Phase.SWITCH_CATEGORY
if (!port.switchCategory(category.tabLabel)) fail("类目「${category.tabLabel}」未切换成功")
phase = Phase.READ_LIST
val entries = WeiboHotSearchParser.parse(port.readListTree())
val entry = entries.getOrNull(entryIndex) ?: fail("类目「${category.tabLabel}」第 $entryIndex 条不存在")
phase = Phase.OPEN_TOPIC
if (!port.openTopic(entryIndex)) fail("话题「${entry.title.take(12)}」未打开")
phase = Phase.READ_TOPIC
val topic = port.readTopicTree()
phase = Phase.OPEN_POST
if (!port.openPost(postIndex)) fail("第 $postIndex 条博文未打开")
phase = Phase.READ_POST
val post = WeiboPostParser.parse(port.readPostTree(), port.readPostOcrLines(), nowMs())
phase = Phase.COPY_SHARE_LINK
val linkText = runCatching { port.openShareMenu() }.getOrDefault(false)
.let { opened -> if (opened) port.copyShareLink() else null }
runCatching { port.leaveShareMenu() }
val shareLink = WeiboShareLinkParser.parse(linkText)
phase = Phase.SAVE_OBSERVATION
observation = WeiboPostObservation(
category = category,
hotEntry = entry,
author = post.author,
content = post.content,
publishedAtText = post.publishedAtText,
publishedAtMs = post.publishedAtMs,
repostCount = post.repostCount,
commentCount = post.commentCount,
likeCount = post.likeCount,
sourceUrl = shareLink.canonicalUrl,
fetchedAtMs = nowMs(),
runGeneration = runGeneration,
unknowns = buildUnknowns(entry, post, shareLink, topic),
)
} catch (stop: StopRequest) {
failure = stop.message
failedAt = phase
} finally {
phase = Phase.EXIT
val leftShare = runCatching { port.leaveShareMenu() }.getOrDefault(true)
val backed = runCatching { port.backToHotList() }.getOrDefault(false)
exitedSafely = leftShare && backed
}
return Result(
outcome = if (observation != null) "已观察" else "失败",
phase = failedAt ?: Phase.DONE,
observation = observation,
reason = failure.orEmpty(),
exitedSafely = exitedSafely,
)
}
private class StopRequest(message: String) : RuntimeException(message)
private fun fail(reason: String): Nothing = throw StopRequest(reason)
/** 未知口径清单:把“没读到什么”显式记录,供筛选阶段按“缺值不伪造”处置。 */
private fun buildUnknowns(
entry: WeiboHotEntry,
post: WeiboPostDetail,
shareLink: WeiboShareLinkResult,
topic: SourceNode,
): List<String> {
val unknowns = mutableListOf<String>()
if (entry.rank == null) unknowns += "排名未知(排名为图片渲染)"
if (entry.heatValue == null) unknowns += "热度数值未知(原文=${entry.heatRaw ?: "缺失"})"
if (post.publishedAtMs == null) unknowns += "发布时间未知:${post.unknownReason}"
if (!shareLink.accepted) unknowns += "分享链接未核验:${shareLink.reason}"
if (topic.selfAndDescendants().none { it.text.isNotBlank() }) unknowns += "话题页无可读文本"
return unknowns
}
}
@@ -0,0 +1,56 @@
package com.haorui.app.crossplatform.source.weibo
import com.haorui.app.crossplatform.source.SourceNode
/**
* 微博热搜榜解析器(com.sina.weibo,2026-11-14 e1 取证结构)。
*
* 榜单行结构(嵌套实测,⚠️ id 命名沿用 coupon 控件但实际是热搜行):
* 行容器(无 id、clickable)→ iv_coupon_icon(排名图片) + rl_coupon_des
* → tv_coupon_des(词条标题) + [tv_coupon_des_extr(热度数值)] + [iv_highlight_icon(标签图片)]
*
* 关键口径:
* - 排名数字与热/新/爆标签都是**图片渲染**,节点树读不到:rank/label 保留 null,不按行序推断
* (置顶行与“•”推广行会穿插,行序 ≠ 排名);
* - 热度只认纯数值文本(实测 1398201 形态);“17:52登顶”“最近…”等非数值口径保留原文、数值为 null;
* - 无热度数值的行(置顶/官宣/上新位)标记 heatMissing,不删除、不伪造热度——
* 用户勾选模式下由人决定是否采集。
*/
object WeiboHotSearchParser {
const val PACKAGE = "com.sina.weibo"
internal fun res(name: String) = "$PACKAGE:id/$name"
private val HEAT_PATTERN = Regex("^(\\d{1,3}(?:,\\d{3})+|\\d+)$")
fun parse(root: SourceNode): List<WeiboHotEntry> {
// 成组锚点用双 id:rl_coupon_des + tv_coupon_des。
// ⚠️ 单 id(tv_coupon_des)会让 deepestGroupsContaining 把标题节点自身当组(自包含),
// 组内读不到兄弟的热度节点;双 id 使组落在 rl_coupon_des(含标题与热度)。
val rows = root.deepestGroupsContaining(res("rl_coupon_des"), res("tv_coupon_des"))
return rows.mapIndexedNotNull { index, row -> parseRow(row, index) }
}
private fun parseRow(row: SourceNode, index: Int): WeiboHotEntry? {
val title = row.firstById(res("tv_coupon_des"))?.text?.trim().orEmpty()
if (title.isEmpty()) return null // 缺词条的行不是候选:跳过,不伪造身份
val heatRaw = row.firstById(res("tv_coupon_des_extr"))?.text?.trim()?.takeIf { it.isNotEmpty() }
val heat = parseHeat(heatRaw)
return WeiboHotEntry(
title = title,
heatRaw = heatRaw,
heatValue = heat,
rank = null, // 排名为图片渲染,保留未知
label = null, // 标签为图片渲染,保留未知
order = index,
heatMissing = heat == null,
)
}
/** “1398201”→1398201;“1,398,201”→1398201;“17:52登顶”等非纯数值保留未知。 */
internal fun parseHeat(raw: String?): Long? {
if (raw.isNullOrBlank()) return null
val match = HEAT_PATTERN.matchEntire(raw.trim()) ?: return null
return match.groupValues[1].replace(",", "").toLongOrNull()?.takeIf { it >= 0 }
}
}
@@ -0,0 +1,94 @@
package com.haorui.app.crossplatform.source.weibo
/**
* 微博采集解析结果模型。
*
* 口径约束(缺值不伪造):解析不到的字段一律保留 null,
* 不从行序、图标或无关文本推断补齐。
*/
/**
* 微博热搜条目(2026-11-14 e1 取证形态)。
* 排名数字与热/新/爆标签均为图片渲染(iv_coupon_icon / iv_highlight_icon),节点树不可读:
* [rank]、[label] 保留 null(未知),不按行序推断——置顶行与推广行会穿插在榜单中。
* [order] 仅为展示序(页面从上到下),不是排名。
*/
data class WeiboHotEntry(
val title: String,
val heatRaw: String? = null,
val heatValue: Long? = null,
val rank: Int? = null,
val label: String? = null,
val order: Int = 0,
/** 无热度数值的行(置顶/推广/官宣位)嫌疑标记;不删除,交由筛选阶段与用户勾选处置。 */
val heatMissing: Boolean = true,
)
/**
* 微博热搜类目(2026-11-14 e2 实测 Tab 清单,横滑全量枚举)。
* 末位「更多」为类目行入口按钮,不作类目;未核验的类目不入清单。
* [tabLabel] 为微博 Tab 显示文本(采集时按键名定位),[id] 为内部稳定键。
*/
data class WeiboHotCategory(val id: String, val tabLabel: String)
object WeiboHotCategories {
val ALL: List<WeiboHotCategory> = listOf(
WeiboHotCategory("mine", "我的"),
WeiboHotCategory("hot", "热搜"),
WeiboHotCategory("ent", "文娱"),
WeiboHotCategory("society", "社会"),
WeiboHotCategory("sports", "体育"),
WeiboHotCategory("acg", "ACG"),
WeiboHotCategory("local", "同城"),
WeiboHotCategory("tech", "科技"),
WeiboHotCategory("life", "生活"),
)
fun byIds(ids: Collection<String>): List<WeiboHotCategory> = ALL.filter { it.id in ids }
}
/**
* 单条微博博文观察结果(2026-11-14 e1 取证形态)。
* 发布时间唯一合法来源是博文详情的时间文本(实测 `26-11-14 17:43` 两位年份形态);
* 缺失或解析不出保留 null,不用“4小时前”类相对时间之外的页面位置回填。
*/
data class WeiboPostObservation(
val category: WeiboHotCategory? = null,
val hotEntry: WeiboHotEntry? = null,
val author: String? = null,
val content: String? = null,
val publishedAtText: String? = null,
val publishedAtMs: Long? = null,
val repostCount: Long? = null,
val commentCount: Long? = null,
val likeCount: Long? = null,
val sourceUrl: String? = null,
val fetchedAtMs: Long = 0,
val runGeneration: Long = 0,
val unknowns: List<String> = emptyList(),
)
/**
* 博文详情解析结果。
* [publishedAtText] 只认已核验时间形态(`26-11-14 17:43` 两位年份等);
* 作者/正文/互动数的节点结构尚未 dump 核验(e1 仅截图),在核验前保留 null 并记录原因——不猜测布局。
*/
data class WeiboPostDetail(
val author: String? = null,
val content: String? = null,
val publishedAtText: String? = null,
val publishedAtMs: Long? = null,
val repostCount: Long? = null,
val commentCount: Long? = null,
val likeCount: Long? = null,
val unknownReason: String = "",
)
/** 分享链接解析结果。accepted=false 时 [reason] 说明拒绝原因。 */
data class WeiboShareLinkResult(
val accepted: Boolean,
val userId: String? = null,
val postId: String? = null,
val canonicalUrl: String? = null,
val reason: String = "",
)
@@ -0,0 +1,59 @@
package com.haorui.app.crossplatform.source.weibo
import com.haorui.app.crossplatform.source.SourceNode
/**
* 微博博文详情解析器(2026-11-14 e3 取证:树+OCR 双源)。
*
* 详情页作者行/正文为**自绘文本**,节点树读不到(e3 dump 实测 text 为空):
* 发布时间只能从 OCR 文本行按已核验形态提取(`26-11-14 20:49` 两位年份等,见 [WeiboTimeParser]);
* 互动数在节点树中(实测“转发 105/评论 366/赞 2904”文本形态)。
* 正文/作者在 OCR 行语义定型前保留 null 并记录原因——不按截图臆造布局,不拼凑无关行。
*/
object WeiboPostParser {
/**
* 时间形 token(行内查找):`26-11-14 20:49` 两位年份 / 完整年份 / 相对时间。
* OCR 行合并实测存在(作者行整行如“头条新闻 置顶 26-11-14 20:49 头条… 已编辑”),
* 故按 token 匹配而非整行;两位年份形在微博页面上特异性高,误配风险由调用方时间窗复核兜底。
*/
private val TIME_TOKEN = Regex("(?<!\\d)(?:\\d{2}|\\d{4})-\\d{1,2}-\\d{1,2}\\s+\\d{1,2}:\\d{2}(?::\\d{2})?(?!\\d)")
private val RELATIVE_TOKEN = Regex("(?<![\\d\\u4e00-\\u9fff])\\d+\\s*(?:分钟|小时|天)前(?![\\d\\u4e00-\\u9fff])|(?<![\\d\\u4e00-\\u9fff])刚刚(?![\\u4e00-\\u9fff])")
private val REPOST = Regex("^转发\\s*(\\d+(?:,\\d{3})*)$")
private val COMMENT = Regex("^评论\\s*(\\d+(?:,\\d{3})*)$")
private val LIKE = Regex("^赞\\s*(\\d+(?:,\\d{3})*)$")
fun parse(root: SourceNode, ocrLines: List<String>, nowMs: Long): WeiboPostDetail {
val treeTexts = root.selfAndDescendants().map { it.text.trim() }.filter { it.isNotEmpty() }
val timeText = findTimeToken(ocrLines)
return WeiboPostDetail(
author = null,
content = null,
publishedAtText = timeText,
publishedAtMs = timeText?.let { WeiboTimeParser.parse(it, nowMs) },
repostCount = firstCount(treeTexts, REPOST),
commentCount = firstCount(treeTexts, COMMENT),
likeCount = firstCount(treeTexts, LIKE),
unknownReason = if (timeText == null) {
"OCR 文本行中无已核验发布时间形态;作者/正文待 OCR 语义定型,保留未知"
} else {
"作者/正文待 OCR 语义定型,保留未知"
},
)
}
/** 按行序找第一个时间形 token:绝对时间优先于相对时间(同一屏内相对时间常见于卡片,绝对时间更可信)。 */
private fun findTimeToken(lines: List<String>): String? {
lines.forEach { line ->
TIME_TOKEN.find(line)?.let { return it.value.trim() }
}
lines.forEach { line ->
RELATIVE_TOKEN.find(line)?.let { return it.value.trim() }
}
return null
}
private fun firstCount(texts: List<String>, pattern: Regex): Long? =
texts.firstNotNullOfOrNull { text ->
pattern.matchEntire(text)?.groupValues?.get(1)?.replace(",", "")?.toLongOrNull()
}
}
@@ -0,0 +1,40 @@
package com.haorui.app.crossplatform.source.weibo
/**
* 微博分享链接解析(2026-11-14 e3 取证:复制链接实测形态)。
*
* 实测:`https://weibo.com/<用户UID>/<博文ID>`——完整标准域名、**无查询串无追踪参数**,
* 路径直接携带稳定身份(如 https://weibo.com/1618051664/5365257549909249)。
* 只接受该形态;非微博域名、缺段、带端口/伪装域一律拒绝——“未核验的形态不进入生产配置”。
* 查询串若未来版本出现,按追踪参数整体剥离后再验路径。
*/
object WeiboShareLinkParser {
private val POST_URL = Regex("^https?://(?:www\\.|m\\.)?weibo\\.com/(\\d{4,})/(\\d{4,})/?$")
fun parse(
raw: String?,
expectedUserId: String? = null,
expectedPostId: String? = null,
): WeiboShareLinkResult {
val text = raw?.trim().orEmpty()
if (text.isEmpty()) return WeiboShareLinkResult(false, reason = "链接为空")
val pathOnly = text.substringBefore('#').substringBefore('?').trimEnd('/')
val match = POST_URL.matchEntire(pathOnly)
?: return WeiboShareLinkResult(false, reason = "未核验的微博链接形态或非微博域名")
val userId = match.groupValues[1]
val postId = match.groupValues[2]
if (expectedUserId != null && expectedUserId != userId) {
return WeiboShareLinkResult(false, reason = "链接与候选不匹配:期望用户 $expectedUserId,实际 $userId")
}
if (expectedPostId != null && expectedPostId != postId) {
return WeiboShareLinkResult(false, reason = "链接与候选不匹配:期望博文 $expectedPostId,实际 $postId")
}
return WeiboShareLinkResult(
accepted = true,
userId = userId,
postId = postId,
canonicalUrl = "https://weibo.com/$userId/$postId",
reason = "可执行",
)
}
}
@@ -0,0 +1,50 @@
package com.haorui.app.crossplatform.source.weibo
import java.util.Calendar
/**
* 微博页面时间文本解析(保守白名单)。
*
* 已核验形态(2026-11-14 e1 博文详情实测):`26-11-14 17:43`(**两位年份** + 月日时分);
* 卡片级相对时间(“4小时前”“昨天 12:47”)与完整年份形态一并收录。
* 识别不了的形态一律返回 null,不猜测。
*/
object WeiboTimeParser {
/** 两位年份形态:26-11-14 17:43(20xx 年)。 */
private val SHORT_YEAR_TIME = Regex("^(\\d{2})-(\\d{1,2})-(\\d{1,2})\\s+(\\d{1,2}):(\\d{2})$")
private val FULL_TIME = Regex("^(\\d{4})-(\\d{1,2})-(\\d{1,2})\\s+(\\d{1,2}):(\\d{2})(?::(\\d{2}))?$")
private val RELATIVE = Regex("^(\\d+)\\s*(分钟|小时|天)前$")
fun parse(text: String, nowMs: Long): Long? {
val trimmed = text.trim()
if (trimmed.isEmpty()) return null
if (trimmed == "刚刚") return nowMs
RELATIVE.matchEntire(trimmed)?.let { match ->
val unitMs = when (match.groupValues[2]) {
"分钟" -> 60_000L
"小时" -> 3_600_000L
else -> 86_400_000L
}
return runCatching {
Math.subtractExact(nowMs, Math.multiplyExact(match.groupValues[1].toLong(), unitMs))
}.getOrNull()
}
SHORT_YEAR_TIME.matchEntire(trimmed)?.let { match ->
val g = match.groupValues
return at(2000 + g[1].toInt(), g[2].toInt(), g[3].toInt(), g[4].toInt(), g[5].toInt(), 0)
}
FULL_TIME.matchEntire(trimmed)?.let { match ->
val g = match.groupValues
return at(g[1].toInt(), g[2].toInt(), g[3].toInt(), g[4].toInt(), g[5].toInt(), g[6].toIntOrNull() ?: 0)
}
return null
}
private fun at(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int): Long? {
if (month !in 1..12 || day !in 1..31 || hour !in 0..23 || minute !in 0..59 || second !in 0..59) return null
return Calendar.getInstance().apply {
clear()
set(year, month - 1, day, hour, minute, second)
}.timeInMillis
}
}
@@ -0,0 +1,76 @@
package com.haorui.app.crossplatform.source.zhihu
import com.haorui.app.crossplatform.source.SourceNode
/**
* 知乎问题详情页解析器(com.zhihu.android 11.15.0 取证结构)。
*
* 详情页结构(2026-11-14 真机树纠正):
* - 问题头部为无子节点 WebView:节点树不携带问题标题与问题发布时间;
* - 回答卡为**无 id 容器** → shortContainerTemplateView(avatar/username,作者行)
* 与 answerContentView(tvAnswerExcerpt)、metricView(tvVoteComment)、tvTime 为兄弟节点;
* (2026-11-13 报告曾按裸文本顺序把这些字段记为 shortContainerTemplateView 的子节点,
* e2e 实测丢字段后纠正——成组锚点取“同时含作者行与正文的最深容器”。)
*
* 铁律:`tvTime` 是**回答**时间。问题发布时间(publishedAt)在没有经核验来源前保持 null,
* 任何情况下不得用回答时间回填——“知乎回答时间不能当问题时间”。
*/
object ZhihuDetailParser {
internal fun res(name: String) = "${ZhihuHotListParser.PACKAGE}:id/$name"
private val FINGERPRINT_IDS = listOf(
"recycler", "shortContainerTemplateView", "username",
"tvVoteComment", "tvTime", "tvAllCount", "write_answer",
)
private val COUNT_PATTERNS = mapOf(
"agree" to Regex("(\\d+(?:\\.\\d+)?)\\s*(万|亿)?赞同"),
"favorite" to Regex("(\\d+(?:\\.\\d+)?)\\s*(万|亿)?收藏"),
"comment" to Regex("(\\d+(?:\\.\\d+)?)\\s*(万|亿)?评论"),
)
fun parse(root: SourceNode, nowMs: Long = System.currentTimeMillis()): ZhihuDetailObservation {
val answers = root.deepestGroupsContaining(res("shortContainerTemplateView"), res("answerContentView"))
.map { parseAnswer(it, nowMs) }
return ZhihuDetailObservation(
questionTitle = null,
questionPublishedAtMs = null,
questionPublishedAtUnknownReason =
"问题头部为无子节点 WebView,节点树不携带问题标题与发布时间;tvTime 为回答时间,禁止回填",
totalAnswerText = root.firstById(res("tvAllCount"))?.text?.trim()?.takeIf { it.isNotEmpty() },
answers = answers,
hasShareEntry = root.findAll { it.text == "分享" || it.description == "分享" }.isNotEmpty(),
hasWriteAnswer = root.firstById(res("write_answer")) != null,
pageFingerprint = fingerprint(root),
)
}
private fun parseAnswer(group: SourceNode, nowMs: Long): ZhihuAnswerEntry {
val timeText = group.firstById(res("tvTime"))?.text?.trim()?.takeIf { it.isNotEmpty() }
return ZhihuAnswerEntry(
author = group.firstById(res("username"))?.text?.trim()?.takeIf { it.isNotEmpty() },
excerpt = group.firstById(res("tvAnswerExcerpt"))?.text?.trim()?.takeIf { it.isNotEmpty() },
agreeCount = parseCount(group, "agree"),
favoriteCount = parseCount(group, "favorite"),
commentCount = parseCount(group, "comment"),
answerTimeText = timeText,
answerTimeAtMs = timeText?.let { ZhihuTimeParser.parse(it, nowMs) },
)
}
/** “195 赞同 · 19 收藏 · 60 评论”按段解析;缺段或读不出的段为 null,不从其他行补。 */
private fun parseCount(group: SourceNode, key: String): Long? {
val text = group.firstById(res("tvVoteComment"))?.text?.trim().orEmpty()
if (text.isEmpty()) return null
val match = COUNT_PATTERNS.getValue(key).find(text) ?: return null
val base = match.groupValues[1].toDoubleOrNull() ?: return null
return when (match.groupValues[2]) {
"万" -> base * 10_000
"亿" -> base * 100_000_000
else -> base
}.toLong()
}
private fun fingerprint(root: SourceNode): String =
FINGERPRINT_IDS.filter { root.firstById(res(it)) != null }.joinToString("+")
}
@@ -0,0 +1,269 @@
package com.haorui.app.crossplatform.source.zhihu
import android.os.SystemClock
import android.view.accessibility.AccessibilityNodeInfo
import com.haorui.app.automation.ClipboardBridge
import com.haorui.app.automation.HaoRuiAccessibilityService
import com.haorui.app.automation.NodeLocator
import com.haorui.app.automation.RunLogger
import com.haorui.app.crossplatform.source.SourceNode
import com.haorui.app.crossplatform.source.SourceNodeAccessibility
/**
* 知乎采集真机驱动([ZhihuHotListCollector.Port] 实现,2026-11-14 e3 取证口径)。
*
* 每个操作先在节点树核对目标再点击(禁止盲点);等待用有上限轮询。
* 锚点依据选择器可用性报告 e2/e3:Tab“热榜”、详情 desc“搜索/分享”、
* 分享面板“复制链接”/“问题日志”/`id/shareClose`、问题日志“问题编辑日志”。
*
* 复制链接读取:先走前台剪贴板快速路径(本机实测受限),
* 失败则搜索框粘贴取证(e3 实测可用)——全程留在知乎 App 内,
* 不违反“一条候选完成才让出前台、不中途切换 App”。
*/
internal class ZhihuDevicePort(
private val service: HaoRuiAccessibilityService,
) : ZhihuHotListCollector.Port {
private companion object {
const val TAG = "Zhihu-Port"
const val ZHIHU_PKG = "com.zhihu.android"
const val WAIT_STEP_MS = 400L
}
// ── 基础工具 ─────────────────────────────────────────────
private fun log(message: String) = RunLogger.i(TAG, message)
private fun tree(): SourceNode? = service.root()?.let { SourceNodeAccessibility.from(it) }
/** 有上限轮询等待页面状态;root 瞬时为空不算失败。 */
private fun waitTree(timeoutMs: Long, until: (SourceNode) -> Boolean): Boolean {
val deadline = SystemClock.elapsedRealtime() + timeoutMs
while (SystemClock.elapsedRealtime() < deadline) {
val t = tree()
if (t != null && until(t)) return true
Thread.sleep(WAIT_STEP_MS)
}
return false
}
/** 按文本/描述定位并点击(带重试窗口);返回是否点击成功。 */
private fun tapText(text: String, timeoutMs: Long = 4_000L): Boolean {
val deadline = SystemClock.elapsedRealtime() + timeoutMs
while (SystemClock.elapsedRealtime() < deadline) {
val root = service.root()
val node = NodeLocator.byText(root, text) ?: NodeLocator.byDesc(root, text)
if (node != null) {
try {
if (kotlinx.coroutines.runBlocking { service.gestures.tapNode(node) }) return true
} finally {
runCatching { node.recycle() }
}
}
Thread.sleep(WAIT_STEP_MS)
}
log("未找到可点击目标「$text」")
return false
}
/** 活节点按类名后缀查找(输入框清空等需要 ACTION_SET_TEXT 的场景)。 */
private fun liveByClass(root: AccessibilityNodeInfo?, suffix: String): AccessibilityNodeInfo? {
if (root == null) return null
if (root.className?.toString()?.endsWith(suffix) == true) return root
for (i in 0 until root.childCount) {
val child = root.getChild(i) ?: continue
val found = liveByClass(child, suffix)
if (found != null) {
if (found !== child) runCatching { child.recycle() }
return found
}
runCatching { child.recycle() }
}
return null
}
private fun findByClass(root: SourceNode, simpleName: String): SourceNode? =
root.selfAndDescendants().firstOrNull { it.className.endsWith(simpleName) }
// ── Port 实现 ────────────────────────────────────────────
override fun ensureAppForeground(): Boolean {
service.launchApp(ZHIHU_PKG)
val deadline = SystemClock.elapsedRealtime() + 25_000
var sawApp = false
while (SystemClock.elapsedRealtime() < deadline) {
if (service.currentPackage() == ZHIHU_PKG) {
sawApp = true
// 开屏广告倒计时会自跳过;“跳过”按钮出现即点(只点跳过,不点广告本体)。
val skip = NodeLocator.byTextContains(service.root(), "跳过")
if (skip != null) {
runCatching {
kotlinx.coroutines.runBlocking { service.gestures.tapNode(skip) }
}
runCatching { skip.recycle() }
Thread.sleep(WAIT_STEP_MS)
continue
}
if (tree()?.findAll { it.text == "热榜" }?.isNotEmpty() == true) return true
}
Thread.sleep(WAIT_STEP_MS)
}
log("进入前台失败(见到 App=$sawApp);页面采样=${tree()?.selfAndDescendants()?.map { it.text }?.filter { it.isNotBlank() }?.take(6)}")
return false
}
override fun openHotList(): Boolean {
// 已在热榜(解析器读得出卡片)则不点 Tab:重复点会触发刷新反而延长加载
if (waitTree(1_500) { t -> ZhihuHotListParser.parse(t).isNotEmpty() }) return true
if (!tapText("热榜")) return false
val ready = waitTree(12_000) { t -> ZhihuHotListParser.parse(t).isNotEmpty() }
if (!ready) {
val t = tree()
val nodes = t?.selfAndDescendants().orEmpty()
log(
"热榜未就绪:trend_layout=${nodes.count { n -> n.id.endsWith(":id/trend_layout") }} " +
"title=${nodes.count { n -> n.id.endsWith(":id/title") }} " +
"采样=${nodes.map { it.text }.filter { it.isNotBlank() }.take(8)}",
)
}
return ready
}
override fun readListTree(): SourceNode = tree() ?: SourceNode()
override fun openCard(index: Int): Boolean {
val entries = ZhihuHotListParser.parse(readListTree())
val title = entries.getOrNull(index)?.title ?: return false
// 按完整标题定位卡片标题节点:与解析结果绑定,跳过无标题卡不串位
val deadline = SystemClock.elapsedRealtime() + 4_000
var tapped = false
while (!tapped && SystemClock.elapsedRealtime() < deadline) {
val node = NodeLocator.byText(service.root(), title)
if (node != null) {
try {
tapped = kotlinx.coroutines.runBlocking { service.gestures.tapNode(node) }
} finally {
runCatching { node.recycle() }
}
}
if (!tapped) Thread.sleep(WAIT_STEP_MS)
}
if (!tapped) return false
return waitTree(6_000) { t ->
t.findAll { it.text == "邀请回答" || it.text == "关注问题" || it.text == "写回答" }.isNotEmpty()
}
}
override fun readDetailTree(): SourceNode = tree() ?: SourceNode()
override fun openShareMenu(): Boolean {
// 详情页右上 ⋮ 的 content-desc 为“分享”(e2 取证);面板标题“分享问题”为就绪标志
if (!tapText("分享")) return false
return waitTree(5_000) { t -> t.findAll { it.text == "分享问题" }.isNotEmpty() }
}
override fun copyShareLink(): String? {
if (!tapText("复制链接")) return null
Thread.sleep(800) // 等 toast 与剪贴板写入(面板会自动关闭)
// 快速路径:剪贴板读取(本机受限,保留兼容其他设备)
val quick = runCatching {
ClipboardBridge.readFromClipboard(service) { log("剪贴板诊断: $it") }
}.getOrNull()
if (!quick.isNullOrBlank() && quick.contains("zhihu.")) return quick.trim()
log("剪贴板不可读,走搜索框粘贴取证")
return readLinkViaSearchBox()
}
/**
* 本机兜底:知乎搜索框 ACTION_PASTE → 读输入框文本 → 清空 → 返回详情。
* e3 实测路径(当时用长按菜单粘贴);此处直接对输入框派发系统粘贴动作,
* 不依赖长按菜单的文字匹配。全程留在知乎 App 内,不违反前台独占约束。
*/
private fun readLinkViaSearchBox(): String? {
if (!tapText("搜索")) return null
if (!waitTree(5_000) { t -> findByClass(t, "EditText") != null }) return null
val pasted = run {
val liveInput = liveByClass(service.root(), "EditText") ?: return@run false
try {
runCatching { liveInput.performAction(AccessibilityNodeInfo.ACTION_PASTE) }.getOrDefault(false)
} finally {
runCatching { liveInput.recycle() }
}
}
if (!pasted) {
log("搜索框 ACTION_PASTE 未被接受")
return null
}
Thread.sleep(500)
val link = tree()?.let { findByClass(it, "EditText") }?.text?.trim().orEmpty()
// 清空输入框,不留痕
val clearInput = liveByClass(service.root(), "EditText")
if (clearInput != null) {
try {
kotlinx.coroutines.runBlocking { service.gestures.setText(clearInput, "") }
} finally {
runCatching { clearInput.recycle() }
}
}
service.gestures.back() // 离开搜索页回详情(验证回到详情,最多再补一次返回)
if (!waitTree(4_000) { t -> t.findAll { it.text == "邀请回答" || it.text == "关注问题" || it.text == "写回答" }.isNotEmpty() }) {
service.gestures.back()
waitTree(4_000) { t -> t.findAll { it.text == "邀请回答" || it.text == "关注问题" || it.text == "写回答" }.isNotEmpty() }
}
return link.takeIf { it.contains("zhihu.") }
}
override fun openQuestionLog(): Boolean {
// 复制链接后面板已自动关闭;且可能刚从搜索页返回——先校准到详情页再开面板
if (waitTree(1_500) { t -> t.findAll { it.text == "分享问题" }.isNotEmpty() }) {
// 面板恰好开着,直接走下面的入口定位
} else {
if (!waitTree(1_500) { t -> t.findAll { it.text == "邀请回答" || it.text == "关注问题" }.isNotEmpty() }) {
service.gestures.back()
waitTree(3_000) { t -> t.findAll { it.text == "邀请回答" || it.text == "关注问题" }.isNotEmpty() }
}
if (!openShareMenu()) return false
}
if (!tapText("问题日志")) return false
return waitTree(6_000) { t -> t.findAll { it.text.contains("问题编辑日志") || it.text.contains("添加了问题") }.isNotEmpty() }
}
override fun readQuestionLogTree(): SourceNode = tree() ?: SourceNode()
override fun leaveQuestionLog(): Boolean {
if (!service.gestures.back()) return false
return waitTree(5_000) { t ->
t.findAll { it.text == "邀请回答" || it.text == "关注问题" || it.text == "写回答" }.isNotEmpty()
}
}
override fun leaveShareMenu(): Boolean {
// 面板可能已自动关闭:关闭键不在即视为已离开
if (waitTree(1_500) { t -> t.findAll { it.text == "分享问题" }.isEmpty() }) return true
val root = service.root()
val close = NodeLocator.byId(root, "$ZHIHU_PKG:id/shareClose")
if (close != null) {
try {
if (kotlinx.coroutines.runBlocking { service.gestures.tapNode(close) }) {
return waitTree(3_000) { t -> t.findAll { it.text == "分享问题" }.isEmpty() }
}
} finally {
runCatching { close.recycle() }
}
}
service.gestures.back()
return waitTree(3_000) { t -> t.findAll { it.text == "分享问题" }.isEmpty() }
}
override fun backToFeed(): Boolean {
// 最多三次返回:详情 → 热榜
repeat(3) {
if (waitTree(1_500) { t ->
t.findAll { it.id.endsWith(":id/trend_layout") }.isNotEmpty() &&
t.findAll { it.text == "邀请回答" }.isEmpty()
}
) return true
service.gestures.back()
}
return waitTree(3_000) { t -> t.findAll { it.id.endsWith(":id/trend_layout") }.isNotEmpty() }
}
}
@@ -0,0 +1,158 @@
package com.haorui.app.crossplatform.source.zhihu
import com.haorui.app.crossplatform.source.SourceNode
/**
* 知乎单候选采集状态机(骨架)。
*
* 设计稿状态:OPEN_APP -> OPEN_FEED -> READ_LIST -> OPEN_DETAIL
* -> READ_DETAIL -> COPY_SOURCE_LINK -> READ_QUESTION_LOG -> SAVE_OBSERVATION -> EXIT
*
* 约束(跨平台自动发布设计):
* - 一条候选完成才让出前台,不在分享面板或正文编辑中途切换 App;
* - 任何失败都走 EXIT 安全退出,回到已知可恢复页面;
* - 缺失字段保留未知(进 unknowns),不从标题/回答时间/旧剪贴板推断;
* - 分享链接必须与当前候选配对(已知 question id 时校验),不匹配即拒绝该候选。
*
* 真机驱动通过 [Port] 接入(无障碍节点读取、点击、返回);
* 未完成真机适配前不注册任何能力,采集入口由 SourceRegistry 门控拦截。
*/
class ZhihuHotListCollector(
private val port: Port,
private val nowMs: () -> Long = System::currentTimeMillis,
) {
/** 真机驱动接口:每个方法都是一次页面操作,实现方负责可见性核对,禁止盲点。 */
interface Port {
fun ensureAppForeground(): Boolean
fun openHotList(): Boolean
fun readListTree(): SourceNode
fun openCard(index: Int): Boolean
fun readDetailTree(): SourceNode
fun openShareMenu(): Boolean
fun copyShareLink(): String?
/** 从分享面板打开问题日志页(2026-11-14 取证:面板底行左一)。 */
fun openQuestionLog(): Boolean
fun readQuestionLogTree(): SourceNode
/** 从问题日志页返回详情/可恢复页面;失败不阻断 EXIT 收尾。 */
fun leaveQuestionLog(): Boolean
fun leaveShareMenu(): Boolean
fun backToFeed(): Boolean
}
enum class Phase {
OPEN_APP, OPEN_FEED, READ_LIST, OPEN_DETAIL,
READ_DETAIL, COPY_SOURCE_LINK, READ_QUESTION_LOG, SAVE_OBSERVATION, EXIT, DONE, FAILED,
}
/** 单候选采集结果;失败相位即 [phase],观察到的未知字段进 [unknowns]。 */
data class Result(
val outcome: String,
val phase: Phase,
val observation: ZhihuCandidateObservation? = null,
val reason: String = "",
val exitedSafely: Boolean = false,
)
/** 运行代际:停止/重启后递增,迟到的观察不得混入新代际。 */
var runGeneration: Long = 0
var phase: Phase = Phase.OPEN_APP
private set
/**
* 采集第 [cardIndex] 张热榜卡片(下标来自 READ_LIST 的解析结果)。
* [expectedQuestionId]:该候选此前已知的问题 id(首见观察/去重表),已知则校验分享链接配对。
* 全程独占前台;无论成败最后都执行 EXIT。
*/
fun collectOne(cardIndex: Int, expectedQuestionId: String? = null): Result {
var observation: ZhihuCandidateObservation? = null
var failure: String? = null
var failedAt: Phase? = null
var exitedSafely = false
try {
phase = Phase.OPEN_APP
if (!port.ensureAppForeground()) fail("来源 App 未能进入前台")
phase = Phase.OPEN_FEED
if (!port.openHotList()) fail("热榜入口未打开")
phase = Phase.READ_LIST
val entries = ZhihuHotListParser.parse(port.readListTree())
val entry = entries.getOrNull(cardIndex) ?: fail("热榜第 $cardIndex 张卡片不存在或缺标题")
phase = Phase.OPEN_DETAIL
if (!port.openCard(cardIndex)) fail("未能打开第 $cardIndex 张卡片详情")
phase = Phase.READ_DETAIL
val detail = ZhihuDetailParser.parse(port.readDetailTree(), nowMs())
phase = Phase.COPY_SOURCE_LINK
if (!port.openShareMenu()) fail("分享菜单未打开")
val linkText = port.copyShareLink() ?: fail("复制链接未取得")
val link = ZhihuShareLinkParser.parse(linkText, expectedQuestionId = expectedQuestionId)
if (!link.accepted) fail("分享链接未通过核验:${link.reason}")
// 问题日志:真实发布时间的唯一合法来源(2026-11-14 取证)。
// 打不开/读不到不作失败——发布时间保留未知进 unknowns,由筛选阶段按“仍不明则跳过”处置。
phase = Phase.READ_QUESTION_LOG
val questionLog: ZhihuQuestionLogObservation? = try {
if (port.openQuestionLog()) ZhihuQuestionLogParser.parse(port.readQuestionLogTree(), nowMs()) else null
} catch (_: Exception) {
null
} finally {
runCatching { port.leaveQuestionLog() }
}
phase = Phase.SAVE_OBSERVATION
observation = ZhihuCandidateObservation(
hotEntry = entry,
detail = detail,
shareLink = link,
questionId = link.questionId,
sourceUrl = link.canonicalUrl,
publishedAtMs = questionLog?.questionCreatedAtMs,
questionLog = questionLog,
fetchedAtMs = nowMs(),
runGeneration = runGeneration,
pageFingerprint = detail.pageFingerprint,
unknowns = buildUnknowns(entry, detail, questionLog),
)
} catch (stop: StopRequest) {
failure = stop.message
failedAt = phase
} finally {
phase = Phase.EXIT
// 收尾两步各自尽力:分享面板关不掉也要继续回到已知可恢复页面。
val leftShare = runCatching { port.leaveShareMenu() }.getOrDefault(false)
val backedToFeed = runCatching { port.backToFeed() }.getOrDefault(false)
exitedSafely = leftShare && backedToFeed
}
return Result(
outcome = if (observation != null) "已观察" else "失败",
phase = failedAt ?: Phase.DONE,
observation = observation,
reason = failure.orEmpty(),
exitedSafely = exitedSafely,
)
}
private class StopRequest(message: String) : RuntimeException(message)
private fun fail(reason: String): Nothing = throw StopRequest(reason)
/** 未知口径清单:把“没读到什么”显式记录,供筛选阶段按“缺值不伪造”处置。 */
private fun buildUnknowns(
entry: ZhihuHotEntry,
detail: ZhihuDetailObservation,
questionLog: ZhihuQuestionLogObservation?,
): List<String> {
val unknowns = mutableListOf<String>()
if (entry.rank == null) unknowns += "排名未知(前三名为图片或缺排名节点)"
if (entry.heatValue == null) unknowns += "热度数值未知(原文=${entry.heatRaw ?: "缺失"})"
if (questionLog?.questionCreatedAtMs == null) {
unknowns += "问题发布时间未知:${questionLog?.unknownReason ?: "问题日志页未打开"};${detail.questionPublishedAtUnknownReason}"
}
if (detail.questionTitle == null) unknowns += "问题标题未从节点树取得(WebView 无子节点,待 OCR 补全)"
return unknowns
}
}
@@ -0,0 +1,58 @@
package com.haorui.app.crossplatform.source.zhihu
import com.haorui.app.crossplatform.source.SourceNode
/**
* 知乎热榜页解析器(com.zhihu.android 11.15.0 取证结构)。
*
* 真实卡片结构(2026-11-14 真机树纠正):
* 卡片容器 → trend_layout(position_container → ranking_no | ranking_no_img) + title_layout(title + metrics_text)
* **排名徽标 trend_layout 与 title_layout 是兄弟节点**,不是父子;
* (2026-11-13 报告曾按裸文本顺序误记为 trend_layout → title_layout,e2e 实测解析 0 卡后纠正。)
*
* 关键口径:
* - `id/title` 被顶部 Tab(关注/推荐/热榜/故事)与卡片标题共用,标题只取 title_layout 内的;
* - 排名前三是图片(ranking_no_img,无文本),只认 ranking_no 文本,缺失保留未知;
* - 热度原文/数值/口径词分开保存,解析不出数值不伪造;
* - 成组锚点是“同时含 trend_layout 与 title_layout 的最深容器”,广告行等缺徽标/缺标题行不入组。
*/
object ZhihuHotListParser {
const val PACKAGE = "com.zhihu.android"
internal fun res(name: String) = "$PACKAGE:id/$name"
private val HEAT_PATTERN = Regex("^(\\d+(?:\\.\\d+)?)\\s*(万|亿)?热度$")
fun parse(root: SourceNode): List<ZhihuHotEntry> =
root.deepestGroupsContaining(res("trend_layout"), res("title_layout")).mapNotNull(::parseCard)
private fun parseCard(card: SourceNode): ZhihuHotEntry? {
val titleLayout = card.firstById(res("title_layout")) ?: return null
val title = titleLayout.firstById(res("title"))?.text?.trim().orEmpty()
if (title.isEmpty()) return null // 缺标题的卡片不是候选:跳过,不伪造身份
val heatRaw = titleLayout.firstById(res("metrics_text"))?.text?.trim()?.takeIf { it.isNotEmpty() }
val rank = card.firstById(res("ranking_no"))?.text?.trim()?.toIntOrNull()?.takeIf { it in 1..999 }
val heat = parseHeat(heatRaw)
return ZhihuHotEntry(
title = title,
heatRaw = heatRaw,
heatValue = heat.first,
heatMetric = heat.second,
rank = rank,
)
}
/** “1044 万热度”→(10_440_000, “热度”);数值/单位异常时保留原文,数值与口径为 null。 */
internal fun parseHeat(raw: String?): Pair<Long?, String?> {
if (raw.isNullOrBlank()) return null to null
val match = HEAT_PATTERN.matchEntire(raw.trim()) ?: return null to null
val (number, unit) = match.destructured
val base = number.toDoubleOrNull() ?: return null to null
val value = when (unit) {
"万" -> base * 10_000
"亿" -> base * 100_000_000
else -> base
}
return value.toLong() to "热度"
}
}
@@ -0,0 +1,99 @@
package com.haorui.app.crossplatform.source.zhihu
/**
* 知乎采集解析结果模型。
*
* 口径约束(缺值不伪造):解析不到的字段一律保留 null,
* 不从标题、评论、回答时间或其他无关位置推断补齐。
*/
/** 热榜条目。热度三口径分开保存:原文、归一数值、口径词。 */
data class ZhihuHotEntry(
val title: String,
val heatRaw: String? = null,
val heatValue: Long? = null,
val heatMetric: String? = null,
/** 排名;前三名以图片呈现不可读时保留 null(未知),不按列表顺序推断。 */
val rank: Int? = null,
)
/**
* 回答条目。
* [answerTimeText]/[answerTimeAtMs] 是**回答**时间(tvTime),
* 任何调用方不得把它写入问题发布时间字段——见 [ZhihuDetailObservation.questionPublishedAtMs]。
*/
data class ZhihuAnswerEntry(
val author: String? = null,
val excerpt: String? = null,
val agreeCount: Long? = null,
val favoriteCount: Long? = null,
val commentCount: Long? = null,
val answerTimeText: String? = null,
val answerTimeAtMs: Long? = null,
)
/**
* 问题详情观察结果。
* 知乎 11.15.0 问题头部为无子节点 WebView:问题标题与问题发布时间在节点树中不可读,
* 显式保留 null 并记录原因,等待经核验的补全来源(控件区域 OCR、分享链等)后再填。
*/
data class ZhihuDetailObservation(
val questionTitle: String? = null,
val questionPublishedAtMs: Long? = null,
val questionPublishedAtUnknownReason: String = "",
val totalAnswerText: String? = null,
val answers: List<ZhihuAnswerEntry> = emptyList(),
val hasShareEntry: Boolean = false,
val hasWriteAnswer: Boolean = false,
/** 页面指纹:关键结构节点组合,用于防切页/串素材;不是内容哈希。 */
val pageFingerprint: String = "",
)
/** 分享链接解析结果。accepted=false 时 [reason] 说明拒绝原因。 */
data class ZhihuShareLinkResult(
val accepted: Boolean,
val questionId: String? = null,
val answerId: String? = null,
val canonicalUrl: String? = null,
val reason: String = "",
)
/** 问题日志条目(2026-11-14 e3 取证形态:`logitem-<记录ID>` 容器内含操作、#记录ID 文本与时间戳,顺序不固定)。 */
data class ZhihuQuestionLogEntry(
val recordId: String? = null,
val action: String? = null,
val timeText: String? = null,
val timeAtMs: Long? = null,
)
/**
* 问题日志观察结果。
* 问题真实发布时间的唯一合法来源是「添加了问题」条目时间(2026-11-14 真机核验);
* 缺失、重复或读不出时保留 null 并给原因,不用编辑时间、“最近活动”或回答时间回填。
*/
data class ZhihuQuestionLogObservation(
val questionCreatedAtMs: Long? = null,
val questionCreatedTimeText: String? = null,
val entries: List<ZhihuQuestionLogEntry> = emptyList(),
val unknownReason: String = "",
val pageFingerprint: String = "",
)
/**
* 单候选观察结果(热榜卡片 + 详情 + 原链接)。
* [unknowns] 显式列出未取得字段;筛选阶段按“缺值不伪造”处置,不得用首见时间顶替发布时间。
*/
data class ZhihuCandidateObservation(
val hotEntry: ZhihuHotEntry,
val detail: ZhihuDetailObservation,
val shareLink: ZhihuShareLinkResult,
val questionId: String?,
val sourceUrl: String?,
/** 问题真实发布时间;唯一合法来源是 [questionLog] 的「添加了问题」条目,回答/编辑/首见时间不得回填。 */
val publishedAtMs: Long? = null,
val questionLog: ZhihuQuestionLogObservation? = null,
val fetchedAtMs: Long,
val runGeneration: Long,
val pageFingerprint: String,
val unknowns: List<String> = emptyList(),
)
@@ -0,0 +1,65 @@
package com.haorui.app.crossplatform.source.zhihu
import com.haorui.app.crossplatform.source.SourceNode
/**
* 知乎问题日志页解析器(com.zhihu.android 11.15.0,2026-11-14 e3 真机取证)。
*
* 页面为 WebView 渲染,绝大多数节点无 resource-id,但每个日志条目有结构性锚点
* `logitem-<记录ID>`(撤销按钮为 `revert-<记录ID>`)。条目子树内含操作文本、
* `#记录ID` 文本与时间戳,顺序不固定(实测两种顺序都出现过)。
*
* 问题真实发布时间 = 操作为「添加了问题」的条目时间(e3 取证核验);
* 时间戳只接受实测形态 `YYYY-MM-DD HH:MM:SS`。缺失、重复或读不出时保留 null 并给原因,
* 不用编辑时间、“最近活动于 09:58” 或回答时间回填。
*/
object ZhihuQuestionLogParser {
private val LOG_ITEM_ID = Regex("logitem-(\\d+)")
/** 实测时间形态(问题日志各条目统一为完整日期时间)。 */
private val TIME_SHAPE = Regex("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$")
private val ACTIONS = listOf(
"添加了问题", "编辑了补充说明", "编辑了问题",
"添加了话题", "移除了话题", "锁定问题编辑", "取消锁定问题编辑", "撤销",
)
fun parse(root: SourceNode, nowMs: Long = System.currentTimeMillis()): ZhihuQuestionLogObservation {
val items = root.selfAndDescendants().filter { LOG_ITEM_ID.matches(it.id) }
if (items.isEmpty()) {
return ZhihuQuestionLogObservation(
unknownReason = "页面无 logitem 条目锚点,未核验结构,发布时间保留未知",
pageFingerprint = fingerprint(root),
)
}
val entries = items.map { item ->
val texts = item.selfAndDescendants().map { it.text.trim() }.filter { it.isNotEmpty() }
val timeText = texts.firstOrNull { TIME_SHAPE.matches(it) }
ZhihuQuestionLogEntry(
recordId = LOG_ITEM_ID.matchEntire(item.id)?.groupValues?.get(1),
action = texts.firstOrNull { text -> ACTIONS.any { text == it } },
timeText = timeText,
timeAtMs = timeText?.let { ZhihuTimeParser.parse(it, nowMs) },
)
}
val creations = entries.filter { it.action == "添加了问题" }
val created = creations.singleOrNull()
return ZhihuQuestionLogObservation(
questionCreatedAtMs = created?.timeAtMs,
questionCreatedTimeText = created?.timeText,
entries = entries,
unknownReason = when {
creations.isEmpty() -> "未找到「添加了问题」条目,发布时间保留未知"
creations.size > 1 -> "「添加了问题」条目不唯一,发布时间保留未知"
created?.timeAtMs == null -> "「添加了问题」条目缺少实测形态时间戳,发布时间保留未知"
else -> ""
},
pageFingerprint = fingerprint(root),
)
}
/** 页面指纹:条目锚点数量 + 页脚标识,防切页/串页面;不是内容哈希。 */
private fun fingerprint(root: SourceNode): String {
val items = root.selfAndDescendants().count { LOG_ITEM_ID.matches(it.id) }
val footer = root.findAll { it.text.trim() == "查看问题日志" }.isNotEmpty()
return "logitems=$items;footer=$footer"
}
}
@@ -0,0 +1,43 @@
package com.haorui.app.crossplatform.source.zhihu
/**
* 知乎分享链接解析与配对校验。
*
* 2026-11-13 取证未核验到分享面板实物(留存 dump 为桌面页),当前只接受已知 Web 形态:
* https?://(www.)?zhihu.com/question/<id>[/answer/<id>]
* 路径携带稳定身份(question/answer id),查询串按追踪类参数整体剥离(日志隐藏令牌)。
* 未核验形态、非知乎域名、带端口/伪装域名一律拒绝并给原因——“未经验证的形态不进入生产配置”。
*/
object ZhihuShareLinkParser {
private val QUESTION_URL = Regex("^https?://(?:www\\.)?zhihu\\.com/question/(\\d{4,})(?:/answer/(\\d{4,}))?/?$")
fun parse(
raw: String?,
expectedQuestionId: String? = null,
expectedAnswerId: String? = null,
): ZhihuShareLinkResult {
val text = raw?.trim().orEmpty()
if (text.isEmpty()) return ZhihuShareLinkResult(false, reason = "链接为空")
// 剥离 #fragment 与 ?query(分享追踪类参数),路径中的 question/answer id 才是稳定身份。
val pathOnly = text.substringBefore('#').substringBefore('?').trimEnd('/')
val match = QUESTION_URL.matchEntire(pathOnly)
?: return ZhihuShareLinkResult(false, reason = "未核验的知乎链接形态或非知乎域名")
val questionId = match.groupValues[1]
val answerId = match.groupValues[2].takeIf { it.isNotEmpty() }
if (expectedQuestionId != null && expectedQuestionId != questionId) {
return ZhihuShareLinkResult(false, questionId = questionId, answerId = answerId,
reason = "链接与候选不匹配:期望问题 $expectedQuestionId,实际 $questionId")
}
if (expectedAnswerId != null && expectedAnswerId != answerId) {
return ZhihuShareLinkResult(false, questionId = questionId, answerId = answerId,
reason = "链接与候选不匹配:期望回答 $expectedAnswerId,实际 ${answerId ?: "无"}")
}
return ZhihuShareLinkResult(
accepted = true,
questionId = questionId,
answerId = answerId,
canonicalUrl = "https://www.zhihu.com/question/$questionId" + (answerId?.let { "/answer/$it" } ?: ""),
reason = "可执行",
)
}
}
@@ -0,0 +1,76 @@
package com.haorui.app.crossplatform.source.zhihu
import java.util.Calendar
/**
* 知乎页面时间文本解析(保守白名单)。
*
* 仅用于**回答时间**(tvTime)等条目级时间;问题发布时间必须来自经核验的来源,
* 不在本解析器职责内。识别不了的形态一律返回 null,不猜测。
*/
object ZhihuTimeParser {
private val MINUTES_AGO = Regex("^(\\d+)\\s*分钟前$")
private val HOURS_AGO = Regex("^(\\d+)\\s*小时前$")
private val DAYS_AGO = Regex("^(\\d+)\\s*天前$")
private val DAY_TIME = Regex("^(今天|昨天|前天)\\s+(\\d{1,2}):(\\d{2})$")
private val FULL_TIME = Regex("^(\\d{4})-(\\d{1,2})-(\\d{1,2})(?:\\s+(\\d{1,2}):(\\d{2})(?::(\\d{2}))?)?$")
private val MONTH_DAY = Regex("^(\\d{1,2})-(\\d{1,2})(?:\\s+(\\d{1,2}):(\\d{2}))?$")
fun parse(text: String, nowMs: Long): Long? {
val trimmed = text.trim()
if (trimmed.isEmpty()) return null
MINUTES_AGO.matchEntire(trimmed)?.let { return nowMs - it.groupValues[1].toLong() * 60_000L }
HOURS_AGO.matchEntire(trimmed)?.let { return nowMs - it.groupValues[1].toLong() * 3_600_000L }
DAYS_AGO.matchEntire(trimmed)?.let { return nowMs - it.groupValues[1].toLong() * 86_400_000L }
if (trimmed == "刚刚") return nowMs
DAY_TIME.matchEntire(trimmed)?.let { match ->
val offset = when (match.groupValues[1]) {
"今天" -> 0
"昨天" -> -1
"前天" -> -2
else -> return null
}
return dayAt(nowMs, offset, match.groupValues[2].toInt(), match.groupValues[3].toInt())
}
FULL_TIME.matchEntire(trimmed)?.let { match ->
return calendarAt(
year = match.groupValues[1].toInt(),
month = match.groupValues[2].toInt(),
day = match.groupValues[3].toInt(),
hour = match.groupValues[4].toIntOrNull() ?: 0,
minute = match.groupValues[5].toIntOrNull() ?: 0,
second = match.groupValues[6].toIntOrNull() ?: 0,
)
}
MONTH_DAY.matchEntire(trimmed)?.let { match ->
val year = Calendar.getInstance().apply { timeInMillis = nowMs }.get(Calendar.YEAR)
return calendarAt(
year = year,
month = match.groupValues[1].toInt(),
day = match.groupValues[2].toInt(),
hour = match.groupValues[3].toIntOrNull() ?: 0,
minute = match.groupValues[4].toIntOrNull() ?: 0,
second = 0,
)
}
return null
}
private fun dayAt(nowMs: Long, dayOffset: Int, hour: Int, minute: Int): Long =
Calendar.getInstance().apply {
timeInMillis = nowMs
add(Calendar.DAY_OF_YEAR, dayOffset)
set(Calendar.HOUR_OF_DAY, hour)
set(Calendar.MINUTE, minute)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}.timeInMillis
private fun calendarAt(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int): Long? {
if (month !in 1..12 || day !in 1..31 || hour !in 0..23 || minute !in 0..59 || second !in 0..59) return null
return Calendar.getInstance().apply {
clear()
set(year, month - 1, day, hour, minute, second)
}.timeInMillis
}
}
@@ -1,5 +1,6 @@
package com.haorui.app.crossplatform.ui package com.haorui.app.crossplatform.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.ExperimentalLayoutApi
@@ -59,6 +60,7 @@ import com.haorui.app.crossplatform.model.CrossTaskState
import com.haorui.app.crossplatform.source.SourceRegistry import com.haorui.app.crossplatform.source.SourceRegistry
import com.haorui.app.data.model.AppConfig import com.haorui.app.data.model.AppConfig
import com.haorui.app.ui.components.FieldHelp import com.haorui.app.ui.components.FieldHelp
import com.haorui.app.ui.components.MultiSelectDropdownField
import com.haorui.app.ui.components.Section import com.haorui.app.ui.components.Section
import com.haorui.app.ui.components.StatusBanner import com.haorui.app.ui.components.StatusBanner
import com.haorui.app.ui.components.StatusLevel import com.haorui.app.ui.components.StatusLevel
@@ -345,7 +347,8 @@ private val topicStates = setOf(CrossTaskState.DISCOVERED, CrossTaskState.FILTER
@OptIn(ExperimentalLayoutApi::class) @OptIn(ExperimentalLayoutApi::class)
@Composable @Composable
fun TopicsScreen(config: AppConfig, tasks: List<CrossPublishTask>, loaded: Boolean, loadError: String?, onNavigate: (String) -> Unit) { fun TopicsScreen(config: AppConfig, tasks: List<CrossPublishTask>, loaded: Boolean, loadError: String?,
onConfigChange: (AppConfig) -> Unit, onNavigate: (String) -> Unit) {
var source by rememberSaveable { mutableStateOf("all") } var source by rememberSaveable { mutableStateOf("all") }
var kind by rememberSaveable { mutableStateOf("all") } var kind by rememberSaveable { mutableStateOf("all") }
var selected by remember { mutableStateOf<CrossPublishTask?>(null) } var selected by remember { mutableStateOf<CrossPublishTask?>(null) }
@@ -365,7 +368,38 @@ fun TopicsScreen(config: AppConfig, tasks: List<CrossPublishTask>, loaded: Boole
FilterChip(selected = kind == id, onClick = { kind = id }, label = { Text(label) }) FilterChip(selected = kind == id, onClick = { kind = id }, label = { Text(label) })
} }
} }
// 微博热搜类目:下拉多选(全部实测类目),选择持久化到配置;所选类目决定去微博热搜拉哪些榜单
val selectedCategoryIds: Set<String> = config.crossPlatform.weiboHotCategories.toSet()
Section(title = "微博热搜类目", tag = "下拉可选",
help = "在微博热搜的类目 Tab 中选择要采集的类型;选中后按类目拉取对应榜单,未核验类目不列入") {
MultiSelectDropdownField(
label = "热搜类型(可多选)",
selectedIds = selectedCategoryIds,
options = com.haorui.app.crossplatform.source.weibo.WeiboHotCategories.ALL.map { it.id to it.tabLabel },
onToggle = { id ->
val next = if (id in selectedCategoryIds) selectedCategoryIds - id else selectedCategoryIds + id
onConfigChange(config.copy(crossPlatform = config.crossPlatform.copy(
weiboHotCategories = com.haorui.app.crossplatform.source.weibo.WeiboHotCategories.ALL
.map { it.id }.filter { it in next },
)))
},
onClear = {
onConfigChange(config.copy(crossPlatform = config.crossPlatform.copy(weiboHotCategories = emptyList())))
},
placeholder = "未选择类目",
)
Text(
text = if (selectedCategoryIds.isEmpty()) "尚未选择热搜类型;选择后这里将按类目展示可采集的热搜词条"
else "已选 ${selectedCategoryIds.size} 个类型:" +
com.haorui.app.crossplatform.source.weibo.WeiboHotCategories.byIds(selectedCategoryIds)
.joinToString("、") { it.tabLabel },
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Text("分类:${config.crossPlatform.categories.joinToString("、").ifBlank { "未选择" }} · ${config.crossPlatform.maxAgeHours} 小时内", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) Text("分类:${config.crossPlatform.categories.joinToString("、").ifBlank { "未选择" }} · ${config.crossPlatform.maxAgeHours} 小时内", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
// 微博热搜词条清单:按已选类目拉取真机榜单 → 勾选词条 → 持久化到配置(勾选后系统按所选词条采集)
WeiboHotTopicPicker(config, onConfigChange)
when { when {
loadError != null -> StatusBanner("本地任务读取失败:$loadError", StatusLevel.BAD) loadError != null -> StatusBanner("本地任务读取失败:$loadError", StatusLevel.BAD)
!loaded -> EmptyPanel("正在读取本地候选", "请稍候") !loaded -> EmptyPanel("正在读取本地候选", "请稍候")
@@ -377,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 } } 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) @OptIn(ExperimentalLayoutApi::class)
@Composable @Composable
fun CrossTasksScreen(tasks: List<CrossPublishTask>, loaded: Boolean, loadError: String?, onNavigate: (String) -> Unit) { fun CrossTasksScreen(tasks: List<CrossPublishTask>, loaded: Boolean, loadError: String?, onNavigate: (String) -> Unit) {
@@ -28,6 +28,7 @@ import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox import androidx.compose.material3.Checkbox
import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedButton
@@ -523,6 +524,83 @@ fun DropdownField(
} }
} }
/**
* 下拉多选框:点击展开候选列表,逐项勾选/取消。
* 用于「微博热搜类目」这类需要从固定清单中多选的字段;已选为空时显示占位提示。
*/
@Composable
fun MultiSelectDropdownField(
label: String,
selectedIds: Set<String>,
options: List<Pair<String, String>>,
onToggle: (String) -> Unit,
onClear: () -> Unit,
modifier: Modifier = Modifier,
placeholder: String = "未选择",
help: String? = null,
) {
var expanded by remember { mutableStateOf(false) }
val summary = options.filter { it.first in selectedIds }.joinToString("、") { it.second }.ifBlank { placeholder }
Column(modifier = modifier) {
Text(
text = label,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Box(modifier = Modifier.padding(top = 4.dp)) {
OutlinedTextField(
value = summary,
onValueChange = {},
readOnly = true,
trailingIcon = {
Icon(
imageVector = if (expanded) Icons.Filled.KeyboardArrowUp
else Icons.Filled.KeyboardArrowDown,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.clickable { expanded = !expanded },
)
},
shape = RoundedCornerShape(10.dp),
modifier = Modifier.fillMaxWidth(),
)
Box(
modifier = Modifier
.matchParentSize()
.clickable { expanded = !expanded }
)
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
modifier = Modifier.fillMaxWidth(),
) {
options.forEach { (id, text) ->
DropdownMenuItem(
text = {
Row(verticalAlignment = Alignment.CenterVertically) {
Checkbox(checked = id in selectedIds, onCheckedChange = { onToggle(id) })
Text(text)
}
},
onClick = { onToggle(id) },
)
}
if (options.isNotEmpty()) {
HorizontalDivider()
DropdownMenuItem(
text = { Text("清空选择", color = MaterialTheme.colorScheme.error) },
onClick = {
onClear()
expanded = false
},
)
}
}
}
if (help != null) FieldHelp(help)
}
}
/** 勾选项 */ /** 勾选项 */
@Composable @Composable
fun CheckRow( fun CheckRow(
@@ -250,7 +250,7 @@ fun HaoRuiApp(config: AppConfig, onConfigChange: (AppConfig) -> Unit) {
) )
} }
composable(Routes.TOPICS) { composable(Routes.TOPICS) {
TopicsScreen(config, crossTasks, crossTasksLoaded, crossTasksError) { nav.navigate(it) } TopicsScreen(config, crossTasks, crossTasksLoaded, crossTasksError, onConfigChange) { nav.navigate(it) }
} }
composable(Routes.TASKS) { composable(Routes.TASKS) {
CrossTasksScreen(crossTasks, crossTasksLoaded, crossTasksError) { nav.navigate(it) } CrossTasksScreen(crossTasks, crossTasksLoaded, crossTasksError) { nav.navigate(it) }
@@ -140,4 +140,59 @@ class CrossPlatformConfigTest {
assertEquals(CrossPlatformConfig.MODE_AUTO, decoded.crossPlatform.mode) assertEquals(CrossPlatformConfig.MODE_AUTO, decoded.crossPlatform.mode)
assertEquals(AppConfig().toutiao.autoPublish, decoded.toutiao.autoPublish) assertEquals(AppConfig().toutiao.autoPublish, decoded.toutiao.autoPublish)
} }
// ── 微博热搜类目勾选持久化(2026-11-14 用户口径)──────────────
@Test fun oldJsonWithoutWeiboCategoriesKeepsEmptySelection() {
val old = """{"crossPlatform":{"enabled":false,"maxAgeHours":12}}"""
val config = json.decodeFromString(AppConfig.serializer(), old).crossPlatform
assertTrue(config.weiboHotCategories.isEmpty())
}
@Test fun weiboCategorySelectionSurvivesJsonAndFlatRoundTrip() {
val expected = CrossPlatformConfig(weiboHotCategories = listOf("hot", "society", "tech"))
val fromJson = json.decodeFromString(CrossPlatformConfig.serializer(),
json.encodeToString(CrossPlatformConfig.serializer(), expected)).normalized()
val fromFlat = CrossPlatformConfigCodec.fromFlatMap(CrossPlatformConfigCodec.toFlatMap(expected))
assertEquals(listOf("hot", "society", "tech"), fromJson.weiboHotCategories)
assertEquals(listOf("hot", "society", "tech"), fromFlat.weiboHotCategories)
}
@Test fun weiboCategoryNormalizationDropsUnknownIdsAndDuplicates() {
val config = CrossPlatformConfig(weiboHotCategories = listOf(" tech ", "tech", "未核验类目", "hot")).normalized()
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())
}
} }
@@ -0,0 +1,60 @@
package com.haorui.app.crossplatform.source
import org.junit.Assert.*
import org.junit.Test
/** 页面样本加载器基础行为:属性映射、子树结构、样本损坏必须报错而非空树。 */
class SourceNodeXmlTest {
@Test fun mapsAttributesAndParsesBounds() {
val root = SourceNodeXml.parse(
"""<hierarchy rotation="0"><node index="0" text="标题" resource-id="com.zhihu.android:id/title" class="android.widget.TextView" content-desc="描述" clickable="true" bounds="[10,20][110,220]"/></hierarchy>""",
)
assertEquals("com.zhihu.android:id/title", root.id)
assertEquals("标题", root.text)
assertEquals("描述", root.description)
assertTrue(root.clickable)
assertEquals(SourceBounds(10, 20, 110, 220), root.bounds)
assertEquals(60, root.bounds?.centerX)
assertEquals(120, root.bounds?.centerY)
}
@Test fun buildsChildTree() {
val root = SourceNodeXml.parse(
"""<hierarchy><node text="外" bounds="[0,0][1,1]"><node text="内1" bounds="[0,0][1,1]"/><node text="内2" bounds="[0,0][1,1]"><node text="内内" bounds="[0,0][1,1]"/></node></node></hierarchy>""",
)
assertEquals("外", root.text)
assertEquals(2, root.children.size)
assertEquals(1, root.findAll { it.text == "内内" }.size)
assertEquals(3, root.findAll { it.text.startsWith("内") }.size)
}
@Test fun deepestGroupsCollectCardsNotAncestors() {
val root = SourceNodeXml.parse(
"""<hierarchy><node text="列表" resource-id="list" bounds="[0,0][1,1]">""" +
"""<node text="卡片A" resource-id="card" bounds="[0,0][1,1]"><node text="标题A" resource-id="title" bounds="[0,0][1,1]"/></node>""" +
"""<node text="卡片B" resource-id="card" bounds="[0,0][1,1]"><node text="标题B" resource-id="title" bounds="[0,0][1,1]"/></node>""" +
"""</node></hierarchy>""",
)
val cards = root.deepestGroupsContaining("card", "title")
assertEquals(2, cards.size)
assertEquals(listOf("卡片A", "卡片B"), cards.map { it.text })
val titles = root.deepestGroupsContaining("title")
assertEquals(listOf("标题A", "标题B"), titles.map { it.text })
}
@Test fun brokenSampleThrowsInsteadOfSilentEmptyTree() {
try {
SourceNodeXml.parse("<hierarchy><node")
fail("损坏样本应当抛出 IllegalArgumentException")
} catch (expected: IllegalArgumentException) {
// 预期:解析失败必须显式报错
}
try {
SourceNodeXml.parse("<hierarchy></hierarchy>")
fail("空样本应当抛出 IllegalArgumentException")
} catch (expected: IllegalArgumentException) {
// 预期:没有 node 不能当“页面无节点”
}
}
}
@@ -0,0 +1,200 @@
package com.haorui.app.crossplatform.source.weibo
import com.haorui.app.crossplatform.source.SourceNode
import com.haorui.app.crossplatform.source.SourceNodeXml
import org.junit.Assert.*
import org.junit.Test
/**
* 微博采集骨架验收:时间白名单、详情只取已核验字段、分享链未核验一律拒、
* 流程顺序、失败相位、安全退出与未知口径。
*/
class WeiboHotListCollectorTest {
private val nowMs = 1_763_100_000_000L
private class FakePort : WeiboHotListCollector.Port {
val calls = mutableListOf<String>()
var foregroundOk = true
var hotSearchOk = true
var switchCategoryOk = true
var openTopicOk = true
var openPostOk = true
var shareMenuOk = true
var copiedLink: String? = "https://weibo.example/未核验形态"
val listTree = SourceNodeXml.parse(
WeiboSampleXml.hotListPage(
listOf(
WeiboSampleXml.hotRow("国足马来西亚爆发冲突", "1398201"),
WeiboSampleXml.hotRow("打印店老板堪比AI", "989053"),
),
),
)
val topicTree = SourceNodeXml.parse(WeiboSampleXml.page(WeiboSampleXml.node(text = "话题页文本")))
val postTree = SourceNodeXml.parse(
WeiboSampleXml.page(
WeiboSampleXml.node(text = "转发 105") +
WeiboSampleXml.node(text = "评论 366") +
WeiboSampleXml.node(text = "赞 2904"),
),
)
val postOcrLines = listOf("头条新闻 置顶 26-11-14 20:49 头条… 已编辑", "正文 OCR 行一", "正文 OCR 行二")
override fun ensureAppForeground(): Boolean { calls += "OPEN_APP"; return foregroundOk }
override fun openHotSearch(): Boolean { calls += "OPEN_HOT_SEARCH"; return hotSearchOk }
override fun switchCategory(tabLabel: String): Boolean { calls += "SWITCH_CATEGORY($tabLabel)"; return switchCategoryOk }
override fun readListTree(): SourceNode { calls += "READ_LIST"; return listTree }
override fun openTopic(index: Int): Boolean { calls += "OPEN_TOPIC($index)"; return openTopicOk }
override fun readTopicTree(): SourceNode { calls += "READ_TOPIC"; return topicTree }
override fun openPost(index: Int): Boolean { calls += "OPEN_POST($index)"; return openPostOk }
override fun readPostTree(): SourceNode { calls += "READ_POST"; return postTree }
override fun readPostOcrLines(): List<String> { calls += "READ_POST_OCR"; return postOcrLines }
override fun openShareMenu(): Boolean { calls += "COPY_SHARE_LINK/menu"; return shareMenuOk }
override fun copyShareLink(): String? { calls += "COPY_SHARE_LINK/copy"; return copiedLink }
override fun leaveShareMenu(): Boolean { calls += "EXIT/leaveShare"; return true }
override fun backToHotList(): Boolean { calls += "EXIT/backToHotList"; return true }
}
private fun collector(port: FakePort) = WeiboHotListCollector(port) { nowMs }
private val hot = WeiboHotCategories.ALL.first { it.id == "hot" }
// ── 时间白名单 ────────────────────────────────────────────
@Test fun parsesVerifiedTimeForms() {
// e1 实测两位年份形态:26-11-14 17:43 → 2026-11-14 17:43
val expected = java.util.Calendar.getInstance().apply {
clear(); set(2026, 10, 14, 17, 43, 0)
}.timeInMillis
assertEquals(expected, WeiboTimeParser.parse("26-11-14 17:43", nowMs))
assertEquals(expected, WeiboTimeParser.parse("2026-11-14 17:43", nowMs))
assertEquals(nowMs, WeiboTimeParser.parse("刚刚", nowMs))
assertEquals(nowMs - 4 * 3_600_000L, WeiboTimeParser.parse("4小时前", nowMs))
}
@Test fun unverifiedTimeFormsStayUnknown() {
assertNull(WeiboTimeParser.parse("最近", nowMs))
assertNull(WeiboTimeParser.parse("11月14日", nowMs))
assertNull(WeiboTimeParser.parse("", nowMs))
assertNull(WeiboTimeParser.parse("99-99-99 99:99", nowMs))
}
// ── 详情解析(树+OCR 双源,只取已核验字段)──────────────────
@Test fun postDetailExtractsTimeFromMergedOcrLineAndCountsFromTree() {
// e3 实测:作者/时间为自绘(OCR 合并行形态),互动数在节点树(“转发 105”文本)。
val detail = WeiboPostParser.parse(FakePort().postTree, FakePort().postOcrLines, nowMs)
assertEquals("26-11-14 20:49", detail.publishedAtText)
assertNotNull(detail.publishedAtMs)
assertEquals(105L, detail.repostCount)
assertEquals(366L, detail.commentCount)
assertEquals(2904L, detail.likeCount)
assertNull(detail.author) // OCR 语义未定型,不伪造
assertNull(detail.content)
assertTrue(detail.unknownReason.contains("保留未知"))
}
@Test fun postDetailWithoutVerifiedTimeKeepsTimeUnknown() {
val detail = WeiboPostParser.parse(FakePort().postTree, listOf("正文里只有 11月14日讯 这种叙述"), nowMs)
assertNull(detail.publishedAtText)
assertNull(detail.publishedAtMs)
assertTrue(detail.unknownReason.contains("无已核验发布时间形态"))
}
@Test fun shareLinkAcceptsVerifiedFormAndRejectsOthers() {
// e3 实测形态:https://weibo.com/<UID>/<博文ID>(无查询串,路径即身份)
val ok = WeiboShareLinkParser.parse("https://weibo.com/1618051664/5365257549909249")
assertTrue(ok.reason, ok.accepted)
assertEquals("1618051664", ok.userId)
assertEquals("5365257549909249", ok.postId)
assertEquals("https://weibo.com/1618051664/5365257549909249", ok.canonicalUrl)
// 追踪串剥离后仍按路径身份
assertTrue(WeiboShareLinkParser.parse("https://weibo.com/1618051664/5365257549909249?xtrack=abc").accepted)
// 非核验形态一律拒
assertFalse(WeiboShareLinkParser.parse("https://weibo.example/未核验形态").accepted)
assertFalse(WeiboShareLinkParser.parse("https://www.weibo.cc/123/456").accepted)
assertFalse(WeiboShareLinkParser.parse(null).accepted)
}
@Test fun shareLinkPairingMismatchIsRejected() {
val result = WeiboShareLinkParser.parse(
"https://weibo.com/1618051664/5365257549909249",
expectedUserId = "1618051664",
expectedPostId = "9999999999999999",
)
assertFalse(result.accepted)
assertTrue(result.reason.contains("不匹配"))
}
// ── 采集机:类目清单阶段 ──────────────────────────────────
@Test fun collectCategoryEntriesReturnsListAndExitsSafely() {
val port = FakePort()
val result = collector(port).collectCategoryEntries(hot)
assertEquals("已取得", result.outcome)
assertEquals(WeiboHotListCollector.Phase.DONE, result.phase)
assertTrue(result.exitedSafely)
assertEquals(2, result.entries.size)
assertEquals("国足马来西亚爆发冲突", result.entries[0].title)
assertEquals(1398201L, result.entries[0].heatValue)
assertEquals(
listOf("OPEN_APP", "OPEN_HOT_SEARCH", "SWITCH_CATEGORY(热搜)", "READ_LIST", "EXIT/backToHotList"),
port.calls,
)
}
@Test fun categorySwitchFailureFailsAtSwitchPhaseButStillExits() {
val port = FakePort().apply { switchCategoryOk = false }
val result = collector(port).collectCategoryEntries(hot)
assertEquals("失败", result.outcome)
assertEquals(WeiboHotListCollector.Phase.SWITCH_CATEGORY, result.phase)
assertTrue(result.reason.contains("热搜"))
assertTrue(result.exitedSafely)
}
// ── 采集机:单条内容阶段 ──────────────────────────────────
@Test fun collectOneBuildsObservationWithUnknownsNotFabrication() {
val port = FakePort()
val result = collector(port).collectOne(hot, entryIndex = 0, postIndex = 0)
assertEquals("已观察", result.outcome)
assertEquals(WeiboHotListCollector.Phase.DONE, result.phase)
assertTrue(result.exitedSafely)
val obs = result.observation!!
assertEquals("国足马来西亚爆发冲突", obs.hotEntry!!.title)
assertEquals("26-11-14 20:49", obs.publishedAtText) // 来自 OCR 合并行内的时间 token
assertNotNull(obs.publishedAtMs)
assertNull(obs.author) // 结构未核验,不伪造
assertNull(obs.sourceUrl) // 分享链未核验,不作身份
assertTrue(obs.unknowns.any { it.contains("排名未知") })
assertTrue(obs.unknowns.any { it.contains("分享链接未核验") })
assertFalse(obs.unknowns.any { it.contains("发布时间未知") }) // 时间已从核验形态解析出
assertEquals(nowMs, obs.fetchedAtMs)
}
@Test fun missingEntryFailsAtReadList() {
val result = collector(FakePort()).collectOne(hot, entryIndex = 9)
assertEquals("失败", result.outcome)
assertEquals(WeiboHotListCollector.Phase.READ_LIST, result.phase)
}
@Test fun postOpenFailureFailsAtOpenPostAndExits() {
val port = FakePort().apply { openPostOk = false }
val result = collector(port).collectOne(hot, entryIndex = 1)
assertEquals(WeiboHotListCollector.Phase.OPEN_POST, result.phase)
assertTrue(result.exitedSafely)
}
@Test fun runGenerationPropagatesIntoObservation() {
val port = FakePort()
val machine = collector(port).apply { runGeneration = 7 }
assertEquals(7L, machine.collectOne(hot, 0).observation?.runGeneration)
}
@Test fun verifiedShareLinkBecomesSourceUrl() {
val port = FakePort().apply { copiedLink = "https://weibo.com/1618051664/5365257549909249" }
val obs = collector(port).collectOne(hot, 0).observation!!
assertEquals("https://weibo.com/1618051664/5365257549909249", obs.sourceUrl)
assertFalse(obs.unknowns.any { it.contains("分享链接未核验") })
}
}
@@ -0,0 +1,101 @@
package com.haorui.app.crossplatform.source.weibo
import com.haorui.app.crossplatform.source.SourceNodeXml
import org.junit.Assert.*
import org.junit.Test
/**
* 微博热搜清单解析样本验收(2026-11-14 e1 取证形态)。
* 覆盖:热度数值/非数值口径、置顶与推广行(无热度)、Tab 不串行、
* 排名/标签图片渲染保留未知、缺词条行跳过。
*/
class WeiboHotSearchParserTest {
private fun parse(body: String): List<WeiboHotEntry> =
WeiboHotSearchParser.parse(SourceNodeXml.parse(WeiboSampleXml.hotListPage(listOf(body))))
@Test fun parsesRowsWithTitleAndHeatValue() {
val entries = WeiboHotSearchParser.parse(
SourceNodeXml.parse(
WeiboSampleXml.hotListPage(
listOf(
WeiboSampleXml.hotRow("国足马来西亚爆发冲突", "1398201"),
WeiboSampleXml.hotRow("打印店老板堪比AI", "989053"),
),
),
),
)
assertEquals(2, entries.size)
assertEquals("国足马来西亚爆发冲突", entries[0].title)
assertEquals("1398201", entries[0].heatRaw)
assertEquals(1398201L, entries[0].heatValue)
assertEquals(0, entries[0].order)
assertEquals(989053L, entries[1].heatValue)
assertEquals(1, entries[1].order)
assertFalse(entries[0].heatMissing)
}
@Test fun rankAndLabelStayUnknownBecauseTheyAreRenderedAsImages() {
val entry = parse(WeiboSampleXml.hotRow("打印店老板堪比AI", "989053", withRankIcon = true, withLabelIcon = true)).single()
assertNull(entry.rank) // 排名是 iv_coupon_icon 图片,行序≠排名(置顶/推广穿插),不推断
assertNull(entry.label) // 热/新/爆是 iv_highlight_icon 图片,不推断
}
@Test fun topEntryWithoutHeatStaysListedButMarkedMissing() {
// e1 实测置顶行(“习近平妙喻APEC合作”)无热度数值。
val entry = parse(WeiboSampleXml.hotRow("习近平妙喻APEC合作", heat = null, withLabelIcon = true)).single()
assertEquals("习近平妙喻APEC合作", entry.title)
assertNull(entry.heatRaw)
assertNull(entry.heatValue)
assertTrue(entry.heatMissing)
}
@Test fun nonNumericHeatKeepsRawAndStaysUnknown() {
// “17:52登顶”“最近…”等非纯数值口径:保留原文、数值未知、不伪造。
val entry = parse(WeiboSampleXml.hotRow("高迪 家暴", "17:52登顶")).single()
assertEquals("17:52登顶", entry.heatRaw)
assertNull(entry.heatValue)
assertTrue(entry.heatMissing)
}
@Test fun commaGroupedHeatIsParsed() {
val entry = parse(WeiboSampleXml.hotRow("带千分位热度", "1,398,201")).single()
assertEquals(1398201L, entry.heatValue)
}
@Test fun tabLabelsNeverBecomeEntries() {
val entries = WeiboHotSearchParser.parse(SourceNodeXml.parse(WeiboSampleXml.hotListPage(emptyList())))
assertTrue(entries.isEmpty())
}
@Test fun rowWithoutTitleIsSkippedNotFaked() {
val entries = parse(WeiboSampleXml.hotRow("", "123") + WeiboSampleXml.hotRow("正常词条", "456"))
assertEquals(1, entries.size)
assertEquals("正常词条", entries[0].title)
}
@Test fun negativeOrGarbageHeatStaysUnknown() {
assertNull(WeiboHotSearchParser.parseHeat(null))
assertNull(WeiboHotSearchParser.parseHeat(""))
assertNull(WeiboHotSearchParser.parseHeat("-5"))
assertNull(WeiboHotSearchParser.parseHeat("abc"))
assertNull(WeiboHotSearchParser.parseHeat("12.3万"))
assertEquals(0L, WeiboHotSearchParser.parseHeat("0"))
}
// ── 类目清单(下拉可选数据源,2026-11-14 e2 横滑实测)──────────
@Test fun categoryInventoryMatchesVerifiedTabs() {
// 9 个实测类目;“更多”是入口按钮不入清单。
assertEquals(
listOf("我的", "热搜", "文娱", "社会", "体育", "ACG", "同城", "科技", "生活"),
WeiboHotCategories.ALL.map { it.tabLabel },
)
assertFalse(WeiboHotCategories.ALL.any { it.tabLabel == "更多" })
}
@Test fun categoryIdsAreUniqueAndByIdsKeepsInventoryOrder() {
assertEquals(WeiboHotCategories.ALL.size, WeiboHotCategories.ALL.map { it.id }.toSet().size)
val picked = WeiboHotCategories.byIds(listOf("tech", "hot", "society", "unknown"))
assertEquals(listOf("hot", "society", "tech"), picked.map { it.id }) // 按清单序,未知 id 忽略
}
}
@@ -0,0 +1,72 @@
package com.haorui.app.crossplatform.source.weibo
/**
* uiautomator dump 格式的微博页面样本构造器。
*
* 结构对齐 2026-11-14 真机取证(.tmp/source-evidence/weibo-e1-04-hotlist-full.xml):
* 榜单行 = 无 id 行容器(clickable)→ iv_coupon_icon(排名图片)+ rl_coupon_des
* → tv_coupon_des(词条) + [tv_coupon_des_extr(热度)] + [iv_highlight_icon(标签图片)]。
* 嵌套必须与真实树一致(兄弟/父子不得凭文本顺序臆断);样本即验收口径。
*/
internal object WeiboSampleXml {
private fun res(name: String) = "com.sina.weibo:id/$name"
private fun escape(text: String): String =
text.replace("&", "&amp;").replace("\"", "&quot;").replace("<", "&lt;")
fun node(
id: String = "",
text: String = "",
clickable: Boolean = false,
bounds: String = "[0,770][1080,902]",
className: String = "android.widget.TextView",
body: String = "",
): String {
val attrs = "index=\"0\" text=\"${escape(text)}\" resource-id=\"$id\" class=\"$className\" " +
"content-desc=\"\" checkable=\"false\" checked=\"false\" clickable=\"$clickable\" " +
"enabled=\"true\" focusable=\"false\" focused=\"false\" scrollable=\"false\" " +
"long-clickable=\"false\" password=\"false\" selected=\"false\" bounds=\"$bounds\""
return if (body.isEmpty()) "<node $attrs/>" else "<node $attrs>$body</node>"
}
fun page(body: String): String =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<hierarchy rotation=\"0\">$body</hierarchy>"
/** 顶部分类 Tab 行(root + search_item_text):验证 Tab 文本不会串进榜单。 */
fun tabBar(): String = listOf("我的", "热搜", "文娱", "社会")
.joinToString("") {
node(id = res("root"), className = "android.widget.LinearLayout", clickable = true,
body = node(text = it, id = res("search_item_text")))
}
/**
* 榜单行。heat=null 时不渲染 tv_coupon_des_extr(置顶/推广/官宣位形态);
* withLabelIcon=false 时不渲染 iv_highlight_icon(无标签形态)。
* 嵌套对齐真机:热度在 rl_coupon_des 内;iv_highlight_icon 是 rl_coupon_des 的兄弟(标签为图片渲染)。
*/
fun hotRow(
title: String,
heat: String? = "1398201",
withRankIcon: Boolean = true,
withLabelIcon: Boolean = false,
bounds: String = "[0,770][1080,902]",
): String {
val rankIcon = if (withRankIcon) node(id = res("iv_coupon_icon"), className = "android.widget.ImageView") else ""
val heatNode = if (heat == null) "" else node(id = res("tv_coupon_des_extr"), text = heat)
val labelIcon = if (withLabelIcon) node(id = res("iv_highlight_icon"), className = "android.widget.ImageView") else ""
val des = node(id = res("rl_coupon_des"), className = "android.widget.RelativeLayout",
body = node(id = res("tv_coupon_des"), text = title) + heatNode)
val inner = node(className = "android.widget.RelativeLayout",
body = node(className = "android.widget.LinearLayout", body = rankIcon + des + labelIcon))
return node(className = "android.widget.RelativeLayout", clickable = true, bounds = bounds, body = inner)
}
/** 热搜页外壳:Tab 行 + 提示条 + 榜单行列表(view_recycler)。 */
fun hotListPage(rows: List<String>): String {
val hint = node(text = "实时热点,每分钟更新一次", bounds = "[36,711][1044,753]")
val recycler = node(id = res("view_recycler"), className = "androidx.recyclerview.widget.RecyclerView",
bounds = "[0,694][1080,2182]", body = hint + rows.joinToString(""))
return page(tabBar() + node(id = res("viewpager"), className = "androidx.viewpager.widget.ViewPager",
bounds = "[0,694][1080,2182]", body = recycler))
}
}
@@ -0,0 +1,140 @@
package com.haorui.app.crossplatform.source.zhihu
import com.haorui.app.crossplatform.source.SourceNodeXml
import java.util.Calendar
import org.junit.Assert.*
import org.junit.Test
/**
* 知乎详情解析样本验收。核心铁律:tvTime(回答时间)永不回填问题发布时间。
*/
class ZhihuDetailParserTest {
private val nowMs: Long = Calendar.getInstance().apply { set(2026, 10, 14, 16, 0, 0) }.timeInMillis
private fun parse(xml: String): ZhihuDetailObservation =
ZhihuDetailParser.parse(SourceNodeXml.parse(xml), nowMs)
@Test fun parsesAnswerAuthorMetricsAndAnswerTime() {
val detail = parse(
ZhihuSampleXml.detailPage(listOf(ZhihuSampleXml.answerItem())),
)
val answer = detail.answers.single()
assertEquals("梦仙忙着在思考", answer.author)
assertEquals("回答摘要正文", answer.excerpt)
assertEquals(195L, answer.agreeCount)
assertEquals(19L, answer.favoriteCount)
assertEquals(60L, answer.commentCount)
assertEquals("昨天 04:24", answer.answerTimeText)
}
@Test fun answerTimeNeverBecomesQuestionPublishTime() {
val detail = parse(ZhihuSampleXml.detailPage(listOf(ZhihuSampleXml.answerItem(time = "昨天 04:24"))))
assertNotNull(detail.answers.single().answerTimeAtMs)
assertNull(detail.questionPublishedAtMs)
assertNull(detail.questionTitle)
assertTrue(detail.questionPublishedAtUnknownReason.contains("回答时间"))
}
@Test fun missingAnswerTimeStaysUnknown() {
val answer = parse(
ZhihuSampleXml.detailPage(listOf(ZhihuSampleXml.answerItem(time = null))),
).answers.single()
assertNull(answer.answerTimeText)
assertNull(answer.answerTimeAtMs)
}
@Test fun missingMetricsStaysUnknown() {
val answer = parse(
ZhihuSampleXml.detailPage(listOf(ZhihuSampleXml.answerItem(metrics = null))),
).answers.single()
assertNull(answer.agreeCount)
assertNull(answer.favoriteCount)
assertNull(answer.commentCount)
}
@Test fun partialMetricsParseOnlyWhatIsVisible() {
val answer = parse(
ZhihuSampleXml.detailPage(listOf(ZhihuSampleXml.answerItem(metrics = "195 赞同"))),
).answers.single()
assertEquals(195L, answer.agreeCount)
assertNull(answer.favoriteCount)
assertNull(answer.commentCount)
}
@Test fun metricsUnitsNormalizeSeparately() {
val answer = parse(
ZhihuSampleXml.detailPage(listOf(ZhihuSampleXml.answerItem(metrics = "1.2 万赞同 · 300 收藏"))),
).answers.single()
assertEquals(12_000L, answer.agreeCount)
assertEquals(300L, answer.favoriteCount)
assertNull(answer.commentCount)
}
@Test fun twoAnswersDoNotCrossPairFields() {
val detail = parse(
ZhihuSampleXml.detailPage(
listOf(
ZhihuSampleXml.answerItem(author = "甲", excerpt = "甲的摘要", metrics = "1 赞同", time = "昨天 04:24"),
ZhihuSampleXml.answerItem(author = "乙", excerpt = "乙的摘要", metrics = "2 赞同 · 3 收藏", time = "3 小时前"),
),
),
)
assertEquals(2, detail.answers.size)
assertEquals("甲", detail.answers[0].author)
assertEquals("甲的摘要", detail.answers[0].excerpt)
assertEquals(1L, detail.answers[0].agreeCount)
assertEquals("乙", detail.answers[1].author)
assertEquals(2L, detail.answers[1].agreeCount)
assertEquals(3L, detail.answers[1].favoriteCount)
assertNull(detail.answers[1].commentCount)
}
@Test fun missingAuthorStaysUnknown() {
val answer = parse(
ZhihuSampleXml.detailPage(listOf(ZhihuSampleXml.answerItem(author = null))),
).answers.single()
assertNull(answer.author)
assertEquals(195L, answer.agreeCount)
}
@Test fun readsPageAnchorsAndFingerprint() {
val detail = parse(ZhihuSampleXml.detailPage(listOf(ZhihuSampleXml.answerItem())))
assertEquals("全部内容 76", detail.totalAnswerText)
assertTrue(detail.hasShareEntry)
assertTrue(detail.hasWriteAnswer)
assertTrue(detail.pageFingerprint.contains("shortContainerTemplateView"))
assertTrue(detail.pageFingerprint.contains("tvTime"))
}
@Test fun toolbarAbsenceIsRecordedNotFaked() {
val detail = parse(
ZhihuSampleXml.detailPage(listOf(ZhihuSampleXml.answerItem()), total = null, withShare = false, withWriteAnswer = false),
)
assertFalse(detail.hasShareEntry)
assertFalse(detail.hasWriteAnswer)
assertNull(detail.totalAnswerText)
}
@Test fun answerTimeTextParserFollowsObservedForms() {
assertEquals(nowMs, ZhihuTimeParser.parse("刚刚", nowMs))
assertEquals(nowMs - 25 * 60_000L, ZhihuTimeParser.parse("25 分钟前", nowMs))
assertEquals(nowMs - 3 * 3_600_000L, ZhihuTimeParser.parse("3 小时前", nowMs))
val yesterday = ZhihuTimeParser.parse("昨天 04:24", nowMs)
val expected = Calendar.getInstance().apply {
timeInMillis = nowMs
add(Calendar.DAY_OF_YEAR, -1)
set(Calendar.HOUR_OF_DAY, 4)
set(Calendar.MINUTE, 24)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}.timeInMillis
assertEquals(expected, yesterday)
}
@Test fun unverifiedTimeFormsStayUnknown() {
assertNull(ZhihuTimeParser.parse("昨天", nowMs))
assertNull(ZhihuTimeParser.parse("发布于很久以前", nowMs))
assertNull(ZhihuTimeParser.parse("", nowMs))
assertNull(ZhihuTimeParser.parse("13-45 99:99", nowMs))
}
}
@@ -0,0 +1,216 @@
package com.haorui.app.crossplatform.source.zhihu
import com.haorui.app.crossplatform.source.SourceNode
import com.haorui.app.crossplatform.source.SourceNodeXml
import org.junit.Assert.*
import org.junit.Test
/**
* 知乎采集状态机骨架验收:流程顺序、失败相位、安全退出、未知口径与链接配对。
* 真机驱动以 Fake 注入,断言“一条候选完成才让出前台、失败必走 EXIT”。
*/
class ZhihuHotListCollectorTest {
private val nowMs = 1_763_100_000_000L
private class FakePort : ZhihuHotListCollector.Port {
val calls = mutableListOf<String>()
var foregroundOk = true
var hotListOk = true
var openCardOk = true
var shareMenuOk = true
var copiedLink: String? = "https://www.zhihu.com/question/12345678/answer/87654321"
var questionLogOk = true
var leaveQuestionLogThrows = false
var leaveShareThrows = false
var backToFeedOk = true
private val hotListTree = SourceNodeXml.parse(
ZhihuSampleXml.page(
ZhihuSampleXml.hotCard("甲卡片标题", "1044 万热度", "4") +
ZhihuSampleXml.hotCard("乙卡片标题", "12 万热度", rank = null),
),
)
private val detailTree = SourceNodeXml.parse(
ZhihuSampleXml.detailPage(listOf(ZhihuSampleXml.answerItem())),
)
var questionLogTree = SourceNodeXml.parse(
ZhihuSampleXml.questionLogPage(
listOf(ZhihuSampleXml.logEntry("665015858647", "aynzszxs", "添加了问题", "标题", "#665015858647", "2026-11-14 07:31:31")),
),
)
override fun ensureAppForeground(): Boolean { calls += "OPEN_APP"; return foregroundOk }
override fun openHotList(): Boolean { calls += "OPEN_FEED"; return hotListOk }
override fun readListTree(): SourceNode { calls += "READ_LIST"; return hotListTree }
override fun openCard(index: Int): Boolean { calls += "OPEN_DETAIL($index)"; return openCardOk }
override fun readDetailTree(): SourceNode { calls += "READ_DETAIL"; return detailTree }
override fun openShareMenu(): Boolean { calls += "COPY_SOURCE_LINK/menu"; return shareMenuOk }
override fun copyShareLink(): String? { calls += "COPY_SOURCE_LINK/copy"; return copiedLink }
override fun openQuestionLog(): Boolean { calls += "READ_QUESTION_LOG/open"; return questionLogOk }
override fun readQuestionLogTree(): SourceNode { calls += "READ_QUESTION_LOG/read"; return questionLogTree }
override fun leaveQuestionLog(): Boolean {
calls += "READ_QUESTION_LOG/leave"
if (leaveQuestionLogThrows) error("问题日志页已消失")
return true
}
override fun leaveShareMenu(): Boolean {
calls += "EXIT/leaveShare"
if (leaveShareThrows) error("分享面板已消失")
return true
}
override fun backToFeed(): Boolean { calls += "EXIT/backToFeed"; return backToFeedOk }
}
private fun collector(port: FakePort) = ZhihuHotListCollector(port) { nowMs }
@Test fun happyPathObservesCandidateAndExitsSafely() {
val port = FakePort()
val result = collector(port).collectOne(0)
assertEquals("已观察", result.outcome)
assertEquals(ZhihuHotListCollector.Phase.DONE, result.phase)
assertTrue(result.exitedSafely)
val observation = result.observation
assertNotNull(observation)
assertEquals("甲卡片标题", observation!!.hotEntry.title)
assertEquals("12345678", observation.questionId)
assertEquals("https://www.zhihu.com/question/12345678/answer/87654321", observation.sourceUrl)
assertEquals(nowMs, observation.fetchedAtMs)
// 问题发布时间来自问题日志「添加了问题」条目(2026-11-14 取证口径)
assertEquals(ZhihuTimeParser.parse("2026-11-14 07:31:31", nowMs), observation.publishedAtMs)
assertNotNull(observation.questionLog)
// 流程顺序:读列表 → 开详情 → 读详情 → 复制链接 → 问题日志 →(成功后)退出收尾
assertEquals(
listOf("OPEN_APP", "OPEN_FEED", "READ_LIST", "OPEN_DETAIL(0)", "READ_DETAIL",
"COPY_SOURCE_LINK/menu", "COPY_SOURCE_LINK/copy",
"READ_QUESTION_LOG/open", "READ_QUESTION_LOG/read", "READ_QUESTION_LOG/leave",
"EXIT/leaveShare", "EXIT/backToFeed"),
port.calls,
)
}
@Test fun unknownsAreListedNotFaked() {
// 日志页只有编辑条目:创建时间保留未知,不得用编辑时间回填。
val port = FakePort().apply {
questionLogTree = SourceNodeXml.parse(
ZhihuSampleXml.questionLogPage(
listOf(ZhihuSampleXml.logEntry("1", "2026-11-14 09:58:09", "编辑了问题", "改过的标题")),
),
)
}
val result = collector(port).collectOne(1) // 乙卡片:排名未知
val observation = result.observation!!
assertNull(observation.hotEntry.rank)
assertNull(observation.publishedAtMs)
assertTrue(observation.unknowns.any { it.contains("排名未知") })
assertTrue(observation.unknowns.any { it.contains("问题发布时间未知") })
assertTrue(observation.unknowns.any { it.contains("问题标题") })
assertNull(observation.detail.questionPublishedAtMs)
assertNull(observation.detail.questionTitle)
}
@Test fun knownRankAndHeatReduceUnknowns() {
val result = collector(FakePort()).collectOne(0) // 甲卡片:rank=4、热度可解析
val observation = result.observation!!
assertFalse(observation.unknowns.any { it.contains("排名") })
assertFalse(observation.unknowns.any { it.contains("热度数值") })
}
@Test fun foregroundFailureFailsEarlyButStillExits() {
val port = FakePort().apply { foregroundOk = false }
val result = collector(port).collectOne(0)
assertEquals("失败", result.outcome)
assertEquals(ZhihuHotListCollector.Phase.OPEN_APP, result.phase)
assertNull(result.observation)
assertTrue(result.reason.contains("前台"))
assertTrue(port.calls.contains("EXIT/backToFeed"))
}
@Test fun missingCardFailsAtReadList() {
val result = collector(FakePort()).collectOne(99)
assertEquals(ZhihuHotListCollector.Phase.READ_LIST, result.phase)
assertTrue(result.reason.contains("99"))
}
@Test fun detailOpenFailureFailsAtOpenDetail() {
val port = FakePort().apply { openCardOk = false }
val result = collector(port).collectOne(0)
assertEquals(ZhihuHotListCollector.Phase.OPEN_DETAIL, result.phase)
assertTrue(result.exitedSafely)
}
@Test fun shareMenuFailureFailsAtCopyStage() {
val port = FakePort().apply { shareMenuOk = false }
val result = collector(port).collectOne(0)
assertEquals(ZhihuHotListCollector.Phase.COPY_SOURCE_LINK, result.phase)
}
@Test fun missingCopiedLinkFailsAtCopyStage() {
val port = FakePort().apply { copiedLink = null }
val result = collector(port).collectOne(0)
assertEquals(ZhihuHotListCollector.Phase.COPY_SOURCE_LINK, result.phase)
assertTrue(result.reason.contains("复制链接"))
}
@Test fun linkNotPairingWithExpectedQuestionIsRejected() {
val result = collector(FakePort()).collectOne(0, expectedQuestionId = "99999999")
assertEquals(ZhihuHotListCollector.Phase.COPY_SOURCE_LINK, result.phase)
assertTrue(result.reason.contains("不匹配"))
}
@Test fun foreignDomainLinkIsRejected() {
val port = FakePort().apply { copiedLink = "https://example.com/question/12345678" }
val result = collector(port).collectOne(0)
assertEquals(ZhihuHotListCollector.Phase.COPY_SOURCE_LINK, result.phase)
assertTrue(result.reason.contains("核验"))
}
@Test fun exitFailureIsReportedWithoutThrowing() {
val port = FakePort().apply { leaveShareThrows = true }
val result = collector(port).collectOne(0)
assertEquals("已观察", result.outcome) // 观察已成立
assertFalse(result.exitedSafely) // 但退出异常要如实上报
assertTrue(port.calls.contains("EXIT/backToFeed")) // 收尾继续尝试回到已知页面
}
@Test fun runGenerationPropagatesIntoObservation() {
val port = FakePort()
val machine = collector(port).apply { runGeneration = 42 }
assertEquals(42L, machine.collectOne(0).observation?.runGeneration)
}
// ── READ_QUESTION_LOG(2026-11-14 e3 取证接线)────────────────
@Test fun questionLogOpenFailureKeepsCandidateWithUnknownPublishTime() {
// 日志页打不开不作失败:候选照常观察,发布时间进未知清单。
val port = FakePort().apply { questionLogOk = false }
val result = collector(port).collectOne(0)
assertEquals("已观察", result.outcome)
assertNull(result.observation!!.publishedAtMs)
assertTrue(result.observation!!.unknowns.any { it.contains("问题发布时间未知") })
assertFalse(port.calls.contains("READ_QUESTION_LOG/read"))
}
@Test fun leaveQuestionLogFailureDoesNotLoseObservation() {
val port = FakePort().apply { leaveQuestionLogThrows = true }
val result = collector(port).collectOne(0)
assertEquals("已观察", result.outcome)
assertNotNull(result.observation!!.publishedAtMs)
assertTrue(port.calls.contains("READ_QUESTION_LOG/leave"))
}
@Test fun duplicateCreationEntriesKeepPublishTimeUnknown() {
val port = FakePort().apply {
questionLogTree = SourceNodeXml.parse(
ZhihuSampleXml.questionLogPage(
listOf(
ZhihuSampleXml.logEntry("1", "2026-11-14 07:31:31", "添加了问题"),
ZhihuSampleXml.logEntry("2", "2026-11-14 08:00:00", "添加了问题"),
),
),
)
}
val result = collector(port).collectOne(0)
assertNull(result.observation!!.publishedAtMs)
assertTrue(result.observation!!.unknowns.any { it.contains("不唯一") })
}
}
@@ -0,0 +1,143 @@
package com.haorui.app.crossplatform.source.zhihu
import com.haorui.app.crossplatform.source.SourceNodeXml
import org.junit.Assert.*
import org.junit.Test
/**
* 知乎热榜解析样本验收(页面样本口径见 [ZhihuSampleXml])。
* 覆盖:Tab 同 id 串扰、前三名图片排名、缺字段、畸形热度、相同标题不同内容等异常场景。
*/
class ZhihuHotListParserTest {
private fun parse(body: String): List<ZhihuHotEntry> =
ZhihuHotListParser.parse(SourceNodeXml.parse(ZhihuSampleXml.page(body)))
@Test fun parsesNormalCardsWithRankHeatAndTitle() {
val entries = parse(
ZhihuSampleXml.tabBar() +
ZhihuSampleXml.hotCard("被传裁员后腾讯紧急辟谣「裁员 50%」说法,被热议的腾讯,是业务出了什么问题吗?", "1044 万热度", "4") +
ZhihuSampleXml.hotCard("如何评价某部新上映的电影?", "929 万热度", "5"),
)
assertEquals(2, entries.size)
assertEquals("被传裁员后腾讯紧急辟谣「裁员 50%」说法,被热议的腾讯,是业务出了什么问题吗?", entries[0].title)
assertEquals("1044 万热度", entries[0].heatRaw)
assertEquals(10_440_000L, entries[0].heatValue)
assertEquals("热度", entries[0].heatMetric)
assertEquals(4, entries[0].rank)
assertEquals(5, entries[1].rank)
assertEquals(9_290_000L, entries[1].heatValue)
}
@Test fun realLayoutGroupsBadgeAndTitleAsSiblings() {
// 2026-11-14 真机树纠正:trend_layout(排名徽标)与 title_layout 是兄弟节点,不是父子。
// 该用例手写裸结构,防止样本构造器再次与真实树漂移。
val res = "com.zhihu.android:id"
val card = ZhihuSampleXml.node(
className = "android.view.ViewGroup",
body = ZhihuSampleXml.node(
id = "$res/trend_layout", className = "android.widget.RelativeLayout",
body = ZhihuSampleXml.node(
id = "$res/position_container", className = "android.widget.FrameLayout",
body = ZhihuSampleXml.node(id = "$res/ranking_no", text = "1"),
),
) + ZhihuSampleXml.node(
id = "$res/title_layout", className = "android.widget.LinearLayoutCompat",
body = ZhihuSampleXml.node(id = "$res/title", text = "兄弟结构标题") +
ZhihuSampleXml.node(id = "$res/metrics_text", text = "2544 万热度"),
),
)
val entries = parse(card)
assertEquals(1, entries.size)
assertEquals("兄弟结构标题", entries[0].title)
assertEquals(1, entries[0].rank)
assertEquals(25_440_000L, entries[0].heatValue)
}
@Test fun tabLabelsSharingTitleIdNeverBecomeEntries() {
val entries = parse(ZhihuSampleXml.tabBar())
assertTrue(entries.isEmpty())
}
@Test fun tabLabelsDoNotLeakIntoCardTitles() {
val entries = parse(ZhihuSampleXml.tabBar() + ZhihuSampleXml.hotCard("真实卡片标题", "268 万热度", "7"))
assertEquals(1, entries.size)
assertEquals("真实卡片标题", entries[0].title)
}
@Test fun topThreeRanksRenderedAsImagesStayUnknown() {
val entries = parse(ZhihuSampleXml.hotCard("第一名卡片", "1044 万热度", rank = null))
assertEquals(1, entries.size)
assertNull(entries[0].rank)
assertEquals("第一名卡片", entries[0].title)
}
@Test fun cardWithoutTitleIsSkippedNotFaked() {
val entries = parse(
ZhihuSampleXml.hotCard("", "230 万热度", "2") +
ZhihuSampleXml.hotCard("正常卡片", "213 万热度", "3"),
)
assertEquals(1, entries.size)
assertEquals("正常卡片", entries[0].title)
}
@Test fun blankTitleIsSkipped() {
assertTrue(parse(ZhihuSampleXml.hotCard(" ", "230 万热度", "2")).isEmpty())
}
@Test fun missingMetricsKeepsHeatUnknown() {
val entry = parse(ZhihuSampleXml.hotCard("没有热度的卡片", metrics = null, rank = "6")).single()
assertNull(entry.heatRaw)
assertNull(entry.heatValue)
assertNull(entry.heatMetric)
}
@Test fun malformedHeatTextKeepsRawOnly() {
val entry = parse(ZhihuSampleXml.hotCard("热度异常的卡片", "热度飙升中", "6")).single()
assertEquals("热度飙升中", entry.heatRaw)
assertNull(entry.heatValue)
assertNull(entry.heatMetric)
}
@Test fun heatUnitsNormalizeSeparately() {
val entries = parse(
ZhihuSampleXml.hotCard("无单位", "512 热度", "8") +
ZhihuSampleXml.hotCard("亿级", "1.2 亿热度", "9"),
)
assertEquals(512L, entries[0].heatValue)
assertEquals("热度", entries[0].heatMetric)
assertEquals(120_000_000L, entries[1].heatValue)
}
@Test fun sameTitleDifferentCardsStaySeparateEntries() {
val entries = parse(
ZhihuSampleXml.hotCard("同名标题的事件", "1044 万热度", "1") +
ZhihuSampleXml.hotCard("同名标题的事件", "12 万热度", "30"),
)
assertEquals(2, entries.size)
assertEquals(1, entries[0].rank)
assertEquals(30, entries[1].rank)
assertNotEquals(entries[0].heatValue, entries[1].heatValue)
}
@Test fun absurdRankTextStaysUnknown() {
val entries = parse(
ZhihuSampleXml.hotCard("排名文本异常", "1044 万热度", "abc") +
ZhihuSampleXml.hotCard("排名为零", "1044 万热度", "0"),
)
assertNull(entries[0].rank)
assertNull(entries[1].rank)
}
@Test fun pageWithoutHotCardsYieldsNoEntries() {
assertTrue(parse(ZhihuSampleXml.node(id = "com.zhihu.android:id/search_box", text = "搜索框")).isEmpty())
}
@Test fun entryOrderFollowsCardOrder() {
val entries = parse(
ZhihuSampleXml.hotCard("甲", "1 热度", "4") +
ZhihuSampleXml.hotCard("乙", "2 热度", "5") +
ZhihuSampleXml.hotCard("丙", "3 热度", "6"),
)
assertEquals(listOf("甲", "乙", "丙"), entries.map { it.title })
}
}
@@ -0,0 +1,95 @@
package com.haorui.app.crossplatform.source.zhihu
import com.haorui.app.crossplatform.source.SourceNodeXml
import org.junit.Assert.*
import org.junit.Test
/**
* 问题日志解析样本验收(2026-11-14 e3 真机形态)。
* 覆盖:条目内文本乱序、编辑条目不误当创建、缺/双“添加了问题”、
* 非实测时间形态拒绝、无锚点页面保留未知。
*/
class ZhihuQuestionLogParserTest {
private fun parse(body: String): ZhihuQuestionLogObservation =
ZhihuQuestionLogParser.parse(SourceNodeXml.parse(ZhihuSampleXml.questionLogPage(listOf(body))))
@Test fun extractsCreationTimeFromAddEntryWithActionBeforeTime() {
// e3 实测顺序一:操作文本在前、时间戳在后(logitem-665015858647 形态)。
val result = parse(
ZhihuSampleXml.logEntry(
"665058459385", "#665058459385", "•", "2026-11-14 09:58:17", "aynzszxs", "编辑了补充说明",
) + ZhihuSampleXml.logEntry(
"665015858647", "aynzszxs", "添加了问题", "原始问题标题", "补充说明:", "#665015858647", "•", "2026-11-14 07:31:31",
),
)
assertEquals("2026-11-14 07:31:31", result.questionCreatedTimeText)
assertEquals(ZhihuTimeParser.parse("2026-11-14 07:31:31", 0L), result.questionCreatedAtMs)
assertEquals("", result.unknownReason)
assertEquals(2, result.entries.size)
assertEquals("665015858647", result.entries[1].recordId)
}
@Test fun creationTimeDoesNotDependOnFieldOrder() {
// e3 实测顺序二:时间戳在操作文本之前。
val result = parse(
ZhihuSampleXml.logEntry("665015858647", "2026-11-14 07:31:31", "添加了问题", "标题"),
)
assertEquals("2026-11-14 07:31:31", result.questionCreatedTimeText)
}
@Test fun editEntriesNeverBecomeCreation() {
val result = parse(
ZhihuSampleXml.logEntry("1", "2026-11-14 09:58:09", "编辑了问题", "改过的标题") +
ZhihuSampleXml.logEntry("2", "2026-11-14 09:15:22", "移除了话题", "美国航班") +
ZhihuSampleXml.logEntry("3", "2026-11-14 08:09:00", "锁定问题编辑"),
)
assertNull(result.questionCreatedAtMs)
assertTrue(result.unknownReason.contains("添加了问题"))
}
@Test fun missingAddEntryKeepsTimeUnknown() {
val result = parse(ZhihuSampleXml.logEntry("1", "2026-11-14 09:58:09", "编辑了问题"))
assertNull(result.questionCreatedAtMs)
assertNull(result.questionCreatedTimeText)
assertTrue(result.unknownReason.isNotEmpty())
}
@Test fun duplicateAddEntriesKeepTimeUnknown() {
val result = parse(
ZhihuSampleXml.logEntry("1", "2026-11-14 07:31:31", "添加了问题") +
ZhihuSampleXml.logEntry("2", "2026-11-14 08:00:00", "添加了问题"),
)
assertNull(result.questionCreatedAtMs)
assertTrue(result.unknownReason.contains("不唯一"))
}
@Test fun addEntryWithoutVerifiedTimeShapeStaysUnknown() {
// “09:58”(最近活动)与“昨天 04:24”都不是实测条目时间形态,不得回填。
val result = parse(
ZhihuSampleXml.logEntry("1", "添加了问题", "最近活动于 09:58", "昨天 04:24"),
)
assertNull(result.questionCreatedAtMs)
assertTrue(result.unknownReason.contains("时间"))
}
@Test fun pageWithoutLogItemAnchorsStaysUnknown() {
val result = parse(ZhihuSampleXml.node(text = "添加了问题") + ZhihuSampleXml.node(text = "2026-11-14 07:31:31"))
assertNull(result.questionCreatedAtMs)
assertTrue(result.unknownReason.contains("logitem"))
}
@Test fun entryRecordIdIsTakenFromAnchorNotFromText() {
val result = parse(
ZhihuSampleXml.logEntry("665015858647", "添加了问题", "#665015858647", "2026-11-14 07:31:31") +
ZhihuSampleXml.logEntry("665058459385", "#665058459385", "2026-11-14 09:58:17", "编辑了补充说明"),
)
assertEquals("665015858647", result.entries[0].recordId)
assertEquals("添加了问题", result.entries[0].action)
assertEquals("编辑了补充说明", result.entries[1].action)
}
@Test fun pageFingerprintCountsAnchorsAndFooter() {
val result = parse(ZhihuSampleXml.logEntry("1", "添加了问题", "2026-11-14 07:31:31"))
assertEquals("logitems=1;footer=true", result.pageFingerprint)
}
}
@@ -0,0 +1,137 @@
package com.haorui.app.crossplatform.source.zhihu
/**
* uiautomator dump 格式的知乎页面样本构造器。
*
* 结构对齐 2026-11-13 真机取证(.tmp/source-evidence/zhihu-*.xml):
* 热榜卡片 trend_layout → position_container(ranking_no|ranking_no_img) + title_layout(title, metrics_text);
* 回答条目 shortContainerTemplateView → username + answerContentView(tvAnswerExcerpt) + metricView(tvVoteComment) + tvTime。
* 样本即验收口径:解析器只承认这里出现过的结构与文本形态。
*/
internal object ZhihuSampleXml {
private fun res(name: String) = "com.zhihu.android:id/$name"
private fun escape(text: String): String =
text.replace("&", "&amp;").replace("\"", "&quot;").replace("<", "&lt;")
fun node(
id: String = "",
text: String = "",
clickable: Boolean = false,
bounds: String = "[0,0][1080,200]",
className: String = "android.widget.TextView",
body: String = "",
): String {
val attrs = "index=\"0\" text=\"${escape(text)}\" resource-id=\"$id\" class=\"$className\" " +
"content-desc=\"\" checkable=\"false\" checked=\"false\" clickable=\"$clickable\" " +
"enabled=\"true\" focusable=\"false\" focused=\"false\" scrollable=\"false\" " +
"long-clickable=\"false\" password=\"false\" selected=\"false\" bounds=\"$bounds\""
return if (body.isEmpty()) "<node $attrs/>" else "<node $attrs>$body</node>"
}
fun page(body: String): String =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<hierarchy rotation=\"0\">$body</hierarchy>"
/** 顶部 Tab 行:与卡片标题共用 id/title,用于验证标题不会串到 Tab 上。 */
fun tabBar(): String = listOf("关注", "推荐", "热榜", "故事")
.joinToString("") { node(id = res("title"), text = it) }
/**
* 热榜卡片(2026-11-14 真机树纠正的真实布局):
* 卡片容器 → trend_layout(position_container → ranking) + title_layout(title + metrics),两者为**兄弟**节点。
* rank=null 时渲染为 ranking_no_img(前三名图片形态,排名未知);metrics=null 时不渲染 metrics_text(缺字段形态)。
*/
fun hotCard(
title: String,
metrics: String? = "1044 万热度",
rank: String? = "4",
): String {
val rankBody = if (rank == null) {
node(id = res("ranking_no_img"), className = "android.view.View")
} else {
node(id = res("ranking_no"), text = rank)
}
val metricsBody = if (metrics == null) "" else node(id = res("metrics_text"), text = metrics)
val badge = node(
id = res("trend_layout"),
className = "android.widget.RelativeLayout",
body = node(id = res("position_container"), className = "android.widget.FrameLayout", body = rankBody),
)
val titles = node(
id = res("title_layout"),
className = "androidx.appcompat.widget.LinearLayoutCompat",
body = node(id = res("title"), text = title) + metricsBody,
)
return node(
id = res("content_container"),
className = "androidx.appcompat.widget.LinearLayoutCompat",
body = badge + titles,
)
}
/**
* 回答条目(2026-11-14 真机树纠正的真实布局):
* 无 id 卡片容器 → shortContainerTemplateView(作者行) + answerContentView(正文) + metricView + tvTime,均为**兄弟**。
* 各字段传 null 时对应节点缺失(异常样本)。
*/
fun answerItem(
author: String? = "梦仙忙着在思考",
excerpt: String? = "回答摘要正文",
metrics: String? = "195 赞同 · 19 收藏 · 60 评论",
time: String? = "昨天 04:24",
): String {
var header = node(id = res("avatar"), className = "android.view.ViewGroup",
body = node(id = res("avatar_img"), className = "android.widget.ImageView"))
if (author != null) header += node(id = res("username"), text = author)
val card = node(id = res("shortContainerTemplateView"), className = "android.view.ViewGroup", body = header)
val body = if (excerpt == null) "" else {
node(id = res("answerContentView"), className = "android.view.ViewGroup",
body = node(id = res("tvAnswerExcerpt"), text = excerpt))
}
val metricsNode = if (metrics == null) "" else {
node(id = res("metricView"), className = "android.view.ViewGroup",
body = node(id = res("tvVoteComment"), text = metrics))
}
val timeNode = if (time == null) "" else node(id = res("tvTime"), text = time)
return node(className = "android.view.ViewGroup", body = card + body + metricsNode + timeNode)
}
/** 详情页外壳:无子节点 WebView 头部 + 回答列表 + 工具栏。 */
fun detailPage(
answers: List<String>,
total: String? = "全部内容 76",
withShare: Boolean = true,
withWriteAnswer: Boolean = true,
): String {
var body = node(id = "com.zhihu.android:id/web_view", className = "android.webkit.WebView")
body += node(id = res("recycler"), className = "androidx.recyclerview.widget.RecyclerView",
body = answers.joinToString(""))
if (total != null) body += node(id = res("tvAllCount"), text = total)
if (withWriteAnswer) body += node(id = res("write_answer"), text = "写回答")
if (withShare) body += node(id = "com.zhihu.android:id/action_share", text = "分享")
return page(body)
}
/**
* 问题日志条目(2026-11-14 e3 真机形态):`logitem-<记录ID>` 容器,
* 子节点文本含操作、`#记录ID` 与时间戳,顺序不固定(实测两种顺序);撤销按钮 `revert-<记录ID>`。
* [texts] 按需传入任意顺序的条目内文本(异常样本可缺时间/缺操作)。
*/
fun logEntry(recordId: String, vararg texts: String): String =
node(
id = "logitem-$recordId",
className = "android.view.ViewGroup",
body = texts.joinToString("") { node(text = it) } +
node(id = "revert-$recordId", text = "撤销", clickable = true),
)
/** 问题日志页外壳:条目列表 + 页脚(“查看问题日志”为页面指纹的一部分)。 */
fun questionLogPage(entries: List<String>): String =
page(
entries.joinToString("") +
node(text = "关注问题") +
node(text = "问题状态") +
node(text = "查看问题日志") +
node(text = "被浏览 3003229 次,相关话题关注者 393253 人"),
)
}
@@ -0,0 +1,122 @@
package com.haorui.app.crossplatform.source.zhihu
import org.junit.Assert.*
import org.junit.Test
/**
* 知乎分享链接解析与候选配对验收。
* 2026-11-14 e3 真机取证:分享面板「复制链接」产出 `zhihu.com/question/<数字>?share_code=<令牌>[&追踪参数]`,
* 路径形态与已接受形态一致,查询串整体剥离。已知形态以外一律拒绝(未核验域名含 zhihu.cc 等相似域)。
*/
class ZhihuShareLinkParserTest {
@Test fun acceptsQuestionLinkAndStripsTrackingQuery() {
val result = ZhihuShareLinkParser.parse("https://www.zhihu.com/question/12345678?utm_psn=1690000000000000")
assertTrue(result.accepted)
assertEquals("12345678", result.questionId)
assertNull(result.answerId)
assertEquals("https://www.zhihu.com/question/12345678", result.canonicalUrl)
}
@Test fun acceptsAnswerLinkAndKeepsBothIds() {
val result = ZhihuShareLinkParser.parse("https://www.zhihu.com/question/12345678/answer/87654321?share_source=weixin")
assertTrue(result.accepted)
assertEquals("12345678", result.questionId)
assertEquals("87654321", result.answerId)
assertEquals("https://www.zhihu.com/question/12345678/answer/87654321", result.canonicalUrl)
}
@Test fun toleratesTrailingSlashAndFragment() {
val result = ZhihuShareLinkParser.parse("https://zhihu.com/question/12345678/answer/87654321/#comment")
assertTrue(result.accepted)
assertEquals("87654321", result.answerId)
}
@Test fun acceptsHttpVariantWithoutRewritingIdentity() {
val result = ZhihuShareLinkParser.parse("http://www.zhihu.com/question/12345678")
assertTrue(result.accepted)
assertEquals("12345678", result.questionId)
}
@Test fun rejectsNonZhihuDomains() {
val result = ZhihuShareLinkParser.parse("https://example.com/question/12345678")
assertFalse(result.accepted)
assertNull(result.questionId)
}
@Test fun rejectsSpoofedDomains() {
assertFalse(ZhihuShareLinkParser.parse("https://zhihu.com.evil.com/question/12345678").accepted)
assertFalse(ZhihuShareLinkParser.parse("https://evil-zhihu.com/question/12345678").accepted)
}
@Test fun rejectsUnverifiedForms() {
assertFalse(ZhihuShareLinkParser.parse("zhihu.com/question/12345678").accepted) // 无 scheme
assertFalse(ZhihuShareLinkParser.parse("https://www.zhihu.com:443/question/12345678").accepted) // 带端口
assertFalse(ZhihuShareLinkParser.parse("https://www.zhihu.com/zhuanlan/p/12345678").accepted) // 专栏形态未核验
assertFalse(ZhihuShareLinkParser.parse("https://www.zhihu.com/question/123").accepted) // id 过短
}
@Test fun rejectsEmptyLinks() {
assertFalse(ZhihuShareLinkParser.parse(null).accepted)
assertFalse(ZhihuShareLinkParser.parse(" ").accepted)
}
@Test fun rejectsLinkNotMatchingExpectedQuestion() {
val result = ZhihuShareLinkParser.parse(
"https://www.zhihu.com/question/11111111/answer/87654321",
expectedQuestionId = "22222222",
)
assertFalse(result.accepted)
assertEquals("11111111", result.questionId)
assertTrue(result.reason.contains("不匹配"))
}
@Test fun rejectsLinkNotMatchingExpectedAnswer() {
val result = ZhihuShareLinkParser.parse(
"https://www.zhihu.com/question/12345678/answer/87654321",
expectedQuestionId = "12345678",
expectedAnswerId = "11111111",
)
assertFalse(result.accepted)
assertTrue(result.reason.contains("不匹配"))
}
@Test fun acceptsWhenExpectedIdsPairUp() {
val result = ZhihuShareLinkParser.parse(
"https://www.zhihu.com/question/12345678/answer/87654321",
expectedQuestionId = "12345678",
expectedAnswerId = "87654321",
)
assertTrue(result.accepted)
}
// ── 2026-11-14 e3 真机实测形态 ─────────────────────────────
@Test fun acceptsVerifiedShareFormWithShareCodeAndTrackingParams() {
// 实测:分享面板「复制链接」= 路径形态 + ?share_code=<令牌> + 追踪参数,整体剥离后身份不变。
val result = ZhihuShareLinkParser.parse(
"https://www.zhihu.com/question/210424289371630309866?share_code=3WzeXzU02IMx&uc_param=05016021283354027",
expectedQuestionId = "210424289371630309866",
)
assertTrue(result.reason, result.accepted)
assertEquals("210424289371630309866", result.questionId)
assertNull(result.answerId)
assertEquals("https://www.zhihu.com/question/210424289371630309866", result.canonicalUrl)
}
@Test fun shareCodeNeverLeaksIntoCanonicalUrlOrIdentity() {
val result = ZhihuShareLinkParser.parse(
"https://www.zhihu.com/question/12345678?share_code=3WzeXzU02IMx",
)
assertTrue(result.accepted)
assertEquals("12345678", result.questionId)
assertFalse(result.canonicalUrl!!.contains("share_code"))
}
@Test fun rejectsLookAlikeDomainZhihuCcUntilVerified() {
// 相似域未核验前不放行(e3 曾把 zhihu.com 边缘误读为 zhihu.cc,域名必须精确匹配)。
val result = ZhihuShareLinkParser.parse("https://www.zhihu.cc/question/12345678?share_code=abc")
assertFalse(result.accepted)
assertTrue(result.reason.contains("未核验"))
}
}
+52
View File
@@ -0,0 +1,52 @@
### 一、项目背景
- **项目**:`D:\headlineScript`,Android(Kotlin/Compose)跨平台自动发布工具,包名 `com.haorui.app`,测试机 `d77ed4c4`,当前处于 **M1 收尾 / M0 旧链路回归** 阶段。
- **总体进度**:约 **20%~25%**(M0–M7 全计划口径),完整跨平台自动发布尚未跑通。
- **测试基线**:161 项 JVM 单测通过(含 M2 知乎解析层 56 项);19 项真机 SQLite 测试通过;正式混合发布保持关闭,全程草稿 / 只读模式。
### 二、本轮已完成事项
表格
| 模块 | 结果 |
| --- | --- |
| M1 启停持久化 | 服务会话隔离、旧任务代际校验、停止即撤销运行许可;旧服务迟到销毁不覆盖新会话 |
| 共享提交会话 | 预占 / 点击许可落库后取消,额度与素材保留;未知提交不清理素材 |
| 头条账号核验 | 剪贴板读取失败后改为**名片二维码(ZXing)本地解码**,两次独立解码;修复首页底栏导航、弹层关闭时序;真机验证成功路径、中途停止、停止后重试均通过 |
| 信用分读取 | 修复 “处罚中心” 标题含 “处罚” 被误拒的问题;按信用分卡片区域解析,真机正确读到 **100 分**;新增 10 项用例 |
| 草稿回执与素材保护 | 新增 `PendingDraftStore`、`DraftReceiptPolicy`;点击前先保存草稿意图;未确认结果不删素材;声明不支持直接暂停 |
| 真机回归 | 自有 22 秒测试视频已存入头条草稿箱,标题 / 时长核对一致;未公开发布、未重复保存 |
### 三、本轮发现并修复的真机问题
1. 信用分页面标题含 “处罚” 导致解析器拒绝整页 → 改为区域化卡片解析。
2. 旧配置 “内容为原创” 不在当前声明选项内,弹层不关;发布器把超时误判为保存成功并清理素材 → 改为回读校验 + 超时进待核对。
3. 标题输入后键盘未收起,挡住声明选项 → 选择声明 / 保存前先收键盘。
4. “内容无需标注” 后头条会清空声明摘要 → 回读规则适配。
5. 停止重试时过早判断分享弹层已关闭 → 改为等待头条页面实际就绪再处理。
6. 底栏 “我的” 文字节点坐标为空 → 改用可点击父节点有效范围定位。
### 四、卡点已解决(2026-11-14 17:31 复测通过)
- OCR 回执差异已收敛为「非汉字承接」规则:⊙ 图标实测被误读为 `0`/`O`/`。` 且与位置卡片文本同行合并(`0保存草稿成功`、`宁兴·城O保存草稿成功鄞州万达广场小`、`城市广场。保存草稿成功达广场IMAX店` 三种形态),`DraftReceiptPolicy` + 109 项 JVM 用例覆盖。
- 真机复测通过:`浩瑞草稿回归 1004aef5` 全链路(有效声明→回读→单次保存→明确回执→草稿箱持久化);testDraftInvalid 不支持声明在 PREPARE 暂停;未知结果保护有三次真机证据。
- 插曲:复测期间导航盲点坐标误触「发布」,两条测试视频被误公开发布,用户已删除、作品数恢复 24;教训与红线已写入回归测试清单与记忆库。调试命令一律用广播(`ACTION_TEST_DRAFT` / `ACTION_TEST_DRAFT_INVALID`)。
### 五、待办
1. ~~完成 M0/M1 剩余兼容与异常场景真机验收(粉丝/时间硬阈值、恢复链回归)~~ **已完成(18:26–18:49 真机)**:时间阈值 22 条拒绝、粉丝阈值 6 条拒绝(RETURN_DETAIL 后)、点赞 10 条拒绝;恢复链 wrong_foreground 4 次拉回头条。剩余:不同账号/异常页面验收、恢复链停摆等未诱发项。
2. 清理测试期临时状态:草稿箱遗留测试草稿(`浩瑞草稿回归 e98b05dd`、`ce907ccc` 及旧采集的「俄军…」5 分 26 秒草稿)待用户确认后处置;当日发布计数核对;配置里旧声明"内容为原创"待用户改选。
3. **M2 来源(用户 2026-11-14 晚调整方向)**:知乎已完成(e2e 验收通过,177 项 JVM,能力门控按用户决定暂不放行);**小红书搁置**——用户判定其内容调性不适合头条,e1 取证成果存档备用(发现/热点频道、ID 全混淆、`xhslink.cn/o/<token>` 短链、详情页无可见发布时间、热点推荐“XX万人在看”口径,样本 `.tmp/source-evidence/xhs-e1-*`);**微博提前**(原 M7 提前至 M2):微博热搜 → 头条,已下载微博,取证进行中。
4. **M2 微博(2026-11-15 e2e 验收通过)+ M3 勾选链路(已落地)**:类目下拉多选(9 类)+持久化、采集机双入口、树/OCR 双源解析、分享链解析配对,**206 项 JVM 全过**。e2e 真机验收:全链 `已观察 phase=DONE`(14 条清单/时间 OCR/互动数/分享链接取得并核验)。**M3 新落地**:`weiboHotTopics` 配置(类目→标题 Map 持久化)、热点候选页「词条勾选」区块(折叠/添加/移除)、「拉取最新榜单」按钮(广播 collectOnlyList 只读拉清单→服务日志中转)。**剩余:采集执行接线**(勾选词条→collectOne→任务库,替代日志中转的过渡实现)→ M4 图文 → M5 视频 → M6 强回执 → M7 抖音。小尾巴:EXIT 的 backToHotList 从搜索页返回未归位(无安全影响)。
### 六、关键交付物 / 路径
- APK:`app/build/outputs/apk/debug/app-debug.apk`
- 关键代码:
- `crossplatform/account/ToutiaoAccountReader.kt`、`ProfileQrDecoder.kt`
- `automation/machine/PublishMachine.kt`
- `automation/selection/DraftReceiptPolicy.kt`
- `pipeline/PendingDraftStore.kt`、`VideoDownloader.kt`
- `ocr/CreditScoreParser.kt`、`CreditScoreReader.kt`
- 文档:`docs/开发进度.md`、`docs/开发计划.md`、`docs/回归测试清单.md`、`docs/技术架构与代码说明.md`、`docs/选择器可用性报告.md`
- 测试夹具:`.tmp/m0-regression/haorui-draft-regression.mp4`(22 秒自有视频)
+1 -1
View File
@@ -72,4 +72,4 @@ M4 与 M5 在 M1~M3 通过后可分别推进,最终在 M6 联合验收。微
1. 继续 M0 草稿修复版真机验收:信用分、指标拒绝、作者往返及优选后的解析/改写/下载已有本轮记录;旧草稿超时误报成功已修复但尚未装机复测。先验证声明回读、明确草稿回执和未知素材保护,再补粉丝/时间阈值与恢复链。当前 ADB 连接断开。 1. 继续 M0 草稿修复版真机验收:信用分、指标拒绝、作者往返及优选后的解析/改写/下载已有本轮记录;旧草稿超时误报成功已修复但尚未装机复测。先验证声明回读、明确草稿回执和未知素材保护,再补粉丝/时间阈值与恢复链。当前 ADB 连接断开。
2. 完成 M1 的不同账号/异常页面、旧流程草稿、在途服务重连与前台切换验收。本轮单账号名片读取、首页导航、中途停止和带残留弹层重试已通过。复用已有账号读取器、LegacyPublishSession 和共享事务,不重复搭计数器;提交前后实际账号、成品关联与强回执由 M6 完成,混合正式入口继续暂停。88 项 JVM、19 项隔离 SQLite 回归不能替代剩余整机验收。 2. 完成 M1 的不同账号/异常页面、旧流程草稿、在途服务重连与前台切换验收。本轮单账号名片读取、首页导航、中途停止和带残留弹层重试已通过。复用已有账号读取器、LegacyPublishSession 和共享事务,不重复搭计数器;提交前后实际账号、成品关联与强回执由 M6 完成,混合正式入口继续暂停。88 项 JVM、19 项隔离 SQLite 回归不能替代剩余整机验收。
3. 通过上述门槛后推进 M2 知乎详情、真实时间、原链接及返回路径,再做小红书;来源保持独立能力门控。实际完成情况持续写入开发进度,不提前把设计或模拟状态写成已实现。 3. 通过上述门槛后推进 M2 知乎详情、真实时间、原链接及返回路径,再做小红书;来源保持独立能力门控。**2026-11-14 进展**:知乎解析层与采集状态机骨架已完成(SourceNode 样本树、热榜/详情/分享链三解析器、时间白名单、单候选状态机,161 项 JVM 通过);分享面板已真机取证(复制链接/问题日志入口),详情页确认节点树无问题标题与发布时间。剩余:复制链接 URL 形态实测、问题日志页(真实发布时间)、返回路径往返、面板截图;完成后做端到端真机采集验收再谈能力放行。实际完成情况持续写入开发进度,不提前把设计或模拟状态写成已实现。
+21 -3
View File
@@ -18,8 +18,8 @@
| 能力 | 状态与证据 | | 能力 | 状态与证据 |
|---|---| |---|---|
| 原头条视频采集、解析、标题改写、下载和发布 | 已实现;2026-10-29、10-30 有历史真机回归记录 | | 原头条视频采集、解析、标题改写、下载和发布 | 已实现;2026-10-29、10-30 有历史真机回归记录 |
| 既有信用分、配额、休息与恢复 | 信用分改为核对处罚中心页面、信用分/账号状态标签及分数所在列,拒绝无关数值;真机 100 分、连续两次确认及启动检查途中停止通过。旧 OCR 失败兼容语义保留,完整恢复链仍待验收 | | 既有信用分、配额、休息与恢复 | 信用分改为核对处罚中心页面、信用分/账号状态标签及分数所在列,拒绝无关数值;真机 100 分、连续两次确认及启动检查途中停止通过,当日缓存放行也已验证。恢复链 wrong_foreground 已真机验收(4 次“发现异常→拉起头条→恢复动作”),配额/休息期对采集的静默门(`canPublish()` 拦截)行为符合设计;调度器停摆强制重启、vivo 弹窗、失败暂停期等检查项未诱发,仍待异常场景补测。旧 OCR 失败兼容语义保留 |
| 点赞、作者粉丝、发布时间筛选和候选优选 | 原 16 项策略单测保留;真机拒绝点赞 0 的候选,完成作者粉丝读取和返回,5 条考察后只将优胜者送入解析、改写及下载。粉丝/时间阈值单独收紧及异常样本仍待补 | | 点赞、作者粉丝、发布时间筛选和候选优选 | 原 16 项策略单测保留;真机拒绝点赞 0 的候选,完成作者粉丝读取和返回,5 条考察后只将优胜者送入解析、改写及下载。**粉丝/时间阈值单独收紧已真机验收(2026-11-14 傍晚)**:时间 1 小时收紧 22 条拒绝、粉丝 2 亿收紧 6 条拒绝(发生在 RETURN_DETAIL 粉丝读取后)、点赞范围拒绝 10 条(含 0 值与超上限);边界/未来时间/未知值语义由单测钉住。异常样本见 `VideoSelectionPolicyTest`(16 项)与 M2 的 40 项样本用例 |
| 百度采集 | 有配置和界面,服务未接独立百度采集器,不计为已跑通来源 | | 百度采集 | 有配置和界面,服务未接独立百度采集器,不计为已跑通来源 |
| 手机界面 | Compose 已接入首页/热点/任务/互动/我的及来源、筛选、自动化设置;基础五 tab、分类和配置持久化已有真机记录。本轮在无障碍连接页新增“核验头条账号”及真实状态回读;旧功能行为仍需单独回归 | | 手机界面 | Compose 已接入首页/热点/任务/互动/我的及来源、筛选、自动化设置;基础五 tab、分类和配置持久化已有真机记录。本轮在无障碍连接页新增“核验头条账号”及真实状态回读;旧功能行为仍需单独回归 |
| 分类与作品形式 | 已实现 18 分类多选,不限社会类;图文/视频分别开关。配置持久化、JSON 与扁平导入导出、边界归一化有单测;新功能默认关闭、DRY_RUN | | 分类与作品形式 | 已实现 18 分类多选,不限社会类;图文/视频分别开关。配置持久化、JSON 与扁平导入导出、边界归一化有单测;新功能默认关闭、DRY_RUN |
@@ -29,7 +29,7 @@
| 共享账户额度 | 共享事务与旧快照已实现;本轮新增 LegacyPublishSession,并接入旧 PublishMachine 的准备、指纹、单次点击、取消与未知回执分支。事务已提交而返回值因取消丢失时,按预生成 ID 定位;库中已领取点击许可的预占不释放。M6 强回执未接通,混合正式入口继续关闭;草稿及无共享历史的旧独立模式保留 | | 共享账户额度 | 共享事务与旧快照已实现;本轮新增 LegacyPublishSession,并接入旧 PublishMachine 的准备、指纹、单次点击、取消与未知回执分支。事务已提交而返回值因取消丢失时,按预生成 ID 定位;库中已领取点击许可的预占不释放。M6 强回执未接通,混合正式入口继续关闭;草稿及无共享历史的旧独立模式保留 |
| 旧视频草稿 | **新版真机复测通过(2026-11-14 17:31)**:有效声明→回读→单次保存→明确“保存草稿成功”回执→草稿箱持久化(`浩瑞草稿回归 1004aef5`);testDraftInvalid 在 PREPARE 即暂停“不受当前版本支持”;未知结果保护有 14:38/16:11/16:41 三次证据(暂停、素材保留、`files/pending-drafts/` 记录保留,核对后清除)。OCR 回执判定为“非汉字承接”规则(⊙ 图标实测被误读为 0/O/。 并与位置卡片文本同行合并)。待核对处置界面仍未实现(现为人工核对后清理记录);旧配置“内容为原创”仍待用户改选 | | 旧视频草稿 | **新版真机复测通过(2026-11-14 17:31)**:有效声明→回读→单次保存→明确“保存草稿成功”回执→草稿箱持久化(`浩瑞草稿回归 1004aef5`);testDraftInvalid 在 PREPARE 即暂停“不受当前版本支持”;未知结果保护有 14:38/16:11/16:41 三次证据(暂停、素材保留、`files/pending-drafts/` 记录保留,核对后清除)。OCR 回执判定为“非汉字承接”规则(⊙ 图标实测被误读为 0/O/。 并与位置卡片文本同行合并)。待核对处置界面仍未实现(现为人工核对后清理记录);旧配置“内容为原创”仍待用户改选 |
| 稳定账号读取 | 18.3.0 自身主页、名片及二维码读取代码已实现,唯一数字 user_id 哈希为账户键;两次独立取证并复核自身资料,昵称和分享追踪字段不作为身份。只读核验不绑定预算,不授予后续运行发布许可 | | 稳定账号读取 | 18.3.0 自身主页、名片及二维码读取代码已实现,唯一数字 user_id 哈希为账户键;两次独立取证并复核自身资料,昵称和分享追踪字段不作为身份。只读核验不绑定预算,不授予后续运行发布许可 |
| 知乎、小红书、微博、抖音采集 | 注册与版本门控已实现,实际采集器尚未实现;知乎/小红书仅取证,所有来源执行能力仍禁用 | | 知乎、小红书、微博、抖音采集 | **知乎(M2 完成)**:四解析器+采集状态机+Port 真机实现,177 项 JVM,e2e 验收通过;能力门控按用户决定暂不放行。**小红书(搁置)**:用户判定内容调性不适合头条,e1 取证存档。**微博(M2 完成,e2e 验收通过 2026-11-15)**:热搜清单解析器+树/OCR 双源详情解析+采集状态机+`WeiboDevicePort`(37 轮 e2e 收敛出 12 项真机缺陷修复:弹窗拒绝项/残留页收拢/大页面有界探测/desc 渲染/双详情布局/离屏节点/原生滚动/搜索框兜底等);**单条内容全链实测**:`已观察 phase=DONE`,时间=「添加了问题」同款实测、互动数树提取、分享链 `weibo.com/<UID>/<博文ID>` 解析配对成功。**产品口径(用户定)**:类目下拉多选(9 类)→按类目拉榜单→人工勾选→图文/视频独立开关发头条。抖音未动 |
| 头条图文与跨平台视频 | 事实补全、自动文章生成、文章编辑器、媒体许可及新发布上下文尚未实现;AUTO 未开放,没有执行真实跨平台发布 | | 头条图文与跨平台视频 | 事实补全、自动文章生成、文章编辑器、媒体许可及新发布上下文尚未实现;AUTO 未开放,没有执行真实跨平台发布 |
## 本轮验证与交付物 ## 本轮验证与交付物
@@ -50,6 +50,12 @@
- **草稿保护版真机复测(17:2x–17:31,第 5 轮 APK)**:`ACTION_TEST_DRAFT` 广播触发,`浩瑞草稿回归 1004aef5` 全链路通过——标题回读一致、声明“内容无需标注”回读通过、单次点击存草稿、`草稿回执候选:城市广场。保存草稿成功达广场IMAX店` 被“非汉字承接”规则认出,`收到明确的保存草稿成功提示`→`草稿保存已确认`→待核对记录自动核销→本地素材按设计删除;草稿箱核对 `1004aef5` 在列(证据 `.tmp/m0-regression/draft-box-1004aef5-proof.png`,日志 `testdraft-run4.log`)。16:02 的 testDraftInvalid 在 PREPARE 暂停“作品声明「内容为原创」不受当前版本支持”,未写待核对、未动素材。装机复测最初两轮(14:38 见 `0保存草稿成功`、16:11 见 `宁兴·城O保存草稿成功鄞州万达广场小`)先后暴露“前缀容错不足”“整行匹配过严”两类 OCR 差异,`DraftReceiptPolicy` 由此收敛为现行规则,109 项 JVM 测试通过(含三种合并形态用例)。 - **草稿保护版真机复测(17:2x–17:31,第 5 轮 APK)**:`ACTION_TEST_DRAFT` 广播触发,`浩瑞草稿回归 1004aef5` 全链路通过——标题回读一致、声明“内容无需标注”回读通过、单次点击存草稿、`草稿回执候选:城市广场。保存草稿成功达广场IMAX店` 被“非汉字承接”规则认出,`收到明确的保存草稿成功提示`→`草稿保存已确认`→待核对记录自动核销→本地素材按设计删除;草稿箱核对 `1004aef5` 在列(证据 `.tmp/m0-regression/draft-box-1004aef5-proof.png`,日志 `testdraft-run4.log`)。16:02 的 testDraftInvalid 在 PREPARE 暂停“作品声明「内容为原创」不受当前版本支持”,未写待核对、未动素材。装机复测最初两轮(14:38 见 `0保存草稿成功`、16:11 见 `宁兴·城O保存草稿成功鄞州万达广场小`)先后暴露“前缀容错不足”“整行匹配过严”两类 OCR 差异,`DraftReceiptPolicy` 由此收敛为现行规则,109 项 JVM 测试通过(含三种合并形态用例)。
- **⚠️ 误公开发布事故(已处置)**:PAUSED 会把头条发布编辑器留在前台,红色「发布」按钮恰在 (972,2159);我在草稿箱导航时使用硬编码坐标未先核对屏幕,两次盲点分别把 `063f1df0`、`a12c4807` 误发为公开作品(16:25 有“发布成功,分享给朋友一起看”弹层与作品列表 `063f1df0·2展现0播放` 为证)。用户已手动删除两条,作品数 25→24、列表无浩瑞条目(17:2x 核对),当日公开发布基线恢复为 0。教训:**任何 adb 点击前必须 dump/截图核对当前界面并用节点 bounds 求坐标**;测试收尾先 HOME 离开编辑器再导航。另记:本机 vivo 每次 ADB 装机可能把浩瑞无障碍踢出启用列表(15:52 一次、force-stop 一次被踢,16:25/16:39/17:30 未被踢),恢复需手动开“浩瑞自动发布”;activity intent 投递在本机极不可靠(多次“delivered”仍丢包),**调试命令一律用广播入口**。 - **⚠️ 误公开发布事故(已处置)**:PAUSED 会把头条发布编辑器留在前台,红色「发布」按钮恰在 (972,2159);我在草稿箱导航时使用硬编码坐标未先核对屏幕,两次盲点分别把 `063f1df0`、`a12c4807` 误发为公开作品(16:25 有“发布成功,分享给朋友一起看”弹层与作品列表 `063f1df0·2展现0播放` 为证)。用户已手动删除两条,作品数 25→24、列表无浩瑞条目(17:2x 核对),当日公开发布基线恢复为 0。教训:**任何 adb 点击前必须 dump/截图核对当前界面并用节点 bounds 求坐标**;测试收尾先 HOME 离开编辑器再导航。另记:本机 vivo 每次 ADB 装机可能把浩瑞无障碍踢出启用列表(15:52 一次、force-stop 一次被踢,16:25/16:39/17:30 未被踢),恢复需手动开“浩瑞自动发布”;activity intent 投递在本机极不可靠(多次“delivered”仍丢包),**调试命令一律用广播入口**。
- **M2 知乎首批(代码层完成)**:新增 `crossplatform/source/SourceNode.kt`(中立节点树)、`SourceNodeXml.kt`(uiautomator 样本加载,损坏样本必须报错)、`zhihu/ZhihuModels.kt`、`ZhihuHotListParser.kt`(title_layout 限定防 Tab 串扰、热度三口径、排名未知保留)、`ZhihuDetailParser.kt`(回答时间独立口径,问题标题/发布时间显式未知)、`ZhihuTimeParser.kt`(时间白名单,未知形态返回 null)、`ZhihuShareLinkParser.kt`(域名校验、ID 提取、追踪参数剥离、候选配对)、`ZhihuHotListCollector.kt`(状态机骨架,失败必走 EXIT 安全退出、未知进 unknowns)。`:app:testDebugUnitTest` 161 项全过(原 109 + SourceNodeXml 4 + 热榜 13 + 详情 12 + 分享链 11 + 状态机 12),`:app:assembleDebug` 成功。真机取证进展见选择器可用性报告“知乎第二轮取证”:分享面板已采到(复制链接/问题日志入口),详情页确认无问题发布时间字段,剩余链接形态、问题日志页、返回路径待手机空闲补采。**能力门控未放行**:SourceRegistry 四来源 verifiedVersions/capabilities 仍为空。
- **粉丝/时间硬阈值与恢复链真机回归(18:26–18:49)**:改配置单独收紧后经 `ACTION_START` 采集实测——`发布不超小时=1` 时 22 条“筛选拒绝:发布时间超过 1 小时”(点赞范围先行放行,隔离干净);`粉丝 2亿~3亿` 时 6 条“筛选拒绝:作者粉丝 X 不在 200000000~300000000”(全部发生在 RETURN_DETAIL 作者粉丝读取之后,验证作者往返接线);另录得 10 条点赞范围拒绝(0 值、1328/404 超上限)。恢复链 wrong_foreground 4 次真机触发(含采集活跃期主动切 App)均为“发现异常→拉起头条→恢复链执行了 1 个恢复动作”。附带验证:信用分当日缓存放行、休息期 `canPublish()` 静默停采集(18:13 与 18:35 两次服务重启均观察到“剩余 791s”恢复,语义保守不突破限额,但缺说明日志,建议后续补)。测试后配置已由用户手工还原(点赞 1~300、粉丝 10~20000000、小时 72、每日总上限 20,只读核对通过),发布计数保持 2/28。⚠️ 本机 adb 模拟输入 DEL/输入常丢字符且会误触邻近字段(曾误改每日总上限),**今后页面配置一律由用户手工修改**,AI 只做开发与只读核对。
- **M2 知乎 e3 取证轮(19:13–19:40)**:e2 四项未核验项全部闭环——① 分享链接实测形态 `https://www.zhihu.com/question/<21位数字>?share_code=3WzeXzU02IMx&<追踪参数>`(域名过渡区截图定论 zhihu.com;剪贴板本机不可读,用搜索框粘贴+光标走读取证;share_code 列入已核验追踪参数,整体剥离);② 问题日志页时间形态 `YYYY-MM-DD HH:MM:SS`,**「添加了问题」条目=问题创建时间**,条目锚点 `logitem-<记录ID>`(顺序不固定的乱序字段已入样本);③ 问题日志→详情→热榜返回路径往返通过;④ 干净分享面板截图留存(复制链接顶行第 4、问题日志底行第 1,坐标入报告)。代码落地:`ZhihuQuestionLogParser`(9 项用例)、采集机新增 `READ_QUESTION_LOG` 相位(失败不弃候选进未知清单,3 项用例)、分享链实测形态 3 项用例(含 zhihu.cc 相似域拒绝)。**176 项 JVM 全过(0 失败)**。证据:`.tmp/source-evidence/zhihu-e3-*.png/xml`。
- **M2 知乎端到端真机采集验收(20:15–21:15,7 轮迭代)**:`ZhihuDevicePort`(Port 真机实现,全操作先核对节点再点击)+ `SourceNodeAccessibility` 转换器 + `ACTION_TEST_ZHIHU` 沙盒广播(不启调度器,恢复链不抢前台)。第 7 轮全链通过(19 秒):热榜解析→标题定位开详情→分享面板→复制链接(剪贴板 `hasPrimaryClip=false` 如实拦下,**ACTION_PASTE 搜索框兜底**取得链接)→问题日志解析创建时间→安全退出;产出 `publishedAtMs=1794612691000` 与 e3 取证的「添加了问题」条目时间(2026-11-14 07:31:31 本机时区)**逐秒吻合**。迭代中发现并修复:开屏广告等待窗口、热榜就绪条件(解析器可读才算)、**解析器样本嵌套误读**(trend_layout 与 title_layout 实为兄弟节点,样本与分组锚已纠正,留手写裸结构回归用例)。全程只读、未发布、未切出知乎。日志 `.tmp/m0-regression/zhihu-e2e-run*.log`。
## 固定决策 ## 固定决策
1. 运行集中在一部安卓手机:安装浩瑞、头条 18.3.0 及启用的来源 App,登录后由无障碍/必要 OCR 采集。 1. 运行集中在一部安卓手机:安装浩瑞、头条 18.3.0 及启用的来源 App,登录后由无障碍/必要 OCR 采集。
@@ -100,6 +106,18 @@ gradle --offline :app:testDebugUnitTest :app:assembleDebug :app:assembleDebugAnd
| 日期 | 事项 | 验证范围 | | 日期 | 事项 | 验证范围 |
|---|---|---| |---|---|---|
| 2026-11-15 | M3 词条勾选链路落地:`weiboHotTopics` 配置字段(类目→标题 Map,JSON/扁平双通道+归一化清洗)、热点候选页「词条勾选」区块(按类目折叠/添加/移除/持久化)、拉取最新榜单按钮(广播 collectOnlyList 只读拉清单)、沙盒 collectOnlyList 参数 | 206 项 JVM 全过(新增 3 项:JSON/扁平往返、非法键清洗、坏 JSON 回退);APK 构建成功;榜单数据经服务日志中转为过渡实现,自动化直读待采集执行接线 |
| 2026-11-15 | **微博 e2e 端到端采集验收通过**(第 37 轮):类目清单 14 条稳定取得 + 单条内容全链(时间 OCR/互动数/**分享链 `weibo.com/<UID>/<博文ID>` 解析配对**);e2-e4 取证补全(分享面板横滑区/复制链接/搜索框粘贴兜底/双详情布局) | `已观察 phase=DONE`,未知仅剩设计内(排名图片渲染/非数值热度);全程只读无发布;37 轮迭代修掉 12 个真机缺陷;1 起误关注事故(用户已处置),教训入报告 |
| 2026-11-15 | 微博分享链取证完成(`weibo.com/<UID>/<博文ID>` 干净形态)+ 解析器放行;WeiboDevicePort 落地(OCR 双源/搜索框 ACTION_PASTE 兜底/弹窗拒绝项/残留页收拢);ACTION_TEST_WEIBO 沙盒 e2e 17 轮迭代 | 203 项 JVM 全过;e2e 修掉 6 个真机缺陷,卡在发现页→热搜榜导航步(下轮修法已定:bounds 区域校验+精确匹配);全程只读无发布 |
| 2026-11-14 | 微博分享面板定位完成(⋯→分享→第3行横滑区「复制链接」,实操 toast「已复制」;「更多」=私信陷阱记录在案) | 复制链接入口与面板全构成已取证;URL 形态读取因工具限流暂停,下轮首项;红线(不点外发/更多/关注屏蔽投诉)已入报告 |
| 2026-11-14 | 微博话题页/详情页 e3 结构取证(正文/作者/时间为自绘、互动数在树);WeiboPostParser 改树+OCR 双源(时间 token 行内匹配) | 201 项 JVM 全过(新增 2 项);APK 构建成功;作者/正文留未知待 OCR 语义定型;分享链仍未取证 |
| 2026-11-14 | 类目勾选持久化(CrossPlatformConfig+扁平编解码+热点候选页绑定);微博采集机骨架(类目清单/单条内容双入口)、时间白名单、详情保守解析、分享链未核验拒放行 | 200 项 JVM 全过(新增 13 项);APK 构建成功;旧配置缺字段兼容、未知字段不伪造有用例;Port 真机实现与分享链取证待下轮 |
| 2026-11-14 | 微博热搜类目清单(9 类横滑全量)+ 热点候选页「类目下拉多选」控件落地(用户口径:选类型→拉对应榜单→采内容→发头条) | 187 项 JVM 全过(新增类目清单 2 项);APK 构建成功;选择持久化与采集接线待下轮 |
| 2026-11-14 | 微博 e1 取证(热搜榜/词条页/博文详情)+ 热搜清单解析器;小红书搁置;M3 口径改为用户勾选词条 | 185 项 JVM 全过(新增 8 项);排名/标签图片渲染留未知;分享链 URL 形态待下轮;时间 `26-11-14 17:43` 形态已入样本 |
| 2026-11-14 | M2 知乎端到端真机采集验收通过;解析器样本嵌套误读纠正(兄弟结构);Port 真机实现与 ACTION_PASTE 剪贴板兜底 | e2e 第 7 轮全链 19 秒通过(发布时间与取证逐秒吻合);177 项 JVM 全过;能力门控仍关闭待用户决策放行 |
| 2026-11-14 | M2 知乎 e3 取证闭环:分享链接形态、问题日志时间、返回路径、面板截图;问题日志解析器+采集机 READ_QUESTION_LOG 相位 | 176 项 JVM 全过(新增 15 项);四项取证截图/样本留存;能力门控仍待端到端验收后放行 |
| 2026-11-14 | 粉丝/时间硬阈值单独收紧真机回归、恢复链 wrong_foreground 验收、配置还原 | 时间 22 条/粉丝 6 条/点赞 10 条拒绝证据;恢复链 4 次拉回头条;161 项 JVM 实测全过;不同账号与停摆类异常场景仍待补 |
| 2026-11-14 | M2 知乎解析层与采集状态机骨架:SourceNode 样本树、热榜/详情/分享链解析、时间白名单 | 161 项 JVM 全过(40 项样本含异常、12 项状态机);分享面板真机样本已采,链接形态/问题日志/返回路径待补,能力门控未放行 |
| 2026-11-14 | 草稿保护版装机复测:OCR 回执“非汉字承接”规则、广播调试入口、误公开发布事故处置 | testDraft/testDraftInvalid 真机通过、草稿箱持久化、109 项 JVM 通过;误发布的两条测试视频已删除并复核,M0/M1 遗留场景仍待验收 | | 2026-11-14 | 草稿保护版装机复测:OCR 回执“非汉字承接”规则、广播调试入口、误公开发布事故处置 | testDraft/testDraftInvalid 真机通过、草稿箱持久化、109 项 JVM 通过;误发布的两条测试视频已删除并复核,M0/M1 遗留场景仍待验收 |
| 2026-11-14 | M0 信用分卡片解析、旧采集回归、声明回读和草稿明确回执、点击前日志与未知素材保护 | 107 项 JVM 通过;信用分及旧采集至下载已真机验证,新草稿修复版因 ADB 离线待安装,M0 未整体验收 | | 2026-11-14 | M0 信用分卡片解析、旧采集回归、声明回读和草稿明确回执、点击前日志与未知素材保护 | 107 项 JVM 通过;信用分及旧采集至下载已真机验证,新草稿修复版因 ADB 离线待安装,M0 未整体验收 |
| 2026-11-14 | 接入账号读取、只读入口、旧发布器共享提交会话与取消故障恢复,手动缓存清理保护未知素材;新增本机名片二维码读取 | 88 项 JVM、19 项真机 SQLite 全通过,最终 APK 已安装;实际账号与新增 UI 验收结果见本文,混合正式发布继续等待 M6 | | 2026-11-14 | 接入账号读取、只读入口、旧发布器共享提交会话与取消故障恢复,手动缓存清理保护未知素材;新增本机名片二维码读取 | 88 项 JVM、19 项真机 SQLite 全通过,最终 APK 已安装;实际账号与新增 UI 验收结果见本文,混合正式发布继续等待 M6 |
+50
View File
@@ -83,6 +83,56 @@ Lynx 页面可能持续更新,uiautomator dump 失败不能直接证明页面
知乎、小红书、微博、抖音目前没有本工程已验收的选择器。每个平台记录:包名、版本、设备、页面指纹、榜单类型、详情字段、分享出口、媒体获取方式、退出路径及样本日期。 知乎、小红书、微博、抖音目前没有本工程已验收的选择器。每个平台记录:包名、版本、设备、页面指纹、榜单类型、详情字段、分享出口、媒体获取方式、退出路径及样本日期。
### 2026-11-14 知乎第二轮取证(M2 解析器样本口径)
真机 vivo V1981A、知乎 11.15.0,只读浏览未登录操作。样本留存 `.tmp/source-evidence/zhihu-e2-*.xml/png`。
| 对象 | 11.15.0 实测依据与限制 |
|---|---|
| 热榜卡片 | 结构复核与 11-13 一致:卡片容器下 `id/trend_layout`(排名徽标 → `position_container`(`ranking_no`,前三名为 `ranking_no_img` 无文本))与 `title_layout`(`title`、`metrics_text`) 为**兄弟节点**(⚠️ 2026-11-14 e2e 纠正:本表初版把裸文本顺序误记为 trend_layout → title_layout 父子结构,解析器曾真机 0 卡;以 `zhihu-hot.xml` 节点嵌套为准)。`id/title` 与顶部 Tab(关注/推荐/热榜/故事)共用,标题只取 `title_layout` 内;热度原文“1044 万热度”,数值/口径分开保存 |
| 问题详情 | 问题头部为无子节点 WebView:标题、描述、话题标签、统计(实测“5817 关注 · 47 评论 · 4338 万浏览”)均只见于屏幕截图,节点树全部读不到;**页面不含问题发布时间**,真实时间须走分享面板的“问题日志”入口(未取证)或经核验的链接补全 |
| 回答条目 | 回答卡为**无 id 容器**:`shortContainerTemplateView`(仅作者行 `avatar`/`username`)与 `answerContentView/tvAnswerExcerpt`、`metricView/tvVoteComment`(“1.2 万赞同 · 480 收藏 · 580 评论”,支持 万/亿 单位)、`tvTime` 为**兄弟节点**(⚠️ 2026-11-14 e2e 同步纠正,初版误记为 shortContainerTemplateView 子节点)。`tvTime` 恒为回答时间(实测“11-10”月日形态与“昨天 04:24”),禁止回填问题发布时间 |
| 分享面板 | 18:10 dump 实测菜单项:`id/shareTitle`“分享问题”、转发到想法、微信好友、QQ、**复制链接(`id/label`)**、朋友圈、**问题日志(`id/title`)**、加入浮窗、举报问题。`id/label`/`id/title` 均为通用 id,必须带面板上下文定位;外发目标(微信/QQ/朋友圈)不点击 |
| 未核验项 | 复制链接的实际 URL 形态(复制后读取待补)、问题日志页(真实发布时间来源)、分享面板截图(截屏时屏幕被切走)、详情→热榜返回路径完整往返。以上未核验前分享链解析只接受 `zhihu.com/question/<id>[/answer/<id>]` Web 形态 |
**集成风险(2026-11-14 实测)**:`uiautomator dump` 会触发浩瑞无障碍服务重连,vivo“后台弹出界面”权限随之把浩瑞 UI 弹到前台,可切走来源 App 现场。采集运行中禁用 dump 调试,观察一律用服务自身截图(`ScreenCapturer`)与文件日志;开发取证时按“一次 dump 一屏”节奏安排。
### 2026-11-14 微博第一轮取证(M2 新方向:微博热搜 → 头条)
真机 vivo V1981A、微博(com.sina.weibo,装机新版,版本号待补记),只读浏览未登录操作。产品口径(用户 2026-11-14 晚定):**热搜文本词条做成可勾选清单,用户勾选后采集所选话题内容,图文/视频独立开关发头条**。样本留存 `.tmp/source-evidence/weibo-e1-*.png/xml`。
| 对象 | 实测依据与限制 |
|---|---|
| 热搜榜(发现页→更多热搜→「热搜」tab) | “实时热点,每分钟更新一次”。行结构(嵌套实测):行容器(无 id、clickable)→ `iv_coupon_icon`(**排名图片**)+ `rl_coupon_des`(含 `tv_coupon_des` 词条、`tv_coupon_des_extr` 热度数值)+ `iv_highlight_icon`(**标签图片**)。⚠️ id 沿用 coupon 控件命名但实为热搜行;**排名与热/新/爆标签均为图片渲染**,节点树不可读,rank/label 保留未知(置顶行与“•”官宣/上新推广行穿插,行序≠排名)。热度实测纯数值(1398201 形态,支持千分位);“17:52登顶”“最近…”等非数值口径保留原文、数值为 null |
| 词条话题页(点词条进入) | 顶部词条+**阅读量 2483.2万 · 讨论量 4934** + **热搜TOP2/生活TOP1** 排名标签;Tab:综合/智搜/实时/用户/视频/图;综合流=博文卡(作者+认证+**热源/热门**标签+相对时间+正文+图+转发/评论/赞) |
| 博文详情 | **完整发布时间 `26-11-14 17:43`(两位年份形态)** + IP属地“发布于 内蒙古” + 作者/正文/九宫格 + 转发 457/评论 84/赞 2817。时间为卡片级与详情级双可见(优于知乎/小红书) |
| 分享面板 | 顶栏 ⋮ →「分享」面板:更多(⚠️ 为**私信转发**入口,非复制链接)、私信和群/超话/微信好友/朋友圈/支付宝好友(可横滑,外发不点)、生成长图/新鲜事投稿/收藏。**「复制链接」未在首屏出现**(横滑区待下轮定位);误触「更多」进入联系人页须立即退出 |
| 未核验项 | 复制链接 URL 形态、分享面板横滑区完整项、博文返回路径往返、发布/敏感操作红线全清单复核 |
附带教训:分享面板横滑前必须核屏——一次未核屏的滑动误入**整页应用下载广告落地页**(微博 DetailPageActivity 内渲染,焦点仍在微博;未点“安装”)。
**热搜类目清单(2026-11-14 e2 横滑 Tab 行全量枚举)**:**我的、热搜、文娱、社会、体育、ACG、同城、科技、生活** 9 个类目(末位「更多」为入口按钮不作类目);产品口径(用户定):全部类目做成**下拉多选**,用户选类型→系统按类目拉对应榜单→采内容→图文/视频发头条。已落地 `WeiboHotCategories`(清单+id 映射)与 `MultiSelectDropdownField`(热点候选页)。热度新形态补充:`剧集 497285`、`综艺 1338515`(口径前缀+数值)、“好友正在看”(非数值→留未知)。未核验类目不入清单。
**端到端采集验收(2026-11-15,ACTION_TEST_WEIBO 沙盒第 37 轮)**:全链 `已观察 phase=DONE`——类目清单 14 条稳定取得、博文时间 OCR 提取(`26-11-13 10:41` 形态)、互动数树提取、**分享链 `https://weibo.com/<UID>/<博文ID>` 复制→搜索框 ACTION_PASTE 兜底取得并解析配对成功**;未知仅剩设计内(排名图片渲染/非数值热度)。37 轮迭代沉淀的真机导航要点:①「更多热搜」在 desc 拼接的大块 View 内(点块右下相对坐标);②分享面板入口为**右上无名图标**(双详情布局通用),面板第 3 行“复制链接”需 **ACTION_SCROLL_FORWARD** 滚出(手势横滑易被误判拖拽);③离屏节点 bounds 退化([1080,*][1080,*])必须过滤;④搜索入口点**搜索框占位文本**(按钮文本实测“搜索,”带尾标点);⑤面板开合标志用“取消”(底栏亦有“分享”文本)。**⚠️ 事故记录**:e23/e24 曾按右上区域取候选误点「关注」(关注了中国日报,用户已取消)——候选必须带“无标签图标/排除关注”过滤,点击前核对标签。
**话题页与博文详情结构(2026-11-14 e3 dump)**:
- 话题页:头 `#话题#`+阅读量/讨论量+主持人;Tab 综合/智搜/实时/视频/图片;博文卡锚点 `mblogHeadtitle`(作者行容器)、**`contentTextView` 为自绘 View(text 空,正文不在树)**、`blog_picture_view`/`weibo_image`(图);互动数为文本节点(“转发 105/评论 366/赞 2904”形态)。
- 博文详情:**作者/发布时间/IP 属地为自绘文本(节点树读不到,e3 dump 实测)**——发布时间只能走 **OCR 行内时间 token**(实测合并行“头条新闻 置顶 26-11-14 20:49 头条… 已编辑”,两位年份形);互动数在树(`转发 105` 文本形态);分享锚点 `share_button`(×4,为打赏快捷行微信/朋友圈/QQ/存图——**不是主分享**)/`share_button_rp`/`shareLayout_*`。已落地 `WeiboPostParser`(树+OCR 双源:时间 token 行内匹配、互动数树提取、作者/正文留未知待 OCR 语义定型)。
- **分享面板(e3 定位完成)**:入口=详情页顶栏「⋯」(996,174)→「分享」面板。面板构成:**「更多」=私信转发陷阱(不点)**、外发行(私信和群/超话/微信好友/朋友圈/支付宝好友/QQ/QQ空间/短信/发送邮件,可横滑,不点)、功能行(用此卡片背景/生成长图/查看编辑记录/新鲜事投稿/收藏 + 横滑区:**复制链接**[第3行横滑后左一]/关注/屏蔽/投诉/返回首页)。**复制链接 URL 形态已取证(粘贴读取)**:`https://weibo.com/<用户UID>/<博文ID>`(如 `https://weibo.com/1618051664/5365257549909249`)——完整标准域名、**无查询串无追踪参数、路径即稳定身份**(三源中最优);`WeiboShareLinkParser` 已放行该形态(含 m./www. 变体、query 剥离、UID/博文ID 配对校验),`weibo.cc` 等相似域拒绝。红线:不点外发目标、不点「更多」、不点关注/屏蔽/投诉。
### 2026-11-14 知乎第三轮取证(e2 未核验项闭环)
真机 vivo V1981A、知乎 11.15.0,只读浏览未登录操作。样本留存 `.tmp/source-evidence/zhihu-e3-*.png/xml`(含干净分享面板截图)。e2 四项未核验项全部闭环:
| 对象 | e3 实测结论 |
|---|---|
| 复制链接 URL 形态 | 面板「复制链接」toast“已复制到剪贴板”;本机 shell/服务读剪贴板被拒(“No items”,与 e2“前台读取返回空”一致),改用搜索框粘贴+光标走读取证。实测形态 **`https://www.zhihu.com/question/<数字ID>?share_code=<12位混合令牌>[&<追踪参数>=<值>]`**——域名为 `zhihu.com`(截图边缘曾把 "m" 误读为 "cc",以过渡区截图定论);`share_code` 等查询串整体剥离,路径身份不变。21 位数字 ID 形态已录入解析用例 |
| 问题日志页(真实发布时间) | 分享面板底行左一「问题日志」进入。页面为 WebView(节点大多无 id),但每条目有结构性锚点 **`logitem-<记录ID>`**(撤销按钮 `revert-<ID>`)。条目内含操作文本(添加了问题/编辑了问题/添加了话题/锁定问题编辑…)、`#记录ID` 文本与时间戳,**顺序不固定**。时间形态实测 **`YYYY-MM-DD HH:MM:SS`**(如 `2026-11-14 07:31:31`);**「添加了问题」条目时间 = 问题创建时间**(本例热榜问题创建于当日 07:31)。页脚“最近活动于 09:58”不是发布时间,不得回填。已实现 `ZhihuQuestionLogParser`(9 项用例) |
| 返回路径 | 问题日志→详情→热榜两级 BACK 完整恢复(热榜排序与选中态保持);EXIT 收尾按“日志→详情→热榜”设计 |
| 分享面板截图 | 干净完整版已存(e3-05-menu.png、e3-25-panel2.png):顶行 转发到想法/微信好友/QQ/复制链接/朋友圈(可横滑出 更多/知乎私信/QQ 空间),底行 问题日志/加入浮窗/举报问题;`复制链接` 位于顶行第 4 位(bounds [657,1706][861,1928]),`问题日志` 底行第 1 位([48,2000][246,2182]) |
附带约束:系统分享面板(顶行「更多」)无文本预览,仅应用格子;外发目标(微信/QQ/朋友圈/信息/便签等)不点击。选择菜单“打开/分享”等动作未使用。分享链解析维持“仅 `zhihu.com/question/<id>[/answer/<id>]` 形态放行”,相似域 `zhihu.cc` 明确拒绝(用例钉住)。
### 2026-11-13 只读取证(尚未放行执行) ### 2026-11-13 只读取证(尚未放行执行)
本轮设备为 vivo V1981A,屏幕可操作;今日头条已安装版本为 18.3.0。下列仅说明实际观察,不代表来源链路已接通。截图和节点树保存在工程 `.tmp/source-evidence/`,不纳入仓库。 本轮设备为 vivo V1981A,屏幕可操作;今日头条已安装版本为 18.3.0。下列仅说明实际观察,不代表来源链路已接通。截图和节点树保存在工程 `.tmp/source-evidence/`,不纳入仓库。