From d5ea3162e8c48c0c37c22d3e64900c5ab918193a Mon Sep 17 00:00:00 2001 From: huanghaohao <759903577@qq.com> Date: Fri, 27 Nov 2026 15:25:45 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8E=A5=E5=85=A5=E5=BF=AB=E6=89=8B=E5=9B=BE?= =?UTF-8?q?=E7=89=87=E5=92=8C=E8=A7=86=E9=A2=91=E4=BD=9C=E5=93=81=E7=9A=84?= =?UTF-8?q?=E8=AF=84=E8=AE=BA=E5=9B=9E=E5=A4=8D=E6=B5=81=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 支持按内容类型搜索、轮流浏览图片和视频、匹配评论关键词以及核对绑定多图和同线程回执。记录已完成的装机验证与待验收项。 --- README.md | 18 +- app/build.gradle.kts | 4 +- app/src/main/AndroidManifest.xml | 1 + .../main/java/com/jieliu/app/MainActivity.kt | 7 +- .../com/jieliu/app/platform/AccessibleUi.kt | 9 +- .../jieliu/app/platform/KuaishouAdapter.kt | 80 ++++ .../jieliu/app/platform/KuaishouComments.kt | 273 ++++++++++++++ .../jieliu/app/platform/KuaishouNavigation.kt | 309 +++++++++++++++ .../app/platform/KuaishouPhotoPicker.kt | 285 ++++++++++++++ .../jieliu/app/platform/KuaishouReplies.kt | 356 ++++++++++++++++++ .../jieliu/app/platform/PlatformAdapter.kt | 11 +- app/src/main/res/values/strings.xml | 2 +- app/src/main/res/xml/accessibility_config.xml | 2 +- docs/ui-preview.html | 5 +- docs/开发进度.md | 12 +- 15 files changed, 1354 insertions(+), 20 deletions(-) create mode 100644 app/src/main/java/com/jieliu/app/platform/KuaishouAdapter.kt create mode 100644 app/src/main/java/com/jieliu/app/platform/KuaishouComments.kt create mode 100644 app/src/main/java/com/jieliu/app/platform/KuaishouNavigation.kt create mode 100644 app/src/main/java/com/jieliu/app/platform/KuaishouPhotoPicker.kt create mode 100644 app/src/main/java/com/jieliu/app/platform/KuaishouReplies.kt diff --git a/README.md b/README.md index 874d938..b78768e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 拾见 -拾见是独立运行的安卓 APK,以内容类型名称搜索。抖音和小红书支持浏览、关键词匹配、多图回复和自动回执,均有连续真机验收记录。哔哩哔哩的普通视频适配已进入真机联调,见[开发进度](docs/开发进度.md)。 +拾见是独立运行的安卓 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 @@ -56,6 +56,10 @@ powershell -NoProfile -File ./scripts/verify-apk.ps1 选择「小红书」后,可设置单次任务笔记上限和每条笔记回复上限。任务会按内容类型搜索,停留到设定时长后返回结果列表打开下一条笔记。部分 vivo 设备首次会弹出跨应用打开提示,确认是「拾见」打开「小红书」后可选择「始终打开」。若等待超时,返回拾见点「继续任务」。 选择「哔哩哔哩」并启用评论匹配后,可在「评论发布位置」选择「回复原评论(仅文字)」或「发布视频评论(可带图片)」。两种方式都用命中的评论关键字选择同一话术库。回复原评论时只提交正文,图片绑定仍保留在话术库。发布视频评论时,正文和按配置顺序绑定的图片一起提交到当前视频的评论区。绑定图无法核对时会在提交前暂停。 [哔哩哔哩发图说明](https://www.bilibili.com/opus/752428294212681795) + + 选择「快手」后,拾见按内容类型名称搜索,优先进入结果上方的「图片」。两栏有可用作品时,轮流处理「图片」和「视频」。两类作品共用单次任务上限、评论关键字和话术库。可用「仅浏览」并将单次任务上限设为至少 2,确认两类作品都能打开。 + + 快手原评论的回复框提供「发布图片」。在话术库配置绑定图后,拾见通过快手相册的「多选」添加图片。快手首次打开相册可能提示授权。任一绑定图无法添加或核对时,任务会在提交前暂停。 4. 在「任务」点「开始任务」。保持手机解锁,由拾见打开目标平台。运行期间让目标平台留在前台。在拾见任务页或用通知栏按钮可暂停。登录、验证、页面布局不可识别等中断可在手机处理后点「继续任务」。 5. 发送后,拾见按本次任务选择的位置核对新增的本人评论。定向回复在原评论线程内核对,哔哩哔哩视频评论在同一视频的按时间评论列表中核对。带图评论还需要同一条评论的正文、所有图片和配置顺序一致。图文自动核对需要 Android 11 或更新版本,图片比对在手机内存中完成。可从待核对卡片启动自动核对,或核对后手动确认或跳过。待核对期间会阻止自动重发。 @@ -65,12 +69,12 @@ powershell -NoProfile -File ./scripts/verify-apk.ps1 | 配置 | 说明 | | --- | --- | -| 目标平台 | 抖音标准版 `com.ss.android.ugc.aweme`、小红书 `com.xingin.xhs`、哔哩哔哩标准版 `tv.danmaku.bili`。 | +| 目标平台 | 抖音标准版 `com.ss.android.ugc.aweme`、小红书 `com.xingin.xhs`、哔哩哔哩标准版 `tv.danmaku.bili`、快手标准版 `com.smile.gifmaker`。 | | 内容类型 | 类型名称直接用于目标平台搜索。「全部类型」按类型顺序尽量均分任务总数,余数优先分给前面的类型。也可只运行一个类型。 | | 评论关键字 | 每个类型可增删改多条关键字。每个关键字对应独立话术库。匹配基于评论正文,兼容全角半角、英文字母大小写和常见中英文空格;重叠时优先选更长的匹配。 | -| 单次任务上限 | 共处理 1–100 项,抖音和哔哩哔哩按视频计数,小红书按笔记计数。浏览完成或扫描后没有可回复的评论均计入进度。 | -| 每条视频或笔记回复上限 | 默认 1 条,可设为 1–100 条。在匹配回复模式下,已确认发送的回复计入上限。达标、评论列表到末尾或扫描范围内没有更多匹配时,浏览下一条。 | -| 观看时长 | 1–300 秒的闭区间,逐视频或笔记取样,默认 5–12 秒。 | +| 单次任务上限 | 共处理 1–100 项,抖音和哔哩哔哩按视频计数,小红书按笔记计数,快手按作品计数。浏览完成或扫描后没有可回复的评论均计入进度。 | +| 每条内容回复上限 | 默认 1 条,可设为 1–100 条。在匹配回复模式下,已确认发送的回复计入上限。达标、评论列表到末尾或扫描范围内没有更多匹配时,浏览下一条。 | +| 观看时长 | 每条内容停留 1–300 秒,从配置区间内取样,默认 5–12 秒。 | | 动作间隔 | 150–30,000 毫秒的闭区间,默认 600–1,800 毫秒。评论滑动在列表内变化起点、距离、轨迹、时长和停留时间,每条内容最多滑动 12 次并在每屏重新读取。 | | 处理方式 | 「仅浏览」观看视频或浏览笔记。评论匹配模式逐屏读取评论,按命中的关键字选话术。同一任务内每条命中的评论最多触发一次提交。 | | 哔哩哔哩评论发布位置 | 「回复原评论(仅文字)」是旧配置的默认值。「发布视频评论(可带图片)」按视频计入发布上限。两种方式共享话术库,新任务使用保存的发布方式。 | @@ -97,7 +101,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 ae1daf2..4eaaaf2 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 = 41 - versionName = "0.1.40" + versionCode = 42 + versionName = "0.1.41" } compileOptions { diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index b7fe0b9..af2db94 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -9,6 +9,7 @@ + "达到发布上限或找不到更多匹配评论时,进入下一个$unit。" else -> "达到回复上限或找不到更多匹配评论时,进入下一个$unit。" } - libraryHint.text = if (browseOnly) "按内容类型搜索$unit。" - else "按内容类型搜索$unit,按关键词匹配评论。每个关键词可配置多条话术。" + libraryHint.text = when { + browseOnly -> "按内容类型搜索$unit。" + spec.id == "kuaishou" -> "按内容类型搜索,轮流处理「图片」和「视频」中的作品。每个关键词可配置多条话术。" + else -> "按内容类型搜索$unit,按关键词匹配评论。每个关键词可配置多条话术。" + } } updatePlatformCopy(specs[selectedPlatform]) val commentSettingsChanged = object : AdapterView.OnItemSelectedListener { 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 0d8fd72..ad41c92 100644 --- a/app/src/main/java/com/jieliu/app/platform/AccessibleUi.kt +++ b/app/src/main/java/com/jieliu/app/platform/AccessibleUi.kt @@ -29,12 +29,13 @@ import kotlin.random.Random /** Uses fresh, target-package-scoped nodes and recycles every reference after each read or action. */ @Suppress("DEPRECATION") -internal class AccessibleUi( +internal class AccessibleUi @JvmOverloads constructor( private val service: AccessibilityService, private val packageName: String, private val cancelled: () -> Boolean, private val pauseBetweenActions: () -> Unit, private val checkPage: ((UiPage) -> Unit)? = null, + private val nodeLimit: Int = 450, ) { private val mainHandler = Handler(Looper.getMainLooper()) @@ -48,7 +49,7 @@ internal class AccessibleUi( checkCancelled() } - fun launchTarget(appName: String) { + fun launchTarget(appName: String, foregroundTimeoutMs: Long = 12_000) { checkCancelled() if (inspect { true } == true) return val launch = service.packageManager.getLaunchIntentForPackage(packageName) @@ -60,7 +61,7 @@ internal class AccessibleUi( } catch (error: android.content.ActivityNotFoundException) { throw PlatformException("未找到${appName}的启动界面", error) } - await(12_000) { inspect { true } } ?: throw PlatformException("等待${appName}进入前台超时") + await(foregroundTimeoutMs) { inspect { true } } ?: throw PlatformException("等待${appName}进入前台超时") } fun inspect(action: (UiPage) -> T): T? = inspect(false, action) @@ -275,7 +276,7 @@ internal class AccessibleUi( } } val childCount = node.childCount - val limit = childCount.coerceAtMost(450 - references.size) + val limit = childCount.coerceAtMost(nodeLimit - references.size) if (limit < childCount) complete = false for (index in 0 until limit) { checkCancelled() diff --git a/app/src/main/java/com/jieliu/app/platform/KuaishouAdapter.kt b/app/src/main/java/com/jieliu/app/platform/KuaishouAdapter.kt new file mode 100644 index 0000000..c178f8d --- /dev/null +++ b/app/src/main/java/com/jieliu/app/platform/KuaishouAdapter.kt @@ -0,0 +1,80 @@ +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 KuaishouAdapter( + spec: PlatformSpec, + ui: AccessibleUi, + photos: PhotoLibrary, + diagnostic: (String) -> Unit, +) : PlatformAdapter { + private val navigation = KuaishouNavigation(spec, ui) + private val comments = KuaishouComments(ui, navigation::matchesContent, navigation::openCommentPanel) + private val replies = KuaishouReplies(ui, comments, photos, diagnostic) + private var openWork: VideoContext? = null + + 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).also { openWork = expected } + + override fun scanComments(): List = 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 (openWork != video || pending.videoKey != video.key || !comments.isOpenFor(video)) return null + return confirmPendingReply(video, pending) + } + + override fun confirmPendingReply(video: VideoContext, pending: PendingComment): CommentPublishResult { + if (openWork != video || pending.videoKey != video.key || !comments.isOpenFor(video)) { + return CommentPublishResult.UNCERTAIN + } + val target = pending.targetKey ?: return CommentPublishResult.UNCERTAIN + val author = pending.targetAuthor ?: return CommentPublishResult.UNCERTAIN + val armedAt = pending.armedAtEpochMs ?: return CommentPublishResult.UNCERTAIN + return replies.confirm(target, author, pending.text, pending.photos, armedAt) + } + + override fun closeComments() { + if (replies.hasUnsettledEditor()) throw PlatformException("请核对快手中打开的回复草稿后继续") + replies.reset() + comments.close() + openWork = null + } +} diff --git a/app/src/main/java/com/jieliu/app/platform/KuaishouComments.kt b/app/src/main/java/com/jieliu/app/platform/KuaishouComments.kt new file mode 100644 index 0000000..7a44d81 --- /dev/null +++ b/app/src/main/java/com/jieliu/app/platform/KuaishouComments.kt @@ -0,0 +1,273 @@ +package com.jieliu.app.platform + +import android.graphics.Rect +import android.view.accessibility.AccessibilityNodeInfo +import java.io.Closeable +import java.security.MessageDigest + +internal class KuaishouComments( + private val ui: AccessibleUi, + private val matchesContent: (UiPage, VideoContext) -> Boolean, + private val openCommentPanel: (UiPage, VideoContext) -> Boolean, +) { + internal data class Panel(val root: UiNode, val list: UiNode?, val close: UiNode, val full: UiNode?, val empty: Boolean) + + internal data class Row( + val target: CommentTarget, + val container: UiNode, + val body: UiNode, + val reply: UiNode?, + val time: String?, + val photos: List?, + val own: Boolean, + ) + + internal data class Thread(val original: Row, val replies: List, val complete: Boolean, val expand: UiNode?) + + private data class Item(val wrapper: UiNode, val kind: Kind, val row: Row?, val expand: UiNode?) + private enum class Kind { ORIGINAL, NESTED, MORE, FOLD, END, UNKNOWN } + + private class Session( + val video: VideoContext, + val window: Int, + val root: UiNodeSource, + ) : Closeable { + override fun close() = root.close() + } + + private var active: Session? = null + + fun isOpenFor(video: VideoContext): Boolean = active?.video == video + + fun open(video: VideoContext): List { + check(active == null) { "请先退出上一个快手评论区" } + ui.pace() + val origin = ui.inspect { page -> + if (!matchesContent(page, video) || page.hasKuaishouCommentDraft()) return@inspect null + page.windowId.takeIf { readPanel(page) != null || openCommentPanel(page, video) } + } ?: throw PlatformException("未能核对当前快手作品及其评论入口") + active = ui.await(7_000) { + ui.inspect { page -> + if (!page.complete || page.windowId != origin) return@inspect null + readPanel(page)?.let { Session(video, page.windowId, it.root.retainSource()) } + } + } ?: throw PlatformException("未能读取当前快手作品的评论区") + return scan() + } + + fun scan(): List = ui.await(3_000) { + ui.inspect { page -> + val session = active ?: return@inspect null + val panel = panel(page) ?: return@inspect null + if (page.hasKuaishouCommentDraft()) return@inspect null + originalRows(page, panel, session.video.key).filter { it.reply != null && !it.own }.map(Row::target) + } + } ?: throw PlatformException("快手评论区已变化") + + fun scroll(): Boolean { + ui.pace() + val before = ui.inspect { page -> + val panel = panel(page)?.takeUnless(Panel::empty) ?: return@inspect null + if (page.hasKuaishouCommentDraft()) return@inspect null + val list = panel.list?.takeIf { it.scrollable && it.bounds.height() >= page.bounds.height() / 7 } + ?: return@inspect null + val positions = positions(page, list) + positions.takeIf { it.isNotEmpty() && ui.scrollUpInside(list.bounds) } + } ?: return false + return ui.await(2_500) { + ui.inspect { page -> + val list = panel(page)?.list ?: return@inspect null + val after = positions(page, list) + true.takeIf { after.isNotEmpty() && before != after } + } + } == true + } + + fun close() { + val session = active ?: return + ui.pace() + val closed = ui.inspect { page -> + if (page.hasKuaishouCommentDraft()) return@inspect false + if (readPanel(page) == null && matchesContent(page, session.video)) return@inspect true + val panel = panel(page) ?: return@inspect false + ui.click(panel.close) + } == true + if (!closed || ui.await(4_000) { + ui.inspect { page -> true.takeIf { readPanel(page) == null && matchesContent(page, session.video) } } + } != true + ) throw PlatformException("关闭快手评论区后未能核对同一作品") + active = null + session.close() + } + + fun panel(page: UiPage): Panel? { + val session = active ?: return null + if (page.windowId != session.window || !page.complete) return null + return readPanel(page)?.takeIf { it.root.hasSource(session.root) } + } + + fun readThread(key: String, author: String, action: (UiPage, Panel, Thread) -> T): T? = + ui.inspect { page -> + val session = active ?: return@inspect null + val panel = panel(page) ?: return@inspect null + if (page.hasKuaishouCommentDraft()) return@inspect null + val row = originalRows(page, panel, session.video.key) + .singleOrNull { it.target.key == key && it.target.author == author } ?: return@inspect null + action(page, panel, readThread(page, panel, row, session.video.key)) + } + + fun ensureThread(key: String, author: String): Boolean { + val before = readThread(key, author) { _, panel, thread -> + thread.complete to (panel.full != null) + } ?: return false + if (before.first) return true + if (before.second) { + ui.pace() + if (readThread(key, author) { _, panel, _ -> panel.full?.let { ui.click(it) } } == true) { + val after = ui.await(3_500) { + readThread(key, author) { _, panel, thread -> thread.complete.takeIf { panel.full == null } } + } + if (after == true) return true + } + } + ui.pace() + val expanded = readThread(key, author) { _, _, thread -> + thread.expand?.let { ui.click(it) } + } == true + if (!expanded) return false + return ui.await(3_500) { + readThread(key, author) { _, _, thread -> true.takeIf { thread.complete } } + } == true + } + + private fun readPanel(page: UiPage): Panel? { + val container = page.nodes.singleOrNull { it.resourceId == "comment_panel_container" } ?: return null + val root = page.nodes.singleOrNull { + it.resourceId == "tabs_panel_container" && it.isDescendantOf(container) && + container.bounds.contains(it.bounds) && it.bounds.width() >= page.bounds.width() * .8 + } ?: return null + val styles = page.nodes.singleOrNull { it.resourceId == "tabs_panel_style" && it.directParent() === root } + ?: return null + val close = page.nodes.singleOrNull { + it.resourceId == "tabs_panel_close" && it.labels() == listOf("关闭评论区") && it.clickable && + it.isDescendantOf(styles) && styles.bounds.contains(it.bounds) + } ?: return null + val full = page.nodes.singleOrNull { + it.resourceId == "tabs_panel_full" && it.labels() == listOf("展开评论区") && it.clickable && + it.directParent() === close.directParent() && styles.bounds.contains(it.bounds) + } + val heading = page.nodes.singleOrNull { + it.resourceId == "tab_text" && it.selected && commentCount.matches(it.text) && + it.isDescendantOf(styles) && styles.bounds.contains(it.bounds) + } ?: return null + val empty = heading.text in setOf("0条评论", "评论0") + val frame = page.nodes.singleOrNull { + it.resourceId == "slide_play_comment_frame" && it.isDescendantOf(root) && + it.bounds.top >= styles.bounds.bottom && root.bounds.contains(it.bounds) + } ?: return null + val list = page.nodes.singleOrNull { + it.resourceId == "recycler_view" && it.className == "androidx.recyclerview.widget.RecyclerView" && + it.directParent() === frame && frame.bounds.contains(it.bounds) && + it.bounds.width() >= frame.bounds.width() * .9 + } + if (!empty && list == null) return null + return Panel(root, list, close, full, empty) + } + + private fun originalRows(page: UiPage, panel: Panel, key: String): List = + visibleItems(page, panel, key).filter { it.kind == Kind.ORIGINAL }.mapNotNull(Item::row) + + private fun readThread(page: UiPage, panel: Panel, row: Row, key: String): Thread { + val list = panel.list ?: return Thread(row, emptyList(), false, null) + val items = visibleItems(page, panel, key) + val index = items.indexOfFirst { it.row?.container === row.container } + if (index < 0) return Thread(row, emptyList(), false, null) + val following = items.drop(index + 1) + val section = following.takeWhile { it.kind != Kind.ORIGINAL && it.kind != Kind.END } + val replies = section.filter { it.kind == Kind.NESTED } + val continuation = section.filter { it.kind == Kind.MORE }.singleOrNull()?.expand + val boundaryVisible = following.size > section.size + val tail = section.lastOrNull()?.wrapper ?: items[index].wrapper + val completeRows = section.dropLast(if (section.lastOrNull()?.kind == Kind.FOLD) 1 else 0) + val complete = completeRows.all { it.kind == Kind.NESTED && it.row != null } && + (boundaryVisible || (list.bounds.contains(tail.bounds) && + !list.supports(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD))) + return Thread(row, replies.mapNotNull(Item::row), complete, continuation) + } + + private fun visibleItems(page: UiPage, panel: Panel, key: String): List { + val list = panel.list ?: return emptyList() + return page.nodes.filter { it.directParent() === list && Rect.intersects(list.bounds, it.bounds) } + .sortedBy { it.bounds.top }.map { wrapper -> readItem(page, list, wrapper, key) } + } + + private fun readItem(page: UiPage, list: UiNode, wrapper: UiNode, key: String): Item { + val children = page.nodes.filter { it.directParent() === wrapper } + val end = children.singleOrNull { it.resourceId == "no_more_container" } + if (end != null && page.nodes.count { + it.directParent() === end && it.resourceId == "no_more_content" && it.labels() == listOf("没有更多评论") + } == 1) return Item(wrapper, Kind.END, null, null) + val more = children.singleOrNull { it.resourceId == "more_root_layout" } + if (more != null) { + val expand = page.nodes.singleOrNull { + it.resourceId == "sub_comment_more" && it.isDescendantOf(more) && it.enabled && it.clickable && + more.bounds.contains(it.bounds) && moreReplies.matches(it.text) + } + val fold = expand == null && page.nodes.count { + it.resourceId == "sub_comment_fold" && it.isDescendantOf(more) && it.labels() == listOf("收起") && + it.enabled && it.clickable && more.bounds.contains(it.bounds) + } == 1 + return Item(wrapper, if (fold) Kind.FOLD else Kind.MORE, null, expand) + } + val container = children.singleOrNull { it.resourceId == "comment_frame" && it.clickable } + ?: return Item(wrapper, Kind.UNKNOWN, null, null) + val avatar = page.nodes.singleOrNull { it.resourceId == "avatar" && it.directParent() === container } + ?: return Item(wrapper, Kind.UNKNOWN, null, null) + val offset = avatar.bounds.left - list.bounds.left + val kind = when { + offset in 0..(list.bounds.width() / 10) -> Kind.ORIGINAL + offset in (list.bounds.width() * .13).toInt()..(list.bounds.width() * .32).toInt() -> Kind.NESTED + else -> Kind.UNKNOWN + } + return Item(wrapper, kind, readRow(page, list, container, key), null) + } + + private fun readRow(page: UiPage, list: UiNode, container: UiNode, key: String): Row? { + val members = page.nodes.filter { it.isDescendantOf(container) && container.bounds.contains(it.bounds) } + val author = members.singleOrNull { it.resourceId == "name" && it.text.isNotBlank() } ?: return null + val body = members.singleOrNull { it.resourceId == "comment" && it.text.isNotBlank() } ?: return null + val time = members.singleOrNull { + it.resourceId in timeIds && it.text.isNotBlank() && it.bounds.top >= body.bounds.bottom + } ?: return null + if (author.bounds.bottom > body.bounds.top || list.bounds.top >= author.bounds.top || + list.bounds.bottom <= time.bounds.bottom || list.bounds.top >= container.bounds.bottom) return null + val reply = members.singleOrNull { + it.resourceId == "comment_reply" && it.labels() == listOf("回复") && it.enabled && it.clickable && + it.bounds.top >= body.bounds.bottom && list.bounds.contains(it.bounds) + } + val pictures = members.filter { it.resourceId == "comment_image" } + val pictureGroups = members.filter { it.resourceId == "layout_emotion_image" } + val photos = pictures.takeIf { images -> + pictureGroups.all { group -> images.any { it.isDescendantOf(group) } } && + images.all { it.bounds.top >= body.bounds.bottom && it.bounds.bottom <= time.bounds.top && + pictureGroups.count { group -> it.isDescendantOf(group) } == 1 && list.bounds.contains(it.bounds) } + }?.sortedWith(compareBy({ it.bounds.top }, { it.bounds.left })) + val target = CommentTarget(targetKey(key, author.text, body.text), body.text, author.text) + val own = members.any { it.resourceId == "comment_author_tag" && it.labels() == listOf("本人") } + return Row(target, container, body, reply, time.text, photos, own) + } + + private fun positions(page: UiPage, list: UiNode): List, Rect>> = page.nodes + .filter { it.isDescendantOf(list) && it.labels().isNotEmpty() && list.bounds.contains(it.bounds) } + .map { it.labels() to Rect(it.bounds) } + + private fun targetKey(videoKey: String, author: String, body: String): String = + MessageDigest.getInstance("SHA-256").digest("$videoKey\u0000$author\u0000$body".toByteArray(Charsets.UTF_8)) + .joinToString("") { "%02x".format(it) } + + private companion object { + val commentCount = Regex("(?:\\d+(?:\\.\\d+)?万?条评论|评论\\d+(?:\\.\\d+)?万?)") + val moreReplies = Regex("展开[1-9]\\d*条回复") + val timeIds = setOf("comment_created_time_and_loc", "comment_caption_meta_info") + } +} diff --git a/app/src/main/java/com/jieliu/app/platform/KuaishouNavigation.kt b/app/src/main/java/com/jieliu/app/platform/KuaishouNavigation.kt new file mode 100644 index 0000000..c72ed66 --- /dev/null +++ b/app/src/main/java/com/jieliu/app/platform/KuaishouNavigation.kt @@ -0,0 +1,309 @@ +package com.jieliu.app.platform + +import android.graphics.Rect +import java.security.MessageDigest +import kotlin.math.abs + +internal class KuaishouNavigation(private val spec: PlatformSpec, private val ui: AccessibleUi) { + private enum class Kind(val label: String, val slot: Int) { IMAGE("图片", 1), VIDEO("视频", 2) } + + private data class SearchEditor(val input: UiNode, val submit: UiNode) + private data class Results(val query: UiNode, val back: UiNode, val tabs: Map, val list: UiNode?) + private data class Card(val node: UiNode, val author: String, val date: String, val imageMark: Boolean) { + val identity: Pair get() = author to date + } + private data class Player(val kind: Kind, val author: String, val date: String, val caption: String, + val comment: UiNode, val back: UiNode) { + fun matches(card: Card): Boolean = author == card.author && date == card.date + } + private data class Work(val context: VideoContext, val kind: Kind, val window: Int) + private data class Opened(val card: Card, val bound: Work?) + + private var query: String? = null + private var active: Work? = null + private val visited = mutableSetOf() + private val examined = Kind.entries.associateWith { mutableSetOf>() } + private val exhausted = mutableSetOf() + + fun launch() = ui.launchTarget(spec.label, foregroundTimeoutMs = 28_000) + + fun search(keyword: String): VideoContext { + val searchText = keyword.trim().takeIf(String::isNotEmpty) + ?: throw PlatformException("快手搜索关键词为空") + active?.let { leave(it) } + openSearch() + ui.pace() + val written = ui.await(4_000) { + ui.inspect { page -> + val editor = page.searchEditor()?.input ?: return@inspect null + if (!editor.hasCurrentInputFocus()) { + ui.click(editor) + return@inspect null + } + editor.text == searchText && !editor.showingHint || ui.setText(editor, searchText) + } + } == true + if (!written) throw PlatformException("快手搜索框未接受关键词") + ui.pace() + val submitted = ui.await(4_000) { + ui.inspect { page -> + val editor = page.searchEditor()?.takeIf { it.input.text == searchText && !it.input.showingHint } + ?: return@inspect null + ui.click(editor.submit) + } + } == true + if (!submitted || ui.await(8_000) { ui.inspect { it.results(searchText)?.query?.text } } != searchText) { + throw PlatformException("快手未显示对应关键词的搜索结果和分类栏") + } + query = searchText + visited.clear() + exhausted.clear() + examined.values.forEach { it.clear() } + return openNext(Kind.IMAGE) + } + + fun currentVideo(): VideoContext = active?.let { work -> + ui.await(4_000) { ui.inspect { page -> work.context.takeIf { matchesContent(page, it) } } } + } ?: throw PlatformException("未能核对当前快手作品") + + fun nextVideo(previous: VideoContext): VideoContext { + val work = active?.takeIf { it.context == previous } ?: throw PlatformException("快手当前作品已变化") + leave(work) + return openNext(if (work.kind == Kind.IMAGE) Kind.VIDEO else Kind.IMAGE) + } + + fun matchesContent(page: UiPage, expected: VideoContext): Boolean { + val work = active?.takeIf { it.context == expected && it.window == page.windowId } ?: return false + val player = page.player() ?: return false + return player.kind == work.kind && player.context() == expected + } + + fun openCommentPanel(page: UiPage, expected: VideoContext): Boolean = + matchesContent(page, expected) && page.player()?.comment?.let { ui.click(it) } == true + + private fun openSearch() { + repeat(6) { + val action = ui.await(5_000) { + ui.inspect { page -> + if (page.hasKuaishouCommentDraft()) throw PlatformException("请先处理快手中打开的评论草稿") + if (page.searchEditor() != null) return@inspect "ready" + val control = page.nodes.singleOrNull { it.resourceId == "tabs_panel_close" && + it.description == "关闭评论区" && it.kuaishouAction() } + ?: page.player()?.back + ?: page.results()?.back + ?: page.nodes.singleOrNull { it.resourceId == "nasa_featured_default_search_view" && + it.description == "查找" && it.kuaishouAction() } + ?: return@inspect null + ui.pace() + "moved".takeIf { ui.click(control) } + } + } + if (action == "ready") return + if (action == null) throw PlatformException("未找到快手的搜索入口") + } + throw PlatformException("未能打开快手的搜索框") + } + + private fun leave(work: Work) { + ui.pace() + val returned = ui.inspect { page -> + matchesContent(page, work.context) && page.player()?.back?.let { ui.click(it) } == true + } == true + if (!returned || !awaitResults()) throw PlatformException("未能从同一快手作品返回搜索结果") + active = null + } + + private fun awaitResults(): Boolean = ui.await(6_000) { + ui.inspect { page -> true.takeIf { page.results(query) != null } } + } == true + + private fun openNext(preferred: Kind): VideoContext { + val searchText = checkNotNull(query) + for (kind in listOf(preferred) + Kind.entries.filterNot { it == preferred }) { + if (kind in exhausted) continue + if (selectTab(searchText, kind)) { + findWork(searchText, kind)?.let { work -> + active = work + return work.context + } + } + exhausted.add(kind) + } + throw PlatformException("快手「图片」和「视频」中没有更多可核对的作品") + } + + private fun selectTab(searchText: String, kind: Kind): Boolean { + ui.pace() + val clicked = ui.await(4_000) { + ui.inspect { page -> + val tab = page.results(searchText)?.tabs?.get(kind) ?: return@inspect null + tab.selected || ui.click(tab) + } + } == true + return clicked && ui.await(6_000) { + ui.inspect { page -> true.takeIf { page.results(searchText)?.tabs?.get(kind)?.selected == true } } + } == true + } + + private fun findWork(searchText: String, kind: Kind): Work? { + val checked = examined.getValue(kind) + var screens = 0 + repeat(25) { + ui.pace() + val clicked = ui.await(4_500) { + ui.inspect { page -> + val results = page.results(searchText)?.takeIf { it.tabs[kind]?.selected == true } + ?: return@inspect null + val list = results.list ?: return@inspect null + val cards = page.cards(list) + if (cards.isEmpty()) return@inspect null + val unique = cards.groupingBy(Card::identity).eachCount() + val card = cards.filter { it.identity !in checked && unique[it.identity] == 1 && + (kind == Kind.IMAGE || !it.imageMark) } + .sortedWith(compareBy { !it.imageMark }.thenBy { it.node.bounds.top }.thenBy { it.node.bounds.left }) + .firstOrNull() + if (card == null) return@inspect Pick.None + checked.add(card.identity) + if (!ui.click(card.node)) throw PlatformException("未能打开已核对的快手搜索作品") + Pick.CardOpened(card) + } + } + if (clicked is Pick.CardOpened) { + val work = readOpened(clicked.card, kind) + if (work.bound != null && visited.add(work.bound.context.key)) return work.bound + val backed = ui.inspect { page -> page.player()?.takeIf { it.matches(work.card) } + ?.back?.let { ui.click(it) } == true } + if (backed != true || !awaitResults()) throw PlatformException("快手作品类型与所选分类不符,未能安全返回") + } else { + if (screens >= 6 || !scrollResults(searchText, kind)) return null + screens++ + } + } + return null + } + + private sealed interface Pick { + data class CardOpened(val card: Card) : Pick + data object None : Pick + } + + private fun readOpened(card: Card, expectedKind: Kind): Opened = ui.await(6_000) { + ui.inspect { page -> + val player = page.player()?.takeIf { it.matches(card) } ?: return@inspect null + Opened(card, Work(player.context(), player.kind, page.windowId).takeIf { player.kind == expectedKind }) + } + } ?: throw PlatformException("快手详情页未对应刚选中的结果卡片") + + private fun scrollResults(searchText: String, kind: Kind): Boolean { + val before = ui.inspect { page -> + val result = page.results(searchText)?.takeIf { it.tabs[kind]?.selected == true } ?: return@inspect null + val list = result.list?.takeIf { it.scrollable } ?: return@inspect null + page.cardPositions(list).takeIf { it.isNotEmpty() && ui.scrollUpInside(list.bounds) } + } ?: return false + return ui.await(3_000) { + ui.inspect { page -> + val list = page.results(searchText)?.takeIf { it.tabs[kind]?.selected == true }?.list + ?: return@inspect null + val after = page.cardPositions(list) + true.takeIf { after.isNotEmpty() && before != after } + } + } == true + } + + private fun UiPage.cardPositions(list: UiNode): List> = nodes.filter { + it.directParent() === list && it.resourceId == "container" && it.description.endsWith("的作品") + }.map { it.description to it.bounds.top } + + private fun UiPage.searchEditor(): SearchEditor? { + val top = nodes.singleOrNull { it.resourceId == "search_home_top_container" } ?: return null + val input = nodes.singleOrNull { it.resourceId == "editor" && it.editable && it.isDescendantOf(top) } ?: return null + val submit = nodes.singleOrNull { it.resourceId == "search_btn_container" && it.kuaishouAction() && + it.isDescendantOf(top) && it.bounds.left >= input.bounds.right } ?: return null + return SearchEditor(input, submit) + } + + private fun UiPage.results(expectedQuery: String? = null): Results? { + if (!complete) return null + val root = nodes.singleOrNull { it.resourceId == "search_result_view" && bounds.contains(it.bounds) } ?: return null + val header = nodes.singleOrNull { it.resourceId == "result_bar" && it.isDescendantOf(root) } ?: return null + val query = nodes.singleOrNull { it.resourceId == "search_result_text" && it.isDescendantOf(header) && + it.text.isNotBlank() && (expectedQuery == null || expectedQuery == it.text) } ?: return null + val back = nodes.singleOrNull { it.resourceId == "left_image" && it.isDescendantOf(header) && + it.kuaishouAction() && it.bounds.right <= query.bounds.left } ?: return null + val container = nodes.singleOrNull { it.resourceId == "tab_container" && it.isDescendantOf(root) && + it.bounds.top >= query.bounds.bottom && it.bounds.width() >= bounds.width() * .85 } ?: return null + val strip = nodes.singleOrNull { it.resourceId == "tabs" && it.directParent() === container && + it.className == "android.widget.HorizontalScrollView" } ?: return null + val bar = nodes.singleOrNull { it.directParent() === strip && it.className == "android.widget.LinearLayout" } ?: return null + val actions = nodes.filter { it.directParent() === bar && it.kuaishouAction() && bar.bounds.contains(it.bounds) } + .sortedBy { it.bounds.left } + val tabs = readSearchTabs(strip, actions) ?: return null + val recycler = nodes.singleOrNull { it.resourceId == "recycler_view" && it.isDescendantOf(root) && + it.bounds.top >= container.bounds.bottom && it.bounds.width() >= bounds.width() * .85 } + return Results(query, back, tabs, recycler) + } + + private fun readSearchTabs(strip: UiNode, actions: List): Map? { + val labelled = Kind.entries.mapNotNull { kind -> + actions.singleOrNull { kind.label in it.labels() }?.let { kind to it } + }.toMap() + if (labelled.size == Kind.entries.size) return labelled + // In the observed native tab bar the first three controls are unlabelled virtual hit regions. + val first = actions.take(3) + if (actions.size !in 4..7 || first.size != 3 || actions.count(UiNode::selected) != 1 || + first.first().bounds.left != strip.bounds.left || first.any { it.labels().isNotEmpty() || + it.className != "android.view.View" || it.bounds.height() != strip.bounds.height() || + it.bounds.width() !in (strip.bounds.width() / 6)..(strip.bounds.width() / 4) } || + first.zipWithNext().any { (left, right) -> left.bounds.right != right.bounds.left || + abs(left.bounds.width() - right.bounds.width()) > strip.bounds.width() / 30 } || + first.withIndex().any { (index, node) -> node.horizontalItemIndex?.let { it != index } == true } + ) return null + return Kind.entries.associateWith { actions[it.slot] } + } + + private fun UiPage.cards(list: UiNode): List = nodes.mapNotNull { row -> + if (row.directParent() !== list || row.resourceId != "container" || !row.kuaishouAction() || + !list.bounds.contains(row.bounds) || row.bounds.height() < list.bounds.width() / 4 + ) return@mapNotNull null + val author = row.description.takeIf { it.endsWith("的作品") }?.removeSuffix("的作品") + ?.takeIf(String::isNotBlank) ?: return@mapNotNull null + val descendants = nodes.filter { it.isDescendantOf(row) } + val date = descendants.singleOrNull { it.resourceId == "bottom_created_time" && it.text.isNotBlank() } + ?.text ?: return@mapNotNull null + if (descendants.none { it.resourceId == "cover_container" && it.directParent() === row } ) return@mapNotNull null + Card(row, author, date, descendants.any { it.resourceId == "image_mark" && it.directParent() === row }) + } + + private fun UiPage.player(): Player? { + if (!complete) return null + val pager = nodes.singleOrNull { it.resourceId == "nasa_groot_view_pager" && + it.bounds.width() >= bounds.width() * .85 } ?: return null + val card = nodes.singleOrNull { it.directParent() === pager && it.resourceId == "root" && + it.bounds.width() >= pager.bounds.width() * .85 } ?: return null + val image = card.description == "查看图片详情" || nodes.any { it.directParent() === card && + it.resourceId == "autoplay_cover_view_page_style" } + val video = nodes.any { it.directParent() === card && it.resourceId == "player" } + if (image == video) return null + val identity = nodes.singleOrNull { it.resourceId == "slide_play_avatar_click_area" && + it.isDescendantOf(card) && it.description.endsWith("作者头像") } ?: return null + val author = identity.description.removeSuffix("作者头像").takeIf(String::isNotBlank) ?: return null + val date = nodes.singleOrNull { it.resourceId == "create_date_tv" && it.isDescendantOf(card) && + it.text.isNotBlank() }?.text ?: return null + val caption = nodes.singleOrNull { it.resourceId == "element_caption_label" && it.isDescendantOf(card) } + ?.text.orEmpty().substringBefore(" … 展开").trim() + val comment = nodes.singleOrNull { it.resourceId == "comment_button" && it.isDescendantOf(card) && + it.kuaishouAction() && it.description.startsWith("评论") } ?: return null + val back = nodes.singleOrNull { it.resourceId == "photo_detail_back_btn" && it.kuaishouAction() && + it.bounds.left < x(.16f) && it.bounds.bottom < y(.16f) } ?: return null + return Player(if (image) Kind.IMAGE else Kind.VIDEO, author, date, caption, comment, back) + } + + private fun Player.context(): VideoContext { + val identity = listOf(kind.name, author, date, caption).joinToString("\u0000") + val key = MessageDigest.getInstance("SHA-256").digest(identity.toByteArray(Charsets.UTF_8)) + .joinToString("") { "%02x".format(it) } + return VideoContext(key, caption.ifBlank { "$author 的${kind.label}作品" }) + } +} + +private fun UiNode.kuaishouAction(): Boolean = enabled && clickable && !editable diff --git a/app/src/main/java/com/jieliu/app/platform/KuaishouPhotoPicker.kt b/app/src/main/java/com/jieliu/app/platform/KuaishouPhotoPicker.kt new file mode 100644 index 0000000..0878310 --- /dev/null +++ b/app/src/main/java/com/jieliu/app/platform/KuaishouPhotoPicker.kt @@ -0,0 +1,285 @@ +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 + +/** Selects the bound photos from the native comment attachment picker. */ +internal class KuaishouPhotoPicker(private val ui: AccessibleUi) { + private data class Surface(val window: Int, val container: UiNodeSource) : AutoCloseable { + override fun close() = container.close() + } + + private data class Picker( + val album: UiNode, + val albumAction: UiNode, + val multi: UiNode, + val grid: UiNode, + val handoff: UiNode?, + val selectedCount: Int, + ) + + private data class Crop(val image: Rect, val indicator: Rect) + private data class Tile(val action: UiNode, val crop: Crop, val ordinal: Int?) + private data class Selection(val picker: Picker, val tiles: List) + + fun select(album: String, references: List, beforeCommitSelection: () -> Unit) { + require(stagedAlbum.matches(album) && references.size in 1..TaskPlan.MAX_TEMPLATE_PHOTOS) + val surface = awaitPage("快手未打开可核对的图片选择器,请检查相册权限") { page -> + val container = page.pickerContainer() ?: return@awaitPage null + val picker = page.readPicker(container) ?: return@awaitPage null + if (picker.selectedCount != 0) throw PlatformException("快手相册已选中其他图片,请清空后重试") + Surface(page.windowId, container.retainSource()) + } + surface.use { + enableMulti(surface) + openAlbum(surface, album, references.size) + val regions = awaitPage("快手专用相册未完整显示本次绑定图片") { page -> + page.selection(surface, album, references.size)?.takeIf { + it.picker.selectedCount == 0 && it.tiles.none { tile -> tile.ordinal != null } + }?.tiles?.map(Tile::crop) + } + val order = readPhotoOrder(surface, album, regions, references) + + val selected = mutableListOf() + for (tileIndex in order) { + ui.pace() + val clicked = ui.inspect { page -> + val current = page.verifiedSelection(surface, album, regions, selected) ?: return@inspect false + ui.click(current.tiles[tileIndex].action) + } == true + if (!clicked) throw PlatformException("快手未接受第 ${selected.size + 1} 张图片的选择") + selected.add(tileIndex) + awaitPage("快手未核对第 ${selected.size} 张图片的选中序号") { page -> + true.takeIf { page.verifiedSelection(surface, album, regions, selected) != null } + } + } + + ui.pace() + val handedOff = ui.inspect { page -> + val current = page.verifiedSelection(surface, album, regions, selected) ?: return@inspect false + val next = current.picker.handoff?.takeIf { it.canClick() } ?: return@inspect false + beforeCommitSelection() + ui.click(next) + } == true + if (!handedOff) throw PlatformException("快手未确认将选中图片带回评论编辑框") + } + } + + private fun enableMulti(surface: Surface) { + ui.pace() + val accepted = ui.inspect { page -> + val picker = page.readPicker(surface) ?: return@inspect false + if (picker.selectedCount != 0) return@inspect false + picker.multi.selected || ui.click(picker.multi) + } == true + if (!accepted) throw PlatformException("快手相册未开启多选") + awaitPage("快手相册未显示多选确认控件") { page -> + true.takeIf { page.readPicker(surface)?.let { it.multi.selected && it.selectedCount == 0 } == true } + } + } + + private fun openAlbum(surface: Surface, album: String, count: Int) { + ui.pace() + val openedList = ui.inspect { page -> + val picker = page.readPicker(surface)?.takeIf { it.multi.selected && it.selectedCount == 0 } + ?: return@inspect null + if (picker.album.text == album) return@inspect false + true.takeIf { ui.click(picker.albumAction) } + } ?: throw PlatformException("快手未展开已核对的相册列表") + if (!openedList) return + + val source = awaitPage("快手未显示原生相册列表") { page -> + page.pickerContainer(surface)?.let { page.albumList(it) }?.retainSource() + } + source.use { + repeat(MAX_ALBUM_SCREENS) { index -> + ui.pace() + val result = ui.inspect { page -> + val container = page.pickerContainer(surface) ?: return@inspect null + val list = page.albumList(container)?.takeIf { it.hasSource(source) } ?: return@inspect null + val labels = page.nodes.filter { + it.resourceId == "label" && it.text == album && it.isDescendantOf(list) + } + if (labels.isEmpty()) { + return@inspect false.takeIf { index < MAX_ALBUM_SCREENS - 1 && + list.scrollable && list.act(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD) } + } + val label = labels.singleOrNull() ?: throw PlatformException("快手相册中存在多个同名专用相册") + val labelsContainer = label.directParent() ?: return@inspect null + val row = labelsContainer.directParent()?.takeIf { + it.resourceId == "item_root" && it.directParent() === list && it.canClick() && + list.bounds.contains(it.bounds) && it.bounds.contains(labelsContainer.bounds) && + labelsContainer.bounds.contains(label.bounds) + } ?: return@inspect null + val quantity = page.nativeChild(labelsContainer, "photo_count") + if (quantity?.text?.toIntOrNull() != count) { + throw PlatformException("快手专用相册中的图片数量与本次绑定不符") + } + true.takeIf { ui.click(row) } + } ?: throw PlatformException("快手相册列表中未找到可核对的本次专用相册") + if (result) return + } + } + throw PlatformException("快手相册列表中未找到本次专用相册") + } + + private fun readPhotoOrder( + surface: Surface, + album: String, + regions: List, + references: List, + ): List { + var nextCapture = 0L + return ui.await(5_000) { + val now = SystemClock.elapsedRealtime() + if (now < nextCapture || !isUnselected(surface, album, regions)) return@await null + nextCapture = now + 350L + val pictures = ui.screenshotPhotos(surface.window, regions.map(Crop::image)) + ?.takeIf { it.size == regions.size && isUnselected(surface, album, regions) } ?: return@await null + val visible = pictures.zip(regions).map { (pixels, region) -> pixels.maskIndicator(region) } + bilibiliAttachmentOrder(references, visible) + } ?: throw PlatformException("快手专用相册的缩略图无法与绑定图片逐一对应") + } + + private fun isUnselected(surface: Surface, album: String, regions: List): Boolean = + ui.inspect { it.verifiedSelection(surface, album, regions, emptyList()) != 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.picker.selectedCount != selected.size || current.tiles.map(Tile::crop) != regions) return null + return current.takeIf { + it.tiles.withIndex().all { (index, tile) -> + val position = selected.indexOf(index) + tile.ordinal == (position + 1).takeIf { position >= 0 } + } + } + } + + private fun UiPage.selection(surface: Surface, album: String, count: Int): Selection? { + val picker = readPicker(surface)?.takeIf { + it.album.text == album && it.multi.selected && it.selectedCount in 0..count + } ?: return null + val cells = nodes.filter { it.resourceId == "preview_container" && it.directParent() === picker.grid } + val camera = cells.filter { nativeChild(it, "ksa_take_photo_layout") != null } + if (camera.size > 1 || camera.any { nativeChild(it, "media_preview") != null }) return null + val media = cells - camera.toSet() + if (media.size != count || media.any { !picker.grid.bounds.contains(it.bounds) }) return null + val tiles = media.map { cell -> + val image = nativeChild(cell, "media_preview")?.takeIf { + it.className == "android.widget.ImageView" && it.labels() == listOf("预览") + } ?: return null + val action = nativeChild(cell, "media_pick_num_area")?.takeIf { it.canClick() } ?: return null + val indicator = nativeDescendant(action, "item_select_circle")?.takeIf { + image.bounds.contains(it.bounds) && it.bounds.width() <= image.bounds.width() / 3 && + it.bounds.height() <= image.bounds.height() / 3 + } ?: return null + val numbers = nodes.filter { it.resourceId == "media_pick_num" && it.isDescendantOf(action) } + if (numbers.size > 1) return null + val ordinal = numbers.singleOrNull()?.let { badge -> + if (!indicator.bounds.contains(badge.bounds)) return null + badge.text.toIntOrNull()?.takeIf { it in 1..count } ?: return null + } + Tile(action, Crop(Rect(image.bounds), Rect(indicator.bounds)), ordinal) + }.sortedWith(compareBy { it.crop.image.top }.thenBy { it.crop.image.left }) + if (tiles.indices.any { index -> tiles.take(index).any { Rect.intersects(it.crop.image, tiles[index].crop.image) } }) return null + return Selection(picker, tiles) + } + + private fun UiPage.pickerContainer(surface: Surface? = null): UiNode? { + if (!complete || surface?.window?.let { it != windowId } == true) return null + return nodes.singleOrNull { + it.resourceId == "photo_container" && it.className == "android.widget.FrameLayout" && + bounds.contains(it.bounds) && surface?.container?.let(it::hasSource) != false + } + } + + private fun UiPage.readPicker(surface: Surface): Picker? = pickerContainer(surface)?.let { readPicker(it) } + + private fun UiPage.readPicker(container: UiNode): Picker? { + if (albumList(container) != null) return null + val toolbar = nativeChild(container, "photo_picker_title_bar") ?: return null + val album = nativeDescendant(toolbar, "tab_text")?.takeIf { it.selected && it.text.isNotEmpty() } ?: return null + val title = album.directParent()?.takeIf { it.resourceId == "title_tv_wrapper" } ?: return null + val albumAction = title.directParent()?.takeIf { + it.canClick() && it.isDescendantOf(toolbar) && toolbar.bounds.contains(it.bounds) && + nativeChild(it, "album_indicator") != null + } ?: return null + val grid = nativeDescendant(container, "album_view_list")?.takeIf { + it.className == RECYCLER && it.bounds.top >= toolbar.bounds.bottom + } ?: return null + val bottom = nativeChild(container, "picked_layout") ?: return null + val toggle = nativeChild(bottom, "single_multi_select_layout") ?: return null + val multi = nativeChild(toggle, "single_multi_select_icon")?.takeIf { it.canClick() } ?: return null + if (nativeChild(toggle, "single_multi_select_text")?.labels() != listOf("多选")) return null + val handoffs = nodes.filter { it.resourceId == "next_step" && it.isDescendantOf(bottom) && bottom.bounds.contains(it.bounds) } + val handoff = handoffs.singleOrNull() + val tray = nativeChild(bottom, "picked_recycler_view") ?: return null + val alreadyPicked = nodes.any { it.resourceId == "media_preview" && it.isDescendantOf(tray) } + val selected = if (multi.selected) { + val button = handoff?.takeIf { it.className == "android.widget.Button" } ?: return null + val label = nextStep.matchEntire(button.text)?.groupValues?.get(1) ?: return null + if (label.isEmpty()) 0 else label.toIntOrNull() ?: return null + } else { + if (handoffs.isNotEmpty() || alreadyPicked) return null + 0 + } + if ((selected == 0) == alreadyPicked) return null + return Picker(album, albumAction, multi, grid, handoff, selected) + } + + private fun UiPage.albumList(container: UiNode): UiNode? { + val overlay = nativeChild(container, "album_list_container") ?: return null + return nativeDescendant(overlay, "recycler_view")?.takeIf { it.className == RECYCLER } + } + + private fun UiPage.nativeChild(parent: UiNode, id: String): UiNode? = nodes.singleOrNull { + it.resourceId == id && it.directParent() === parent && parent.bounds.contains(it.bounds) + } + + private fun UiPage.nativeDescendant(parent: UiNode, id: String): UiNode? = nodes.singleOrNull { + it.resourceId == id && it.isDescendantOf(parent) && parent.bounds.contains(it.bounds) + } + + private fun PhotoPixels.maskIndicator(crop: Crop): PhotoPixels { + val indicator = Rect(crop.indicator).apply { inset(-2, -2) } + val image = crop.image + if (!indicator.intersect(image)) return this + val x = width.toDouble() / image.width() + val y = height.toDouble() / image.height() + val left = floor((indicator.left - image.left) * x).toInt().coerceIn(0, width) + val right = ceil((indicator.right - image.left) * x).toInt().coerceIn(left, width) + val top = floor((indicator.top - image.top) * y).toInt().coerceIn(0, height) + val bottom = ceil((indicator.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 { page -> + if (page.nodes.any { it.resourceId == "title" && it.labels() == listOf("开启相册权限") }) { + throw PlatformException("请先在快手允许相册权限,再继续选择评论图片") + } + probe(page) + } + } ?: throw PlatformException(message) + + private fun UiNode.canClick(): Boolean = enabled && supports(AccessibilityNodeInfo.ACTION_CLICK) + + private companion object { + const val MAX_ALBUM_SCREENS = 7 + const val RECYCLER = "androidx.recyclerview.widget.RecyclerView" + val stagedAlbum = Regex("SJ-[0-9a-f]{12}") + val nextStep = Regex("下一步(?:\\(([1-9])\\))?") + } +} diff --git a/app/src/main/java/com/jieliu/app/platform/KuaishouReplies.kt b/app/src/main/java/com/jieliu/app/platform/KuaishouReplies.kt new file mode 100644 index 0000000..178dc61 --- /dev/null +++ b/app/src/main/java/com/jieliu/app/platform/KuaishouReplies.kt @@ -0,0 +1,356 @@ +package com.jieliu.app.platform + +import android.graphics.Rect +import android.os.Build +import android.view.accessibility.AccessibilityNodeInfo +import com.jieliu.app.data.PhotoLibrary +import com.jieliu.app.data.StagedPhotos +import com.jieliu.app.task.RECHECK_WINDOW_MS +import com.jieliu.app.task.TemplatePhoto +import java.io.Closeable +import kotlin.math.ceil +import kotlin.math.floor + +internal class KuaishouReplies( + private val ui: AccessibleUi, + private val comments: KuaishouComments, + private val photos: PhotoLibrary, + private val diagnostic: (String) -> Unit, +) { + private data class Editor( + val container: UiNode, + val input: UiNode, + val send: UiNode, + val sendWrapper: UiNode, + val picture: UiNode?, + val images: List, + ) + + private class Prepared( + val target: CommentTarget, + val text: String, + val window: Int, + val container: UiNodeSource, + val input: UiNodeSource, + ) : Closeable { + override fun close() { + container.close() + input.close() + } + } + + private data class Receipt(val window: Int, val key: String, val images: List) + private data class DraftImage(val area: Rect, val close: Rect) + private enum class Role { OWN, OTHER } + private data class RoleMenu(val window: Int, val role: Role?) + + private var prepared: Prepared? = null + private val picker = KuaishouPhotoPicker(ui) + + fun prepare(target: CommentTarget, text: String, requiresImages: Boolean): Boolean { + check(prepared == null) { "快手回复草稿尚未完成" } + if (text.isBlank()) return false + if (requiresImages && Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { + throw PlatformException("快手图片核对需要 Android 11 或更新版本") + } + if (!comments.ensureThread(target.key, target.author)) return false + if (inspectRole(target.key, target.author, target.key, null) != Role.OTHER) return false + ui.pace() + val opened = comments.readThread(target.key, target.author) { page, _, thread -> + if (!thread.complete || thread.original.target != target || thread.original.own || + thread.replies.any { it.target.text == text } || page.hasKuaishouCommentDraft()) return@readThread false + thread.original.reply?.let { ui.click(it) } == true + } == true + if (!opened) return false + prepared = ui.await(5_000) { + ui.inspect(traverseHiddenParents = true) { page -> + val editor = readEditor(page, target) ?: return@inspect null + if (!editor.input.isStillBlankAndFocused() || editor.images.isNotEmpty()) return@inspect null + if (requiresImages && editor.picture == null) { + throw PlatformException("当前快手回复框未提供可核对的图片入口") + } + Prepared(target, text, page.windowId, editor.container.retainSource(), editor.input.retainSource()) + } + } ?: throw PlatformException("快手未显示可核对的空白定向回复框") + return true + } + + fun hasPreparedBaseline(key: String, text: String): Boolean = prepared?.let { + it.target.key == key && it.text == text + } == true + + fun preparedTarget(text: String): CommentTarget = prepared?.takeIf { it.text == text }?.target + ?: throw PlatformException("快手回复对象或正文尚未核对") + + 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 = photos.readReceiptPixels(attachments) ?: throw PlatformException("无法读取快手回复的绑定图片") + if (attachments.isNotEmpty()) { + photos.cleanupStaged() + val album = photos.stage(attachments) + staged = album + ui.pace() + val opened = ui.inspect(traverseHiddenParents = true) { page -> + val draft = checkedEditor(page, session) ?: return@inspect false + draft.images.isEmpty() && draft.input.isStillBlankAndFocused() && + draft.picture?.let { ui.click(it) } == true + } == true + if (!opened) throw PlatformException("未打开快手定向回复的图片选择器") + picker.select(album.albumName, references) { handedToEditor = true } + } + ui.pace() + val written = ui.await(4_000) { + ui.inspect(traverseHiddenParents = true) { page -> + val draft = checkedEditor(page, session) ?: return@inspect null + if (draft.images.size != references.size || draft.input.hasDraft()) return@inspect null + if (!draft.input.focused) { + ui.click(draft.input) + return@inspect null + } + ui.setText(draft.input, text, requireBlankFocusedInput = true) + } + } == true + if (!written) throw PlatformException("未能在快手定向回复框写入正文") + ui.pace() + val ready = ui.await(4_000) { + ui.inspect(traverseHiddenParents = true) { page -> readyDraft(page, session, references.size)?.images } + } ?: throw PlatformException("快手未能核对回复草稿和发送按钮") + val captured = ui.screenshotPhotos(session.window, ready.map(DraftImage::area))?.takeIf { it.size == ready.size } + ?.zip(ready) { pixels, image -> pixels.withoutDraftClose(image) } + val unchanged = ui.inspect(traverseHiddenParents = true) { page -> + readyDraft(page, session, references.size)?.images == ready + } == true + if (!unchanged || captured == null || !matchPhotos(references, captured)) { + throw PlatformException("快手草稿图片与按顺序绑定的图片不一致") + } + arm() + return ui.inspect(traverseHiddenParents = true) { page -> + val draft = readyDraft(page, session, references.size)?.takeIf { it.images == ready } ?: return@inspect false + ui.click(draft.sendWrapper) + } == 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 age = System.currentTimeMillis() - armedAt + if (armedAt <= 0 || age !in 0..RECHECK_WINDOW_MS) return CommentPublishResult.UNCERTAIN + val references = photos.readReceiptPixels(attachments) ?: return CommentPublishResult.UNCERTAIN + repeat(RECEIPT_SCREENS) { screen -> + val visible = comments.readThread(key, author) { _, _, _ -> true } == true + if (visible) { + if (!comments.ensureThread(key, author)) return CommentPublishResult.UNCERTAIN + val before = ui.await(4_500) { readReceipt(key, author, text, references.size, armedAt) } + ?: return CommentPublishResult.UNCERTAIN + val captured = ui.screenshotPhotos(before.window, before.images) ?: return CommentPublishResult.UNCERTAIN + if (readReceipt(key, author, text, references.size, armedAt) != before || !matchPhotos(references, captured)) { + return CommentPublishResult.UNCERTAIN + } + if (inspectRole(key, author, key, before) != Role.OTHER || + inspectRole(key, author, before.key, before) != Role.OWN || + readReceipt(key, author, text, references.size, armedAt) != before) { + return CommentPublishResult.UNCERTAIN + } + diagnostic("快手已核对原评论下的本人回复正文及 ${references.size} 张图片") + if (references.isNotEmpty()) photos.cleanupStaged() + return CommentPublishResult.CONFIRMED + } + if (screen == RECEIPT_SCREENS - 1 || !comments.scroll()) return CommentPublishResult.UNCERTAIN + } + return CommentPublishResult.UNCERTAIN + } + + fun hasUnsettledEditor(): Boolean = ui.inspect(traverseHiddenParents = true) { it.hasKuaishouCommentDraft() } == true + + fun reset() { + prepared?.close() + prepared = null + } + + private fun checkedEditor(page: UiPage, session: Prepared): Editor? = + readEditor(page, session.target)?.takeIf { + page.windowId == session.window && it.container.hasSource(session.container) && it.input.hasSource(session.input) + } + + private fun readyDraft(page: UiPage, session: Prepared, count: Int): Editor? { + val editor = checkedEditor(page, session)?.takeIf { + it.images.size == count && it.input.hasCurrentFocusedText(session.text) { hint -> + replyPrompt(hint, session.target.author) + } && it.send.enabled && it.sendWrapper.clickable + } ?: return null + val regions = editor.images.map(DraftImage::area) + if (regions.any { it.isEmpty || !page.bounds.contains(it) } || regions.hasOverlap()) return null + return editor + } + + private fun matchPhotos(references: List, actual: List): Boolean = + references.size == actual.size && references.indices.all { PublishedPhotoMatcher.matches(references[it], actual[it]) } + + private fun List.hasOverlap(): Boolean = indices.any { index -> + subList(0, index).any { Rect.intersects(it, this[index]) } + } + + private fun readEditor(page: UiPage, target: CommentTarget): Editor? { + if (!page.complete) return null + val container = page.nodes.singleOrNull { + it.resourceId == "editor_animation_frame" && page.bounds.contains(it.bounds) && + generateSequence(it.directParent(), UiNode::directParent).take(6) + .any { ancestor -> ancestor.resourceId == "comment_editor_container" } + } ?: return null + val members = page.nodes.filter { it.isDescendantOf(container) && container.bounds.contains(it.bounds) } + val input = members.singleOrNull { + it.resourceId == "editor" && it.className == "android.widget.EditText" && it.editable && + it.directParent()?.resourceId == "edit_container" && replyPrompt(it.hint.ifBlank { + if (it.showingHint) it.text else "" + }, target.author) + } ?: return null + val send = members.singleOrNull { + it.resourceId == "finish_button" && it.className == "android.widget.Button" && it.labels() == listOf("发送") + } ?: return null + val wrapper = send.directParent()?.takeIf { + it.resourceId == "finish_button_wrapper" && it.directParent()?.resourceId == "operation_buttons_layout" && + it.bounds.contains(send.bounds) && it.bounds.top >= input.bounds.bottom + } ?: return null + val picture = members.singleOrNull { + it.resourceId == "picture_button_layout" && it.labels() == listOf("发布图片") && + it.clickable && it.enabled && it.bounds.top >= input.bounds.bottom && it.bounds.right < wrapper.bounds.left + } + val images = readDraftImages(members, input) ?: return null + return Editor(container, input, send, wrapper, picture, images) + } + + private fun readDraftImages(members: List, input: UiNode): List? { + val grids = members.filter { it.resourceId == "multi_picture_recycler_view" } + if (grids.isEmpty()) { + return emptyList().takeIf { members.none { it.resourceId in attachmentNodes } } + } + val grid = grids.singleOrNull()?.takeIf { + it.className == "androidx.recyclerview.widget.RecyclerView" && it.bounds.bottom <= input.bounds.top && + it.directParent()?.resourceId == "emotion_preview_parent_layout" && !it.scrollable + } ?: return null + val tiles = members.filter { it.directParent() === grid }.sortedBy { it.bounds.left } + val add = tiles.lastOrNull()?.takeIf { tile -> + tile.resourceId == "add_image" && tile.clickable && grid.bounds.contains(tile.bounds) && + members.count { it.directParent() === tile && it.resourceId == "add_image_icon" } == 1 + } + return (if (add != null) tiles.dropLast(1) else tiles).map { item -> + if (item.resourceId != "preview_image_layout" || !grid.bounds.contains(item.bounds)) return null + val image = members.singleOrNull { + it.directParent() === item && it.resourceId == "preview_image" && it.bounds == item.bounds + } ?: return null + val close = members.singleOrNull { + it.directParent() === item && it.resourceId == "preview_close" && it.clickable && + image.bounds.contains(it.bounds) && it.bounds.right == image.bounds.right && + it.bounds.top == image.bounds.top && it.bounds.width() < image.bounds.width() / 2 && + it.bounds.height() < image.bounds.height() / 2 + } ?: return null + DraftImage(Rect(image.bounds), Rect(close.bounds)) + } + } + + private fun PhotoPixels.withoutDraftClose(image: DraftImage): PhotoPixels { + val xScale = width.toDouble() / image.area.width() + val yScale = height.toDouble() / image.area.height() + val left = floor((image.close.left - image.area.left) * xScale).toInt().coerceIn(0, width) + val right = ceil((image.close.right - image.area.left) * xScale).toInt().coerceIn(left, width) + val top = floor((image.close.top - image.area.top) * yScale).toInt().coerceIn(0, height) + val bottom = ceil((image.close.bottom - image.area.top) * yScale).toInt().coerceIn(top, height) + val pixels = argb.copyOf() + for (row in top until bottom) pixels.fill(0, row * width + left, row * width + right) + return copy(argb = pixels) + } + + private fun replyPrompt(label: String, author: String): Boolean = author.isNotBlank() && + (label == "回复给: $author" || label == "回复给:$author" || label == "回复给: $author") + + private fun readReceipt(key: String, author: String, text: String, count: Int, armedAt: Long): Receipt? = + comments.readThread(key, author) { page, panel, thread -> + if (!thread.complete || page.hasKuaishouCommentDraft()) return@readThread null + val row = thread.replies.singleOrNull { it.target.text == text } ?: return@readThread null + if (!matchesTime(row.time, armedAt, System.currentTimeMillis())) return@readThread null + val images = row.photos?.takeIf { it.size == count } ?: return@readThread null + val list = panel.list ?: return@readThread null + if (images.any { !page.bounds.contains(it.bounds) || !list.bounds.contains(it.bounds) }) return@readThread null + val regions = images.map { Rect(it.bounds) } + if (regions.any { it.isEmpty } || regions.hasOverlap()) return@readThread null + Receipt(page.windowId, row.target.key, regions) + } + + private fun inspectRole(key: String, author: String, rowKey: String, expected: Receipt?): Role? { + ui.pace() + val sourceWindow = comments.readThread(key, author) { page, panel, thread -> + if (!thread.complete || (expected != null && page.windowId != expected.window)) return@readThread null + val row = if (rowKey == key) thread.original else thread.replies.singleOrNull { it.target.key == rowKey } + if (row == null || (rowKey != key && expected?.images != row.photos?.map { Rect(it.bounds) })) { + return@readThread null + } + val bounds = row.body.bounds + val list = panel.list ?: return@readThread null + if (bounds.isEmpty || !list.bounds.contains(bounds) || !row.container.bounds.contains(bounds)) { + return@readThread null + } + val longClick = AccessibilityNodeInfo.ACTION_LONG_CLICK + val shown = if (row.body.supports(longClick)) row.body.act(longClick) else + ui.touch(bounds.exactCenterX(), bounds.exactCenterY(), bounds.exactCenterX(), bounds.exactCenterY(), 650) + page.windowId.takeIf { shown } + } ?: return null + val menu = ui.await(3_500) { ui.inspect { readRoleMenu(it, sourceWindow) } } ?: return null + val closed = ui.inspect { page -> readRoleMenu(page, sourceWindow) == menu && ui.back() } == true + if (!closed || ui.await(3_500) { + comments.readThread(key, author) { page, _, thread -> + true.takeIf { page.windowId == sourceWindow && thread.complete && + (rowKey == key || thread.replies.count { it.target.key == rowKey } == 1) } + } + } != true + ) return null + return menu.role + } + + private fun readRoleMenu(page: UiPage, previousWindow: Int): RoleMenu? { + if (!page.complete || page.windowId == previousWindow || page.hasKuaishouCommentDraft()) return null + val sheet = page.nodes.singleOrNull { + it.resourceId == "design_bottom_sheet" && it.directParent()?.resourceId == "coordinator" && + page.bounds.contains(it.bounds) + } ?: return null + val labels = page.nodes.filter { + it.resourceId == "item_title" && it.isDescendantOf(sheet) && sheet.bounds.contains(it.bounds) + }.map(UiNode::text) + if (labels.count { it == "复制评论" } != 1) return null + val deletion = labels.count { it == "删除评论" || it == "删除" } + val reporting = labels.count { it == "举报评论" } + val role = when { + deletion == 1 && reporting == 0 -> Role.OWN + deletion == 0 && reporting == 1 -> Role.OTHER + else -> null + } + return RoleMenu(page.windowId, role) + } + + private fun matchesTime(label: String?, armedAt: Long, now: Long): Boolean { + if (armedAt <= 0 || now - armedAt !in 0..RECHECK_WINDOW_MS) return false + val age = now - armedAt + if (label == "刚刚" || label?.startsWith("刚刚 ") == true) return age <= 65_000L + val match = relativeTime.matchEntire(label.orEmpty()) ?: return false + val unit = if (match.groupValues[2] == "分钟") 60_000L else 1_000L + val displayed = match.groupValues[1].toLong() * unit + return age >= displayed - 5_000L && age < displayed + unit + 5_000L + } + + private companion object { + const val RECEIPT_SCREENS = 13 + val relativeTime = Regex("([1-9]\\d?)\\s*(秒|分钟)前(?:\\s+\\S+)?") + val attachmentNodes = setOf("preview_image_layout", "preview_image", "preview_close", "comment_image") + } +} + +internal fun UiPage.hasKuaishouCommentDraft(): Boolean = nodes.any { node -> + node.resourceId == "editor_animation_frame" || + (node.resourceId == "finish_button" && node.enabled && node.labels() == listOf("发送") && + node.directParent()?.resourceId == "comment_editor_bottom_layout") +} 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 75430ff..40499f6 100644 --- a/app/src/main/java/com/jieliu/app/platform/PlatformAdapter.kt +++ b/app/src/main/java/com/jieliu/app/platform/PlatformAdapter.kt @@ -54,11 +54,14 @@ object PlatformRegistry { private val xiaohongshu = PlatformSpec("xiaohongshu", "小红书", "com.xingin.xhs", true, supportsReplies = true, contentUnit = "笔记") private val bilibili = PlatformSpec("bilibili", "哔哩哔哩", "tv.danmaku.bili", true, supportsReplies = true) + private val kuaishou = PlatformSpec("kuaishou", "快手", "com.smile.gifmaker", true, + supportsReplies = true, contentUnit = "作品") val platforms: List = listOf( douyin, xiaohongshu, bilibili, + kuaishou, ) fun create( @@ -79,12 +82,18 @@ object PlatformRegistry { bilibili -> UiPage::requireBilibiliCommentAccess else -> null } - val ui = AccessibleUi(service, spec.packageName, cancelled, pauseBetweenActions, checkPage) + val ui = if (spec == kuaishou) { + // The expanded comment list and the reply editor coexist in one native window. + AccessibleUi(service, spec.packageName, cancelled, pauseBetweenActions, nodeLimit = 900) + } else { + AccessibleUi(service, spec.packageName, cancelled, pauseBetweenActions, checkPage) + } return when (spec.id) { 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), bilibiliCommentScope, receiptDiagnostic) + kuaishou.id -> KuaishouAdapter(spec, ui, PhotoLibrary(service), receiptDiagnostic) else -> throw PlatformException("${spec.label} 暂未接入") } } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 7811e95..78c04d8 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2,7 +2,7 @@ 拾见 拾见任务服务 - 在你主动启动任务时按内容类型搜索和浏览视频,并按配置识别、回复匹配的评论。可在拾见任务页暂停。 + 在你主动启动任务时按内容类型搜索和浏览作品,并按配置识别、回复匹配的评论。可在拾见任务页暂停。 任务 配置 日志 diff --git a/app/src/main/res/xml/accessibility_config.xml b/app/src/main/res/xml/accessibility_config.xml index e24c141..616fd59 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,tv.danmaku.bili" /> + android:packageNames="com.ss.android.ugc.aweme,com.xingin.xhs,tv.danmaku.bili,com.smile.gifmaker" /> diff --git a/docs/ui-preview.html b/docs/ui-preview.html index bdd0da0..b71c481 100644 --- a/docs/ui-preview.html +++ b/docs/ui-preview.html @@ -341,6 +341,7 @@ +
@@ -692,7 +693,9 @@ byId("content-limit-label").textContent = `单次任务${unit}上限`; byId("reply-limit-label").textContent = `每条${unit}${videoComment ? "评论发布" : "回复"}上限`; byId("reply-scope-hint").textContent = `达到${operation}上限或找不到更多匹配评论时,进入下一个${unit}。`; - byId("content-scope-hint").textContent = `按内容类型搜索${unit},按关键词匹配评论。每个关键词可配置多条话术。`; + byId("content-scope-hint").textContent = platformPicker.value === "kuaishou" + ? "按内容类型搜索,轮流处理「图片」和「视频」中的作品。每个关键词可配置多条话术。" + : `按内容类型搜索${unit},按关键词匹配评论。每个关键词可配置多条话术。`; } for (const picker of [platformPicker, replyMode, bilibiliScope]) { picker.addEventListener("change", updateCommentSettings); diff --git a/docs/开发进度.md b/docs/开发进度.md index 22a23ce..51e3b21 100644 --- a/docs/开发进度.md +++ b/docs/开发进度.md @@ -1,6 +1,16 @@ # 拾见开发进度 -最近更新于 2026-11-27 14:35(UTC+8)。以下按开发轮次倒序记录。 +最近更新于 2026-11-27 15:22(UTC+8)。以下按开发轮次倒序记录。 + +## 2026-11-27 · 拾见 0.1.41 接入快手 + +- 注册快手标准版,配置和任务页以「作品」计数。按内容类型名称搜索,优先打开结果页上方的「图片」。两栏均有可用作品时,在「图片」和「视频」之间轮流处理。打开作品后再次核对详情类型,跳过分类下混入的其他类型。重新搜索时先退回搜索页,避免沿用结果列表的浏览位置。 +- 图文和视频沿用评论关键字、话术库轮换、每作品回复上限、日志和任务恢复。定向回复先核对原评论和空白回复框。带图话术从专用相册按绑定顺序选图,并核对草稿正文和缩略图。发送后在同一原评论线程核对唯一正文、发送时间、图片内容及顺序和本人身份,证据不足时保留待核对记录。 +- vivo Android 12、快手 14.10.40。真机确认「图片」「视频」分类和两种作品的评论区结构。15:11 的「仅浏览」任务处理两条不同作品,写入两条 `WATCHED`。最终装机版在图片和视频各匹配原评论并打开已核对收件人的空白回复框。真机另外在图文定向回复草稿中选入两张测试图,随后清空草稿、清理测试图片并恢复临时相册权限。 +- 快手的评论区和回复框可共用同一原生窗口。根据真机节点数量为快手提高快照读取上限。首次出现 vivo 跨应用启动提示时曾等待超时,为快手延长进入前台的等待时间。 +- 离线回放覆盖两类作品选择、错分类拦截、原评论与回复框、双图按顺序选择、正文和回执证据不完整等场景。静态预览在 Chrome 的 1440 和 390 像素宽度验证了快手平台选择和作品计数。原任务配置、检查点及无障碍设置校验保留。 +- 最终版通过离线构建和 74 项 JVM 单测,Lint 为 0 个错误、3 个既有警告。APK 通过 v2 签名校验,覆盖安装后的文件与本地构建产物 SHA-256 一致。 +- 待验收项为两种作品的公开实发及同一次任务写入 `SENT`。本轮真机停在草稿和浏览阶段,回执逻辑使用原生快照回放验证。真机重搜时,在本轮有限搜索范围内未找回先前的图片作品,发布后的原作品重新定位仍需验证。 ## 2026-11-27 · 拾见 0.1.40 哔哩哔哩同次任务验收