完善小红书多图回复与待核对恢复
改进图文和视频笔记定位、附件顺序校验及原评论回执读取。识别社区评论互动限制并保留待核对记录。
This commit is contained in:
@@ -13,8 +13,8 @@ android {
|
|||||||
applicationId = "com.jieliu.app"
|
applicationId = "com.jieliu.app"
|
||||||
minSdk = 26
|
minSdk = 26
|
||||||
targetSdk = 35
|
targetSdk = 35
|
||||||
versionCode = 22
|
versionCode = 23
|
||||||
versionName = "0.1.21"
|
versionName = "0.1.22"
|
||||||
}
|
}
|
||||||
|
|
||||||
compileOptions {
|
compileOptions {
|
||||||
|
|||||||
@@ -106,7 +106,10 @@ internal object TaskControl {
|
|||||||
.copy(plan = plan, message = if (rechecking) "正在准备自动核对回复" else "任务准备运行")
|
.copy(plan = plan, message = if (rechecking) "正在准备自动核对回复" else "任务准备运行")
|
||||||
val run = Run(service, store, initial)
|
val run = Run(service, store, initial)
|
||||||
val cancelled = { run.cancelled }
|
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)
|
val interval = randomIn(plan.actionMillis.first, plan.actionMillis.last)
|
||||||
pauseFor(interval.toLong(), cancelled)
|
pauseFor(interval.toLong(), cancelled)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.jieliu.app.data
|
package com.jieliu.app.data
|
||||||
|
|
||||||
|
import com.jieliu.app.platform.XiaohongshuNoteKind
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import com.jieliu.app.task.ContentType
|
import com.jieliu.app.task.ContentType
|
||||||
import com.jieliu.app.task.KeywordRule
|
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("contentTypes", contentTypes?.let { JSONArray(it.map { type -> type.toJson() }) })
|
||||||
.put("selectedTypeId", selectedTypeId)
|
.put("selectedTypeId", selectedTypeId)
|
||||||
|
.put("xiaohongshuNoteKind", xiaohongshuNoteKind.takeUnless { it == XiaohongshuNoteKind.ANY }?.name)
|
||||||
|
.put("xiaohongshuNoteKey", xiaohongshuNoteKey)
|
||||||
.put("repliesPerVideo", repliesPerVideo)
|
.put("repliesPerVideo", repliesPerVideo)
|
||||||
.put("limit", limit).put("watchMin", watchSeconds.first).put("watchMax", watchSeconds.last)
|
.put("limit", limit).put("watchMin", watchSeconds.first).put("watchMax", watchSeconds.last)
|
||||||
.put("actionMin", actionMillis.first).put("actionMax", actionMillis.last)
|
.put("actionMin", actionMillis.first).put("actionMax", actionMillis.last)
|
||||||
@@ -201,6 +204,9 @@ class LocalStore(context: Context) : TaskRunStorage {
|
|||||||
},
|
},
|
||||||
selectedTypeId = optionalString("selectedTypeId"),
|
selectedTypeId = optionalString("selectedTypeId"),
|
||||||
repliesPerVideo = if (isNull("repliesPerVideo")) 1 else getInt("repliesPerVideo"),
|
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)
|
private fun ContentType.toJson() = JSONObject().put("id", id).put("name", name)
|
||||||
|
|||||||
@@ -21,9 +21,11 @@ import com.jieliu.app.task.TaskPlan
|
|||||||
import com.jieliu.app.task.TemplatePhoto
|
import com.jieliu.app.task.TemplatePhoto
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.FileOutputStream
|
import java.io.FileOutputStream
|
||||||
|
import java.io.IOException
|
||||||
import java.nio.file.Files
|
import java.nio.file.Files
|
||||||
import java.nio.file.LinkOption.NOFOLLOW_LINKS
|
import java.nio.file.LinkOption.NOFOLLOW_LINKS
|
||||||
import java.nio.file.StandardCopyOption.ATOMIC_MOVE
|
import java.nio.file.StandardCopyOption.ATOMIC_MOVE
|
||||||
|
import java.security.MessageDigest
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
|
|
||||||
data class StagedPhotos(val albumName: String, val uris: List<Uri>)
|
data class StagedPhotos(val albumName: String, val uris: List<Uri>)
|
||||||
@@ -97,6 +99,26 @@ class PhotoLibrary(context: Context) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal fun attachmentDigests(photos: List<TemplatePhoto>): List<String>? = 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<TemplatePhoto>): StagedPhotos = synchronized(lock) {
|
fun stage(photos: List<TemplatePhoto>): StagedPhotos = synchronized(lock) {
|
||||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) error("暂存话术图片需要 Android 10 或更新版本。")
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) error("暂存话术图片需要 Android 10 或更新版本。")
|
||||||
require(photos.size in 1..TaskPlan.MAX_TEMPLATE_PHOTOS &&
|
require(photos.size in 1..TaskPlan.MAX_TEMPLATE_PHOTOS &&
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ data class CommentTarget(val key: String, val text: String, val author: String)
|
|||||||
enum class CommentPublishResult { CONFIRMED, UNCERTAIN }
|
enum class CommentPublishResult { CONFIRMED, UNCERTAIN }
|
||||||
|
|
||||||
class PlatformException(message: String, cause: Throwable? = null) : RuntimeException(message, cause)
|
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. */
|
/** Call from one worker thread. Calls wait for accessibility state and may block. */
|
||||||
interface PlatformAdapter {
|
interface PlatformAdapter {
|
||||||
@@ -29,6 +30,7 @@ interface PlatformAdapter {
|
|||||||
fun currentVideo(): VideoContext
|
fun currentVideo(): VideoContext
|
||||||
fun nextVideo(previous: VideoContext): VideoContext
|
fun nextVideo(previous: VideoContext): VideoContext
|
||||||
fun openComments(expected: VideoContext): List<String>
|
fun openComments(expected: VideoContext): List<String>
|
||||||
|
fun openCommentsForReceipt(expected: VideoContext) { openComments(expected) }
|
||||||
fun scanComments(): List<CommentTarget> = emptyList()
|
fun scanComments(): List<CommentTarget> = emptyList()
|
||||||
fun scrollComments(): Boolean = false
|
fun scrollComments(): Boolean = false
|
||||||
/** False means no reply control was activated and scanning may continue. */
|
/** 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
|
fun hasPreparedReplyBaseline(targetKey: String, text: String): Boolean = false
|
||||||
/** Read back one previously armed reply. This must never prepare or submit a comment. */
|
/** Read back one previously armed reply. This must never prepare or submit a comment. */
|
||||||
fun confirmPendingReply(video: VideoContext, pending: PendingComment): CommentPublishResult = CommentPublishResult.UNCERTAIN
|
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()
|
fun closeComments()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,6 +63,10 @@ object PlatformRegistry {
|
|||||||
platformId: String,
|
platformId: String,
|
||||||
service: AccessibilityService,
|
service: AccessibilityService,
|
||||||
cancelled: () -> Boolean,
|
cancelled: () -> Boolean,
|
||||||
|
noteKind: XiaohongshuNoteKind = XiaohongshuNoteKind.ANY,
|
||||||
|
targetNoteKey: String? = null,
|
||||||
|
pinnedResumeNoteKey: String? = null,
|
||||||
|
receiptDiagnostic: (String) -> Unit = {},
|
||||||
pauseBetweenActions: () -> Unit = {},
|
pauseBetweenActions: () -> Unit = {},
|
||||||
): PlatformAdapter {
|
): PlatformAdapter {
|
||||||
val spec = platforms.firstOrNull { it.id == platformId }
|
val spec = platforms.firstOrNull { it.id == platformId }
|
||||||
@@ -66,7 +74,8 @@ object PlatformRegistry {
|
|||||||
val ui = AccessibleUi(service, spec.packageName, cancelled, pauseBetweenActions)
|
val ui = AccessibleUi(service, spec.packageName, cancelled, pauseBetweenActions)
|
||||||
return when (spec.id) {
|
return when (spec.id) {
|
||||||
douyin.id -> DouyinAdapter(spec, ui, PhotoLibrary(service))
|
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} 暂未接入")
|
else -> throw PlatformException("${spec.label} 暂未接入")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,6 +26,54 @@ internal object PublishedPhotoMatcher {
|
|||||||
compare(reference, referenceBounds, published, fittedContent)
|
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<Int>, 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 {
|
private fun compare(reference: PhotoPixels, referenceBounds: Box, published: PhotoPixels, publishedBounds: Box): Boolean {
|
||||||
if (min(referenceBounds.width, referenceBounds.height) < MIN_SIDE ||
|
if (min(referenceBounds.width, referenceBounds.height) < MIN_SIDE ||
|
||||||
min(publishedBounds.width, publishedBounds.height) < MIN_SIDE) return false
|
min(publishedBounds.width, publishedBounds.height) < MIN_SIDE) return false
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.jieliu.app.platform
|
package com.jieliu.app.platform
|
||||||
|
|
||||||
import android.graphics.Rect
|
import android.graphics.Rect
|
||||||
|
import android.util.Log
|
||||||
import android.view.accessibility.AccessibilityNodeInfo
|
import android.view.accessibility.AccessibilityNodeInfo
|
||||||
import com.jieliu.app.data.PhotoLibrary
|
import com.jieliu.app.data.PhotoLibrary
|
||||||
import com.jieliu.app.task.PendingComment
|
import com.jieliu.app.task.PendingComment
|
||||||
@@ -9,10 +10,16 @@ import java.io.Closeable
|
|||||||
import java.security.MessageDigest
|
import java.security.MessageDigest
|
||||||
import kotlin.math.abs
|
import kotlin.math.abs
|
||||||
|
|
||||||
|
enum class XiaohongshuNoteKind { ANY, IMAGE, VIDEO }
|
||||||
|
|
||||||
internal class XiaohongshuAdapter(
|
internal class XiaohongshuAdapter(
|
||||||
private val spec: PlatformSpec,
|
private val spec: PlatformSpec,
|
||||||
private val ui: AccessibleUi,
|
private val ui: AccessibleUi,
|
||||||
private val photoLibrary: PhotoLibrary,
|
private val photoLibrary: PhotoLibrary,
|
||||||
|
private val noteKind: XiaohongshuNoteKind = XiaohongshuNoteKind.ANY,
|
||||||
|
private val targetNoteKey: String? = null,
|
||||||
|
private val pinnedResumeNoteKey: String? = null,
|
||||||
|
receiptDiagnostic: (String) -> Unit = {},
|
||||||
) : PlatformAdapter {
|
) : PlatformAdapter {
|
||||||
private data class SearchHeader(val editor: UiNode, val submit: UiNode)
|
private data class SearchHeader(val editor: UiNode, val submit: UiNode)
|
||||||
private data class ResultHeader(val query: UiNode, val tabs: 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 CardIdentity(val key: String, val title: String, val author: String)
|
||||||
private data class ResultCard(val action: UiNode, val identity: CardIdentity)
|
private data class ResultCard(val action: UiNode, val identity: CardIdentity)
|
||||||
private data class PreparedReply(val target: CommentTarget, val text: String)
|
private data class PreparedReply(val target: CommentTarget, val text: String)
|
||||||
|
private data class OpenCommentNote(val note: VideoContext, val empty: Boolean)
|
||||||
private data class NoteControls(
|
private data class NoteControls(
|
||||||
val author: UiNode,
|
val author: UiNode,
|
||||||
val more: UiNode,
|
val more: UiNode,
|
||||||
val toolbar: UiNode,
|
val toolbar: UiNode,
|
||||||
val caption: UiNode? = null,
|
val caption: UiNode? = null,
|
||||||
)
|
) {
|
||||||
|
val kind: XiaohongshuNoteKind get() =
|
||||||
|
if (caption == null) XiaohongshuNoteKind.IMAGE else XiaohongshuNoteKind.VIDEO
|
||||||
|
}
|
||||||
private class NoteBinding(
|
private class NoteBinding(
|
||||||
val video: VideoContext,
|
val video: VideoContext,
|
||||||
val author: String,
|
val author: String,
|
||||||
val windowId: Int,
|
val windowId: Int,
|
||||||
|
val kind: XiaohongshuNoteKind,
|
||||||
val authorSource: UiNodeSource,
|
val authorSource: UiNodeSource,
|
||||||
val moreSource: UiNodeSource,
|
val moreSource: UiNodeSource,
|
||||||
) : Closeable {
|
) : Closeable {
|
||||||
@@ -48,11 +60,11 @@ internal class XiaohongshuAdapter(
|
|||||||
private var keyword: String? = null
|
private var keyword: String? = null
|
||||||
private val examinedCards = mutableSetOf<String>()
|
private val examinedCards = mutableSetOf<String>()
|
||||||
private var activeNote: NoteBinding? = null
|
private var activeNote: NoteBinding? = null
|
||||||
private var commentNote: VideoContext? = null
|
private var commentNote: OpenCommentNote? = null
|
||||||
private var preparedReply: PreparedReply? = null
|
private var preparedReply: PreparedReply? = null
|
||||||
private val comments = XiaohongshuComments(ui, ::matchesNote, ::openNoteComments)
|
private val comments = XiaohongshuComments(ui, ::matchesNote, ::openNoteComments)
|
||||||
private val composer = XiaohongshuReplyComposer(ui, photoLibrary, comments)
|
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)
|
override fun launch() = ui.launchTarget(spec.label)
|
||||||
|
|
||||||
@@ -89,6 +101,7 @@ internal class XiaohongshuAdapter(
|
|||||||
if (ui.inspect { it.searchHeader()?.editor?.focused == true } == true) return
|
if (ui.inspect { it.searchHeader()?.editor?.focused == true } == true) return
|
||||||
ui.pace()
|
ui.pace()
|
||||||
val opened = awaitPage(4_000, "小红书首页未显示可核对的搜索入口") { page ->
|
val opened = awaitPage(4_000, "小红书首页未显示可核对的搜索入口") { page ->
|
||||||
|
page.requireXhsCommentAccess()
|
||||||
val header = page.searchHeader()
|
val header = page.searchHeader()
|
||||||
if (header != null) return@awaitPage header.editor.focused || ui.click(header.editor)
|
if (header != null) return@awaitPage header.editor.focused || ui.click(header.editor)
|
||||||
val results = page.resultHeader()
|
val results = page.resultHeader()
|
||||||
@@ -166,6 +179,7 @@ internal class XiaohongshuAdapter(
|
|||||||
|
|
||||||
private fun UiPage.resultList(keyword: String): ResultList? {
|
private fun UiPage.resultList(keyword: String): ResultList? {
|
||||||
val header = resultHeader()?.takeIf { it.query.text == keyword } ?: return null
|
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" &&
|
val list = nodes.singleOrNull { it.className == "androidx.recyclerview.widget.RecyclerView" &&
|
||||||
it.bounds.width() >= bounds.width() * .90f && it.bounds.bottom >= y(.65f) &&
|
it.bounds.width() >= bounds.width() * .90f && it.bounds.bottom >= y(.65f) &&
|
||||||
it.bounds.top <= header.tabs.bounds.bottom + 36 } ?: return null
|
it.bounds.top <= header.tabs.bounds.bottom + 36 } ?: return null
|
||||||
@@ -175,6 +189,29 @@ internal class XiaohongshuAdapter(
|
|||||||
return ResultList(list, viewport).takeUnless { viewport.isEmpty }
|
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<ResultCard> {
|
private fun UiPage.resultCards(surface: ResultList): List<ResultCard> {
|
||||||
val cards = nodes.asSequence().filter { node ->
|
val cards = nodes.asSequence().filter { node ->
|
||||||
node.directParent() === surface.list && node.className == "android.widget.FrameLayout" &&
|
node.directParent() === surface.list && node.className == "android.widget.FrameLayout" &&
|
||||||
@@ -193,18 +230,27 @@ internal class XiaohongshuAdapter(
|
|||||||
} ?: return@mapNotNull null
|
} ?: return@mapNotNull null
|
||||||
ResultCard(card, CardIdentity(identity(author.text, title.text), title.text, author.text))
|
ResultCard(card, CardIdentity(identity(author.text, title.text), title.text, author.text))
|
||||||
}.toList()
|
}.toList()
|
||||||
|
if (targetNoteKey != null && cards.count { it.identity.matchesSelection() } > 1) {
|
||||||
|
throw PlatformException("小红书搜索结果中有多个卡片对应指定笔记,已停止")
|
||||||
|
}
|
||||||
val counts = cards.groupingBy { it.identity.key }.eachCount()
|
val counts = cards.groupingBy { it.identity.key }.eachCount()
|
||||||
return cards.filter { counts[it.identity.key] == 1 }
|
return cards.filter { counts[it.identity.key] == 1 }
|
||||||
.sortedWith(compareBy({ it.action.bounds.top }, { it.action.bounds.left }))
|
.sortedWith(compareBy({ it.action.bounds.top }, { it.action.bounds.left }))
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun openNextResult(keyword: String): VideoContext {
|
private fun openNextResult(keyword: String): VideoContext {
|
||||||
|
if (targetNoteKey != null && examinedCards.isNotEmpty()) {
|
||||||
|
throw PlatformException("指定的小红书笔记已在本次搜索中处理")
|
||||||
|
}
|
||||||
|
val notFound = if (targetNoteKey == null) "小红书未找到下一条可核对的笔记"
|
||||||
|
else "小红书未在当前搜索结果中找到指定笔记"
|
||||||
|
selectVideoResults(keyword)
|
||||||
repeat(8) {
|
repeat(8) {
|
||||||
ui.pace()
|
ui.pace()
|
||||||
val step = awaitPage(9_000, "小红书未显示当前关键词对应的可读笔记结果") { page ->
|
val step = awaitPage(9_000, "小红书未显示当前关键词对应的可读笔记结果") { page ->
|
||||||
val surface = page.resultList(keyword) ?: return@awaitPage null
|
val surface = page.resultList(keyword) ?: return@awaitPage null
|
||||||
val cards = page.resultCards(surface).takeIf { it.isNotEmpty() } ?: 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 (next != null) {
|
||||||
if (!ui.click(next.action)) throw PlatformException("小红书未确认已打开选中的笔记卡片")
|
if (!ui.click(next.action)) throw PlatformException("小红书未确认已打开选中的笔记卡片")
|
||||||
return@awaitPage ResultStep.Opened(next.identity)
|
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 })
|
ResultStep.Scrolled(cards.associate { it.identity.key to it.action.bounds.top })
|
||||||
}
|
}
|
||||||
when (step) {
|
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 ->
|
is ResultStep.Scrolled -> if (!waitForMovement(step.positions) { page ->
|
||||||
val surface = page.resultList(keyword) ?: return@waitForMovement null
|
val surface = page.resultList(keyword) ?: return@waitForMovement null
|
||||||
page.resultCards(surface).associate { it.identity.key to it.action.bounds.top }
|
page.resultCards(surface).associate { it.identity.key to it.action.bounds.top }
|
||||||
}) throw PlatformException("小红书未显示更多可核对的笔记")
|
}) throw PlatformException(if (targetNoteKey == null) "小红书未显示更多可核对的笔记" else notFound)
|
||||||
ResultStep.End -> throw PlatformException("小红书当前搜索结果已浏览完毕")
|
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? {
|
private fun bindNote(card: CardIdentity, keyword: String): VideoContext? {
|
||||||
val binding = awaitNoteBinding(card, 5_000) ?: verifyOrSkipImageNote(card, keyword) ?: return null
|
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()
|
resetNote()
|
||||||
activeNote = binding
|
activeNote = binding
|
||||||
examinedCards += card.key
|
examinedCards += card.key
|
||||||
@@ -248,7 +306,7 @@ internal class XiaohongshuAdapter(
|
|||||||
} ?: throw PlatformException("小红书未能核对笔记详情与选中的结果卡片")
|
} ?: throw PlatformException("小红书未能核对笔记详情与选中的结果卡片")
|
||||||
shell.use { anchor ->
|
shell.use { anchor ->
|
||||||
revealImageNoteText(card, anchor)?.let { return it }
|
revealImageNoteText(card, anchor)?.let { return it }
|
||||||
leaveUnverifiedImageNote(anchor, keyword)
|
leaveResultNote(anchor, keyword)
|
||||||
}
|
}
|
||||||
examinedCards += card.key
|
examinedCards += card.key
|
||||||
return null
|
return null
|
||||||
@@ -273,23 +331,29 @@ internal class XiaohongshuAdapter(
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun leaveUnverifiedImageNote(anchor: NoteBinding, keyword: String) {
|
private fun leaveResultNote(anchor: NoteBinding, keyword: String) {
|
||||||
ui.pace()
|
ui.pace()
|
||||||
val left = awaitPage(4_000, "小红书未能安全退出无法核对的图文笔记") { page ->
|
val left = awaitPage(4_000, "小红书未能安全退出当前搜索结果的笔记") { page ->
|
||||||
val detail = page.boundNote(anchor) ?: return@awaitPage null
|
if (page.boundNote(anchor) == null || page.nodes.any { it.editable && (it.focused || it.hasDraft()) }) {
|
||||||
if (detail.caption != null || page.nodes.any { it.editable && it.focused }) return@awaitPage null
|
return@awaitPage null
|
||||||
|
}
|
||||||
ui.back()
|
ui.back()
|
||||||
}
|
}
|
||||||
if (!left) throw PlatformException("小红书未确认退出无法核对的图文笔记")
|
if (!left) throw PlatformException("小红书未确认退出当前搜索结果的笔记")
|
||||||
|
selectVideoResults(keyword)
|
||||||
awaitPage(6_000, "退出小红书笔记后未核对到同一搜索结果") { page ->
|
awaitPage(6_000, "退出小红书笔记后未核对到同一搜索结果") { page ->
|
||||||
true.takeIf { page.resultList(keyword) != null }
|
true.takeIf { page.resultList(keyword) != null }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun UiPage.retainNote(card: CardIdentity, detail: NoteControls): NoteBinding =
|
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())
|
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 {
|
override fun currentVideo(): VideoContext {
|
||||||
val note = activeNote ?: throw PlatformException("请先通过小红书搜索打开笔记")
|
val note = activeNote ?: throw PlatformException("请先通过小红书搜索打开笔记")
|
||||||
return awaitPage(4_000, "小红书当前笔记已变化") { page ->
|
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.
|
// Search cards may combine the note's title and body into one preview label.
|
||||||
val compactPreview = preview.replace(layoutGaps, "")
|
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 ->
|
return visibleText.filter { it.directParent() != null }.groupBy { it.directParent() }.values.count { parts ->
|
||||||
parts.sortedBy { it.bounds.top }.zipWithNext().any { (titleNode, bodyNode) ->
|
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.left - bodyNode.bounds.left) <= 2 &&
|
||||||
abs(titleNode.bounds.right - bodyNode.bounds.right) <= 2 &&
|
abs(titleNode.bounds.right - bodyNode.bounds.right) <= 2 &&
|
||||||
bodyNode.bounds.top in titleNode.bounds.bottom..(titleNode.bounds.bottom + titleNode.bounds.height()) &&
|
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
|
} == 1
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun UiPage.boundNote(note: NoteBinding): NoteControls? = noteControls()?.takeIf {
|
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))
|
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 {
|
private fun matchesNote(page: UiPage, expected: VideoContext): Boolean {
|
||||||
val note = activeNote?.takeIf { it.video.key == expected.key && it.windowId == page.windowId } ?: return false
|
val note = activeNote?.takeIf { it.video.key == expected.key && it.windowId == page.windowId } ?: return false
|
||||||
if (page.boundNote(note) != null) return true
|
if (page.boundNote(note) != null) return true
|
||||||
|
if (note.kind != XiaohongshuNoteKind.IMAGE) return false
|
||||||
val (author, more) = page.imageNoteHeader() ?: return false
|
val (author, more) = page.imageNoteHeader() ?: return false
|
||||||
return author.text == note.author && author.hasSource(note.authorSource) && more.hasSource(note.moreSource)
|
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 {
|
private fun openNoteComments(page: UiPage, expected: VideoContext): Boolean {
|
||||||
val note = activeNote?.takeIf { it.video.key == expected.key } ?: return false
|
val note = activeNote?.takeIf { it.video.key == expected.key } ?: return false
|
||||||
val controls = page.boundNote(note) ?: return false
|
val controls = page.boundNote(note) ?: return false
|
||||||
if (page.nodes.any { it.editable && (it.focused || it.hasDraft()) }) return false
|
if (page.nodes.any { it.editable && (it.focused || it.hasDraft()) }) return false
|
||||||
val button = page.nodes.singleOrNull { node ->
|
val button = page.noteCommentButton(controls)?.takeUnless { zeroComments.matches(it.description) } ?: return false
|
||||||
node.directParent() === controls.toolbar && node.className == "android.widget.Button" &&
|
if (controls.kind == XiaohongshuNoteKind.VIDEO) {
|
||||||
commentLabel.matches(node.description) && node.isNativeClick()
|
if (!page.bounds.contains(button.bounds) || button.bounds.centerX() < page.x(.75f) ||
|
||||||
} ?: return false
|
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)
|
return ui.click(button)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun openComments(expected: VideoContext): List<String> {
|
override fun openComments(expected: VideoContext): List<String> = openCommentSurface(expected, forReceipt = false)
|
||||||
if (commentNote != null || currentVideo().key != expected.key) {
|
|
||||||
throw PlatformException("小红书当前笔记或评论区已变化")
|
override fun openCommentsForReceipt(expected: VideoContext) {
|
||||||
|
openCommentSurface(expected, forReceipt = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun openCommentSurface(expected: VideoContext, forReceipt: Boolean): List<String> {
|
||||||
|
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
|
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 {
|
return try {
|
||||||
comments.open(expected).also { commentNote = expected }
|
comments.open(expected).also { commentNote = OpenCommentNote(expected, empty = false) }
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
comments.reset()
|
comments.reset()
|
||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun scanComments(): List<CommentTarget> = comments.scan()
|
override fun scanComments(): List<CommentTarget> {
|
||||||
|
val session = commentNote
|
||||||
|
if (session?.empty != true) return comments.scan()
|
||||||
|
if (currentVideo().key != session.note.key) throw PlatformException("小红书当前笔记已变化")
|
||||||
|
return emptyList()
|
||||||
|
}
|
||||||
|
|
||||||
override fun scrollComments(): Boolean {
|
override fun scrollComments(): Boolean {
|
||||||
if (preparedReply != null) throw PlatformException("请先完成或关闭当前小红书回复草稿")
|
if (preparedReply != null) throw PlatformException("请先完成或关闭当前小红书回复草稿")
|
||||||
|
if (commentNote?.empty == true) return false
|
||||||
return comments.scroll()
|
return comments.scroll()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun prepareReply(target: CommentTarget, expectedText: String): Boolean {
|
override fun prepareReply(target: CommentTarget, expectedText: String): Boolean {
|
||||||
check(commentNote != null && preparedReply == null) { "请先确认小红书评论区和草稿状态" }
|
check(commentNote != null && preparedReply == null) { "请先确认小红书评论区和草稿状态" }
|
||||||
|
if (commentNote?.empty == true) return false
|
||||||
if (!receipt.captureBaseline(target, expectedText) || !composer.prepare(target)) return false
|
if (!receipt.captureBaseline(target, expectedText) || !composer.prepare(target)) return false
|
||||||
preparedReply = PreparedReply(target, expectedText)
|
preparedReply = PreparedReply(target, expectedText)
|
||||||
return true
|
return true
|
||||||
@@ -471,12 +584,33 @@ internal class XiaohongshuAdapter(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun confirmPendingReply(video: VideoContext, pending: PendingComment): CommentPublishResult {
|
override fun confirmPendingReply(video: VideoContext, pending: PendingComment): CommentPublishResult =
|
||||||
if (video.key != commentNote?.key || video.key != pending.videoKey) return CommentPublishResult.UNCERTAIN
|
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 target = pending.targetKey ?: return CommentPublishResult.UNCERTAIN
|
||||||
val author = pending.targetAuthor ?: return CommentPublishResult.UNCERTAIN
|
val author = pending.targetAuthor ?: return CommentPublishResult.UNCERTAIN
|
||||||
val since = pending.armedAtEpochMs ?: 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(
|
private fun confirmReceipt(
|
||||||
@@ -485,13 +619,14 @@ internal class XiaohongshuAdapter(
|
|||||||
text: String,
|
text: String,
|
||||||
photos: List<TemplatePhoto>,
|
photos: List<TemplatePhoto>,
|
||||||
armedAt: Long,
|
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()
|
if (result == CommentPublishResult.CONFIRMED && photos.isNotEmpty()) photoLibrary.cleanupStaged()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun closeComments() {
|
override fun closeComments() {
|
||||||
if (commentNote == null) return
|
val session = commentNote ?: return
|
||||||
comments.close()
|
if (!session.empty) comments.close()
|
||||||
composer.close()
|
composer.close()
|
||||||
preparedReply = null
|
preparedReply = null
|
||||||
commentNote = null
|
commentNote = null
|
||||||
@@ -531,6 +666,7 @@ internal class XiaohongshuAdapter(
|
|||||||
val likeLabel = Regex("(?:已)?点赞$COUNTER")
|
val likeLabel = Regex("(?:已)?点赞$COUNTER")
|
||||||
val favoriteLabel = Regex("(?:已)?收藏$COUNTER")
|
val favoriteLabel = Regex("(?:已)?收藏$COUNTER")
|
||||||
val commentLabel = Regex("评论$COUNTER")
|
val commentLabel = Regex("评论$COUNTER")
|
||||||
|
val zeroComments = Regex("评论\\s+0")
|
||||||
val whitespace = Regex("\\s+")
|
val whitespace = Regex("\\s+")
|
||||||
val layoutGaps = Regex("[\\s\\p{Cc}\\p{Cf}\\p{Z}]+")
|
val layoutGaps = Regex("[\\s\\p{Cc}\\p{Cf}\\p{Z}]+")
|
||||||
val expandCaption = Regex("(?:\\.{3}|…)+\\s*展开(?:全文)?$")
|
val expandCaption = Regex("(?:\\.{3}|…)+\\s*展开(?:全文)?$")
|
||||||
|
|||||||
@@ -141,8 +141,8 @@ internal class XiaohongshuComments(
|
|||||||
if (matchesNote(page, session.note) && !page.hasActiveDraft()) return@inspect true
|
if (matchesNote(page, session.note) && !page.hasActiveDraft()) return@inspect true
|
||||||
val visible = surface(page) ?: return@inspect false
|
val visible = surface(page) ?: return@inspect false
|
||||||
if (page.hasActiveDraft()) return@inspect false
|
if (page.hasActiveDraft()) return@inspect false
|
||||||
val close = page.modalCloseControl(visible)
|
val close = page.modalCloseControl(visible) ?: return@inspect false
|
||||||
if (close != null) ui.click(close) else ui.back()
|
ui.click(close)
|
||||||
}
|
}
|
||||||
if (closed != true || ui.await(4_000) {
|
if (closed != true || ui.await(4_000) {
|
||||||
ui.inspect { page -> true.takeIf { matchesNote(page, session.note) && !page.hasActiveDraft() } }
|
ui.inspect { page -> true.takeIf { matchesNote(page, session.note) && !page.hasActiveDraft() } }
|
||||||
@@ -200,7 +200,11 @@ internal class XiaohongshuComments(
|
|||||||
var bottom = current.container.bounds.bottom
|
var bottom = current.container.bounds.bottom
|
||||||
for (slot in slots.drop(start + 1)) {
|
for (slot in slots.drop(start + 1)) {
|
||||||
val gap = slot.bounds.top - bottom
|
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) {
|
if (page.parts(visible, slot, nested = false).size == 1) {
|
||||||
return XhsCommentThread(replies, complete = true, expand = null)
|
return XhsCommentThread(replies, complete = true, expand = null)
|
||||||
}
|
}
|
||||||
@@ -255,11 +259,36 @@ internal class XiaohongshuComments(
|
|||||||
node.bounds.centerX() <= x(.67f) && node.bounds.centerY() <= y(.72f)
|
node.bounds.centerX() <= x(.67f) && node.bounds.centerY() <= y(.72f)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun UiPage.commentFooter(inline: Boolean): UiNode? = nodes.singleOrNull { node ->
|
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.editable && node.bounds.centerX() <= x(.57f) && node.bounds.centerY() >= y(.72f) &&
|
||||||
(node.description == "评论框" || !inline && node.text in commentPlaceholders) &&
|
node.description == "评论框" &&
|
||||||
node.className in setOf("android.widget.TextView", "android.widget.Button", "android.view.ViewGroup")
|
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? {
|
private fun UiPage.focusedCommentFooter(list: UiNode, heading: UiNode?): UiNode? {
|
||||||
val editor = nodes.singleOrNull { it.editable && it.focused } ?: return null
|
val editor = nodes.singleOrNull { it.editable && it.focused } ?: return null
|
||||||
@@ -273,11 +302,16 @@ internal class XiaohongshuComments(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun UiPage.modalCloseControl(surface: XhsCommentSurface): UiNode? {
|
private fun UiPage.modalCloseControl(surface: XhsCommentSurface): UiNode? {
|
||||||
|
if (surface.inline || hasActiveDraft() || videoCommentFooter() == null) return null
|
||||||
val heading = surface.heading ?: 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 ->
|
return nodes.singleOrNull { node ->
|
||||||
node.isNativeClick() && node.labels().singleOrNull() in closeLabels && node.bounds.centerX() >= x(.75f) &&
|
node.directParent() === owner && node.className == "android.widget.ImageView" && node.isNativeClick() &&
|
||||||
abs(node.bounds.centerY() - heading.bounds.centerY()) <= heading.bounds.height() &&
|
node.labels().isEmpty() && node.bounds.centerX() >= x(.88f) && bounds.contains(node.bounds) &&
|
||||||
shareNearParent(heading, node, maxDepth = 3)
|
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
|
if (page.isOwn(original)) return@mapNotNull null
|
||||||
val author = original.author
|
val author = original.author
|
||||||
val body = original.body
|
val body = original.body
|
||||||
val reply = page.nodes.singleOrNull { node ->
|
val reply = page.originalReplyAction(visible, slot, original)
|
||||||
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)
|
val target = CommentTarget(identity(note.key, author.text, body.text), body.text, author.text)
|
||||||
XhsCommentRow(target, slot, reply, author, body)
|
XhsCommentRow(target, slot, reply, author, body)
|
||||||
}
|
}
|
||||||
@@ -308,6 +337,26 @@ internal class XiaohongshuComments(
|
|||||||
return candidates.filter { counts[it.target.key] == 1 }
|
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<RowParts> {
|
private fun UiPage.parts(surface: XhsCommentSurface, slot: UiNode, nested: Boolean): List<RowParts> {
|
||||||
val width = surface.viewport.width()
|
val width = surface.viewport.width()
|
||||||
val avatars = nodes.filter { node -> node.isDescendantOf(slot) && node.isNativeClick() &&
|
val avatars = nodes.filter { node -> node.isDescendantOf(slot) && node.isNativeClick() &&
|
||||||
@@ -356,27 +405,72 @@ internal class XiaohongshuComments(
|
|||||||
return candidates.map { parts ->
|
return candidates.map { parts ->
|
||||||
val detail = nodes.filter { node -> node.isDescendantOf(slot) && node.bounds.top >= parts.body.bounds.bottom &&
|
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 }
|
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 &&
|
val images = detail.filter { it.className in attachmentClasses &&
|
||||||
it.bounds.width() >= surface.viewport.width() * .105f && it.bounds.height() >= surface.viewport.width() * .09f }
|
it.bounds.width() >= surface.viewport.width() * .105f && it.bounds.height() >= surface.viewport.width() * .09f }
|
||||||
if (images.any { !it.isNativeClick() || !XhsCommentLabels.photoDescription(it.description) ||
|
.sortedWith(compareBy({ it.bounds.top }, { it.bounds.left }))
|
||||||
!surface.viewport.contains(it.bounds) }) return null
|
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
|
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)
|
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()))
|
identity(parentKey, parts.author.text, parts.body.text, images.size.toString()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun blankPhotoStrip(surface: XhsCommentSurface, slot: UiNode, body: UiNode, time: UiNode?, images: List<UiNode>): 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 {
|
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) }
|
node.labels().any(XhsCommentLabels::blocksThreadBoundary) }
|
||||||
val unique = labels.singleOrNull()
|
val unique = labels.singleOrNull()
|
||||||
val action = unique?.takeIf { node -> node.isNativeClick() && node.className in replyControlClasses &&
|
val action = unique?.let { expansionAction(surface, slot, it) }
|
||||||
surface.viewport.contains(node.bounds) && XhsCommentLabels.expandsReplies(node.labels().singleOrNull().orEmpty()) }
|
|
||||||
return Continuation(labels.isNotEmpty(), action)
|
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<String, Int> = nodes.asSequence()
|
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 &&
|
.filter { it.isDescendantOf(surface.root) && it.commentText() && it.bounds.width() >= surface.viewport.width() * .35f &&
|
||||||
surface.viewport.contains(it.bounds.centerX(), it.bounds.centerY()) }
|
surface.viewport.contains(it.bounds.centerX(), it.bounds.centerY()) }
|
||||||
@@ -395,14 +489,24 @@ internal class XiaohongshuComments(
|
|||||||
private companion object {
|
private companion object {
|
||||||
const val RECYCLER = "androidx.recyclerview.widget.RecyclerView"
|
const val RECYCLER = "androidx.recyclerview.widget.RecyclerView"
|
||||||
val noteMarkers = setOf("nickNameTV", "moreOperateIV", "matrixNickNameView", "noteContentText")
|
val noteMarkers = setOf("nickNameTV", "moreOperateIV", "matrixNickNameView", "noteContentText")
|
||||||
val commentPlaceholders = setOf("说点什么...", "说点什么…")
|
|
||||||
val closeLabels = setOf("关闭", "关闭评论", "关闭评论区")
|
|
||||||
val ownLabels = setOf("我", "我发布的评论", "我发布的回复")
|
val ownLabels = setOf("我", "我发布的评论", "我发布的回复")
|
||||||
val replyControlClasses = setOf("android.widget.TextView", "android.widget.Button")
|
val replyControlClasses = setOf("android.widget.TextView", "android.widget.Button")
|
||||||
val attachmentClasses = setOf("android.widget.ImageView", "android.view.View")
|
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 {
|
internal object XhsCommentLabels {
|
||||||
private val heading = Regex("共\\s*(\\d+)\\s*条评论")
|
private val heading = Regex("共\\s*(\\d+)\\s*条评论")
|
||||||
private val empty = setOf("暂无评论", "还没有评论")
|
private val empty = setOf("暂无评论", "还没有评论")
|
||||||
|
|||||||
@@ -6,8 +6,11 @@ import com.jieliu.app.data.PhotoLibrary
|
|||||||
import com.jieliu.app.task.TaskPlan
|
import com.jieliu.app.task.TaskPlan
|
||||||
import com.jieliu.app.task.TemplatePhoto
|
import com.jieliu.app.task.TemplatePhoto
|
||||||
import java.io.Closeable
|
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(
|
internal class XiaohongshuReplyComposer(
|
||||||
private val ui: AccessibleUi,
|
private val ui: AccessibleUi,
|
||||||
private val photos: PhotoLibrary,
|
private val photos: PhotoLibrary,
|
||||||
@@ -15,8 +18,10 @@ internal class XiaohongshuReplyComposer(
|
|||||||
) : Closeable {
|
) : Closeable {
|
||||||
private class Prepared(
|
private class Prepared(
|
||||||
val target: CommentTarget,
|
val target: CommentTarget,
|
||||||
val windowId: Int,
|
val originalWindow: Int,
|
||||||
val surface: UiNodeSource,
|
val surface: UiNodeSource,
|
||||||
|
val editorWindow: Int,
|
||||||
|
val toolbarIcons: Int,
|
||||||
val container: UiNodeSource,
|
val container: UiNodeSource,
|
||||||
val editor: UiNodeSource,
|
val editor: UiNodeSource,
|
||||||
) : Closeable {
|
) : 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 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 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 ImageRegion(val bounds: Rect, val overlay: Rect)
|
||||||
private data class DraftSnapshot(val windowId: Int, val images: List<Rect>)
|
private data class ImageSnapshot(val windowId: Int, val images: List<ImageRegion>)
|
||||||
private data class ReadyDraft(val send: UiNode, val snapshot: DraftSnapshot)
|
private data class ReadyDraft(val send: UiNode, val snapshot: ImageSnapshot)
|
||||||
|
|
||||||
private var prepared: Prepared? = null
|
private var prepared: Prepared? = null
|
||||||
|
|
||||||
@@ -47,7 +54,7 @@ internal class XiaohongshuReplyComposer(
|
|||||||
val surface = comments.surface(page) ?: throw PlatformException("小红书评论区已变化")
|
val surface = comments.surface(page) ?: throw PlatformException("小红书评论区已变化")
|
||||||
val row = comments.row(page, target.key)?.takeIf { it.target == target } ?: return@inspect null
|
val row = comments.row(page, target.key)?.takeIf { it.target == target } ?: return@inspect null
|
||||||
val reply = row.reply?.takeIf {
|
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()
|
surface.viewport.contains(it.bounds) && it.nativeClick()
|
||||||
} ?: return@inspect null
|
} ?: return@inspect null
|
||||||
if (page.hasPrivateDraft() || page.nodes.any { it.editable && (it.focused || it.hasReplyPrompt()) }) {
|
if (page.hasPrivateDraft() || page.nodes.any { it.editable && (it.focused || it.hasReplyPrompt()) }) {
|
||||||
@@ -57,24 +64,26 @@ internal class XiaohongshuReplyComposer(
|
|||||||
val anchor = surface.root.retainSource()
|
val anchor = surface.root.retainSource()
|
||||||
try {
|
try {
|
||||||
if (!ui.click(reply)) throw PlatformException("未确认小红书已打开选中评论的回复框")
|
if (!ui.click(reply)) throw PlatformException("未确认小红书已打开选中评论的回复框")
|
||||||
surface.windowId to anchor
|
Origin(surface.windowId, if (surface.inline) 5 else 6, anchor)
|
||||||
} catch (error: Throwable) {
|
} catch (error: Throwable) {
|
||||||
anchor.close()
|
anchor.close()
|
||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
} ?: return false
|
} ?: return false
|
||||||
|
|
||||||
val (windowId, anchor) = opened
|
val (windowId, toolbarIcons, anchor) = opened
|
||||||
try {
|
try {
|
||||||
prepared = awaitPage(5_000, "无法核对小红书回复对象或空白回复框") { page ->
|
prepared = awaitPage(5_000, "无法核对小红书回复对象或空白回复框") { page ->
|
||||||
if (!page.matchesTarget(target, windowId, anchor)) return@awaitPage null
|
// Only the exact native original-row action above may establish this new reply window.
|
||||||
val composer = page.openedComposer(target) ?: return@awaitPage null
|
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
|
val thumbnails = page.draftThumbnails(composer) ?: return@awaitPage null
|
||||||
if (composer.editor.hasDraft() || thumbnails.isNotEmpty()) {
|
if (composer.editor.hasDraft() || thumbnails.isNotEmpty()) {
|
||||||
throw PlatformException("小红书回复框已有草稿或附件,请处理后继续")
|
throw PlatformException("小红书回复框已有草稿或附件,请处理后继续")
|
||||||
}
|
}
|
||||||
if (!composer.editor.isStillBlankAndFocused()) return@awaitPage null
|
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
|
return true
|
||||||
} finally {
|
} finally {
|
||||||
@@ -96,7 +105,10 @@ internal class XiaohongshuReplyComposer(
|
|||||||
if (!blank) throw PlatformException("小红书回复框已变化或已有草稿,未修改内容")
|
if (!blank) throw PlatformException("小红书回复框已变化或已有草稿,未修改内容")
|
||||||
|
|
||||||
val references = if (attachments.isEmpty()) emptyList() else {
|
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 {
|
val staged = if (references.isEmpty()) null else {
|
||||||
photos.cleanupStaged()
|
photos.cleanupStaged()
|
||||||
@@ -117,7 +129,7 @@ internal class XiaohongshuReplyComposer(
|
|||||||
page.readyDraft(session, text, references.size)?.snapshot
|
page.readyDraft(session, text, references.size)?.snapshot
|
||||||
}
|
}
|
||||||
if (references.isNotEmpty()) {
|
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
|
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
|
val session = prepared?.takeIf { it.sendAttempted } ?: return false
|
||||||
return ui.await(3_000) {
|
return ui.await(3_000) {
|
||||||
ui.inspect { page ->
|
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
|
if (page.hasPrivateDraft() || page.nodes.any { it.editable && (it.focused || it.hasReplyPrompt()) }) return@inspect null
|
||||||
val oldContainer = page.nodes.singleOrNull { it.hasSource(session.container) }
|
true.takeIf { page.nodes.none { it.replyCue(session.target) } }
|
||||||
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
|
} == true
|
||||||
}
|
}
|
||||||
@@ -160,48 +165,56 @@ internal class XiaohongshuReplyComposer(
|
|||||||
prepared = null
|
prepared = null
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun attach(session: Prepared, album: String, references: List<PhotoPixels>, beforeAttach: () -> Unit) {
|
private fun attach(session: Prepared, album: String, references: List<AttachmentReference>, beforeAttach: () -> Unit) {
|
||||||
ui.pace()
|
ui.pace()
|
||||||
val pickerOpened = ui.inspect { page ->
|
val pickerOpened = ui.inspect { page ->
|
||||||
val composer = page.checkedComposer(session) ?: return@inspect false
|
val composer = page.checkedComposer(session) ?: return@inspect false
|
||||||
if (!composer.editor.isStillBlankAndFocused() || page.draftThumbnails(composer)?.isEmpty() != true) 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(composer.toolbar.album)
|
||||||
ui.click(action)
|
|
||||||
} == true
|
} == true
|
||||||
if (!pickerOpened) throw PlatformException("小红书未打开已核对回复框的相册")
|
if (!pickerOpened) throw PlatformException("小红书未打开已核对回复框的相册")
|
||||||
|
|
||||||
val openAlbumList = awaitPage(6_000, "小红书相册页或相册分类控件不可核对") { page ->
|
val (pickerWindow, openAlbumList) = awaitPage(6_000, "小红书相册页或相册分类控件不可核对") { page ->
|
||||||
if (page.albumHeading(setOf(album)) != null) return@awaitPage false
|
if (page.windowId == session.editorWindow || page.windowId == session.originalWindow) return@awaitPage null
|
||||||
val heading = page.albumHeading(pickerHeadings) ?: return@awaitPage null
|
if (page.albumHeading(album) != null) return@awaitPage page.windowId to false
|
||||||
val toggle = heading.nativeAction() ?: return@awaitPage null
|
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("小红书未接受相册分类操作")
|
if (!ui.click(toggle)) throw PlatformException("小红书未接受相册分类操作")
|
||||||
true
|
page.windowId to true
|
||||||
}
|
}
|
||||||
if (openAlbumList) {
|
if (openAlbumList) {
|
||||||
awaitPage(6_000, "小红书相册没有唯一的本次专用相册") { page ->
|
awaitPage(6_000, "小红书相册没有唯一的本次专用相册") { page ->
|
||||||
|
if (page.windowId == pickerWindow || page.windowId == session.editorWindow || page.windowId == session.originalWindow) {
|
||||||
|
return@awaitPage null
|
||||||
|
}
|
||||||
val label = page.nodes.singleOrNull {
|
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
|
} ?: 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("小红书未打开本次专用相册")
|
if (!ui.click(item)) throw PlatformException("小红书未打开本次专用相册")
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
val empty = awaitPage(6_000, "小红书专用相册未完整显示所有可多选图片") { page ->
|
val empty = awaitPage(6_000, "小红书专用相册未完整显示所有可多选图片") { page ->
|
||||||
|
if (page.windowId != pickerWindow) return@awaitPage null
|
||||||
val picker = page.picker(album, references.size) ?: return@awaitPage null
|
val picker = page.picker(album, references.size) ?: return@awaitPage null
|
||||||
if (picker.count != 0 || picker.tiles.any { it.ordinal != 0 }) {
|
if (picker.count != 0 || picker.tiles.any { it.ordinal != 0 }) {
|
||||||
throw PlatformException("小红书相册已有选中图片,未修改选择")
|
throw PlatformException("小红书相册已有选中图片,未修改选择")
|
||||||
}
|
}
|
||||||
picker.snapshot(page.windowId)
|
picker.snapshot(page.windowId)
|
||||||
}
|
}
|
||||||
val crops = ui.screenshotPhotos(empty.windowId, empty.images)
|
val crops = captureVisibleImages(empty)
|
||||||
?.takeIf { it.size == references.size } ?: throw PlatformException("无法核对小红书专用相册的全部缩略图")
|
?.takeIf { it.size == references.size } ?: throw PlatformException("无法核对小红书专用相册的全部缩略图")
|
||||||
val order = references.map { reference ->
|
val order = pickerAttachmentOrder(references, crops)
|
||||||
crops.indices.singleOrNull { PublishedPhotoMatcher.matches(reference, crops[it]) }
|
|
||||||
?: throw PlatformException("小红书专用相册中的图片无法唯一对应本次附件")
|
?: throw PlatformException("小红书专用相册中的图片无法唯一对应本次附件")
|
||||||
}
|
|
||||||
if (order.toSet().size != references.size) throw PlatformException("小红书专用相册出现重复图片匹配")
|
|
||||||
|
|
||||||
val selected = MutableList(references.size) { 0 }
|
val selected = MutableList(references.size) { 0 }
|
||||||
for ((index, tileIndex) in order.withIndex()) {
|
for ((index, tileIndex) in order.withIndex()) {
|
||||||
@@ -232,13 +245,34 @@ internal class XiaohongshuReplyComposer(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun verifyPhotos(references: List<PhotoPixels>, windowId: Int, bounds: List<Rect>, failure: String) {
|
private fun verifyPhotos(references: List<AttachmentReference>, snapshot: ImageSnapshot, failure: String) {
|
||||||
val crops = ui.screenshotPhotos(windowId, bounds) ?: throw PlatformException(failure)
|
val crops = captureVisibleImages(snapshot) ?: throw PlatformException(failure)
|
||||||
if (crops.size != references.size || references.indices.any { !PublishedPhotoMatcher.matches(references[it], crops[it]) }) {
|
if (matchedAttachmentDigests(references, crops, PublishedPhotoMatcher::matchesXhsDraft) !=
|
||||||
|
references.map(AttachmentReference::digest)) {
|
||||||
throw PlatformException(failure)
|
throw PlatformException(failure)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun captureVisibleImages(snapshot: ImageSnapshot): List<PhotoPixels>? {
|
||||||
|
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 {
|
private fun UiPage.matchesTarget(target: CommentTarget, windowId: Int, surfaceSource: UiNodeSource): Boolean {
|
||||||
val surface = comments.surface(this) ?: return false
|
val surface = comments.surface(this) ?: return false
|
||||||
return this.windowId == windowId && surface.windowId == windowId && surface.root.hasSource(surfaceSource) &&
|
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 {
|
private fun UiPage.hasPrivateDraft(): Boolean = nodes.any {
|
||||||
it.editable && it.hasDraft() || it.labels().any(removeActions::contains) ||
|
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? {
|
private fun UiPage.openedComposer(target: CommentTarget, toolbarIcons: Int): Composer? {
|
||||||
val row = comments.row(this, target.key)?.takeIf { it.target == target } ?: return null
|
val editor = nodes.singleOrNull { it.className == EDIT_TEXT && it.canEdit() && it.focused &&
|
||||||
val editor = nodes.singleOrNull { it.canEdit() && it.focused && it.bounds.centerY() >= y(.40f) &&
|
it.bounds.centerY() >= y(.40f) && it.bounds.width() >= bounds.width() * .65f && it.replyCue(target) }
|
||||||
it.bounds.width() >= bounds.width() * .25f } ?: return null
|
?: return null
|
||||||
|
val toolbar = replyToolbar(editor, toolbarIcons) ?: return null
|
||||||
val container = generateSequence(editor.directParent()) { it.directParent() }.take(4).firstOrNull { scope ->
|
val container = generateSequence(editor.directParent()) { it.directParent() }.take(4).firstOrNull { scope ->
|
||||||
scope.bounds.contains(editor.bounds) && scope.bounds.height() <= bounds.height() * .50f &&
|
scope.bounds.contains(editor.bounds) && scope.bounds.height() <= bounds.height() * .50f &&
|
||||||
scope !== row.container && !row.container.isDescendantOf(scope) &&
|
toolbar.root.isDescendantOf(scope) && nodes.none { it !== editor && it.editable && it.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 null
|
||||||
return Composer(editor, container)
|
return Composer(editor, container, toolbar)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun UiPage.checkedComposer(session: Prepared): Composer? {
|
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 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
|
it.isDescendantOf(container) && container.bounds.contains(it.bounds) } ?: return null
|
||||||
if (nodes.any { it !== editor && it.editable && it.focused }) return null
|
if (nodes.any { it !== editor && it.editable && it.focused } || !editor.replyCue(session.target)) return null
|
||||||
if (!editor.replyCue(session.target) && editor.hint.isNotEmpty() && !editor.hasDraft() &&
|
val toolbar = replyToolbar(editor, session.toolbarIcons)?.takeIf { it.root.isDescendantOf(container) } ?: return null
|
||||||
nodes.none { it.isDescendantOf(container) && it.replyCue(session.target) }) return null
|
return Composer(editor, container, toolbar)
|
||||||
return Composer(editor, container)
|
}
|
||||||
|
|
||||||
|
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? {
|
private fun UiPage.readyDraft(session: Prepared, text: String, count: Int): ReadyDraft? {
|
||||||
@@ -280,81 +332,92 @@ internal class XiaohongshuReplyComposer(
|
|||||||
val editor = composer.editor
|
val editor = composer.editor
|
||||||
if (editor.text != text || !editor.hasCurrentFocusedText(text) { matchesReplyCue(it, session.target) }) return null
|
if (editor.text != text || !editor.hasCurrentFocusedText(text) { matchesReplyCue(it, session.target) }) return null
|
||||||
val previews = draftThumbnails(composer)?.takeIf { it.size == count } ?: return null
|
val previews = draftThumbnails(composer)?.takeIf { it.size == count } ?: return null
|
||||||
val send = composerActions(composer, sendActions).singleOrNull { action ->
|
val send = composer.toolbar.send.takeIf { it.nativeClick() } ?: return null
|
||||||
action.bounds.centerX() > editor.bounds.centerX() &&
|
return ReadyDraft(send, ImageSnapshot(windowId, previews))
|
||||||
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()
|
private fun UiPage.draftThumbnails(composer: Composer): List<ImageRegion>? {
|
||||||
.filter { !it.editable && it.isDescendantOf(composer.container) && it.labels().any(labels::contains) }
|
val toolbar = composer.toolbar
|
||||||
.mapNotNull { it.nativeAction() }
|
val lower = nodes.filter { it.isDescendantOf(composer.container) && it.className == IMAGE_VIEW &&
|
||||||
.filter { it.isDescendantOf(composer.container) && composer.container.bounds.contains(it.bounds) }
|
it.bounds.centerY() > toolbar.album.bounds.bottom && !it.isDescendantOf(toolbar.root) }
|
||||||
.distinct().toList()
|
if (lower.isEmpty()) return emptyList()
|
||||||
|
if (lower.any { !it.nativeClick() || !composer.container.bounds.contains(it.bounds) || !bounds.contains(it.bounds) }) return null
|
||||||
private fun UiPage.draftThumbnails(composer: Composer): List<UiNode>? {
|
val cells = lower.filter { abs(it.bounds.width() - it.bounds.height()) <= 2 &&
|
||||||
val scoped = nodes.filter { it.isDescendantOf(composer.container) }
|
it.bounds.width() >= toolbar.album.bounds.width() && it.bounds.top >= toolbar.album.bounds.bottom }
|
||||||
val removals = scoped.filter { it.labels().any(removeActions::contains) }.mapNotNull { it.nativeAction() }.distinct()
|
.sortedBy { it.bounds.left }
|
||||||
val threshold = maxOf(24, composer.editor.bounds.height() / 2)
|
if (cells.isEmpty()) return null
|
||||||
val previews = scoped.filter { node ->
|
val first = cells.first().bounds
|
||||||
node.isImage() && node.bounds.width() >= threshold && node.bounds.height() >= threshold &&
|
if (cells.any { !sameSize(it.bounds, first) || abs(it.bounds.top - first.top) > 2 }) return null
|
||||||
node.labels().none { it in imageActions || it in removeActions || it in composerIcons }
|
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<ImageRegion>()
|
||||||
|
val usedRemovals = mutableSetOf<UiNode>()
|
||||||
|
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) ||
|
if (usedRemovals.size != removals.size || found.isEmpty() || found.size > TaskPlan.MAX_TEMPLATE_PHOTOS) return null
|
||||||
!bounds.contains(it.bounds) }) return null
|
if (found.size != cells.size - 1 && found.size != TaskPlan.MAX_TEMPLATE_PHOTOS) return null
|
||||||
val pairedRemovals = previews.map { it.previewRemoval(removals) ?: return null }
|
return found
|
||||||
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? {
|
private fun UiPage.albumHeading(label: String): UiNode? {
|
||||||
val parent = directParent() ?: return null
|
val hasExit = nodes.count { it.className == IMAGE_VIEW && it.bounds.centerY() < y(.24f) &&
|
||||||
return removals.singleOrNull { it.directParent() === parent && bounds.contains(it.bounds.centerX(), it.bounds.centerY()) }
|
it.bounds.centerX() < x(.23f) && it.labels().contains("关闭") && it.nativeClick() } == 1
|
||||||
}
|
|
||||||
|
|
||||||
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
|
if (!hasExit) return null
|
||||||
return nodes.singleOrNull { !it.editable && it.bounds.centerY() < y(.24f) &&
|
return nodes.singleOrNull { it.className == TEXT_VIEW && !it.editable && it.bounds.centerY() < y(.24f) &&
|
||||||
it.bounds.centerX() in x(.22f)..x(.78f) && it.labels().any(labels::contains) }
|
it.bounds.centerX() in x(.22f)..x(.78f) && it.text == label }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun UiPage.picker(album: String, expected: Int): Picker? {
|
private fun UiPage.picker(album: String, expected: Int): Picker? {
|
||||||
val heading = albumHeading(setOf(album)) ?: return null
|
val heading = albumHeading(album) ?: return null
|
||||||
val doneLabel = nodes.singleOrNull { node -> !node.editable && node.bounds.centerY() > y(.70f) &&
|
val done = nodes.singleOrNull { node -> node.className == TEXT_VIEW && node.nativeClick() &&
|
||||||
node.labels().any { selectionCount.matches(it.filterNot(Char::isWhitespace)) } } ?: return null
|
node.bounds.centerY() > y(.80f) && node.bounds.centerX() > x(.74f) &&
|
||||||
val match = doneLabel.labels().mapNotNull { selectionCount.matchEntire(it.filterNot(Char::isWhitespace)) }
|
selectionCount.matches(node.text.filterNot(Char::isWhitespace)) } ?: return null
|
||||||
.singleOrNull() ?: 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 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
|
// The picker contains nested RecyclerViews. Bind all tiles to their innermost common gallery.
|
||||||
val grid = nodes.singleOrNull { it.className in photoGridClasses && it.bounds.top >= heading.bounds.bottom &&
|
val images = nodes.filter { it.className == IMAGE_VIEW && it.bounds.width() >= bounds.width() * .15f &&
|
||||||
it.bounds.bottom <= done.bounds.bottom && it.bounds.width() >= bounds.width() * .60f } ?: return null
|
abs(it.bounds.width() - it.bounds.height()) <= 2 && it.bounds.top >= heading.bounds.bottom &&
|
||||||
val images = nodes.filter { it.isDescendantOf(grid) && it.isImage() && it.bounds.width() >= bounds.width() * .15f &&
|
it.bounds.bottom <= done.bounds.top && bounds.contains(it.bounds) && it.nearestGallery() != null }
|
||||||
it.bounds.height() >= bounds.width() * .15f && grid.bounds.contains(it.bounds) && bounds.contains(it.bounds) }
|
|
||||||
if (images.size != expected) return 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 tiles = images.map { image ->
|
||||||
val parent = image.directParent() ?: return null
|
val parent = image.directParent() ?: return null
|
||||||
val select = nodes.singleOrNull { it.directParent() === parent && image.bounds.contains(it.bounds) && it.nativeClick() &&
|
val select = nodes.singleOrNull { it.directParent() === parent && it.className == "android.widget.FrameLayout" &&
|
||||||
it.selectionOrdinal() != null } ?: return null
|
image.bounds.contains(it.bounds) && it.nativeClick() && it.labels().isEmpty() &&
|
||||||
AlbumTile(image, select, select.selectionOrdinal() ?: return null)
|
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<AlbumTile> { it.image.bounds.top }.thenBy { it.image.bounds.left })
|
}.sortedWith(compareBy<AlbumTile> { it.image.bounds.top }.thenBy { it.image.bounds.left })
|
||||||
if (tiles.map(AlbumTile::select).distinct().size != expected) return null
|
if (tiles.map(AlbumTile::select).distinct().size != expected) return null
|
||||||
return Picker(tiles, done, count)
|
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<Int>, 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<Int>, count: Int): Boolean =
|
||||||
this.count == count && snapshot(windowId) == expected && tiles.map(AlbumTile::ordinal) == selected
|
this.count == count && snapshot(windowId) == expected && tiles.map(AlbumTile::ordinal) == selected
|
||||||
|
|
||||||
private fun UiNode.selectionOrdinal(): Int? {
|
private fun UiPage.selectionOrdinal(select: UiNode): Int? {
|
||||||
val values = labels().mapNotNull { label ->
|
val marks = nodes.filter { it.isDescendantOf(select) && it.className == TEXT_VIEW && !it.clickable &&
|
||||||
if (!selected && label in unselectedLabels) 0 else ordinalLabel.matchEntire(label.filterNot(Char::isWhitespace))
|
select.bounds.contains(it.bounds) && it.text.toIntOrNull()?.let { number -> number in 1..TaskPlan.MAX_TEMPLATE_PHOTOS } == true }
|
||||||
?.groupValues?.get(1)?.toIntOrNull()
|
if (!select.selected) return 0.takeIf { marks.isEmpty() }
|
||||||
}.distinct()
|
return marks.singleOrNull()?.takeIf { it.selected }?.text?.toIntOrNull()
|
||||||
return values.singleOrNull()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun UiNode.replyCue(target: CommentTarget): Boolean = sequenceOf(hint, description, text.takeIf { !editable || showingHint }.orEmpty())
|
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
|
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.canEdit() = enabled && editable && supports(AccessibilityNodeInfo.ACTION_SET_TEXT)
|
||||||
private fun UiNode.nativeClick() = enabled && !editable && supports(AccessibilityNodeInfo.ACTION_CLICK)
|
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 sameSize(first: Rect, second: Rect) =
|
||||||
private fun UiNode.isImage() = className == "android.widget.ImageView" ||
|
abs(first.width() - second.width()) <= 2 && abs(first.height() - second.height()) <= 2
|
||||||
className == "android.view.View" && labels().any(imageLabels::contains)
|
|
||||||
|
|
||||||
private fun <T : Any> awaitPage(timeout: Long, failure: String, read: (UiPage) -> T?): T =
|
private fun <T : Any> awaitPage(timeout: Long, failure: String, read: (UiPage) -> T?): T =
|
||||||
ui.await(timeout) { ui.inspect(read) } ?: throw PlatformException(failure)
|
ui.await(timeout) { ui.inspect(read) } ?: throw PlatformException(failure)
|
||||||
|
|
||||||
private companion object {
|
private companion object {
|
||||||
val sendActions = setOf("发送", "发送回复", "发送评论")
|
const val IMAGE_VIEW = "android.widget.ImageView"
|
||||||
val imageActions = setOf("相册", "插入图片", "添加图片", "选择图片")
|
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 removeActions = setOf("删除图片", "移除图片", "删除照片", "移除照片")
|
||||||
val composerIcons = setOf("发送", "表情", "表情包", "拍照", "话题", "@")
|
|
||||||
val previewLabels = setOf("图片预览", "照片预览")
|
val previewLabels = setOf("图片预览", "照片预览")
|
||||||
val imageLabels = setOf("图片", "照片", "图片预览", "照片预览", "图片缩略图", "照片缩略图")
|
val selectionCount = Regex("""完成(?:\(([0-9]+)\))?""")
|
||||||
val pickerExit = setOf("返回", "关闭", "取消")
|
}
|
||||||
val pickerHeadings = setOf("相册", "最近项目", "全部照片", "全部图片", "所有照片", "最近")
|
}
|
||||||
val photoGridClasses = setOf("androidx.recyclerview.widget.RecyclerView", "android.widget.GridView")
|
|
||||||
val unselectedLabels = setOf("选择", "未选中", "未选择")
|
private data class AttachmentReference(val digest: String, val pixels: PhotoPixels)
|
||||||
val selectionCount = Regex("""(?:完成|确定|添加)(?:[((]([0-9]+)(?:/[0-9]+)?[))])?""")
|
|
||||||
val ordinalLabel = Regex("""(?:已选中|已选择|第)?([1-9])(?:张图片|张)?""")
|
private fun pickerAttachmentOrder(references: List<AttachmentReference>, crops: List<PhotoPixels>): List<Int>? {
|
||||||
|
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<AttachmentReference>,
|
||||||
|
crops: List<PhotoPixels>,
|
||||||
|
matches: (PhotoPixels, PhotoPixels) -> Boolean,
|
||||||
|
): List<String>? {
|
||||||
|
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()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,29 +1,44 @@
|
|||||||
package com.jieliu.app.platform
|
package com.jieliu.app.platform
|
||||||
|
|
||||||
import android.graphics.Rect
|
import android.graphics.Rect
|
||||||
|
import android.view.accessibility.AccessibilityNodeInfo
|
||||||
import com.jieliu.app.data.PhotoLibrary
|
import com.jieliu.app.data.PhotoLibrary
|
||||||
import com.jieliu.app.task.TemplatePhoto
|
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. */
|
/** Reads one original comment thread. No editor activation, input, or submission is performed here. */
|
||||||
internal class XiaohongshuReplyReceipt(
|
internal class XiaohongshuReplyReceipt(
|
||||||
private val ui: AccessibleUi,
|
private val ui: AccessibleUi,
|
||||||
private val photos: PhotoLibrary,
|
private val photos: PhotoLibrary,
|
||||||
private val comments: XiaohongshuComments,
|
private val comments: XiaohongshuComments,
|
||||||
|
private val diagnostic: (String) -> Unit = {},
|
||||||
) {
|
) {
|
||||||
private data class SurfaceKey(val windowId: Int, val inline: Boolean)
|
private data class SurfaceKey(val windowId: Int, val inline: Boolean)
|
||||||
private data class OriginalComment(val key: String, val author: String)
|
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 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 Baseline(val stamp: ThreadStamp, val parentVisible: Boolean, val authorTop: Int, val bodies: List<String>)
|
||||||
private data class VisibleReceipt(val identity: String, val body: Rect, val photos: List<Rect>)
|
private data class VisibleReceipt(val identity: String, val originalBody: Rect, val body: Rect, val photos: List<Rect>, 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<String>()
|
||||||
|
|
||||||
|
fun record(event: String) {
|
||||||
|
if (seen.add(event)) emit(event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fun captureBaseline(target: CommentTarget, expectedText: String): Boolean {
|
fun captureBaseline(target: CommentTarget, expectedText: String): Boolean {
|
||||||
if (target.key.isBlank() || target.author.isBlank() || expectedText.isBlank()) return false
|
if (target.key.isBlank() || target.author.isBlank() || expectedText.isBlank()) return false
|
||||||
val original = OriginalComment(target.key, target.author)
|
val original = OriginalComment(target.key, target.author)
|
||||||
val scope = findSurface() ?: return false
|
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) {
|
val baseline = ui.await(THREAD_WAIT_MS) {
|
||||||
readThread(scope, original) { surface, parent, thread ->
|
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
|
} ?: return false
|
||||||
// A missing own badge cannot turn an already visible identical body into evidence of a new reply.
|
// 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.none(String::isBlank) &&
|
||||||
baseline.stamp.replyIds.distinct().size == baseline.stamp.replyIds.size
|
baseline.stamp.replyIds.distinct().size == baseline.stamp.replyIds.size
|
||||||
}
|
}
|
||||||
if (pageIndex == MAX_EXPANSIONS || !expandThread(scope, original, baseline.stamp)) 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
|
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
|
return false
|
||||||
}
|
}
|
||||||
@@ -45,34 +76,60 @@ internal class XiaohongshuReplyReceipt(
|
|||||||
text: String,
|
text: String,
|
||||||
photos: List<TemplatePhoto>,
|
photos: List<TemplatePhoto>,
|
||||||
armedAt: Long,
|
armedAt: Long,
|
||||||
|
fromStart: Boolean,
|
||||||
): CommentPublishResult {
|
): CommentPublishResult {
|
||||||
|
val diagnostics = Diagnostics(diagnostic)
|
||||||
|
diagnostics.record("小红书开始回查回复")
|
||||||
if (targetKey.isBlank() || author.isBlank() || text.isBlank() || !validXhsReceiptAge(armedAt, System.currentTimeMillis())) {
|
if (targetKey.isBlank() || author.isBlank() || text.isBlank() || !validXhsReceiptAge(armedAt, System.currentTimeMillis())) {
|
||||||
|
diagnostics.record("小红书回查缺少回复记录或已超过核对时限")
|
||||||
return CommentPublishResult.UNCERTAIN
|
return CommentPublishResult.UNCERTAIN
|
||||||
}
|
}
|
||||||
val original = OriginalComment(targetKey, author)
|
val original = OriginalComment(targetKey, author)
|
||||||
val references = this.photos.readReceiptPixels(photos) ?: return CommentPublishResult.UNCERTAIN
|
val references = this.photos.readReceiptPixels(photos) ?: run {
|
||||||
val scope = findSurface() ?: return CommentPublishResult.UNCERTAIN
|
diagnostics.record("小红书回查无法读取原始附件")
|
||||||
if (!seekOriginal(scope, original)) return CommentPublishResult.UNCERTAIN
|
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 expansions = 0
|
||||||
var revisitedOriginal = false
|
var revisitedOriginal = false
|
||||||
val opened = mutableSetOf<ThreadStamp>()
|
val opened = mutableSetOf<ThreadStamp>()
|
||||||
|
val ownershipChecks = mutableSetOf<String>()
|
||||||
repeat(MAX_RECEIPT_PASSES) {
|
repeat(MAX_RECEIPT_PASSES) {
|
||||||
if (ui.await(RECEIPT_WAIT_MS) { verifiedReceipt(scope, original, text, references, armedAt) } == true) {
|
val confirmed = ui.await(RECEIPT_WAIT_MS) {
|
||||||
return CommentPublishResult.CONFIRMED
|
verifiedReceipt(scope, original, text, references, armedAt, ownershipChecks, diagnostics)
|
||||||
}
|
}
|
||||||
|
if (confirmed == true) return CommentPublishResult.CONFIRMED
|
||||||
val seen = readThread(scope, original) { _, _, thread -> stamp(thread) }
|
val seen = readThread(scope, original) { _, _, thread -> stamp(thread) }
|
||||||
if (seen == null) {
|
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
|
revisitedOriginal = true
|
||||||
} else if (seen.expandLabels != null && expansions < MAX_EXPANSIONS && seen !in opened &&
|
} else if (seen.expandLabels != null && expansions < MAX_EXPANSIONS && seen !in opened) {
|
||||||
expandThread(scope, original, seen)
|
diagnostics.record("小红书回查已找到原评论的展开控件")
|
||||||
) {
|
when (expandThread(scope, original, seen, diagnostics)) {
|
||||||
|
true -> {
|
||||||
expansions++
|
expansions++
|
||||||
opened.add(seen)
|
opened.add(seen)
|
||||||
ui.await(THREAD_WAIT_MS) { changedThread(scope, original, seen) }
|
if (ui.await(THREAD_WAIT_MS) { changedThread(scope, original, seen) } != true) {
|
||||||
} else if (!bringLowerReplyIntoView(scope, original)) {
|
diagnostics.record("小红书回查展开后未读取到线程变化")
|
||||||
return CommentPublishResult.UNCERTAIN
|
}
|
||||||
|
}
|
||||||
|
false -> if (!bringLowerReplyIntoView(scope, original)) return CommentPublishResult.UNCERTAIN
|
||||||
|
null -> Unit
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
diagnostics.record("小红书回查未找到可展开的回复控件")
|
||||||
|
if (!bringLowerReplyIntoView(scope, original)) return CommentPublishResult.UNCERTAIN
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return CommentPublishResult.UNCERTAIN
|
return CommentPublishResult.UNCERTAIN
|
||||||
@@ -84,72 +141,201 @@ internal class XiaohongshuReplyReceipt(
|
|||||||
text: String,
|
text: String,
|
||||||
references: List<PhotoPixels>,
|
references: List<PhotoPixels>,
|
||||||
armedAt: Long,
|
armedAt: Long,
|
||||||
|
ownershipChecks: MutableSet<String>,
|
||||||
|
diagnostics: Diagnostics,
|
||||||
): Boolean? {
|
): Boolean? {
|
||||||
val before = receiptRow(scope, original, text, references.size, armedAt) ?: return null
|
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) ?: return null
|
val captured = if (references.isEmpty()) emptyList() else ui.screenshotPhotos(scope.windowId, before.photos) ?: run {
|
||||||
val after = receiptRow(scope, original, text, references.size, armedAt) ?: return null
|
diagnostics.record("小红书回查未能截取已发布的图片")
|
||||||
return true.takeIf {
|
return null
|
||||||
before == after && captured.size == references.size &&
|
|
||||||
references.indices.all { PublishedPhotoMatcher.matches(references[it], captured[it]) }
|
|
||||||
}
|
}
|
||||||
|
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? =
|
private fun receiptRow(
|
||||||
readThread(scope, original) { surface, parent, thread ->
|
scope: SurfaceKey,
|
||||||
|
original: OriginalComment,
|
||||||
|
text: String,
|
||||||
|
photoCount: Int,
|
||||||
|
armedAt: Long,
|
||||||
|
diagnostics: Diagnostics? = null,
|
||||||
|
): VisibleReceipt? = readThread(scope, original) { surface, parent, thread ->
|
||||||
val viewport = surface.viewport
|
val viewport = surface.viewport
|
||||||
if (!contains(viewport, parent.body.bounds)) return@readThread null
|
if (!contains(viewport, parent.body.bounds)) return@readThread null
|
||||||
val reply = thread.replies.singleOrNull { it.own && it.body.text == text } ?: return@readThread null
|
val reply = thread.replies.singleOrNull { it.body.text == text } ?: run {
|
||||||
val time = reply.timeLabel ?: return@readThread null
|
diagnostics?.record("小红书回查暂未读取到唯一匹配的回复正文")
|
||||||
|
return@readThread null
|
||||||
|
}
|
||||||
|
diagnostics?.record("小红书回查已找到匹配的回复正文")
|
||||||
|
val time = reply.timeLabel
|
||||||
if (reply.identity.isBlank() || thread.replies.count { it.identity == reply.identity } != 1 ||
|
if (reply.identity.isBlank() || thread.replies.count { it.identity == reply.identity } != 1 ||
|
||||||
!contains(viewport, reply.body.bounds) || !matchesXhsReceiptTime(time, armedAt, System.currentTimeMillis())
|
!contains(viewport, reply.body.bounds) || time == null || !matchesXhsReceiptTime(time, armedAt, System.currentTimeMillis())
|
||||||
) return@readThread null
|
) {
|
||||||
|
diagnostics?.record("小红书回查无法核对回复位置、唯一性或发布时间")
|
||||||
|
return@readThread null
|
||||||
|
}
|
||||||
|
|
||||||
val crops = reply.photos.map { Rect(it.bounds) }
|
val crops = reply.photos.map { Rect(it.bounds) }
|
||||||
if (crops.size != photoCount || crops.any {
|
if (crops.size != photoCount || crops.any {
|
||||||
!contains(viewport, it) || it.top <= viewport.top || it.bottom >= viewport.bottom || Rect.intersects(reply.body.bounds, it)
|
!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]) } }
|
} || 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)
|
diagnostics?.record("小红书回查无法核对已发布图片的数量或位置")
|
||||||
|
return@readThread null
|
||||||
|
}
|
||||||
|
VisibleReceipt(reply.identity, Rect(parent.body.bounds), Rect(reply.body.bounds), crops, reply.own)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun seekOriginal(scope: SurfaceKey, original: OriginalComment, forwardLimit: Int = MAX_FORWARD_SCROLLS): Boolean {
|
private fun inspectRole(scope: SurfaceKey, body: Rect, isSameReceipt: () -> Boolean): CommentRole? {
|
||||||
if (originalVisible(scope, original)) return true
|
if (!isSameReceipt()) return null
|
||||||
repeat(MAX_REVERSE_SCROLLS + forwardLimit) { index ->
|
val x = body.exactCenterX()
|
||||||
if (!moveWithinSurface(scope, towardEarlier = index < MAX_REVERSE_SCROLLS)) return false
|
val y = body.exactCenterY()
|
||||||
if (ui.await(RECEIPT_WAIT_MS) { true.takeIf { originalVisible(scope, original) } } == true) return true
|
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
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun originalVisible(scope: SurfaceKey, original: OriginalComment): Boolean =
|
private fun originalPosition(scope: SurfaceKey, original: OriginalComment): Rect? =
|
||||||
readOriginal(scope, original) { _, _ -> true } == true
|
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 ->
|
private fun awaitStableOriginal(scope: SurfaceKey, original: OriginalComment, diagnostics: Diagnostics): Boolean {
|
||||||
val area = matchingSurface(page, scope)?.viewport ?: return@inspect false
|
var previous: Rect? = null
|
||||||
if (area.height() < 100) return@inspect false
|
var stationary = 0
|
||||||
val x = area.exactCenterX()
|
val stable = ui.await(THREAD_WAIT_MS) {
|
||||||
val nearTop = area.top + area.height() * .25f
|
val current = originalPosition(scope, original)
|
||||||
val nearBottom = area.top + area.height() * .76f
|
if (current != null) diagnostics.record("小红书回查已看到原评论")
|
||||||
if (towardEarlier) ui.touch(x, nearTop, x, nearBottom, 360L)
|
stationary = if (current != null && current == previous) stationary + 1 else 0
|
||||||
else ui.touch(x, nearBottom, x, nearTop, 360L)
|
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
|
} == true
|
||||||
|
|
||||||
private fun bringLowerReplyIntoView(scope: SurfaceKey, original: OriginalComment): Boolean =
|
private fun bringLowerReplyIntoView(scope: SurfaceKey, original: OriginalComment): Boolean =
|
||||||
readOriginal(scope, original) { surface, parent ->
|
readOriginal(scope, original) { surface, parent ->
|
||||||
val area = surface.viewport
|
val area = surface.viewport
|
||||||
val shift = (parent.body.bounds.top - area.top - 18).coerceAtMost(area.height() / 4)
|
val shift = (parent.author.bounds.top - area.top - maxOf(24, area.width() / 30)).coerceAtMost(area.height() / 4)
|
||||||
if (shift < 22) return@readOriginal false
|
if (shift < maxOf(42, area.width() / 18)) return@readOriginal false
|
||||||
val x = area.exactCenterX()
|
val x = area.exactCenterX()
|
||||||
val from = area.top + area.height() * .72f
|
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
|
} == 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 ->
|
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
|
val expand = thread.expand ?: return@readThread false
|
||||||
!thread.complete && contains(surface.viewport, expand.bounds) && ui.click(expand)
|
if (thread.complete || !contains(surface.viewport, expand.bounds)) return@readThread false
|
||||||
} == true
|
diagnostics?.record("小红书回查正在展开原评论的回复")
|
||||||
|
ui.click(expand, surface.viewport).also { accepted ->
|
||||||
|
diagnostics?.record(if (accepted) "小红书回查已触发展开回复" else "小红书回查未能触发展开回复")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun changedThread(scope: SurfaceKey, original: OriginalComment, previous: ThreadStamp): Boolean? =
|
private fun changedThread(scope: SurfaceKey, original: OriginalComment, previous: ThreadStamp): Boolean? =
|
||||||
readThread(scope, original) { _, _, thread -> true.takeIf { stamp(thread) != previous } }
|
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) {
|
private fun findSurface(): SurfaceKey? = ui.await(THREAD_WAIT_MS) {
|
||||||
ui.inspect { page ->
|
ui.inspect { page ->
|
||||||
|
page.requireXhsCommentAccess()
|
||||||
if (hasOpenEditor(page)) return@inspect null
|
if (hasOpenEditor(page)) return@inspect null
|
||||||
comments.surface(page)?.takeIf { it.windowId == page.windowId && contains(page.bounds, it.viewport) }
|
comments.surface(page)?.takeIf { it.windowId == page.windowId && contains(page.bounds, it.viewport) }
|
||||||
?.let { SurfaceKey(it.windowId, it.inline) }
|
?.let { SurfaceKey(it.windowId, it.inline) }
|
||||||
@@ -167,6 +354,7 @@ internal class XiaohongshuReplyReceipt(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun matchingSurface(page: UiPage, scope: SurfaceKey): XhsCommentSurface? {
|
private fun matchingSurface(page: UiPage, scope: SurfaceKey): XhsCommentSurface? {
|
||||||
|
page.requireXhsCommentAccess()
|
||||||
if (page.windowId != scope.windowId || hasOpenEditor(page)) return null
|
if (page.windowId != scope.windowId || hasOpenEditor(page)) return null
|
||||||
return comments.surface(page)?.takeIf {
|
return comments.surface(page)?.takeIf {
|
||||||
it.windowId == scope.windowId && it.inline == scope.inline && contains(page.bounds, it.viewport)
|
it.windowId == scope.windowId && it.inline == scope.inline && contains(page.bounds, it.viewport)
|
||||||
@@ -199,20 +387,22 @@ internal class XiaohongshuReplyReceipt(
|
|||||||
|
|
||||||
private companion object {
|
private companion object {
|
||||||
const val MAX_EXPANSIONS = 4
|
const val MAX_EXPANSIONS = 4
|
||||||
|
const val MAX_BASELINE_ADJUSTMENTS = 2
|
||||||
const val MAX_RECEIPT_PASSES = 9
|
const val MAX_RECEIPT_PASSES = 9
|
||||||
const val MAX_REVERSE_SCROLLS = 2
|
const val MAX_REVERSE_SCROLLS = 2
|
||||||
const val MAX_FORWARD_SCROLLS = 12
|
const val MAX_FORWARD_SCROLLS = 12
|
||||||
const val THREAD_WAIT_MS = 1_550L
|
const val THREAD_WAIT_MS = 1_550L
|
||||||
const val RECEIPT_WAIT_MS = 850L
|
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 const val XHS_RECEIPT_CLOCK_SLACK_MS = 5_000L
|
||||||
private val xhsReceiptRelativeTime = Regex("([0-9]{1,2})[ \\u00a0]*(秒前|分钟前)")
|
private val xhsReceiptRelativeTime = Regex("([0-9]{1,2})[ \\u00a0]*(秒前|分钟前)")
|
||||||
|
|
||||||
internal fun validXhsReceiptAge(armedAt: Long, now: Long): Boolean =
|
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 {
|
internal fun matchesXhsReceiptTime(label: String, armedAt: Long, now: Long): Boolean {
|
||||||
if (!validXhsReceiptAge(armedAt, now)) return false
|
if (!validXhsReceiptAge(armedAt, now)) return false
|
||||||
|
|||||||
@@ -70,8 +70,9 @@ data class TaskCheckpoint(
|
|||||||
val video = activeVideo ?: return false
|
val video = activeVideo ?: return false
|
||||||
val target = claim.targetKey?.takeIf { it.isNotBlank() } ?: return false
|
val target = claim.targetKey?.takeIf { it.isNotBlank() } ?: return false
|
||||||
val armedAt = claim.armedAtEpochMs ?: 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) &&
|
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 {
|
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
|
private fun Outcome.isConfirmedReply(): Boolean = this == Outcome.SENT || this == Outcome.USER_CONFIRMED
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.jieliu.app.task
|
package com.jieliu.app.task
|
||||||
|
|
||||||
|
import com.jieliu.app.platform.XiaohongshuNoteKind
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
|
|
||||||
enum class ReplyMode(val label: String) {
|
enum class ReplyMode(val label: String) {
|
||||||
@@ -42,11 +43,16 @@ data class TaskPlan(
|
|||||||
val contentTypes: List<ContentType>? = null,
|
val contentTypes: List<ContentType>? = null,
|
||||||
val selectedTypeId: String? = null,
|
val selectedTypeId: String? = null,
|
||||||
val repliesPerVideo: Int = 1,
|
val repliesPerVideo: Int = 1,
|
||||||
|
val xiaohongshuNoteKind: XiaohongshuNoteKind = XiaohongshuNoteKind.ANY,
|
||||||
|
val xiaohongshuNoteKey: String? = null,
|
||||||
) {
|
) {
|
||||||
fun validate() {
|
fun validate() {
|
||||||
if (contentTypes == null) validateLegacy() else validateHierarchy(contentTypes)
|
if (contentTypes == null) validateLegacy() else validateHierarchy(contentTypes)
|
||||||
require(limit in 1..100) { "单次任务数量须为 1–100。" }
|
require(limit in 1..100) { "单次任务数量须为 1–100。" }
|
||||||
require(repliesPerVideo in 1..MAX_REPLIES_PER_VIDEO) { "每条视频回复数量须为 1–$MAX_REPLIES_PER_VIDEO。" }
|
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) {
|
require(watchSeconds.first in 1..300 && watchSeconds.last in watchSeconds.first..300) {
|
||||||
"观看区间须在 1–300 秒之间,且下限不大于上限。"
|
"观看区间须在 1–300 秒之间,且下限不大于上限。"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import com.jieliu.app.platform.CommentPublishResult
|
|||||||
import com.jieliu.app.platform.CommentTarget
|
import com.jieliu.app.platform.CommentTarget
|
||||||
import com.jieliu.app.platform.PlatformAdapter
|
import com.jieliu.app.platform.PlatformAdapter
|
||||||
import com.jieliu.app.platform.PlatformException
|
import com.jieliu.app.platform.PlatformException
|
||||||
|
import com.jieliu.app.platform.PlatformInteractionRestrictedException
|
||||||
import com.jieliu.app.platform.PlatformRegistry
|
import com.jieliu.app.platform.PlatformRegistry
|
||||||
import com.jieliu.app.platform.VideoContext
|
import com.jieliu.app.platform.VideoContext
|
||||||
import java.util.concurrent.CancellationException
|
import java.util.concurrent.CancellationException
|
||||||
@@ -103,7 +104,7 @@ internal class TaskRunner(
|
|||||||
checkpoint = armed
|
checkpoint = armed
|
||||||
}
|
}
|
||||||
val confirmation = if (result == CommentPublishResult.UNCERTAIN && checkpoint.canAutomaticallyRecheck()) {
|
val confirmation = if (result == CommentPublishResult.UNCERTAIN && checkpoint.canAutomaticallyRecheck()) {
|
||||||
confirmPending(checkpoint, inCurrentRun = true)
|
confirmPending(checkpoint, currentVideo = candidate)
|
||||||
} else result
|
} else result
|
||||||
check(confirmation == CommentPublishResult.CONFIRMED) { "请在目标应用里核对这条评论的发送结果。" }
|
check(confirmation == CommentPublishResult.CONFIRMED) { "请在目标应用里核对这条评论的发送结果。" }
|
||||||
persist(checkpoint.recordReply(Outcome.SENT))
|
persist(checkpoint.recordReply(Outcome.SENT))
|
||||||
@@ -122,6 +123,10 @@ internal class TaskRunner(
|
|||||||
store.appendLog("任务完成 · 处理 ${checkpoint.receipts.size} 条 · 确认发送 ${checkpoint.sentCount} 条")
|
store.appendLog("任务完成 · 处理 ${checkpoint.receipts.size} 条 · 确认发送 ${checkpoint.sentCount} 条")
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
val message = when {
|
val message = when {
|
||||||
|
error is PlatformInteractionRestrictedException -> {
|
||||||
|
val suffix = if (checkpoint.pending == null) "任务已暂停。" else "已保留本次提交等待核对。"
|
||||||
|
"${error.message},$suffix"
|
||||||
|
}
|
||||||
recheckPending && checkpoint.pending != null -> {
|
recheckPending && checkpoint.pending != null -> {
|
||||||
if (cancelled() || error is CancellationException) "自动核对已暂停,发送结果仍待核对。"
|
if (cancelled() || error is CancellationException) "自动核对已暂停,发送结果仍待核对。"
|
||||||
else "自动核对未确认,发送结果仍待核对。"
|
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()) { "这条回复的自动核对期限已过。" }
|
check(checkpoint.canAutomaticallyRecheck()) { "这条回复的自动核对期限已过。" }
|
||||||
val pending = checkNotNull(checkpoint.pending)
|
val pending = checkNotNull(checkpoint.pending)
|
||||||
val type = checkNotNull(checkpoint.contentType)
|
val type = checkNotNull(checkpoint.contentType)
|
||||||
requireRunning(cancelled)
|
requireRunning(cancelled)
|
||||||
if (inCurrentRun) {
|
if (currentVideo != null) {
|
||||||
store.appendLog("本次任务继续核对已提交回复")
|
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 {
|
} else {
|
||||||
store.appendLog("开始自动核对一条待确认回复")
|
store.appendLog("开始自动核对一条待确认回复")
|
||||||
status("正在打开目标应用")
|
status("正在打开目标应用")
|
||||||
platform.launch()
|
receiptPhase("打开目标应用") { platform.launch() }
|
||||||
}
|
}
|
||||||
status("正在定位待核对的$contentUnit")
|
status("正在定位待核对的$contentUnit")
|
||||||
val video = locateVideo(platform.search(type.name), checkpoint)
|
val video = receiptPhase("定位原$contentUnit") { locateVideo(platform.search(type.name), checkpoint) }
|
||||||
requireRunning(cancelled)
|
requireRunning(cancelled)
|
||||||
|
store.appendLog("已重新定位待核对的原$contentUnit")
|
||||||
status("正在打开待核对的${contentUnit}评论区")
|
status("正在打开待核对的${contentUnit}评论区")
|
||||||
platform.openComments(video)
|
receiptPhase("打开原${contentUnit}评论区") { platform.openCommentsForReceipt(video) }
|
||||||
requireRunning(cancelled)
|
requireRunning(cancelled)
|
||||||
|
store.appendLog("已打开原${contentUnit}评论区,正在核对回复")
|
||||||
status("正在核对已发送的回复")
|
status("正在核对已发送的回复")
|
||||||
return platform.confirmPendingReply(video, pending).also { requireRunning(cancelled) }
|
return receiptPhase("核对已发送的回复") { platform.confirmPendingReply(video, pending) }
|
||||||
|
.also { requireRunning(cancelled) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private inline fun <T> 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 {
|
private fun locateVideo(first: VideoContext, checkpoint: TaskCheckpoint): VideoContext {
|
||||||
|
|||||||
@@ -53,6 +53,22 @@ class PublishedPhotoMatcherTest {
|
|||||||
assertFalse(PublishedPhotoMatcher.matches(reference, recolored))
|
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() {
|
@Test fun rejectsMissingFlatTransparentAndTooSmallEvidence() {
|
||||||
val solid = photo(64, 64) { _, _ -> rgb(127, 127, 127) }
|
val solid = photo(64, 64) { _, _ -> rgb(127, 127, 127) }
|
||||||
val transparent = photo(64, 64) { x, y -> pattern(x, y) and 0x00ffffff }
|
val transparent = photo(64, 64) { x, y -> pattern(x, y) and 0x00ffffff }
|
||||||
|
|||||||
@@ -19,7 +19,8 @@ class XhsReceiptTimeTest {
|
|||||||
val times = listOf("", "今天", "11-26", "刚刚 浙江", "昨日 11:20", "99分钟前")
|
val times = listOf("", "今天", "11-26", "刚刚 浙江", "昨日 11:20", "99分钟前")
|
||||||
assertTrue(times.none { matchesXhsReceiptTime(it, armedAt, armedAt + 3_000L) })
|
assertTrue(times.none { matchesXhsReceiptTime(it, armedAt, armedAt + 3_000L) })
|
||||||
assertFalse(matchesXhsReceiptTime("刚刚", armedAt, armedAt - 1L))
|
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))
|
assertFalse(validXhsReceiptAge(0, armedAt))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user