feat:M2 微博端到端采集验收——完整通过

This commit is contained in:
2026-11-15 13:19:22 +08:00
parent 1dae7453be
commit cc0f621c53
38 changed files with 3797 additions and 6 deletions
@@ -415,6 +415,10 @@ class HaoRuiAccessibilityService : AccessibilityService() {
// 自有素材草稿回归(debug APK):vivo 真机 activity intent 投递不稳,广播为可靠入口
addAction("com.haorui.app.ACTION_TEST_DRAFT")
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_PUBLISH")
@@ -623,6 +627,19 @@ class HaoRuiAccessibilityService : AccessibilityService() {
val accepted = startDraftSandbox(path, intent.action == "com.haorui.app.ACTION_TEST_DRAFT_INVALID")
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;只读采集:类目词条清单 + 单条内容)
"com.haorui.app.ACTION_TEST_WEIBO" -> {
val categoryId = intent.getStringExtra("categoryId") ?: "hot"
val entryIndex = intent.getStringExtra("entryIndex")?.toIntOrNull() ?: 0
val accepted = startWeiboCollectSandbox(categoryId, entryIndex)
RunLogger.i(TAG, "微博采集沙盒受理=$accepted(广播 ACTION_TEST_WEIBO category=$categoryId entry=$entryIndex)")
}
// 回归测试发布模式切换(草稿/正式;autoPublish 无 UI 开关,走广播)
"com.haorui.app.ACTION_SET_DRAFT" -> setAutoPublish(false)
"com.haorui.app.ACTION_SET_PUBLISH" -> setAutoPublish(true)
@@ -709,6 +726,94 @@ class HaoRuiAccessibilityService : AccessibilityService() {
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 的微博类目采集沙盒(端到端真机验收)。
* 先拉类目词条清单(用户勾选清单的数据源),再采单条内容全链;只读、不发布、不启调度器。
*/
fun startWeiboCollectSandbox(categoryId: String, entryIndex: Int): Boolean = synchronized(stepLifecycleLock) {
if (applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE == 0 ||
!::scheduler.isInitialized || scheduler.isRunning || publisher.isWorking || interactor.isWorking ||
frontGuard.creditNavigating || !foregroundCoordinator.isIdle()) return@synchronized false
val category = com.haorui.app.crossplatform.source.weibo.WeiboHotCategories.ALL
.firstOrNull { it.id == categoryId } ?: return@synchronized false
launchForegroundTask {
val ticket = foregroundCoordinator.tryEnterLegacy("WEIBO-SANDBOX") ?: return@launchForegroundTask
try {
val machine = com.haorui.app.crossplatform.source.weibo.WeiboHotListCollector(
com.haorui.app.crossplatform.source.weibo.WeiboDevicePort(this@HaoRuiAccessibilityService),
)
RunLogger.i(TAG, "微博采集沙盒开始:类目「${category.tabLabel}」")
val list = machine.collectCategoryEntries(category)
RunLogger.i(
TAG,
"微博采集沙盒清单: outcome=${list.outcome} phase=${list.phase} exited=${list.exitedSafely} " +
"条目=${list.entries.size} reason=${list.reason}",
)
list.entries.take(5).forEachIndexed { i, e ->
RunLogger.i(TAG, "微博采集沙盒清单[$i]: ${e.title} heat=${e.heatRaw ?: "未知"} heatMissing=${e.heatMissing}")
}
val result = machine.collectOne(category, entryIndex)
RunLogger.i(
TAG,
"微博采集沙盒结果: outcome=${result.outcome} phase=${result.phase} " +
"exited=${result.exitedSafely} reason=${result.reason}",
)
result.observation?.let { obs ->
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? {
if (currentCrossRunGeneration() == null) return null
@@ -28,6 +28,8 @@ data class CrossPlatformConfig(
val fansGateEnabled: Boolean = false,
val fansMax: Int = 500_000,
val categories: List<String> = DEFAULT_CATEGORIES,
/** 微博热搜类目勾选(WeiboHotCategories.id;空=未选择。旧配置缺字段按空处理保持兼容)。 */
val weiboHotCategories: List<String> = emptyList(),
) {
fun normalized(): CrossPlatformConfig {
val maximumDuration = videoMaxSeconds.coerceIn(20, 4000)
@@ -45,6 +47,7 @@ data class CrossPlatformConfig(
likesMin = likesMin.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(),
weiboHotCategories = weiboHotCategories.map { it.trim() }.filter { it in WEIBO_CATEGORY_IDS }.distinct(),
)
}
@@ -66,6 +69,9 @@ data class CrossPlatformConfig(
"文化历史", "宠物", "家居", "健康科普", "影视娱乐", "游戏", "财经",
)
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 +95,7 @@ object CrossPlatformConfigCodec {
"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(),
"categories" to c.categories.joinToString("|"),
"weibo_hot_categories" to c.weiboHotCategories.joinToString("|"),
).mapKeys { (key, _) -> PREFIX + key }
}
@@ -122,6 +129,8 @@ object CrossPlatformConfigCodec {
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),
categories = value("categories")?.split('|') ?: d.categories,
weiboHotCategories = value("weibo_hot_categories")?.split('|')?.filter { it.isNotBlank() }
?: d.weiboHotCategories,
).normalized()
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
}
}
@@ -59,6 +59,7 @@ import com.haorui.app.crossplatform.model.CrossTaskState
import com.haorui.app.crossplatform.source.SourceRegistry
import com.haorui.app.data.model.AppConfig
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.StatusBanner
import com.haorui.app.ui.components.StatusLevel
@@ -345,7 +346,8 @@ private val topicStates = setOf(CrossTaskState.DISCOVERED, CrossTaskState.FILTER
@OptIn(ExperimentalLayoutApi::class)
@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 kind by rememberSaveable { mutableStateOf("all") }
var selected by remember { mutableStateOf<CrossPublishTask?>(null) }
@@ -365,6 +367,35 @@ fun TopicsScreen(config: AppConfig, tasks: List<CrossPublishTask>, loaded: Boole
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)
when {
loadError != null -> StatusBanner("本地任务读取失败:$loadError", StatusLevel.BAD)
@@ -28,6 +28,7 @@ import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
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
fun CheckRow(
@@ -250,7 +250,7 @@ fun HaoRuiApp(config: AppConfig, onConfigChange: (AppConfig) -> Unit) {
)
}
composable(Routes.TOPICS) {
TopicsScreen(config, crossTasks, crossTasksLoaded, crossTasksError) { nav.navigate(it) }
TopicsScreen(config, crossTasks, crossTasksLoaded, crossTasksError, onConfigChange) { nav.navigate(it) }
}
composable(Routes.TASKS) {
CrossTasksScreen(crossTasks, crossTasksLoaded, crossTasksError) { nav.navigate(it) }