完善小红书评论匹配、多图回复和自动回执

- 按内容类型读取笔记评论并匹配关键词,从对应话术库随机轮换话术及绑定图片
- 核对原评论、完整正文和全部附件,记录提交意图后发送并核对同一条回复
- 更新配置预览和开发进度,离线构建及 51 项单测通过,真机联调待开展
This commit is contained in:
2026-11-26 14:55:57 +08:00
parent 110665d602
commit dffc9fc7b5
13 changed files with 1306 additions and 31 deletions
@@ -0,0 +1,15 @@
package com.jieliu.app.platform
import com.jieliu.app.data.PhotoLibrary
import com.jieliu.app.task.TemplatePhoto
internal fun PhotoLibrary.readReceiptPixels(photos: List<TemplatePhoto>): List<PhotoPixels>? = photos.map { photo ->
val bitmap = receiptThumbnail(photo) ?: return null
try {
val pixels = IntArray(bitmap.width * bitmap.height)
bitmap.getPixels(pixels, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)
PhotoPixels(bitmap.width, bitmap.height, pixels)
} finally {
bitmap.recycle()
}
}
@@ -46,7 +46,8 @@ interface PlatformAdapter {
object PlatformRegistry {
private val douyin = PlatformSpec("douyin", "抖音", "com.ss.android.ugc.aweme", true, supportsReplies = true)
private val xiaohongshu = PlatformSpec("xiaohongshu", "小红书", "com.xingin.xhs", true, contentUnit = "笔记")
private val xiaohongshu = PlatformSpec("xiaohongshu", "小红书", "com.xingin.xhs", true,
supportsReplies = true, contentUnit = "笔记")
val platforms: List<PlatformSpec> = listOf(
douyin,
@@ -65,7 +66,7 @@ object PlatformRegistry {
val ui = AccessibleUi(service, spec.packageName, cancelled, pauseBetweenActions)
return when (spec.id) {
douyin.id -> DouyinAdapter(spec, ui, PhotoLibrary(service))
xiaohongshu.id -> XiaohongshuAdapter(spec, ui)
xiaohongshu.id -> XiaohongshuAdapter(spec, ui, PhotoLibrary(service))
else -> throw PlatformException("${spec.label} 暂未接入")
}
}
@@ -2,6 +2,9 @@ package com.jieliu.app.platform
import android.graphics.Rect
import android.view.accessibility.AccessibilityNodeInfo
import com.jieliu.app.data.PhotoLibrary
import com.jieliu.app.task.PendingComment
import com.jieliu.app.task.TemplatePhoto
import java.io.Closeable
import java.security.MessageDigest
import kotlin.math.abs
@@ -9,12 +12,14 @@ import kotlin.math.abs
internal class XiaohongshuAdapter(
private val spec: PlatformSpec,
private val ui: AccessibleUi,
private val photoLibrary: PhotoLibrary,
) : PlatformAdapter {
private data class SearchHeader(val editor: UiNode, val submit: UiNode)
private data class ResultHeader(val query: UiNode, val tabs: UiNode)
private data class ResultList(val list: UiNode, val viewport: Rect)
private data class CardIdentity(val key: String, val title: String, val author: String)
private data class ResultCard(val action: UiNode, val identity: CardIdentity)
private data class PreparedReply(val target: CommentTarget, val text: String)
private data class NoteControls(
val author: UiNode,
val more: UiNode,
@@ -43,11 +48,17 @@ internal class XiaohongshuAdapter(
private var keyword: String? = null
private val examinedCards = mutableSetOf<String>()
private var activeNote: NoteBinding? = null
private var commentNote: VideoContext? = null
private var preparedReply: PreparedReply? = null
private val comments = XiaohongshuComments(ui, ::matchesNote, ::openNoteComments)
private val composer = XiaohongshuReplyComposer(ui, photoLibrary, comments)
private val receipt = XiaohongshuReplyReceipt(ui, photoLibrary, comments)
override fun launch() = ui.launchTarget(spec.label)
override fun search(keyword: String): VideoContext {
require(keyword.isNotBlank()) { "小红书搜索词不能为空" }
if (commentNote != null) closeComments()
this.keyword = null
examinedCards.clear()
resetNote()
@@ -84,7 +95,10 @@ internal class XiaohongshuAdapter(
if (results != null) return@awaitPage ui.click(results.query)
val entry = page.homeSearchEntry()
if (entry != null) return@awaitPage ui.click(entry)
if (page.noteControls() != null && page.nodes.none { it.editable && it.focused }) return@awaitPage ui.back()
comments.dismissVideoPanelForSearch(page)?.let { return@awaitPage it }
if (page.noteControls() != null && page.nodes.none { it.editable && (it.focused || it.hasDraft()) }) {
return@awaitPage ui.back()
}
null
}
if (!opened) throw PlatformException("小红书未确认已打开搜索框")
@@ -299,12 +313,17 @@ internal class XiaohongshuAdapter(
private fun UiPage.noteControls(): NoteControls? = imageNoteControls() ?: videoNoteControls()
private fun UiPage.imageNoteControls(): NoteControls? {
private fun UiPage.imageNoteHeader(): Pair<UiNode, UiNode>? {
val author = nodes.singleOrNull { it.resourceId == "nickNameTV" && it.isUneditableText() &&
it.bounds.centerY() <= y(.21f) } ?: return null
val more = nodes.singleOrNull { it.resourceId == "moreOperateIV" && it.className == "android.widget.ImageView" &&
it.bounds.centerX() >= x(.82f) && it.bounds.centerY() <= y(.21f) && it.isNativeClick() } ?: return null
if (author.bounds.top >= more.bounds.bottom || author.bounds.bottom <= more.bounds.top) return null
return author to more
}
private fun UiPage.imageNoteControls(): NoteControls? {
val (author, more) = imageNoteHeader() ?: return null
val prompt = nodes.singleOrNull { it.description == "评论框" && it.className == "android.widget.TextView" &&
it.bounds.centerY() >= y(.76f) && it.bounds.centerX() <= x(.49f) && it.isNativeClick() } ?: return null
val toolbar = prompt.directParent()?.takeIf { it.className == "android.view.ViewGroup" } ?: return null
@@ -372,13 +391,111 @@ internal class XiaohongshuAdapter(
activeNote = null
}
override fun openComments(expected: VideoContext): List<String> =
throw PlatformException("小红书评论区暂未开放")
private fun matchesNote(page: UiPage, expected: VideoContext): Boolean {
val note = activeNote?.takeIf { it.video.key == expected.key && it.windowId == page.windowId } ?: return false
if (page.boundNote(note) != null) return true
val (author, more) = page.imageNoteHeader() ?: return false
return author.text == note.author && author.hasSource(note.authorSource) && more.hasSource(note.moreSource)
}
private fun openNoteComments(page: UiPage, expected: VideoContext): Boolean {
val note = activeNote?.takeIf { it.video.key == expected.key } ?: return false
val controls = page.boundNote(note) ?: return false
if (page.nodes.any { it.editable && (it.focused || it.hasDraft()) }) return false
val button = page.nodes.singleOrNull { node ->
node.directParent() === controls.toolbar && node.className == "android.widget.Button" &&
commentLabel.matches(node.description) && node.isNativeClick()
} ?: return false
return ui.click(button)
}
override fun openComments(expected: VideoContext): List<String> {
if (commentNote != null || currentVideo().key != expected.key) {
throw PlatformException("小红书当前笔记或评论区已变化")
}
preparedReply = null
return try {
comments.open(expected).also { commentNote = expected }
} catch (error: Exception) {
comments.reset()
throw error
}
}
override fun scanComments(): List<CommentTarget> = comments.scan()
override fun scrollComments(): Boolean {
if (preparedReply != null) throw PlatformException("请先完成或关闭当前小红书回复草稿")
return comments.scroll()
}
override fun prepareReply(target: CommentTarget, expectedText: String): Boolean {
check(commentNote != null && preparedReply == null) { "请先确认小红书评论区和草稿状态" }
if (!receipt.captureBaseline(target, expectedText) || !composer.prepare(target)) return false
preparedReply = PreparedReply(target, expectedText)
return true
}
override fun hasPreparedReplyBaseline(targetKey: String, text: String): Boolean =
preparedReply?.let { it.target.key == targetKey && it.text == text } == true
override fun publishComment(text: String, beforeClick: () -> Unit): CommentPublishResult =
throw PlatformException("小红书暂未开放自动回复")
publishPrepared(text, emptyList(), beforeClick)
override fun closeComments() = Unit
override fun publishPhotoComment(
text: String,
photos: List<TemplatePhoto>,
beforeClick: () -> Unit,
): CommentPublishResult = publishPrepared(text, photos, beforeClick)
private fun publishPrepared(
text: String,
photos: List<TemplatePhoto>,
beforeClick: () -> Unit,
): CommentPublishResult {
val reply = preparedReply?.takeIf { it.text == text }
?: throw PlatformException("小红书原评论或回复话术已变化,未触发发送")
var armedAt: Long? = null
try {
val clicked = composer.submit(reply.target, text, photos) {
check(armedAt == null) { "小红书回复已记录提交意图" }
beforeClick()
armedAt = System.currentTimeMillis()
}
val since = armedAt ?: throw PlatformException("小红书未能记录回复提交意图")
if (!clicked || !composer.closedAfterSubmit()) return CommentPublishResult.UNCERTAIN
return confirmReceipt(reply.target.key, reply.target.author, text, photos, since)
} finally {
composer.close()
preparedReply = null
}
}
override fun confirmPendingReply(video: VideoContext, pending: PendingComment): CommentPublishResult {
if (video.key != commentNote?.key || video.key != pending.videoKey) return CommentPublishResult.UNCERTAIN
val target = pending.targetKey ?: return CommentPublishResult.UNCERTAIN
val author = pending.targetAuthor ?: return CommentPublishResult.UNCERTAIN
val since = pending.armedAtEpochMs ?: return CommentPublishResult.UNCERTAIN
return confirmReceipt(target, author, pending.text, pending.photos, since)
}
private fun confirmReceipt(
targetKey: String,
author: String,
text: String,
photos: List<TemplatePhoto>,
armedAt: Long,
): CommentPublishResult = receipt.confirm(targetKey, author, text, photos, armedAt).also { result ->
if (result == CommentPublishResult.CONFIRMED && photos.isNotEmpty()) photoLibrary.cleanupStaged()
}
override fun closeComments() {
if (commentNote == null) return
comments.close()
composer.close()
preparedReply = null
commentNote = null
}
private fun UiNode.isNativeClick(): Boolean = enabled && supports(AccessibilityNodeInfo.ACTION_CLICK)
@@ -0,0 +1,419 @@
package com.jieliu.app.platform
import android.graphics.Rect
import android.view.accessibility.AccessibilityNodeInfo
import java.io.Closeable
import java.security.MessageDigest
import kotlin.math.abs
internal data class XhsCommentSurface(
val root: UiNode,
val viewport: Rect,
val windowId: Int,
val heading: UiNode?,
val inline: Boolean,
val empty: Boolean,
)
internal data class XhsCommentRow(
val target: CommentTarget,
val container: UiNode,
val reply: UiNode?,
val author: UiNode,
val body: UiNode,
)
internal data class XhsCommentThread(val replies: List<XhsReplyRow>, val complete: Boolean, val expand: UiNode?)
internal data class XhsReplyRow(
val body: UiNode,
val own: Boolean,
val photos: List<UiNode>,
val timeLabel: String?,
val identity: String,
)
internal class XiaohongshuComments(
private val ui: AccessibleUi,
private val matchesNote: (UiPage, VideoContext) -> Boolean,
private val openVideoComments: (UiPage, VideoContext) -> Boolean,
) {
private data class Origin(val windowId: Int, val inline: Boolean)
private class Session(
val note: VideoContext,
val inline: Boolean,
val windowId: Int,
val root: UiNodeSource,
val heading: UiNodeSource?,
) : Closeable {
override fun close() {
root.close()
heading?.close()
}
}
private data class RowParts(val author: UiNode, val body: UiNode, val nextTop: Int)
private data class Continuation(val blocking: Boolean, val action: UiNode?)
private var active: Session? = null
fun open(expected: VideoContext): List<String> {
if (active != null) throw PlatformException("小红书评论区仍处于打开状态")
val origin = ui.inspect { page ->
if (!matchesNote(page, expected)) return@inspect null
val image = page.nodes.any { it.resourceId == "nickNameTV" }
val video = page.nodes.any { it.resourceId == "matrixNickNameView" }
if (image == video) return@inspect null
Origin(page.windowId, inline = image)
} ?: throw PlatformException("小红书当前笔记无法核对,未打开评论区")
val initial = ui.inspect { page ->
if (!origin.inline || page.windowId != origin.windowId || !matchesNote(page, expected)) return@inspect null
page.initialSurface(inline = true)?.let { retainSession(expected, it) }
}
if (initial != null) {
active = initial
return scan().map(CommentTarget::text)
}
ui.pace()
val opened = ui.inspect { page -> page.windowId == origin.windowId && matchesNote(page, expected) &&
!page.hasActiveDraft() && openVideoComments(page, expected) }
if (opened != true) throw PlatformException("小红书未确认打开本条笔记的评论区")
val session = ui.await(7_000) {
ui.inspect { page ->
if (origin.inline) {
if (page.windowId != origin.windowId || !matchesNote(page, expected)) return@inspect null
} else if (page.windowId == origin.windowId || matchesNote(page, expected)) {
return@inspect null
}
val surface = page.initialSurface(origin.inline) ?: return@inspect null
retainSession(expected, surface)
}
} ?: throw PlatformException("小红书未显示可核对的评论列表")
active = session
return scan().map(CommentTarget::text)
}
fun scan(): List<CommentTarget> = ui.await(3_000) {
ui.inspect { page ->
val visible = surface(page) ?: return@inspect null
originalRows(page, visible).filter { it.reply != null }.map(XhsCommentRow::target)
}
} ?: throw PlatformException("小红书评论区已变化,无法读取评论")
fun scroll(): Boolean {
ui.pace()
val before = ui.inspect { page ->
val visible = surface(page)?.takeUnless { it.empty } ?: return@inspect null
if (!visible.root.scrollable || page.hasActiveDraft() ||
visible.viewport.height() < page.bounds.height() * .15f) return@inspect null
val anchors = page.commentPositions(visible)
anchors.takeIf { ui.scrollUpInside(visible.viewport) }
} ?: return false
var previous: Map<String, Int>? = null
var moved = false
ui.await(2_500) {
ui.inspect { page ->
val visible = surface(page) ?: return@inspect null
val after = page.commentPositions(visible)
if (after.isEmpty()) return@inspect null
moved = moved || before.keys != after.keys || after.any { (key, y) -> abs((before[key] ?: y) - y) >= 5 }
val preceding = previous
previous = after
true.takeIf { moved && preceding != null && preceding.keys == after.keys &&
after.all { (key, y) -> abs((preceding[key] ?: y) - y) <= 2 } }
}
}
return moved
}
fun close() {
val session = active ?: return
if (session.inline) {
if (ui.inspect { page -> matchesNote(page, session.note) && !page.hasActiveDraft() } != true) {
throw PlatformException("小红书原笔记或评论草稿状态已变化")
}
} else {
ui.pace()
val closed = ui.inspect { page ->
if (matchesNote(page, session.note) && !page.hasActiveDraft()) return@inspect true
val visible = surface(page) ?: return@inspect false
if (page.hasActiveDraft()) return@inspect false
val close = page.modalCloseControl(visible)
if (close != null) ui.click(close) else ui.back()
}
if (closed != true || ui.await(4_000) {
ui.inspect { page -> true.takeIf { matchesNote(page, session.note) && !page.hasActiveDraft() } }
} != true) {
throw PlatformException("关闭小红书评论区后未能核对原笔记")
}
}
reset()
}
fun reset() {
active?.close()
active = null
}
fun dismissVideoPanelForSearch(page: UiPage): Boolean? {
if (active != null || page.hasActiveDraft() || page.nodes.any { it.resourceId in noteMarkers }) return null
val panel = page.initialSurface(inline = false) ?: return null
val close = page.modalCloseControl(panel) ?: return null
return ui.click(close)
}
fun surface(page: UiPage): XhsCommentSurface? {
val session = active ?: return null
if (page.windowId != session.windowId || (session.inline && !matchesNote(page, session.note))) return null
val list = page.nodes.singleOrNull { it.hasSource(session.root) } ?: return null
val heading = page.commentHeading()?.takeIf { label -> session.heading?.let(label::hasSource) == true }
if (heading != null && list === heading && XhsCommentLabels.commentCount(heading.text) == 0) {
return XhsCommentSurface(list, Rect(list.bounds), page.windowId, heading, session.inline, empty = true)
}
if (!session.inline && heading == null) return null
val footer = if (page.nodes.any { it.editable && it.focused }) page.focusedCommentFooter(list, heading)
else page.commentFooter(session.inline)
return footer?.let { page.surfaceFor(list, heading, session.inline, it) }
}
fun row(page: UiPage, targetKey: String): XhsCommentRow? {
val visible = surface(page) ?: return null
return originalRows(page, visible).singleOrNull { it.target.key == targetKey }
}
fun thread(page: UiPage, parent: XhsCommentRow): XhsCommentThread? {
val visible = surface(page) ?: return null
val current = originalRows(page, visible).singleOrNull { it.target == parent.target && it.container === parent.container }
?: return null
val slots = page.commentSlots(visible)
val start = slots.indexOf(current.container).takeIf { it >= 0 } ?: return null
val replies = mutableListOf<XhsReplyRow>()
val inlineReplies = page.nestedRows(visible, current.container, parent.target.key, current.body.bounds.bottom)
?: return XhsCommentThread(replies, complete = false, expand = null)
replies.addAll(inlineReplies)
val inside = page.continuation(visible, current.container, current.body.bounds.bottom)
if (inside.blocking) return XhsCommentThread(replies, complete = false, expand = inside.action)
var bottom = current.container.bounds.bottom
for (slot in slots.drop(start + 1)) {
val gap = slot.bounds.top - bottom
if (gap < -2 || gap > visible.viewport.width() * .04f || slot.bounds.top >= visible.viewport.bottom) break
if (page.parts(visible, slot, nested = false).size == 1) {
return XhsCommentThread(replies, complete = true, expand = null)
}
val more = page.continuation(visible, slot, slot.bounds.top)
if (more.blocking) return XhsCommentThread(replies, complete = false, expand = more.action)
val nested = page.nestedRows(visible, slot, current.target.key, slot.bounds.top)
if (nested.isNullOrEmpty()) {
val terminal = page.nodes.any { (it === slot || it.isDescendantOf(slot)) && it.text == "没有更多评论了" }
return XhsCommentThread(replies, complete = terminal, expand = null)
}
replies.addAll(nested)
bottom = slot.bounds.bottom
}
return XhsCommentThread(replies, complete = slots.lastOrNull()?.bounds?.bottom == bottom &&
bottom < visible.viewport.bottom - 2 && !visible.root.scrollable &&
!visible.root.supports(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD),
expand = null)
}
private fun UiPage.initialSurface(inline: Boolean): XhsCommentSurface? {
val heading = commentHeading() ?: return null
val footer = commentFooter(inline) ?: return null
if (heading.bounds.bottom >= footer.bounds.top) return null
val list = nodes.singleOrNull { node ->
node.className == RECYCLER && node.bounds.width() >= bounds.width() * .84f &&
node.bounds.height() >= bounds.height() * .14f && node.bounds.bottom > heading.bounds.bottom &&
node.bounds.bottom <= footer.bounds.bottom && if (inline) heading.isDescendantOf(node) else
(heading.isDescendantOf(node) || node.bounds.top >= heading.bounds.top &&
shareNearParent(heading, node, maxDepth = 4))
}
if (list == null && XhsCommentLabels.commentCount(heading.text) == 0) {
return XhsCommentSurface(heading, Rect(heading.bounds), windowId, heading, inline, empty = true)
}
return list?.let { surfaceFor(it, heading, inline, footer) }
}
private fun retainSession(note: VideoContext, surface: XhsCommentSurface): Session = Session(note,
surface.inline, surface.windowId, surface.root.retainSource(), surface.heading?.retainSource())
private fun UiPage.surfaceFor(list: UiNode, heading: UiNode?, inline: Boolean, footer: UiNode): XhsCommentSurface? {
val viewport = Rect(list.bounds)
if (!viewport.intersect(bounds)) return null
if (heading != null) viewport.top = maxOf(viewport.top, heading.bounds.bottom)
viewport.bottom = minOf(viewport.bottom, footer.bounds.top)
if (viewport.isEmpty) return null
return XhsCommentSurface(list, viewport, windowId, heading, inline,
empty = heading?.let { XhsCommentLabels.commentCount(it.text) } == 0)
}
private fun UiPage.commentHeading(): UiNode? = nodes.singleOrNull { node ->
node.commentText() && XhsCommentLabels.commentCount(node.text) != null &&
node.bounds.centerX() <= x(.67f) && node.bounds.centerY() <= y(.72f)
}
private fun UiPage.commentFooter(inline: Boolean): UiNode? = nodes.singleOrNull { node ->
!node.editable && node.bounds.centerX() <= x(.57f) && node.bounds.centerY() >= y(.72f) &&
(node.description == "评论框" || !inline && node.text in commentPlaceholders) &&
node.className in setOf("android.widget.TextView", "android.widget.Button", "android.view.ViewGroup")
}
private fun UiPage.focusedCommentFooter(list: UiNode, heading: UiNode?): UiNode? {
val editor = nodes.singleOrNull { it.editable && it.focused } ?: return null
return editor.takeIf { node ->
node.className == "android.widget.EditText" && node.enabled &&
node.supports(AccessibilityNodeInfo.ACTION_SET_TEXT) && node.bounds.width() >= bounds.width() * .38f &&
node.bounds.centerY() >= y(.55f) && node.bounds.top > (heading?.bounds?.bottom ?: list.bounds.top) &&
node.bounds.centerX() in list.bounds.left until list.bounds.right &&
bounds.contains(node.bounds) && shareNearParent(node, list, maxDepth = 6)
}
}
private fun UiPage.modalCloseControl(surface: XhsCommentSurface): UiNode? {
val heading = surface.heading ?: return null
return nodes.singleOrNull { node ->
node.isNativeClick() && node.labels().singleOrNull() in closeLabels && node.bounds.centerX() >= x(.75f) &&
abs(node.bounds.centerY() - heading.bounds.centerY()) <= heading.bounds.height() &&
shareNearParent(heading, node, maxDepth = 3)
}
}
private fun UiPage.hasActiveDraft(): Boolean = nodes.any { it.editable && (it.focused || it.hasDraft()) }
private fun UiPage.commentSlots(surface: XhsCommentSurface): List<UiNode> =
nodes.filter { it.directParent() === surface.root && Rect.intersects(it.bounds, surface.viewport) }
.sortedBy { it.bounds.top }
private fun originalRows(page: UiPage, visible: XhsCommentSurface): List<XhsCommentRow> {
val note = active?.note ?: return emptyList()
if (visible.empty) return emptyList()
val candidates = page.commentSlots(visible).mapNotNull { slot ->
val original = page.parts(visible, slot, nested = false).singleOrNull() ?: return@mapNotNull null
if (page.isOwn(original)) return@mapNotNull null
val author = original.author
val body = original.body
val reply = page.nodes.singleOrNull { node ->
node.isDescendantOf(slot) && node.isNativeClick() &&
node.className in replyControlClasses && node.labels().singleOrNull() == "回复" &&
node.bounds.top >= body.bounds.bottom && node.bounds.bottom <= original.nextTop &&
node.bounds.left >= author.bounds.left && visible.viewport.contains(node.bounds)
}
val target = CommentTarget(identity(note.key, author.text, body.text), body.text, author.text)
XhsCommentRow(target, slot, reply, author, body)
}
val counts = candidates.groupingBy { it.target.key }.eachCount()
return candidates.filter { counts[it.target.key] == 1 }
}
private fun UiPage.parts(surface: XhsCommentSurface, slot: UiNode, nested: Boolean): List<RowParts> {
val width = surface.viewport.width()
val avatars = nodes.filter { node -> node.isDescendantOf(slot) && node.isNativeClick() &&
node.className == "android.widget.ImageView" && node.bounds.width() in (width * .035f).toInt()..(width * .14f).toInt() &&
abs(node.bounds.width() - node.bounds.height()) <= width * .025f &&
node.bounds.centerY() in surface.viewport.top until surface.viewport.bottom &&
node.bounds.centerX() in (surface.viewport.left + width * .07f).toInt()..(surface.viewport.left + width * .34f).toInt() }
.sortedBy { it.bounds.top }
return avatars.mapIndexedNotNull { index, avatar ->
val isNested = avatar.bounds.centerX() >= surface.viewport.left + width * .18f
if (isNested != nested) return@mapIndexedNotNull null
val nextTop = avatars.drop(index + 1).firstOrNull { it.bounds.top > avatar.bounds.top + 2 }?.bounds?.top
?: slot.bounds.bottom
val author = nodes.singleOrNull { node ->
node.isDescendantOf(slot) && node.commentText() && node.isNativeClick() &&
abs(node.bounds.top - avatar.bounds.top) <= avatar.bounds.height() / 3 &&
node.bounds.left in avatar.bounds.right..(avatar.bounds.right + (width * .10f).toInt()) &&
surface.viewport.contains(node.bounds)
} ?: return@mapIndexedNotNull null
val body = nodes.singleOrNull { node ->
node.isDescendantOf(slot) && node.commentText() && !node.clickable &&
abs(node.bounds.left - author.bounds.left) <= width * .025f && node.bounds.width() >= width * .48f &&
node.bounds.top in (author.bounds.bottom - 2)..(author.bounds.bottom + (width * .05f).toInt()) &&
node.bounds.bottom <= nextTop && surface.viewport.contains(node.bounds)
} ?: return@mapIndexedNotNull null
RowParts(author, body, nextTop)
}
}
private fun UiPage.isOwn(parts: RowParts): Boolean {
val meta = parts.author.directParent() ?: return false
return nodes.count { node -> node !== parts.author && node.directParent() === meta && !node.clickable &&
node.commentText() && node.labels().singleOrNull() in ownLabels && node.bounds.left >= parts.author.bounds.right &&
abs(node.bounds.centerY() - parts.author.bounds.centerY()) <= parts.author.bounds.height() / 2 } == 1
}
private fun UiPage.nestedRows(surface: XhsCommentSurface, slot: UiNode, parentKey: String, after: Int): List<XhsReplyRow>? {
val candidates = parts(surface, slot, nested = true).filter { it.author.bounds.top >= after }
val unexplained = nodes.any { node -> node.isDescendantOf(slot) && node.className == "android.widget.ImageView" &&
node.isNativeClick() && node.bounds.top >= after && node.bounds.centerX() in
(surface.viewport.left + surface.viewport.width() * .18f).toInt()..(surface.viewport.left + surface.viewport.width() * .34f).toInt() &&
node.bounds.width() in (surface.viewport.width() * .035f).toInt()..(surface.viewport.width() * .14f).toInt() &&
abs(node.bounds.width() - node.bounds.height()) <= surface.viewport.width() * .025f &&
candidates.none { abs(it.author.bounds.top - node.bounds.top) <= node.bounds.height() / 3 } }
if (unexplained) return null
return candidates.map { parts ->
val detail = nodes.filter { node -> node.isDescendantOf(slot) && node.bounds.top >= parts.body.bounds.bottom &&
node.bounds.bottom <= parts.nextTop && node.bounds.left >= parts.body.bounds.left - 2 }
val time = detail.filter { it.commentText() }.mapNotNull { XhsCommentLabels.relativeTime(it.text) }.distinct().singleOrNull()
val images = detail.filter { it.className in attachmentClasses &&
it.bounds.width() >= surface.viewport.width() * .105f && it.bounds.height() >= surface.viewport.width() * .09f }
if (images.any { !it.isNativeClick() || !XhsCommentLabels.photoDescription(it.description) ||
!surface.viewport.contains(it.bounds) }) return null
if (images.indices.any { i -> images.take(i).any { Rect.intersects(it.bounds, images[i].bounds) } }) return null
val own = isOwn(parts)
XhsReplyRow(parts.body, own, images.sortedWith(compareBy({ it.bounds.top }, { it.bounds.left })), time,
identity(parentKey, parts.author.text, parts.body.text, images.size.toString()))
}
}
private fun UiPage.continuation(surface: XhsCommentSurface, slot: UiNode, after: Int): Continuation {
val labels = nodes.filter { node -> (node === slot || node.isDescendantOf(slot)) && node.bounds.top >= after &&
node.labels().any(XhsCommentLabels::blocksThreadBoundary) }
val unique = labels.singleOrNull()
val action = unique?.takeIf { node -> node.isNativeClick() && node.className in replyControlClasses &&
surface.viewport.contains(node.bounds) && XhsCommentLabels.expandsReplies(node.labels().singleOrNull().orEmpty()) }
return Continuation(labels.isNotEmpty(), action)
}
private fun UiPage.commentPositions(surface: XhsCommentSurface): Map<String, Int> = nodes.asSequence()
.filter { it.isDescendantOf(surface.root) && it.commentText() && it.bounds.width() >= surface.viewport.width() * .35f &&
surface.viewport.contains(it.bounds.centerX(), it.bounds.centerY()) }
.groupBy { it.text }.mapNotNull { (body, hits) -> hits.singleOrNull()?.let { identity(body) to it.bounds.top } }.toMap()
private fun shareNearParent(first: UiNode, second: UiNode, maxDepth: Int): Boolean =
generateSequence(first.directParent(), UiNode::directParent).take(maxDepth).any { second.isDescendantOf(it) }
private fun UiNode.commentText(): Boolean = className == "android.widget.TextView" && !editable && text.isNotBlank()
private fun UiNode.isNativeClick(): Boolean = enabled && supports(AccessibilityNodeInfo.ACTION_CLICK)
private fun identity(vararg values: String): String = MessageDigest.getInstance("SHA-256")
.digest(values.joinToString("\u0000").toByteArray(Charsets.UTF_8)).joinToString("") { "%02x".format(it) }
private companion object {
const val RECYCLER = "androidx.recyclerview.widget.RecyclerView"
val noteMarkers = setOf("nickNameTV", "moreOperateIV", "matrixNickNameView", "noteContentText")
val commentPlaceholders = setOf("说点什么...", "说点什么…")
val closeLabels = setOf("关闭", "关闭评论", "关闭评论区")
val ownLabels = setOf("我", "我发布的评论", "我发布的回复")
val replyControlClasses = setOf("android.widget.TextView", "android.widget.Button")
val attachmentClasses = setOf("android.widget.ImageView", "android.view.View")
}
}
internal object XhsCommentLabels {
private val heading = Regex("共\\s*(\\d+)\\s*条评论")
private val empty = setOf("暂无评论", "还没有评论")
private val relativeTime = Regex("^(刚刚|[1-9][0-9]?\\s*分钟前|(?:[1-5][0-9]|[1-9])\\s*秒前)(?:\\s|$)")
private val expand = Regex("(?:展开|查看)\\s*[1-9][0-9]*\\s*条回复|展开更多回复")
private val unknown = Regex("(?:展开|查看).{0,16}(?:回复|更多)")
private val photo = Regex("(?:查看)?图片(?:\\s*[1-9][0-9]*)?")
fun commentCount(text: String): Int? = if (text in empty) 0 else heading.matchEntire(text)?.groupValues?.get(1)?.toIntOrNull()
fun relativeTime(text: String): String? = relativeTime.find(text)?.groupValues?.get(1)
fun expandsReplies(label: String): Boolean = expand.matches(label)
fun blocksThreadBoundary(label: String): Boolean = expandsReplies(label) || unknown.matches(label)
fun photoDescription(label: String): Boolean = photo.matches(label)
}
@@ -0,0 +1,397 @@
package com.jieliu.app.platform
import android.graphics.Rect
import android.view.accessibility.AccessibilityNodeInfo
import com.jieliu.app.data.PhotoLibrary
import com.jieliu.app.task.TaskPlan
import com.jieliu.app.task.TemplatePhoto
import java.io.Closeable
/** The XHS reply and picker anchors still require device verification. */
internal class XiaohongshuReplyComposer(
private val ui: AccessibleUi,
private val photos: PhotoLibrary,
private val comments: XiaohongshuComments,
) : Closeable {
private class Prepared(
val target: CommentTarget,
val windowId: Int,
val surface: UiNodeSource,
val container: UiNodeSource,
val editor: UiNodeSource,
) : Closeable {
var claimed = false
var sendAttempted = false
override fun close() {
editor.close()
container.close()
surface.close()
}
}
private data class Composer(val editor: UiNode, val container: UiNode)
private data class AlbumTile(val image: UiNode, val select: UiNode, val ordinal: Int)
private data class Picker(val tiles: List<AlbumTile>, val done: UiNode, val count: Int)
private data class PickerSnapshot(val windowId: Int, val images: List<Rect>)
private data class DraftSnapshot(val windowId: Int, val images: List<Rect>)
private data class ReadyDraft(val send: UiNode, val snapshot: DraftSnapshot)
private var prepared: Prepared? = null
/** False leaves the current comments list untouched so the caller can scan another row. */
fun prepare(target: CommentTarget): Boolean {
close()
ui.pace()
val opened = ui.inspect { page ->
val surface = comments.surface(page) ?: throw PlatformException("小红书评论区已变化")
val row = comments.row(page, target.key)?.takeIf { it.target == target } ?: return@inspect null
val reply = row.reply?.takeIf {
it.isDescendantOf(row.container) && row.container.bounds.contains(it.bounds) &&
surface.viewport.contains(it.bounds) && it.nativeClick()
} ?: return@inspect null
if (page.hasPrivateDraft() || page.nodes.any { it.editable && (it.focused || it.hasReplyPrompt()) }) {
throw PlatformException("小红书评论区已有草稿、附件或打开的回复框,请处理后继续")
}
val anchor = surface.root.retainSource()
try {
if (!ui.click(reply)) throw PlatformException("未确认小红书已打开选中评论的回复框")
surface.windowId to anchor
} catch (error: Throwable) {
anchor.close()
throw error
}
} ?: return false
val (windowId, anchor) = opened
try {
prepared = awaitPage(5_000, "无法核对小红书回复对象或空白回复框") { page ->
if (!page.matchesTarget(target, windowId, anchor)) return@awaitPage null
val composer = page.openedComposer(target) ?: return@awaitPage null
val thumbnails = page.draftThumbnails(composer) ?: return@awaitPage null
if (composer.editor.hasDraft() || thumbnails.isNotEmpty()) {
throw PlatformException("小红书回复框已有草稿或附件,请处理后继续")
}
if (!composer.editor.isStillBlankAndFocused()) return@awaitPage null
Prepared(target, windowId, anchor, composer.container.retainSource(), composer.editor.retainSource())
}
return true
} finally {
if (prepared == null) anchor.close()
}
}
/** Returns whether the one native send action was accepted. Publication still requires a receipt. */
fun submit(target: CommentTarget, text: String, attachments: List<TemplatePhoto>, beforeClick: () -> Unit): Boolean {
val session = prepared?.takeIf { it.target == target && !it.claimed }
?: throw PlatformException("尚未核对小红书的回复对象")
require(text.isNotBlank() && attachments.size <= TaskPlan.MAX_TEMPLATE_PHOTOS)
session.claimed = true
ui.pace()
val blank = ui.inspect { page ->
val composer = page.checkedComposer(session) ?: return@inspect false
composer.editor.isStillBlankAndFocused() && page.draftThumbnails(composer)?.isEmpty() == true
} == true
if (!blank) throw PlatformException("小红书回复框已变化或已有草稿,未修改内容")
val references = if (attachments.isEmpty()) emptyList() else {
photos.readReceiptPixels(attachments) ?: throw PlatformException("无法读取小红书回复的绑定图片")
}
val staged = if (references.isEmpty()) null else {
photos.cleanupStaged()
photos.stage(attachments)
}
var broughtIntoDraft = false
try {
if (staged != null) attach(session, staged.albumName, references) { broughtIntoDraft = true }
val written = ui.inspect { page ->
val composer = page.checkedComposer(session) ?: return@inspect false
if (page.draftThumbnails(composer)?.size != references.size) return@inspect false
ui.setText(composer.editor, text, requireBlankFocusedInput = true)
} == true
if (!written) throw PlatformException("小红书回复框没有接受完整文本")
ui.pace()
val ready = awaitPage(5_000, "小红书未回读到完整回复、附件和唯一发送按钮") { page ->
page.readyDraft(session, text, references.size)?.snapshot
}
if (references.isNotEmpty()) {
verifyPhotos(references, ready.windowId, ready.images, "小红书回复草稿的图片与绑定图片不符")
}
val current = ui.inspect { page -> page.readyDraft(session, text, references.size)?.snapshot } == ready
if (!current) throw PlatformException("小红书回复框或图片已变化,未触发发送")
beforeClick()
return ui.inspect { page ->
val draft = page.readyDraft(session, text, references.size)?.takeIf { it.snapshot == ready } ?: return@inspect false
session.sendAttempted = true
ui.click(draft.send)
} == true
} finally {
if (staged != null) {
if (broughtIntoDraft) photos.leaveStagedForReview(staged) else photos.removeStaged(staged)
}
}
}
/** Checks dismissal only. An image or text receipt is evaluated separately by the comment adapter. */
fun closedAfterSubmit(): Boolean {
val session = prepared?.takeIf { it.sendAttempted } ?: return false
return ui.await(3_000) {
ui.inspect { page ->
if (!page.matchesTarget(session.target, session.windowId, session.surface)) return@inspect null
if (page.hasPrivateDraft() || page.nodes.any { it.editable && (it.focused || it.hasReplyPrompt()) }) return@inspect null
val oldContainer = page.nodes.singleOrNull { it.hasSource(session.container) }
val oldEditor = page.nodes.singleOrNull { it.hasSource(session.editor) }
if (page.nodes.any { node -> node.replyCue(session.target) ||
(oldContainer != null && node.isDescendantOf(oldContainer) && node.hasReplyPrompt()) }) return@inspect null
if ((oldContainer == null) != (oldEditor == null)) return@inspect null
if (oldContainer != null && oldEditor != null) {
if (page.draftThumbnails(Composer(oldEditor, oldContainer))?.isEmpty() != true) return@inspect null
}
true
}
} == true
}
override fun close() {
prepared?.close()
prepared = null
}
private fun attach(session: Prepared, album: String, references: List<PhotoPixels>, beforeAttach: () -> Unit) {
ui.pace()
val pickerOpened = ui.inspect { page ->
val composer = page.checkedComposer(session) ?: return@inspect false
if (!composer.editor.isStillBlankAndFocused() || page.draftThumbnails(composer)?.isEmpty() != true) return@inspect false
val action = page.composerActions(composer, imageActions).singleOrNull() ?: return@inspect false
ui.click(action)
} == true
if (!pickerOpened) throw PlatformException("小红书未打开已核对回复框的相册")
val openAlbumList = awaitPage(6_000, "小红书相册页或相册分类控件不可核对") { page ->
if (page.albumHeading(setOf(album)) != null) return@awaitPage false
val heading = page.albumHeading(pickerHeadings) ?: return@awaitPage null
val toggle = heading.nativeAction() ?: return@awaitPage null
if (!ui.click(toggle)) throw PlatformException("小红书未接受相册分类操作")
true
}
if (openAlbumList) {
awaitPage(6_000, "小红书相册没有唯一的本次专用相册") { page ->
val label = page.nodes.singleOrNull {
!it.editable && it.hasExactLabel(album) && it.bounds.centerY() > page.y(.14f)
} ?: return@awaitPage null
val item = label.nativeAction() ?: return@awaitPage null
if (!ui.click(item)) throw PlatformException("小红书未打开本次专用相册")
true
}
}
val empty = awaitPage(6_000, "小红书专用相册未完整显示所有可多选图片") { page ->
val picker = page.picker(album, references.size) ?: return@awaitPage null
if (picker.count != 0 || picker.tiles.any { it.ordinal != 0 }) {
throw PlatformException("小红书相册已有选中图片,未修改选择")
}
picker.snapshot(page.windowId)
}
val crops = ui.screenshotPhotos(empty.windowId, empty.images)
?.takeIf { it.size == references.size } ?: throw PlatformException("无法核对小红书专用相册的全部缩略图")
val order = references.map { reference ->
crops.indices.singleOrNull { PublishedPhotoMatcher.matches(reference, crops[it]) }
?: throw PlatformException("小红书专用相册中的图片无法唯一对应本次附件")
}
if (order.toSet().size != references.size) throw PlatformException("小红书专用相册出现重复图片匹配")
val selected = MutableList(references.size) { 0 }
for ((index, tileIndex) in order.withIndex()) {
ui.pace()
val accepted = ui.inspect { page ->
val picker = page.picker(album, references.size) ?: return@inspect false
if (!picker.matches(empty, page.windowId, selected, index)) return@inspect false
ui.click(picker.tiles[tileIndex].select)
} == true
if (!accepted) throw PlatformException("小红书专用相册未接受第 ${index + 1} 张图片")
selected[tileIndex] = index + 1
awaitPage(4_000, "小红书未核对第 ${index + 1} 张附件的选中顺序") { page ->
true.takeIf { page.picker(album, references.size)?.matches(empty, page.windowId, selected, index + 1) == true }
}
}
ui.pace()
val returned = ui.inspect { page ->
val picker = page.picker(album, references.size) ?: return@inspect false
if (!picker.matches(empty, page.windowId, selected, references.size) || !picker.done.nativeClick()) return@inspect false
beforeAttach()
ui.click(picker.done)
} == true
if (!returned) throw PlatformException("小红书未确认将选中的图片带回回复框")
awaitPage(6_000, "小红书回复框未完整回读全部图片附件") { page ->
val composer = page.checkedComposer(session) ?: return@awaitPage null
true.takeIf { composer.editor.isStillBlankAndFocused() && page.draftThumbnails(composer)?.size == references.size }
}
}
private fun verifyPhotos(references: List<PhotoPixels>, windowId: Int, bounds: List<Rect>, failure: String) {
val crops = ui.screenshotPhotos(windowId, bounds) ?: throw PlatformException(failure)
if (crops.size != references.size || references.indices.any { !PublishedPhotoMatcher.matches(references[it], crops[it]) }) {
throw PlatformException(failure)
}
}
private fun UiPage.matchesTarget(target: CommentTarget, windowId: Int, surfaceSource: UiNodeSource): Boolean {
val surface = comments.surface(this) ?: return false
return this.windowId == windowId && surface.windowId == windowId && surface.root.hasSource(surfaceSource) &&
comments.row(this, target.key)?.target == target
}
private fun UiPage.hasPrivateDraft(): Boolean = nodes.any {
it.editable && it.hasDraft() || it.labels().any(removeActions::contains) ||
it.isImage() && it.labels().any(previewLabels::contains)
}
private fun UiPage.openedComposer(target: CommentTarget): Composer? {
val row = comments.row(this, target.key)?.takeIf { it.target == target } ?: return null
val editor = nodes.singleOrNull { it.canEdit() && it.focused && it.bounds.centerY() >= y(.40f) &&
it.bounds.width() >= bounds.width() * .25f } ?: return null
val container = generateSequence(editor.directParent()) { it.directParent() }.take(4).firstOrNull { scope ->
scope.bounds.contains(editor.bounds) && scope.bounds.height() <= bounds.height() * .50f &&
scope !== row.container && !row.container.isDescendantOf(scope) &&
nodes.none { it !== editor && it.editable && it.isDescendantOf(scope) } &&
(editor.replyCue(target) || nodes.any { it.isDescendantOf(scope) && it.replyCue(target) }) &&
nodes.any { it.isDescendantOf(scope) && it.labels().any { label -> label in sendActions || label in imageActions } }
} ?: return null
return Composer(editor, container)
}
private fun UiPage.checkedComposer(session: Prepared): Composer? {
if (!matchesTarget(session.target, session.windowId, session.surface)) return null
val container = nodes.singleOrNull { it.hasSource(session.container) } ?: return null
val editor = nodes.singleOrNull { it.focused && it.canEdit() && it.hasSource(session.editor) &&
it.isDescendantOf(container) && container.bounds.contains(it.bounds) } ?: return null
if (nodes.any { it !== editor && it.editable && it.focused }) return null
if (!editor.replyCue(session.target) && editor.hint.isNotEmpty() && !editor.hasDraft() &&
nodes.none { it.isDescendantOf(container) && it.replyCue(session.target) }) return null
return Composer(editor, container)
}
private fun UiPage.readyDraft(session: Prepared, text: String, count: Int): ReadyDraft? {
val composer = checkedComposer(session) ?: return null
val editor = composer.editor
if (editor.text != text || !editor.hasCurrentFocusedText(text) { matchesReplyCue(it, session.target) }) return null
val previews = draftThumbnails(composer)?.takeIf { it.size == count } ?: return null
val send = composerActions(composer, sendActions).singleOrNull { action ->
action.bounds.centerX() > editor.bounds.centerX() &&
action.bounds.centerY() >= editor.bounds.top && action.bounds.top <= editor.bounds.bottom + editor.bounds.height() * 2
} ?: return null
return ReadyDraft(send, DraftSnapshot(windowId, previews.map { Rect(it.bounds) }))
}
private fun UiPage.composerActions(composer: Composer, labels: Set<String>): List<UiNode> = 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<UiNode>? {
val scoped = nodes.filter { it.isDescendantOf(composer.container) }
val removals = scoped.filter { it.labels().any(removeActions::contains) }.mapNotNull { it.nativeAction() }.distinct()
val threshold = maxOf(24, composer.editor.bounds.height() / 2)
val previews = scoped.filter { node ->
node.isImage() && node.bounds.width() >= threshold && node.bounds.height() >= threshold &&
node.labels().none { it in imageActions || it in removeActions || it in composerIcons }
}
if (previews.size != removals.size || previews.any { !composer.container.bounds.contains(it.bounds) ||
!bounds.contains(it.bounds) }) return null
val pairedRemovals = previews.map { it.previewRemoval(removals) ?: return null }
if (pairedRemovals.distinct().size != previews.size) return null
if (scoped.any { it.scrollable && (it.horizontalItemCount ?: 0) > previews.size }) return null
return previews.sortedWith(compareBy<UiNode> { it.bounds.top }.thenBy { it.bounds.left })
}
private fun UiNode.previewRemoval(removals: List<UiNode>): 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<String>): UiNode? {
val hasExit = nodes.any { it.bounds.centerY() < y(.24f) && it.labels().any(pickerExit::contains) && it.nativeAction() != null }
if (!hasExit) return null
return nodes.singleOrNull { !it.editable && it.bounds.centerY() < y(.24f) &&
it.bounds.centerX() in x(.22f)..x(.78f) && it.labels().any(labels::contains) }
}
private fun UiPage.picker(album: String, expected: Int): Picker? {
val heading = albumHeading(setOf(album)) ?: return null
val doneLabel = nodes.singleOrNull { node -> !node.editable && node.bounds.centerY() > y(.70f) &&
node.labels().any { selectionCount.matches(it.filterNot(Char::isWhitespace)) } } ?: return null
val match = doneLabel.labels().mapNotNull { selectionCount.matchEntire(it.filterNot(Char::isWhitespace)) }
.singleOrNull() ?: return null
val count = match.groupValues[1].ifEmpty { "0" }.toIntOrNull()?.takeIf { it in 0..expected } ?: return null
val done = if (count == 0) doneLabel else doneLabel.nativeAction() ?: return null
val grid = nodes.singleOrNull { it.className in photoGridClasses && it.bounds.top >= heading.bounds.bottom &&
it.bounds.bottom <= done.bounds.bottom && it.bounds.width() >= bounds.width() * .60f } ?: return null
val images = nodes.filter { it.isDescendantOf(grid) && it.isImage() && it.bounds.width() >= bounds.width() * .15f &&
it.bounds.height() >= bounds.width() * .15f && grid.bounds.contains(it.bounds) && bounds.contains(it.bounds) }
if (images.size != expected) return null
val tiles = images.map { image ->
val parent = image.directParent() ?: return null
val select = nodes.singleOrNull { it.directParent() === parent && image.bounds.contains(it.bounds) && it.nativeClick() &&
it.selectionOrdinal() != null } ?: return null
AlbumTile(image, select, select.selectionOrdinal() ?: return null)
}.sortedWith(compareBy<AlbumTile> { it.image.bounds.top }.thenBy { it.image.bounds.left })
if (tiles.map(AlbumTile::select).distinct().size != expected) return null
return Picker(tiles, done, count)
}
private fun Picker.snapshot(windowId: Int) = PickerSnapshot(windowId, tiles.map { Rect(it.image.bounds) })
private fun Picker.matches(expected: PickerSnapshot, windowId: Int, selected: List<Int>, count: Int): Boolean =
this.count == count && snapshot(windowId) == expected && tiles.map(AlbumTile::ordinal) == selected
private fun UiNode.selectionOrdinal(): Int? {
val values = labels().mapNotNull { label ->
if (!selected && label in unselectedLabels) 0 else ordinalLabel.matchEntire(label.filterNot(Char::isWhitespace))
?.groupValues?.get(1)?.toIntOrNull()
}.distinct()
return values.singleOrNull()
}
private fun UiNode.replyCue(target: CommentTarget): Boolean = sequenceOf(hint, description, text.takeIf { !editable || showingHint }.orEmpty())
.any { matchesReplyCue(it, target) }
private fun UiNode.hasReplyPrompt(): Boolean = sequenceOf(hint, description, text.takeIf { !editable || showingHint }.orEmpty())
.any { it.trim().startsWith("回复") }
private fun matchesReplyCue(label: String, target: CommentTarget): Boolean {
val author = target.author.trim().removePrefix("@").trim()
val cue = label.trim().removeSuffix(":").removeSuffix(":").trim()
return author.isNotEmpty() && cue.startsWith("回复") && cue.removePrefix("回复").trim().removePrefix("@").trim() == author
}
private fun UiNode.hasExactLabel(wanted: String) = labels().contains(wanted)
private fun UiNode.canEdit() = enabled && editable && supports(AccessibilityNodeInfo.ACTION_SET_TEXT)
private fun UiNode.nativeClick() = enabled && !editable && supports(AccessibilityNodeInfo.ACTION_CLICK)
private fun UiNode.nativeAction(): UiNode? = takeIf { it.nativeClick() }
?: directParent()?.takeIf { it.nativeClick() && it.bounds.contains(bounds) }
private fun UiNode.isImage() = className == "android.widget.ImageView" ||
className == "android.view.View" && labels().any(imageLabels::contains)
private fun <T : Any> awaitPage(timeout: Long, failure: String, read: (UiPage) -> T?): T =
ui.await(timeout) { ui.inspect(read) } ?: throw PlatformException(failure)
private companion object {
val sendActions = setOf("发送", "发送回复", "发送评论")
val imageActions = setOf("相册", "插入图片", "添加图片", "选择图片")
val removeActions = setOf("删除图片", "移除图片", "删除照片", "移除照片")
val composerIcons = setOf("发送", "表情", "表情包", "拍照", "话题", "@")
val previewLabels = setOf("图片预览", "照片预览")
val imageLabels = setOf("图片", "照片", "图片预览", "照片预览", "图片缩略图", "照片缩略图")
val pickerExit = setOf("返回", "关闭", "取消")
val pickerHeadings = setOf("相册", "最近项目", "全部照片", "全部图片", "所有照片", "最近")
val photoGridClasses = setOf("androidx.recyclerview.widget.RecyclerView", "android.widget.GridView")
val unselectedLabels = setOf("选择", "未选中", "未选择")
val selectionCount = Regex("""(?:完成|确定|添加)(?:[((]([0-9]+)(?:/[0-9]+)?[))])?""")
val ordinalLabel = Regex("""(?:已选中|已选择|第)?([1-9])(?:张图片|张)?""")
}
}
@@ -0,0 +1,228 @@
package com.jieliu.app.platform
import android.graphics.Rect
import com.jieliu.app.data.PhotoLibrary
import com.jieliu.app.task.TemplatePhoto
/** Reads one original comment thread. No editor activation, input, or submission is performed here. */
internal class XiaohongshuReplyReceipt(
private val ui: AccessibleUi,
private val photos: PhotoLibrary,
private val comments: XiaohongshuComments,
) {
private data class SurfaceKey(val windowId: Int, val inline: Boolean)
private data class OriginalComment(val key: String, val author: String)
private data class ThreadStamp(val complete: Boolean, val replyIds: List<String>, val expandLabels: List<String>?)
private data class Baseline(val stamp: ThreadStamp, val parentVisible: Boolean, val bodies: List<String>)
private data class VisibleReceipt(val identity: String, val body: Rect, val photos: List<Rect>)
fun captureBaseline(target: CommentTarget, expectedText: String): Boolean {
if (target.key.isBlank() || target.author.isBlank() || expectedText.isBlank()) return false
val original = OriginalComment(target.key, target.author)
val scope = findSurface() ?: return false
repeat(MAX_EXPANSIONS + 1) { pageIndex ->
val baseline = ui.await(THREAD_WAIT_MS) {
readThread(scope, original) { surface, parent, thread ->
Baseline(stamp(thread), contains(surface.viewport, parent.body.bounds), thread.replies.map { it.body.text })
}
} ?: return false
// A missing own badge cannot turn an already visible identical body into evidence of a new reply.
if (baseline.bodies.any { it == expectedText }) return false
if (baseline.stamp.complete) {
return baseline.parentVisible && baseline.bodies.none(String::isBlank) &&
baseline.stamp.replyIds.none(String::isBlank) &&
baseline.stamp.replyIds.distinct().size == baseline.stamp.replyIds.size
}
if (pageIndex == MAX_EXPANSIONS || !expandThread(scope, original, baseline.stamp)) return false
if (ui.await(THREAD_WAIT_MS) { changedThread(scope, original, baseline.stamp) } != true) return false
}
return false
}
fun confirm(
targetKey: String,
author: String,
text: String,
photos: List<TemplatePhoto>,
armedAt: Long,
): CommentPublishResult {
if (targetKey.isBlank() || author.isBlank() || text.isBlank() || !validXhsReceiptAge(armedAt, System.currentTimeMillis())) {
return CommentPublishResult.UNCERTAIN
}
val original = OriginalComment(targetKey, author)
val references = this.photos.readReceiptPixels(photos) ?: return CommentPublishResult.UNCERTAIN
val scope = findSurface() ?: return CommentPublishResult.UNCERTAIN
if (!seekOriginal(scope, original)) return CommentPublishResult.UNCERTAIN
var expansions = 0
var revisitedOriginal = false
val opened = mutableSetOf<ThreadStamp>()
repeat(MAX_RECEIPT_PASSES) {
if (ui.await(RECEIPT_WAIT_MS) { verifiedReceipt(scope, original, text, references, armedAt) } == true) {
return CommentPublishResult.CONFIRMED
}
val seen = readThread(scope, original) { _, _, thread -> stamp(thread) }
if (seen == null) {
if (revisitedOriginal || !seekOriginal(scope, original, forwardLimit = 0)) return CommentPublishResult.UNCERTAIN
revisitedOriginal = true
} else if (seen.expandLabels != null && expansions < MAX_EXPANSIONS && seen !in opened &&
expandThread(scope, original, seen)
) {
expansions++
opened.add(seen)
ui.await(THREAD_WAIT_MS) { changedThread(scope, original, seen) }
} else if (!bringLowerReplyIntoView(scope, original)) {
return CommentPublishResult.UNCERTAIN
}
}
return CommentPublishResult.UNCERTAIN
}
private fun verifiedReceipt(
scope: SurfaceKey,
original: OriginalComment,
text: String,
references: List<PhotoPixels>,
armedAt: Long,
): Boolean? {
val before = receiptRow(scope, original, text, references.size, armedAt) ?: return null
val captured = if (references.isEmpty()) emptyList() else ui.screenshotPhotos(scope.windowId, before.photos) ?: return null
val after = receiptRow(scope, original, text, references.size, armedAt) ?: return null
return true.takeIf {
before == after && captured.size == references.size &&
references.indices.all { PublishedPhotoMatcher.matches(references[it], captured[it]) }
}
}
private fun receiptRow(scope: SurfaceKey, original: OriginalComment, text: String, photoCount: Int, armedAt: Long): VisibleReceipt? =
readThread(scope, original) { surface, parent, thread ->
val viewport = surface.viewport
if (!contains(viewport, parent.body.bounds)) return@readThread null
val reply = thread.replies.singleOrNull { it.own && it.body.text == text } ?: return@readThread null
val time = reply.timeLabel ?: return@readThread null
if (reply.identity.isBlank() || thread.replies.count { it.identity == reply.identity } != 1 ||
!contains(viewport, reply.body.bounds) || !matchesXhsReceiptTime(time, armedAt, System.currentTimeMillis())
) return@readThread null
val crops = reply.photos.map { Rect(it.bounds) }
if (crops.size != photoCount || crops.any {
!contains(viewport, it) || it.top <= viewport.top || it.bottom >= viewport.bottom || Rect.intersects(reply.body.bounds, it)
} || crops.indices.any { index -> (0 until index).any { Rect.intersects(crops[it], crops[index]) } }
) return@readThread null
VisibleReceipt(reply.identity, Rect(reply.body.bounds), crops)
}
private fun seekOriginal(scope: SurfaceKey, original: OriginalComment, forwardLimit: Int = MAX_FORWARD_SCROLLS): Boolean {
if (originalVisible(scope, original)) return true
repeat(MAX_REVERSE_SCROLLS + forwardLimit) { index ->
if (!moveWithinSurface(scope, towardEarlier = index < MAX_REVERSE_SCROLLS)) return false
if (ui.await(RECEIPT_WAIT_MS) { true.takeIf { originalVisible(scope, original) } } == true) return true
}
return false
}
private fun originalVisible(scope: SurfaceKey, original: OriginalComment): Boolean =
readOriginal(scope, original) { _, _ -> true } == true
private fun moveWithinSurface(scope: SurfaceKey, towardEarlier: Boolean): Boolean = ui.inspect { page ->
val area = matchingSurface(page, scope)?.viewport ?: return@inspect false
if (area.height() < 100) return@inspect false
val x = area.exactCenterX()
val nearTop = area.top + area.height() * .25f
val nearBottom = area.top + area.height() * .76f
if (towardEarlier) ui.touch(x, nearTop, x, nearBottom, 360L)
else ui.touch(x, nearBottom, x, nearTop, 360L)
} == true
private fun bringLowerReplyIntoView(scope: SurfaceKey, original: OriginalComment): Boolean =
readOriginal(scope, original) { surface, parent ->
val area = surface.viewport
val shift = (parent.body.bounds.top - area.top - 18).coerceAtMost(area.height() / 4)
if (shift < 22) return@readOriginal false
val x = area.exactCenterX()
val from = area.top + area.height() * .72f
ui.touch(x, from, x, from - shift, 290L)
} == true
private fun expandThread(scope: SurfaceKey, original: OriginalComment, previous: ThreadStamp): Boolean =
readThread(scope, original) { surface, _, thread ->
if (stamp(thread) != previous) return@readThread true
val expand = thread.expand ?: return@readThread false
!thread.complete && contains(surface.viewport, expand.bounds) && ui.click(expand)
} == true
private fun changedThread(scope: SurfaceKey, original: OriginalComment, previous: ThreadStamp): Boolean? =
readThread(scope, original) { _, _, thread -> true.takeIf { stamp(thread) != previous } }
private fun stamp(thread: XhsCommentThread) = ThreadStamp(
thread.complete, thread.replies.map { it.identity }, thread.expand?.labels(),
)
private fun findSurface(): SurfaceKey? = ui.await(THREAD_WAIT_MS) {
ui.inspect { page ->
if (hasOpenEditor(page)) return@inspect null
comments.surface(page)?.takeIf { it.windowId == page.windowId && contains(page.bounds, it.viewport) }
?.let { SurfaceKey(it.windowId, it.inline) }
}
}
private fun matchingSurface(page: UiPage, scope: SurfaceKey): XhsCommentSurface? {
if (page.windowId != scope.windowId || hasOpenEditor(page)) return null
return comments.surface(page)?.takeIf {
it.windowId == scope.windowId && it.inline == scope.inline && contains(page.bounds, it.viewport)
}
}
private fun hasOpenEditor(page: UiPage): Boolean = page.nodes.any { it.editable && (it.focused || it.hasDraft()) }
private fun <T> readOriginal(scope: SurfaceKey, original: OriginalComment, read: (XhsCommentSurface, XhsCommentRow) -> T): T? =
ui.inspect { page ->
val surface = matchingSurface(page, scope) ?: return@inspect null
val row = comments.row(page, original.key)?.takeIf { it.target.key == original.key && it.target.author == original.author }
?: return@inspect null
read(surface, row)
}
private fun <T> readThread(
scope: SurfaceKey,
original: OriginalComment,
read: (XhsCommentSurface, XhsCommentRow, XhsCommentThread) -> T,
): T? = ui.inspect { page ->
val surface = matchingSurface(page, scope) ?: return@inspect null
val row = comments.row(page, original.key)?.takeIf { it.target.key == original.key && it.target.author == original.author }
?: return@inspect null
val thread = comments.thread(page, row) ?: return@inspect null
read(surface, row, thread)
}
private fun contains(outer: Rect, inner: Rect) = !inner.isEmpty && outer.contains(inner)
private companion object {
const val MAX_EXPANSIONS = 4
const val MAX_RECEIPT_PASSES = 9
const val MAX_REVERSE_SCROLLS = 2
const val MAX_FORWARD_SCROLLS = 12
const val THREAD_WAIT_MS = 1_550L
const val RECEIPT_WAIT_MS = 850L
}
}
private const val XHS_RECEIPT_MAX_AGE_MS = 30 * 60 * 1_000L
private const val XHS_RECEIPT_CLOCK_SLACK_MS = 5_000L
private val xhsReceiptRelativeTime = Regex("([0-9]{1,2})[ \\u00a0]*(秒前|分钟前)")
internal fun validXhsReceiptAge(armedAt: Long, now: Long): Boolean =
armedAt > 0 && armedAt <= now && now - armedAt <= XHS_RECEIPT_MAX_AGE_MS
internal fun matchesXhsReceiptTime(label: String, armedAt: Long, now: Long): Boolean {
if (!validXhsReceiptAge(armedAt, now)) return false
val normalized = label.trim()
val elapsed = now - armedAt
if (normalized == "刚刚") return elapsed < 60_000L + XHS_RECEIPT_CLOCK_SLACK_MS
val match = xhsReceiptRelativeTime.matchEntire(normalized) ?: return false
val amount = match.groupValues[1].toLong()
val unit = if (match.groupValues[2] == "秒前") 1_000L else 60_000L
val earliest = amount * unit - XHS_RECEIPT_CLOCK_SLACK_MS
val latest = (amount + 1) * unit + XHS_RECEIPT_CLOCK_SLACK_MS
return elapsed >= earliest && elapsed < latest
}
@@ -0,0 +1,38 @@
package com.jieliu.app.platform
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class XhsCommentLabelsTest {
@Test
fun syntheticHeadingRequiresStandaloneCommentCount() {
assertEquals(66, XhsCommentLabels.commentCount("共 66 条评论"))
assertEquals(0, XhsCommentLabels.commentCount("共0条评论"))
assertEquals(0, XhsCommentLabels.commentCount("暂无评论"))
assertEquals(0, XhsCommentLabels.commentCount("还没有评论"))
assertNull(XhsCommentLabels.commentCount("评论 2"))
assertNull(XhsCommentLabels.commentCount("评论加载中"))
assertNull(XhsCommentLabels.commentCount("这里共 2 条评论"))
}
@Test
fun syntheticContinuationDistinguishesReplyExpansionFromAnAmbiguousToggle() {
assertTrue(XhsCommentLabels.expandsReplies("展开 2 条回复"))
assertTrue(XhsCommentLabels.blocksThreadBoundary("展开更多"))
assertFalse(XhsCommentLabels.expandsReplies("展开更多"))
assertFalse(XhsCommentLabels.blocksThreadBoundary("展开全文"))
}
@Test
fun syntheticReceiptLabelsRequireExplicitMediaAndRelativeTime() {
assertTrue(XhsCommentLabels.photoDescription("查看图片 2"))
assertFalse(XhsCommentLabels.photoDescription("用户图片"))
assertEquals("刚刚", XhsCommentLabels.relativeTime("刚刚 北京"))
assertEquals("42 秒前", XhsCommentLabels.relativeTime("42 秒前 北京"))
assertEquals("3 分钟前", XhsCommentLabels.relativeTime("3 分钟前 北京"))
assertNull(XhsCommentLabels.relativeTime("回复 3 分钟前"))
}
}
@@ -0,0 +1,25 @@
package com.jieliu.app.platform
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class XhsReceiptTimeTest {
private val armedAt = 1_790_000_000_000L
@Test fun relativeLabelMustAgreeWithRecordedSubmission() {
assertTrue(matchesXhsReceiptTime("刚刚", armedAt, armedAt + 2_000L))
assertTrue(matchesXhsReceiptTime("12 秒前", armedAt, armedAt + 12_600L))
assertTrue(matchesXhsReceiptTime("1分钟前", armedAt, armedAt + 82_000L))
assertFalse(matchesXhsReceiptTime("2分钟前", armedAt, armedAt + 62_000L))
assertFalse(matchesXhsReceiptTime("刚刚", armedAt, armedAt + 70_000L))
}
@Test fun unsupportedLabelsAndFutureOrExpiredArmsAreInconclusive() {
val times = listOf("", "今天", "11-26", "刚刚 浙江", "昨日 11:20", "99分钟前")
assertTrue(times.none { matchesXhsReceiptTime(it, armedAt, armedAt + 3_000L) })
assertFalse(matchesXhsReceiptTime("刚刚", armedAt, armedAt - 1L))
assertFalse(matchesXhsReceiptTime("31分钟前", armedAt, armedAt + 31 * 60_000L))
assertFalse(validXhsReceiptAge(0, armedAt))
}
}
@@ -3,6 +3,7 @@ package com.jieliu.app.task
import com.jieliu.app.platform.CommentPublishResult
import com.jieliu.app.platform.CommentTarget
import com.jieliu.app.platform.PlatformAdapter
import com.jieliu.app.platform.PlatformRegistry
import com.jieliu.app.platform.VideoContext
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
@@ -286,6 +287,35 @@ class TaskRunnerTest {
assertEquals(0, platform.swipes)
}
@Test fun xiaohongshuRotatesBoundPhotoSetsAndRechecksWithoutResending() {
val alternativePhotos = listOf(TemplatePhoto(id("photo3"), "三.png"), TemplatePhoto(id("photo4"), "四.png"))
val alternate = ReplyPhrase(id("alternate"), "另一条 API 充值话术", alternativePhotos)
val rule = apiRule.copy(phrases = apiRule.phrases + alternate)
val contentType = firstType.copy(rules = listOf(rule))
val plan = plan(contentType).copy(platformId = "xiaohongshu", limit = 2, repliesPerVideo = 2)
val store = RecordingStore(TaskCheckpoint("xhs-multi-receipt", plan))
val targets = listOf(target("first", "想咨询 API 充值"), target("second", "请问API充值"), target("extra", "关于 API 充值"))
val platform = FakePlatform(store, result = CommentPublishResult.UNCERTAIN).apply {
knownBaseline = true
recheckResult = CommentPublishResult.CONFIRMED
screensForVideo = { video -> if (video.key == "video-0") listOf(emptyList()) else listOf(targets) }
}
execute(store, platform)
assertTrue(PlatformRegistry.platforms.single { it.id == plan.platformId }.supportsReplies)
assertEquals(listOf("first", "second"), platform.attempts.map { it.targetKey })
assertEquals(rule.phrases.associate { it.text to it.photos }, platform.attempts.associate { it.text to it.photos })
assertEquals(platform.attempts.map { "video-1" to it }, platform.rechecks)
assertEquals(2, platform.publishCalls)
assertEquals(2, store.pendingWrites)
assertTrue(store.logs.contains("第 2 条笔记已确认 2/2 条回复"))
assertEquals(listOf(Outcome.NO_REPLY, Outcome.SENT), store.checkpoint.receipts.map { it.outcome })
assertEquals(listOf(Outcome.SENT, Outcome.SENT), store.checkpoint.receipts.last().replies.map { it.outcome })
assertNull(store.checkpoint.pending)
assertTrue(store.checkpoint.complete)
}
@Test fun manualConfirmationBelowQuotaResumesTheSameVideoWithoutReplyingToTheSameTarget() {
val store = RecordingStore(TaskCheckpoint("resume-quota", plan(firstType).copy(limit = 2, repliesPerVideo = 2)))
val remaining = listOf(listOf(target("first", "付款方式"), target("second", "付款方式")))