修复小红书和哔哩哔哩回复后互动全流程
This commit is contained in:
@@ -13,8 +13,8 @@ android {
|
||||
applicationId = "com.jieliu.app"
|
||||
minSdk = 26
|
||||
targetSdk = 35
|
||||
versionCode = 49
|
||||
versionName = "0.1.48"
|
||||
versionCode = 50
|
||||
versionName = "0.1.49"
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
|
||||
@@ -110,9 +110,10 @@ internal class BilibiliAdapter(
|
||||
engageActionButton(ui, { page ->
|
||||
if (!navigation.matchesVideo(page, video)) return@engageActionButton null
|
||||
page.visibleByViewId(viewId).singleOrNull {
|
||||
it.enabled && page.bounds.contains(it.bounds) && BilibiliLabels.videoAction(it.description, action)
|
||||
it.enabled && it.clickable && it.checked != null && page.bounds.contains(it.bounds) &&
|
||||
BilibiliLabels.videoAction(it.description, action)
|
||||
}
|
||||
}, action, "已$action", action, diagnostic)
|
||||
}, UiNode::checked, action, diagnostic)
|
||||
} catch (error: CancellationException) {
|
||||
throw error
|
||||
} catch (error: Exception) {
|
||||
|
||||
@@ -325,6 +325,8 @@ internal class BilibiliComments(
|
||||
var sawList = false
|
||||
var sawCompleteList = false
|
||||
var sawOriginalBelowFirst = false
|
||||
var lastClippedViewport: Rect? = null
|
||||
var expansionAttempts = 0
|
||||
fun readOpenedThread(): ThreadScope? = ui.inspect { page ->
|
||||
sawHeading = sawHeading || page.hasDetailHeading()
|
||||
if (page.hasEditor()) return@inspect null
|
||||
@@ -335,9 +337,19 @@ internal class BilibiliComments(
|
||||
val original = rows.firstOrNull()?.takeIf { it.target == target }
|
||||
if (original == null) {
|
||||
sawOriginalBelowFirst = sawOriginalBelowFirst || rows.any { it.target == target }
|
||||
// 原评论常在滚动后才进视图,多滚几次再等。
|
||||
val clipped = BilibiliComposeComments.clippedOriginalViewport(page, list, target)
|
||||
if (clipped != null) {
|
||||
// This swipe only exposes more of the same verified thread. The full row is still required below.
|
||||
val previous = lastClippedViewport
|
||||
if (expansionAttempts < 2 && (previous == null || clipped.top < previous.top)) {
|
||||
lastClippedViewport = clipped
|
||||
expansionAttempts++
|
||||
ui.scrollUpInside(clipped)
|
||||
}
|
||||
return@inspect null
|
||||
}
|
||||
val backward = AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
|
||||
if (movedToRoot < 3 && list.supports(backward)) {
|
||||
if (lastClippedViewport == null && movedToRoot < 3 && list.supports(backward)) {
|
||||
movedToRoot++
|
||||
list.act(backward)
|
||||
}
|
||||
@@ -359,7 +371,7 @@ internal class BilibiliComments(
|
||||
if (thread == null) thread = ui.await(6_500, ::readOpenedThread)
|
||||
if (thread == null) {
|
||||
diagnostic("哔哩哔哩评论详情诊断 标题=$sawHeading 列表=$sawList 完整列表=$sawCompleteList " +
|
||||
"原评论位于非首行=$sawOriginalBelowFirst 向前滚动尝试=$movedToRoot")
|
||||
"原评论位于非首行=$sawOriginalBelowFirst 向前滚动尝试=$movedToRoot 展开详情尝试=$expansionAttempts")
|
||||
if (!sawHeading && !sawList && ui.inspect { threadEntryOnMain(it, scope, target) != null } == true) {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -157,10 +157,12 @@ internal object BilibiliComposeComments {
|
||||
list: UiNode,
|
||||
target: (author: String, body: String) -> CommentTarget,
|
||||
): List<BilibiliComments.Row> {
|
||||
if (!isList(page, list)) return emptyList()
|
||||
val detail = detail(page)?.takeIf { it.list === list }
|
||||
if (detail == null && list(page) !== list) return emptyList()
|
||||
val siblings = page.children(list)
|
||||
return siblings.mapIndexedNotNull { index, row ->
|
||||
val identity = rowIdentity(page, list, row) ?: return@mapIndexedNotNull null
|
||||
val detailStart = detail?.header?.bounds?.bottom.takeIf { index == 0 }
|
||||
val identity = rowIdentity(page, list, row, detailStart) ?: return@mapIndexedNotNull null
|
||||
val author = identity.author.text
|
||||
val body = identity.body
|
||||
val reply = footerAction(page, list, row, REPLY_LABELS) ?: return@mapIndexedNotNull null
|
||||
@@ -191,13 +193,32 @@ internal object BilibiliComposeComments {
|
||||
|
||||
/** The native count must account for every visible nested row before proving a full thread. */
|
||||
fun completeThread(page: UiPage, list: UiNode, nestedCount: Int): Boolean {
|
||||
if (!page.complete || detail(page)?.list !== list) return false
|
||||
val counts = page.children(list).flatMap { page.children(it) }.mapNotNull { marker ->
|
||||
if (!page.complete) return false
|
||||
val detail = detail(page)?.takeIf { it.list === list } ?: return false
|
||||
val rows = page.children(list)
|
||||
val counts = rows.flatMap { page.children(it) }.mapNotNull { marker ->
|
||||
if (marker.className != TEXT_VIEW || marker.clickable || !list.bounds.contains(marker.bounds)) return@mapNotNull null
|
||||
THREAD_TOTAL.matchEntire(marker.text)?.groupValues?.get(1)?.toIntOrNull()
|
||||
}
|
||||
if (counts.singleOrNull() != nestedCount) return false
|
||||
return page.children(list).count { rowIdentity(page, list, it) != null } == nestedCount + 1
|
||||
return rows.withIndex().count { (index, row) ->
|
||||
val detailStart = detail.header.bounds.bottom.takeIf { index == 0 }
|
||||
rowIdentity(page, list, row, detailStart) != null
|
||||
} == nestedCount + 1
|
||||
}
|
||||
|
||||
/** A partly raised reply sheet can expose the original's identity above a clipped footer. */
|
||||
fun clippedOriginalViewport(page: UiPage, list: UiNode, target: CommentTarget): Rect? {
|
||||
if (!page.complete || !list.scrollable) return null
|
||||
val detail = detail(page)?.takeIf { it.list === list } ?: return null
|
||||
if (list.bounds.top - detail.header.bounds.bottom < detail.header.bounds.height()) return null
|
||||
val first = page.children(list).firstOrNull() ?: return null
|
||||
if (first.bounds.top != list.bounds.top || first.bounds.bottom != list.bounds.bottom) return null
|
||||
val identity = rowIdentity(page, list, first) ?: return null
|
||||
if (identity.author.text != target.author || identity.body.description != target.text ||
|
||||
footerAction(page, list, first, REPLY_LABELS) != null
|
||||
) return null
|
||||
return Rect(list.bounds)
|
||||
}
|
||||
|
||||
private fun composeList(page: UiPage, compose: UiNode, staticDetailPanel: UiNode? = null): UiNode? =
|
||||
@@ -222,13 +243,17 @@ internal object BilibiliComposeComments {
|
||||
} == 1
|
||||
}
|
||||
|
||||
private fun rowIdentity(page: UiPage, list: UiNode, row: UiNode): Identity? {
|
||||
private fun rowIdentity(page: UiPage, list: UiNode, row: UiNode, detailStart: Int? = null): Identity? {
|
||||
if (row.className != VIEW || row.directParent() !== list || !row.biliClick() || row.editable ||
|
||||
row.bounds.width() < list.bounds.width() * .90 || !list.bounds.contains(row.bounds)
|
||||
row.bounds.width() < list.bounds.width() * .90
|
||||
) return null
|
||||
val visible = Rect(row.bounds)
|
||||
// The first detail row can begin at the header edge, above the list's top inset.
|
||||
if (visible.top == detailStart && visible.top < list.bounds.top) visible.top = list.bounds.top
|
||||
if (!list.bounds.contains(visible)) return null
|
||||
val children = page.children(row)
|
||||
val author = children.singleOrNull {
|
||||
it.className == BUTTON && it.biliClick() && row.bounds.contains(it.bounds) &&
|
||||
it.className == BUTTON && it.biliClick() && visible.contains(it.bounds) &&
|
||||
it.text.isNotBlank() && it.text == it.description
|
||||
} ?: return null
|
||||
// A short author name has a square touch target that extends past the rendered label.
|
||||
@@ -238,7 +263,7 @@ internal object BilibiliComposeComments {
|
||||
val body = children.singleOrNull {
|
||||
it.className == VIEW && !it.clickable && !it.editable && it.text.isEmpty() && it.description.isNotBlank() &&
|
||||
it.bounds.top >= bodyTop && it.bounds.left <= author.bounds.centerX() &&
|
||||
it.bounds.width() >= row.bounds.width() * .50 && row.bounds.contains(it.bounds)
|
||||
it.bounds.width() >= row.bounds.width() * .50 && visible.contains(it.bounds)
|
||||
} ?: return null
|
||||
return Identity(author, body)
|
||||
}
|
||||
|
||||
@@ -41,21 +41,36 @@ internal fun engageActionButton(
|
||||
donePrefix: String,
|
||||
name: String,
|
||||
diagnostic: (String) -> Unit,
|
||||
): EngagementAction = engageActionButton(ui, find, { node ->
|
||||
when {
|
||||
node.description.startsWith(donePrefix) -> true
|
||||
node.description.startsWith(pendingPrefix) -> false
|
||||
else -> null
|
||||
}
|
||||
}, name, diagnostic)
|
||||
|
||||
/** [readChecked] returns null when the button's current state cannot be verified. */
|
||||
internal fun engageActionButton(
|
||||
ui: AccessibleUi,
|
||||
find: (UiPage) -> UiNode?,
|
||||
readChecked: (UiNode) -> Boolean?,
|
||||
name: String,
|
||||
diagnostic: (String) -> Unit,
|
||||
): EngagementAction {
|
||||
ui.pace()
|
||||
val button = ui.await(3_000) {
|
||||
ui.inspect { page -> find(page)?.let { it.description to it.bounds } }
|
||||
ui.inspect { page -> find(page)?.let { Triple(it.description, it.bounds, readChecked(it)) } }
|
||||
}
|
||||
if (button == null) {
|
||||
diagnostic("${name}未找到按钮")
|
||||
return EngagementAction.FAILED
|
||||
}
|
||||
val (description, bounds) = button
|
||||
if (description.startsWith(donePrefix)) {
|
||||
val (description, bounds, checked) = button
|
||||
if (checked == true) {
|
||||
diagnostic("${name}已是目标状态 $description")
|
||||
return EngagementAction.SKIPPED
|
||||
}
|
||||
if (!description.startsWith(pendingPrefix)) {
|
||||
if (checked == null) {
|
||||
diagnostic("${name}状态无法识别 $description")
|
||||
return EngagementAction.FAILED
|
||||
}
|
||||
@@ -64,7 +79,7 @@ internal fun engageActionButton(
|
||||
val dispatched = ui.touch(x, y, x, y, 85)
|
||||
diagnostic("${name}触屏($x,$y)=$dispatched")
|
||||
val flipped = ui.await(5_000) {
|
||||
ui.inspect { page -> true.takeIf { find(page)?.description?.startsWith(donePrefix) == true } }
|
||||
ui.inspect { page -> true.takeIf { find(page)?.let(readChecked) == true } }
|
||||
} == true
|
||||
diagnostic("${name}核对=$flipped")
|
||||
return if (flipped) EngagementAction.DONE else EngagementAction.FAILED
|
||||
|
||||
@@ -8,10 +8,21 @@ import com.jieliu.app.task.PendingComment
|
||||
import com.jieliu.app.task.TemplatePhoto
|
||||
import java.io.Closeable
|
||||
import java.security.MessageDigest
|
||||
import java.util.concurrent.CancellationException
|
||||
import kotlin.math.abs
|
||||
|
||||
enum class XiaohongshuNoteKind { ANY, IMAGE, VIDEO }
|
||||
|
||||
internal enum class XiaohongshuEngagementControl(val label: String) {
|
||||
LIKE("点赞"), FAVORITE("收藏");
|
||||
|
||||
val donePrefix = "已$label"
|
||||
// The same toolbar can use a space before the counter only while the button is unselected.
|
||||
private val description = Regex("(?:已)?$label(?:\\s*[0-9]+(?:\\.[0-9]+)?(?:万|亿)?\\+?)?")
|
||||
|
||||
fun matches(value: String): Boolean = description.matches(value)
|
||||
}
|
||||
|
||||
internal class XiaohongshuAdapter(
|
||||
private val spec: PlatformSpec,
|
||||
private val ui: AccessibleUi,
|
||||
@@ -412,8 +423,8 @@ internal class XiaohongshuAdapter(
|
||||
it.bounds.centerY() >= y(.76f) && it.bounds.centerX() <= x(.49f) && it.isNativeClick() } ?: return null
|
||||
val toolbar = prompt.directParent()?.takeIf { it.className == "android.view.ViewGroup" } ?: return null
|
||||
val buttons = nodes.filter { it.directParent() === toolbar && it.className == "android.widget.Button" && it.isNativeClick() }
|
||||
if (buttons.count { likeLabel.matches(it.description) } != 1 ||
|
||||
buttons.count { favoriteLabel.matches(it.description) } != 1) return null
|
||||
if (buttons.count { XiaohongshuEngagementControl.LIKE.matches(it.description) } != 1 ||
|
||||
buttons.count { XiaohongshuEngagementControl.FAVORITE.matches(it.description) } != 1) return null
|
||||
if (buttons.count { commentLabel.matches(it.description) && it.bounds.centerX() >= x(.75f) } != 1) return null
|
||||
return NoteControls(author, more, toolbar)
|
||||
}
|
||||
@@ -648,28 +659,32 @@ internal class XiaohongshuAdapter(
|
||||
|
||||
/** 回复确认后点击笔记底部工具栏的点赞和/或收藏。状态前缀「已」表示已完成,不重复点击以免误取消。 */
|
||||
override fun engage(video: VideoContext, like: Boolean, favorite: Boolean): EngagementResult {
|
||||
if (!like && !favorite) return EngagementResult()
|
||||
fun only(enabled: Boolean, action: EngagementAction) = if (enabled) action else EngagementAction.SKIPPED
|
||||
val failed = EngagementResult(only(like, EngagementAction.FAILED), only(favorite, EngagementAction.FAILED))
|
||||
val note = activeNote?.takeIf { it.video.key == video.key }
|
||||
return EngagementResult(
|
||||
like = if (like) engageButton(note, XiaohongshuEngagementControl.LIKE) else EngagementAction.SKIPPED,
|
||||
favorite = if (favorite) engageButton(note, XiaohongshuEngagementControl.FAVORITE) else EngagementAction.SKIPPED,
|
||||
)
|
||||
}
|
||||
|
||||
private fun engageButton(note: NoteBinding?, control: XiaohongshuEngagementControl): EngagementAction {
|
||||
if (note == null || commentNote != null) return EngagementAction.FAILED
|
||||
return try {
|
||||
val note = activeNote?.takeIf { it.video.key == video.key } ?: return failed
|
||||
EngagementResult(
|
||||
only(like, engageActionButton(ui, { page -> page.engagementButton(note, likeLabel) },
|
||||
likePendingPrefix, engagementDonePrefix, "点赞", diagnostic)),
|
||||
only(favorite, engageActionButton(ui, { page -> page.engagementButton(note, favoriteLabel) },
|
||||
favoritePendingPrefix, engagementDonePrefix, "收藏", diagnostic)),
|
||||
)
|
||||
engageActionButton(ui, { page -> page.engagementButton(note, control) },
|
||||
control.label, control.donePrefix, control.label, diagnostic)
|
||||
} catch (error: CancellationException) {
|
||||
throw error
|
||||
} catch (_: Exception) {
|
||||
failed
|
||||
EngagementAction.FAILED
|
||||
}
|
||||
}
|
||||
|
||||
/** 笔记工具栏里的互动按钮。小红书不暴露资源 ID,只能按描述识别。 */
|
||||
private fun UiPage.engagementButton(note: NoteBinding, label: Regex): UiNode? {
|
||||
private fun UiPage.engagementButton(note: NoteBinding, control: XiaohongshuEngagementControl): UiNode? {
|
||||
if (nodes.any { it.editable && (it.focused || it.hasDraft()) }) return null
|
||||
val toolbar = boundNote(note)?.toolbar ?: return null
|
||||
return nodes.filter {
|
||||
it.directParent() === toolbar && it.className == "android.widget.Button" && it.isNativeClick() &&
|
||||
label.matches(it.description)
|
||||
bounds.contains(it.bounds) && toolbar.bounds.contains(it.bounds) && control.matches(it.description)
|
||||
}.singleOrNull()
|
||||
}
|
||||
|
||||
@@ -712,13 +727,6 @@ internal class XiaohongshuAdapter(
|
||||
|
||||
private companion object {
|
||||
const val COUNTER = "(?:\\s+[0-9]+(?:\\.[0-9]+)?(?:万|亿)?\\+?)?"
|
||||
val likeLabel = Regex("(?:已)?点赞$COUNTER")
|
||||
val favoriteLabel = Regex("(?:已)?收藏$COUNTER")
|
||||
|
||||
// 工具栏按钮描述形如「点赞 298」,已操作时加「已」前缀。
|
||||
const val likePendingPrefix = "点赞"
|
||||
const val favoritePendingPrefix = "收藏"
|
||||
const val engagementDonePrefix = "已"
|
||||
val commentLabel = Regex("评论$COUNTER")
|
||||
val zeroComments = Regex("评论\\s+0")
|
||||
val whitespace = Regex("\\s+")
|
||||
|
||||
@@ -132,7 +132,11 @@ internal class XiaohongshuComments(
|
||||
fun close() {
|
||||
val session = active ?: return
|
||||
if (session.inline) {
|
||||
if (ui.inspect { page -> matchesNote(page, session.note) && !page.hasActiveDraft() } != true) {
|
||||
// Returning from the ownership menu is asynchronous. Wait without acting on any window.
|
||||
val restored = ui.await(4_000) {
|
||||
ui.inspect { page -> true.takeIf { matchesNote(page, session.note) && !page.hasActiveDraft() } }
|
||||
}
|
||||
if (restored != true) {
|
||||
throw PlatformException("小红书原笔记或评论草稿状态已变化")
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -232,7 +232,7 @@ internal class TaskRunner(
|
||||
receiptPhase("打开目标应用") { platform.launch() }
|
||||
}
|
||||
status("正在定位待核对的$contentUnit")
|
||||
val video = receiptPhase("定位原$contentUnit") { locateVideo(platform.search(type.name), checkpoint) }
|
||||
val video = receiptPhase("定位原$contentUnit") { locateVideoForReceipt(type.name, checkpoint, pending) }
|
||||
requireRunning(cancelled)
|
||||
store.appendLog("已重新定位待核对的原$contentUnit")
|
||||
status("正在打开待核对的${contentUnit}评论区")
|
||||
@@ -244,6 +244,21 @@ internal class TaskRunner(
|
||||
.also { requireRunning(cancelled) }
|
||||
}
|
||||
|
||||
private fun locateVideoForReceipt(typeName: String, checkpoint: TaskCheckpoint, pending: PendingComment): VideoContext {
|
||||
val title = pending.title.trim()
|
||||
if (bilibili && title.isNotBlank() && title != typeName) {
|
||||
try {
|
||||
return locateVideo(platform.search(title), checkpoint, pending.videoKey)
|
||||
} catch (error: Exception) {
|
||||
if (error is CancellationException || (error !is PlatformException && error !is IllegalStateException)) {
|
||||
throw error
|
||||
}
|
||||
requireRunning(cancelled)
|
||||
}
|
||||
}
|
||||
return locateVideo(platform.search(typeName), checkpoint, pending.videoKey)
|
||||
}
|
||||
|
||||
private inline fun <T> receiptPhase(stage: String, action: () -> T): T = try {
|
||||
action()
|
||||
} catch (error: Exception) {
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.jieliu.app.platform
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class XiaohongshuEngagementControlTest {
|
||||
@Test fun toolbarRecognizesBothStatesWithOrWithoutSpaces() {
|
||||
listOf("点赞 3053", "点赞3053", "已点赞3054", "已点赞 3054", "点赞", "已点赞1.2万+").forEach {
|
||||
assertTrue(it, XiaohongshuEngagementControl.LIKE.matches(it))
|
||||
}
|
||||
listOf("收藏 1037", "收藏1037", "已收藏1038", "已收藏 1038", "收藏", "已收藏2万").forEach {
|
||||
assertTrue(it, XiaohongshuEngagementControl.FAVORITE.matches(it))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun toolbarDoesNotUseOtherActionsOrCommentTextAsButtons() {
|
||||
listOf("收藏 1037", "取消点赞", "已点赞 3054 次", "评论点赞 2").forEach {
|
||||
assertFalse(it, XiaohongshuEngagementControl.LIKE.matches(it))
|
||||
}
|
||||
listOf("已点赞3054", "收藏夹 1037", "已收藏 1038 次", "评论 607").forEach {
|
||||
assertFalse(it, XiaohongshuEngagementControl.FAVORITE.matches(it))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -332,6 +332,29 @@ class TaskRunnerTest {
|
||||
assertEquals(pending.copy(armedAtEpochMs = null), legacy.checkpoint.pending)
|
||||
}
|
||||
|
||||
@Test fun bilibiliRecheckSearchesTheSavedTitleBeforeFallingBackToTheContentType() {
|
||||
val plan = plan(firstType).copy(platformId = "bilibili")
|
||||
val pending = PendingComment("video-0", "原视频标题", "已提交的话术", targetKey = "original",
|
||||
targetAuthor = "测试用户", armedAtEpochMs = System.currentTimeMillis())
|
||||
for (titleUnavailable in listOf(false, true)) {
|
||||
val store = RecordingStore(TaskCheckpoint("bili-title-recheck", plan).startVideo(pending.videoKey).arm(pending))
|
||||
val platform = FakePlatform(store).apply {
|
||||
recheckResult = CommentPublishResult.CONFIRMED
|
||||
onSearch = { query ->
|
||||
if (titleUnavailable && query == pending.title) throw PlatformException("标题搜索暂不可用")
|
||||
}
|
||||
}
|
||||
|
||||
execute(store, platform, recheckPending = true)
|
||||
|
||||
val expectedSearches = if (titleUnavailable) listOf(pending.title, firstType.name) else listOf(pending.title)
|
||||
assertEquals(expectedSearches, platform.searches)
|
||||
assertEquals(listOf(pending.videoKey to pending), platform.rechecks)
|
||||
assertEquals(0, platform.publishCalls)
|
||||
assertEquals(Outcome.SENT, store.checkpoint.receipts.single().outcome)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun browseUsesOnlySelectedTypeWithoutOpeningTheCommentPanel() {
|
||||
val plan = plan(firstType, secondType).copy(selectedTypeId = secondType.id, replyMode = ReplyMode.BROWSE)
|
||||
val store = RecordingStore(TaskCheckpoint("browse", plan))
|
||||
@@ -712,6 +735,7 @@ class TaskRunnerTest {
|
||||
val unavailable = mutableSetOf<String>()
|
||||
var knownBaseline = false
|
||||
var recheckResult = CommentPublishResult.UNCERTAIN
|
||||
var onSearch: (String) -> Unit = {}
|
||||
var onScroll: () -> Unit = {}
|
||||
var onPrepare: (Boolean) -> Unit = {}
|
||||
var beforePublish: () -> Unit = {}
|
||||
@@ -739,6 +763,7 @@ class TaskRunnerTest {
|
||||
|
||||
override fun search(keyword: String): VideoContext {
|
||||
searches.add(keyword)
|
||||
onSearch(keyword)
|
||||
nextKey = firstVideoBySearch.getOrPut(keyword) { nextKey }
|
||||
return showVideo("样片-$keyword")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user