diff --git a/README.md b/README.md index 05fe97c..e743525 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 拾见 -拾见是独立运行的安卓 APK,以内容类型名称搜索。抖音支持浏览、按关键词匹配原评论、选择话术与绑定图、发送和自动回执。小红书支持仅浏览,可从同一关键词的结果列表打开图文和视频笔记。哔哩哔哩待适配。 +拾见是独立运行的安卓 APK,以内容类型名称搜索。抖音和小红书可配置浏览或匹配评论并回复,回复支持多条话术、绑定多图和自动回执。小红书图文笔记浏览已通过真机验收,评论回复待真机联调。哔哩哔哩待适配。 ## 界面 @@ -53,38 +53,38 @@ powershell -NoProfile -File ./scripts/verify-apk.ps1 2. 打开「拾见 → 任务 → 打开无障碍设置」,在系统中开启「拾见任务服务」。若较新系统把侧载应用的开关置灰,查看应用详情菜单是否提供「允许受限设置」,再返回无障碍设置。具体入口因厂商而异。[Android 官方帮助](https://support.google.com/android/answer/12623953?hl=zh-Hans) 3. 在「配置」创建内容类型并填写实际要搜索的名称,例如「大模型充值」。在该类型中添加评论关键字,例如「付款方式」和「账号订阅」,分别维护话术和图片。选择搜索范围、处理方式和任务参数,点「保存配置」。可以先用「仅浏览」模式验证搜索和播放。 - 小红书请选择「小红书(仅浏览)」及「仅浏览」,设置单次任务笔记上限。任务会按内容类型搜索,停留到设定时长后返回结果列表打开下一条笔记。部分 vivo 设备首次会弹出跨应用打开提示,确认是「拾见」打开「小红书」后可选择「始终打开」。若等待超时,返回拾见点「继续任务」。 + 选择「小红书」后,可设置单次任务笔记上限和每条笔记回复上限。任务会按内容类型搜索,停留到设定时长后返回结果列表打开下一条笔记。部分 vivo 设备首次会弹出跨应用打开提示,确认是「拾见」打开「小红书」后可选择「始终打开」。若等待超时,返回拾见点「继续任务」。 4. 在「任务」点「开始任务」。保持手机解锁,由拾见打开目标平台。运行期间让目标平台留在前台。在拾见任务页或用通知栏按钮可暂停。登录、验证、页面布局不可识别等中断可在手机处理后点「继续任务」。 -5. 抖音发布后,拾见核对原评论下新增的本人回复,匹配正文和全部绑定图片后自动登记回执。图文自动核对需要 Android 11 或更新版本,图片比对在手机内存中完成。待核对卡片出现「自动核对回复」时,可让拾见再次查找并核对这条回复。若仍显示待核对,可到原评论下核对正文及图片,再选择「确认已发送」或「跳过此回复」。待核对期间会阻止自动重发。 +5. 发送后,拾见尝试核对原评论下新增的本人回复,匹配正文和同一回复内的全部绑定图片后登记回执。图文自动核对需要 Android 11 或更新版本,图片比对在手机内存中完成。待核对卡片出现「自动核对回复」时,可让拾见再次查找并核对这条回复。若仍显示待核对,可到原评论下核对正文及图片,再选择「确认已发送」或「跳过此回复」。待核对期间会阻止自动重发。 -安装完成后,任务可以脱离电脑运行。加载平台内容需要手机网络,抖音的话术匹配和选择在拾见本机完成。 +安装完成后,任务可以脱离电脑运行。加载平台内容需要手机网络,话术匹配和选择在拾见本机完成。 ## 配置项 | 配置 | 说明 | | --- | --- | -| 目标平台 | 抖音标准版 `com.ss.android.ugc.aweme` 支持浏览和匹配回复。小红书 `com.xingin.xhs` 支持仅浏览。 | +| 目标平台 | 抖音标准版 `com.ss.android.ugc.aweme`。小红书 `com.xingin.xhs`。 | | 内容类型 | 类型名称直接用于目标平台搜索。「全部类型」按类型顺序尽量均分任务总数,余数优先分给前面的类型。也可只运行一个类型。 | | 评论关键字 | 每个类型可增删改多条关键字。每个关键字对应独立话术库。匹配基于评论正文,兼容全角半角、英文字母大小写和常见中英文空格;重叠时优先选更长的匹配。 | -| 单次任务上限 | 共处理 1–100 项,抖音按视频计数,小红书按笔记计数。浏览完成计入进度。抖音扫描后没有可回复的评论也计入进度。 | -| 每条视频回复上限 | 默认 1 条,可设为 1–100 条。在匹配回复模式下,已确认发送的回复计入上限。达标、评论列表到末尾或扫描范围内没有更多匹配时,浏览下一个视频。 | +| 单次任务上限 | 共处理 1–100 项,抖音按视频计数,小红书按笔记计数。浏览完成或扫描后没有可回复的评论均计入进度。 | +| 每条视频或笔记回复上限 | 默认 1 条,可设为 1–100 条。在匹配回复模式下,已确认发送的回复计入上限。达标、评论列表到末尾或扫描范围内没有更多匹配时,浏览下一条。 | | 观看时长 | 1–300 秒的闭区间,逐视频或笔记取样,默认 5–12 秒。 | -| 动作间隔 | 150–30,000 毫秒的闭区间,默认 600–1,800 毫秒。评论滑动在评论列表内变化起点、距离、轨迹、时长和停留时间,每个视频最多滑动 12 次并在每屏重新读取。 | -| 处理方式 | 「仅浏览」观看视频或浏览笔记。抖音的「匹配评论并回复」逐屏读取评论,匹配到当前类型中有可用话术的关键字后回复原评论。同一任务内每条原评论最多尝试一次发送。 | -| 话术库 | 每个关键字最多 100 条话术,每条最多 120 个 Unicode 码点。支持 {keyword} 和 {title},分别填入命中的关键字和视频标题。各库独立随机轮换,有可用替代时避开连续重复。 | +| 动作间隔 | 150–30,000 毫秒的闭区间,默认 600–1,800 毫秒。评论滑动在列表内变化起点、距离、轨迹、时长和停留时间,每条内容最多滑动 12 次并在每屏重新读取。 | +| 处理方式 | 「仅浏览」观看视频或浏览笔记。「匹配评论并回复」逐屏读取评论,匹配到当前类型中有可用话术的关键字后回复原评论。同一任务内每条原评论最多尝试一次发送。 | +| 话术库 | 每个关键字最多 100 条话术,每条最多 120 个 Unicode 码点。支持 {keyword} 和 {title},分别填入命中的关键字和视频或笔记标题。各库独立随机轮换,有可用替代时避开连续重复。 | | 话术图片 | 每条话术独立绑定最多 9 张 JPEG 或 PNG,可一次多选、逐张调整顺序或移除。单张最多 20 MB,需要 Android 10 或更新版本。编辑原话术时会保留其图片。 | 保存后,关键字、话术和图片从下一次评论识别起生效,同时在提交前核对命中的话术库。搜索范围、类型名称、任务及回复上限和动作区间用于下次新任务。恢复保留搜索计划、处理进度和已记录的抽取进度。 ## 恢复和兼容性 -发送前,应用核对原评论对象和编辑框,把视频指纹、原评论标识、回复正文和图片列表写入本地检查点。回执不明确时,任务保留待核对记录,任务页显示原评论作者与待核对的图文。恢复时先定位同一未完成视频并跳过已尝试的原评论,也会跳过已结束处理的视频。视频指纹基于可见作者和标题,同作者、同标题的不同视频可能合并,标题变化也可能改变指纹。 +发送前,应用核对原评论对象和编辑框,把视频或笔记指纹、原评论标识、回复正文和图片列表写入本地检查点。回执不明确时,任务保留待核对记录,任务页显示原评论作者与待核对的图文。恢复时先定位同一未完成内容并跳过已尝试的原评论,也会跳过已结束处理的内容。内容指纹基于可见作者和标题,同作者、同标题的不同内容可能合并,标题变化也可能改变指纹。 旧配置的搜索关键词迁移为同名内容类型和首条评论关键字,保留原分组话术及对应图片。原分组没有话术时,原通用话术随该组迁入。旧版已有的发送待核对记录仍可核对。 拾见为手动选定的图片保存本机私有副本。回复选图时只使用本次创建的临时相册,并在提交前核对选中的图片数和编辑框中的附件总数。图库权限、相册布局或附件数量无法确认时,任务会停在当步并记录原因。用户核对完成后,拾见清理临时相册图片。选图基于 Android 系统文件选择器,临时相册基于系统媒体库。[Android 文件选择器](https://developer.android.com/training/data-storage/shared/documents-files) · [Android 媒体库](https://developer.android.com/training/data-storage/shared/media) -抖音页面识别依据无障碍节点及控件语义,受安装版本、登录状态及服务端布局影响。若搜索、播放器或评论区域缺少可读节点,任务会在相应环节暂停,并在日志记录原因。 +页面识别依据无障碍节点及控件语义,受目标平台版本、登录状态及服务端布局影响。若搜索、播放器或评论区域缺少可读节点,任务会在相应环节暂停,并在日志记录原因。小红书按同一笔记内可见的作者和正文定位原评论,相同作者重复发布相同正文时可能被合并。话术库可绑定的图片数和平台评论可接收的图片数分别判断,平台未接收全部图片时会停止提交。 在 vivo Android 12 真机上,系统的「智能控制后台耗电」曾在抖音播放期间冻结拾见任务线程。遇到相同现象时,可在「系统设置 → 电池 → 后台耗电管理 → 拾见」选择「允许后台高耗电」,再从任务页继续。[vivo 客服说明](https://kefu.vivo.com.cn/robot/imgmsgData/2616a9cd7cd64a5083a264d16e5767da/index_1.html) @@ -121,4 +121,4 @@ powershell -NoProfile -File ./scripts/verify-apk.ps1 0.1.19 在 vivo Android 12、抖音 39.8.0 上完成连续真机验收。单次启动后自动搜索、匹配原评论、实发 1 条图文回复,在同一回复内核对正文及 1 张绑定图后自动写入 `SENT`。启动至回执用时 89 秒,待核对为 0。APK v2 签名校验和 45 项 JVM 单测通过。 -0.1.20 在 vivo Android 12、小红书 9.54.0 上验证了小红书仅浏览模式。允许跨应用始终打开后,真机从启动到自动搜索并浏览 3 条不同图文笔记用时 57 秒。检查点继续运行也已验证。小红书评论匹配、图文回复和回执待适配。 +0.1.20 在 vivo Android 12、小红书 9.54.0 上验证了小红书仅浏览模式。允许跨应用始终打开后,真机从启动到自动搜索并浏览 3 条不同图文笔记用时 57 秒。检查点继续运行也已验证。 diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 72a54a5..fd878ac 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 = 21 - versionName = "0.1.20" + versionCode = 22 + versionName = "0.1.21" } compileOptions { diff --git a/app/src/main/java/com/jieliu/app/platform/PhotoReceiptImages.kt b/app/src/main/java/com/jieliu/app/platform/PhotoReceiptImages.kt new file mode 100644 index 0000000..57f9f10 --- /dev/null +++ b/app/src/main/java/com/jieliu/app/platform/PhotoReceiptImages.kt @@ -0,0 +1,15 @@ +package com.jieliu.app.platform + +import com.jieliu.app.data.PhotoLibrary +import com.jieliu.app.task.TemplatePhoto + +internal fun PhotoLibrary.readReceiptPixels(photos: List): List? = photos.map { photo -> + val bitmap = receiptThumbnail(photo) ?: return null + try { + val pixels = IntArray(bitmap.width * bitmap.height) + bitmap.getPixels(pixels, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height) + PhotoPixels(bitmap.width, bitmap.height, pixels) + } finally { + bitmap.recycle() + } +} 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 2fd5008..ea9da0a 100644 --- a/app/src/main/java/com/jieliu/app/platform/PlatformAdapter.kt +++ b/app/src/main/java/com/jieliu/app/platform/PlatformAdapter.kt @@ -46,7 +46,8 @@ interface PlatformAdapter { object PlatformRegistry { private val douyin = PlatformSpec("douyin", "抖音", "com.ss.android.ugc.aweme", true, supportsReplies = true) - private val xiaohongshu = PlatformSpec("xiaohongshu", "小红书", "com.xingin.xhs", true, contentUnit = "笔记") + private val xiaohongshu = PlatformSpec("xiaohongshu", "小红书", "com.xingin.xhs", true, + supportsReplies = true, contentUnit = "笔记") val platforms: List = listOf( douyin, @@ -65,7 +66,7 @@ object PlatformRegistry { val ui = AccessibleUi(service, spec.packageName, cancelled, pauseBetweenActions) return when (spec.id) { douyin.id -> DouyinAdapter(spec, ui, PhotoLibrary(service)) - xiaohongshu.id -> XiaohongshuAdapter(spec, ui) + xiaohongshu.id -> XiaohongshuAdapter(spec, ui, PhotoLibrary(service)) 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 3075dec..d7804fa 100644 --- a/app/src/main/java/com/jieliu/app/platform/XiaohongshuAdapter.kt +++ b/app/src/main/java/com/jieliu/app/platform/XiaohongshuAdapter.kt @@ -2,6 +2,9 @@ package com.jieliu.app.platform import android.graphics.Rect import android.view.accessibility.AccessibilityNodeInfo +import com.jieliu.app.data.PhotoLibrary +import com.jieliu.app.task.PendingComment +import com.jieliu.app.task.TemplatePhoto import java.io.Closeable import java.security.MessageDigest import kotlin.math.abs @@ -9,12 +12,14 @@ import kotlin.math.abs internal class XiaohongshuAdapter( private val spec: PlatformSpec, private val ui: AccessibleUi, + private val photoLibrary: PhotoLibrary, ) : PlatformAdapter { private data class SearchHeader(val editor: UiNode, val submit: UiNode) private data class ResultHeader(val query: UiNode, val tabs: UiNode) private data class ResultList(val list: UiNode, val viewport: Rect) private data class CardIdentity(val key: String, val title: String, val author: String) private data class ResultCard(val action: UiNode, val identity: CardIdentity) + private data class PreparedReply(val target: CommentTarget, val text: String) private data class NoteControls( val author: UiNode, val more: UiNode, @@ -43,11 +48,17 @@ internal class XiaohongshuAdapter( private var keyword: String? = null private val examinedCards = mutableSetOf() private var activeNote: NoteBinding? = null + private var commentNote: VideoContext? = null + private var preparedReply: PreparedReply? = null + private val comments = XiaohongshuComments(ui, ::matchesNote, ::openNoteComments) + private val composer = XiaohongshuReplyComposer(ui, photoLibrary, comments) + private val receipt = XiaohongshuReplyReceipt(ui, photoLibrary, comments) override fun launch() = ui.launchTarget(spec.label) override fun search(keyword: String): VideoContext { require(keyword.isNotBlank()) { "小红书搜索词不能为空" } + if (commentNote != null) closeComments() this.keyword = null examinedCards.clear() resetNote() @@ -84,7 +95,10 @@ internal class XiaohongshuAdapter( if (results != null) return@awaitPage ui.click(results.query) val entry = page.homeSearchEntry() if (entry != null) return@awaitPage ui.click(entry) - if (page.noteControls() != null && page.nodes.none { it.editable && it.focused }) return@awaitPage ui.back() + comments.dismissVideoPanelForSearch(page)?.let { return@awaitPage it } + if (page.noteControls() != null && page.nodes.none { it.editable && (it.focused || it.hasDraft()) }) { + return@awaitPage ui.back() + } null } if (!opened) throw PlatformException("小红书未确认已打开搜索框") @@ -299,12 +313,17 @@ internal class XiaohongshuAdapter( private fun UiPage.noteControls(): NoteControls? = imageNoteControls() ?: videoNoteControls() - private fun UiPage.imageNoteControls(): NoteControls? { + private fun UiPage.imageNoteHeader(): Pair? { val author = nodes.singleOrNull { it.resourceId == "nickNameTV" && it.isUneditableText() && it.bounds.centerY() <= y(.21f) } ?: return null val more = nodes.singleOrNull { it.resourceId == "moreOperateIV" && it.className == "android.widget.ImageView" && it.bounds.centerX() >= x(.82f) && it.bounds.centerY() <= y(.21f) && it.isNativeClick() } ?: return null if (author.bounds.top >= more.bounds.bottom || author.bounds.bottom <= more.bounds.top) return null + return author to more + } + + private fun UiPage.imageNoteControls(): NoteControls? { + val (author, more) = imageNoteHeader() ?: return null val prompt = nodes.singleOrNull { it.description == "评论框" && it.className == "android.widget.TextView" && it.bounds.centerY() >= y(.76f) && it.bounds.centerX() <= x(.49f) && it.isNativeClick() } ?: return null val toolbar = prompt.directParent()?.takeIf { it.className == "android.view.ViewGroup" } ?: return null @@ -372,13 +391,111 @@ internal class XiaohongshuAdapter( activeNote = null } - override fun openComments(expected: VideoContext): List = - throw PlatformException("小红书评论区暂未开放") + private fun matchesNote(page: UiPage, expected: VideoContext): Boolean { + val note = activeNote?.takeIf { it.video.key == expected.key && it.windowId == page.windowId } ?: return false + if (page.boundNote(note) != null) return true + val (author, more) = page.imageNoteHeader() ?: return false + return author.text == note.author && author.hasSource(note.authorSource) && more.hasSource(note.moreSource) + } + + private fun openNoteComments(page: UiPage, expected: VideoContext): Boolean { + val note = activeNote?.takeIf { it.video.key == expected.key } ?: return false + val controls = page.boundNote(note) ?: return false + if (page.nodes.any { it.editable && (it.focused || it.hasDraft()) }) return false + val button = page.nodes.singleOrNull { node -> + node.directParent() === controls.toolbar && node.className == "android.widget.Button" && + commentLabel.matches(node.description) && node.isNativeClick() + } ?: return false + return ui.click(button) + } + + override fun openComments(expected: VideoContext): List { + if (commentNote != null || currentVideo().key != expected.key) { + throw PlatformException("小红书当前笔记或评论区已变化") + } + preparedReply = null + return try { + comments.open(expected).also { commentNote = expected } + } catch (error: Exception) { + comments.reset() + throw error + } + } + + override fun scanComments(): List = comments.scan() + + override fun scrollComments(): Boolean { + if (preparedReply != null) throw PlatformException("请先完成或关闭当前小红书回复草稿") + return comments.scroll() + } + + override fun prepareReply(target: CommentTarget, expectedText: String): Boolean { + check(commentNote != null && preparedReply == null) { "请先确认小红书评论区和草稿状态" } + if (!receipt.captureBaseline(target, expectedText) || !composer.prepare(target)) return false + preparedReply = PreparedReply(target, expectedText) + return true + } + + override fun hasPreparedReplyBaseline(targetKey: String, text: String): Boolean = + preparedReply?.let { it.target.key == targetKey && it.text == text } == true override fun publishComment(text: String, beforeClick: () -> Unit): CommentPublishResult = - throw PlatformException("小红书暂未开放自动回复") + publishPrepared(text, emptyList(), beforeClick) - override fun closeComments() = Unit + override fun publishPhotoComment( + text: String, + photos: List, + beforeClick: () -> Unit, + ): CommentPublishResult = publishPrepared(text, photos, beforeClick) + + private fun publishPrepared( + text: String, + photos: List, + beforeClick: () -> Unit, + ): CommentPublishResult { + val reply = preparedReply?.takeIf { it.text == text } + ?: throw PlatformException("小红书原评论或回复话术已变化,未触发发送") + var armedAt: Long? = null + try { + val clicked = composer.submit(reply.target, text, photos) { + check(armedAt == null) { "小红书回复已记录提交意图" } + beforeClick() + armedAt = System.currentTimeMillis() + } + val since = armedAt ?: throw PlatformException("小红书未能记录回复提交意图") + if (!clicked || !composer.closedAfterSubmit()) return CommentPublishResult.UNCERTAIN + return confirmReceipt(reply.target.key, reply.target.author, text, photos, since) + } finally { + composer.close() + preparedReply = null + } + } + + override fun confirmPendingReply(video: VideoContext, pending: PendingComment): CommentPublishResult { + if (video.key != commentNote?.key || video.key != pending.videoKey) return CommentPublishResult.UNCERTAIN + val target = pending.targetKey ?: return CommentPublishResult.UNCERTAIN + val author = pending.targetAuthor ?: return CommentPublishResult.UNCERTAIN + val since = pending.armedAtEpochMs ?: return CommentPublishResult.UNCERTAIN + return confirmReceipt(target, author, pending.text, pending.photos, since) + } + + private fun confirmReceipt( + targetKey: String, + author: String, + text: String, + photos: List, + armedAt: Long, + ): CommentPublishResult = receipt.confirm(targetKey, author, text, photos, armedAt).also { result -> + if (result == CommentPublishResult.CONFIRMED && photos.isNotEmpty()) photoLibrary.cleanupStaged() + } + + override fun closeComments() { + if (commentNote == null) return + comments.close() + composer.close() + preparedReply = null + commentNote = null + } private fun UiNode.isNativeClick(): Boolean = enabled && supports(AccessibilityNodeInfo.ACTION_CLICK) diff --git a/app/src/main/java/com/jieliu/app/platform/XiaohongshuComments.kt b/app/src/main/java/com/jieliu/app/platform/XiaohongshuComments.kt new file mode 100644 index 0000000..d1e649c --- /dev/null +++ b/app/src/main/java/com/jieliu/app/platform/XiaohongshuComments.kt @@ -0,0 +1,419 @@ +package com.jieliu.app.platform + +import android.graphics.Rect +import android.view.accessibility.AccessibilityNodeInfo +import java.io.Closeable +import java.security.MessageDigest +import kotlin.math.abs + +internal data class XhsCommentSurface( + val root: UiNode, + val viewport: Rect, + val windowId: Int, + val heading: UiNode?, + val inline: Boolean, + val empty: Boolean, +) + +internal data class XhsCommentRow( + val target: CommentTarget, + val container: UiNode, + val reply: UiNode?, + val author: UiNode, + val body: UiNode, +) + +internal data class XhsCommentThread(val replies: List, val complete: Boolean, val expand: UiNode?) + +internal data class XhsReplyRow( + val body: UiNode, + val own: Boolean, + val photos: List, + val timeLabel: String?, + val identity: String, +) + +internal class XiaohongshuComments( + private val ui: AccessibleUi, + private val matchesNote: (UiPage, VideoContext) -> Boolean, + private val openVideoComments: (UiPage, VideoContext) -> Boolean, +) { + private data class Origin(val windowId: Int, val inline: Boolean) + + private class Session( + val note: VideoContext, + val inline: Boolean, + val windowId: Int, + val root: UiNodeSource, + val heading: UiNodeSource?, + ) : Closeable { + override fun close() { + root.close() + heading?.close() + } + } + + private data class RowParts(val author: UiNode, val body: UiNode, val nextTop: Int) + private data class Continuation(val blocking: Boolean, val action: UiNode?) + + private var active: Session? = null + + fun open(expected: VideoContext): List { + if (active != null) throw PlatformException("小红书评论区仍处于打开状态") + val origin = ui.inspect { page -> + if (!matchesNote(page, expected)) return@inspect null + val image = page.nodes.any { it.resourceId == "nickNameTV" } + val video = page.nodes.any { it.resourceId == "matrixNickNameView" } + if (image == video) return@inspect null + Origin(page.windowId, inline = image) + } ?: throw PlatformException("小红书当前笔记无法核对,未打开评论区") + + val initial = ui.inspect { page -> + if (!origin.inline || page.windowId != origin.windowId || !matchesNote(page, expected)) return@inspect null + page.initialSurface(inline = true)?.let { retainSession(expected, it) } + } + if (initial != null) { + active = initial + return scan().map(CommentTarget::text) + } + + ui.pace() + val opened = ui.inspect { page -> page.windowId == origin.windowId && matchesNote(page, expected) && + !page.hasActiveDraft() && openVideoComments(page, expected) } + if (opened != true) throw PlatformException("小红书未确认打开本条笔记的评论区") + val session = ui.await(7_000) { + ui.inspect { page -> + if (origin.inline) { + if (page.windowId != origin.windowId || !matchesNote(page, expected)) return@inspect null + } else if (page.windowId == origin.windowId || matchesNote(page, expected)) { + return@inspect null + } + val surface = page.initialSurface(origin.inline) ?: return@inspect null + retainSession(expected, surface) + } + } ?: throw PlatformException("小红书未显示可核对的评论列表") + active = session + return scan().map(CommentTarget::text) + } + + fun scan(): List = ui.await(3_000) { + ui.inspect { page -> + val visible = surface(page) ?: return@inspect null + originalRows(page, visible).filter { it.reply != null }.map(XhsCommentRow::target) + } + } ?: throw PlatformException("小红书评论区已变化,无法读取评论") + + fun scroll(): Boolean { + ui.pace() + val before = ui.inspect { page -> + val visible = surface(page)?.takeUnless { it.empty } ?: return@inspect null + if (!visible.root.scrollable || page.hasActiveDraft() || + visible.viewport.height() < page.bounds.height() * .15f) return@inspect null + val anchors = page.commentPositions(visible) + anchors.takeIf { ui.scrollUpInside(visible.viewport) } + } ?: return false + var previous: Map? = null + var moved = false + ui.await(2_500) { + ui.inspect { page -> + val visible = surface(page) ?: return@inspect null + val after = page.commentPositions(visible) + if (after.isEmpty()) return@inspect null + moved = moved || before.keys != after.keys || after.any { (key, y) -> abs((before[key] ?: y) - y) >= 5 } + val preceding = previous + previous = after + true.takeIf { moved && preceding != null && preceding.keys == after.keys && + after.all { (key, y) -> abs((preceding[key] ?: y) - y) <= 2 } } + } + } + return moved + } + + fun close() { + val session = active ?: return + if (session.inline) { + if (ui.inspect { page -> matchesNote(page, session.note) && !page.hasActiveDraft() } != true) { + throw PlatformException("小红书原笔记或评论草稿状态已变化") + } + } else { + ui.pace() + val closed = ui.inspect { page -> + if (matchesNote(page, session.note) && !page.hasActiveDraft()) return@inspect true + val visible = surface(page) ?: return@inspect false + if (page.hasActiveDraft()) return@inspect false + val close = page.modalCloseControl(visible) + if (close != null) ui.click(close) else ui.back() + } + if (closed != true || ui.await(4_000) { + ui.inspect { page -> true.takeIf { matchesNote(page, session.note) && !page.hasActiveDraft() } } + } != true) { + throw PlatformException("关闭小红书评论区后未能核对原笔记") + } + } + reset() + } + + fun reset() { + active?.close() + active = null + } + + fun dismissVideoPanelForSearch(page: UiPage): Boolean? { + if (active != null || page.hasActiveDraft() || page.nodes.any { it.resourceId in noteMarkers }) return null + val panel = page.initialSurface(inline = false) ?: return null + val close = page.modalCloseControl(panel) ?: return null + return ui.click(close) + } + + fun surface(page: UiPage): XhsCommentSurface? { + val session = active ?: return null + if (page.windowId != session.windowId || (session.inline && !matchesNote(page, session.note))) return null + val list = page.nodes.singleOrNull { it.hasSource(session.root) } ?: return null + val heading = page.commentHeading()?.takeIf { label -> session.heading?.let(label::hasSource) == true } + if (heading != null && list === heading && XhsCommentLabels.commentCount(heading.text) == 0) { + return XhsCommentSurface(list, Rect(list.bounds), page.windowId, heading, session.inline, empty = true) + } + if (!session.inline && heading == null) return null + val footer = if (page.nodes.any { it.editable && it.focused }) page.focusedCommentFooter(list, heading) + else page.commentFooter(session.inline) + return footer?.let { page.surfaceFor(list, heading, session.inline, it) } + } + + fun row(page: UiPage, targetKey: String): XhsCommentRow? { + val visible = surface(page) ?: return null + return originalRows(page, visible).singleOrNull { it.target.key == targetKey } + } + + fun thread(page: UiPage, parent: XhsCommentRow): XhsCommentThread? { + val visible = surface(page) ?: return null + val current = originalRows(page, visible).singleOrNull { it.target == parent.target && it.container === parent.container } + ?: return null + val slots = page.commentSlots(visible) + val start = slots.indexOf(current.container).takeIf { it >= 0 } ?: return null + val replies = mutableListOf() + val inlineReplies = page.nestedRows(visible, current.container, parent.target.key, current.body.bounds.bottom) + ?: return XhsCommentThread(replies, complete = false, expand = null) + replies.addAll(inlineReplies) + val inside = page.continuation(visible, current.container, current.body.bounds.bottom) + if (inside.blocking) return XhsCommentThread(replies, complete = false, expand = inside.action) + + var bottom = current.container.bounds.bottom + for (slot in slots.drop(start + 1)) { + val gap = slot.bounds.top - bottom + if (gap < -2 || gap > visible.viewport.width() * .04f || slot.bounds.top >= visible.viewport.bottom) break + if (page.parts(visible, slot, nested = false).size == 1) { + return XhsCommentThread(replies, complete = true, expand = null) + } + val more = page.continuation(visible, slot, slot.bounds.top) + if (more.blocking) return XhsCommentThread(replies, complete = false, expand = more.action) + val nested = page.nestedRows(visible, slot, current.target.key, slot.bounds.top) + if (nested.isNullOrEmpty()) { + val terminal = page.nodes.any { (it === slot || it.isDescendantOf(slot)) && it.text == "没有更多评论了" } + return XhsCommentThread(replies, complete = terminal, expand = null) + } + replies.addAll(nested) + bottom = slot.bounds.bottom + } + return XhsCommentThread(replies, complete = slots.lastOrNull()?.bounds?.bottom == bottom && + bottom < visible.viewport.bottom - 2 && !visible.root.scrollable && + !visible.root.supports(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD), + expand = null) + } + + private fun UiPage.initialSurface(inline: Boolean): XhsCommentSurface? { + val heading = commentHeading() ?: return null + val footer = commentFooter(inline) ?: return null + if (heading.bounds.bottom >= footer.bounds.top) return null + val list = nodes.singleOrNull { node -> + node.className == RECYCLER && node.bounds.width() >= bounds.width() * .84f && + node.bounds.height() >= bounds.height() * .14f && node.bounds.bottom > heading.bounds.bottom && + node.bounds.bottom <= footer.bounds.bottom && if (inline) heading.isDescendantOf(node) else + (heading.isDescendantOf(node) || node.bounds.top >= heading.bounds.top && + shareNearParent(heading, node, maxDepth = 4)) + } + if (list == null && XhsCommentLabels.commentCount(heading.text) == 0) { + return XhsCommentSurface(heading, Rect(heading.bounds), windowId, heading, inline, empty = true) + } + return list?.let { surfaceFor(it, heading, inline, footer) } + } + + private fun retainSession(note: VideoContext, surface: XhsCommentSurface): Session = Session(note, + surface.inline, surface.windowId, surface.root.retainSource(), surface.heading?.retainSource()) + + private fun UiPage.surfaceFor(list: UiNode, heading: UiNode?, inline: Boolean, footer: UiNode): XhsCommentSurface? { + val viewport = Rect(list.bounds) + if (!viewport.intersect(bounds)) return null + if (heading != null) viewport.top = maxOf(viewport.top, heading.bounds.bottom) + viewport.bottom = minOf(viewport.bottom, footer.bounds.top) + if (viewport.isEmpty) return null + return XhsCommentSurface(list, viewport, windowId, heading, inline, + empty = heading?.let { XhsCommentLabels.commentCount(it.text) } == 0) + } + + private fun UiPage.commentHeading(): UiNode? = nodes.singleOrNull { node -> + node.commentText() && XhsCommentLabels.commentCount(node.text) != null && + node.bounds.centerX() <= x(.67f) && node.bounds.centerY() <= y(.72f) + } + + private fun UiPage.commentFooter(inline: Boolean): UiNode? = nodes.singleOrNull { node -> + !node.editable && node.bounds.centerX() <= x(.57f) && node.bounds.centerY() >= y(.72f) && + (node.description == "评论框" || !inline && node.text in commentPlaceholders) && + node.className in setOf("android.widget.TextView", "android.widget.Button", "android.view.ViewGroup") + } + + private fun UiPage.focusedCommentFooter(list: UiNode, heading: UiNode?): UiNode? { + val editor = nodes.singleOrNull { it.editable && it.focused } ?: return null + return editor.takeIf { node -> + node.className == "android.widget.EditText" && node.enabled && + node.supports(AccessibilityNodeInfo.ACTION_SET_TEXT) && node.bounds.width() >= bounds.width() * .38f && + node.bounds.centerY() >= y(.55f) && node.bounds.top > (heading?.bounds?.bottom ?: list.bounds.top) && + node.bounds.centerX() in list.bounds.left until list.bounds.right && + bounds.contains(node.bounds) && shareNearParent(node, list, maxDepth = 6) + } + } + + private fun UiPage.modalCloseControl(surface: XhsCommentSurface): UiNode? { + val heading = surface.heading ?: return null + return nodes.singleOrNull { node -> + node.isNativeClick() && node.labels().singleOrNull() in closeLabels && node.bounds.centerX() >= x(.75f) && + abs(node.bounds.centerY() - heading.bounds.centerY()) <= heading.bounds.height() && + shareNearParent(heading, node, maxDepth = 3) + } + } + + private fun UiPage.hasActiveDraft(): Boolean = nodes.any { it.editable && (it.focused || it.hasDraft()) } + + private fun UiPage.commentSlots(surface: XhsCommentSurface): List = + nodes.filter { it.directParent() === surface.root && Rect.intersects(it.bounds, surface.viewport) } + .sortedBy { it.bounds.top } + + private fun originalRows(page: UiPage, visible: XhsCommentSurface): List { + val note = active?.note ?: return emptyList() + if (visible.empty) return emptyList() + val candidates = page.commentSlots(visible).mapNotNull { slot -> + val original = page.parts(visible, slot, nested = false).singleOrNull() ?: return@mapNotNull null + if (page.isOwn(original)) return@mapNotNull null + val author = original.author + val body = original.body + val reply = page.nodes.singleOrNull { node -> + node.isDescendantOf(slot) && node.isNativeClick() && + node.className in replyControlClasses && node.labels().singleOrNull() == "回复" && + node.bounds.top >= body.bounds.bottom && node.bounds.bottom <= original.nextTop && + node.bounds.left >= author.bounds.left && visible.viewport.contains(node.bounds) + } + val target = CommentTarget(identity(note.key, author.text, body.text), body.text, author.text) + XhsCommentRow(target, slot, reply, author, body) + } + val counts = candidates.groupingBy { it.target.key }.eachCount() + return candidates.filter { counts[it.target.key] == 1 } + } + + private fun UiPage.parts(surface: XhsCommentSurface, slot: UiNode, nested: Boolean): List { + val width = surface.viewport.width() + val avatars = nodes.filter { node -> node.isDescendantOf(slot) && node.isNativeClick() && + node.className == "android.widget.ImageView" && node.bounds.width() in (width * .035f).toInt()..(width * .14f).toInt() && + abs(node.bounds.width() - node.bounds.height()) <= width * .025f && + node.bounds.centerY() in surface.viewport.top until surface.viewport.bottom && + node.bounds.centerX() in (surface.viewport.left + width * .07f).toInt()..(surface.viewport.left + width * .34f).toInt() } + .sortedBy { it.bounds.top } + return avatars.mapIndexedNotNull { index, avatar -> + val isNested = avatar.bounds.centerX() >= surface.viewport.left + width * .18f + if (isNested != nested) return@mapIndexedNotNull null + val nextTop = avatars.drop(index + 1).firstOrNull { it.bounds.top > avatar.bounds.top + 2 }?.bounds?.top + ?: slot.bounds.bottom + val author = nodes.singleOrNull { node -> + node.isDescendantOf(slot) && node.commentText() && node.isNativeClick() && + abs(node.bounds.top - avatar.bounds.top) <= avatar.bounds.height() / 3 && + node.bounds.left in avatar.bounds.right..(avatar.bounds.right + (width * .10f).toInt()) && + surface.viewport.contains(node.bounds) + } ?: return@mapIndexedNotNull null + val body = nodes.singleOrNull { node -> + node.isDescendantOf(slot) && node.commentText() && !node.clickable && + abs(node.bounds.left - author.bounds.left) <= width * .025f && node.bounds.width() >= width * .48f && + node.bounds.top in (author.bounds.bottom - 2)..(author.bounds.bottom + (width * .05f).toInt()) && + node.bounds.bottom <= nextTop && surface.viewport.contains(node.bounds) + } ?: return@mapIndexedNotNull null + RowParts(author, body, nextTop) + } + } + + private fun UiPage.isOwn(parts: RowParts): Boolean { + val meta = parts.author.directParent() ?: return false + return nodes.count { node -> node !== parts.author && node.directParent() === meta && !node.clickable && + node.commentText() && node.labels().singleOrNull() in ownLabels && node.bounds.left >= parts.author.bounds.right && + abs(node.bounds.centerY() - parts.author.bounds.centerY()) <= parts.author.bounds.height() / 2 } == 1 + } + + private fun UiPage.nestedRows(surface: XhsCommentSurface, slot: UiNode, parentKey: String, after: Int): List? { + val candidates = parts(surface, slot, nested = true).filter { it.author.bounds.top >= after } + val unexplained = nodes.any { node -> node.isDescendantOf(slot) && node.className == "android.widget.ImageView" && + node.isNativeClick() && node.bounds.top >= after && node.bounds.centerX() in + (surface.viewport.left + surface.viewport.width() * .18f).toInt()..(surface.viewport.left + surface.viewport.width() * .34f).toInt() && + node.bounds.width() in (surface.viewport.width() * .035f).toInt()..(surface.viewport.width() * .14f).toInt() && + abs(node.bounds.width() - node.bounds.height()) <= surface.viewport.width() * .025f && + candidates.none { abs(it.author.bounds.top - node.bounds.top) <= node.bounds.height() / 3 } } + if (unexplained) return null + return candidates.map { parts -> + val detail = nodes.filter { node -> node.isDescendantOf(slot) && node.bounds.top >= parts.body.bounds.bottom && + node.bounds.bottom <= parts.nextTop && node.bounds.left >= parts.body.bounds.left - 2 } + val time = detail.filter { it.commentText() }.mapNotNull { XhsCommentLabels.relativeTime(it.text) }.distinct().singleOrNull() + val images = detail.filter { it.className in attachmentClasses && + it.bounds.width() >= surface.viewport.width() * .105f && it.bounds.height() >= surface.viewport.width() * .09f } + if (images.any { !it.isNativeClick() || !XhsCommentLabels.photoDescription(it.description) || + !surface.viewport.contains(it.bounds) }) return null + if (images.indices.any { i -> images.take(i).any { Rect.intersects(it.bounds, images[i].bounds) } }) return null + val own = isOwn(parts) + XhsReplyRow(parts.body, own, images.sortedWith(compareBy({ it.bounds.top }, { it.bounds.left })), time, + identity(parentKey, parts.author.text, parts.body.text, images.size.toString())) + } + } + + private fun UiPage.continuation(surface: XhsCommentSurface, slot: UiNode, after: Int): Continuation { + val labels = nodes.filter { node -> (node === slot || node.isDescendantOf(slot)) && node.bounds.top >= after && + node.labels().any(XhsCommentLabels::blocksThreadBoundary) } + val unique = labels.singleOrNull() + val action = unique?.takeIf { node -> node.isNativeClick() && node.className in replyControlClasses && + surface.viewport.contains(node.bounds) && XhsCommentLabels.expandsReplies(node.labels().singleOrNull().orEmpty()) } + return Continuation(labels.isNotEmpty(), action) + } + + private fun UiPage.commentPositions(surface: XhsCommentSurface): Map = nodes.asSequence() + .filter { it.isDescendantOf(surface.root) && it.commentText() && it.bounds.width() >= surface.viewport.width() * .35f && + surface.viewport.contains(it.bounds.centerX(), it.bounds.centerY()) } + .groupBy { it.text }.mapNotNull { (body, hits) -> hits.singleOrNull()?.let { identity(body) to it.bounds.top } }.toMap() + + private fun shareNearParent(first: UiNode, second: UiNode, maxDepth: Int): Boolean = + generateSequence(first.directParent(), UiNode::directParent).take(maxDepth).any { second.isDescendantOf(it) } + + private fun UiNode.commentText(): Boolean = className == "android.widget.TextView" && !editable && text.isNotBlank() + + private fun UiNode.isNativeClick(): Boolean = enabled && supports(AccessibilityNodeInfo.ACTION_CLICK) + + private fun identity(vararg values: String): String = MessageDigest.getInstance("SHA-256") + .digest(values.joinToString("\u0000").toByteArray(Charsets.UTF_8)).joinToString("") { "%02x".format(it) } + + private companion object { + const val RECYCLER = "androidx.recyclerview.widget.RecyclerView" + val noteMarkers = setOf("nickNameTV", "moreOperateIV", "matrixNickNameView", "noteContentText") + val commentPlaceholders = setOf("说点什么...", "说点什么…") + val closeLabels = setOf("关闭", "关闭评论", "关闭评论区") + val ownLabels = setOf("我", "我发布的评论", "我发布的回复") + val replyControlClasses = setOf("android.widget.TextView", "android.widget.Button") + val attachmentClasses = setOf("android.widget.ImageView", "android.view.View") + } +} + +internal object XhsCommentLabels { + private val heading = Regex("共\\s*(\\d+)\\s*条评论") + private val empty = setOf("暂无评论", "还没有评论") + private val relativeTime = Regex("^(刚刚|[1-9][0-9]?\\s*分钟前|(?:[1-5][0-9]|[1-9])\\s*秒前)(?:\\s|$)") + private val expand = Regex("(?:展开|查看)\\s*[1-9][0-9]*\\s*条回复|展开更多回复") + private val unknown = Regex("(?:展开|查看).{0,16}(?:回复|更多)") + private val photo = Regex("(?:查看)?图片(?:\\s*[1-9][0-9]*)?") + + fun commentCount(text: String): Int? = if (text in empty) 0 else heading.matchEntire(text)?.groupValues?.get(1)?.toIntOrNull() + fun relativeTime(text: String): String? = relativeTime.find(text)?.groupValues?.get(1) + fun expandsReplies(label: String): Boolean = expand.matches(label) + fun blocksThreadBoundary(label: String): Boolean = expandsReplies(label) || unknown.matches(label) + fun photoDescription(label: String): Boolean = photo.matches(label) +} diff --git a/app/src/main/java/com/jieliu/app/platform/XiaohongshuReplyComposer.kt b/app/src/main/java/com/jieliu/app/platform/XiaohongshuReplyComposer.kt new file mode 100644 index 0000000..50d2109 --- /dev/null +++ b/app/src/main/java/com/jieliu/app/platform/XiaohongshuReplyComposer.kt @@ -0,0 +1,397 @@ +package com.jieliu.app.platform + +import android.graphics.Rect +import android.view.accessibility.AccessibilityNodeInfo +import com.jieliu.app.data.PhotoLibrary +import com.jieliu.app.task.TaskPlan +import com.jieliu.app.task.TemplatePhoto +import java.io.Closeable + +/** The XHS reply and picker anchors still require device verification. */ +internal class XiaohongshuReplyComposer( + private val ui: AccessibleUi, + private val photos: PhotoLibrary, + private val comments: XiaohongshuComments, +) : Closeable { + private class Prepared( + val target: CommentTarget, + val windowId: Int, + val surface: UiNodeSource, + val container: UiNodeSource, + val editor: UiNodeSource, + ) : Closeable { + var claimed = false + var sendAttempted = false + + override fun close() { + editor.close() + container.close() + surface.close() + } + } + + private data class Composer(val editor: UiNode, val container: UiNode) + private data class AlbumTile(val image: UiNode, val select: UiNode, val ordinal: Int) + private data class Picker(val tiles: List, val done: UiNode, val count: Int) + private data class PickerSnapshot(val windowId: Int, val images: List) + private data class DraftSnapshot(val windowId: Int, val images: List) + private data class ReadyDraft(val send: UiNode, val snapshot: DraftSnapshot) + + private var prepared: Prepared? = null + + /** False leaves the current comments list untouched so the caller can scan another row. */ + fun prepare(target: CommentTarget): Boolean { + close() + ui.pace() + val opened = ui.inspect { page -> + val surface = comments.surface(page) ?: throw PlatformException("小红书评论区已变化") + val row = comments.row(page, target.key)?.takeIf { it.target == target } ?: return@inspect null + val reply = row.reply?.takeIf { + it.isDescendantOf(row.container) && row.container.bounds.contains(it.bounds) && + surface.viewport.contains(it.bounds) && it.nativeClick() + } ?: return@inspect null + if (page.hasPrivateDraft() || page.nodes.any { it.editable && (it.focused || it.hasReplyPrompt()) }) { + throw PlatformException("小红书评论区已有草稿、附件或打开的回复框,请处理后继续") + } + + val anchor = surface.root.retainSource() + try { + if (!ui.click(reply)) throw PlatformException("未确认小红书已打开选中评论的回复框") + surface.windowId to anchor + } catch (error: Throwable) { + anchor.close() + throw error + } + } ?: return false + + val (windowId, anchor) = opened + try { + prepared = awaitPage(5_000, "无法核对小红书回复对象或空白回复框") { page -> + if (!page.matchesTarget(target, windowId, anchor)) return@awaitPage null + val composer = page.openedComposer(target) ?: return@awaitPage null + val thumbnails = page.draftThumbnails(composer) ?: return@awaitPage null + if (composer.editor.hasDraft() || thumbnails.isNotEmpty()) { + throw PlatformException("小红书回复框已有草稿或附件,请处理后继续") + } + if (!composer.editor.isStillBlankAndFocused()) return@awaitPage null + Prepared(target, windowId, anchor, composer.container.retainSource(), composer.editor.retainSource()) + } + return true + } finally { + if (prepared == null) anchor.close() + } + } + + /** Returns whether the one native send action was accepted. Publication still requires a receipt. */ + fun submit(target: CommentTarget, text: String, attachments: List, beforeClick: () -> Unit): Boolean { + val session = prepared?.takeIf { it.target == target && !it.claimed } + ?: throw PlatformException("尚未核对小红书的回复对象") + require(text.isNotBlank() && attachments.size <= TaskPlan.MAX_TEMPLATE_PHOTOS) + session.claimed = true + ui.pace() + val blank = ui.inspect { page -> + val composer = page.checkedComposer(session) ?: return@inspect false + composer.editor.isStillBlankAndFocused() && page.draftThumbnails(composer)?.isEmpty() == true + } == true + if (!blank) throw PlatformException("小红书回复框已变化或已有草稿,未修改内容") + + val references = if (attachments.isEmpty()) emptyList() else { + photos.readReceiptPixels(attachments) ?: throw PlatformException("无法读取小红书回复的绑定图片") + } + val staged = if (references.isEmpty()) null else { + photos.cleanupStaged() + photos.stage(attachments) + } + var broughtIntoDraft = false + try { + if (staged != null) attach(session, staged.albumName, references) { broughtIntoDraft = true } + val written = ui.inspect { page -> + val composer = page.checkedComposer(session) ?: return@inspect false + if (page.draftThumbnails(composer)?.size != references.size) return@inspect false + ui.setText(composer.editor, text, requireBlankFocusedInput = true) + } == true + if (!written) throw PlatformException("小红书回复框没有接受完整文本") + + ui.pace() + val ready = awaitPage(5_000, "小红书未回读到完整回复、附件和唯一发送按钮") { page -> + page.readyDraft(session, text, references.size)?.snapshot + } + if (references.isNotEmpty()) { + verifyPhotos(references, ready.windowId, ready.images, "小红书回复草稿的图片与绑定图片不符") + } + + val current = ui.inspect { page -> page.readyDraft(session, text, references.size)?.snapshot } == ready + if (!current) throw PlatformException("小红书回复框或图片已变化,未触发发送") + beforeClick() + return ui.inspect { page -> + val draft = page.readyDraft(session, text, references.size)?.takeIf { it.snapshot == ready } ?: return@inspect false + session.sendAttempted = true + ui.click(draft.send) + } == true + } finally { + if (staged != null) { + if (broughtIntoDraft) photos.leaveStagedForReview(staged) else photos.removeStaged(staged) + } + } + } + + /** Checks dismissal only. An image or text receipt is evaluated separately by the comment adapter. */ + fun closedAfterSubmit(): Boolean { + val session = prepared?.takeIf { it.sendAttempted } ?: return false + return ui.await(3_000) { + ui.inspect { page -> + if (!page.matchesTarget(session.target, session.windowId, session.surface)) return@inspect null + if (page.hasPrivateDraft() || page.nodes.any { it.editable && (it.focused || it.hasReplyPrompt()) }) return@inspect null + val oldContainer = page.nodes.singleOrNull { it.hasSource(session.container) } + val oldEditor = page.nodes.singleOrNull { it.hasSource(session.editor) } + if (page.nodes.any { node -> node.replyCue(session.target) || + (oldContainer != null && node.isDescendantOf(oldContainer) && node.hasReplyPrompt()) }) return@inspect null + if ((oldContainer == null) != (oldEditor == null)) return@inspect null + if (oldContainer != null && oldEditor != null) { + if (page.draftThumbnails(Composer(oldEditor, oldContainer))?.isEmpty() != true) return@inspect null + } + true + } + } == true + } + + override fun close() { + prepared?.close() + prepared = null + } + + private fun attach(session: Prepared, album: String, references: List, beforeAttach: () -> Unit) { + ui.pace() + val pickerOpened = ui.inspect { page -> + val composer = page.checkedComposer(session) ?: return@inspect false + if (!composer.editor.isStillBlankAndFocused() || page.draftThumbnails(composer)?.isEmpty() != true) return@inspect false + val action = page.composerActions(composer, imageActions).singleOrNull() ?: return@inspect false + ui.click(action) + } == true + if (!pickerOpened) throw PlatformException("小红书未打开已核对回复框的相册") + + val openAlbumList = awaitPage(6_000, "小红书相册页或相册分类控件不可核对") { page -> + if (page.albumHeading(setOf(album)) != null) return@awaitPage false + val heading = page.albumHeading(pickerHeadings) ?: return@awaitPage null + val toggle = heading.nativeAction() ?: return@awaitPage null + if (!ui.click(toggle)) throw PlatformException("小红书未接受相册分类操作") + true + } + if (openAlbumList) { + awaitPage(6_000, "小红书相册没有唯一的本次专用相册") { page -> + val label = page.nodes.singleOrNull { + !it.editable && it.hasExactLabel(album) && it.bounds.centerY() > page.y(.14f) + } ?: return@awaitPage null + val item = label.nativeAction() ?: return@awaitPage null + if (!ui.click(item)) throw PlatformException("小红书未打开本次专用相册") + true + } + } + + val empty = awaitPage(6_000, "小红书专用相册未完整显示所有可多选图片") { page -> + val picker = page.picker(album, references.size) ?: return@awaitPage null + if (picker.count != 0 || picker.tiles.any { it.ordinal != 0 }) { + throw PlatformException("小红书相册已有选中图片,未修改选择") + } + picker.snapshot(page.windowId) + } + val crops = ui.screenshotPhotos(empty.windowId, empty.images) + ?.takeIf { it.size == references.size } ?: throw PlatformException("无法核对小红书专用相册的全部缩略图") + val order = references.map { reference -> + crops.indices.singleOrNull { PublishedPhotoMatcher.matches(reference, crops[it]) } + ?: throw PlatformException("小红书专用相册中的图片无法唯一对应本次附件") + } + if (order.toSet().size != references.size) throw PlatformException("小红书专用相册出现重复图片匹配") + + val selected = MutableList(references.size) { 0 } + for ((index, tileIndex) in order.withIndex()) { + ui.pace() + val accepted = ui.inspect { page -> + val picker = page.picker(album, references.size) ?: return@inspect false + if (!picker.matches(empty, page.windowId, selected, index)) return@inspect false + ui.click(picker.tiles[tileIndex].select) + } == true + if (!accepted) throw PlatformException("小红书专用相册未接受第 ${index + 1} 张图片") + selected[tileIndex] = index + 1 + awaitPage(4_000, "小红书未核对第 ${index + 1} 张附件的选中顺序") { page -> + true.takeIf { page.picker(album, references.size)?.matches(empty, page.windowId, selected, index + 1) == true } + } + } + + ui.pace() + val returned = ui.inspect { page -> + val picker = page.picker(album, references.size) ?: return@inspect false + if (!picker.matches(empty, page.windowId, selected, references.size) || !picker.done.nativeClick()) return@inspect false + beforeAttach() + ui.click(picker.done) + } == true + if (!returned) throw PlatformException("小红书未确认将选中的图片带回回复框") + awaitPage(6_000, "小红书回复框未完整回读全部图片附件") { page -> + val composer = page.checkedComposer(session) ?: return@awaitPage null + true.takeIf { composer.editor.isStillBlankAndFocused() && page.draftThumbnails(composer)?.size == references.size } + } + } + + private fun verifyPhotos(references: List, windowId: Int, bounds: List, failure: String) { + val crops = ui.screenshotPhotos(windowId, bounds) ?: throw PlatformException(failure) + if (crops.size != references.size || references.indices.any { !PublishedPhotoMatcher.matches(references[it], crops[it]) }) { + throw PlatformException(failure) + } + } + + private fun UiPage.matchesTarget(target: CommentTarget, windowId: Int, surfaceSource: UiNodeSource): Boolean { + val surface = comments.surface(this) ?: return false + return this.windowId == windowId && surface.windowId == windowId && surface.root.hasSource(surfaceSource) && + comments.row(this, target.key)?.target == target + } + + private fun UiPage.hasPrivateDraft(): Boolean = nodes.any { + it.editable && it.hasDraft() || it.labels().any(removeActions::contains) || + it.isImage() && it.labels().any(previewLabels::contains) + } + + private fun UiPage.openedComposer(target: CommentTarget): Composer? { + val row = comments.row(this, target.key)?.takeIf { it.target == target } ?: return null + val editor = nodes.singleOrNull { it.canEdit() && it.focused && it.bounds.centerY() >= y(.40f) && + it.bounds.width() >= bounds.width() * .25f } ?: return null + val container = generateSequence(editor.directParent()) { it.directParent() }.take(4).firstOrNull { scope -> + scope.bounds.contains(editor.bounds) && scope.bounds.height() <= bounds.height() * .50f && + scope !== row.container && !row.container.isDescendantOf(scope) && + nodes.none { it !== editor && it.editable && it.isDescendantOf(scope) } && + (editor.replyCue(target) || nodes.any { it.isDescendantOf(scope) && it.replyCue(target) }) && + nodes.any { it.isDescendantOf(scope) && it.labels().any { label -> label in sendActions || label in imageActions } } + } ?: return null + return Composer(editor, container) + } + + private fun UiPage.checkedComposer(session: Prepared): Composer? { + if (!matchesTarget(session.target, session.windowId, session.surface)) return null + val container = nodes.singleOrNull { it.hasSource(session.container) } ?: return null + val editor = nodes.singleOrNull { it.focused && it.canEdit() && it.hasSource(session.editor) && + it.isDescendantOf(container) && container.bounds.contains(it.bounds) } ?: return null + if (nodes.any { it !== editor && it.editable && it.focused }) return null + if (!editor.replyCue(session.target) && editor.hint.isNotEmpty() && !editor.hasDraft() && + nodes.none { it.isDescendantOf(container) && it.replyCue(session.target) }) return null + return Composer(editor, container) + } + + private fun UiPage.readyDraft(session: Prepared, text: String, count: Int): ReadyDraft? { + val composer = checkedComposer(session) ?: return null + val editor = composer.editor + if (editor.text != text || !editor.hasCurrentFocusedText(text) { matchesReplyCue(it, session.target) }) return null + val previews = draftThumbnails(composer)?.takeIf { it.size == count } ?: return null + val send = composerActions(composer, sendActions).singleOrNull { action -> + action.bounds.centerX() > editor.bounds.centerX() && + action.bounds.centerY() >= editor.bounds.top && action.bounds.top <= editor.bounds.bottom + editor.bounds.height() * 2 + } ?: return null + return ReadyDraft(send, DraftSnapshot(windowId, previews.map { Rect(it.bounds) })) + } + + private fun UiPage.composerActions(composer: Composer, labels: Set): List = nodes.asSequence() + .filter { !it.editable && it.isDescendantOf(composer.container) && it.labels().any(labels::contains) } + .mapNotNull { it.nativeAction() } + .filter { it.isDescendantOf(composer.container) && composer.container.bounds.contains(it.bounds) } + .distinct().toList() + + private fun UiPage.draftThumbnails(composer: Composer): List? { + val scoped = nodes.filter { it.isDescendantOf(composer.container) } + val removals = scoped.filter { it.labels().any(removeActions::contains) }.mapNotNull { it.nativeAction() }.distinct() + val threshold = maxOf(24, composer.editor.bounds.height() / 2) + val previews = scoped.filter { node -> + node.isImage() && node.bounds.width() >= threshold && node.bounds.height() >= threshold && + node.labels().none { it in imageActions || it in removeActions || it in composerIcons } + } + if (previews.size != removals.size || previews.any { !composer.container.bounds.contains(it.bounds) || + !bounds.contains(it.bounds) }) return null + val pairedRemovals = previews.map { it.previewRemoval(removals) ?: return null } + if (pairedRemovals.distinct().size != previews.size) return null + if (scoped.any { it.scrollable && (it.horizontalItemCount ?: 0) > previews.size }) return null + return previews.sortedWith(compareBy { it.bounds.top }.thenBy { it.bounds.left }) + } + + private fun UiNode.previewRemoval(removals: List): UiNode? { + val parent = directParent() ?: return null + return removals.singleOrNull { it.directParent() === parent && bounds.contains(it.bounds.centerX(), it.bounds.centerY()) } + } + + private fun UiPage.albumHeading(labels: Set): UiNode? { + val hasExit = nodes.any { it.bounds.centerY() < y(.24f) && it.labels().any(pickerExit::contains) && it.nativeAction() != null } + if (!hasExit) return null + return nodes.singleOrNull { !it.editable && it.bounds.centerY() < y(.24f) && + it.bounds.centerX() in x(.22f)..x(.78f) && it.labels().any(labels::contains) } + } + + private fun UiPage.picker(album: String, expected: Int): Picker? { + val heading = albumHeading(setOf(album)) ?: return null + val doneLabel = nodes.singleOrNull { node -> !node.editable && node.bounds.centerY() > y(.70f) && + node.labels().any { selectionCount.matches(it.filterNot(Char::isWhitespace)) } } ?: return null + val match = doneLabel.labels().mapNotNull { selectionCount.matchEntire(it.filterNot(Char::isWhitespace)) } + .singleOrNull() ?: return null + val count = match.groupValues[1].ifEmpty { "0" }.toIntOrNull()?.takeIf { it in 0..expected } ?: return null + val done = if (count == 0) doneLabel else doneLabel.nativeAction() ?: return null + val grid = nodes.singleOrNull { it.className in photoGridClasses && it.bounds.top >= heading.bounds.bottom && + it.bounds.bottom <= done.bounds.bottom && it.bounds.width() >= bounds.width() * .60f } ?: return null + val images = nodes.filter { it.isDescendantOf(grid) && it.isImage() && it.bounds.width() >= bounds.width() * .15f && + it.bounds.height() >= bounds.width() * .15f && grid.bounds.contains(it.bounds) && bounds.contains(it.bounds) } + if (images.size != expected) return null + val tiles = images.map { image -> + val parent = image.directParent() ?: return null + val select = nodes.singleOrNull { it.directParent() === parent && image.bounds.contains(it.bounds) && it.nativeClick() && + it.selectionOrdinal() != null } ?: return null + AlbumTile(image, select, select.selectionOrdinal() ?: return null) + }.sortedWith(compareBy { it.image.bounds.top }.thenBy { it.image.bounds.left }) + if (tiles.map(AlbumTile::select).distinct().size != expected) return null + return Picker(tiles, done, count) + } + + private fun Picker.snapshot(windowId: Int) = PickerSnapshot(windowId, tiles.map { Rect(it.image.bounds) }) + + private fun Picker.matches(expected: PickerSnapshot, windowId: Int, selected: List, count: Int): Boolean = + this.count == count && snapshot(windowId) == expected && tiles.map(AlbumTile::ordinal) == selected + + private fun UiNode.selectionOrdinal(): Int? { + val values = labels().mapNotNull { label -> + if (!selected && label in unselectedLabels) 0 else ordinalLabel.matchEntire(label.filterNot(Char::isWhitespace)) + ?.groupValues?.get(1)?.toIntOrNull() + }.distinct() + return values.singleOrNull() + } + + private fun UiNode.replyCue(target: CommentTarget): Boolean = sequenceOf(hint, description, text.takeIf { !editable || showingHint }.orEmpty()) + .any { matchesReplyCue(it, target) } + + private fun UiNode.hasReplyPrompt(): Boolean = sequenceOf(hint, description, text.takeIf { !editable || showingHint }.orEmpty()) + .any { it.trim().startsWith("回复") } + + private fun matchesReplyCue(label: String, target: CommentTarget): Boolean { + val author = target.author.trim().removePrefix("@").trim() + val cue = label.trim().removeSuffix(":").removeSuffix(":").trim() + return author.isNotEmpty() && cue.startsWith("回复") && cue.removePrefix("回复").trim().removePrefix("@").trim() == author + } + + private fun UiNode.hasExactLabel(wanted: String) = labels().contains(wanted) + private fun UiNode.canEdit() = enabled && editable && supports(AccessibilityNodeInfo.ACTION_SET_TEXT) + private fun UiNode.nativeClick() = enabled && !editable && supports(AccessibilityNodeInfo.ACTION_CLICK) + private fun UiNode.nativeAction(): UiNode? = takeIf { it.nativeClick() } + ?: directParent()?.takeIf { it.nativeClick() && it.bounds.contains(bounds) } + private fun UiNode.isImage() = className == "android.widget.ImageView" || + className == "android.view.View" && labels().any(imageLabels::contains) + + private fun awaitPage(timeout: Long, failure: String, read: (UiPage) -> T?): T = + ui.await(timeout) { ui.inspect(read) } ?: throw PlatformException(failure) + + private companion object { + val sendActions = setOf("发送", "发送回复", "发送评论") + val imageActions = setOf("相册", "插入图片", "添加图片", "选择图片") + val removeActions = setOf("删除图片", "移除图片", "删除照片", "移除照片") + val composerIcons = setOf("发送", "表情", "表情包", "拍照", "话题", "@") + val previewLabels = setOf("图片预览", "照片预览") + val imageLabels = setOf("图片", "照片", "图片预览", "照片预览", "图片缩略图", "照片缩略图") + val pickerExit = setOf("返回", "关闭", "取消") + val pickerHeadings = setOf("相册", "最近项目", "全部照片", "全部图片", "所有照片", "最近") + val photoGridClasses = setOf("androidx.recyclerview.widget.RecyclerView", "android.widget.GridView") + val unselectedLabels = setOf("选择", "未选中", "未选择") + val selectionCount = Regex("""(?:完成|确定|添加)(?:[((]([0-9]+)(?:/[0-9]+)?[))])?""") + val ordinalLabel = Regex("""(?:已选中|已选择|第)?([1-9])(?:张图片|张)?""") + } +} diff --git a/app/src/main/java/com/jieliu/app/platform/XiaohongshuReplyReceipt.kt b/app/src/main/java/com/jieliu/app/platform/XiaohongshuReplyReceipt.kt new file mode 100644 index 0000000..e84f28f --- /dev/null +++ b/app/src/main/java/com/jieliu/app/platform/XiaohongshuReplyReceipt.kt @@ -0,0 +1,228 @@ +package com.jieliu.app.platform + +import android.graphics.Rect +import com.jieliu.app.data.PhotoLibrary +import com.jieliu.app.task.TemplatePhoto + +/** Reads one original comment thread. No editor activation, input, or submission is performed here. */ +internal class XiaohongshuReplyReceipt( + private val ui: AccessibleUi, + private val photos: PhotoLibrary, + private val comments: XiaohongshuComments, +) { + private data class SurfaceKey(val windowId: Int, val inline: Boolean) + private data class OriginalComment(val key: String, val author: String) + private data class ThreadStamp(val complete: Boolean, val replyIds: List, val expandLabels: List?) + private data class Baseline(val stamp: ThreadStamp, val parentVisible: Boolean, val bodies: List) + private data class VisibleReceipt(val identity: String, val body: Rect, val photos: List) + + fun captureBaseline(target: CommentTarget, expectedText: String): Boolean { + if (target.key.isBlank() || target.author.isBlank() || expectedText.isBlank()) return false + val original = OriginalComment(target.key, target.author) + val scope = findSurface() ?: return false + repeat(MAX_EXPANSIONS + 1) { pageIndex -> + val baseline = ui.await(THREAD_WAIT_MS) { + readThread(scope, original) { surface, parent, thread -> + Baseline(stamp(thread), contains(surface.viewport, parent.body.bounds), thread.replies.map { it.body.text }) + } + } ?: return false + // A missing own badge cannot turn an already visible identical body into evidence of a new reply. + if (baseline.bodies.any { it == expectedText }) return false + if (baseline.stamp.complete) { + return baseline.parentVisible && baseline.bodies.none(String::isBlank) && + baseline.stamp.replyIds.none(String::isBlank) && + baseline.stamp.replyIds.distinct().size == baseline.stamp.replyIds.size + } + if (pageIndex == MAX_EXPANSIONS || !expandThread(scope, original, baseline.stamp)) return false + if (ui.await(THREAD_WAIT_MS) { changedThread(scope, original, baseline.stamp) } != true) return false + } + return false + } + + fun confirm( + targetKey: String, + author: String, + text: String, + photos: List, + armedAt: Long, + ): CommentPublishResult { + if (targetKey.isBlank() || author.isBlank() || text.isBlank() || !validXhsReceiptAge(armedAt, System.currentTimeMillis())) { + return CommentPublishResult.UNCERTAIN + } + val original = OriginalComment(targetKey, author) + val references = this.photos.readReceiptPixels(photos) ?: return CommentPublishResult.UNCERTAIN + val scope = findSurface() ?: return CommentPublishResult.UNCERTAIN + if (!seekOriginal(scope, original)) return CommentPublishResult.UNCERTAIN + + var expansions = 0 + var revisitedOriginal = false + val opened = mutableSetOf() + repeat(MAX_RECEIPT_PASSES) { + if (ui.await(RECEIPT_WAIT_MS) { verifiedReceipt(scope, original, text, references, armedAt) } == true) { + return CommentPublishResult.CONFIRMED + } + val seen = readThread(scope, original) { _, _, thread -> stamp(thread) } + if (seen == null) { + if (revisitedOriginal || !seekOriginal(scope, original, forwardLimit = 0)) return CommentPublishResult.UNCERTAIN + revisitedOriginal = true + } else if (seen.expandLabels != null && expansions < MAX_EXPANSIONS && seen !in opened && + expandThread(scope, original, seen) + ) { + expansions++ + opened.add(seen) + ui.await(THREAD_WAIT_MS) { changedThread(scope, original, seen) } + } else if (!bringLowerReplyIntoView(scope, original)) { + return CommentPublishResult.UNCERTAIN + } + } + return CommentPublishResult.UNCERTAIN + } + + private fun verifiedReceipt( + scope: SurfaceKey, + original: OriginalComment, + text: String, + references: List, + armedAt: Long, + ): Boolean? { + val before = receiptRow(scope, original, text, references.size, armedAt) ?: return null + val captured = if (references.isEmpty()) emptyList() else ui.screenshotPhotos(scope.windowId, before.photos) ?: return null + val after = receiptRow(scope, original, text, references.size, armedAt) ?: return null + return true.takeIf { + before == after && captured.size == references.size && + references.indices.all { PublishedPhotoMatcher.matches(references[it], captured[it]) } + } + } + + private fun receiptRow(scope: SurfaceKey, original: OriginalComment, text: String, photoCount: Int, armedAt: Long): VisibleReceipt? = + readThread(scope, original) { surface, parent, thread -> + val viewport = surface.viewport + if (!contains(viewport, parent.body.bounds)) return@readThread null + val reply = thread.replies.singleOrNull { it.own && it.body.text == text } ?: return@readThread null + val time = reply.timeLabel ?: return@readThread null + if (reply.identity.isBlank() || thread.replies.count { it.identity == reply.identity } != 1 || + !contains(viewport, reply.body.bounds) || !matchesXhsReceiptTime(time, armedAt, System.currentTimeMillis()) + ) return@readThread null + + val crops = reply.photos.map { Rect(it.bounds) } + if (crops.size != photoCount || crops.any { + !contains(viewport, it) || it.top <= viewport.top || it.bottom >= viewport.bottom || Rect.intersects(reply.body.bounds, it) + } || crops.indices.any { index -> (0 until index).any { Rect.intersects(crops[it], crops[index]) } } + ) return@readThread null + VisibleReceipt(reply.identity, Rect(reply.body.bounds), crops) + } + + private fun seekOriginal(scope: SurfaceKey, original: OriginalComment, forwardLimit: Int = MAX_FORWARD_SCROLLS): Boolean { + if (originalVisible(scope, original)) return true + repeat(MAX_REVERSE_SCROLLS + forwardLimit) { index -> + if (!moveWithinSurface(scope, towardEarlier = index < MAX_REVERSE_SCROLLS)) return false + if (ui.await(RECEIPT_WAIT_MS) { true.takeIf { originalVisible(scope, original) } } == true) return true + } + return false + } + + private fun originalVisible(scope: SurfaceKey, original: OriginalComment): Boolean = + readOriginal(scope, original) { _, _ -> true } == true + + private fun moveWithinSurface(scope: SurfaceKey, towardEarlier: Boolean): Boolean = ui.inspect { page -> + val area = matchingSurface(page, scope)?.viewport ?: return@inspect false + if (area.height() < 100) return@inspect false + val x = area.exactCenterX() + val nearTop = area.top + area.height() * .25f + val nearBottom = area.top + area.height() * .76f + if (towardEarlier) ui.touch(x, nearTop, x, nearBottom, 360L) + else ui.touch(x, nearBottom, x, nearTop, 360L) + } == true + + private fun bringLowerReplyIntoView(scope: SurfaceKey, original: OriginalComment): Boolean = + readOriginal(scope, original) { surface, parent -> + val area = surface.viewport + val shift = (parent.body.bounds.top - area.top - 18).coerceAtMost(area.height() / 4) + if (shift < 22) return@readOriginal false + val x = area.exactCenterX() + val from = area.top + area.height() * .72f + ui.touch(x, from, x, from - shift, 290L) + } == true + + private fun expandThread(scope: SurfaceKey, original: OriginalComment, previous: ThreadStamp): Boolean = + readThread(scope, original) { surface, _, thread -> + if (stamp(thread) != previous) return@readThread true + val expand = thread.expand ?: return@readThread false + !thread.complete && contains(surface.viewport, expand.bounds) && ui.click(expand) + } == true + + private fun changedThread(scope: SurfaceKey, original: OriginalComment, previous: ThreadStamp): Boolean? = + readThread(scope, original) { _, _, thread -> true.takeIf { stamp(thread) != previous } } + + private fun stamp(thread: XhsCommentThread) = ThreadStamp( + thread.complete, thread.replies.map { it.identity }, thread.expand?.labels(), + ) + + private fun findSurface(): SurfaceKey? = ui.await(THREAD_WAIT_MS) { + ui.inspect { page -> + if (hasOpenEditor(page)) return@inspect null + comments.surface(page)?.takeIf { it.windowId == page.windowId && contains(page.bounds, it.viewport) } + ?.let { SurfaceKey(it.windowId, it.inline) } + } + } + + private fun matchingSurface(page: UiPage, scope: SurfaceKey): XhsCommentSurface? { + if (page.windowId != scope.windowId || hasOpenEditor(page)) return null + return comments.surface(page)?.takeIf { + it.windowId == scope.windowId && it.inline == scope.inline && contains(page.bounds, it.viewport) + } + } + + private fun hasOpenEditor(page: UiPage): Boolean = page.nodes.any { it.editable && (it.focused || it.hasDraft()) } + + private fun readOriginal(scope: SurfaceKey, original: OriginalComment, read: (XhsCommentSurface, XhsCommentRow) -> T): T? = + ui.inspect { page -> + val surface = matchingSurface(page, scope) ?: return@inspect null + val row = comments.row(page, original.key)?.takeIf { it.target.key == original.key && it.target.author == original.author } + ?: return@inspect null + read(surface, row) + } + + private fun readThread( + scope: SurfaceKey, + original: OriginalComment, + read: (XhsCommentSurface, XhsCommentRow, XhsCommentThread) -> T, + ): T? = ui.inspect { page -> + val surface = matchingSurface(page, scope) ?: return@inspect null + val row = comments.row(page, original.key)?.takeIf { it.target.key == original.key && it.target.author == original.author } + ?: return@inspect null + val thread = comments.thread(page, row) ?: return@inspect null + read(surface, row, thread) + } + + private fun contains(outer: Rect, inner: Rect) = !inner.isEmpty && outer.contains(inner) + + private companion object { + const val MAX_EXPANSIONS = 4 + const val MAX_RECEIPT_PASSES = 9 + const val MAX_REVERSE_SCROLLS = 2 + const val MAX_FORWARD_SCROLLS = 12 + const val THREAD_WAIT_MS = 1_550L + const val RECEIPT_WAIT_MS = 850L + } +} + +private const val XHS_RECEIPT_MAX_AGE_MS = 30 * 60 * 1_000L +private const val XHS_RECEIPT_CLOCK_SLACK_MS = 5_000L +private val xhsReceiptRelativeTime = Regex("([0-9]{1,2})[ \\u00a0]*(秒前|分钟前)") + +internal fun validXhsReceiptAge(armedAt: Long, now: Long): Boolean = + armedAt > 0 && armedAt <= now && now - armedAt <= XHS_RECEIPT_MAX_AGE_MS + +internal fun matchesXhsReceiptTime(label: String, armedAt: Long, now: Long): Boolean { + if (!validXhsReceiptAge(armedAt, now)) return false + val normalized = label.trim() + val elapsed = now - armedAt + if (normalized == "刚刚") return elapsed < 60_000L + XHS_RECEIPT_CLOCK_SLACK_MS + val match = xhsReceiptRelativeTime.matchEntire(normalized) ?: return false + val amount = match.groupValues[1].toLong() + val unit = if (match.groupValues[2] == "秒前") 1_000L else 60_000L + val earliest = amount * unit - XHS_RECEIPT_CLOCK_SLACK_MS + val latest = (amount + 1) * unit + XHS_RECEIPT_CLOCK_SLACK_MS + return elapsed >= earliest && elapsed < latest +} diff --git a/app/src/test/java/com/jieliu/app/platform/XhsCommentLabelsTest.kt b/app/src/test/java/com/jieliu/app/platform/XhsCommentLabelsTest.kt new file mode 100644 index 0000000..3886e9c --- /dev/null +++ b/app/src/test/java/com/jieliu/app/platform/XhsCommentLabelsTest.kt @@ -0,0 +1,38 @@ +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 XhsCommentLabelsTest { + @Test + fun syntheticHeadingRequiresStandaloneCommentCount() { + assertEquals(66, XhsCommentLabels.commentCount("共 66 条评论")) + assertEquals(0, XhsCommentLabels.commentCount("共0条评论")) + assertEquals(0, XhsCommentLabels.commentCount("暂无评论")) + assertEquals(0, XhsCommentLabels.commentCount("还没有评论")) + assertNull(XhsCommentLabels.commentCount("评论 2")) + assertNull(XhsCommentLabels.commentCount("评论加载中")) + assertNull(XhsCommentLabels.commentCount("这里共 2 条评论")) + } + + @Test + fun syntheticContinuationDistinguishesReplyExpansionFromAnAmbiguousToggle() { + assertTrue(XhsCommentLabels.expandsReplies("展开 2 条回复")) + assertTrue(XhsCommentLabels.blocksThreadBoundary("展开更多")) + assertFalse(XhsCommentLabels.expandsReplies("展开更多")) + assertFalse(XhsCommentLabels.blocksThreadBoundary("展开全文")) + } + + @Test + fun syntheticReceiptLabelsRequireExplicitMediaAndRelativeTime() { + assertTrue(XhsCommentLabels.photoDescription("查看图片 2")) + assertFalse(XhsCommentLabels.photoDescription("用户图片")) + assertEquals("刚刚", XhsCommentLabels.relativeTime("刚刚 北京")) + assertEquals("42 秒前", XhsCommentLabels.relativeTime("42 秒前 北京")) + assertEquals("3 分钟前", XhsCommentLabels.relativeTime("3 分钟前 北京")) + assertNull(XhsCommentLabels.relativeTime("回复 3 分钟前")) + } +} diff --git a/app/src/test/java/com/jieliu/app/platform/XhsReceiptTimeTest.kt b/app/src/test/java/com/jieliu/app/platform/XhsReceiptTimeTest.kt new file mode 100644 index 0000000..bd56c96 --- /dev/null +++ b/app/src/test/java/com/jieliu/app/platform/XhsReceiptTimeTest.kt @@ -0,0 +1,25 @@ +package com.jieliu.app.platform + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class XhsReceiptTimeTest { + private val armedAt = 1_790_000_000_000L + + @Test fun relativeLabelMustAgreeWithRecordedSubmission() { + assertTrue(matchesXhsReceiptTime("刚刚", armedAt, armedAt + 2_000L)) + assertTrue(matchesXhsReceiptTime("12 秒前", armedAt, armedAt + 12_600L)) + assertTrue(matchesXhsReceiptTime("1分钟前", armedAt, armedAt + 82_000L)) + assertFalse(matchesXhsReceiptTime("2分钟前", armedAt, armedAt + 62_000L)) + assertFalse(matchesXhsReceiptTime("刚刚", armedAt, armedAt + 70_000L)) + } + + @Test fun unsupportedLabelsAndFutureOrExpiredArmsAreInconclusive() { + val times = listOf("", "今天", "11-26", "刚刚 浙江", "昨日 11:20", "99分钟前") + assertTrue(times.none { matchesXhsReceiptTime(it, armedAt, armedAt + 3_000L) }) + assertFalse(matchesXhsReceiptTime("刚刚", armedAt, armedAt - 1L)) + assertFalse(matchesXhsReceiptTime("31分钟前", armedAt, armedAt + 31 * 60_000L)) + assertFalse(validXhsReceiptAge(0, armedAt)) + } +} 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 30adabf..877cd43 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.PlatformRegistry import com.jieliu.app.platform.VideoContext import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse @@ -286,6 +287,35 @@ class TaskRunnerTest { assertEquals(0, platform.swipes) } + @Test fun xiaohongshuRotatesBoundPhotoSetsAndRechecksWithoutResending() { + val alternativePhotos = listOf(TemplatePhoto(id("photo3"), "三.png"), TemplatePhoto(id("photo4"), "四.png")) + val alternate = ReplyPhrase(id("alternate"), "另一条 API 充值话术", alternativePhotos) + val rule = apiRule.copy(phrases = apiRule.phrases + alternate) + val contentType = firstType.copy(rules = listOf(rule)) + val plan = plan(contentType).copy(platformId = "xiaohongshu", limit = 2, repliesPerVideo = 2) + val store = RecordingStore(TaskCheckpoint("xhs-multi-receipt", plan)) + val targets = listOf(target("first", "想咨询 API 充值"), target("second", "请问API充值"), target("extra", "关于 API 充值")) + val platform = FakePlatform(store, result = CommentPublishResult.UNCERTAIN).apply { + knownBaseline = true + recheckResult = CommentPublishResult.CONFIRMED + screensForVideo = { video -> if (video.key == "video-0") listOf(emptyList()) else listOf(targets) } + } + + execute(store, platform) + + assertTrue(PlatformRegistry.platforms.single { it.id == plan.platformId }.supportsReplies) + assertEquals(listOf("first", "second"), platform.attempts.map { it.targetKey }) + assertEquals(rule.phrases.associate { it.text to it.photos }, platform.attempts.associate { it.text to it.photos }) + assertEquals(platform.attempts.map { "video-1" to it }, platform.rechecks) + assertEquals(2, platform.publishCalls) + assertEquals(2, store.pendingWrites) + assertTrue(store.logs.contains("第 2 条笔记已确认 2/2 条回复")) + assertEquals(listOf(Outcome.NO_REPLY, Outcome.SENT), store.checkpoint.receipts.map { it.outcome }) + assertEquals(listOf(Outcome.SENT, Outcome.SENT), store.checkpoint.receipts.last().replies.map { it.outcome }) + assertNull(store.checkpoint.pending) + assertTrue(store.checkpoint.complete) + } + @Test fun manualConfirmationBelowQuotaResumesTheSameVideoWithoutReplyingToTheSameTarget() { val store = RecordingStore(TaskCheckpoint("resume-quota", plan(firstType).copy(limit = 2, repliesPerVideo = 2))) val remaining = listOf(listOf(target("first", "付款方式"), target("second", "付款方式"))) diff --git a/docs/ui-preview.html b/docs/ui-preview.html index bb61382..5676487 100644 --- a/docs/ui-preview.html +++ b/docs/ui-preview.html @@ -339,7 +339,7 @@
@@ -476,7 +476,6 @@ const byId = id => document.getElementById(id); const scope = byId("search-scope"); const platformPicker = byId("target-platform"); - const modePicker = byId("reply-mode"); const typePicker = byId("content-type"); const rulePicker = byId("keyword-rule"); const phrasePicker = byId("reply-phrase"); @@ -673,8 +672,8 @@ const unit = notes ? "笔记" : "视频"; byId("content-limit-label").textContent = `单次任务${unit}上限`; byId("reply-limit-label").textContent = `每条${unit}回复上限`; - byId("reply-scope-hint").textContent = notes ? "小红书当前仅支持浏览。" : "达到回复上限或找不到更多匹配评论时,进入下一个视频。"; - byId("content-scope-hint").textContent = notes ? "按内容类型搜索笔记。" : "按内容类型搜索视频,按关键词匹配评论。每个关键词可配置多条话术。"; + byId("reply-scope-hint").textContent = `达到回复上限或找不到更多匹配评论时,进入下一个${unit}。`; + byId("content-scope-hint").textContent = `按内容类型搜索${unit},按关键词匹配评论。每个关键词可配置多条话术。`; }); byId("save-preview").addEventListener("click", () => { const status = byId("library-status"); @@ -684,9 +683,6 @@ if (platformPicker.value === "bilibili") { error = "哔哩哔哩还未适配,请选择已接入的平台。"; focus = platformPicker; - } else if (platformPicker.value === "xiaohongshu" && modePicker.value !== "仅浏览") { - error = "小红书当前仅支持浏览,请将处理方式设为「仅浏览」。"; - focus = modePicker; } status.textContent = error || "预览配置已更新。"; status.classList.toggle("error", Boolean(error)); diff --git a/docs/开发进度.md b/docs/开发进度.md index 37c4235..43c97fa 100644 --- a/docs/开发进度.md +++ b/docs/开发进度.md @@ -1,6 +1,15 @@ # 拾见开发进度 -最近更新于 2026-11-26 14:35(UTC+8)。以下按开发轮次倒序记录。 +最近更新于 2026-11-26 14:52(UTC+8)。以下按开发轮次倒序记录。 + +## 2026-11-26 · 拾见 0.1.21 小红书评论回复适配 + +- 已提交 0.1.20 小红书浏览版并推送到 `main`,远端提交为 `110665d`。 +- 已接入小红书图文和视频笔记的评论区。按内容类型搜索,逐屏读取可定位回复入口的原评论,命中后从对应关键词的话术库轮换抽取话术及其绑定图片。沿用单笔记回复上限、无匹配推进和检查点恢复。 +- 提交前核对同一原评论的回复框、完整正文、临时相册和全部绑定图,先保存提交意图,再点击一次发送。回执核对原评论下同一条本人回复的正文、时间及全部图片。证据不足时保留待核对,继续核对只读取已有回复。 +- 静态配置页在离线 Chrome 的 390 和 1440 像素宽度验证通过。小红书可保存「匹配评论并回复」,两项上限会使用「笔记」单位,旧版图片绑定、抖音字段和哔哩哔哩禁用校验均通过复测。 +- 0.1.21 离线构建通过,调试 APK 通过 v2 签名校验,51 项 JVM 单测通过,Lint 为 0 个错误、4 个既有警告。用例覆盖按小红书笔记推进、不同话术与对应多图、发送结果不明确时只读复核,以及评论标签和回执时间。回执截图前后分别核对发布时间,允许时间标签正常跳动。 +- 手机安装、回复框及相册实际控件、小红书允许的图片数量、本人回复标识及实发回执留待真机联调。 ## 2026-11-26 · 拾见 0.1.20 小红书首轮适配