From 5df863cd22d2adcb55fb60fad9d990576b1b4b40 Mon Sep 17 00:00:00 2001 From: huanghaohao <759903577@qq.com> Date: Thu, 26 Nov 2026 17:15:26 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E5=96=84=E5=B0=8F=E7=BA=A2=E4=B9=A6?= =?UTF-8?q?=E5=A4=9A=E5=9B=BE=E5=9B=9E=E5=A4=8D=E4=B8=8E=E5=BE=85=E6=A0=B8?= =?UTF-8?q?=E5=AF=B9=E6=81=A2=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 改进图文和视频笔记定位、附件顺序校验及原评论回执读取。识别社区评论互动限制并保留待核对记录。 --- app/build.gradle.kts | 4 +- .../java/com/jieliu/app/AutomationService.kt | 5 +- .../java/com/jieliu/app/data/LocalStore.kt | 6 + .../java/com/jieliu/app/data/PhotoLibrary.kt | 22 ++ .../jieliu/app/platform/PlatformAdapter.kt | 11 +- .../app/platform/PublishedPhotoMatcher.kt | 48 +++ .../jieliu/app/platform/XiaohongshuAdapter.kt | 200 +++++++++-- .../app/platform/XiaohongshuComments.kt | 154 ++++++-- .../app/platform/XiaohongshuReplyComposer.kt | 336 +++++++++++------- .../app/platform/XiaohongshuReplyReceipt.kt | 322 +++++++++++++---- .../com/jieliu/app/task/TaskCheckpoint.kt | 5 +- .../main/java/com/jieliu/app/task/TaskPlan.kt | 6 + .../java/com/jieliu/app/task/TaskRunner.kt | 40 ++- .../app/platform/PublishedPhotoMatcherTest.kt | 16 + .../jieliu/app/platform/XhsReceiptTimeTest.kt | 3 +- 15 files changed, 914 insertions(+), 264 deletions(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index fd878ac..e85e22b 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 = 22 - versionName = "0.1.21" + versionCode = 23 + versionName = "0.1.22" } compileOptions { diff --git a/app/src/main/java/com/jieliu/app/AutomationService.kt b/app/src/main/java/com/jieliu/app/AutomationService.kt index 9ec2e44..572e45b 100644 --- a/app/src/main/java/com/jieliu/app/AutomationService.kt +++ b/app/src/main/java/com/jieliu/app/AutomationService.kt @@ -106,7 +106,10 @@ internal object TaskControl { .copy(plan = plan, message = if (rechecking) "正在准备自动核对回复" else "任务准备运行") val run = Run(service, store, initial) val cancelled = { run.cancelled } - val platform = PlatformRegistry.create(plan.platformId, service, cancelled) { + val platform = PlatformRegistry.create(plan.platformId, service, cancelled, + noteKind = plan.xiaohongshuNoteKind, targetNoteKey = plan.xiaohongshuNoteKey, + pinnedResumeNoteKey = initial.activeVideo?.videoKey.takeIf { plan.xiaohongshuNoteKey != null }, + receiptDiagnostic = { stage -> store.appendLog(stage) }) { val interval = randomIn(plan.actionMillis.first, plan.actionMillis.last) pauseFor(interval.toLong(), cancelled) } diff --git a/app/src/main/java/com/jieliu/app/data/LocalStore.kt b/app/src/main/java/com/jieliu/app/data/LocalStore.kt index c5a51e4..d144a67 100644 --- a/app/src/main/java/com/jieliu/app/data/LocalStore.kt +++ b/app/src/main/java/com/jieliu/app/data/LocalStore.kt @@ -1,5 +1,6 @@ package com.jieliu.app.data +import com.jieliu.app.platform.XiaohongshuNoteKind import android.content.Context import com.jieliu.app.task.ContentType import com.jieliu.app.task.KeywordRule @@ -166,6 +167,8 @@ class LocalStore(context: Context) : TaskRunStorage { })) .put("contentTypes", contentTypes?.let { JSONArray(it.map { type -> type.toJson() }) }) .put("selectedTypeId", selectedTypeId) + .put("xiaohongshuNoteKind", xiaohongshuNoteKind.takeUnless { it == XiaohongshuNoteKind.ANY }?.name) + .put("xiaohongshuNoteKey", xiaohongshuNoteKey) .put("repliesPerVideo", repliesPerVideo) .put("limit", limit).put("watchMin", watchSeconds.first).put("watchMax", watchSeconds.last) .put("actionMin", actionMillis.first).put("actionMax", actionMillis.last) @@ -201,6 +204,9 @@ class LocalStore(context: Context) : TaskRunStorage { }, selectedTypeId = optionalString("selectedTypeId"), repliesPerVideo = if (isNull("repliesPerVideo")) 1 else getInt("repliesPerVideo"), + xiaohongshuNoteKind = XiaohongshuNoteKind.entries.firstOrNull { it.name == optionalString("xiaohongshuNoteKind") } + ?: XiaohongshuNoteKind.ANY, + xiaohongshuNoteKey = optionalString("xiaohongshuNoteKey"), ) private fun ContentType.toJson() = JSONObject().put("id", id).put("name", name) diff --git a/app/src/main/java/com/jieliu/app/data/PhotoLibrary.kt b/app/src/main/java/com/jieliu/app/data/PhotoLibrary.kt index 5e16d8a..f8896b0 100644 --- a/app/src/main/java/com/jieliu/app/data/PhotoLibrary.kt +++ b/app/src/main/java/com/jieliu/app/data/PhotoLibrary.kt @@ -21,9 +21,11 @@ import com.jieliu.app.task.TaskPlan import com.jieliu.app.task.TemplatePhoto import java.io.File import java.io.FileOutputStream +import java.io.IOException import java.nio.file.Files import java.nio.file.LinkOption.NOFOLLOW_LINKS import java.nio.file.StandardCopyOption.ATOMIC_MOVE +import java.security.MessageDigest import java.util.UUID data class StagedPhotos(val albumName: String, val uris: List) @@ -97,6 +99,26 @@ class PhotoLibrary(context: Context) { } } + internal fun attachmentDigests(photos: List): List? = synchronized(lock) { + val buffer = ByteArray(DEFAULT_BUFFER_SIZE) + try { + photos.map { photo -> + val source = importedFile(photo) ?: return@synchronized null + val digest = MessageDigest.getInstance("SHA-256") + source.inputStream().use { input -> + var count = input.read(buffer) + while (count != -1) { + digest.update(buffer, 0, count) + count = input.read(buffer) + } + } + digest.digest().joinToString("") { "%02x".format(it) } + } + } catch (_: IOException) { + null + } + } + fun stage(photos: List): StagedPhotos = synchronized(lock) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) error("暂存话术图片需要 Android 10 或更新版本。") require(photos.size in 1..TaskPlan.MAX_TEMPLATE_PHOTOS && 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 ea9da0a..da45d51 100644 --- a/app/src/main/java/com/jieliu/app/platform/PlatformAdapter.kt +++ b/app/src/main/java/com/jieliu/app/platform/PlatformAdapter.kt @@ -21,6 +21,7 @@ data class CommentTarget(val key: String, val text: String, val author: String) enum class CommentPublishResult { CONFIRMED, UNCERTAIN } class PlatformException(message: String, cause: Throwable? = null) : RuntimeException(message, cause) +internal class PlatformInteractionRestrictedException(message: String) : RuntimeException(message) /** Call from one worker thread. Calls wait for accessibility state and may block. */ interface PlatformAdapter { @@ -29,6 +30,7 @@ interface PlatformAdapter { fun currentVideo(): VideoContext fun nextVideo(previous: VideoContext): VideoContext fun openComments(expected: VideoContext): List + fun openCommentsForReceipt(expected: VideoContext) { openComments(expected) } fun scanComments(): List = emptyList() fun scrollComments(): Boolean = false /** False means no reply control was activated and scanning may continue. */ @@ -41,6 +43,8 @@ interface PlatformAdapter { fun hasPreparedReplyBaseline(targetKey: String, text: String): Boolean = false /** Read back one previously armed reply. This must never prepare or submit a comment. */ fun confirmPendingReply(video: VideoContext, pending: PendingComment): CommentPublishResult = CommentPublishResult.UNCERTAIN + /** Read back from an already bound note. Null means a fresh read-only search is needed. */ + fun confirmPendingReplyInPlace(video: VideoContext, pending: PendingComment): CommentPublishResult? = null fun closeComments() } @@ -59,6 +63,10 @@ object PlatformRegistry { platformId: String, service: AccessibilityService, cancelled: () -> Boolean, + noteKind: XiaohongshuNoteKind = XiaohongshuNoteKind.ANY, + targetNoteKey: String? = null, + pinnedResumeNoteKey: String? = null, + receiptDiagnostic: (String) -> Unit = {}, pauseBetweenActions: () -> Unit = {}, ): PlatformAdapter { val spec = platforms.firstOrNull { it.id == platformId } @@ -66,7 +74,8 @@ 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, PhotoLibrary(service)) + xiaohongshu.id -> XiaohongshuAdapter(spec, ui, PhotoLibrary(service), noteKind, targetNoteKey, + pinnedResumeNoteKey, receiptDiagnostic) else -> throw PlatformException("${spec.label} 暂未接入") } } diff --git a/app/src/main/java/com/jieliu/app/platform/PublishedPhotoMatcher.kt b/app/src/main/java/com/jieliu/app/platform/PublishedPhotoMatcher.kt index 4d3c819..94e2a2f 100644 --- a/app/src/main/java/com/jieliu/app/platform/PublishedPhotoMatcher.kt +++ b/app/src/main/java/com/jieliu/app/platform/PublishedPhotoMatcher.kt @@ -26,6 +26,54 @@ internal object PublishedPhotoMatcher { compare(reference, referenceBounds, published, fittedContent) } + fun matchesXhsDraft(reference: PhotoPixels, thumbnail: PhotoPixels): Boolean { + if (matches(reference, thumbnail)) return true + if (!reference.isUsable() || !thumbnail.isUsable()) return false + val visible = thumbnail.bounds() + val expectedBounds = reference.bounds().centered(visible.aspect) + if (min(expectedBounds.width, expectedBounds.height) < MIN_SIDE) return false + val expected = grid(reference, expectedBounds) + val actual = grid(thumbnail, visible) + val samples = expected.indices.filter { channel(expected[it], 24) >= 245 && channel(actual[it], 24) >= 245 } + if (samples.size < GRID * GRID * 3 / 4) return false + // The 9.54.0 attachment preview changes color tones while retaining the same spatial image. + return listOf(16, 8, 0).all { matchesDraftChannel(expected, actual, samples, it) } + } + + private fun matchesDraftChannel(expected: IntArray, actual: IntArray, samples: List, shift: Int): Boolean { + var sumExpected = 0.0 + var sumActual = 0.0 + var squareExpected = 0.0 + var squareActual = 0.0 + var product = 0.0 + var rawError = 0 + for (index in samples) { + val left = channel(expected[index], shift) + val right = channel(actual[index], shift) + sumExpected += left + sumActual += right + squareExpected += left * left + squareActual += right * right + product += left * right + rawError += abs(left - right) + } + val size = samples.size + val meanExpected = sumExpected / size + val meanActual = sumActual / size + val varianceExpected = squareExpected / size - meanExpected * meanExpected + val varianceActual = squareActual / size - meanActual * meanActual + if (rawError.toDouble() / size > 35.0 || min(varianceExpected, varianceActual) < 36.0) return false + val covariance = product / size - meanExpected * meanActual + if (covariance / sqrt(varianceExpected * varianceActual) < .985) return false + val slope = covariance / varianceExpected + val offset = meanActual - slope * meanExpected + if (slope !in .35..1.10 || abs(offset) > 80.0) return false + val adjustedError = samples.sumOf { index -> + abs(channel(actual[index], shift) - (slope * channel(expected[index], shift) + offset)) + } + return adjustedError / size <= 3.5 + } + private fun compare(reference: PhotoPixels, referenceBounds: Box, published: PhotoPixels, publishedBounds: Box): Boolean { if (min(referenceBounds.width, referenceBounds.height) < MIN_SIDE || min(publishedBounds.width, publishedBounds.height) < MIN_SIDE) return false 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 d7804fa..9836399 100644 --- a/app/src/main/java/com/jieliu/app/platform/XiaohongshuAdapter.kt +++ b/app/src/main/java/com/jieliu/app/platform/XiaohongshuAdapter.kt @@ -1,6 +1,7 @@ package com.jieliu.app.platform import android.graphics.Rect +import android.util.Log import android.view.accessibility.AccessibilityNodeInfo import com.jieliu.app.data.PhotoLibrary import com.jieliu.app.task.PendingComment @@ -9,10 +10,16 @@ import java.io.Closeable import java.security.MessageDigest import kotlin.math.abs +enum class XiaohongshuNoteKind { ANY, IMAGE, VIDEO } + internal class XiaohongshuAdapter( private val spec: PlatformSpec, private val ui: AccessibleUi, private val photoLibrary: PhotoLibrary, + private val noteKind: XiaohongshuNoteKind = XiaohongshuNoteKind.ANY, + private val targetNoteKey: String? = null, + private val pinnedResumeNoteKey: String? = null, + receiptDiagnostic: (String) -> Unit = {}, ) : PlatformAdapter { private data class SearchHeader(val editor: UiNode, val submit: UiNode) private data class ResultHeader(val query: UiNode, val tabs: UiNode) @@ -20,16 +27,21 @@ internal class XiaohongshuAdapter( 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 OpenCommentNote(val note: VideoContext, val empty: Boolean) private data class NoteControls( val author: UiNode, val more: UiNode, val toolbar: UiNode, val caption: UiNode? = null, - ) + ) { + val kind: XiaohongshuNoteKind get() = + if (caption == null) XiaohongshuNoteKind.IMAGE else XiaohongshuNoteKind.VIDEO + } private class NoteBinding( val video: VideoContext, val author: String, val windowId: Int, + val kind: XiaohongshuNoteKind, val authorSource: UiNodeSource, val moreSource: UiNodeSource, ) : Closeable { @@ -48,11 +60,11 @@ internal class XiaohongshuAdapter( private var keyword: String? = null private val examinedCards = mutableSetOf() private var activeNote: NoteBinding? = null - private var commentNote: VideoContext? = null + private var commentNote: OpenCommentNote? = 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) + private val receipt = XiaohongshuReplyReceipt(ui, photoLibrary, comments, receiptDiagnostic) override fun launch() = ui.launchTarget(spec.label) @@ -89,6 +101,7 @@ internal class XiaohongshuAdapter( if (ui.inspect { it.searchHeader()?.editor?.focused == true } == true) return ui.pace() val opened = awaitPage(4_000, "小红书首页未显示可核对的搜索入口") { page -> + page.requireXhsCommentAccess() val header = page.searchHeader() if (header != null) return@awaitPage header.editor.focused || ui.click(header.editor) val results = page.resultHeader() @@ -166,6 +179,7 @@ internal class XiaohongshuAdapter( private fun UiPage.resultList(keyword: String): ResultList? { val header = resultHeader()?.takeIf { it.query.text == keyword } ?: return null + if (noteKind == XiaohongshuNoteKind.VIDEO && videoResultTab(header.tabs)?.selected != true) return null val list = nodes.singleOrNull { it.className == "androidx.recyclerview.widget.RecyclerView" && it.bounds.width() >= bounds.width() * .90f && it.bounds.bottom >= y(.65f) && it.bounds.top <= header.tabs.bounds.bottom + 36 } ?: return null @@ -175,6 +189,29 @@ internal class XiaohongshuAdapter( return ResultList(list, viewport).takeUnless { viewport.isEmpty } } + private fun UiPage.videoResultTab(strip: UiNode): UiNode? { + val label = nodes.singleOrNull { it.isDescendantOf(strip) && it.isUneditableText() && it.text == "视频" } + ?: return null + return label.directParent()?.takeIf { tab -> + tab.className == "androidx.appcompat.app.ActionBar\$Tab" && tab.isNativeClick() && + strip.bounds.contains(tab.bounds) && tab.bounds.contains(label.bounds) && tab.selected == label.selected + } + } + + private fun selectVideoResults(keyword: String) { + if (noteKind != XiaohongshuNoteKind.VIDEO) return + ui.pace() + val clicked = awaitPage(8_000, "未找到小红书当前搜索词的视频分类") { page -> + val header = page.resultHeader()?.takeIf { it.query.text == keyword } ?: return@awaitPage null + val tab = page.videoResultTab(header.tabs) ?: return@awaitPage null + tab.selected || ui.click(tab) + } + if (!clicked) throw PlatformException("小红书未确认切换到视频分类") + awaitPage(7_000, "小红书未显示当前搜索词的视频结果") { page -> + true.takeIf { page.resultList(keyword) != null } + } + } + private fun UiPage.resultCards(surface: ResultList): List { val cards = nodes.asSequence().filter { node -> node.directParent() === surface.list && node.className == "android.widget.FrameLayout" && @@ -193,18 +230,27 @@ internal class XiaohongshuAdapter( } ?: return@mapNotNull null ResultCard(card, CardIdentity(identity(author.text, title.text), title.text, author.text)) }.toList() + if (targetNoteKey != null && cards.count { it.identity.matchesSelection() } > 1) { + throw PlatformException("小红书搜索结果中有多个卡片对应指定笔记,已停止") + } val counts = cards.groupingBy { it.identity.key }.eachCount() return cards.filter { counts[it.identity.key] == 1 } .sortedWith(compareBy({ it.action.bounds.top }, { it.action.bounds.left })) } private fun openNextResult(keyword: String): VideoContext { + if (targetNoteKey != null && examinedCards.isNotEmpty()) { + throw PlatformException("指定的小红书笔记已在本次搜索中处理") + } + val notFound = if (targetNoteKey == null) "小红书未找到下一条可核对的笔记" + else "小红书未在当前搜索结果中找到指定笔记" + selectVideoResults(keyword) repeat(8) { ui.pace() val step = awaitPage(9_000, "小红书未显示当前关键词对应的可读笔记结果") { page -> val surface = page.resultList(keyword) ?: return@awaitPage null val cards = page.resultCards(surface).takeIf { it.isNotEmpty() } ?: return@awaitPage null - val next = cards.firstOrNull { it.identity.key !in examinedCards } + val next = cards.firstOrNull { card -> card.identity.key !in examinedCards && card.identity.matchesSelection() } if (next != null) { if (!ui.click(next.action)) throw PlatformException("小红书未确认已打开选中的笔记卡片") return@awaitPage ResultStep.Opened(next.identity) @@ -213,19 +259,31 @@ internal class XiaohongshuAdapter( ResultStep.Scrolled(cards.associate { it.identity.key to it.action.bounds.top }) } when (step) { - is ResultStep.Opened -> bindNote(step.card, keyword)?.let { return it } + is ResultStep.Opened -> { + bindNote(step.card, keyword)?.let { return it } + if (targetNoteKey != null) throw PlatformException("未能核对指定的小红书笔记") + } is ResultStep.Scrolled -> if (!waitForMovement(step.positions) { page -> val surface = page.resultList(keyword) ?: return@waitForMovement null page.resultCards(surface).associate { it.identity.key to it.action.bounds.top } - }) throw PlatformException("小红书未显示更多可核对的笔记") - ResultStep.End -> throw PlatformException("小红书当前搜索结果已浏览完毕") + }) throw PlatformException(if (targetNoteKey == null) "小红书未显示更多可核对的笔记" else notFound) + ResultStep.End -> throw PlatformException(if (targetNoteKey == null) "小红书当前搜索结果已浏览完毕" else notFound) } } - throw PlatformException("小红书未找到下一条可核对的笔记") + throw PlatformException(notFound) } + private fun CardIdentity.matchesSelection(): Boolean = targetNoteKey?.let { expected -> + key == expected || identity(author.replace(layoutGaps, ""), title.replace(layoutGaps, "")) == expected + } ?: true + private fun bindNote(card: CardIdentity, keyword: String): VideoContext? { val binding = awaitNoteBinding(card, 5_000) ?: verifyOrSkipImageNote(card, keyword) ?: return null + if (noteKind != XiaohongshuNoteKind.ANY && binding.kind != noteKind) { + binding.use { leaveResultNote(it, keyword) } + examinedCards += card.key + return null + } resetNote() activeNote = binding examinedCards += card.key @@ -248,7 +306,7 @@ internal class XiaohongshuAdapter( } ?: throw PlatformException("小红书未能核对笔记详情与选中的结果卡片") shell.use { anchor -> revealImageNoteText(card, anchor)?.let { return it } - leaveUnverifiedImageNote(anchor, keyword) + leaveResultNote(anchor, keyword) } examinedCards += card.key return null @@ -273,23 +331,29 @@ internal class XiaohongshuAdapter( return null } - private fun leaveUnverifiedImageNote(anchor: NoteBinding, keyword: String) { + private fun leaveResultNote(anchor: NoteBinding, keyword: String) { ui.pace() - val left = awaitPage(4_000, "小红书未能安全退出无法核对的图文笔记") { page -> - val detail = page.boundNote(anchor) ?: return@awaitPage null - if (detail.caption != null || page.nodes.any { it.editable && it.focused }) return@awaitPage null + val left = awaitPage(4_000, "小红书未能安全退出当前搜索结果的笔记") { page -> + if (page.boundNote(anchor) == null || page.nodes.any { it.editable && (it.focused || it.hasDraft()) }) { + return@awaitPage null + } ui.back() } - if (!left) throw PlatformException("小红书未确认退出无法核对的图文笔记") + if (!left) throw PlatformException("小红书未确认退出当前搜索结果的笔记") + selectVideoResults(keyword) awaitPage(6_000, "退出小红书笔记后未核对到同一搜索结果") { page -> true.takeIf { page.resultList(keyword) != null } } } private fun UiPage.retainNote(card: CardIdentity, detail: NoteControls): NoteBinding = - NoteBinding(VideoContext(card.key, card.title), card.author, windowId, + NoteBinding(VideoContext(selectedNoteIdentity(card), card.title), card.author, windowId, detail.kind, detail.author.retainSource(), detail.more.retainSource()) + // A verified pinned result can be rendered with different spacing when the same note is reopened. + private fun selectedNoteIdentity(card: CardIdentity): String = + if (targetNoteKey != null && card.matchesSelection()) pinnedResumeNoteKey ?: targetNoteKey else card.key + override fun currentVideo(): VideoContext { val note = activeNote ?: throw PlatformException("请先通过小红书搜索打开笔记") return awaitPage(4_000, "小红书当前笔记已变化") { page -> @@ -371,18 +435,28 @@ internal class XiaohongshuAdapter( // Search cards may combine the note's title and body into one preview label. val compactPreview = preview.replace(layoutGaps, "") + if (compactPreview.length >= 48) { + // Some cards repeat the start of the title after a shortened title segment. + val leadingText = compactPreview.take(24) + val repeatStart = compactPreview.indexOf(leadingText, startIndex = leadingText.length) + if (repeatStart >= leadingText.length) { + val titlePrefix = compactPreview.substring(0, repeatStart) + if (visibleText.count { it.text.normalizedPostText().replace(layoutGaps, "").startsWith(titlePrefix) } == 1) return true + } + } return visibleText.filter { it.directParent() != null }.groupBy { it.directParent() }.values.count { parts -> parts.sortedBy { it.bounds.top }.zipWithNext().any { (titleNode, bodyNode) -> + val fullText = (titleNode.text + "\n" + bodyNode.text).normalizedPostText().replace(layoutGaps, "") abs(titleNode.bounds.left - bodyNode.bounds.left) <= 2 && abs(titleNode.bounds.right - bodyNode.bounds.right) <= 2 && bodyNode.bounds.top in titleNode.bounds.bottom..(titleNode.bounds.bottom + titleNode.bounds.height()) && - (titleNode.text + "\n" + bodyNode.text).normalizedPostText().replace(layoutGaps, "") == compactPreview + (fullText == compactPreview || compactPreview.length >= 24 && fullText.startsWith(compactPreview)) } } == 1 } private fun UiPage.boundNote(note: NoteBinding): NoteControls? = noteControls()?.takeIf { - windowId == note.windowId && it.author.text == note.author && it.author.hasSource(note.authorSource) && + windowId == note.windowId && it.kind == note.kind && it.author.text == note.author && it.author.hasSource(note.authorSource) && it.more.hasSource(note.moreSource) && (it.caption == null || hasNoteText(it, note.video.title)) } @@ -394,43 +468,82 @@ internal class XiaohongshuAdapter( 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 + if (note.kind != XiaohongshuNoteKind.IMAGE) return false val (author, more) = page.imageNoteHeader() ?: return false return author.text == note.author && author.hasSource(note.authorSource) && more.hasSource(note.moreSource) } + private fun UiPage.noteCommentButton(controls: NoteControls): UiNode? = nodes.singleOrNull { node -> + node.directParent() === controls.toolbar && node.className == "android.widget.Button" && + commentLabel.matches(node.description) && node.isNativeClick() + } + 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 + val button = page.noteCommentButton(controls)?.takeUnless { zeroComments.matches(it.description) } ?: return false + if (controls.kind == XiaohongshuNoteKind.VIDEO) { + if (!page.bounds.contains(button.bounds) || button.bounds.centerX() < page.x(.75f) || + button.bounds.centerY() < page.y(.86f)) return false + val iconX = button.bounds.left + button.bounds.width() * .23f + val iconY = button.bounds.exactCenterY() + return ui.touch(iconX, iconY, iconX, iconY, 80L).also { dispatched -> + Log.i("ShijianXhs", "Video comments window=${page.windowId}, gestureDispatched=$dispatched") + } + } return ui.click(button) } - override fun openComments(expected: VideoContext): List { - if (commentNote != null || currentVideo().key != expected.key) { - throw PlatformException("小红书当前笔记或评论区已变化") + override fun openComments(expected: VideoContext): List = openCommentSurface(expected, forReceipt = false) + + override fun openCommentsForReceipt(expected: VideoContext) { + openCommentSurface(expected, forReceipt = true) + } + + private fun openCommentSurface(expected: VideoContext, forReceipt: Boolean): List { + if (commentNote != null) throw PlatformException("小红书当前笔记或评论区已变化") + val note = activeNote?.takeIf { it.video.key == expected.key } + ?: throw PlatformException("小红书当前笔记已变化") + val empty = awaitPage(if (forReceipt) 8_000 else 4_000, "小红书未核对当前笔记的评论入口") { page -> + val controls = page.boundNote(note) ?: return@awaitPage null + if (page.nodes.any { it.editable && (it.focused || it.hasDraft()) }) return@awaitPage null + val label = page.noteCommentButton(controls)?.description ?: return@awaitPage null + val zero = zeroComments.matches(label) + // A reopened player can briefly expose a zero/unloaded counter even when a reply exists. + if (forReceipt && (zero || label == "评论")) return@awaitPage null + zero } preparedReply = null + Log.i("ShijianXhs", "Comment list preflight kind=${note.kind}, receipt=$forReceipt, empty=$empty") + if (empty) { + commentNote = OpenCommentNote(expected, empty = true) + return emptyList() + } return try { - comments.open(expected).also { commentNote = expected } + comments.open(expected).also { commentNote = OpenCommentNote(expected, empty = false) } } catch (error: Exception) { comments.reset() throw error } } - override fun scanComments(): List = comments.scan() + override fun scanComments(): List { + val session = commentNote + if (session?.empty != true) return comments.scan() + if (currentVideo().key != session.note.key) throw PlatformException("小红书当前笔记已变化") + return emptyList() + } override fun scrollComments(): Boolean { if (preparedReply != null) throw PlatformException("请先完成或关闭当前小红书回复草稿") + if (commentNote?.empty == true) return false return comments.scroll() } override fun prepareReply(target: CommentTarget, expectedText: String): Boolean { check(commentNote != null && preparedReply == null) { "请先确认小红书评论区和草稿状态" } + if (commentNote?.empty == true) return false if (!receipt.captureBaseline(target, expectedText) || !composer.prepare(target)) return false preparedReply = PreparedReply(target, expectedText) return true @@ -471,12 +584,33 @@ internal class XiaohongshuAdapter( } } - override fun confirmPendingReply(video: VideoContext, pending: PendingComment): CommentPublishResult { - if (video.key != commentNote?.key || video.key != pending.videoKey) return CommentPublishResult.UNCERTAIN + override fun confirmPendingReply(video: VideoContext, pending: PendingComment): CommentPublishResult = + confirmPendingOnSurface(video, pending, fromStart = true) + + private fun confirmPendingOnSurface(video: VideoContext, pending: PendingComment, fromStart: Boolean): CommentPublishResult { + val session = commentNote?.takeUnless { it.empty } ?: return CommentPublishResult.UNCERTAIN + if (video.key != session.note.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) + return confirmReceipt(target, author, pending.text, pending.photos, since, fromStart) + } + + override fun confirmPendingReplyInPlace(video: VideoContext, pending: PendingComment): CommentPublishResult? { + val note = activeNote?.takeIf { it.video.key == video.key && video.key == pending.videoKey } ?: return null + val session = commentNote?.takeIf { !it.empty && it.note.key == video.key } ?: return null + if (preparedReply != null || session.note != video) return null + + if (ui.inspect { page -> comments.surface(page) != null && page.nodes.none { it.editable && (it.focused || it.hasDraft()) } } + == true) { + return confirmPendingOnSurface(video, pending, fromStart = false) + } + if (ui.inspect { page -> page.boundNote(note) != null && page.nodes.none { it.editable && (it.focused || it.hasDraft()) } } + != true) return null + + closeComments() + openCommentsForReceipt(video) + return confirmPendingReply(video, pending) } private fun confirmReceipt( @@ -485,13 +619,14 @@ internal class XiaohongshuAdapter( text: String, photos: List, armedAt: Long, - ): CommentPublishResult = receipt.confirm(targetKey, author, text, photos, armedAt).also { result -> + fromStart: Boolean = false, + ): CommentPublishResult = receipt.confirm(targetKey, author, text, photos, armedAt, fromStart).also { result -> if (result == CommentPublishResult.CONFIRMED && photos.isNotEmpty()) photoLibrary.cleanupStaged() } override fun closeComments() { - if (commentNote == null) return - comments.close() + val session = commentNote ?: return + if (!session.empty) comments.close() composer.close() preparedReply = null commentNote = null @@ -531,6 +666,7 @@ internal class XiaohongshuAdapter( val likeLabel = Regex("(?:已)?点赞$COUNTER") val favoriteLabel = Regex("(?:已)?收藏$COUNTER") val commentLabel = Regex("评论$COUNTER") + val zeroComments = Regex("评论\\s+0") val whitespace = Regex("\\s+") val layoutGaps = Regex("[\\s\\p{Cc}\\p{Cf}\\p{Z}]+") val expandCaption = Regex("(?:\\.{3}|…)+\\s*展开(?:全文)?$") diff --git a/app/src/main/java/com/jieliu/app/platform/XiaohongshuComments.kt b/app/src/main/java/com/jieliu/app/platform/XiaohongshuComments.kt index d1e649c..85ca105 100644 --- a/app/src/main/java/com/jieliu/app/platform/XiaohongshuComments.kt +++ b/app/src/main/java/com/jieliu/app/platform/XiaohongshuComments.kt @@ -141,8 +141,8 @@ internal class XiaohongshuComments( 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() + val close = page.modalCloseControl(visible) ?: return@inspect false + ui.click(close) } if (closed != true || ui.await(4_000) { ui.inspect { page -> true.takeIf { matchesNote(page, session.note) && !page.hasActiveDraft() } } @@ -200,7 +200,11 @@ internal class XiaohongshuComments( 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 (gap < -expansionOffset(visible) || gap > visible.viewport.width() * .055f || slot.bounds.top >= visible.viewport.bottom) break + if (gap < -2) { + val overlap = page.continuation(visible, slot, bottom) + return XhsCommentThread(replies, complete = false, expand = overlap.action) + } if (page.parts(visible, slot, nested = false).size == 1) { return XhsCommentThread(replies, complete = true, expand = null) } @@ -255,10 +259,35 @@ internal class XiaohongshuComments( 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.commentFooter(inline: Boolean): UiNode? { + if (!inline) return videoCommentFooter() + return nodes.singleOrNull { node -> + !node.editable && node.bounds.centerX() <= x(.57f) && node.bounds.centerY() >= y(.72f) && + node.description == "评论框" && + node.className in setOf("android.widget.TextView", "android.widget.Button", "android.view.ViewGroup") + } + } + + private fun UiPage.videoCommentFooter(): UiNode? { + val editor = nodes.singleOrNull { node -> + node.className == "android.widget.EditText" && node.editable && node.enabled && !node.focused && + node.showingHint && node.hint.isNotBlank() && node.text == node.hint && !node.hint.startsWith("回复") && + node.supports(AccessibilityNodeInfo.ACTION_SET_TEXT) && node.bounds.centerY() >= y(.84f) && + node.bounds.centerX() <= x(.53f) && node.bounds.width() >= bounds.width() * .55f + } ?: return null + val footer = editor.directParent()?.directParent()?.directParent()?.takeIf { owner -> + owner.className == "android.widget.LinearLayout" && owner.isNativeClick() && owner.bounds.contains(editor.bounds) && + bounds.contains(owner.bounds) && owner.bounds.width() >= bounds.width() * .95f && + owner.bounds.height() <= bounds.height() * .14f && owner.bounds.bottom >= y(.95f) + } ?: return null + + val icons = nodes.filter { node -> node.className == "android.widget.ImageView" && node.isNativeClick() && + node.directParent()?.directParent() === footer && footer.bounds.contains(node.bounds) && + node.bounds.left > editor.bounds.right && abs(node.bounds.centerY() - editor.bounds.centerY()) <= editor.bounds.height() / 2 && + abs(node.bounds.width() - node.bounds.height()) <= 2 && node.bounds.width() >= bounds.width() * .045f } + .sortedBy { it.bounds.left } + return footer.takeIf { icons.size == 2 && icons[0].directParent() === icons[1].directParent() && + icons[0].bounds.right < icons[1].bounds.left } } private fun UiPage.focusedCommentFooter(list: UiNode, heading: UiNode?): UiNode? { @@ -273,11 +302,16 @@ internal class XiaohongshuComments( } private fun UiPage.modalCloseControl(surface: XhsCommentSurface): UiNode? { + if (surface.inline || hasActiveDraft() || videoCommentFooter() == null) return null val heading = surface.heading ?: return null + val owner = heading.directParent() ?: return null + if (!surface.empty && abs(surface.root.bounds.top - heading.bounds.bottom) > 2) 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) + node.directParent() === owner && node.className == "android.widget.ImageView" && node.isNativeClick() && + node.labels().isEmpty() && node.bounds.centerX() >= x(.88f) && bounds.contains(node.bounds) && + node.bounds.width() in (bounds.width() * .045f).toInt()..(bounds.width() * .075f).toInt() && + abs(node.bounds.width() - node.bounds.height()) <= 2 && node.bounds.top < heading.bounds.top && + abs(node.bounds.bottom - heading.bounds.top) <= bounds.width() * .015f } } @@ -295,12 +329,7 @@ internal class XiaohongshuComments( 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 reply = page.originalReplyAction(visible, slot, original) val target = CommentTarget(identity(note.key, author.text, body.text), body.text, author.text) XhsCommentRow(target, slot, reply, author, body) } @@ -308,6 +337,26 @@ internal class XiaohongshuComments( return candidates.filter { counts[it.target.key] == 1 } } + private fun UiPage.originalReplyAction(surface: XhsCommentSurface, slot: UiNode, original: RowParts): UiNode? { + val footerTop = original.body.bounds.bottom + val labels = nodes.filter { node -> + node.isDescendantOf(slot) && node.bounds.top >= footerTop && node.bounds.bottom <= original.nextTop && + node.bounds.left >= original.author.bounds.left && surface.viewport.contains(node.bounds) + } + val controls = labels.filter { it.isNativeClick() && it.className in replyControlClasses && + it.labels().singleOrNull() == "回复" } + if (controls.isNotEmpty()) return controls.singleOrNull() + if (slot.directParent() !== surface.root || slot.className != "android.widget.LinearLayout" || + !slot.isNativeClick() || slot.bounds.width() < surface.viewport.width() * .90f || + !surface.viewport.contains(slot.bounds) || slot.bounds.bottom != original.nextTop) return null + + val footer = labels.singleOrNull { node -> node.commentText() && !node.clickable && + rowReplyFooter.matches(node.text) && slot.bounds.contains(node.bounds) && + abs(node.bounds.left - original.author.bounds.left) <= 2 && + node.bounds.top <= footerTop + original.author.bounds.height() } + return slot.takeIf { footer != null } + } + 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() && @@ -356,27 +405,72 @@ internal class XiaohongshuComments( 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 timestamps = detail.filter { it.commentText() && XhsCommentLabels.relativeTime(it.text) != null } + val time = timestamps.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 + .sortedWith(compareBy({ it.bounds.top }, { it.bounds.left })) + if (images.any { !it.isNativeClick() || !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 labeled = images.all { XhsCommentLabels.photoDescription(it.description) } + val ordered = if (labeled) images else images.sortedBy { it.bounds.left } + if (!labeled && !blankPhotoStrip(surface, slot, parts.body, timestamps.singleOrNull(), ordered)) return null val own = isOwn(parts) - XhsReplyRow(parts.body, own, images.sortedWith(compareBy({ it.bounds.top }, { it.bounds.left })), time, + XhsReplyRow(parts.body, own, ordered, time, identity(parentKey, parts.author.text, parts.body.text, images.size.toString())) } } + private fun blankPhotoStrip(surface: XhsCommentSurface, slot: UiNode, body: UiNode, time: UiNode?, images: List): Boolean { + if (images.size < 2 || time == null || time.clickable || abs(time.bounds.left - body.bounds.left) > 2) return false + val width = surface.viewport.width() + val maximumGap = (width * .035f).toInt() + val first = images.first().bounds + if (first.width() !in (width * .17f).toInt()..(width * .22f).toInt() || + abs(first.left - body.bounds.left) > 2 || first.top - body.bounds.bottom !in 0..maximumGap || + time.bounds.top - first.bottom !in 1..maximumGap) return false + + val tiles = images.map { image -> + if (image.className != "android.widget.ImageView" || image.labels().isNotEmpty() || + abs(image.bounds.top - first.top) > 2 || abs(image.bounds.width() - first.width()) > 2 || + abs(image.bounds.width() - image.bounds.height()) > 2 || image.bounds.bottom >= time.bounds.top) return false + image.directParent()?.takeIf { it.bounds.contains(image.bounds) } ?: return false + } + val strip = tiles.first().directParent() ?: return false + if (!strip.isDescendantOf(slot) || tiles.distinct().size != images.size || + tiles.any { it.directParent() !== strip || !strip.bounds.contains(it.bounds) }) return false + return images.zipWithNext().all { (left, right) -> right.bounds.left - left.bounds.right in 1..maximumGap } + } + 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 && + val labels = nodes.filter { node -> (node === slot || node.isDescendantOf(slot)) && + node.bounds.top >= after - expansionOffset(surface) && node.bounds.centerY() >= 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()) } + val action = unique?.let { expansionAction(surface, slot, it) } return Continuation(labels.isNotEmpty(), action) } + private fun expansionAction(surface: XhsCommentSurface, slot: UiNode, label: UiNode): UiNode? { + val text = label.labels().singleOrNull() ?: return null + if (!XhsCommentLabels.expandsReplies(text) || !surface.viewport.contains(label.bounds)) return null + if (label.className in replyControlClasses && label.isNativeClick()) return label + if (label.clickable || label.editable || !observedExpansion.matches(text)) return null + val passiveLabel = if (surface.inline) label.commentText() else label.className == "android.widget.Button" && + label.text == text && label.description == text + if (!passiveLabel) return null + val owner = label.directParent()?.directParent() ?: return null + val offset = expansionOffset(surface) + return label.takeIf { owner !== slot && owner.isDescendantOf(slot) && owner.className == "android.widget.LinearLayout" && + owner.labels().isEmpty() && owner.isNativeClick() && surface.viewport.contains(owner.bounds) && + slot.bounds.contains(owner.bounds.centerX(), owner.bounds.centerY()) && + owner.bounds.top >= slot.bounds.top - offset && owner.bounds.bottom <= slot.bounds.bottom + offset && + owner.bounds.contains(label.bounds.centerX(), label.bounds.centerY()) && + abs(owner.bounds.top - label.bounds.top) <= offset && abs(owner.bounds.bottom - label.bounds.bottom) <= offset } + } + + private fun expansionOffset(surface: XhsCommentSurface): Int = (surface.viewport.width() * .02f).toInt().coerceAtLeast(2) + 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()) } @@ -395,14 +489,24 @@ internal class XiaohongshuComments( 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") + val rowReplyFooter = Regex("(?:0?[1-9]|1[0-2])-(?:0?[1-9]|[12][0-9]|3[01])\\s+\\p{IsHan}{2,8}\\s+回复") + val observedExpansion = Regex("展开\\s*[1-9][0-9]*\\s*条回复") } } +internal fun UiPage.requireXhsCommentAccess() { + val title = nodes.singleOrNull { it.text == "社区评论互动功能限制中" && !it.clickable } ?: return + val parent = title.directParent() ?: return + val others = nodes.filter { it.directParent() === parent && bounds.contains(it.bounds) } + if (others.count { it.text == "账号存在安全风险" && !it.clickable } == 1 && + others.count { it.text == "知道了" && it.clickable } == 1 && + others.count { it.text == "查看详情" && it.clickable } == 1 + ) throw PlatformInteractionRestrictedException("小红书提示账号存在安全风险,社区评论互动功能受限") +} + internal object XhsCommentLabels { private val heading = Regex("共\\s*(\\d+)\\s*条评论") private val empty = setOf("暂无评论", "还没有评论") diff --git a/app/src/main/java/com/jieliu/app/platform/XiaohongshuReplyComposer.kt b/app/src/main/java/com/jieliu/app/platform/XiaohongshuReplyComposer.kt index 50d2109..c490060 100644 --- a/app/src/main/java/com/jieliu/app/platform/XiaohongshuReplyComposer.kt +++ b/app/src/main/java/com/jieliu/app/platform/XiaohongshuReplyComposer.kt @@ -6,8 +6,11 @@ import com.jieliu.app.data.PhotoLibrary import com.jieliu.app.task.TaskPlan import com.jieliu.app.task.TemplatePhoto import java.io.Closeable +import kotlin.math.abs +import kotlin.math.ceil +import kotlin.math.floor -/** The XHS reply and picker anchors still require device verification. */ +/** Native reply and photo picker topology observed on Xiaohongshu 9.54.0. */ internal class XiaohongshuReplyComposer( private val ui: AccessibleUi, private val photos: PhotoLibrary, @@ -15,8 +18,10 @@ internal class XiaohongshuReplyComposer( ) : Closeable { private class Prepared( val target: CommentTarget, - val windowId: Int, + val originalWindow: Int, val surface: UiNodeSource, + val editorWindow: Int, + val toolbarIcons: Int, val container: UiNodeSource, val editor: UiNodeSource, ) : Closeable { @@ -30,12 +35,14 @@ internal class XiaohongshuReplyComposer( } } - private data class Composer(val editor: UiNode, val container: UiNode) + private data class Origin(val windowId: Int, val toolbarIcons: Int, val surface: UiNodeSource) + private data class Composer(val editor: UiNode, val container: UiNode, val toolbar: Toolbar) + private data class Toolbar(val root: UiNode, val album: UiNode, val send: 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 data class ImageRegion(val bounds: Rect, val overlay: Rect) + private data class ImageSnapshot(val windowId: Int, val images: List) + private data class ReadyDraft(val send: UiNode, val snapshot: ImageSnapshot) private var prepared: Prepared? = null @@ -47,7 +54,7 @@ internal class XiaohongshuReplyComposer( 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) && + (it === row.container || 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()) }) { @@ -57,24 +64,26 @@ internal class XiaohongshuReplyComposer( val anchor = surface.root.retainSource() try { if (!ui.click(reply)) throw PlatformException("未确认小红书已打开选中评论的回复框") - surface.windowId to anchor + Origin(surface.windowId, if (surface.inline) 5 else 6, anchor) } catch (error: Throwable) { anchor.close() throw error } } ?: return false - val (windowId, anchor) = opened + val (windowId, toolbarIcons, 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 + // Only the exact native original-row action above may establish this new reply window. + if (page.windowId == windowId || comments.surface(page) != null) return@awaitPage null + val composer = page.openedComposer(target, toolbarIcons) ?: 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()) + Prepared(target, windowId, anchor, page.windowId, toolbarIcons, + composer.container.retainSource(), composer.editor.retainSource()) } return true } finally { @@ -96,7 +105,10 @@ internal class XiaohongshuReplyComposer( if (!blank) throw PlatformException("小红书回复框已变化或已有草稿,未修改内容") val references = if (attachments.isEmpty()) emptyList() else { - photos.readReceiptPixels(attachments) ?: throw PlatformException("无法读取小红书回复的绑定图片") + val pixels = photos.readReceiptPixels(attachments) ?: throw PlatformException("无法读取小红书回复的绑定图片") + val digests = photos.attachmentDigests(attachments)?.takeIf { it.size == pixels.size } + ?: throw PlatformException("无法核对小红书回复的绑定图片文件") + pixels.indices.map { AttachmentReference(digests[it], pixels[it]) } } val staged = if (references.isEmpty()) null else { photos.cleanupStaged() @@ -117,7 +129,7 @@ internal class XiaohongshuReplyComposer( page.readyDraft(session, text, references.size)?.snapshot } if (references.isNotEmpty()) { - verifyPhotos(references, ready.windowId, ready.images, "小红书回复草稿的图片与绑定图片不符") + verifyPhotos(references, ready, "小红书回复草稿的图片与绑定图片不符") } val current = ui.inspect { page -> page.readyDraft(session, text, references.size)?.snapshot } == ready @@ -140,17 +152,10 @@ internal class XiaohongshuReplyComposer( 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 + page.requireXhsCommentAccess() + if (!page.matchesTarget(session.target, session.originalWindow, 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.takeIf { page.nodes.none { it.replyCue(session.target) } } } } == true } @@ -160,48 +165,56 @@ internal class XiaohongshuReplyComposer( prepared = null } - private fun attach(session: Prepared, album: String, references: List, beforeAttach: () -> Unit) { + 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) + ui.click(composer.toolbar.album) } == 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 + val (pickerWindow, openAlbumList) = awaitPage(6_000, "小红书相册页或相册分类控件不可核对") { page -> + if (page.windowId == session.editorWindow || page.windowId == session.originalWindow) return@awaitPage null + if (page.albumHeading(album) != null) return@awaitPage page.windowId to false + val heading = page.albumHeading("全部") ?: return@awaitPage null + val toggle = heading.directParent()?.directParent()?.takeIf { + it.className == RELATIVE_LAYOUT && it.nativeClick() && it.bounds.contains(heading.bounds) + } ?: return@awaitPage null if (!ui.click(toggle)) throw PlatformException("小红书未接受相册分类操作") - true + page.windowId to true } if (openAlbumList) { awaitPage(6_000, "小红书相册没有唯一的本次专用相册") { page -> + if (page.windowId == pickerWindow || page.windowId == session.editorWindow || page.windowId == session.originalWindow) { + return@awaitPage null + } val label = page.nodes.singleOrNull { - !it.editable && it.hasExactLabel(album) && it.bounds.centerY() > page.y(.14f) + it.className == TEXT_VIEW && it.text == album && page.bounds.contains(it.bounds) } ?: return@awaitPage null - val item = label.nativeAction() ?: return@awaitPage null + val item = label.directParent()?.takeIf { it.className == RELATIVE_LAYOUT && it.nativeClick() && + it.bounds.contains(label.bounds) && it.bounds.width() >= page.bounds.width() * .80f } ?: return@awaitPage null + val count = page.nodes.singleOrNull { it.directParent() === item && it !== label && + it.className == TEXT_VIEW && it.text == references.size.toString() && + it.bounds.centerX() > label.bounds.centerX() && item.bounds.contains(it.bounds) } + if (count == null) return@awaitPage null if (!ui.click(item)) throw PlatformException("小红书未打开本次专用相册") true } } val empty = awaitPage(6_000, "小红书专用相册未完整显示所有可多选图片") { page -> + if (page.windowId != pickerWindow) return@awaitPage null 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) + val crops = captureVisibleImages(empty) ?.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 order = pickerAttachmentOrder(references, crops) + ?: throw PlatformException("小红书专用相册中的图片无法唯一对应本次附件") val selected = MutableList(references.size) { 0 } for ((index, tileIndex) in order.withIndex()) { @@ -232,13 +245,34 @@ internal class XiaohongshuReplyComposer( } } - 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]) }) { + private fun verifyPhotos(references: List, snapshot: ImageSnapshot, failure: String) { + val crops = captureVisibleImages(snapshot) ?: throw PlatformException(failure) + if (matchedAttachmentDigests(references, crops, PublishedPhotoMatcher::matchesXhsDraft) != + references.map(AttachmentReference::digest)) { throw PlatformException(failure) } } + private fun captureVisibleImages(snapshot: ImageSnapshot): List? { + val captured = ui.screenshotPhotos(snapshot.windowId, snapshot.images.map(ImageRegion::bounds)) + ?.takeIf { it.size == snapshot.images.size } ?: return null + return captured.zip(snapshot.images) { picture, region -> picture.maskControl(region) } + } + + private fun PhotoPixels.maskControl(region: ImageRegion): PhotoPixels { + val overlay = Rect(region.overlay).apply { inset(-2, -2) } + if (!overlay.intersect(region.bounds)) return this + val xScale = width.toDouble() / region.bounds.width() + val yScale = height.toDouble() / region.bounds.height() + val left = floor((overlay.left - region.bounds.left) * xScale).toInt().coerceIn(0, width) + val right = ceil((overlay.right - region.bounds.left) * xScale).toInt().coerceIn(left, width) + val top = floor((overlay.top - region.bounds.top) * yScale).toInt().coerceIn(0, height) + val bottom = ceil((overlay.bottom - region.bounds.top) * yScale).toInt().coerceIn(top, height) + val masked = argb.copyOf() + for (y in top until bottom) masked.fill(0, y * width + left, y * width + right) + return copy(argb = masked) + } + 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) && @@ -247,32 +281,50 @@ internal class XiaohongshuReplyComposer( private fun UiPage.hasPrivateDraft(): Boolean = nodes.any { it.editable && it.hasDraft() || it.labels().any(removeActions::contains) || - it.isImage() && it.labels().any(previewLabels::contains) + it.className == IMAGE_VIEW && 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 + private fun UiPage.openedComposer(target: CommentTarget, toolbarIcons: Int): Composer? { + val editor = nodes.singleOrNull { it.className == EDIT_TEXT && it.canEdit() && it.focused && + it.bounds.centerY() >= y(.40f) && it.bounds.width() >= bounds.width() * .65f && it.replyCue(target) } + ?: return null + val toolbar = replyToolbar(editor, toolbarIcons) ?: 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 } } + toolbar.root.isDescendantOf(scope) && nodes.none { it !== editor && it.editable && it.isDescendantOf(scope) } } ?: return null - return Composer(editor, container) + return Composer(editor, container, toolbar) } private fun UiPage.checkedComposer(session: Prepared): Composer? { - if (!matchesTarget(session.target, session.windowId, session.surface)) return null + if (windowId != session.editorWindow || comments.surface(this) != null) return null val container = nodes.singleOrNull { it.hasSource(session.container) } ?: return null - val editor = nodes.singleOrNull { it.focused && it.canEdit() && it.hasSource(session.editor) && + val editor = nodes.singleOrNull { it.className == EDIT_TEXT && 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) + if (nodes.any { it !== editor && it.editable && it.focused } || !editor.replyCue(session.target)) return null + val toolbar = replyToolbar(editor, session.toolbarIcons)?.takeIf { it.root.isDescendantOf(container) } ?: return null + return Composer(editor, container, toolbar) + } + + private fun UiPage.replyToolbar(editor: UiNode, toolbarIcons: Int): Toolbar? { + val send = nodes.singleOrNull { + it.className == TEXT_VIEW && it.text == "发送" && !it.editable && it.bounds.centerX() >= x(.75f) && + it.bounds.top >= editor.bounds.bottom && it.bounds.top - editor.bounds.bottom <= editor.bounds.height() * 2 + } ?: return null + val root = send.directParent() ?: return null + val overlay = nodes.singleOrNull { it.directParent() === root && it.className == "android.view.View" && + it.labels().isEmpty() && it.bounds == send.bounds && it.nativeClick() } ?: return null + if (!root.bounds.contains(overlay.bounds)) return null + val icons = nodes.filter { it.directParent() === root && it.className == IMAGE_VIEW && it.nativeClick() } + .sortedBy { it.bounds.left } + if (icons.size != toolbarIcons) return null + val first = icons.first().bounds + if (abs(first.width() - first.height()) > 2 || first.width() < 24 || first.width() > bounds.width() * .18f) return null + if (icons.any { icon -> !root.bounds.contains(icon.bounds) || icon.bounds.right > send.bounds.left || + abs(icon.bounds.centerY() - send.bounds.centerY()) > 2 || !sameSize(icon.bounds, first) }) return null + val gaps = icons.zipWithNext { left, right -> right.bounds.left - left.bounds.right } + if (gaps.any { it < 0 || it > first.width() / 3 || abs(it - gaps.first()) > 2 }) return null + return Toolbar(root, icons[1], send) } private fun UiPage.readyDraft(session: Prepared, text: String, count: Int): ReadyDraft? { @@ -280,81 +332,92 @@ internal class XiaohongshuReplyComposer( 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) })) + val send = composer.toolbar.send.takeIf { it.nativeClick() } ?: return null + return ReadyDraft(send, ImageSnapshot(windowId, previews)) } - 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 } + private fun UiPage.draftThumbnails(composer: Composer): List? { + val toolbar = composer.toolbar + val lower = nodes.filter { it.isDescendantOf(composer.container) && it.className == IMAGE_VIEW && + it.bounds.centerY() > toolbar.album.bounds.bottom && !it.isDescendantOf(toolbar.root) } + if (lower.isEmpty()) return emptyList() + if (lower.any { !it.nativeClick() || !composer.container.bounds.contains(it.bounds) || !bounds.contains(it.bounds) }) return null + val cells = lower.filter { abs(it.bounds.width() - it.bounds.height()) <= 2 && + it.bounds.width() >= toolbar.album.bounds.width() && it.bounds.top >= toolbar.album.bounds.bottom } + .sortedBy { it.bounds.left } + if (cells.isEmpty()) return null + val first = cells.first().bounds + if (cells.any { !sameSize(it.bounds, first) || abs(it.bounds.top - first.top) > 2 }) return null + val cellParents = cells.map { it.directParent() ?: return null } + val strip = cellParents.first().directParent() ?: return null + if (cellParents.distinct().size != cells.size || cellParents.any { it.directParent() !== strip }) return null + if ((strip.horizontalItemCount ?: cells.size) != cells.size) return null + val removals = lower.filterNot(cells::contains) + val found = mutableListOf() + val usedRemovals = mutableSetOf() + for ((index, cell) in cells.withIndex()) { + val sameCell = removals.filter { it.directParent() === cellParents[index] } + if (sameCell.isEmpty() && index == cells.lastIndex) continue // Trailing Add tile has no remove sibling. + val remove = sameCell.singleOrNull() ?: return null + val image = cell.bounds + val overlay = remove.bounds + if (!Rect.intersects(image, overlay) || overlay.width() > image.width() / 2 || overlay.height() > image.height() / 2 || + overlay.top > image.top || overlay.left < image.centerX() || overlay.right < image.right || !usedRemovals.add(remove)) return null + found.add(ImageRegion(Rect(image), Rect(overlay))) } - 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 }) + if (usedRemovals.size != removals.size || found.isEmpty() || found.size > TaskPlan.MAX_TEMPLATE_PHOTOS) return null + if (found.size != cells.size - 1 && found.size != TaskPlan.MAX_TEMPLATE_PHOTOS) return null + return found } - 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 } + private fun UiPage.albumHeading(label: String): UiNode? { + val hasExit = nodes.count { it.className == IMAGE_VIEW && it.bounds.centerY() < y(.24f) && + it.bounds.centerX() < x(.23f) && it.labels().contains("关闭") && it.nativeClick() } == 1 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) } + return nodes.singleOrNull { it.className == TEXT_VIEW && !it.editable && it.bounds.centerY() < y(.24f) && + it.bounds.centerX() in x(.22f)..x(.78f) && it.text == label } } 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 heading = albumHeading(album) ?: return null + val done = nodes.singleOrNull { node -> node.className == TEXT_VIEW && node.nativeClick() && + node.bounds.centerY() > y(.80f) && node.bounds.centerX() > x(.74f) && + selectionCount.matches(node.text.filterNot(Char::isWhitespace)) } ?: return null + val match = selectionCount.matchEntire(done.text.filterNot(Char::isWhitespace)) ?: 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) } + // The picker contains nested RecyclerViews. Bind all tiles to their innermost common gallery. + val images = nodes.filter { it.className == IMAGE_VIEW && it.bounds.width() >= bounds.width() * .15f && + abs(it.bounds.width() - it.bounds.height()) <= 2 && it.bounds.top >= heading.bounds.bottom && + it.bounds.bottom <= done.bounds.top && bounds.contains(it.bounds) && it.nearestGallery() != null } if (images.size != expected) return null + val grid = images.firstOrNull()?.nearestGallery()?.takeIf { it.bounds.width() >= bounds.width() * .60f } ?: return null + if (images.any { it.nearestGallery() !== grid || !grid.bounds.contains(it.bounds) }) 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) + val select = nodes.singleOrNull { it.directParent() === parent && it.className == "android.widget.FrameLayout" && + image.bounds.contains(it.bounds) && it.nativeClick() && it.labels().isEmpty() && + abs(it.bounds.top - image.bounds.top) <= 2 && abs(it.bounds.right - image.bounds.right) <= 2 && + it.bounds.width() <= image.bounds.width() / 2 && it.bounds.height() <= image.bounds.height() / 2 } + ?: return null + AlbumTile(image, select, selectionOrdinal(select) ?: 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 UiNode.nearestGallery(): UiNode? = generateSequence(directParent()) { it.directParent() } + .firstOrNull { it.className == "androidx.recyclerview.widget.RecyclerView" } - private fun Picker.matches(expected: PickerSnapshot, windowId: Int, selected: List, count: Int): Boolean = + private fun Picker.snapshot(windowId: Int) = ImageSnapshot(windowId, tiles.map { ImageRegion(Rect(it.image.bounds), Rect(it.select.bounds)) }) + + private fun Picker.matches(expected: ImageSnapshot, 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 UiPage.selectionOrdinal(select: UiNode): Int? { + val marks = nodes.filter { it.isDescendantOf(select) && it.className == TEXT_VIEW && !it.clickable && + select.bounds.contains(it.bounds) && it.text.toIntOrNull()?.let { number -> number in 1..TaskPlan.MAX_TEMPLATE_PHOTOS } == true } + if (!select.selected) return 0.takeIf { marks.isEmpty() } + return marks.singleOrNull()?.takeIf { it.selected }?.text?.toIntOrNull() } private fun UiNode.replyCue(target: CommentTarget): Boolean = sequenceOf(hint, description, text.takeIf { !editable || showingHint }.orEmpty()) @@ -369,29 +432,46 @@ internal class XiaohongshuReplyComposer( 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 sameSize(first: Rect, second: Rect) = + abs(first.width() - second.width()) <= 2 && abs(first.height() - second.height()) <= 2 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("相册", "插入图片", "添加图片", "选择图片") + const val IMAGE_VIEW = "android.widget.ImageView" + const val TEXT_VIEW = "android.widget.TextView" + const val EDIT_TEXT = "android.widget.EditText" + const val RELATIVE_LAYOUT = "android.widget.RelativeLayout" 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])(?:张图片|张)?""") + val selectionCount = Regex("""完成(?:\(([0-9]+)\))?""") + } +} + +private data class AttachmentReference(val digest: String, val pixels: PhotoPixels) + +private fun pickerAttachmentOrder(references: List, crops: List): List? { + val digests = matchedAttachmentDigests(references, crops, PublishedPhotoMatcher::matches) ?: return null + val availableTiles = digests.withIndex().groupBy({ it.value }, { it.index }).mapValues { ArrayDeque(it.value) } + // Byte-identical copies use distinct native tiles, taken in their displayed order. + return references.map { availableTiles.getValue(it.digest).removeFirst() } +} + +private fun matchedAttachmentDigests( + references: List, + crops: List, + matches: (PhotoPixels, PhotoPixels) -> Boolean, +): List? { + if (crops.size != references.size) return null + val distinctFiles = references.distinctBy(AttachmentReference::digest) + val digests = crops.map { crop -> + distinctFiles.singleOrNull { matches(it.pixels, crop) }?.digest ?: return null + } + return digests.takeIf { + it.groupingBy { digest -> digest }.eachCount() == references.groupingBy(AttachmentReference::digest).eachCount() } } diff --git a/app/src/main/java/com/jieliu/app/platform/XiaohongshuReplyReceipt.kt b/app/src/main/java/com/jieliu/app/platform/XiaohongshuReplyReceipt.kt index e84f28f..98e43f6 100644 --- a/app/src/main/java/com/jieliu/app/platform/XiaohongshuReplyReceipt.kt +++ b/app/src/main/java/com/jieliu/app/platform/XiaohongshuReplyReceipt.kt @@ -1,29 +1,44 @@ 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.TemplatePhoto +import com.jieliu.app.task.XIAOHONGSHU_RECHECK_WINDOW_MS /** 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 val diagnostic: (String) -> Unit = {}, ) { 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) + private data class Baseline(val stamp: ThreadStamp, val parentVisible: Boolean, val authorTop: Int, val bodies: List) + private data class VisibleReceipt(val identity: String, val originalBody: Rect, val body: Rect, val photos: List, val own: Boolean) + private enum class CommentRole { OWN, OTHER } + private data class RoleMenu(val windowId: Int, val scroll: Rect, val role: CommentRole?) + private class Diagnostics(private val emit: (String) -> Unit) { + private val seen = mutableSetOf() + + fun record(event: String) { + if (seen.add(event)) emit(event) + } + } 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 -> + var expansions = 0 + var adjustments = 0 + repeat(MAX_EXPANSIONS + MAX_BASELINE_ADJUSTMENTS + 1) { 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 }) + val parentVisible = contains(surface.viewport, parent.author.bounds) && contains(surface.viewport, parent.body.bounds) + Baseline(stamp(thread), parentVisible, parent.author.bounds.top, 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. @@ -33,8 +48,24 @@ internal class XiaohongshuReplyReceipt( 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 + if (baseline.stamp.expandLabels != null && expansions < MAX_EXPANSIONS) { + when (expandThread(scope, original, baseline.stamp)) { + false -> return false + null -> return@repeat + true -> Unit + } + expansions++ + if (ui.await(THREAD_WAIT_MS) { changedThread(scope, original, baseline.stamp) } != true) return false + } else { + if (adjustments == MAX_BASELINE_ADJUSTMENTS) return false + ui.pace() + if (!bringLowerReplyIntoView(scope, original)) return false + adjustments++ + val moved = ui.await(THREAD_WAIT_MS) { + readOriginal(scope, original) { _, parent -> true.takeIf { baseline.authorTop - parent.author.bounds.top >= 12 } } + } + if (moved != true) return false + } } return false } @@ -45,34 +76,60 @@ internal class XiaohongshuReplyReceipt( text: String, photos: List, armedAt: Long, + fromStart: Boolean, ): CommentPublishResult { + val diagnostics = Diagnostics(diagnostic) + diagnostics.record("小红书开始回查回复") if (targetKey.isBlank() || author.isBlank() || text.isBlank() || !validXhsReceiptAge(armedAt, System.currentTimeMillis())) { + diagnostics.record("小红书回查缺少回复记录或已超过核对时限") 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 + val references = this.photos.readReceiptPixels(photos) ?: run { + diagnostics.record("小红书回查无法读取原始附件") + return CommentPublishResult.UNCERTAIN + } + val scope = findSurface() ?: run { + diagnostics.record("小红书回查无法定位评论区") + return CommentPublishResult.UNCERTAIN + } + if (!seekOriginal(scope, original, diagnostics, reverseLimit = if (fromStart) 0 else MAX_REVERSE_SCROLLS)) { + diagnostics.record("小红书回查未能稳定定位原评论") + return CommentPublishResult.UNCERTAIN + } var expansions = 0 var revisitedOriginal = false val opened = mutableSetOf() + val ownershipChecks = mutableSetOf() repeat(MAX_RECEIPT_PASSES) { - if (ui.await(RECEIPT_WAIT_MS) { verifiedReceipt(scope, original, text, references, armedAt) } == true) { - return CommentPublishResult.CONFIRMED + val confirmed = ui.await(RECEIPT_WAIT_MS) { + verifiedReceipt(scope, original, text, references, armedAt, ownershipChecks, diagnostics) } + if (confirmed == 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 + diagnostics.record("小红书回查暂时无法读取原评论线程") + if (revisitedOriginal || !seekOriginal(scope, original, diagnostics, 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 + } else if (seen.expandLabels != null && expansions < MAX_EXPANSIONS && seen !in opened) { + diagnostics.record("小红书回查已找到原评论的展开控件") + when (expandThread(scope, original, seen, diagnostics)) { + true -> { + expansions++ + opened.add(seen) + if (ui.await(THREAD_WAIT_MS) { changedThread(scope, original, seen) } != true) { + diagnostics.record("小红书回查展开后未读取到线程变化") + } + } + false -> if (!bringLowerReplyIntoView(scope, original)) return CommentPublishResult.UNCERTAIN + null -> Unit + } + } else { + diagnostics.record("小红书回查未找到可展开的回复控件") + if (!bringLowerReplyIntoView(scope, original)) return CommentPublishResult.UNCERTAIN } } return CommentPublishResult.UNCERTAIN @@ -84,72 +141,201 @@ internal class XiaohongshuReplyReceipt( text: String, references: List, armedAt: Long, + ownershipChecks: MutableSet, + diagnostics: Diagnostics, ): 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]) } + val before = receiptRow(scope, original, text, references.size, armedAt, diagnostics) ?: return null + val captured = if (references.isEmpty()) emptyList() else ui.screenshotPhotos(scope.windowId, before.photos) ?: run { + diagnostics.record("小红书回查未能截取已发布的图片") + return null } + val after = receiptRow(scope, original, text, references.size, armedAt) + if (before != after) { + diagnostics.record("小红书回查截取图片时回复位置发生变化") + return null + } + if (captured.size != references.size || !references.indices.all { PublishedPhotoMatcher.matches(references[it], captured[it]) }) { + diagnostics.record("小红书回查的已发布图片未通过内容比对") + return null + } + if (references.isNotEmpty()) diagnostics.record("小红书回查已核对已发布图片") + if (before.own) { + diagnostics.record("小红书回查已读取到本人回复标记") + return true + } + if (!ownershipChecks.add(before.identity)) return null + + // XHS may hide the self badge. Compare the action menus on this exact reply and its original. + val current = { receiptRow(scope, original, text, references.size, armedAt) == before } + diagnostics.record("小红书回查正在比对评论菜单以核对本人身份") + val own = inspectRole(scope, before.originalBody, current) == CommentRole.OTHER && + inspectRole(scope, before.body, current) == CommentRole.OWN && current() + diagnostics.record(if (own) "小红书回查已通过评论菜单确认本人身份" else "小红书回查未能通过评论菜单核对本人身份") + return true.takeIf { own } } - 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 receiptRow( + scope: SurfaceKey, + original: OriginalComment, + text: String, + photoCount: Int, + armedAt: Long, + diagnostics: Diagnostics? = null, + ): 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.body.text == text } ?: run { + diagnostics?.record("小红书回查暂未读取到唯一匹配的回复正文") + return@readThread null + } + diagnostics?.record("小红书回查已找到匹配的回复正文") + val time = reply.timeLabel + if (reply.identity.isBlank() || thread.replies.count { it.identity == reply.identity } != 1 || + !contains(viewport, reply.body.bounds) || time == null || !matchesXhsReceiptTime(time, armedAt, System.currentTimeMillis()) + ) { + diagnostics?.record("小红书回查无法核对回复位置、唯一性或发布时间") + return@readThread null } - 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 + 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]) } } + ) { + diagnostics?.record("小红书回查无法核对已发布图片的数量或位置") + return@readThread null + } + VisibleReceipt(reply.identity, Rect(parent.body.bounds), Rect(reply.body.bounds), crops, reply.own) + } + + private fun inspectRole(scope: SurfaceKey, body: Rect, isSameReceipt: () -> Boolean): CommentRole? { + if (!isSameReceipt()) return null + val x = body.exactCenterX() + val y = body.exactCenterY() + if (!ui.touch(x, y, x, y, 670L)) return null + val menu = ui.await(MENU_WAIT_MS) { ui.inspect { roleMenu(it, scope.windowId) } } ?: return null + val confirmed = try { + menu.role ?: run { + val area = menu.scroll + val scrollX = area.exactCenterX() + if (!ui.touch(scrollX, area.top + area.height() * .83f, scrollX, area.top + area.height() * .19f, 450L)) { + null + } else ui.await(MENU_WAIT_MS) { + ui.inspect { page -> roleMenu(page, scope.windowId)?.takeIf { it.windowId == menu.windowId }?.role } + } + } + } finally { + if (ui.inspect { page -> roleMenu(page, scope.windowId)?.windowId } == menu.windowId) ui.back() + } + return confirmed.takeIf { ui.await(MENU_WAIT_MS) { true.takeIf { isSameReceipt() } } == true } + } + + private fun roleMenu(page: UiPage, previousWindowId: Int): RoleMenu? { + if (page.windowId == previousWindowId || page.bounds.top <= 0 || hasOpenEditor(page)) return null + val scroll = page.nodes.singleOrNull { node -> + node.className == "android.widget.ScrollView" && node.scrollable && page.bounds.contains(node.bounds) && + node.bounds.width() >= page.bounds.width() * .94f && node.bounds.height() >= page.bounds.height() * .75f && + node.bounds.bottom == page.bounds.bottom + } ?: return null + val actions = page.nodes.mapNotNull { node -> + if (node.className != "android.widget.TextView" || node.clickable || !node.isDescendantOf(scroll) || + !scroll.bounds.contains(node.bounds) + ) return@mapNotNull null + val cell = node.directParent()?.directParent()?.takeIf { + it.className == "android.widget.LinearLayout" && it.enabled && + it.supports(AccessibilityNodeInfo.ACTION_CLICK) && it.bounds.contains(node.bounds) && + it.bounds.width() >= scroll.bounds.width() * .94f + } ?: return@mapNotNull null + node.text to cell + } + val labels = actions.map { it.first } + if (sharedMenuActions.count { it in labels } < 2) return null + val finalAction = actions.singleOrNull { it.first == "删除" || it.first == "举报" } + val role = finalAction?.takeIf { (_, cell) -> + "收藏" in labels && "复制" in labels && scroll.bounds.contains(cell.bounds) && + scroll.bounds.bottom - cell.bounds.bottom <= scroll.bounds.width() * .05f + }?.let { (label, _) -> if (label == "删除") CommentRole.OWN else CommentRole.OTHER } + return RoleMenu(page.windowId, Rect(scroll.bounds), role) + } + + private fun seekOriginal( + scope: SurfaceKey, + original: OriginalComment, + diagnostics: Diagnostics, + forwardLimit: Int = MAX_FORWARD_SCROLLS, + reverseLimit: Int = MAX_REVERSE_SCROLLS, + ): Boolean { + if (originalPosition(scope, original) != null) { + diagnostics.record("小红书回查已看到原评论") + if (awaitStableOriginal(scope, original, diagnostics)) return true + } + for (index in 0 until reverseLimit) { + if (!moveBackward(scope)) break + if (awaitStableOriginal(scope, original, diagnostics)) return true + } + repeat(forwardLimit) { + if (ui.inspect { matchingSurface(it, scope) != null } != true) return false + diagnostics.record("小红书回查正在向下查找原评论") + val moved = comments.scroll() + if (awaitStableOriginal(scope, original, diagnostics)) return true + if (!moved) return false } return false } - private fun originalVisible(scope: SurfaceKey, original: OriginalComment): Boolean = - readOriginal(scope, original) { _, _ -> true } == true + private fun originalPosition(scope: SurfaceKey, original: OriginalComment): Rect? = + readOriginal(scope, original) { surface, row -> + if (contains(surface.viewport, row.author.bounds) && contains(surface.viewport, row.body.bounds)) { + Rect(row.body.bounds) + } else null + } - 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) + private fun awaitStableOriginal(scope: SurfaceKey, original: OriginalComment, diagnostics: Diagnostics): Boolean { + var previous: Rect? = null + var stationary = 0 + val stable = ui.await(THREAD_WAIT_MS) { + val current = originalPosition(scope, original) + if (current != null) diagnostics.record("小红书回查已看到原评论") + stationary = if (current != null && current == previous) stationary + 1 else 0 + previous = current + true.takeIf { stationary >= 2 } + } == true + if (stable) diagnostics.record("小红书回查已稳定定位原评论") + return stable + } + + private fun moveBackward(scope: SurfaceKey): Boolean = ui.inspect { page -> + val surface = matchingSurface(page, scope) ?: return@inspect false + // Pulling the video sheet down from the first comment can dismiss it. + val backward = AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD + surface.root.supports(backward) && surface.root.act(backward) } == 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 shift = (parent.author.bounds.top - area.top - maxOf(24, area.width() / 30)).coerceAtMost(area.height() / 4) + if (shift < maxOf(42, area.width() / 18)) return@readOriginal false val x = area.exactCenterX() val from = area.top + area.height() * .72f - ui.touch(x, from, x, from - shift, 290L) + ui.touch(x, from, x, from - shift, maxOf(450L, shift * 2L)) } == true - private fun expandThread(scope: SurfaceKey, original: OriginalComment, previous: ThreadStamp): Boolean = + private fun expandThread( + scope: SurfaceKey, + original: OriginalComment, + previous: ThreadStamp, + diagnostics: Diagnostics? = null, + ): Boolean? = readThread(scope, original) { surface, _, thread -> - if (stamp(thread) != previous) return@readThread true + if (stamp(thread) != previous) return@readThread null val expand = thread.expand ?: return@readThread false - !thread.complete && contains(surface.viewport, expand.bounds) && ui.click(expand) - } == true + if (thread.complete || !contains(surface.viewport, expand.bounds)) return@readThread false + diagnostics?.record("小红书回查正在展开原评论的回复") + ui.click(expand, surface.viewport).also { accepted -> + diagnostics?.record(if (accepted) "小红书回查已触发展开回复" else "小红书回查未能触发展开回复") + } + } private fun changedThread(scope: SurfaceKey, original: OriginalComment, previous: ThreadStamp): Boolean? = readThread(scope, original) { _, _, thread -> true.takeIf { stamp(thread) != previous } } @@ -160,6 +346,7 @@ internal class XiaohongshuReplyReceipt( private fun findSurface(): SurfaceKey? = ui.await(THREAD_WAIT_MS) { ui.inspect { page -> + page.requireXhsCommentAccess() 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) } @@ -167,6 +354,7 @@ internal class XiaohongshuReplyReceipt( } private fun matchingSurface(page: UiPage, scope: SurfaceKey): XhsCommentSurface? { + page.requireXhsCommentAccess() 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) @@ -199,20 +387,22 @@ internal class XiaohongshuReplyReceipt( private companion object { const val MAX_EXPANSIONS = 4 + const val MAX_BASELINE_ADJUSTMENTS = 2 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 + const val MENU_WAIT_MS = 1_900L + val sharedMenuActions = setOf("分享到微信", "问点点", "搜索", "回复", "收藏", "复制") } } -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 + armedAt > 0 && armedAt <= now && now - armedAt <= XIAOHONGSHU_RECHECK_WINDOW_MS internal fun matchesXhsReceiptTime(label: String, armedAt: Long, now: Long): Boolean { if (!validXhsReceiptAge(armedAt, now)) return false diff --git a/app/src/main/java/com/jieliu/app/task/TaskCheckpoint.kt b/app/src/main/java/com/jieliu/app/task/TaskCheckpoint.kt index 791c64c..a2511c5 100644 --- a/app/src/main/java/com/jieliu/app/task/TaskCheckpoint.kt +++ b/app/src/main/java/com/jieliu/app/task/TaskCheckpoint.kt @@ -70,8 +70,9 @@ data class TaskCheckpoint( val video = activeVideo ?: return false val target = claim.targetKey?.takeIf { it.isNotBlank() } ?: return false val armedAt = claim.armedAtEpochMs ?: return false + val window = if (plan.platformId == "xiaohongshu") XIAOHONGSHU_RECHECK_WINDOW_MS else RECHECK_WINDOW_MS return receipts.size < plan.limit && video.videoKey == claim.videoKey && !hasSeen(claim.videoKey) && - !video.hasHandled(target) && armedAt > 0 && armedAt <= nowEpochMs && nowEpochMs - armedAt <= RECHECK_WINDOW_MS + !video.hasHandled(target) && armedAt > 0 && armedAt <= nowEpochMs && nowEpochMs - armedAt <= window } fun arm(comment: PendingComment): TaskCheckpoint { @@ -217,4 +218,6 @@ data class TaskCheckpoint( } } +internal const val XIAOHONGSHU_RECHECK_WINDOW_MS = 60 * 60 * 1_000L + private fun Outcome.isConfirmedReply(): Boolean = this == Outcome.SENT || this == Outcome.USER_CONFIRMED diff --git a/app/src/main/java/com/jieliu/app/task/TaskPlan.kt b/app/src/main/java/com/jieliu/app/task/TaskPlan.kt index 1d71eab..cc8adad 100644 --- a/app/src/main/java/com/jieliu/app/task/TaskPlan.kt +++ b/app/src/main/java/com/jieliu/app/task/TaskPlan.kt @@ -1,5 +1,6 @@ package com.jieliu.app.task +import com.jieliu.app.platform.XiaohongshuNoteKind import java.util.UUID enum class ReplyMode(val label: String) { @@ -42,11 +43,16 @@ data class TaskPlan( val contentTypes: List? = null, val selectedTypeId: String? = null, val repliesPerVideo: Int = 1, + val xiaohongshuNoteKind: XiaohongshuNoteKind = XiaohongshuNoteKind.ANY, + val xiaohongshuNoteKey: String? = null, ) { fun validate() { if (contentTypes == null) validateLegacy() else validateHierarchy(contentTypes) require(limit in 1..100) { "单次任务数量须为 1–100。" } require(repliesPerVideo in 1..MAX_REPLIES_PER_VIDEO) { "每条视频回复数量须为 1–$MAX_REPLIES_PER_VIDEO。" } + require(xiaohongshuNoteKey == null || xiaohongshuNoteKey.matches(Regex("[0-9a-f]{64}"))) { + "小红书目标笔记标识无效。" + } require(watchSeconds.first in 1..300 && watchSeconds.last in watchSeconds.first..300) { "观看区间须在 1–300 秒之间,且下限不大于上限。" } diff --git a/app/src/main/java/com/jieliu/app/task/TaskRunner.kt b/app/src/main/java/com/jieliu/app/task/TaskRunner.kt index 1f0aa98..3fd0bd3 100644 --- a/app/src/main/java/com/jieliu/app/task/TaskRunner.kt +++ b/app/src/main/java/com/jieliu/app/task/TaskRunner.kt @@ -4,6 +4,7 @@ import com.jieliu.app.platform.CommentPublishResult import com.jieliu.app.platform.CommentTarget import com.jieliu.app.platform.PlatformAdapter import com.jieliu.app.platform.PlatformException +import com.jieliu.app.platform.PlatformInteractionRestrictedException import com.jieliu.app.platform.PlatformRegistry import com.jieliu.app.platform.VideoContext import java.util.concurrent.CancellationException @@ -103,7 +104,7 @@ internal class TaskRunner( checkpoint = armed } val confirmation = if (result == CommentPublishResult.UNCERTAIN && checkpoint.canAutomaticallyRecheck()) { - confirmPending(checkpoint, inCurrentRun = true) + confirmPending(checkpoint, currentVideo = candidate) } else result check(confirmation == CommentPublishResult.CONFIRMED) { "请在目标应用里核对这条评论的发送结果。" } persist(checkpoint.recordReply(Outcome.SENT)) @@ -122,6 +123,10 @@ internal class TaskRunner( store.appendLog("任务完成 · 处理 ${checkpoint.receipts.size} 条 · 确认发送 ${checkpoint.sentCount} 条") } catch (error: Exception) { val message = when { + error is PlatformInteractionRestrictedException -> { + val suffix = if (checkpoint.pending == null) "任务已暂停。" else "已保留本次提交等待核对。" + "${error.message},$suffix" + } recheckPending && checkpoint.pending != null -> { if (cancelled() || error is CancellationException) "自动核对已暂停,发送结果仍待核对。" else "自动核对未确认,发送结果仍待核对。" @@ -140,26 +145,47 @@ internal class TaskRunner( } } - private fun confirmPending(checkpoint: TaskCheckpoint, inCurrentRun: Boolean = false): CommentPublishResult { + private fun confirmPending(checkpoint: TaskCheckpoint, currentVideo: VideoContext? = null): CommentPublishResult { check(checkpoint.canAutomaticallyRecheck()) { "这条回复的自动核对期限已过。" } val pending = checkNotNull(checkpoint.pending) val type = checkNotNull(checkpoint.contentType) requireRunning(cancelled) - if (inCurrentRun) { + if (currentVideo != null) { store.appendLog("本次任务继续核对已提交回复") + status("正在核对当前${contentUnit}下已发送的回复") + val local = try { + platform.confirmPendingReplyInPlace(currentVideo, pending) + } catch (_: PlatformException) { + store.appendLog("当前${contentUnit}评论区未能完成核对,重新定位原$contentUnit") + null + } + requireRunning(cancelled) + if (local == CommentPublishResult.CONFIRMED) return local } else { store.appendLog("开始自动核对一条待确认回复") status("正在打开目标应用") - platform.launch() + receiptPhase("打开目标应用") { platform.launch() } } status("正在定位待核对的$contentUnit") - val video = locateVideo(platform.search(type.name), checkpoint) + val video = receiptPhase("定位原$contentUnit") { locateVideo(platform.search(type.name), checkpoint) } requireRunning(cancelled) + store.appendLog("已重新定位待核对的原$contentUnit") status("正在打开待核对的${contentUnit}评论区") - platform.openComments(video) + receiptPhase("打开原${contentUnit}评论区") { platform.openCommentsForReceipt(video) } requireRunning(cancelled) + store.appendLog("已打开原${contentUnit}评论区,正在核对回复") status("正在核对已发送的回复") - return platform.confirmPendingReply(video, pending).also { requireRunning(cancelled) } + return receiptPhase("核对已发送的回复") { platform.confirmPendingReply(video, pending) } + .also { requireRunning(cancelled) } + } + + private inline fun receiptPhase(stage: String, action: () -> T): T = try { + action() + } catch (error: Exception) { + if (!cancelled() && error !is CancellationException) { + store.appendLog("自动核对在“$stage”阶段中断(${error.javaClass.simpleName})", warning = true) + } + throw error } private fun locateVideo(first: VideoContext, checkpoint: TaskCheckpoint): VideoContext { diff --git a/app/src/test/java/com/jieliu/app/platform/PublishedPhotoMatcherTest.kt b/app/src/test/java/com/jieliu/app/platform/PublishedPhotoMatcherTest.kt index 88e3846..dca4941 100644 --- a/app/src/test/java/com/jieliu/app/platform/PublishedPhotoMatcherTest.kt +++ b/app/src/test/java/com/jieliu/app/platform/PublishedPhotoMatcherTest.kt @@ -53,6 +53,22 @@ class PublishedPhotoMatcherTest { assertFalse(PublishedPhotoMatcher.matches(reference, recolored)) } + @Test fun recognizesXhsDraftToneShiftWithoutAcceptingDifferentSpatialContent() { + val reference = photo(144, 144) { x, y -> pattern(x, y) } + val shifted = photo(144, 144) { x, y -> + val pixel = pattern(x, y) + if (x > .7 && y < .3) 0 else rgb( + (((pixel ushr 16) and 255) * .83 + 39).toInt(), + (((pixel ushr 8) and 255) * .67 + 20).toInt(), + ((pixel and 255) * .80 + 7).toInt(), + ) + } + val different = photo(144, 144) { x, y -> pattern(1 - x, y) } + assertFalse(PublishedPhotoMatcher.matches(reference, shifted)) + assertTrue(PublishedPhotoMatcher.matchesXhsDraft(reference, shifted)) + assertFalse(PublishedPhotoMatcher.matchesXhsDraft(different, shifted)) + } + @Test fun rejectsMissingFlatTransparentAndTooSmallEvidence() { val solid = photo(64, 64) { _, _ -> rgb(127, 127, 127) } val transparent = photo(64, 64) { x, y -> pattern(x, y) and 0x00ffffff } diff --git a/app/src/test/java/com/jieliu/app/platform/XhsReceiptTimeTest.kt b/app/src/test/java/com/jieliu/app/platform/XhsReceiptTimeTest.kt index bd56c96..78b06aa 100644 --- a/app/src/test/java/com/jieliu/app/platform/XhsReceiptTimeTest.kt +++ b/app/src/test/java/com/jieliu/app/platform/XhsReceiptTimeTest.kt @@ -19,7 +19,8 @@ class XhsReceiptTimeTest { 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)) + assertTrue(matchesXhsReceiptTime("31分钟前", armedAt, armedAt + 31 * 60_000L)) + assertFalse(matchesXhsReceiptTime("61分钟前", armedAt, armedAt + 61 * 60_000L)) assertFalse(validXhsReceiptAge(0, armedAt)) } }