diff --git a/README.md b/README.md index e743525..fe627be 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 拾见 -拾见是独立运行的安卓 APK,以内容类型名称搜索。抖音和小红书可配置浏览或匹配评论并回复,回复支持多条话术、绑定多图和自动回执。小红书图文笔记浏览已通过真机验收,评论回复待真机联调。哔哩哔哩待适配。 +拾见是独立运行的安卓 APK,以内容类型名称搜索。抖音和小红书支持浏览、关键词匹配、多图回复和自动回执,均有连续真机验收记录。哔哩哔哩的普通视频适配已进入真机联调,见[开发进度](docs/开发进度.md)。 ## 界面 @@ -43,7 +43,7 @@ powershell -NoProfile -File ./scripts/verify-apk.ps1 ## 安装和运行 -1. 在手机安装并登录要使用的平台(抖音标准版或小红书)。可直接打开传到手机的拾见 APK 安装,也可开启手机 USB 调试后运行以下命令。 +1. 在手机安装并登录要使用的平台(抖音标准版、小红书或哔哩哔哩标准版)。可直接打开传到手机的拾见 APK 安装,也可开启手机 USB 调试后运行以下命令。 ~~~powershell powershell -NoProfile -File ./scripts/device.ps1 devices -l @@ -54,6 +54,8 @@ powershell -NoProfile -File ./scripts/verify-apk.ps1 3. 在「配置」创建内容类型并填写实际要搜索的名称,例如「大模型充值」。在该类型中添加评论关键字,例如「付款方式」和「账号订阅」,分别维护话术和图片。选择搜索范围、处理方式和任务参数,点「保存配置」。可以先用「仅浏览」模式验证搜索和播放。 选择「小红书」后,可设置单次任务笔记上限和每条笔记回复上限。任务会按内容类型搜索,停留到设定时长后返回结果列表打开下一条笔记。部分 vivo 设备首次会弹出跨应用打开提示,确认是「拾见」打开「小红书」后可选择「始终打开」。若等待超时,返回拾见点「继续任务」。 + + 选择「哔哩哔哩」后,任务按普通视频计数。在 vivo Android 12 的哔哩哔哩 9.21.0 上,同一视频的顶层评论有图片按钮,指向原评论的楼中楼回复框和「插入内容」面板均没有图片选项。拾见会在提交前暂停带图任务,并保留当前视频进度。该设备上的新版回复界面仍待完成实发和自动回执验收。 [哔哩哔哩发图说明](https://www.bilibili.com/opus/752428294212681795) 4. 在「任务」点「开始任务」。保持手机解锁,由拾见打开目标平台。运行期间让目标平台留在前台。在拾见任务页或用通知栏按钮可暂停。登录、验证、页面布局不可识别等中断可在手机处理后点「继续任务」。 5. 发送后,拾见尝试核对原评论下新增的本人回复,匹配正文和同一回复内的全部绑定图片后登记回执。图文自动核对需要 Android 11 或更新版本,图片比对在手机内存中完成。待核对卡片出现「自动核对回复」时,可让拾见再次查找并核对这条回复。若仍显示待核对,可到原评论下核对正文及图片,再选择「确认已发送」或「跳过此回复」。待核对期间会阻止自动重发。 @@ -63,10 +65,10 @@ powershell -NoProfile -File ./scripts/verify-apk.ps1 | 配置 | 说明 | | --- | --- | -| 目标平台 | 抖音标准版 `com.ss.android.ugc.aweme`。小红书 `com.xingin.xhs`。 | +| 目标平台 | 抖音标准版 `com.ss.android.ugc.aweme`、小红书 `com.xingin.xhs`、哔哩哔哩标准版 `tv.danmaku.bili`。 | | 内容类型 | 类型名称直接用于目标平台搜索。「全部类型」按类型顺序尽量均分任务总数,余数优先分给前面的类型。也可只运行一个类型。 | | 评论关键字 | 每个类型可增删改多条关键字。每个关键字对应独立话术库。匹配基于评论正文,兼容全角半角、英文字母大小写和常见中英文空格;重叠时优先选更长的匹配。 | -| 单次任务上限 | 共处理 1–100 项,抖音按视频计数,小红书按笔记计数。浏览完成或扫描后没有可回复的评论均计入进度。 | +| 单次任务上限 | 共处理 1–100 项,抖音和哔哩哔哩按视频计数,小红书按笔记计数。浏览完成或扫描后没有可回复的评论均计入进度。 | | 每条视频或笔记回复上限 | 默认 1 条,可设为 1–100 条。在匹配回复模式下,已确认发送的回复计入上限。达标、评论列表到末尾或扫描范围内没有更多匹配时,浏览下一条。 | | 观看时长 | 1–300 秒的闭区间,逐视频或笔记取样,默认 5–12 秒。 | | 动作间隔 | 150–30,000 毫秒的闭区间,默认 600–1,800 毫秒。评论滑动在列表内变化起点、距离、轨迹、时长和停留时间,每条内容最多滑动 12 次并在每屏重新读取。 | @@ -94,7 +96,7 @@ powershell -NoProfile -File ./scripts/verify-apk.ps1 | --- | --- | | app/src/main/res/layout、MainActivity.kt | 页面结构、参数控件和任务操作。 | | app/src/main/java/com/jieliu/app/AutomationService.kt | 无障碍服务连接、任务生命周期、暂停通知。 | -| app/src/main/java/com/jieliu/app/platform | 平台接口、注册表、节点和手势操作、抖音和小红书适配器。 | +| app/src/main/java/com/jieliu/app/platform | 平台接口、注册表、节点和手势操作,以及抖音、小红书、哔哩哔哩适配器。 | | app/src/main/java/com/jieliu/app/task | 内容类型调度、评论关键字匹配、话术轮换和恢复规则。 | | app/src/main/java/com/jieliu/app/data | 配置、图片、发送检查点和运行日志。 | | docs/技术调研.md | 前期技术选型、通用组件评估和设计依据。 | diff --git a/app/build.gradle.kts b/app/build.gradle.kts index e85e22b..9738068 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -13,8 +13,8 @@ android { applicationId = "com.jieliu.app" minSdk = 26 targetSdk = 35 - versionCode = 23 - versionName = "0.1.22" + versionCode = 25 + versionName = "0.1.24" } compileOptions { diff --git a/app/src/main/java/com/jieliu/app/platform/AccessibleUi.kt b/app/src/main/java/com/jieliu/app/platform/AccessibleUi.kt index bc3703b..0d8fd72 100644 --- a/app/src/main/java/com/jieliu/app/platform/AccessibleUi.kt +++ b/app/src/main/java/com/jieliu/app/platform/AccessibleUi.kt @@ -63,10 +63,12 @@ internal class AccessibleUi( await(12_000) { inspect { true } } ?: throw PlatformException("等待${appName}进入前台超时") } - fun inspect(action: (UiPage) -> T): T? { + fun inspect(action: (UiPage) -> T): T? = inspect(false, action) + + fun inspect(traverseHiddenParents: Boolean, action: (UiPage) -> T): T? { checkCancelled() val root = targetRoot() ?: return null - return capture(root).use { page -> + return capture(root, traverseHiddenParents).use { page -> checkPage?.invoke(page) action(page) } @@ -247,7 +249,7 @@ internal class AccessibleUi( } } - private fun capture(root: AccessibilityNodeInfo): UiPage { + private fun capture(root: AccessibilityNodeInfo, traverseHiddenParents: Boolean = false): UiPage { val pending = ArrayDeque>() val references = mutableListOf() val nodes = mutableListOf() @@ -256,10 +258,13 @@ internal class AccessibleUi( try { val bounds = Rect().also { root.getBoundsInScreen(it) } val deadline = SystemClock.elapsedRealtime() + 1_800 + var complete = true while (pending.isNotEmpty() && SystemClock.elapsedRealtime() < deadline) { checkCancelled() val (node, parent, depth) = pending.removeFirst() - if (node !== root && (!node.isVisibleToUser || node.packageName?.toString() != packageName)) continue + if (node !== root && (node.packageName?.toString() != packageName || + !traverseHiddenParents && !node.isVisibleToUser) + ) continue var ancestor = parent if (node.isVisibleToUser) { val nodeBounds = Rect().also { node.getBoundsInScreen(it) } @@ -269,15 +274,25 @@ internal class AccessibleUi( ancestor = captured } } - for (index in 0 until node.childCount.coerceAtMost(450 - references.size)) { + val childCount = node.childCount + val limit = childCount.coerceAtMost(450 - references.size) + if (limit < childCount) complete = false + for (index in 0 until limit) { checkCancelled() - if (SystemClock.elapsedRealtime() >= deadline) break - val child = node.getChild(index) ?: continue + if (SystemClock.elapsedRealtime() >= deadline) { + complete = false + break + } + val child = node.getChild(index) + if (child == null) { + complete = false + continue + } references.add(child) pending.add(Triple(child, ancestor, depth + 1)) } } - return UiPage(root.windowId, bounds, nodes, references) + return UiPage(root.windowId, bounds, nodes, references, complete && pending.isEmpty()) } catch (error: Throwable) { references.forEach { it.recycle() } throw error @@ -419,6 +434,7 @@ internal class UiPage( val bounds: Rect, val nodes: List, private val references: MutableList, + val complete: Boolean, ) : Closeable { fun x(fraction: Float): Int = bounds.left + (bounds.width() * fraction).roundToInt() fun y(fraction: Float): Int = bounds.top + (bounds.height() * fraction).roundToInt() @@ -476,6 +492,7 @@ internal class UiNode( val editable: Boolean = !node.isPassword && (node.isEditable || supports(AccessibilityNodeInfo.ACTION_SET_TEXT)) val focused: Boolean = node.isFocused val selected: Boolean = node.isSelected + val checked: Boolean? = node.isChecked.takeIf { node.isCheckable } val showingHint: Boolean = node.isShowingHintText val scrollable: Boolean = node.isScrollable val horizontalItemCount: Int? diff --git a/app/src/main/java/com/jieliu/app/platform/BilibiliAdapter.kt b/app/src/main/java/com/jieliu/app/platform/BilibiliAdapter.kt new file mode 100644 index 0000000..ccc6860 --- /dev/null +++ b/app/src/main/java/com/jieliu/app/platform/BilibiliAdapter.kt @@ -0,0 +1,79 @@ +package com.jieliu.app.platform + +import com.jieliu.app.data.PhotoLibrary +import com.jieliu.app.task.PendingComment +import com.jieliu.app.task.TemplatePhoto + +internal class BilibiliAdapter( + spec: PlatformSpec, + private val ui: AccessibleUi, + photos: PhotoLibrary, + diagnostic: (String) -> Unit, +) : PlatformAdapter { + private val navigation = BilibiliVideoNavigation(spec, ui) + private val comments = BilibiliComments(ui, navigation) + private val replies = BilibiliReplies(ui, comments, photos, diagnostic) + + override fun launch() = navigation.launch() + + override fun search(keyword: String): VideoContext { + closeComments() + return navigation.search(keyword) + } + + override fun currentVideo(): VideoContext = navigation.currentVideo() + + override fun nextVideo(previous: VideoContext): VideoContext { + closeComments() + return navigation.nextVideo(previous) + } + + override fun openComments(expected: VideoContext): List = + comments.open(expected).map(CommentTarget::text) + + override fun scanComments(): List { + comments.leaveThread() + return comments.scan() + } + + override fun scrollComments(): Boolean = comments.scroll() + + override fun prepareReply(target: CommentTarget, expectedText: String, requiresImages: Boolean): Boolean = + replies.prepare(target, expectedText, requiresImages) + + override fun hasPreparedReplyBaseline(targetKey: String, text: String): Boolean = + replies.hasPreparedBaseline(targetKey, text) + + override fun publishComment(text: String, beforeClick: () -> Unit): CommentPublishResult = + publishPhotoComment(text, emptyList(), beforeClick) + + override fun publishPhotoComment(text: String, photos: List, beforeClick: () -> Unit): CommentPublishResult { + val target = replies.preparedTarget(text) + var armedAt = 0L + val clicked = replies.submit(target, text, photos) { + armedAt = System.currentTimeMillis() + beforeClick() + } + if (!clicked || armedAt == 0L) return CommentPublishResult.UNCERTAIN + return replies.confirm(target.key, target.author, text, photos, armedAt) + } + + override fun confirmPendingReplyInPlace(video: VideoContext, pending: PendingComment): CommentPublishResult? { + if (pending.videoKey != video.key || !comments.isOpenFor(video)) return null + return confirmPendingReply(video, pending) + } + + override fun confirmPendingReply(video: VideoContext, pending: PendingComment): CommentPublishResult { + val targetKey = pending.targetKey ?: return CommentPublishResult.UNCERTAIN + val author = pending.targetAuthor ?: return CommentPublishResult.UNCERTAIN + val armedAt = pending.armedAtEpochMs ?: return CommentPublishResult.UNCERTAIN + if (video.key != pending.videoKey || !comments.isOpenFor(video)) return CommentPublishResult.UNCERTAIN + return replies.confirm(targetKey, author, pending.text, pending.photos, armedAt) + } + + override fun closeComments() { + if (replies.hasUnsettledEditor()) throw PlatformException("哔哩哔哩回复框仍打开,请核对草稿后继续") + replies.reset() + comments.close() + } +} diff --git a/app/src/main/java/com/jieliu/app/platform/BilibiliComments.kt b/app/src/main/java/com/jieliu/app/platform/BilibiliComments.kt new file mode 100644 index 0000000..f8b6659 --- /dev/null +++ b/app/src/main/java/com/jieliu/app/platform/BilibiliComments.kt @@ -0,0 +1,363 @@ +package com.jieliu.app.platform + +import android.graphics.Rect +import android.view.accessibility.AccessibilityNodeInfo +import java.io.Closeable +import java.security.MessageDigest + +internal class BilibiliComments( + private val ui: AccessibleUi, + private val navigation: BilibiliVideoNavigation, +) { + internal data class Row( + val target: CommentTarget, + val container: UiNode, + val body: UiNode, + val reply: UiNode, + val more: UiNode?, + val time: String?, + val images: List?, + val own: Boolean, + val threadEntry: UiNode?, + val emptyThread: Boolean, + ) + + internal data class ThreadRows(val original: Row, val replies: List, val complete: Boolean) + + private data class MainScope(val video: VideoContext, val window: Int, val list: UiNodeSource) : Closeable { + override fun close() = list.close() + } + + private data class ThreadScope(val target: CommentTarget, val window: Int, val list: UiNodeSource) : Closeable { + override fun close() = list.close() + } + + private data class MainTransition(val window: Int, val tab: UiNodeSource) : Closeable { + override fun close() = tab.close() + } + + private var main: MainScope? = null + private var thread: ThreadScope? = null + + fun isOpenFor(video: VideoContext): Boolean = main?.video == video + + fun open(video: VideoContext): List { + check(main == null) { "请先退出上一个哔哩哔哩评论区" } + ui.pace() + val transition = ui.inspect { page -> + if (!navigation.matchesVideo(page, video) || page.hasEditor()) return@inspect null + val tabs = page.videoTabs() ?: return@inspect null + val tab = tabs.second + val anchor = MainTransition(page.windowId, tab.retainSource()) + try { + if (page.commentList() != null || navigation.commentEntry(page, video)?.let { ui.click(it) } == true) { + anchor + } else { + anchor.close() + null + } + } catch (error: Throwable) { + anchor.close() + throw error + } + } ?: throw PlatformException("未能核对哔哩哔哩视频和原生评论标签") + transition.use { proof -> + main = ui.await(7_000) { + ui.inspect { page -> + if (page.windowId != proof.window || page.hasEditor()) return@inspect null + val tab = page.videoTabs()?.second ?: return@inspect null + if (!tab.hasSource(proof.tab)) return@inspect null + page.commentList()?.takeIf { page.detailHeader() == null } + ?.let { MainScope(video, page.windowId, it.retainSource()) } + } + } + } + if (main == null) throw PlatformException("哔哩哔哩未显示可核对的评论列表") + return scan() + } + + fun scan(): List = ui.await(3_000) { + ui.inspect { page -> + val scope = main ?: return@inspect null + val list = mainList(page, scope) ?: return@inspect null + page.rows(list, scope.video.key).filterNot(Row::own).map(Row::target) + } + } ?: throw PlatformException("哔哩哔哩评论区已变化") + + fun scroll(): Boolean { + val scope = main ?: return false + ui.pace() + val previous = ui.inspect { page -> + val list = mainList(page, scope) ?: return@inspect null + val positions = page.rows(list, scope.video.key).associate { it.target.key to it.container.bounds.top } + positions.takeIf { list.scrollable && ui.scrollUpInside(list.bounds) } + } ?: return false + return ui.await(2_500) { + ui.inspect { page -> + val list = mainList(page, scope) ?: return@inspect null + val positions = page.rows(list, scope.video.key).associate { it.target.key to it.container.bounds.top } + true.takeIf { positions.isNotEmpty() && positions != previous } + } + } == true + } + + fun readOriginal(target: CommentTarget, action: (UiPage, Row) -> T): T? = ui.inspect { page -> + if (!page.complete) return@inspect null + if (thread != null) { + readLiveThread(page, target)?.original?.let { action(page, it) } + } else { + val scope = main ?: return@inspect null + val list = mainList(page, scope) ?: return@inspect null + page.rows(list, scope.video.key).singleOrNull { it.target == target }?.let { action(page, it) } + } + } + + fun isComposeOriginal(target: CommentTarget): Boolean = readOriginal(target) { page, row -> + BilibiliComposeComments.list(page)?.let(row.container::isDescendantOf) == true + } == true + + fun readThread(target: CommentTarget, action: (UiPage, ThreadRows) -> T): T? = ui.inspect { page -> + readLiveThread(page, target)?.let { action(page, it) } + } + + fun threadTarget(key: String, author: String): CommentTarget? { + val selected = thread?.target + if (selected?.key == key && selected.author == author) return selected + repeat(13) { index -> + val scope = main ?: return null + val candidate = ui.inspect { page -> + val list = mainList(page, scope) ?: return@inspect null + page.rows(list, scope.video.key).singleOrNull { it.target.key == key && it.target.author == author }?.target + } + if (candidate != null) return candidate + if (index == 12 || !scroll()) return null + } + return null + } + + fun enterThread(target: CommentTarget): Boolean { + if (thread?.target == target) return readThread(target) { _, _ -> true } == true + if (thread != null) return false + val opened = readOriginal(target) { _, row -> row.threadEntry?.let { ui.click(it) } == true } == true + if (!opened) return false + val scope = main ?: return false + var movedToRoot = false + thread = ui.await(5_000) { + ui.inspect { page -> + if (page.detailHeader() == null || page.hasEditor()) return@inspect null + val list = page.detailList() ?: return@inspect null + val original = page.threadRows(list, scope.video.key, target)?.original + if (original == null) { + val backward = AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD + if (!movedToRoot && list.supports(backward)) { + movedToRoot = true + list.act(backward) + } + return@inspect null + } + ThreadScope(original.target, page.windowId, list.retainSource()) + } + } + if (thread == null) throw PlatformException("未能核对哔哩哔哩的原评论和回复详情") + return true + } + + fun leaveThread() { + val scope = main ?: return + val opened = thread ?: return + val closed = ui.await(4_000) { + ui.inspect { page -> + if (page.windowId != opened.window || page.hasEditor() || page.detailList()?.hasSource(opened.list) != true) return@inspect null + val close = BilibiliComposeComments.detail(page)?.close ?: page.detailHeader()?.let { header -> + page.nodes.singleOrNull { it.resourceId in setOf("close", "back") && it.isDescendantOf(header) && it.biliClick() } + } + close?.let { ui.click(it) } + } + } == true + if (!closed || ui.await(4_000) { ui.inspect { page -> true.takeIf { mainList(page, scope) != null } } } != true) { + throw PlatformException("未能返回哔哩哔哩原视频评论区") + } + opened.close() + thread = null + } + + fun close() { + val scope = main ?: return + leaveThread() + val closed = ui.inspect { page -> + if (mainList(page, scope) == null) return@inspect false + navigation.introductionEntry(page, scope.video)?.let { ui.click(it) } == true + } == true + if (!closed || ui.await(5_000) { + ui.inspect { page -> true.takeIf { navigation.matchesVideo(page, scope.video) } } + } != true) throw PlatformException("未能退出哔哩哔哩评论标签") + scope.close() + main = null + } + + private fun readLiveThread(page: UiPage, target: CommentTarget): ThreadRows? { + val selected = thread ?: return null + val scope = main ?: return null + if (!page.complete || selected.target != target || selected.window != page.windowId || page.hasEditor()) return null + val list = page.detailList()?.takeIf { it.hasSource(selected.list) } ?: return null + return page.threadRows(list, scope.video.key, target) + } + + private fun mainList(page: UiPage, scope: MainScope): UiNode? { + if (page.windowId != scope.window || page.detailHeader() != null || page.hasEditor() || page.videoTabs() == null) return null + return page.commentList()?.takeIf { it.hasSource(scope.list) } + } + + private fun UiPage.videoTabs(): Pair? { + val info = nodes.singleOrNull { it.resourceId == "tab_title" && it.labels() == listOf("简介") && + it.bounds.centerY() in y(.20f)..y(.70f) } + ?: return null + val comments = nodes.singleOrNull { node -> node.resourceId == "tab_title" && node.labels().any { commentTab.matches(it) } && + node.bounds.centerX() > info.bounds.centerX() && kotlin.math.abs(node.bounds.centerY() - info.bounds.centerY()) <= info.bounds.height() } + ?: return null + val strip = generateSequence(info.directParent(), UiNode::directParent).take(5).firstOrNull { + it.resourceId in setOf("tabs", "comment_tab_layout") && comments.isDescendantOf(it) + } ?: return null + return (info to comments).takeIf { strip.bounds.contains(info.bounds) && strip.bounds.contains(comments.bounds) } + } + + private fun UiPage.commentList(): UiNode? = BilibiliComposeComments.list(this) ?: nodes.singleOrNull { + it.resourceId in setOf("cmt3_recycler", "recycler") && it.bounds.width() >= bounds.width() * .72 && bounds.contains(it.bounds) && + (it.resourceId == "cmt3_recycler" || + generateSequence(it.directParent(), UiNode::directParent).take(4).any { parent -> parent.resourceId == "main_container" }) + } + + private fun UiPage.detailHeader(): UiNode? = BilibiliComposeComments.detail(this)?.header ?: nodes.singleOrNull { header -> + header.resourceId in setOf("cmt3_page_title_container", "header") && nodes.any { it.isDescendantOf(header) && + it.resourceId in setOf("title", "desc", "comment_title") && it.labels() == listOf("评论详情") } + } + + private fun UiPage.detailList(): UiNode? { + BilibiliComposeComments.detail(this)?.let { return it.list } + val header = detailHeader() ?: return null + val panel = header.directParent() ?: return null + return nodes.singleOrNull { it.resourceId in setOf("cmt3_recycler", "recycler") && it.isDescendantOf(panel) && + it.bounds.top >= header.bounds.bottom && it.bounds.width() >= panel.bounds.width() * .72 && bounds.contains(it.bounds) } + } + + private fun UiPage.hasEditor(): Boolean = nodes.any { it.editable && it.focused } + + private fun UiPage.rows(list: UiNode, videoKey: String): List { + val viewport = Rect(list.bounds) + val parsed = if (BilibiliComposeComments.isList(this, list)) { + BilibiliComposeComments.rows(this, list) { author, body -> + CommentTarget(commentKey(videoKey, author, body), body, author) + } + } else nodes.filter { it.directParent() === list && viewport.contains(it.bounds) } + .mapNotNull { row(it, videoKey) } + val counts = parsed.groupingBy { it.target.key }.eachCount() + return parsed.filter { counts[it.target.key] == 1 } + } + + private fun UiPage.row(container: UiNode, videoKey: String): Row? { + val root = if (container.resourceId == "comment_item_root_layout") container else nodes.singleOrNull { + it.resourceId == "comment_item_root_layout" && it.isDescendantOf(container) && container.bounds.contains(it.bounds) + } + if (root != null) return modernRow(root, videoKey) + val members = members(container) + val header = members.singleOrNull { it.resourceId == "item_include_header" } ?: return null + val user = members.singleOrNull { it.isDescendantOf(header) && it.resourceId == "user_name" && it.text.isNotBlank() } + ?: return null + val body = members.singleOrNull { it.resourceId == "primary_message" && it.text.isNotBlank() && !it.editable } + ?: return null + val actions = members.singleOrNull { it.resourceId == "item_include_actions" } ?: return null + val reply = members.singleOrNull { it.isDescendantOf(actions) && it.resourceId == "reply_button" && + it.labels().contains("回复") && it.biliClick() } ?: return null + if (body.bounds.top < user.bounds.bottom || actions.bounds.top < body.bounds.bottom) return null + val time = members.singleOrNull { it.isDescendantOf(actions) && it.resourceId == "description" }?.text + val more = members.singleOrNull { it.isDescendantOf(actions) && it.resourceId == "more_button" && it.biliClick() } + val countActions = members.filter { node -> node.labels().any { (BilibiliLabels.replyCount(it) ?: 0) > 0 } } + .mapNotNull { it.nearbyClick()?.takeIf { action -> action !== container && action.isDescendantOf(container) } }.distinct() + val own = members.any { it.isDescendantOf(header) && it !== user && !it.clickable && it.text in ownLabels } + val target = CommentTarget(commentKey(videoKey, user.text, body.text), body.text, user.text) + return Row(target, container, body, reply, more, time, commentPhotos(members, body, actions.bounds.top), own, + countActions.singleOrNull(), members.any { it.labels().any { label -> BilibiliLabels.replyCount(label) == 0 } }) + } + + private fun UiPage.modernRow(root: UiNode, videoKey: String): Row? { + val all = members(root) + val preview = all.singleOrNull { it.resourceId == "secondary" } + ?: all.singleOrNull { it.resourceId == "replies_recycle_view" } + val members = all.filterNot { preview != null && (it === preview || it.isDescendantOf(preview)) } + val header = members.singleOrNull { it.resourceId == "name_layout" } ?: return null + val user = members.singleOrNull { it.resourceId == "name" && it.isDescendantOf(header) && it.text.isNotBlank() } ?: return null + val body = members.singleOrNull { it.resourceId == "comment_message" && it.text.isNotBlank() && !it.editable } ?: return null + val reply = members.singleOrNull { it.resourceId == "action4" && it.labels().any { label -> label in replyLabels } && it.biliClick() } + ?: return null + if (body.bounds.top < user.bounds.bottom || reply.bounds.top < body.bounds.bottom) return null + val time = members.firstOrNull { it.resourceId == "release_time" && it.text.isNotBlank() }?.text + ?: members.singleOrNull { it.resourceId == "time" && it.text.isNotBlank() }?.text + val more = members.singleOrNull { it.resourceId == "menu_img" && it.biliClick() } + val entry = members.singleOrNull { it.resourceId == "action5" && it.labels().contains("查看对话,按钮") && it.biliClick() } + ?: preview?.let { group -> + all.filter { it.resourceId == "comment_count" && it.isDescendantOf(group) && + it.labels().any { label -> (BilibiliLabels.replyCount(label) ?: 0) > 0 } } + .mapNotNull { label -> + generateSequence(label, UiNode::directParent).take(5).takeWhile { it !== group } + .firstOrNull { it.biliClick() && it.isDescendantOf(group) && it.bounds.contains(label.bounds) } + }.distinct().singleOrNull() + } + val own = members.any { (it.isDescendantOf(header) || it.resourceId == "label_container") && + it !== user && !it.clickable && it.text in ownLabels } + val target = CommentTarget(commentKey(videoKey, user.text, body.text), body.text, user.text) + return Row(target, root, body, reply, more, time, commentPhotos(members, body, reply.bounds.top), own, entry, + entry == null && preview == null && all.none { it.labels().any { label -> (BilibiliLabels.replyCount(label) ?: 0) > 0 } }) + } + + private fun UiPage.members(container: UiNode): List = nodes.filter { + it.isDescendantOf(container) && container.bounds.contains(it.bounds) + } + + private fun commentPhotos(members: List, body: UiNode, actionTop: Int): List? { + val inside = members.filter { it.bounds.top >= body.bounds.bottom && it.bounds.bottom <= actionTop } + val imageSet = members.filter { it.resourceId in setOf("image_set", "image_set_layout") } + if (imageSet.isEmpty()) return emptyList().takeIf { inside.none { it.resourceId in photoIds } } + val group = imageSet.singleOrNull() ?: return null + if (members.any { it.isDescendantOf(group) && it.labels().any { label -> label == "展开" || label == "查看全部图片" } }) return null + val minThumbnail = body.bounds.width() * .075 + return inside.filter { it.isDescendantOf(group) && it.biliClick() && + it.bounds.width() >= minThumbnail && it.bounds.height() >= minThumbnail && + (it.resourceId in photoIds || it.className.endsWith("ImageView")) } + .takeIf { it.isNotEmpty() } + ?.sortedWith(compareBy({ it.bounds.top }, { it.bounds.left })) + } + + private fun UiPage.threadRows(list: UiNode, videoKey: String, target: CommentTarget): ThreadRows? { + val rows = rows(list, videoKey) + val original = rows.firstOrNull()?.takeIf { it.target == target } ?: return null + val children = nodes.filter { it.directParent() === list && list.bounds.contains(it.bounds) } + val complete = if (BilibiliComposeComments.isList(this, list)) { + BilibiliComposeComments.completeThread(this, list, rows.size - 1) + } else !list.supports(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD) && + !list.supports(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD) && children.none { child -> + val members = members(child) + child.labels().any(::blocksThreadCompletion) || members.any { it.labels().any(::blocksThreadCompletion) } || + members.any { it.resourceId in setOf("item_include_header", "name_layout") } && row(child, videoKey) == null + } + return ThreadRows(original, rows.drop(1), complete) + } + + private fun blocksThreadCompletion(label: String): Boolean = + label in setOf("展开更多评论", "查看更多回复", "加载中", "加载失败", "点击重试") + + private fun commentKey(videoKey: String, name: String, body: String): String = + MessageDigest.getInstance("SHA-256").digest("$videoKey\u0000$name\u0000$body".toByteArray(Charsets.UTF_8)) + .joinToString("") { "%02x".format(it) } + + private companion object { + val commentTab = Regex("评论(?:\\s*\\d+(?:\\.\\d+)?[万亿]?)?") + val ownLabels = setOf("我", "我发布的评论", "我发布的回复") + val replyLabels = setOf("回复", "回复,按钮") + val photoIds = setOf("comment_image", "image_item", "picture") + } +} + +internal fun UiNode.biliClick(): Boolean = enabled && supports(AccessibilityNodeInfo.ACTION_CLICK) + +internal fun UiNode.nearbyClick(): UiNode? = generateSequence(this, UiNode::directParent).take(3) + .firstOrNull { it.biliClick() && it.bounds.contains(bounds) } diff --git a/app/src/main/java/com/jieliu/app/platform/BilibiliComposeComments.kt b/app/src/main/java/com/jieliu/app/platform/BilibiliComposeComments.kt new file mode 100644 index 0000000..decfe67 --- /dev/null +++ b/app/src/main/java/com/jieliu/app/platform/BilibiliComposeComments.kt @@ -0,0 +1,186 @@ +package com.jieliu.app.platform + +import android.graphics.Rect + +/** Virtual accessibility nodes observed in the Bilibili 9.21.0 video comment tab and reply detail. */ +internal object BilibiliComposeComments { + internal data class Detail(val header: UiNode, val list: UiNode, val close: UiNode) + + private data class Action(val node: UiNode, val label: UiNode) + private data class Identity(val author: UiNode, val body: UiNode) + + fun list(page: UiPage): UiNode? { + val container = page.nodes.singleOrNull { node -> + node.resourceId == "comment_container" && node.bounds.width() >= page.bounds.width() * .75 && + page.bounds.contains(node.bounds) + } ?: return null + val compose = page.children(container).singleOrNull { it.className == COMPOSE_VIEW } ?: return null + return composeList(page, compose) + } + + fun detail(page: UiPage): Detail? { + val pager = page.nodes.singleOrNull { it.resourceId == "fl_tab_pager_container" } ?: return null + val heading = page.nodes.singleOrNull { + it.className == TEXT_VIEW && it.labels() == listOf("评论详情") && it.isDescendantOf(pager) + } ?: return null + val header = heading.directParent() ?: return null + val panel = header.directParent() ?: return null + val compose = generateSequence(panel.directParent(), UiNode::directParent).take(3) + .firstOrNull { it.className == COMPOSE_VIEW && it.isDescendantOf(pager) } ?: return null + if (header.className != VIEW || header.bounds.width() < compose.bounds.width() * .90 || + !header.bounds.contains(heading.bounds) || !compose.bounds.contains(header.bounds) + ) return null + val list = composeList(page, compose)?.takeIf { + it.bounds.top >= header.bounds.bottom && it.directParent()?.directParent() === panel + } ?: return null + val close = page.children(header).singleOrNull { + it.className == VIEW && it.biliClick() && header.bounds.contains(it.bounds) && + it.bounds.left >= header.bounds.centerX() && it.bounds.right > header.bounds.right - header.bounds.width() * .1 && + it.bounds.width() <= header.bounds.width() * .20 && it.bounds.top <= heading.bounds.centerY() && + it.bounds.bottom > heading.bounds.centerY() && it.labels().all { label -> label in CLOSE_LABELS } + } ?: return null + return Detail(header, list, close) + } + + fun isList(page: UiPage, list: UiNode): Boolean = list(page) === list || detail(page)?.list === list + + fun rows( + page: UiPage, + list: UiNode, + target: (author: String, body: String) -> CommentTarget, + ): List { + if (!isList(page, list)) return emptyList() + val siblings = page.children(list) + val parsed = siblings.mapIndexedNotNull { index, row -> + val identity = rowIdentity(page, list, row) ?: return@mapIndexedNotNull null + val author = identity.author.text + val body = identity.body + val reply = footerAction(page, list, row, REPLY_LABELS) ?: return@mapIndexedNotNull null + val more = footerAction(page, list, row, MORE_LABELS) ?: return@mapIndexedNotNull null + if (!sameLine(reply.label.bounds, more.label.bounds) || more.label.bounds.left <= reply.label.bounds.right || + reply.label.bounds.centerY() <= body.bounds.bottom || reply.label.bounds.height() < identity.author.bounds.height() * .20 + ) return@mapIndexedNotNull null + val time = footerTime(page, row, reply.label) ?: return@mapIndexedNotNull null + val next = siblings.getOrNull(index + 1) + val threadEntry = next?.let { threadEntry(page, list, more.label.bounds, it) } + val emptyThread = threadEntry == null && next != null && page.complete && + rowIdentity(page, list, next) != null && next.bounds.top >= more.label.bounds.bottom + val own = page.children(row).any { + it !== identity.author && !it.clickable && it.bounds.left >= identity.author.bounds.right && + sameLine(it.bounds, identity.author.bounds) && it.labels().any(OWN_LABELS::contains) + } + BilibiliComments.Row( + target(author, body.description), row, body, reply.node, more.node, time, + photos(page, row, body.bounds, reply.label.bounds), own, threadEntry, emptyThread, + ) + } + val counts = parsed.groupingBy { it.target.key }.eachCount() + return parsed.filter { counts[it.target.key] == 1 } + } + + /** The native count must account for every visible nested row before proving a full thread. */ + fun completeThread(page: UiPage, list: UiNode, nestedCount: Int): Boolean { + if (!page.complete || detail(page)?.list !== list) return false + val counts = page.children(list).flatMap { page.children(it) }.mapNotNull { marker -> + if (marker.className != TEXT_VIEW || marker.clickable || !list.bounds.contains(marker.bounds)) return@mapNotNull null + THREAD_TOTAL.matchEntire(marker.text)?.groupValues?.get(1)?.toIntOrNull() + } + if (counts.singleOrNull() != nestedCount) return false + return page.children(list).count { rowIdentity(page, list, it) != null } == nestedCount + 1 + } + + private fun composeList(page: UiPage, compose: UiNode): UiNode? = + page.nodes.singleOrNull { + it.className == VIEW && it.resourceId.isEmpty() && it.scrollable && !it.clickable && + it.isDescendantOf(compose) && it.depth - compose.depth in 2..4 && + compose.bounds.contains(it.bounds) && it.bounds.width() >= compose.bounds.width() * .90 && + it.bounds.height() >= compose.bounds.height() * .45 + } + + private fun rowIdentity(page: UiPage, list: UiNode, row: UiNode): Identity? { + if (row.className != VIEW || row.directParent() !== list || !row.biliClick() || row.editable || + row.bounds.width() < list.bounds.width() * .90 || !list.bounds.contains(row.bounds) + ) return null + val children = page.children(row) + val author = children.singleOrNull { + it.className == BUTTON && it.biliClick() && row.bounds.contains(it.bounds) && + it.text.isNotBlank() && it.text == it.description + } ?: return null + val body = children.singleOrNull { + it.className == VIEW && !it.clickable && !it.editable && it.text.isEmpty() && it.description.isNotBlank() && + it.bounds.top >= author.bounds.bottom && it.bounds.left <= author.bounds.centerX() && + it.bounds.width() >= row.bounds.width() * .50 && row.bounds.contains(it.bounds) + } ?: return null + return Identity(author, body) + } + + private fun footerAction(page: UiPage, list: UiNode, row: UiNode, labels: Set): Action? = + page.children(row).filter { it.className == VIEW && it.biliClick() && !it.editable } + .mapNotNull { action -> + val label = page.children(action).singleOrNull { + it.className == VIEW && !it.clickable && it.description in labels && + action.bounds.contains(it.bounds) && row.bounds.contains(it.bounds) && list.bounds.contains(it.bounds) + } ?: return@mapNotNull null + Action(action, label) + }.singleOrNull() + + private fun footerTime(page: UiPage, row: UiNode, reply: UiNode): String? = + page.children(row).filter { it.className == VIEW && !it.biliClick() && it.bounds.left < reply.bounds.left } + .mapNotNull { group -> + val parts = page.children(group) + val label = parts.singleOrNull { + it.className == TEXT_VIEW && !it.clickable && it.text.isNotBlank() && FOOTER_TIME.containsMatchIn(it.text) && + group.bounds.contains(it.bounds) && row.bounds.contains(it.bounds) && + sameLine(it.bounds, reply.bounds) && it.bounds.right <= reply.bounds.left + } ?: return@mapNotNull null + label.text.takeIf { parts.any { it.className == VIEW && !it.clickable && it.description == label.text } } + }.singleOrNull() + + private fun threadEntry(page: UiPage, list: UiNode, footer: Rect, sibling: UiNode): UiNode? { + if (sibling.className != VIEW || sibling.clickable || !list.bounds.contains(sibling.bounds) || + sibling.bounds.bottom <= footer.bottom || sibling.bounds.top < footer.top || + sibling.bounds.width() >= list.bounds.width() * .90 + ) return null + val action = page.children(sibling).singleOrNull { + it.className == VIEW && it.biliClick() && sibling.bounds.contains(it.bounds) + } ?: return null + val markers = page.children(action) + val text = markers.singleOrNull { + it.className == TEXT_VIEW && !it.clickable && action.bounds.contains(it.bounds) && + it.bounds.top >= footer.bottom && it.text.startsWith("共") && (BilibiliLabels.replyCount(it.text) ?: 0) > 0 + } ?: return null + return action.takeIf { + markers.count { marker -> marker.className == VIEW && !marker.clickable && + marker.description == text.text && action.bounds.contains(marker.bounds) } == 1 + } + } + + private fun photos(page: UiPage, row: UiNode, body: Rect, footer: Rect): List? { + // An unlabeled content action here can also be a media card or inserted content. + val attachment = page.children(row).any { + it.className == VIEW && it.biliClick() && it.bounds.centerY() in body.bottom until footer.top && + it.bounds.left >= body.left && row.bounds.contains(it.bounds) + } + return emptyList().takeUnless { attachment } + } + + private fun sameLine(first: Rect, second: Rect): Boolean = + first.top <= second.centerY() && second.centerY() < first.bottom && + second.top <= first.centerY() && first.centerY() < second.bottom + + private fun UiPage.children(parent: UiNode): List = nodes.filter { it.directParent() === parent } + + private const val COMPOSE_VIEW = "androidx.compose.ui.platform.ComposeView" + private const val VIEW = "android.view.View" + private const val TEXT_VIEW = "android.widget.TextView" + private const val BUTTON = "android.widget.Button" + private val CLOSE_LABELS = setOf("关闭", "返回", "关闭评论详情") + private val MORE_LABELS = setOf("更多", "更多操作", "更多操作,按钮") + private val REPLY_LABELS = setOf("回复", "回复,按钮") + private val OWN_LABELS = setOf("我", "我发布的评论", "我发布的回复") + private val THREAD_TOTAL = Regex("相关回复共\\s*(\\d+)\\s*条") + private val FOOTER_TIME = Regex( + "^(?:刚刚|昨天|前天|\\d+\\s*(?:秒|分钟|小时|天|周|月|年)前|" + + "(?:\\d{4}年)?\\d{1,2}月\\d{1,2}日|(?:\\d{4}[-/.])?\\d{1,2}[-/.]\\d{1,2})(?:$|[^\\d])", + ) +} diff --git a/app/src/main/java/com/jieliu/app/platform/BilibiliLabels.kt b/app/src/main/java/com/jieliu/app/platform/BilibiliLabels.kt new file mode 100644 index 0000000..c93c756 --- /dev/null +++ b/app/src/main/java/com/jieliu/app/platform/BilibiliLabels.kt @@ -0,0 +1,29 @@ +package com.jieliu.app.platform + +import com.jieliu.app.task.RECHECK_WINDOW_MS + +internal object BilibiliLabels { + private val replyCount = Regex("(?:(?:全部|查看|展开|共)\\s*)?(\\d+)\\s*条回复(?:\\s*[>>])?") + private val relativeTime = Regex("^(刚刚|[1-9]\\d?\\s*(?:秒|分钟)前)(?:\\s|$)") + + fun replyCount(label: String): Int? = replyCount.matchEntire(label)?.groupValues?.get(1)?.toIntOrNull() + + fun replyPrompt(label: String, author: String): Boolean { + if (author.isBlank()) return false + return listOf("回复 @", "回复@", "回复 ", "回复").any { prefix -> + val exact = prefix + author + label.startsWith(exact) && label.substring(exact.length) in setOf("", ":", ":", " :", " :") + } + } + + fun matchesSubmissionTime(label: String, armedAt: Long, now: Long): Boolean { + if (armedAt <= 0 || armedAt > now || now - armedAt > RECHECK_WINDOW_MS) return false + val time = relativeTime.find(label)?.groupValues?.get(1)?.replace(" ", "") ?: return false + val age = now - armedAt + val slack = 5_000L + if (time == "刚刚") return age < 60_000L + slack + val unit = if (time.endsWith("分钟前")) 60_000L else 1_000L + val amount = time.takeWhile(Char::isDigit).toLongOrNull() ?: return false + return age >= amount * unit - slack && age < (amount + 1) * unit + slack + } +} diff --git a/app/src/main/java/com/jieliu/app/platform/BilibiliPhotoPicker.kt b/app/src/main/java/com/jieliu/app/platform/BilibiliPhotoPicker.kt new file mode 100644 index 0000000..d658492 --- /dev/null +++ b/app/src/main/java/com/jieliu/app/platform/BilibiliPhotoPicker.kt @@ -0,0 +1,272 @@ +package com.jieliu.app.platform + +import android.graphics.Rect +import android.os.SystemClock +import android.view.accessibility.AccessibilityNodeInfo +import com.jieliu.app.task.TaskPlan +import kotlin.math.ceil +import kotlin.math.floor + +/** Uses the native ImagePicker opened by the verified reply editor. */ +internal class BilibiliPhotoPicker(private val ui: AccessibleUi) { + private data class Chrome(val heading: UiNode, val grid: UiNode, val confirm: UiNode, val count: Int) + private data class Region(val image: Rect, val overlay: Rect) + private data class Tile(val action: UiNode, val region: Region, val selected: Boolean, val ordinal: Int?) + private data class Selection(val chrome: Chrome, val tiles: List) + private data class Surface(val window: Int, val heading: UiNodeSource, val grid: UiNodeSource) : AutoCloseable { + override fun close() { + heading.close() + grid.close() + } + } + + fun select(album: String, references: List, beforeCommitSelection: () -> Unit) { + require(album.matches(albumName) && references.size in 1..TaskPlan.MAX_TEMPLATE_PHOTOS) + val surface = awaitPage("哔哩哔哩未打开可核对的图片选择器") { page -> + val chrome = page.chrome() ?: return@awaitPage null + if (chrome.count != 0) throw PlatformException("哔哩哔哩相册已有所选图片,未修改选择") + Surface(page.windowId, chrome.heading.retainSource(), chrome.grid.retainSource()) + } + surface.use { + openAlbum(surface, album, references.size) + val regions = awaitPage("哔哩哔哩专用相册未完整显示本次绑定图片") { page -> + val visible = page.selection(surface, album, references.size) ?: return@awaitPage null + if (visible.chrome.count != 0 || visible.tiles.any(Tile::selected)) { + throw PlatformException("哔哩哔哩专用相册已有所选图片,未修改选择") + } + visible.tiles.map(Tile::region) + } + val selected = mutableListOf() + var nextCaptureAt = 0L + val thumbnails = ui.await(5_000) { + val now = SystemClock.elapsedRealtime() + if (now < nextCaptureAt || !matches(surface, album, regions, selected)) return@await null + nextCaptureAt = now + 400L + ui.screenshotPhotos(surface.window, regions.map(Region::image)) + ?.takeIf { it.size == regions.size && matches(surface, album, regions, selected) } + ?.zip(regions)?.map { (pixels, region) -> pixels.maskOverlay(region) } + } ?: throw PlatformException("无法完整截取哔哩哔哩专用相册的图片缩略图") + val order = bilibiliAttachmentOrder(references, thumbnails) + ?: throw PlatformException("哔哩哔哩专用相册的缩略图无法与绑定图片逐一对应") + + for ((index, tileIndex) in order.withIndex()) { + ui.pace() + val accepted = ui.inspect { page -> + val current = page.verifiedSelection(surface, album, regions, selected) ?: return@inspect false + ui.click(current.tiles[tileIndex].action) + } == true + if (!accepted) throw PlatformException("哔哩哔哩相册未接受第 ${index + 1} 张图片的选择") + selected.add(tileIndex) + awaitPage("哔哩哔哩未核对第 ${index + 1} 张图片的选中状态和数量") { page -> + true.takeIf { page.verifiedSelection(surface, album, regions, selected) != null } + } + } + + ui.pace() + val accepted = ui.inspect { page -> + val picked = page.verifiedSelection(surface, album, regions, selected) ?: return@inspect false + val confirm = picked.chrome.confirm.takeIf { it.nativePickerClick() } ?: return@inspect false + beforeCommitSelection() + ui.click(confirm) + } == true + if (!accepted) throw PlatformException("哔哩哔哩未确认将选中的图片带回回复框") + } + } + + private fun openAlbum(surface: Surface, album: String, count: Int) { + ui.pace() + val listed = ui.inspect { page -> + val heading = page.chrome(surface)?.takeIf { it.count == 0 }?.heading ?: return@inspect null + if (heading.text == album) return@inspect false + if (!heading.nativePickerClick() || !ui.click(heading)) return@inspect null + true + } ?: throw PlatformException("哔哩哔哩未打开已核对的相册列表") + if (!listed) return + val list = awaitPage("哔哩哔哩未显示原生相册列表") { page -> + page.visibleList(ALBUM_LIST)?.let { it.retainSource() to page.windowId } + } + list.first.use { source -> + repeat(MAX_ALBUM_PAGES) { index -> + val selected = ui.inspect { page -> + val recycler = page.visibleList(ALBUM_LIST)?.takeIf { page.windowId == list.second && it.hasSource(source) } + ?: throw PlatformException("哔哩哔哩相册列表已变化") + val labels = page.nodes.filter { it.resourceId == ALBUM_NAME && it.text == album && it.isDescendantOf(recycler) } + if (labels.isEmpty()) return@inspect false + val label = labels.singleOrNull() ?: throw PlatformException("哔哩哔哩显示了多个同名专用相册") + val row = label.directParent()?.takeIf { + it.resourceId == ALBUM_ROW && it.nativePickerClick() && recycler.bounds.contains(it.bounds) && + it.bounds.contains(label.bounds) + } ?: throw PlatformException("哔哩哔哩未识别专用相册的原生列表项") + val quantity = page.nodes.singleOrNull { + it.resourceId == ALBUM_SIZE && it.directParent() === row && row.bounds.contains(it.bounds) + } + if (quantity == null || parseAlbumSize(quantity.text) != count || !ui.click(row)) { + throw PlatformException("哔哩哔哩未确认本次专用相册的图片数量或打开动作") + } + true + } + if (selected == true) return + if (index == MAX_ALBUM_PAGES - 1) return@repeat + ui.pace() + val moved = ui.inspect { page -> + val recycler = page.visibleList(ALBUM_LIST)?.takeIf { + page.windowId == list.second && it.hasSource(source) && it.scrollable && it.supports(FORWARD) + } ?: return@inspect false + recycler.act(FORWARD) + } == true + if (!moved) throw PlatformException("哔哩哔哩相册列表未找到本次专用相册") + } + } + throw PlatformException("哔哩哔哩相册列表未找到本次专用相册") + } + + private fun matches(surface: Surface, album: String, regions: List, selected: List): Boolean = + ui.inspect { it.verifiedSelection(surface, album, regions, selected) != null } == true + + private fun UiPage.verifiedSelection( + surface: Surface, + album: String, + regions: List, + selected: List, + ): Selection? { + val current = selection(surface, album, regions.size) ?: return null + if (current.chrome.count != selected.size || current.tiles.map(Tile::region) != regions) return null + val positions = selected.withIndex().associate { (index, tile) -> tile to index + 1 } + return current.takeIf { + current.tiles.withIndex().all { (index, tile) -> + val ordinal = positions[index] + tile.selected == (ordinal != null) && (tile.ordinal == null || tile.ordinal == ordinal) + } + } + } + + private fun UiPage.selection(surface: Surface, album: String, count: Int): Selection? { + val chrome = chrome(surface)?.takeIf { it.heading.text == album && it.count in 0..count } ?: return null + val cells = nodes.filter { it.resourceId == CELL && it.isDescendantOf(chrome.grid) } + if (cells.size != count || cells.any { !chrome.grid.bounds.contains(it.bounds) }) return null + val visible = cells.map { cell -> + if (nodes.any { it.resourceId == VIDEO_BADGE && it.isDescendantOf(cell) }) return null + val image = nodes.singleOrNull { + it.resourceId == THUMBNAIL && it.isDescendantOf(cell) && cell.bounds.contains(it.bounds) + } ?: return null + val holder = nodes.singleOrNull { + it.resourceId == CHECK_HOLDER && it.isDescendantOf(cell) && cell.bounds.contains(it.bounds) + } ?: return null + val checker = nodes.singleOrNull { + it.resourceId == CHECKER && it.isDescendantOf(holder) && holder.bounds.contains(it.bounds) && + it.bounds.width() <= cell.bounds.width() / 2 && it.bounds.height() <= cell.bounds.height() / 2 + } ?: return null + val action = listOf(holder, checker).singleOrNull { it.nativePickerClick() } ?: return null + val ordinal = checker.text.toIntOrNull()?.takeIf { it in 1..TaskPlan.MAX_TEMPLATE_PHOTOS } + val nativeChecks = listOfNotNull(holder.checked, checker.checked).distinct() + val marked = checker.selected || holder.selected || ordinal != null + if (nativeChecks.size > 1 || (nativeChecks.singleOrNull() == false && marked)) return null + val checked = nativeChecks.singleOrNull() ?: marked + Tile(action, Region(Rect(image.bounds), Rect(checker.bounds)), checked, ordinal) + }.sortedWith(compareBy { it.region.image.top }.thenBy { it.region.image.left }) + if (visible.indices.any { right -> (0 until right).any { left -> + Rect.intersects(visible[left].region.image, visible[right].region.image) + } }) return null + return Selection(chrome, visible) + } + + private fun UiPage.chrome(surface: Surface? = null): Chrome? { + if (!complete) return null + if (surface != null && windowId != surface.window) return null + if (nodes.any { it.resourceId == ALBUM_LIST }) return null + val header = nodes.singleOrNull { it.resourceId == TOOLBAR && bounds.contains(it.bounds) } ?: return null + val heading = nodes.singleOrNull { + it.resourceId == ALBUM_HEADING && it.text.isNotBlank() && !it.editable && + it.isDescendantOf(header) && header.bounds.contains(it.bounds) && surface?.heading?.let(it::hasSource) != false + } ?: return null + val grid = visibleList(GRID)?.takeIf { it.bounds.top >= header.bounds.bottom && surface?.grid?.let(it::hasSource) != false } + ?: return null + val actions = nodes.singleOrNull { + it.resourceId == PICKER_ACTIONS && bounds.contains(it.bounds) && it.bounds.top >= grid.bounds.bottom + } ?: return null + val confirm = nodes.singleOrNull { + it.resourceId == CONFIRM && it.isDescendantOf(actions) && actions.bounds.contains(it.bounds) && !it.editable + } ?: return null + val preview = nodes.singleOrNull { + it.resourceId == PREVIEW && it.isDescendantOf(actions) && actions.bounds.contains(it.bounds) && !it.editable + } ?: return null + val confirmed = parsePickerCount(confirm.text, "确定") ?: return null + val previewed = parsePickerCount(preview.text, "预览") ?: return null + val numbers = listOf(confirmed, previewed).filter { it >= 0 }.distinct() + if (numbers.size > 1) return null + return Chrome(heading, grid, confirm, numbers.singleOrNull() ?: 0) + } + + private fun UiPage.visibleList(id: String): UiNode? = nodes.singleOrNull { + complete && it.resourceId == id && it.className in recyclerClasses && bounds.contains(it.bounds) + } + + private fun PhotoPixels.maskOverlay(region: Region): PhotoPixels { + val overlay = Rect(region.overlay).apply { inset(-2, -2) } + val image = region.image + if (!overlay.intersect(image)) return this + val x = width.toDouble() / image.width() + val y = height.toDouble() / image.height() + val left = floor((overlay.left - image.left) * x).toInt().coerceIn(0, width) + val right = ceil((overlay.right - image.left) * x).toInt().coerceIn(left, width) + val top = floor((overlay.top - image.top) * y).toInt().coerceIn(0, height) + val bottom = ceil((overlay.bottom - image.top) * y).toInt().coerceIn(top, height) + return copy(argb = argb.copyOf().apply { + for (row in top until bottom) fill(0, row * width + left, row * width + right) + }) + } + + private fun awaitPage(message: String, probe: (UiPage) -> T?): T = + ui.await(5_000) { ui.inspect(probe) } ?: throw PlatformException(message) + + private fun UiNode.nativePickerClick(): Boolean = enabled && supports(AccessibilityNodeInfo.ACTION_CLICK) + + private companion object { + const val MAX_ALBUM_PAGES = 7 + const val TOOLBAR = "nav_top_bar" + const val ALBUM_HEADING = "pick_album_txt" + const val GRID = "media_recycleview" + const val CELL = "image_item_layout" + const val THUMBNAIL = "image_item" + const val CHECK_HOLDER = "media_item_check_layout" + const val CHECKER = "media_item_check" + const val VIDEO_BADGE = "video_layout" + const val PICKER_ACTIONS = "multi_picker_layout" + const val CONFIRM = "choose_ok_btn" + const val PREVIEW = "choose_preview_btn" + const val ALBUM_LIST = "album_recycleview" + const val ALBUM_ROW = "album_layout" + const val ALBUM_NAME = "album_name" + const val ALBUM_SIZE = "album_size" + const val FORWARD = AccessibilityNodeInfo.ACTION_SCROLL_FORWARD + val albumName = Regex("SJ-[0-9a-f]{12}") + val recyclerClasses = setOf("androidx.recyclerview.widget.RecyclerView", "tv.danmaku.bili.widget.RecyclerView") + val quantity = Regex("[0-9]{1,2}") + val buttonCount = Regex("[((]([0-9]{1,2})(?:/([0-9]{1,2}))?[))]") + + fun parseAlbumSize(text: String): Int? { + val compact = text.filterNot(Char::isWhitespace).removeSuffix("张图片").removeSuffix("张照片") + .removeSuffix("张").removeSuffix("项").removeSurrounding("(", ")").removeSurrounding("(", ")") + return compact.takeIf(quantity::matches)?.toIntOrNull() + } + + fun parsePickerCount(text: String, action: String): Int? { + val compact = text.filterNot(Char::isWhitespace) + if (!compact.startsWith(action)) return null + val suffix = compact.removePrefix(action) + if (suffix.isEmpty()) return -1 // The default label carries no explicit counter. + val groups = buttonCount.matchEntire(suffix)?.groupValues ?: return null + val count = groups[1].toIntOrNull() ?: return null + val maximum = groups[2].takeIf(String::isNotEmpty)?.toIntOrNull() + return count.takeIf { it in 0..TaskPlan.MAX_TEMPLATE_PHOTOS && (maximum == null || it <= maximum) } + } + } +} + +internal fun bilibiliAttachmentOrder(references: List, thumbnails: List): List? { + if (references.isEmpty() || references.size != thumbnails.size) return null + val order = references.map { reference -> + thumbnails.indices.singleOrNull { PublishedPhotoMatcher.matches(reference, thumbnails[it]) } ?: return null + } + return order.takeIf { it.distinct().size == references.size } +} diff --git a/app/src/main/java/com/jieliu/app/platform/BilibiliReplies.kt b/app/src/main/java/com/jieliu/app/platform/BilibiliReplies.kt new file mode 100644 index 0000000..67e270f --- /dev/null +++ b/app/src/main/java/com/jieliu/app/platform/BilibiliReplies.kt @@ -0,0 +1,323 @@ +package com.jieliu.app.platform + +import android.graphics.Rect +import android.os.Build +import com.jieliu.app.data.PhotoLibrary +import com.jieliu.app.data.StagedPhotos +import com.jieliu.app.task.TemplatePhoto +import java.io.Closeable + +internal class BilibiliReplies( + private val ui: AccessibleUi, + private val comments: BilibiliComments, + private val photos: PhotoLibrary, + private val diagnostic: (String) -> Unit, +) { + private data class Editor(val container: UiNode, val input: UiNode, val send: UiNode) + private data class Prepared( + val target: CommentTarget, + val text: String, + val window: Int, + val bar: UiNodeSource, + val input: UiNodeSource, + ) : Closeable { + override fun close() { + bar.close() + input.close() + } + } + + private data class ImageView(val window: Int, val regions: List) + private data class ReceiptRow(val key: String, val own: Boolean, val images: ImageView) + private enum class Role { OWN, OTHER } + private data class RoleMenu(val window: Int, val role: Role) + + private val picker = BilibiliPhotoPicker(ui) + private var prepared: Prepared? = null + + fun prepare(target: CommentTarget, text: String, requiresImages: Boolean): Boolean { + check(prepared == null && text.isNotBlank()) + if (comments.isComposeOriginal(target)) return inspectComposeReply(target, requiresImages) + val threadOpened = comments.enterThread(target) + val baseline = if (threadOpened) { + comments.readThread(target) { _, thread -> thread.complete && thread.replies.none { it.target.text == text } } == true + } else comments.readOriginal(target) { _, row -> row.emptyThread } == true + if (!baseline) { + if (threadOpened) comments.leaveThread() + return false + } + + ui.pace() + val opened = comments.readOriginal(target) { page, row -> + if (page.editorBar() != null || row.own) return@readOriginal false + ui.click(row.reply) + } == true + if (!opened) { + if (threadOpened) comments.leaveThread() + return false + } + prepared = ui.await(5_000) { + ui.inspect { page -> + val editor = page.replyEditor(target) ?: return@inspect null + if (!editor.input.isStillBlankAndFocused() || page.draftPictures(editor)?.isNotEmpty() != false) { + return@inspect null + } + Prepared(target, text, page.windowId, editor.container.retainSource(), editor.input.retainSource()) + } + } ?: throw PlatformException("哔哩哔哩未显示指向原评论的空白回复框") + return true + } + + fun hasPreparedBaseline(targetKey: String, text: String): Boolean = + prepared?.let { it.target.key == targetKey && it.text == text } == true + + fun preparedTarget(text: String): CommentTarget = prepared?.takeIf { it.text == text }?.target + ?: throw PlatformException("尚未核对哔哩哔哩的原评论回复框") + + fun hasUnsettledEditor(): Boolean = ui.inspect(traverseHiddenParents = true) { page -> + page.editorBar() != null || page.composeInput() != null + } == true + + private fun inspectComposeReply(target: CommentTarget, requiresImages: Boolean): Boolean { + ui.pace() + val originalWindow = comments.readOriginal(target) { page, row -> + page.windowId.takeIf { !row.own && ui.click(row.reply) } + } ?: return false + val hasImageEntry = ui.await(5_000) { + ui.inspect(traverseHiddenParents = true) { page -> + if (page.windowId == originalWindow) return@inspect null + val (surface, input) = page.composeInput() ?: return@inspect null + val cue = input.hint.ifBlank { input.text } + if (!input.showingHint || !BilibiliLabels.replyPrompt(cue, target.author) || + input.text.isNotBlank() && input.text != cue + ) return@inspect null + page.nodes.any { it.isDescendantOf(surface) && it.labels().any { label -> + label in attachmentLabels || label == "图片" || label == "相册" + } } + } + } ?: throw PlatformException("哔哩哔哩未显示指向原评论的空白回复框") + diagnostic("哔哩哔哩已核对匹配评论和指向原作者的回复框") + val reason = if (requiresImages && !hasImageEntry) "原评论的回复框未提供可核对的图片入口" + else "此评论界面的本人回复回执尚未完成核对" + throw PlatformException("哔哩哔哩${reason},已在提交前停止") + } + + private fun UiPage.composeInput(): Pair? { + val input = nodes.singleOrNull { it.resourceId == "edit" && it.enabled && it.editable && it.focused } ?: return null + val surface = nodes.singleOrNull { + it.className == "androidx.compose.ui.platform.ComposeView" && input.isDescendantOf(it) + } ?: return null + if (surface.bounds.width() < bounds.width() * .85 || !surface.bounds.contains(input.bounds)) return null + val publish = nodes.singleOrNull { it.isDescendantOf(surface) && it.text == "发布" && + it.bounds.centerY() > input.bounds.bottom && it.bounds.centerX() > surface.bounds.centerX() } + ?: return null + if (nodes.none { it.isDescendantOf(surface) && it.text == "转到动态" && + it.bounds.centerX() < surface.bounds.centerX() && it.bounds.top <= publish.bounds.centerY() && + it.bounds.bottom >= publish.bounds.centerY() }) return null + return surface to input + } + + fun reset() { + prepared?.close() + prepared = null + } + + fun submit(target: CommentTarget, text: String, attachments: List, arm: () -> Unit): Boolean { + val session = prepared?.takeIf { it.target == target && it.text == text } + ?: throw PlatformException("哔哩哔哩回复对象或正文已变更") + var staged: StagedPhotos? = null + var handedToEditor = false + try { + val references = if (attachments.isNotEmpty()) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { + throw PlatformException("图片回复核对需要 Android 11 或更新版本") + } + val canAttach = ui.inspect { page -> + val editor = page.checkedEditor(session) ?: return@inspect false + page.photoButton(editor) != null && editor.input.isStillBlankAndFocused() && page.draftPictures(editor)?.isEmpty() == true + } == true + if (!canAttach) { + throw PlatformException("哔哩哔哩原评论的回复框未提供可核对的图片入口,已在提交前停止") + } + val pixels = photos.readReceiptPixels(attachments) ?: throw PlatformException("无法读取绑定图片") + photos.cleanupStaged() + val album = photos.stage(attachments) + staged = album + ui.pace() + val opened = ui.inspect { page -> + val editor = page.checkedEditor(session) ?: return@inspect false + if (!editor.input.isStillBlankAndFocused() || page.draftPictures(editor)?.isEmpty() != true) return@inspect false + page.photoButton(editor)?.let { ui.click(it) } == true + } == true + if (!opened) throw PlatformException("未打开哔哩哔哩原回复的图片选择器") + picker.select(album.albumName, pixels) { handedToEditor = true } + pixels + } else emptyList() + + val wrote = ui.await(5_000) { + ui.inspect { page -> + val editor = page.checkedEditor(session) ?: return@inspect null + if (page.draftPictures(editor)?.size != references.size || !editor.input.isStillBlankAndFocused()) return@inspect null + ui.setText(editor.input, text, requireBlankFocusedInput = true) + } + } == true + if (!wrote) throw PlatformException("无法在哔哩哔哩原回复框中写入完整正文") + + ui.pace() + val ready = ui.await(5_000) { + ui.inspect { page -> page.readyDraft(session, references.size)?.second } + } ?: throw PlatformException("未能回读哔哩哔哩回复正文、图片和发布按钮") + if (!verifyImages(ready, references) { ui.inspect { it.readyDraft(session, references.size)?.second } }) { + throw PlatformException("哔哩哔哩草稿图片与按顺序绑定的图片不一致") + } + if (ui.inspect { it.readyDraft(session, references.size)?.second } != ready) { + throw PlatformException("哔哩哔哩回复草稿已变更") + } + arm() + return ui.inspect { page -> + val draft = page.readyDraft(session, references.size)?.takeIf { it.second == ready } ?: return@inspect false + ui.click(draft.first.send) + } == true + } finally { + reset() + staged?.let { if (handedToEditor) photos.leaveStagedForReview(it) else photos.removeStaged(it) } + } + } + + fun confirm(key: String, author: String, text: String, attachments: List, armedAt: Long): CommentPublishResult { + val references = photos.readReceiptPixels(attachments) ?: return CommentPublishResult.UNCERTAIN + val target = ui.await(4_000) { comments.threadTarget(key, author) } ?: return CommentPublishResult.UNCERTAIN + if (ui.await(5_000) { true.takeIf { comments.enterThread(target) } } != true) return CommentPublishResult.UNCERTAIN + val readReceipt = { receiptRow(target, text, references.size, armedAt) } + val initial = ui.await(5_000, readReceipt) ?: return CommentPublishResult.UNCERTAIN + diagnostic("哔哩哔哩已在原评论线程找到唯一匹配的回复正文") + if (!initial.own && inspectRole(target, null, initial.key, readReceipt) != Role.OTHER) return CommentPublishResult.UNCERTAIN + + val current = ui.await(5_000) { readReceipt()?.takeIf { it.key == initial.key } } ?: return CommentPublishResult.UNCERTAIN + if (!verifyImages(current.images, references) { readReceipt()?.takeIf { it.key == initial.key }?.images }) { + return CommentPublishResult.UNCERTAIN + } + if (references.isNotEmpty()) diagnostic("哔哩哔哩已按顺序核对原回复的全部图片") + if (!current.own && inspectRole(target, current, initial.key, readReceipt) != Role.OWN) return CommentPublishResult.UNCERTAIN + diagnostic("哔哩哔哩已核对原评论下的本人回复") + return CommentPublishResult.CONFIRMED + } + + private fun receiptRow(target: CommentTarget, text: String, count: Int, armedAt: Long): ReceiptRow? = + comments.readThread(target) { page, thread -> + val row = thread.replies.singleOrNull { it.target.text == text } ?: return@readThread null + val time = row.time ?: return@readThread null + if (!BilibiliLabels.matchesSubmissionTime(time, armedAt, System.currentTimeMillis())) return@readThread null + val pictures = row.images?.takeIf { it.size == count } ?: return@readThread null + imageView(page, pictures)?.let { ReceiptRow(row.target.key, row.own, it) } + } + + private fun inspectRole( + target: CommentTarget, + expected: ReceiptRow?, + replyKey: String, + readReceipt: () -> ReceiptRow?, + ): Role? { + val before = readReceipt()?.takeIf { it.key == replyKey && (expected == null || it == expected) } ?: return null + val opened = comments.readThread(target) { page, thread -> + if (page.windowId != before.images.window) return@readThread false + val row = if (expected == null) thread.original else thread.replies.singleOrNull { it.target.key == replyKey } + if (expected != null && imageView(page, row?.images ?: return@readThread false) != expected.images) return@readThread false + row?.more?.let { ui.click(it) } == true + } == true + if (!opened) return null + val menu = ui.await(3_500) { ui.inspect { it.roleMenu(before.images.window) } } ?: return null + val closed = ui.inspect { page -> page.roleMenu(before.images.window) == menu && ui.back() } == true + return menu.role.takeIf { closed } + } + + private fun UiPage.roleMenu(previousWindow: Int): RoleMenu? { + if (!complete || windowId == previousWindow || editorBar() != null) return null + fun exactAction(label: String) = nodes.filter { it.labels().any { value -> + value == label || value == "$label,按钮" + } }.mapNotNull(UiNode::nearbyClick).distinct() + if (exactAction("复制").size != 1) return null + val remove = exactAction("删除").size + val report = exactAction("举报").size + return when { + remove == 1 && report == 0 -> RoleMenu(windowId, Role.OWN) + remove == 0 && report == 1 -> RoleMenu(windowId, Role.OTHER) + else -> null + } + } + + private fun verifyImages(snapshot: ImageView, expected: List, readBack: () -> ImageView?): Boolean { + val actual = ui.screenshotPhotos(snapshot.window, snapshot.regions) ?: return false + return readBack() == snapshot && actual.size == expected.size && + expected.indices.all { PublishedPhotoMatcher.matches(expected[it], actual[it]) } + } + + private fun imageView(page: UiPage, pictures: List): ImageView? { + val regions = pictures.map { Rect(it.bounds) } + if (regions.any { it.isEmpty || !page.bounds.contains(it) } || regions.indices.any { i -> + (0 until i).any { Rect.intersects(regions[it], regions[i]) } + }) return null + return ImageView(page.windowId, regions) + } + + private fun UiPage.readyDraft(session: Prepared, count: Int): Pair? { + val editor = checkedEditor(session) ?: return null + if (!editor.send.biliClick() || !editor.input.hasCurrentFocusedText(session.text) { BilibiliLabels.replyPrompt(it, session.target.author) }) { + return null + } + val pictures = draftPictures(editor)?.takeIf { it.size == count } ?: return null + return imageView(this, pictures)?.let { editor to it } + } + + private fun UiPage.checkedEditor(session: Prepared): Editor? { + if (windowId != session.window) return null + return replyEditor(session.target)?.takeIf { it.container.hasSource(session.bar) && it.input.hasSource(session.input) } + } + + private fun UiPage.editorBar(): UiNode? = nodes.singleOrNull { bar -> + bar.resourceId == "comment_bar" && nodes.any { it.isDescendantOf(bar) && it.resourceId == "edit" && it.editable } + } + + private fun UiPage.replyEditor(target: CommentTarget): Editor? { + if (!complete) return null + val bar = editorBar() ?: return null + val input = nodes.singleOrNull { it.resourceId == "edit" && it.isDescendantOf(bar) && it.editable && it.focused } ?: return null + if (!listOf(input.hint, input.description, input.text.takeIf { input.showingHint }.orEmpty()) + .any { BilibiliLabels.replyPrompt(it, target.author) }) return null + val send = nodes.singleOrNull { it.resourceId == "send" && it.isDescendantOf(bar) && + it.labels().any { label -> label == "发布" || label == "发布,按钮" } } ?: return null + val shareOptions = nodes.filter { it.isDescendantOf(bar) && it.resourceId in shareContainers } + if (shareOptions.any { option -> + nodes.singleOrNull { node -> node.isDescendantOf(option) && node.resourceId in shareCheckboxes }?.checked != false + }) return null + if (nodes.any { node -> node.isDescendantOf(bar) && + (node.resourceId == "sync_activity_checkbox" || node.labels().contains("转发至动态")) && + node.resourceId in shareCheckboxes && node.checked != false }) return null + return Editor(bar, input, send) + } + + private fun UiPage.photoButton(editor: Editor): UiNode? = nodes.singleOrNull { node -> + node.isDescendantOf(editor.container) && node.biliClick() && + node.labels().any(attachmentLabels::contains) + } + + private fun UiPage.draftPictures(editor: Editor): List? { + val strips = nodes.filter { it.isDescendantOf(editor.container) && it.resourceId in draftStrips } + if (strips.isEmpty()) return emptyList().takeIf { + nodes.none { it.isDescendantOf(editor.container) && (it.resourceId in draftPhotoIds || it.labels().any { label -> imageOrdinal.matches(label) }) } + } + val strip = strips.singleOrNull() ?: return null + return nodes.filter { it.isDescendantOf(strip) && strip.bounds.contains(it.bounds) && + (it.resourceId in draftPhotoIds || it.labels().any { label -> imageOrdinal.matches(label) }) } + .sortedWith(compareBy({ it.bounds.top }, { it.bounds.left })) + } + + private companion object { + val imageOrdinal = Regex("(?:第\\s*)?\\d+\\s*张图片") + val draftStrips = setOf("image_set_layout", "picture_list_container") + val draftPhotoIds = setOf("comment_image", "image_item", "picture") + val shareContainers = setOf("sync_follow_container", "sync_activity_container") + val shareCheckboxes = setOf("checkbox", "sync_activity_checkbox") + val attachmentLabels = setOf("添加图片", "添加图片,按钮", "选择图片", "选择图片,按钮") + } +} diff --git a/app/src/main/java/com/jieliu/app/platform/BilibiliVideoNavigation.kt b/app/src/main/java/com/jieliu/app/platform/BilibiliVideoNavigation.kt new file mode 100644 index 0000000..8d2d6a1 --- /dev/null +++ b/app/src/main/java/com/jieliu/app/platform/BilibiliVideoNavigation.kt @@ -0,0 +1,428 @@ +package com.jieliu.app.platform + +import android.graphics.Rect +import android.view.accessibility.AccessibilityNodeInfo +import java.security.MessageDigest + +/** Native portrait search and ordinary UGC video layouts from the official 9.21.0 resource table. */ +internal class BilibiliVideoNavigation( + private val spec: PlatformSpec, + private val ui: AccessibleUi, +) { + private data class Card(val video: VideoContext, val author: String, val entry: UiNode) + private data class Selection(val video: VideoContext, val author: String) + private data class Opened(val video: VideoContext, val author: String, val windowId: Int) + private data class PlayerTabs(val strip: UiNode, val introduction: UiNode, val comments: UiNode) + private enum class SearchStart { READY, THREAD, COMMENTS, PLAYER } + + private var keyword: String? = null + private var opened: Opened? = null + private var requireVideoTab = false + private val visited = mutableSetOf() + + fun launch() = ui.launchTarget(spec.label) + + fun search(keyword: String): VideoContext { + val query = keyword.trim().takeIf { it.isNotEmpty() } + ?: throw PlatformException("哔哩哔哩搜索关键词为空") + opened?.let { returnToResults(it.video) } + this.keyword = null + requireVideoTab = false + visited.clear() + recoverSearchStartingView() + openEditor() + val written = ui.inspect { page -> + val editor = searchInput(page)?.takeIf { it.focused } ?: return@inspect false + editor.text == query && !editor.showingHint || ui.setText(editor, query) + } == true + if (!written) throw PlatformException("哔哩哔哩搜索框未接受关键词") + ui.await(4_500) { ui.inspect { page -> true.takeIf { searchInput(page)?.hasCurrentQuery(query) == true } } } + ?: throw PlatformException("哔哩哔哩未能核对搜索框中的完整关键词") + val submitted = ui.inspect { page -> + val editor = searchInput(page) ?: return@inspect false + val submit = searchSubmit(page) ?: return@inspect false + sameRow(editor.bounds, submit.bounds) && editor.bounds.right <= submit.bounds.centerX() && + editor.hasCurrentQuery(query) && ui.click(submit) + } == true + if (!submitted) throw PlatformException("哔哩哔哩未能提交已经核对的搜索关键词") + awaitResults(query) + preferVideoTab(query) + this.keyword = query + return openNextResult(query) + } + + fun currentVideo(): VideoContext { + val expected = opened?.video ?: throw PlatformException("尚未绑定哔哩哔哩搜索结果中的视频") + return ui.await(4_500) { ui.inspect { page -> expected.takeIf { matchesVideo(page, it) } } } + ?: throw PlatformException("哔哩哔哩未能核对当前播放器的视频与 UP 主") + } + + fun nextVideo(previous: VideoContext): VideoContext { + val query = keyword ?: throw PlatformException("哔哩哔哩尚未完成关键词搜索") + returnToResults(previous) + return openNextResult(query) + } + + /** Available while the introduction exposes the exact bound title and uploader. */ + fun matchesVideo(page: UiPage, expected: VideoContext): Boolean { + val binding = opened ?: return false + return expected == binding.video && page.windowId == binding.windowId && + playerMatches(page, expected.title, binding.author) + } + + /** Read a comment tab only from a verified video detail page and its paired intro/comment strip. */ + fun commentEntry(page: UiPage, expected: VideoContext): UiNode? { + if (!matchesVideo(page, expected)) return null + val tabs = playerTabs(page) ?: return null + return actionInside(tabs.comments, tabs.strip) + } + + /** When a caller has independently verified the open comment tab, return its paired intro action. */ + fun introductionEntry(page: UiPage, expected: VideoContext): UiNode? { + val binding = opened ?: return null + if (binding.video != expected || binding.windowId != page.windowId || + page.nodes.any { it.editable && it.focused } + ) return null + val tabs = playerTabs(page) ?: return null + if (!hasPlayer(page, tabs)) return null + return actionInside(tabs.introduction, tabs.strip) + } + + private fun recoverSearchStartingView() { + val completed = mutableSetOf() + while (true) { + val stage = ui.await(6_000) { ui.inspect(::searchStart) } + ?: throw PlatformException("未能识别哔哩哔哩首页、搜索框或可安全退出的视频页面") + if (stage == SearchStart.READY) return + if (!completed.add(stage)) throw PlatformException("哔哩哔哩未返回可开始搜索的页面") + ui.pace() + val moved = ui.inspect { page -> + if (searchStart(page) != stage) return@inspect false + when (stage) { + SearchStart.THREAD -> threadClose(page)?.let { ui.click(it) } == true + SearchStart.COMMENTS -> playerTabs(page)?.let { tabs -> + actionInside(tabs.introduction, tabs.strip)?.let { ui.click(it) } + } == true + SearchStart.PLAYER -> ui.back() + SearchStart.READY -> false + } + } == true + if (!moved || ui.await(5_000) { ui.inspect { page -> searchStart(page)?.takeIf { it != stage } } } == null) { + throw PlatformException("哔哩哔哩未能从已识别的页面返回搜索") + } + } + } + + private fun searchStart(page: UiPage): SearchStart? { + if (searchInput(page) != null || resultQuery(page) != null || homeSearch(page) != null) return SearchStart.READY + if (page.nodes.any { it.editable && (it.focused || it.resourceId == "edit" && it.hasDraft()) }) return null + if (threadClose(page) != null) return SearchStart.THREAD + val tabs = playerTabs(page) ?: return null + if (!hasPlayer(page, tabs)) return null + if (page.nodes.any { it.resourceId == "cmt3_page_title_container" }) return null + val commentSurface = page.nodes.singleOrNull { + it.resourceId == "comment_container" && it.bounds.top >= tabs.strip.bounds.top && + it.bounds.width() >= page.bounds.width() * .75 + } + if (BilibiliComposeComments.list(page) != null || commentSurface != null && page.nodes.any { + it.resourceId in COMMENT_CONTENT_IDS && it.isDescendantOf(commentSurface) + } + ) return SearchStart.COMMENTS + return SearchStart.PLAYER + } + + private fun threadClose(page: UiPage): UiNode? { + BilibiliComposeComments.detail(page)?.let { return it.close } + val heading = page.nodes.singleOrNull { it.resourceId == "cmt3_page_title_container" } ?: return null + val title = page.nodes.singleOrNull { + it.resourceId == "title" && it.labels() == listOf("评论详情") && it.isDescendantOf(heading) + } ?: return null + if (page.nodes.none { it.resourceId == "cmt3_recycler" && it.bounds.top >= heading.bounds.bottom }) return null + return page.nodes.singleOrNull { + it.resourceId == "close" && it.isDescendantOf(heading) && it.enabled && it.clickable && + heading.bounds.contains(it.bounds) && sameRow(title.bounds, it.bounds) && + it.bounds.centerX() > title.bounds.centerX() + } + } + + private fun openEditor() { + val activated = ui.await(6_000) { ui.inspect { page -> + if (searchInput(page) != null) return@inspect true + (resultQuery(page) ?: homeSearch(page))?.let { ui.click(it) } + } } + if (activated != true) throw PlatformException("哔哩哔哩未找到可激活的首页搜索入口或搜索输入框") + ui.await(5_500) { ui.inspect { page -> + val input = searchInput(page) ?: return@inspect null + if (input.focused) return@inspect true + if (!input.supports(AccessibilityNodeInfo.ACTION_FOCUS) || !input.act(AccessibilityNodeInfo.ACTION_FOCUS)) { + ui.click(input) + } + null + } } + ?: throw PlatformException("哔哩哔哩搜索输入框未获得焦点") + } + + private fun searchSubmit(page: UiPage): UiNode? = page.nodes.singleOrNull { + it.resourceId == "action_search" && it.enabled && it.clickable && + "搜索" in it.labels() && it.bounds.centerX() >= page.x(.70f) && it.bounds.centerY() <= page.y(.22f) + } + + private fun searchHolder(page: UiPage): UiNode? { + val back = page.nodes.singleOrNull { + it.resourceId == "iv_back_arrow" && "返回" in it.labels() && + it.bounds.centerX() < page.x(.20f) && it.bounds.centerY() < page.y(.22f) + } ?: return null + return page.nodes.singleOrNull { + it.resourceId == "search_bar_input" && sameRow(it.bounds, back.bounds) && + it.bounds.left >= back.bounds.centerX() + } + } + + private fun searchInput(page: UiPage): UiNode? { + val holder = searchHolder(page) ?: return null + return page.nodes.singleOrNull { node -> + node.resourceId == "search_src_text" && node.editable && node.enabled && + node.isDescendantOf(holder) && holder.bounds.contains(node.bounds) && + node.supports(AccessibilityNodeInfo.ACTION_SET_TEXT) + } + } + + private fun resultQuery(page: UiPage): UiNode? { + if (page.nodes.none { it.resourceId == "search_result_layout" }) return null + val holder = searchHolder(page) ?: return null + return page.nodes.singleOrNull { + it.resourceId == "search_fake_text" && it.enabled && it.clickable && !it.editable && + it.text.isNotBlank() && it.isDescendantOf(holder) && holder.bounds.contains(it.bounds) + } + } + + private fun homeSearch(page: UiPage): UiNode? { + val bottom = page.nodes.singleOrNull { it.resourceId in HOME_NAV_IDS && it.bounds.centerY() >= page.y(.80f) } + ?: return null + if (page.nodes.none { it.isDescendantOf(bottom) && "首页" in it.labels() }) return null + val toolbar = page.nodes.singleOrNull { + it.resourceId == "app_bar" && it.bounds.top <= page.y(.20f) + } ?: return null + val candidates = page.nodes.filter { node -> + node.isDescendantOf(toolbar) && node.bounds.centerY() <= page.y(.20f) && node.enabled && node.clickable && + (node.resourceId == "expand_search" || "搜索栏,按钮" in node.labels()) + } + val native = candidates.singleOrNull { candidate -> + candidates.none { other -> other !== candidate && candidate.isDescendantOf(other) } + } + if (native != null) return native + val compose = page.nodes.singleOrNull { + it.resourceId == "top_bar_collapsible" && it.className == "androidx.compose.ui.platform.ComposeView" && + it.isDescendantOf(toolbar) + } ?: return null + val icon = page.nodes.singleOrNull { + it.description == "Search Icon" && it.isDescendantOf(compose) && it.bounds.centerY() <= page.y(.20f) + } ?: return null + return icon.directParent()?.takeIf { + it.biliClick() && compose.bounds.contains(it.bounds) && it.bounds.contains(icon.bounds) && + it.bounds.width() >= toolbar.bounds.width() * .35 + } + } + + private fun results(page: UiPage, query: String): UiNode? { + val input = resultQuery(page) ?: searchInput(page)?.takeUnless { it.focused } ?: return null + if (input.text != query || input.showingHint) return null + val resultRoot = page.nodes.singleOrNull { it.resourceId == "search_result_layout" } ?: return null + if (requireVideoTab && resultVideoTab(page)?.selected != true) return null + if (page.nodes.any { it.resourceId == "search_sug_view_container" && + it.bounds.height() > page.bounds.height() * .15 + } + ) return null + return page.nodes.singleOrNull { + it.resourceId == "recycler_view" && (it.className.endsWith("RecyclerView") || + it.className == "android.widget.GridView") && + it.isDescendantOf(resultRoot) && it.bounds.width() >= page.bounds.width() * .80 && + it.bounds.height() >= page.bounds.height() * .25 + } + } + + private fun awaitResults(query: String) { + ui.await(12_000) { ui.inspect { page -> true.takeIf { results(page, query) != null } } } + ?: throw PlatformException("哔哩哔哩没有显示与关键词一致的搜索结果列表") + } + + private fun preferVideoTab(query: String) { + val selection = ui.inspect { page -> if (results(page, query) != null) resultVideoTab(page)?.selected else null } + ?: return + if (!selection) { + ui.pace() + val selected = ui.inspect { page -> + if (results(page, query) == null) return@inspect false + val tab = resultVideoTab(page) ?: return@inspect false + tab.selected || ui.click(tab) + } == true + if (!selected || ui.await(7_500) { + ui.inspect { page -> true.takeIf { results(page, query) != null && resultVideoTab(page)?.selected == true } } + } != true + ) throw PlatformException("哔哩哔哩未能核对搜索结果的视频分类") + } + requireVideoTab = true + } + + private fun resultVideoTab(page: UiPage): UiNode? { + val tabs = page.nodes.singleOrNull { it.resourceId == "tabs" && it.bounds.centerY() <= page.y(.28f) } + ?: return null + val label = page.nodes.singleOrNull { it.isDescendantOf(tabs) && it.labels() == listOf("视频") } ?: return null + return actionInside(label, tabs) + } + + private fun openNextResult(query: String): VideoContext { + repeat(MAX_RESULT_PAGES) { + ui.pace() + val candidate = ui.inspect { page -> + val list = results(page, query) + ?: throw PlatformException("哔哩哔哩搜索列表已离开原关键词") + val cards = cards(page, list) + val duplicateKeys = cards.groupingBy { it.video.key }.eachCount() + val next = cards.firstOrNull { it.video.key !in visited && duplicateKeys[it.video.key] == 1 } + ?: return@inspect null + if (!ui.click(next.entry)) throw PlatformException("哔哩哔哩视频结果的原生点击失败") + Selection(next.video, next.author) + } + if (candidate != null) { + val video = candidate.video + val binding = ui.await(11_000) { + ui.inspect { page -> + Opened(video, candidate.author, page.windowId) + .takeIf { playerMatches(page, video.title, candidate.author) } + } + } ?: throw PlatformException("哔哩哔哩未能核对视频详情与搜索结果卡片的标题和 UP 主") + opened = binding + visited.add(video.key) + return video + } + if (!advanceResults(query)) throw PlatformException("哔哩哔哩没有更多可核对的普通视频搜索结果") + } + throw PlatformException("哔哩哔哩已达到本次视频搜索浏览上限") + } + + private fun cards(page: UiPage, list: UiNode): List { + val viewport = Rect(list.bounds).apply { if (!intersect(page.bounds)) setEmpty() } + return page.nodes.filter { + it.directParent() === list && it.enabled && it.clickable && it.resourceId != "ad_tint_frame" && + it.bounds.width() >= list.bounds.width() * .80 && viewport.contains(it.bounds) + }.mapNotNull { row -> + val children = page.nodes.filter { it.isDescendantOf(row) } + if (children.any { it.labels().any(AD_LABELS::contains) }) return@mapNotNull null + val title = children.singleOrNull { it.resourceId == "title" }?.metadataText() ?: return@mapNotNull null + val author = children.singleOrNull { it.resourceId == "upuser" }?.metadataText() + ?.removePrefix("UP主:")?.removePrefix("UP主:")?.trim()?.takeIf { it.isNotEmpty() } + ?: return@mapNotNull null + if (children.singleOrNull { it.resourceId == "duration" && it.labels().any(VIDEO_DURATION::matches) } == null || + children.none { it.resourceId == "duration_badge" || it.resourceId == "cover" } + ) return@mapNotNull null + val key = MessageDigest.getInstance("SHA-256") + .digest("bilibili\u0000$author\u0000$title".toByteArray(Charsets.UTF_8)) + .joinToString("") { "%02x".format(it) } + Card(VideoContext(key, title), author, row) + }.sortedBy { it.entry.bounds.top } + } + + private fun advanceResults(query: String): Boolean { + val state = ui.inspect { page -> + val list = results(page, query) ?: return@inspect null + if (!list.scrollable) return@inspect null + val viewport = Rect(list.bounds) + if (!viewport.intersect(page.bounds) || !ui.scrollUpInside(viewport)) return@inspect null + cards(page, list).map { it.video.key to it.entry.bounds.top } + } ?: return false + return ui.await(3_500) { + ui.inspect { page -> + val list = results(page, query) ?: return@inspect null + true.takeIf { cards(page, list).map { it.video.key to it.entry.bounds.top } != state } + } + } == true + } + + private fun returnToResults(expected: VideoContext) { + val query = keyword ?: throw PlatformException("哔哩哔哩当前视频缺少已核对的搜索关键词") + ui.pace() + val moved = ui.inspect { page -> + matchesVideo(page, expected) && page.nodes.none { it.editable && it.focused } && ui.back() + } == true + if (!moved) throw PlatformException("哔哩哔哩无法从已核对的视频回到原搜索列表") + awaitResults(query) + opened = null + } + + private fun playerMatches(page: UiPage, title: String, author: String): Boolean { + if (page.nodes.any { it.resourceId == "search_result_layout" || it.editable && it.focused }) return false + val tabs = playerTabs(page) ?: return false + if (!hasPlayer(page, tabs)) return false + return detailField(page, "title", tabs.strip.bounds.bottom, title) != null && + detailField(page, "author_name", tabs.strip.bounds.bottom, author) != null + } + + private fun hasPlayer(page: UiPage, tabs: PlayerTabs): Boolean { + val area = page.nodes.singleOrNull { + it.resourceId == "video_area" && it.bounds.width() >= page.bounds.width() * .80 && + it.bounds.height() >= page.bounds.height() * .12 && it.bounds.top < tabs.strip.bounds.top + } ?: return false + val container = page.nodes.singleOrNull { + it.resourceId == "video_container" && it.isDescendantOf(area) && + it.bounds.width() >= area.bounds.width() * .80 && area.bounds.contains(it.bounds) + } ?: return false + if (area.bounds.bottom <= tabs.strip.bounds.bottom) return true + return page.nodes.count { + it.resourceId == "control_container" && it.isDescendantOf(container) && + it.bounds.width() >= area.bounds.width() * .80 && it.bounds.height() >= page.bounds.height() * .12 && + it.bounds.bottom <= tabs.strip.bounds.bottom && it.bounds.top >= area.bounds.top + } == 1 + } + + private fun detailField(page: UiPage, id: String, minTop: Int, expected: String): UiNode? { + fun matches(node: UiNode): Boolean = node.bounds.bottom > minTop && + node.bounds.top < page.y(.80f) && (node.metadataText() == expected || + id == "title" && node.directParent()?.hasFullVideoTitle(expected) == true) + val full = page.nodes.filter { it.resourceId == id && matches(it) } + if (full.isNotEmpty()) return full.singleOrNull() + return page.visibleByViewId(id).singleOrNull(::matches) + } + + private fun playerTabs(page: UiPage): PlayerTabs? { + val strip = page.nodes.singleOrNull { + it.resourceId == "tabs" && it.bounds.centerY() in page.y(.16f)..page.y(.62f) && + it.bounds.height() <= page.bounds.height() * .16 + } ?: return null + val intro = page.nodes.singleOrNull { + it.resourceId == "tab_title" && it.labels() == listOf("简介") && it.isDescendantOf(strip) + } ?: return null + val comment = page.nodes.singleOrNull { + it.resourceId == "tab_title" && it.labels().any(COMMENT_TAB::matches) && it.isDescendantOf(strip) && + sameRow(it.bounds, intro.bounds) && it.bounds.centerX() > intro.bounds.centerX() + } ?: return null + return PlayerTabs(strip, intro, comment) + } + + private fun actionInside(label: UiNode, boundary: UiNode): UiNode? = + generateSequence(label, UiNode::directParent).takeWhile { it !== boundary } + .firstOrNull { it.enabled && it.clickable && boundary.bounds.contains(it.bounds) } + + private fun UiNode.hasFullVideoTitle(expected: String): Boolean = description.replace(LAYOUT_SPACE, " ").trim() + .removePrefix("互动视频,").removePrefix("视频,") + .removeSuffix(",展开").removeSuffix(",收起") == expected + + private fun UiNode.metadataText(): String? = text.replace(LAYOUT_SPACE, " ").trim().takeIf { it.isNotBlank() } + + // The native search hint contains a rotating recommendation, even with a query filled in. + private fun UiNode.hasCurrentQuery(query: String): Boolean = hasCurrentFocusedText(query) { true } + + private fun sameRow(first: Rect, second: Rect): Boolean = + first.top <= second.centerY() && second.centerY() < first.bottom && + second.top <= first.centerY() && first.centerY() < second.bottom + + private companion object { + const val MAX_RESULT_PAGES = 8 + val LAYOUT_SPACE = Regex("[\\s\\u00a0\\u2007\\u202f\\u3000]+") + val VIDEO_DURATION = Regex("(?:\\d{1,3}:)?\\d{1,3}:\\d{2}") + val COMMENT_TAB = Regex("评论(?:[\\s·((]*[\\d.]+万?[))]?)?") + val HOME_NAV_IDS = setOf("bottom_navigation", "tab_host") + val COMMENT_CONTENT_IDS = setOf("cmt3_recycler", "cmt3_placeholder", "recycler") + val AD_LABELS = setOf("广告", "推广", "广告·", "赞助") + } +} diff --git a/app/src/main/java/com/jieliu/app/platform/DouyinAdapter.kt b/app/src/main/java/com/jieliu/app/platform/DouyinAdapter.kt index ceb015f..ec0f8e3 100644 --- a/app/src/main/java/com/jieliu/app/platform/DouyinAdapter.kt +++ b/app/src/main/java/com/jieliu/app/platform/DouyinAdapter.kt @@ -227,7 +227,7 @@ internal class DouyinAdapter( return moved } - override fun prepareReply(target: CommentTarget, expectedText: String): Boolean { + override fun prepareReply(target: CommentTarget, expectedText: String, requiresImages: Boolean): Boolean { val panel = openPanel ?: throw PlatformException("请先打开抖音评论区") replyRequired = true preparedReply = null diff --git a/app/src/main/java/com/jieliu/app/platform/PlatformAdapter.kt b/app/src/main/java/com/jieliu/app/platform/PlatformAdapter.kt index 0427ffd..0e1cc27 100644 --- a/app/src/main/java/com/jieliu/app/platform/PlatformAdapter.kt +++ b/app/src/main/java/com/jieliu/app/platform/PlatformAdapter.kt @@ -34,7 +34,7 @@ interface PlatformAdapter { fun scanComments(): List = emptyList() fun scrollComments(): Boolean = false /** False means no reply control was activated and scanning may continue. */ - fun prepareReply(target: CommentTarget, expectedText: String): Boolean = false + fun prepareReply(target: CommentTarget, expectedText: String, requiresImages: Boolean): Boolean = false fun publishComment(text: String, beforeClick: () -> Unit): CommentPublishResult fun publishPhotoComment(text: String, photos: List, beforeClick: () -> Unit): CommentPublishResult { throw PlatformException("当前平台不支持发布图片评论") @@ -52,11 +52,12 @@ object PlatformRegistry { private val douyin = PlatformSpec("douyin", "抖音", "com.ss.android.ugc.aweme", true, supportsReplies = true) private val xiaohongshu = PlatformSpec("xiaohongshu", "小红书", "com.xingin.xhs", true, supportsReplies = true, contentUnit = "笔记") + private val bilibili = PlatformSpec("bilibili", "哔哩哔哩", "tv.danmaku.bili", true, supportsReplies = true) val platforms: List = listOf( douyin, xiaohongshu, - PlatformSpec("bilibili", "哔哩哔哩", "tv.danmaku.bili", false), + bilibili, ) fun create( @@ -77,6 +78,7 @@ object PlatformRegistry { douyin.id -> DouyinAdapter(spec, ui, PhotoLibrary(service)) xiaohongshu.id -> XiaohongshuAdapter(spec, ui, PhotoLibrary(service), noteKind, targetNoteKey, pinnedResumeNoteKey, receiptDiagnostic) + bilibili.id -> BilibiliAdapter(spec, ui, PhotoLibrary(service), receiptDiagnostic) else -> throw PlatformException("${spec.label} 暂未接入") } } diff --git a/app/src/main/java/com/jieliu/app/platform/XiaohongshuAdapter.kt b/app/src/main/java/com/jieliu/app/platform/XiaohongshuAdapter.kt index b661c37..e895edb 100644 --- a/app/src/main/java/com/jieliu/app/platform/XiaohongshuAdapter.kt +++ b/app/src/main/java/com/jieliu/app/platform/XiaohongshuAdapter.kt @@ -562,7 +562,7 @@ internal class XiaohongshuAdapter( return comments.scroll() } - override fun prepareReply(target: CommentTarget, expectedText: String): Boolean { + override fun prepareReply(target: CommentTarget, expectedText: String, requiresImages: Boolean): Boolean { check(commentNote != null && preparedReply == null) { "请先确认小红书评论区和草稿状态" } if (commentNote?.empty == true) return false if (!receipt.captureBaseline(target, expectedText) || !composer.prepare(target)) return false diff --git a/app/src/main/java/com/jieliu/app/task/TaskCheckpoint.kt b/app/src/main/java/com/jieliu/app/task/TaskCheckpoint.kt index a2511c5..f8124c0 100644 --- a/app/src/main/java/com/jieliu/app/task/TaskCheckpoint.kt +++ b/app/src/main/java/com/jieliu/app/task/TaskCheckpoint.kt @@ -213,11 +213,9 @@ data class TaskCheckpoint( return null } - private companion object { - const val RECHECK_WINDOW_MS = 30 * 60 * 1_000L - } } +internal const val RECHECK_WINDOW_MS = 30 * 60 * 1_000L internal const val XIAOHONGSHU_RECHECK_WINDOW_MS = 60 * 60 * 1_000L private fun Outcome.isConfirmedReply(): Boolean = this == Outcome.SENT || this == Outcome.USER_CONFIRMED diff --git a/app/src/main/java/com/jieliu/app/task/TaskRunner.kt b/app/src/main/java/com/jieliu/app/task/TaskRunner.kt index 3fd0bd3..236b60e 100644 --- a/app/src/main/java/com/jieliu/app/task/TaskRunner.kt +++ b/app/src/main/java/com/jieliu/app/task/TaskRunner.kt @@ -222,7 +222,9 @@ internal class TaskRunner( if (progress.hasHandled(target.key)) continue val rule = matcher.matchingRule(target.text) ?: continue val selection = checkpoint.selectReply(rule, title) ?: continue - if (platform.prepareReply(target, selection.text)) return MatchedReply(target, rule, selection) + if (platform.prepareReply(target, selection.text, selection.photos.isNotEmpty())) { + return MatchedReply(target, rule, selection) + } } return null } diff --git a/app/src/main/res/xml/accessibility_config.xml b/app/src/main/res/xml/accessibility_config.xml index 2802883..e24c141 100644 --- a/app/src/main/res/xml/accessibility_config.xml +++ b/app/src/main/res/xml/accessibility_config.xml @@ -8,4 +8,4 @@ android:canTakeScreenshot="true" android:description="@string/accessibility_description" android:notificationTimeout="200" - android:packageNames="com.ss.android.ugc.aweme,com.xingin.xhs" /> + android:packageNames="com.ss.android.ugc.aweme,com.xingin.xhs,tv.danmaku.bili" /> diff --git a/app/src/test/java/com/jieliu/app/platform/BilibiliLabelsTest.kt b/app/src/test/java/com/jieliu/app/platform/BilibiliLabelsTest.kt new file mode 100644 index 0000000..cfa7e09 --- /dev/null +++ b/app/src/test/java/com/jieliu/app/platform/BilibiliLabelsTest.kt @@ -0,0 +1,33 @@ +package com.jieliu.app.platform + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class BilibiliLabelsTest { + @Test fun replyPromptBindsTheWholeAuthorName() { + assertTrue(BilibiliLabels.replyPrompt("回复 @小明:", "小明")) + assertTrue(BilibiliLabels.replyPrompt("回复 @小明 :", "小明")) + assertTrue(BilibiliLabels.replyPrompt("回复@名字:", "名字:")) + assertFalse(BilibiliLabels.replyPrompt("回复 @小明同学", "小明")) + assertFalse(BilibiliLabels.replyPrompt("说点什么吧", "小明")) + } + + @Test fun distinguishesThreadCountsFromGenericExpansion() { + assertEquals(0, BilibiliLabels.replyCount("共 0 条回复")) + assertEquals(3, BilibiliLabels.replyCount("展开 3 条回复")) + assertEquals(5, BilibiliLabels.replyCount("全部5条回复>")) + assertNull(BilibiliLabels.replyCount("展开更多评论")) + } + + @Test fun relativeAgeMustAgreeWithTheArmedSubmission() { + val armed = 1_000_000L + assertTrue(BilibiliLabels.matchesSubmissionTime("刚刚 广东", armed, armed + 4_000)) + assertTrue(BilibiliLabels.matchesSubmissionTime("2分钟前 广东", armed, armed + 135_000)) + assertFalse(BilibiliLabels.matchesSubmissionTime("刚刚 广东", armed, armed + 70_000)) + assertFalse(BilibiliLabels.matchesSubmissionTime("2分钟前 广东", armed, armed + 5_000)) + assertFalse(BilibiliLabels.matchesSubmissionTime("刚刚 广东", armed, armed - 1)) + } +} diff --git a/app/src/test/java/com/jieliu/app/platform/BilibiliPhotoPickerTest.kt b/app/src/test/java/com/jieliu/app/platform/BilibiliPhotoPickerTest.kt new file mode 100644 index 0000000..2ac7360 --- /dev/null +++ b/app/src/test/java/com/jieliu/app/platform/BilibiliPhotoPickerTest.kt @@ -0,0 +1,29 @@ +package com.jieliu.app.platform + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class BilibiliPhotoPickerTest { + private val vertical = stripedPhoto(vertical = true) + private val horizontal = stripedPhoto(vertical = false) + + @Test fun selectsDistinctThumbnailsInConfiguredOrder() { + assertEquals(listOf(1, 0), bilibiliAttachmentOrder(listOf(vertical, horizontal), listOf(horizontal, vertical))) + } + + @Test fun rejectsAMissingOrAmbiguousThumbnail() { + assertNull(bilibiliAttachmentOrder(listOf(vertical, horizontal), listOf(vertical))) + assertNull(bilibiliAttachmentOrder(listOf(vertical, horizontal), listOf(vertical, vertical))) + assertNull(bilibiliAttachmentOrder(listOf(vertical, vertical), listOf(vertical, horizontal))) + } + + private fun stripedPhoto(vertical: Boolean): PhotoPixels { + val size = 48 + val pixels = IntArray(size * size) { i -> + val axis = if (vertical) i % size else i / size + if (axis / 8 % 2 == 0) 0xffab2c1e.toInt() else 0xff2baa95.toInt() + } + return PhotoPixels(size, size, pixels) + } +} diff --git a/app/src/test/java/com/jieliu/app/task/TaskRunnerTest.kt b/app/src/test/java/com/jieliu/app/task/TaskRunnerTest.kt index 16c9462..603b658 100644 --- a/app/src/test/java/com/jieliu/app/task/TaskRunnerTest.kt +++ b/app/src/test/java/com/jieliu/app/task/TaskRunnerTest.kt @@ -3,6 +3,7 @@ package com.jieliu.app.task import com.jieliu.app.platform.CommentPublishResult import com.jieliu.app.platform.CommentTarget import com.jieliu.app.platform.PlatformAdapter +import com.jieliu.app.platform.PlatformException import com.jieliu.app.platform.PlatformInteractionRestrictedException import com.jieliu.app.platform.PlatformRegistry import com.jieliu.app.platform.VideoContext @@ -14,6 +15,25 @@ import org.junit.Test import java.util.UUID class TaskRunnerTest { + @Test fun unsupportedBilibiliAttachmentStopsBeforeAnySendIntent() { + val store = RecordingStore(TaskCheckpoint("bilibili-no-picker", plan(firstType).copy(platformId = "bilibili"))) + val platform = FakePlatform(store, listOf(listOf(target("original", "API 充值")))).apply { + onPrepare = { requiresImages -> + assertTrue(requiresImages) + throw PlatformException("哔哩哔哩原回复的图片入口不可用") + } + } + + execute(store, platform) + + assertEquals(listOf("original"), platform.preparations) + assertEquals(0, store.pendingWrites) + assertEquals(0, platform.publishCalls) + assertNull(store.checkpoint.pending) + assertTrue(platform.attempts.isEmpty()) + assertTrue(store.checkpoint.receipts.isEmpty()) + } + @Test fun searchesTypeNameAndRepliesInThreadToTheMatchingKeywordAfterScrolling() { val plan = plan(firstType, secondType) val store = RecordingStore(TaskCheckpoint("type-search", plan)) @@ -444,6 +464,7 @@ class TaskRunnerTest { var knownBaseline = false var recheckResult = CommentPublishResult.UNCERTAIN var onScroll: () -> Unit = {} + var onPrepare: (Boolean) -> Unit = {} var beforePublish: () -> Unit = {} var afterPublish: () -> Unit = {} var onRecheck: () -> Unit = {} @@ -496,8 +517,9 @@ class TaskRunnerTest { return true } - override fun prepareReply(target: CommentTarget, expectedText: String): Boolean { + override fun prepareReply(target: CommentTarget, expectedText: String, requiresImages: Boolean): Boolean { preparations.add(target.key) + onPrepare(requiresImages) if (target.key in unavailable) return false preparedTexts.add(expectedText) replyTarget = target diff --git a/docs/ui-preview.html b/docs/ui-preview.html index 5676487..917045e 100644 --- a/docs/ui-preview.html +++ b/docs/ui-preview.html @@ -298,11 +298,11 @@

准备运行

-

抖音 · 仅浏览

-

内容类型 1 个 · 单次 3 个视频

- -

已处理视频 0 / 3 · 已确认回复 0 条

-

内容类型 · 模型服务

+

抖音 · 仅浏览

+

内容类型 1 个 · 单次 3 个视频

+ +

已处理视频 0 / 3 · 已确认回复 0 条

+

内容类型 · 模型服务

无障碍服务未连接

@@ -338,9 +338,9 @@
@@ -668,8 +668,7 @@ }); } platformPicker.addEventListener("change", () => { - const notes = platformPicker.value === "xiaohongshu"; - const unit = notes ? "笔记" : "视频"; + const unit = platformPicker.selectedOptions[0].dataset.unit; byId("content-limit-label").textContent = `单次任务${unit}上限`; byId("reply-limit-label").textContent = `每条${unit}回复上限`; byId("reply-scope-hint").textContent = `达到回复上限或找不到更多匹配评论时,进入下一个${unit}。`; @@ -678,16 +677,27 @@ byId("save-preview").addEventListener("click", () => { const status = byId("library-status"); const invalid = [byId("video-limit"), byId("replies-per-video")].find(input => !input.validity.valid); - let error = invalid ? `${invalid.labels[0].textContent}须为 1–100 的整数。` : ""; - let focus = invalid; - if (platformPicker.value === "bilibili") { - error = "哔哩哔哩还未适配,请选择已接入的平台。"; - focus = platformPicker; + const error = invalid ? `${invalid.labels[0].textContent}须为 1–100 的整数。` : ""; + if (!error) { + const platform = platformPicker.selectedOptions[0]; + const unit = platform.dataset.unit; + const limit = byId("video-limit").valueAsNumber; + const selectedType = pick(types, scope); + const searchTypes = selectedType ? [selectedType] : types; + const type = byId("task-content-type"); + const progress = byId("task-progress"); + byId("task-mode").textContent = `${platform.text} · ${byId("reply-mode").value}`; + byId("task-scope").textContent = `内容类型 ${searchTypes.length} 个 · 单次 ${limit} 个${unit}`; + byId("task-summary").textContent = `已处理${unit} 0 / ${limit} · 已确认回复 0 条`; + progress.max = limit; + progress.setAttribute("aria-label", `已处理 0 个${unit},共 ${limit} 个`); + type.hidden = searchTypes.length === 0; + type.textContent = searchTypes.length ? `内容类型 · ${searchTypes[0].name}` : ""; } status.textContent = error || "预览配置已更新。"; status.classList.toggle("error", Boolean(error)); status.hidden = false; - focus?.focus({ preventScroll: true }); + invalid?.focus({ preventScroll: true }); status.scrollIntoView({ block: "nearest", inline: "nearest" }); }); redrawLibrary(); diff --git a/docs/开发进度.md b/docs/开发进度.md index 815d163..dee7c97 100644 --- a/docs/开发进度.md +++ b/docs/开发进度.md @@ -1,6 +1,22 @@ # 拾见开发进度 -最近更新于 2026-11-27 09:27(UTC+8)。以下按开发轮次倒序记录。 +最近更新于 2026-11-27 10:24(UTC+8)。以下按开发轮次倒序记录。 + +## 2026-11-27 · 拾见 0.1.24 哔哩哔哩真机联调 + +- 在 vivo Android 12、哔哩哔哩 9.21.0(9210300)上联调。首次跨应用打开按此前设置选择「始终打开」。已补充真机首页搜索入口、动态搜索提示、结果页关键词、播放器完整标题,以及新版评论列表和回复控件的识别。 +- 10:20:42 从「开始任务」冷启动哔哩哔哩,自动搜索「国外大模型充值」并连续观看两条不同视频,10:21:02 写入两条 `WATCHED`。 +- 10:22:43 用最终安装包从「开始任务」冷启动。保留原有话术和两张绑定图,临时采用现场可见的关键词。10:23:00 自动核对匹配评论和指向原评论作者的空白回复框,记录图片入口不可用并在提交前停止。两个任务从启动到结果都没有手动操作哔哩哔哩,实发记录为 0,待核对记录为 0。 +- 同一视频的顶层评论编辑器有独立图片按钮。从评论列表和「评论详情」进入的定向回复均没有该按钮,展开「插入内容」也没有显示图片选项。楼中楼双图实发及正文、图片的自动回执仍待验收。 [哔哩哔哩发图说明](https://www.bilibili.com/opus/752428294212681795) +- 离线构建和 63 项 JVM 单测通过,Lint 为 0 个错误、4 个既有警告。0.1.24 调试 APK 通过 v2 签名校验,已覆盖安装,设备包与本地 APK 的 SHA-256 一致。已恢复手机原配置、原检查点和无障碍设置,并归档本轮测试证据。 + +## 2026-11-27 · 拾见 0.1.23 哔哩哔哩适配 + +- 接入哔哩哔哩标准版普通视频。按内容类型名称搜索,在评论区逐屏匹配关键词,随机轮换对应话术并保留绑定图片的顺序。任务上限和单视频回复上限均按视频推进。 +- 提交前核对视频、原评论、回复框和草稿附件。提交后在同一任务里回读原评论下的本人回复,核对同一条回复的正文、全部图片及顺序,再写入 `SENT`。回读证据不足时保留待核对记录。 +- 离线编译出调试 APK,已通过 v2 签名校验,并确认包内无障碍配置包含哔哩哔哩。63 项 JVM 单测通过,覆盖回复对象与标签识别、图片选择和顺序、图片入口缺失时在提交前停止等场景。Lint 为 0 个错误、4 个既有警告。 +- 静态预览在离线 Chrome 的 1440 和 390 像素宽度通过验证,覆盖平台选择、保存回复模式、绑定并排序两张图片,以及抖音和小红书计数单位回归。 +- Android 真机联调待进行。哔哩哔哩公开的多图说明适用于视频评论区的带图笔记,楼中楼回复是否有图片入口需在目标手机和账号上验证。若楼中楼缺少图片入口,带图任务会在提交前暂停。 [哔哩哔哩发图说明](https://www.bilibili.com/opus/752428294212681795) ## 2026-11-27 · 拾见 0.1.22 小红书连续真机验收