接入快手图片和视频作品的评论回复流程
支持按内容类型搜索、轮流浏览图片和视频、匹配评论关键词以及核对绑定多图和同线程回执。记录已完成的装机验证与待验收项。
This commit is contained in:
@@ -13,8 +13,8 @@ android {
|
||||
applicationId = "com.jieliu.app"
|
||||
minSdk = 26
|
||||
targetSdk = 35
|
||||
versionCode = 41
|
||||
versionName = "0.1.40"
|
||||
versionCode = 42
|
||||
versionName = "0.1.41"
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
<package android:name="com.ss.android.ugc.aweme" />
|
||||
<package android:name="com.xingin.xhs" />
|
||||
<package android:name="tv.danmaku.bili" />
|
||||
<package android:name="com.smile.gifmaker" />
|
||||
</queries>
|
||||
|
||||
<application
|
||||
|
||||
@@ -408,8 +408,11 @@ class MainActivity : Activity() {
|
||||
videoComment -> "达到发布上限或找不到更多匹配评论时,进入下一个$unit。"
|
||||
else -> "达到回复上限或找不到更多匹配评论时,进入下一个$unit。"
|
||||
}
|
||||
libraryHint.text = if (browseOnly) "按内容类型搜索$unit。"
|
||||
else "按内容类型搜索$unit,按关键词匹配评论。每个关键词可配置多条话术。"
|
||||
libraryHint.text = when {
|
||||
browseOnly -> "按内容类型搜索$unit。"
|
||||
spec.id == "kuaishou" -> "按内容类型搜索,轮流处理「图片」和「视频」中的作品。每个关键词可配置多条话术。"
|
||||
else -> "按内容类型搜索$unit,按关键词匹配评论。每个关键词可配置多条话术。"
|
||||
}
|
||||
}
|
||||
updatePlatformCopy(specs[selectedPlatform])
|
||||
val commentSettingsChanged = object : AdapterView.OnItemSelectedListener {
|
||||
|
||||
@@ -29,12 +29,13 @@ import kotlin.random.Random
|
||||
|
||||
/** Uses fresh, target-package-scoped nodes and recycles every reference after each read or action. */
|
||||
@Suppress("DEPRECATION")
|
||||
internal class AccessibleUi(
|
||||
internal class AccessibleUi @JvmOverloads constructor(
|
||||
private val service: AccessibilityService,
|
||||
private val packageName: String,
|
||||
private val cancelled: () -> Boolean,
|
||||
private val pauseBetweenActions: () -> Unit,
|
||||
private val checkPage: ((UiPage) -> Unit)? = null,
|
||||
private val nodeLimit: Int = 450,
|
||||
) {
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
@@ -48,7 +49,7 @@ internal class AccessibleUi(
|
||||
checkCancelled()
|
||||
}
|
||||
|
||||
fun launchTarget(appName: String) {
|
||||
fun launchTarget(appName: String, foregroundTimeoutMs: Long = 12_000) {
|
||||
checkCancelled()
|
||||
if (inspect { true } == true) return
|
||||
val launch = service.packageManager.getLaunchIntentForPackage(packageName)
|
||||
@@ -60,7 +61,7 @@ internal class AccessibleUi(
|
||||
} catch (error: android.content.ActivityNotFoundException) {
|
||||
throw PlatformException("未找到${appName}的启动界面", error)
|
||||
}
|
||||
await(12_000) { inspect { true } } ?: throw PlatformException("等待${appName}进入前台超时")
|
||||
await(foregroundTimeoutMs) { inspect { true } } ?: throw PlatformException("等待${appName}进入前台超时")
|
||||
}
|
||||
|
||||
fun <T> inspect(action: (UiPage) -> T): T? = inspect(false, action)
|
||||
@@ -275,7 +276,7 @@ internal class AccessibleUi(
|
||||
}
|
||||
}
|
||||
val childCount = node.childCount
|
||||
val limit = childCount.coerceAtMost(450 - references.size)
|
||||
val limit = childCount.coerceAtMost(nodeLimit - references.size)
|
||||
if (limit < childCount) complete = false
|
||||
for (index in 0 until limit) {
|
||||
checkCancelled()
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.jieliu.app.platform
|
||||
|
||||
import com.jieliu.app.data.PhotoLibrary
|
||||
import com.jieliu.app.task.PendingComment
|
||||
import com.jieliu.app.task.TemplatePhoto
|
||||
|
||||
internal class KuaishouAdapter(
|
||||
spec: PlatformSpec,
|
||||
ui: AccessibleUi,
|
||||
photos: PhotoLibrary,
|
||||
diagnostic: (String) -> Unit,
|
||||
) : PlatformAdapter {
|
||||
private val navigation = KuaishouNavigation(spec, ui)
|
||||
private val comments = KuaishouComments(ui, navigation::matchesContent, navigation::openCommentPanel)
|
||||
private val replies = KuaishouReplies(ui, comments, photos, diagnostic)
|
||||
private var openWork: VideoContext? = null
|
||||
|
||||
override fun launch() = navigation.launch()
|
||||
|
||||
override fun search(keyword: String): VideoContext {
|
||||
closeComments()
|
||||
return navigation.search(keyword)
|
||||
}
|
||||
|
||||
override fun currentVideo(): VideoContext = navigation.currentVideo()
|
||||
|
||||
override fun nextVideo(previous: VideoContext): VideoContext {
|
||||
closeComments()
|
||||
return navigation.nextVideo(previous)
|
||||
}
|
||||
|
||||
override fun openComments(expected: VideoContext): List<String> = comments.open(expected)
|
||||
.map(CommentTarget::text).also { openWork = expected }
|
||||
|
||||
override fun scanComments(): List<CommentTarget> = comments.scan()
|
||||
override fun scrollComments(): Boolean = comments.scroll()
|
||||
|
||||
override fun prepareReply(target: CommentTarget, expectedText: String, requiresImages: Boolean): Boolean =
|
||||
replies.prepare(target, expectedText, requiresImages)
|
||||
|
||||
override fun hasPreparedReplyBaseline(targetKey: String, text: String): Boolean =
|
||||
replies.hasPreparedBaseline(targetKey, text)
|
||||
|
||||
override fun publishComment(text: String, beforeClick: () -> Unit): CommentPublishResult =
|
||||
publishPhotoComment(text, emptyList(), beforeClick)
|
||||
|
||||
override fun publishPhotoComment(text: String, photos: List<TemplatePhoto>,
|
||||
beforeClick: () -> Unit): CommentPublishResult {
|
||||
val target = replies.preparedTarget(text)
|
||||
var armedAt = 0L
|
||||
val clicked = replies.submit(target, text, photos) {
|
||||
armedAt = System.currentTimeMillis()
|
||||
beforeClick()
|
||||
}
|
||||
if (!clicked || armedAt == 0L) return CommentPublishResult.UNCERTAIN
|
||||
return replies.confirm(target.key, target.author, text, photos, armedAt)
|
||||
}
|
||||
|
||||
override fun confirmPendingReplyInPlace(video: VideoContext, pending: PendingComment): CommentPublishResult? {
|
||||
if (openWork != video || pending.videoKey != video.key || !comments.isOpenFor(video)) return null
|
||||
return confirmPendingReply(video, pending)
|
||||
}
|
||||
|
||||
override fun confirmPendingReply(video: VideoContext, pending: PendingComment): CommentPublishResult {
|
||||
if (openWork != video || pending.videoKey != video.key || !comments.isOpenFor(video)) {
|
||||
return CommentPublishResult.UNCERTAIN
|
||||
}
|
||||
val target = pending.targetKey ?: return CommentPublishResult.UNCERTAIN
|
||||
val author = pending.targetAuthor ?: return CommentPublishResult.UNCERTAIN
|
||||
val armedAt = pending.armedAtEpochMs ?: return CommentPublishResult.UNCERTAIN
|
||||
return replies.confirm(target, author, pending.text, pending.photos, armedAt)
|
||||
}
|
||||
|
||||
override fun closeComments() {
|
||||
if (replies.hasUnsettledEditor()) throw PlatformException("请核对快手中打开的回复草稿后继续")
|
||||
replies.reset()
|
||||
comments.close()
|
||||
openWork = null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
package com.jieliu.app.platform
|
||||
|
||||
import android.graphics.Rect
|
||||
import android.view.accessibility.AccessibilityNodeInfo
|
||||
import java.io.Closeable
|
||||
import java.security.MessageDigest
|
||||
|
||||
internal class KuaishouComments(
|
||||
private val ui: AccessibleUi,
|
||||
private val matchesContent: (UiPage, VideoContext) -> Boolean,
|
||||
private val openCommentPanel: (UiPage, VideoContext) -> Boolean,
|
||||
) {
|
||||
internal data class Panel(val root: UiNode, val list: UiNode?, val close: UiNode, val full: UiNode?, val empty: Boolean)
|
||||
|
||||
internal data class Row(
|
||||
val target: CommentTarget,
|
||||
val container: UiNode,
|
||||
val body: UiNode,
|
||||
val reply: UiNode?,
|
||||
val time: String?,
|
||||
val photos: List<UiNode>?,
|
||||
val own: Boolean,
|
||||
)
|
||||
|
||||
internal data class Thread(val original: Row, val replies: List<Row>, val complete: Boolean, val expand: UiNode?)
|
||||
|
||||
private data class Item(val wrapper: UiNode, val kind: Kind, val row: Row?, val expand: UiNode?)
|
||||
private enum class Kind { ORIGINAL, NESTED, MORE, FOLD, END, UNKNOWN }
|
||||
|
||||
private class Session(
|
||||
val video: VideoContext,
|
||||
val window: Int,
|
||||
val root: UiNodeSource,
|
||||
) : Closeable {
|
||||
override fun close() = root.close()
|
||||
}
|
||||
|
||||
private var active: Session? = null
|
||||
|
||||
fun isOpenFor(video: VideoContext): Boolean = active?.video == video
|
||||
|
||||
fun open(video: VideoContext): List<CommentTarget> {
|
||||
check(active == null) { "请先退出上一个快手评论区" }
|
||||
ui.pace()
|
||||
val origin = ui.inspect { page ->
|
||||
if (!matchesContent(page, video) || page.hasKuaishouCommentDraft()) return@inspect null
|
||||
page.windowId.takeIf { readPanel(page) != null || openCommentPanel(page, video) }
|
||||
} ?: throw PlatformException("未能核对当前快手作品及其评论入口")
|
||||
active = ui.await(7_000) {
|
||||
ui.inspect { page ->
|
||||
if (!page.complete || page.windowId != origin) return@inspect null
|
||||
readPanel(page)?.let { Session(video, page.windowId, it.root.retainSource()) }
|
||||
}
|
||||
} ?: throw PlatformException("未能读取当前快手作品的评论区")
|
||||
return scan()
|
||||
}
|
||||
|
||||
fun scan(): List<CommentTarget> = ui.await(3_000) {
|
||||
ui.inspect { page ->
|
||||
val session = active ?: return@inspect null
|
||||
val panel = panel(page) ?: return@inspect null
|
||||
if (page.hasKuaishouCommentDraft()) return@inspect null
|
||||
originalRows(page, panel, session.video.key).filter { it.reply != null && !it.own }.map(Row::target)
|
||||
}
|
||||
} ?: throw PlatformException("快手评论区已变化")
|
||||
|
||||
fun scroll(): Boolean {
|
||||
ui.pace()
|
||||
val before = ui.inspect { page ->
|
||||
val panel = panel(page)?.takeUnless(Panel::empty) ?: return@inspect null
|
||||
if (page.hasKuaishouCommentDraft()) return@inspect null
|
||||
val list = panel.list?.takeIf { it.scrollable && it.bounds.height() >= page.bounds.height() / 7 }
|
||||
?: return@inspect null
|
||||
val positions = positions(page, list)
|
||||
positions.takeIf { it.isNotEmpty() && ui.scrollUpInside(list.bounds) }
|
||||
} ?: return false
|
||||
return ui.await(2_500) {
|
||||
ui.inspect { page ->
|
||||
val list = panel(page)?.list ?: return@inspect null
|
||||
val after = positions(page, list)
|
||||
true.takeIf { after.isNotEmpty() && before != after }
|
||||
}
|
||||
} == true
|
||||
}
|
||||
|
||||
fun close() {
|
||||
val session = active ?: return
|
||||
ui.pace()
|
||||
val closed = ui.inspect { page ->
|
||||
if (page.hasKuaishouCommentDraft()) return@inspect false
|
||||
if (readPanel(page) == null && matchesContent(page, session.video)) return@inspect true
|
||||
val panel = panel(page) ?: return@inspect false
|
||||
ui.click(panel.close)
|
||||
} == true
|
||||
if (!closed || ui.await(4_000) {
|
||||
ui.inspect { page -> true.takeIf { readPanel(page) == null && matchesContent(page, session.video) } }
|
||||
} != true
|
||||
) throw PlatformException("关闭快手评论区后未能核对同一作品")
|
||||
active = null
|
||||
session.close()
|
||||
}
|
||||
|
||||
fun panel(page: UiPage): Panel? {
|
||||
val session = active ?: return null
|
||||
if (page.windowId != session.window || !page.complete) return null
|
||||
return readPanel(page)?.takeIf { it.root.hasSource(session.root) }
|
||||
}
|
||||
|
||||
fun <T> readThread(key: String, author: String, action: (UiPage, Panel, Thread) -> T): T? =
|
||||
ui.inspect { page ->
|
||||
val session = active ?: return@inspect null
|
||||
val panel = panel(page) ?: return@inspect null
|
||||
if (page.hasKuaishouCommentDraft()) return@inspect null
|
||||
val row = originalRows(page, panel, session.video.key)
|
||||
.singleOrNull { it.target.key == key && it.target.author == author } ?: return@inspect null
|
||||
action(page, panel, readThread(page, panel, row, session.video.key))
|
||||
}
|
||||
|
||||
fun ensureThread(key: String, author: String): Boolean {
|
||||
val before = readThread(key, author) { _, panel, thread ->
|
||||
thread.complete to (panel.full != null)
|
||||
} ?: return false
|
||||
if (before.first) return true
|
||||
if (before.second) {
|
||||
ui.pace()
|
||||
if (readThread(key, author) { _, panel, _ -> panel.full?.let { ui.click(it) } } == true) {
|
||||
val after = ui.await(3_500) {
|
||||
readThread(key, author) { _, panel, thread -> thread.complete.takeIf { panel.full == null } }
|
||||
}
|
||||
if (after == true) return true
|
||||
}
|
||||
}
|
||||
ui.pace()
|
||||
val expanded = readThread(key, author) { _, _, thread ->
|
||||
thread.expand?.let { ui.click(it) }
|
||||
} == true
|
||||
if (!expanded) return false
|
||||
return ui.await(3_500) {
|
||||
readThread(key, author) { _, _, thread -> true.takeIf { thread.complete } }
|
||||
} == true
|
||||
}
|
||||
|
||||
private fun readPanel(page: UiPage): Panel? {
|
||||
val container = page.nodes.singleOrNull { it.resourceId == "comment_panel_container" } ?: return null
|
||||
val root = page.nodes.singleOrNull {
|
||||
it.resourceId == "tabs_panel_container" && it.isDescendantOf(container) &&
|
||||
container.bounds.contains(it.bounds) && it.bounds.width() >= page.bounds.width() * .8
|
||||
} ?: return null
|
||||
val styles = page.nodes.singleOrNull { it.resourceId == "tabs_panel_style" && it.directParent() === root }
|
||||
?: return null
|
||||
val close = page.nodes.singleOrNull {
|
||||
it.resourceId == "tabs_panel_close" && it.labels() == listOf("关闭评论区") && it.clickable &&
|
||||
it.isDescendantOf(styles) && styles.bounds.contains(it.bounds)
|
||||
} ?: return null
|
||||
val full = page.nodes.singleOrNull {
|
||||
it.resourceId == "tabs_panel_full" && it.labels() == listOf("展开评论区") && it.clickable &&
|
||||
it.directParent() === close.directParent() && styles.bounds.contains(it.bounds)
|
||||
}
|
||||
val heading = page.nodes.singleOrNull {
|
||||
it.resourceId == "tab_text" && it.selected && commentCount.matches(it.text) &&
|
||||
it.isDescendantOf(styles) && styles.bounds.contains(it.bounds)
|
||||
} ?: return null
|
||||
val empty = heading.text in setOf("0条评论", "评论0")
|
||||
val frame = page.nodes.singleOrNull {
|
||||
it.resourceId == "slide_play_comment_frame" && it.isDescendantOf(root) &&
|
||||
it.bounds.top >= styles.bounds.bottom && root.bounds.contains(it.bounds)
|
||||
} ?: return null
|
||||
val list = page.nodes.singleOrNull {
|
||||
it.resourceId == "recycler_view" && it.className == "androidx.recyclerview.widget.RecyclerView" &&
|
||||
it.directParent() === frame && frame.bounds.contains(it.bounds) &&
|
||||
it.bounds.width() >= frame.bounds.width() * .9
|
||||
}
|
||||
if (!empty && list == null) return null
|
||||
return Panel(root, list, close, full, empty)
|
||||
}
|
||||
|
||||
private fun originalRows(page: UiPage, panel: Panel, key: String): List<Row> =
|
||||
visibleItems(page, panel, key).filter { it.kind == Kind.ORIGINAL }.mapNotNull(Item::row)
|
||||
|
||||
private fun readThread(page: UiPage, panel: Panel, row: Row, key: String): Thread {
|
||||
val list = panel.list ?: return Thread(row, emptyList(), false, null)
|
||||
val items = visibleItems(page, panel, key)
|
||||
val index = items.indexOfFirst { it.row?.container === row.container }
|
||||
if (index < 0) return Thread(row, emptyList(), false, null)
|
||||
val following = items.drop(index + 1)
|
||||
val section = following.takeWhile { it.kind != Kind.ORIGINAL && it.kind != Kind.END }
|
||||
val replies = section.filter { it.kind == Kind.NESTED }
|
||||
val continuation = section.filter { it.kind == Kind.MORE }.singleOrNull()?.expand
|
||||
val boundaryVisible = following.size > section.size
|
||||
val tail = section.lastOrNull()?.wrapper ?: items[index].wrapper
|
||||
val completeRows = section.dropLast(if (section.lastOrNull()?.kind == Kind.FOLD) 1 else 0)
|
||||
val complete = completeRows.all { it.kind == Kind.NESTED && it.row != null } &&
|
||||
(boundaryVisible || (list.bounds.contains(tail.bounds) &&
|
||||
!list.supports(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)))
|
||||
return Thread(row, replies.mapNotNull(Item::row), complete, continuation)
|
||||
}
|
||||
|
||||
private fun visibleItems(page: UiPage, panel: Panel, key: String): List<Item> {
|
||||
val list = panel.list ?: return emptyList()
|
||||
return page.nodes.filter { it.directParent() === list && Rect.intersects(list.bounds, it.bounds) }
|
||||
.sortedBy { it.bounds.top }.map { wrapper -> readItem(page, list, wrapper, key) }
|
||||
}
|
||||
|
||||
private fun readItem(page: UiPage, list: UiNode, wrapper: UiNode, key: String): Item {
|
||||
val children = page.nodes.filter { it.directParent() === wrapper }
|
||||
val end = children.singleOrNull { it.resourceId == "no_more_container" }
|
||||
if (end != null && page.nodes.count {
|
||||
it.directParent() === end && it.resourceId == "no_more_content" && it.labels() == listOf("没有更多评论")
|
||||
} == 1) return Item(wrapper, Kind.END, null, null)
|
||||
val more = children.singleOrNull { it.resourceId == "more_root_layout" }
|
||||
if (more != null) {
|
||||
val expand = page.nodes.singleOrNull {
|
||||
it.resourceId == "sub_comment_more" && it.isDescendantOf(more) && it.enabled && it.clickable &&
|
||||
more.bounds.contains(it.bounds) && moreReplies.matches(it.text)
|
||||
}
|
||||
val fold = expand == null && page.nodes.count {
|
||||
it.resourceId == "sub_comment_fold" && it.isDescendantOf(more) && it.labels() == listOf("收起") &&
|
||||
it.enabled && it.clickable && more.bounds.contains(it.bounds)
|
||||
} == 1
|
||||
return Item(wrapper, if (fold) Kind.FOLD else Kind.MORE, null, expand)
|
||||
}
|
||||
val container = children.singleOrNull { it.resourceId == "comment_frame" && it.clickable }
|
||||
?: return Item(wrapper, Kind.UNKNOWN, null, null)
|
||||
val avatar = page.nodes.singleOrNull { it.resourceId == "avatar" && it.directParent() === container }
|
||||
?: return Item(wrapper, Kind.UNKNOWN, null, null)
|
||||
val offset = avatar.bounds.left - list.bounds.left
|
||||
val kind = when {
|
||||
offset in 0..(list.bounds.width() / 10) -> Kind.ORIGINAL
|
||||
offset in (list.bounds.width() * .13).toInt()..(list.bounds.width() * .32).toInt() -> Kind.NESTED
|
||||
else -> Kind.UNKNOWN
|
||||
}
|
||||
return Item(wrapper, kind, readRow(page, list, container, key), null)
|
||||
}
|
||||
|
||||
private fun readRow(page: UiPage, list: UiNode, container: UiNode, key: String): Row? {
|
||||
val members = page.nodes.filter { it.isDescendantOf(container) && container.bounds.contains(it.bounds) }
|
||||
val author = members.singleOrNull { it.resourceId == "name" && it.text.isNotBlank() } ?: return null
|
||||
val body = members.singleOrNull { it.resourceId == "comment" && it.text.isNotBlank() } ?: return null
|
||||
val time = members.singleOrNull {
|
||||
it.resourceId in timeIds && it.text.isNotBlank() && it.bounds.top >= body.bounds.bottom
|
||||
} ?: return null
|
||||
if (author.bounds.bottom > body.bounds.top || list.bounds.top >= author.bounds.top ||
|
||||
list.bounds.bottom <= time.bounds.bottom || list.bounds.top >= container.bounds.bottom) return null
|
||||
val reply = members.singleOrNull {
|
||||
it.resourceId == "comment_reply" && it.labels() == listOf("回复") && it.enabled && it.clickable &&
|
||||
it.bounds.top >= body.bounds.bottom && list.bounds.contains(it.bounds)
|
||||
}
|
||||
val pictures = members.filter { it.resourceId == "comment_image" }
|
||||
val pictureGroups = members.filter { it.resourceId == "layout_emotion_image" }
|
||||
val photos = pictures.takeIf { images ->
|
||||
pictureGroups.all { group -> images.any { it.isDescendantOf(group) } } &&
|
||||
images.all { it.bounds.top >= body.bounds.bottom && it.bounds.bottom <= time.bounds.top &&
|
||||
pictureGroups.count { group -> it.isDescendantOf(group) } == 1 && list.bounds.contains(it.bounds) }
|
||||
}?.sortedWith(compareBy({ it.bounds.top }, { it.bounds.left }))
|
||||
val target = CommentTarget(targetKey(key, author.text, body.text), body.text, author.text)
|
||||
val own = members.any { it.resourceId == "comment_author_tag" && it.labels() == listOf("本人") }
|
||||
return Row(target, container, body, reply, time.text, photos, own)
|
||||
}
|
||||
|
||||
private fun positions(page: UiPage, list: UiNode): List<Pair<List<String>, Rect>> = page.nodes
|
||||
.filter { it.isDescendantOf(list) && it.labels().isNotEmpty() && list.bounds.contains(it.bounds) }
|
||||
.map { it.labels() to Rect(it.bounds) }
|
||||
|
||||
private fun targetKey(videoKey: String, author: String, body: String): String =
|
||||
MessageDigest.getInstance("SHA-256").digest("$videoKey\u0000$author\u0000$body".toByteArray(Charsets.UTF_8))
|
||||
.joinToString("") { "%02x".format(it) }
|
||||
|
||||
private companion object {
|
||||
val commentCount = Regex("(?:\\d+(?:\\.\\d+)?万?条评论|评论\\d+(?:\\.\\d+)?万?)")
|
||||
val moreReplies = Regex("展开[1-9]\\d*条回复")
|
||||
val timeIds = setOf("comment_created_time_and_loc", "comment_caption_meta_info")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
package com.jieliu.app.platform
|
||||
|
||||
import android.graphics.Rect
|
||||
import java.security.MessageDigest
|
||||
import kotlin.math.abs
|
||||
|
||||
internal class KuaishouNavigation(private val spec: PlatformSpec, private val ui: AccessibleUi) {
|
||||
private enum class Kind(val label: String, val slot: Int) { IMAGE("图片", 1), VIDEO("视频", 2) }
|
||||
|
||||
private data class SearchEditor(val input: UiNode, val submit: UiNode)
|
||||
private data class Results(val query: UiNode, val back: UiNode, val tabs: Map<Kind, UiNode>, val list: UiNode?)
|
||||
private data class Card(val node: UiNode, val author: String, val date: String, val imageMark: Boolean) {
|
||||
val identity: Pair<String, String> get() = author to date
|
||||
}
|
||||
private data class Player(val kind: Kind, val author: String, val date: String, val caption: String,
|
||||
val comment: UiNode, val back: UiNode) {
|
||||
fun matches(card: Card): Boolean = author == card.author && date == card.date
|
||||
}
|
||||
private data class Work(val context: VideoContext, val kind: Kind, val window: Int)
|
||||
private data class Opened(val card: Card, val bound: Work?)
|
||||
|
||||
private var query: String? = null
|
||||
private var active: Work? = null
|
||||
private val visited = mutableSetOf<String>()
|
||||
private val examined = Kind.entries.associateWith { mutableSetOf<Pair<String, String>>() }
|
||||
private val exhausted = mutableSetOf<Kind>()
|
||||
|
||||
fun launch() = ui.launchTarget(spec.label, foregroundTimeoutMs = 28_000)
|
||||
|
||||
fun search(keyword: String): VideoContext {
|
||||
val searchText = keyword.trim().takeIf(String::isNotEmpty)
|
||||
?: throw PlatformException("快手搜索关键词为空")
|
||||
active?.let { leave(it) }
|
||||
openSearch()
|
||||
ui.pace()
|
||||
val written = ui.await(4_000) {
|
||||
ui.inspect { page ->
|
||||
val editor = page.searchEditor()?.input ?: return@inspect null
|
||||
if (!editor.hasCurrentInputFocus()) {
|
||||
ui.click(editor)
|
||||
return@inspect null
|
||||
}
|
||||
editor.text == searchText && !editor.showingHint || ui.setText(editor, searchText)
|
||||
}
|
||||
} == true
|
||||
if (!written) throw PlatformException("快手搜索框未接受关键词")
|
||||
ui.pace()
|
||||
val submitted = ui.await(4_000) {
|
||||
ui.inspect { page ->
|
||||
val editor = page.searchEditor()?.takeIf { it.input.text == searchText && !it.input.showingHint }
|
||||
?: return@inspect null
|
||||
ui.click(editor.submit)
|
||||
}
|
||||
} == true
|
||||
if (!submitted || ui.await(8_000) { ui.inspect { it.results(searchText)?.query?.text } } != searchText) {
|
||||
throw PlatformException("快手未显示对应关键词的搜索结果和分类栏")
|
||||
}
|
||||
query = searchText
|
||||
visited.clear()
|
||||
exhausted.clear()
|
||||
examined.values.forEach { it.clear() }
|
||||
return openNext(Kind.IMAGE)
|
||||
}
|
||||
|
||||
fun currentVideo(): VideoContext = active?.let { work ->
|
||||
ui.await(4_000) { ui.inspect { page -> work.context.takeIf { matchesContent(page, it) } } }
|
||||
} ?: throw PlatformException("未能核对当前快手作品")
|
||||
|
||||
fun nextVideo(previous: VideoContext): VideoContext {
|
||||
val work = active?.takeIf { it.context == previous } ?: throw PlatformException("快手当前作品已变化")
|
||||
leave(work)
|
||||
return openNext(if (work.kind == Kind.IMAGE) Kind.VIDEO else Kind.IMAGE)
|
||||
}
|
||||
|
||||
fun matchesContent(page: UiPage, expected: VideoContext): Boolean {
|
||||
val work = active?.takeIf { it.context == expected && it.window == page.windowId } ?: return false
|
||||
val player = page.player() ?: return false
|
||||
return player.kind == work.kind && player.context() == expected
|
||||
}
|
||||
|
||||
fun openCommentPanel(page: UiPage, expected: VideoContext): Boolean =
|
||||
matchesContent(page, expected) && page.player()?.comment?.let { ui.click(it) } == true
|
||||
|
||||
private fun openSearch() {
|
||||
repeat(6) {
|
||||
val action = ui.await(5_000) {
|
||||
ui.inspect { page ->
|
||||
if (page.hasKuaishouCommentDraft()) throw PlatformException("请先处理快手中打开的评论草稿")
|
||||
if (page.searchEditor() != null) return@inspect "ready"
|
||||
val control = page.nodes.singleOrNull { it.resourceId == "tabs_panel_close" &&
|
||||
it.description == "关闭评论区" && it.kuaishouAction() }
|
||||
?: page.player()?.back
|
||||
?: page.results()?.back
|
||||
?: page.nodes.singleOrNull { it.resourceId == "nasa_featured_default_search_view" &&
|
||||
it.description == "查找" && it.kuaishouAction() }
|
||||
?: return@inspect null
|
||||
ui.pace()
|
||||
"moved".takeIf { ui.click(control) }
|
||||
}
|
||||
}
|
||||
if (action == "ready") return
|
||||
if (action == null) throw PlatformException("未找到快手的搜索入口")
|
||||
}
|
||||
throw PlatformException("未能打开快手的搜索框")
|
||||
}
|
||||
|
||||
private fun leave(work: Work) {
|
||||
ui.pace()
|
||||
val returned = ui.inspect { page ->
|
||||
matchesContent(page, work.context) && page.player()?.back?.let { ui.click(it) } == true
|
||||
} == true
|
||||
if (!returned || !awaitResults()) throw PlatformException("未能从同一快手作品返回搜索结果")
|
||||
active = null
|
||||
}
|
||||
|
||||
private fun awaitResults(): Boolean = ui.await(6_000) {
|
||||
ui.inspect { page -> true.takeIf { page.results(query) != null } }
|
||||
} == true
|
||||
|
||||
private fun openNext(preferred: Kind): VideoContext {
|
||||
val searchText = checkNotNull(query)
|
||||
for (kind in listOf(preferred) + Kind.entries.filterNot { it == preferred }) {
|
||||
if (kind in exhausted) continue
|
||||
if (selectTab(searchText, kind)) {
|
||||
findWork(searchText, kind)?.let { work ->
|
||||
active = work
|
||||
return work.context
|
||||
}
|
||||
}
|
||||
exhausted.add(kind)
|
||||
}
|
||||
throw PlatformException("快手「图片」和「视频」中没有更多可核对的作品")
|
||||
}
|
||||
|
||||
private fun selectTab(searchText: String, kind: Kind): Boolean {
|
||||
ui.pace()
|
||||
val clicked = ui.await(4_000) {
|
||||
ui.inspect { page ->
|
||||
val tab = page.results(searchText)?.tabs?.get(kind) ?: return@inspect null
|
||||
tab.selected || ui.click(tab)
|
||||
}
|
||||
} == true
|
||||
return clicked && ui.await(6_000) {
|
||||
ui.inspect { page -> true.takeIf { page.results(searchText)?.tabs?.get(kind)?.selected == true } }
|
||||
} == true
|
||||
}
|
||||
|
||||
private fun findWork(searchText: String, kind: Kind): Work? {
|
||||
val checked = examined.getValue(kind)
|
||||
var screens = 0
|
||||
repeat(25) {
|
||||
ui.pace()
|
||||
val clicked = ui.await(4_500) {
|
||||
ui.inspect { page ->
|
||||
val results = page.results(searchText)?.takeIf { it.tabs[kind]?.selected == true }
|
||||
?: return@inspect null
|
||||
val list = results.list ?: return@inspect null
|
||||
val cards = page.cards(list)
|
||||
if (cards.isEmpty()) return@inspect null
|
||||
val unique = cards.groupingBy(Card::identity).eachCount()
|
||||
val card = cards.filter { it.identity !in checked && unique[it.identity] == 1 &&
|
||||
(kind == Kind.IMAGE || !it.imageMark) }
|
||||
.sortedWith(compareBy<Card> { !it.imageMark }.thenBy { it.node.bounds.top }.thenBy { it.node.bounds.left })
|
||||
.firstOrNull()
|
||||
if (card == null) return@inspect Pick.None
|
||||
checked.add(card.identity)
|
||||
if (!ui.click(card.node)) throw PlatformException("未能打开已核对的快手搜索作品")
|
||||
Pick.CardOpened(card)
|
||||
}
|
||||
}
|
||||
if (clicked is Pick.CardOpened) {
|
||||
val work = readOpened(clicked.card, kind)
|
||||
if (work.bound != null && visited.add(work.bound.context.key)) return work.bound
|
||||
val backed = ui.inspect { page -> page.player()?.takeIf { it.matches(work.card) }
|
||||
?.back?.let { ui.click(it) } == true }
|
||||
if (backed != true || !awaitResults()) throw PlatformException("快手作品类型与所选分类不符,未能安全返回")
|
||||
} else {
|
||||
if (screens >= 6 || !scrollResults(searchText, kind)) return null
|
||||
screens++
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private sealed interface Pick {
|
||||
data class CardOpened(val card: Card) : Pick
|
||||
data object None : Pick
|
||||
}
|
||||
|
||||
private fun readOpened(card: Card, expectedKind: Kind): Opened = ui.await(6_000) {
|
||||
ui.inspect { page ->
|
||||
val player = page.player()?.takeIf { it.matches(card) } ?: return@inspect null
|
||||
Opened(card, Work(player.context(), player.kind, page.windowId).takeIf { player.kind == expectedKind })
|
||||
}
|
||||
} ?: throw PlatformException("快手详情页未对应刚选中的结果卡片")
|
||||
|
||||
private fun scrollResults(searchText: String, kind: Kind): Boolean {
|
||||
val before = ui.inspect { page ->
|
||||
val result = page.results(searchText)?.takeIf { it.tabs[kind]?.selected == true } ?: return@inspect null
|
||||
val list = result.list?.takeIf { it.scrollable } ?: return@inspect null
|
||||
page.cardPositions(list).takeIf { it.isNotEmpty() && ui.scrollUpInside(list.bounds) }
|
||||
} ?: return false
|
||||
return ui.await(3_000) {
|
||||
ui.inspect { page ->
|
||||
val list = page.results(searchText)?.takeIf { it.tabs[kind]?.selected == true }?.list
|
||||
?: return@inspect null
|
||||
val after = page.cardPositions(list)
|
||||
true.takeIf { after.isNotEmpty() && before != after }
|
||||
}
|
||||
} == true
|
||||
}
|
||||
|
||||
private fun UiPage.cardPositions(list: UiNode): List<Pair<String, Int>> = nodes.filter {
|
||||
it.directParent() === list && it.resourceId == "container" && it.description.endsWith("的作品")
|
||||
}.map { it.description to it.bounds.top }
|
||||
|
||||
private fun UiPage.searchEditor(): SearchEditor? {
|
||||
val top = nodes.singleOrNull { it.resourceId == "search_home_top_container" } ?: return null
|
||||
val input = nodes.singleOrNull { it.resourceId == "editor" && it.editable && it.isDescendantOf(top) } ?: return null
|
||||
val submit = nodes.singleOrNull { it.resourceId == "search_btn_container" && it.kuaishouAction() &&
|
||||
it.isDescendantOf(top) && it.bounds.left >= input.bounds.right } ?: return null
|
||||
return SearchEditor(input, submit)
|
||||
}
|
||||
|
||||
private fun UiPage.results(expectedQuery: String? = null): Results? {
|
||||
if (!complete) return null
|
||||
val root = nodes.singleOrNull { it.resourceId == "search_result_view" && bounds.contains(it.bounds) } ?: return null
|
||||
val header = nodes.singleOrNull { it.resourceId == "result_bar" && it.isDescendantOf(root) } ?: return null
|
||||
val query = nodes.singleOrNull { it.resourceId == "search_result_text" && it.isDescendantOf(header) &&
|
||||
it.text.isNotBlank() && (expectedQuery == null || expectedQuery == it.text) } ?: return null
|
||||
val back = nodes.singleOrNull { it.resourceId == "left_image" && it.isDescendantOf(header) &&
|
||||
it.kuaishouAction() && it.bounds.right <= query.bounds.left } ?: return null
|
||||
val container = nodes.singleOrNull { it.resourceId == "tab_container" && it.isDescendantOf(root) &&
|
||||
it.bounds.top >= query.bounds.bottom && it.bounds.width() >= bounds.width() * .85 } ?: return null
|
||||
val strip = nodes.singleOrNull { it.resourceId == "tabs" && it.directParent() === container &&
|
||||
it.className == "android.widget.HorizontalScrollView" } ?: return null
|
||||
val bar = nodes.singleOrNull { it.directParent() === strip && it.className == "android.widget.LinearLayout" } ?: return null
|
||||
val actions = nodes.filter { it.directParent() === bar && it.kuaishouAction() && bar.bounds.contains(it.bounds) }
|
||||
.sortedBy { it.bounds.left }
|
||||
val tabs = readSearchTabs(strip, actions) ?: return null
|
||||
val recycler = nodes.singleOrNull { it.resourceId == "recycler_view" && it.isDescendantOf(root) &&
|
||||
it.bounds.top >= container.bounds.bottom && it.bounds.width() >= bounds.width() * .85 }
|
||||
return Results(query, back, tabs, recycler)
|
||||
}
|
||||
|
||||
private fun readSearchTabs(strip: UiNode, actions: List<UiNode>): Map<Kind, UiNode>? {
|
||||
val labelled = Kind.entries.mapNotNull { kind ->
|
||||
actions.singleOrNull { kind.label in it.labels() }?.let { kind to it }
|
||||
}.toMap()
|
||||
if (labelled.size == Kind.entries.size) return labelled
|
||||
// In the observed native tab bar the first three controls are unlabelled virtual hit regions.
|
||||
val first = actions.take(3)
|
||||
if (actions.size !in 4..7 || first.size != 3 || actions.count(UiNode::selected) != 1 ||
|
||||
first.first().bounds.left != strip.bounds.left || first.any { it.labels().isNotEmpty() ||
|
||||
it.className != "android.view.View" || it.bounds.height() != strip.bounds.height() ||
|
||||
it.bounds.width() !in (strip.bounds.width() / 6)..(strip.bounds.width() / 4) } ||
|
||||
first.zipWithNext().any { (left, right) -> left.bounds.right != right.bounds.left ||
|
||||
abs(left.bounds.width() - right.bounds.width()) > strip.bounds.width() / 30 } ||
|
||||
first.withIndex().any { (index, node) -> node.horizontalItemIndex?.let { it != index } == true }
|
||||
) return null
|
||||
return Kind.entries.associateWith { actions[it.slot] }
|
||||
}
|
||||
|
||||
private fun UiPage.cards(list: UiNode): List<Card> = nodes.mapNotNull { row ->
|
||||
if (row.directParent() !== list || row.resourceId != "container" || !row.kuaishouAction() ||
|
||||
!list.bounds.contains(row.bounds) || row.bounds.height() < list.bounds.width() / 4
|
||||
) return@mapNotNull null
|
||||
val author = row.description.takeIf { it.endsWith("的作品") }?.removeSuffix("的作品")
|
||||
?.takeIf(String::isNotBlank) ?: return@mapNotNull null
|
||||
val descendants = nodes.filter { it.isDescendantOf(row) }
|
||||
val date = descendants.singleOrNull { it.resourceId == "bottom_created_time" && it.text.isNotBlank() }
|
||||
?.text ?: return@mapNotNull null
|
||||
if (descendants.none { it.resourceId == "cover_container" && it.directParent() === row } ) return@mapNotNull null
|
||||
Card(row, author, date, descendants.any { it.resourceId == "image_mark" && it.directParent() === row })
|
||||
}
|
||||
|
||||
private fun UiPage.player(): Player? {
|
||||
if (!complete) return null
|
||||
val pager = nodes.singleOrNull { it.resourceId == "nasa_groot_view_pager" &&
|
||||
it.bounds.width() >= bounds.width() * .85 } ?: return null
|
||||
val card = nodes.singleOrNull { it.directParent() === pager && it.resourceId == "root" &&
|
||||
it.bounds.width() >= pager.bounds.width() * .85 } ?: return null
|
||||
val image = card.description == "查看图片详情" || nodes.any { it.directParent() === card &&
|
||||
it.resourceId == "autoplay_cover_view_page_style" }
|
||||
val video = nodes.any { it.directParent() === card && it.resourceId == "player" }
|
||||
if (image == video) return null
|
||||
val identity = nodes.singleOrNull { it.resourceId == "slide_play_avatar_click_area" &&
|
||||
it.isDescendantOf(card) && it.description.endsWith("作者头像") } ?: return null
|
||||
val author = identity.description.removeSuffix("作者头像").takeIf(String::isNotBlank) ?: return null
|
||||
val date = nodes.singleOrNull { it.resourceId == "create_date_tv" && it.isDescendantOf(card) &&
|
||||
it.text.isNotBlank() }?.text ?: return null
|
||||
val caption = nodes.singleOrNull { it.resourceId == "element_caption_label" && it.isDescendantOf(card) }
|
||||
?.text.orEmpty().substringBefore(" … 展开").trim()
|
||||
val comment = nodes.singleOrNull { it.resourceId == "comment_button" && it.isDescendantOf(card) &&
|
||||
it.kuaishouAction() && it.description.startsWith("评论") } ?: return null
|
||||
val back = nodes.singleOrNull { it.resourceId == "photo_detail_back_btn" && it.kuaishouAction() &&
|
||||
it.bounds.left < x(.16f) && it.bounds.bottom < y(.16f) } ?: return null
|
||||
return Player(if (image) Kind.IMAGE else Kind.VIDEO, author, date, caption, comment, back)
|
||||
}
|
||||
|
||||
private fun Player.context(): VideoContext {
|
||||
val identity = listOf(kind.name, author, date, caption).joinToString("\u0000")
|
||||
val key = MessageDigest.getInstance("SHA-256").digest(identity.toByteArray(Charsets.UTF_8))
|
||||
.joinToString("") { "%02x".format(it) }
|
||||
return VideoContext(key, caption.ifBlank { "$author 的${kind.label}作品" })
|
||||
}
|
||||
}
|
||||
|
||||
private fun UiNode.kuaishouAction(): Boolean = enabled && clickable && !editable
|
||||
@@ -0,0 +1,285 @@
|
||||
package com.jieliu.app.platform
|
||||
|
||||
import android.graphics.Rect
|
||||
import android.os.SystemClock
|
||||
import android.view.accessibility.AccessibilityNodeInfo
|
||||
import com.jieliu.app.task.TaskPlan
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.floor
|
||||
|
||||
/** Selects the bound photos from the native comment attachment picker. */
|
||||
internal class KuaishouPhotoPicker(private val ui: AccessibleUi) {
|
||||
private data class Surface(val window: Int, val container: UiNodeSource) : AutoCloseable {
|
||||
override fun close() = container.close()
|
||||
}
|
||||
|
||||
private data class Picker(
|
||||
val album: UiNode,
|
||||
val albumAction: UiNode,
|
||||
val multi: UiNode,
|
||||
val grid: UiNode,
|
||||
val handoff: UiNode?,
|
||||
val selectedCount: Int,
|
||||
)
|
||||
|
||||
private data class Crop(val image: Rect, val indicator: Rect)
|
||||
private data class Tile(val action: UiNode, val crop: Crop, val ordinal: Int?)
|
||||
private data class Selection(val picker: Picker, val tiles: List<Tile>)
|
||||
|
||||
fun select(album: String, references: List<PhotoPixels>, beforeCommitSelection: () -> Unit) {
|
||||
require(stagedAlbum.matches(album) && references.size in 1..TaskPlan.MAX_TEMPLATE_PHOTOS)
|
||||
val surface = awaitPage("快手未打开可核对的图片选择器,请检查相册权限") { page ->
|
||||
val container = page.pickerContainer() ?: return@awaitPage null
|
||||
val picker = page.readPicker(container) ?: return@awaitPage null
|
||||
if (picker.selectedCount != 0) throw PlatformException("快手相册已选中其他图片,请清空后重试")
|
||||
Surface(page.windowId, container.retainSource())
|
||||
}
|
||||
surface.use {
|
||||
enableMulti(surface)
|
||||
openAlbum(surface, album, references.size)
|
||||
val regions = awaitPage("快手专用相册未完整显示本次绑定图片") { page ->
|
||||
page.selection(surface, album, references.size)?.takeIf {
|
||||
it.picker.selectedCount == 0 && it.tiles.none { tile -> tile.ordinal != null }
|
||||
}?.tiles?.map(Tile::crop)
|
||||
}
|
||||
val order = readPhotoOrder(surface, album, regions, references)
|
||||
|
||||
val selected = mutableListOf<Int>()
|
||||
for (tileIndex in order) {
|
||||
ui.pace()
|
||||
val clicked = ui.inspect { page ->
|
||||
val current = page.verifiedSelection(surface, album, regions, selected) ?: return@inspect false
|
||||
ui.click(current.tiles[tileIndex].action)
|
||||
} == true
|
||||
if (!clicked) throw PlatformException("快手未接受第 ${selected.size + 1} 张图片的选择")
|
||||
selected.add(tileIndex)
|
||||
awaitPage("快手未核对第 ${selected.size} 张图片的选中序号") { page ->
|
||||
true.takeIf { page.verifiedSelection(surface, album, regions, selected) != null }
|
||||
}
|
||||
}
|
||||
|
||||
ui.pace()
|
||||
val handedOff = ui.inspect { page ->
|
||||
val current = page.verifiedSelection(surface, album, regions, selected) ?: return@inspect false
|
||||
val next = current.picker.handoff?.takeIf { it.canClick() } ?: return@inspect false
|
||||
beforeCommitSelection()
|
||||
ui.click(next)
|
||||
} == true
|
||||
if (!handedOff) throw PlatformException("快手未确认将选中图片带回评论编辑框")
|
||||
}
|
||||
}
|
||||
|
||||
private fun enableMulti(surface: Surface) {
|
||||
ui.pace()
|
||||
val accepted = ui.inspect { page ->
|
||||
val picker = page.readPicker(surface) ?: return@inspect false
|
||||
if (picker.selectedCount != 0) return@inspect false
|
||||
picker.multi.selected || ui.click(picker.multi)
|
||||
} == true
|
||||
if (!accepted) throw PlatformException("快手相册未开启多选")
|
||||
awaitPage("快手相册未显示多选确认控件") { page ->
|
||||
true.takeIf { page.readPicker(surface)?.let { it.multi.selected && it.selectedCount == 0 } == true }
|
||||
}
|
||||
}
|
||||
|
||||
private fun openAlbum(surface: Surface, album: String, count: Int) {
|
||||
ui.pace()
|
||||
val openedList = ui.inspect { page ->
|
||||
val picker = page.readPicker(surface)?.takeIf { it.multi.selected && it.selectedCount == 0 }
|
||||
?: return@inspect null
|
||||
if (picker.album.text == album) return@inspect false
|
||||
true.takeIf { ui.click(picker.albumAction) }
|
||||
} ?: throw PlatformException("快手未展开已核对的相册列表")
|
||||
if (!openedList) return
|
||||
|
||||
val source = awaitPage("快手未显示原生相册列表") { page ->
|
||||
page.pickerContainer(surface)?.let { page.albumList(it) }?.retainSource()
|
||||
}
|
||||
source.use {
|
||||
repeat(MAX_ALBUM_SCREENS) { index ->
|
||||
ui.pace()
|
||||
val result = ui.inspect { page ->
|
||||
val container = page.pickerContainer(surface) ?: return@inspect null
|
||||
val list = page.albumList(container)?.takeIf { it.hasSource(source) } ?: return@inspect null
|
||||
val labels = page.nodes.filter {
|
||||
it.resourceId == "label" && it.text == album && it.isDescendantOf(list)
|
||||
}
|
||||
if (labels.isEmpty()) {
|
||||
return@inspect false.takeIf { index < MAX_ALBUM_SCREENS - 1 &&
|
||||
list.scrollable && list.act(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD) }
|
||||
}
|
||||
val label = labels.singleOrNull() ?: throw PlatformException("快手相册中存在多个同名专用相册")
|
||||
val labelsContainer = label.directParent() ?: return@inspect null
|
||||
val row = labelsContainer.directParent()?.takeIf {
|
||||
it.resourceId == "item_root" && it.directParent() === list && it.canClick() &&
|
||||
list.bounds.contains(it.bounds) && it.bounds.contains(labelsContainer.bounds) &&
|
||||
labelsContainer.bounds.contains(label.bounds)
|
||||
} ?: return@inspect null
|
||||
val quantity = page.nativeChild(labelsContainer, "photo_count")
|
||||
if (quantity?.text?.toIntOrNull() != count) {
|
||||
throw PlatformException("快手专用相册中的图片数量与本次绑定不符")
|
||||
}
|
||||
true.takeIf { ui.click(row) }
|
||||
} ?: throw PlatformException("快手相册列表中未找到可核对的本次专用相册")
|
||||
if (result) return
|
||||
}
|
||||
}
|
||||
throw PlatformException("快手相册列表中未找到本次专用相册")
|
||||
}
|
||||
|
||||
private fun readPhotoOrder(
|
||||
surface: Surface,
|
||||
album: String,
|
||||
regions: List<Crop>,
|
||||
references: List<PhotoPixels>,
|
||||
): List<Int> {
|
||||
var nextCapture = 0L
|
||||
return ui.await(5_000) {
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
if (now < nextCapture || !isUnselected(surface, album, regions)) return@await null
|
||||
nextCapture = now + 350L
|
||||
val pictures = ui.screenshotPhotos(surface.window, regions.map(Crop::image))
|
||||
?.takeIf { it.size == regions.size && isUnselected(surface, album, regions) } ?: return@await null
|
||||
val visible = pictures.zip(regions).map { (pixels, region) -> pixels.maskIndicator(region) }
|
||||
bilibiliAttachmentOrder(references, visible)
|
||||
} ?: throw PlatformException("快手专用相册的缩略图无法与绑定图片逐一对应")
|
||||
}
|
||||
|
||||
private fun isUnselected(surface: Surface, album: String, regions: List<Crop>): Boolean =
|
||||
ui.inspect { it.verifiedSelection(surface, album, regions, emptyList()) != null } == true
|
||||
|
||||
private fun UiPage.verifiedSelection(
|
||||
surface: Surface,
|
||||
album: String,
|
||||
regions: List<Crop>,
|
||||
selected: List<Int>,
|
||||
): Selection? {
|
||||
val current = selection(surface, album, regions.size) ?: return null
|
||||
if (current.picker.selectedCount != selected.size || current.tiles.map(Tile::crop) != regions) return null
|
||||
return current.takeIf {
|
||||
it.tiles.withIndex().all { (index, tile) ->
|
||||
val position = selected.indexOf(index)
|
||||
tile.ordinal == (position + 1).takeIf { position >= 0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun UiPage.selection(surface: Surface, album: String, count: Int): Selection? {
|
||||
val picker = readPicker(surface)?.takeIf {
|
||||
it.album.text == album && it.multi.selected && it.selectedCount in 0..count
|
||||
} ?: return null
|
||||
val cells = nodes.filter { it.resourceId == "preview_container" && it.directParent() === picker.grid }
|
||||
val camera = cells.filter { nativeChild(it, "ksa_take_photo_layout") != null }
|
||||
if (camera.size > 1 || camera.any { nativeChild(it, "media_preview") != null }) return null
|
||||
val media = cells - camera.toSet()
|
||||
if (media.size != count || media.any { !picker.grid.bounds.contains(it.bounds) }) return null
|
||||
val tiles = media.map { cell ->
|
||||
val image = nativeChild(cell, "media_preview")?.takeIf {
|
||||
it.className == "android.widget.ImageView" && it.labels() == listOf("预览")
|
||||
} ?: return null
|
||||
val action = nativeChild(cell, "media_pick_num_area")?.takeIf { it.canClick() } ?: return null
|
||||
val indicator = nativeDescendant(action, "item_select_circle")?.takeIf {
|
||||
image.bounds.contains(it.bounds) && it.bounds.width() <= image.bounds.width() / 3 &&
|
||||
it.bounds.height() <= image.bounds.height() / 3
|
||||
} ?: return null
|
||||
val numbers = nodes.filter { it.resourceId == "media_pick_num" && it.isDescendantOf(action) }
|
||||
if (numbers.size > 1) return null
|
||||
val ordinal = numbers.singleOrNull()?.let { badge ->
|
||||
if (!indicator.bounds.contains(badge.bounds)) return null
|
||||
badge.text.toIntOrNull()?.takeIf { it in 1..count } ?: return null
|
||||
}
|
||||
Tile(action, Crop(Rect(image.bounds), Rect(indicator.bounds)), ordinal)
|
||||
}.sortedWith(compareBy<Tile> { it.crop.image.top }.thenBy { it.crop.image.left })
|
||||
if (tiles.indices.any { index -> tiles.take(index).any { Rect.intersects(it.crop.image, tiles[index].crop.image) } }) return null
|
||||
return Selection(picker, tiles)
|
||||
}
|
||||
|
||||
private fun UiPage.pickerContainer(surface: Surface? = null): UiNode? {
|
||||
if (!complete || surface?.window?.let { it != windowId } == true) return null
|
||||
return nodes.singleOrNull {
|
||||
it.resourceId == "photo_container" && it.className == "android.widget.FrameLayout" &&
|
||||
bounds.contains(it.bounds) && surface?.container?.let(it::hasSource) != false
|
||||
}
|
||||
}
|
||||
|
||||
private fun UiPage.readPicker(surface: Surface): Picker? = pickerContainer(surface)?.let { readPicker(it) }
|
||||
|
||||
private fun UiPage.readPicker(container: UiNode): Picker? {
|
||||
if (albumList(container) != null) return null
|
||||
val toolbar = nativeChild(container, "photo_picker_title_bar") ?: return null
|
||||
val album = nativeDescendant(toolbar, "tab_text")?.takeIf { it.selected && it.text.isNotEmpty() } ?: return null
|
||||
val title = album.directParent()?.takeIf { it.resourceId == "title_tv_wrapper" } ?: return null
|
||||
val albumAction = title.directParent()?.takeIf {
|
||||
it.canClick() && it.isDescendantOf(toolbar) && toolbar.bounds.contains(it.bounds) &&
|
||||
nativeChild(it, "album_indicator") != null
|
||||
} ?: return null
|
||||
val grid = nativeDescendant(container, "album_view_list")?.takeIf {
|
||||
it.className == RECYCLER && it.bounds.top >= toolbar.bounds.bottom
|
||||
} ?: return null
|
||||
val bottom = nativeChild(container, "picked_layout") ?: return null
|
||||
val toggle = nativeChild(bottom, "single_multi_select_layout") ?: return null
|
||||
val multi = nativeChild(toggle, "single_multi_select_icon")?.takeIf { it.canClick() } ?: return null
|
||||
if (nativeChild(toggle, "single_multi_select_text")?.labels() != listOf("多选")) return null
|
||||
val handoffs = nodes.filter { it.resourceId == "next_step" && it.isDescendantOf(bottom) && bottom.bounds.contains(it.bounds) }
|
||||
val handoff = handoffs.singleOrNull()
|
||||
val tray = nativeChild(bottom, "picked_recycler_view") ?: return null
|
||||
val alreadyPicked = nodes.any { it.resourceId == "media_preview" && it.isDescendantOf(tray) }
|
||||
val selected = if (multi.selected) {
|
||||
val button = handoff?.takeIf { it.className == "android.widget.Button" } ?: return null
|
||||
val label = nextStep.matchEntire(button.text)?.groupValues?.get(1) ?: return null
|
||||
if (label.isEmpty()) 0 else label.toIntOrNull() ?: return null
|
||||
} else {
|
||||
if (handoffs.isNotEmpty() || alreadyPicked) return null
|
||||
0
|
||||
}
|
||||
if ((selected == 0) == alreadyPicked) return null
|
||||
return Picker(album, albumAction, multi, grid, handoff, selected)
|
||||
}
|
||||
|
||||
private fun UiPage.albumList(container: UiNode): UiNode? {
|
||||
val overlay = nativeChild(container, "album_list_container") ?: return null
|
||||
return nativeDescendant(overlay, "recycler_view")?.takeIf { it.className == RECYCLER }
|
||||
}
|
||||
|
||||
private fun UiPage.nativeChild(parent: UiNode, id: String): UiNode? = nodes.singleOrNull {
|
||||
it.resourceId == id && it.directParent() === parent && parent.bounds.contains(it.bounds)
|
||||
}
|
||||
|
||||
private fun UiPage.nativeDescendant(parent: UiNode, id: String): UiNode? = nodes.singleOrNull {
|
||||
it.resourceId == id && it.isDescendantOf(parent) && parent.bounds.contains(it.bounds)
|
||||
}
|
||||
|
||||
private fun PhotoPixels.maskIndicator(crop: Crop): PhotoPixels {
|
||||
val indicator = Rect(crop.indicator).apply { inset(-2, -2) }
|
||||
val image = crop.image
|
||||
if (!indicator.intersect(image)) return this
|
||||
val x = width.toDouble() / image.width()
|
||||
val y = height.toDouble() / image.height()
|
||||
val left = floor((indicator.left - image.left) * x).toInt().coerceIn(0, width)
|
||||
val right = ceil((indicator.right - image.left) * x).toInt().coerceIn(left, width)
|
||||
val top = floor((indicator.top - image.top) * y).toInt().coerceIn(0, height)
|
||||
val bottom = ceil((indicator.bottom - image.top) * y).toInt().coerceIn(top, height)
|
||||
return copy(argb = argb.copyOf().apply {
|
||||
for (row in top until bottom) fill(0, row * width + left, row * width + right)
|
||||
})
|
||||
}
|
||||
|
||||
private fun <T : Any> awaitPage(message: String, probe: (UiPage) -> T?): T =
|
||||
ui.await(5_000) {
|
||||
ui.inspect { page ->
|
||||
if (page.nodes.any { it.resourceId == "title" && it.labels() == listOf("开启相册权限") }) {
|
||||
throw PlatformException("请先在快手允许相册权限,再继续选择评论图片")
|
||||
}
|
||||
probe(page)
|
||||
}
|
||||
} ?: throw PlatformException(message)
|
||||
|
||||
private fun UiNode.canClick(): Boolean = enabled && supports(AccessibilityNodeInfo.ACTION_CLICK)
|
||||
|
||||
private companion object {
|
||||
const val MAX_ALBUM_SCREENS = 7
|
||||
const val RECYCLER = "androidx.recyclerview.widget.RecyclerView"
|
||||
val stagedAlbum = Regex("SJ-[0-9a-f]{12}")
|
||||
val nextStep = Regex("下一步(?:\\(([1-9])\\))?")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
package com.jieliu.app.platform
|
||||
|
||||
import android.graphics.Rect
|
||||
import android.os.Build
|
||||
import android.view.accessibility.AccessibilityNodeInfo
|
||||
import com.jieliu.app.data.PhotoLibrary
|
||||
import com.jieliu.app.data.StagedPhotos
|
||||
import com.jieliu.app.task.RECHECK_WINDOW_MS
|
||||
import com.jieliu.app.task.TemplatePhoto
|
||||
import java.io.Closeable
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.floor
|
||||
|
||||
internal class KuaishouReplies(
|
||||
private val ui: AccessibleUi,
|
||||
private val comments: KuaishouComments,
|
||||
private val photos: PhotoLibrary,
|
||||
private val diagnostic: (String) -> Unit,
|
||||
) {
|
||||
private data class Editor(
|
||||
val container: UiNode,
|
||||
val input: UiNode,
|
||||
val send: UiNode,
|
||||
val sendWrapper: UiNode,
|
||||
val picture: UiNode?,
|
||||
val images: List<DraftImage>,
|
||||
)
|
||||
|
||||
private class Prepared(
|
||||
val target: CommentTarget,
|
||||
val text: String,
|
||||
val window: Int,
|
||||
val container: UiNodeSource,
|
||||
val input: UiNodeSource,
|
||||
) : Closeable {
|
||||
override fun close() {
|
||||
container.close()
|
||||
input.close()
|
||||
}
|
||||
}
|
||||
|
||||
private data class Receipt(val window: Int, val key: String, val images: List<Rect>)
|
||||
private data class DraftImage(val area: Rect, val close: Rect)
|
||||
private enum class Role { OWN, OTHER }
|
||||
private data class RoleMenu(val window: Int, val role: Role?)
|
||||
|
||||
private var prepared: Prepared? = null
|
||||
private val picker = KuaishouPhotoPicker(ui)
|
||||
|
||||
fun prepare(target: CommentTarget, text: String, requiresImages: Boolean): Boolean {
|
||||
check(prepared == null) { "快手回复草稿尚未完成" }
|
||||
if (text.isBlank()) return false
|
||||
if (requiresImages && Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
|
||||
throw PlatformException("快手图片核对需要 Android 11 或更新版本")
|
||||
}
|
||||
if (!comments.ensureThread(target.key, target.author)) return false
|
||||
if (inspectRole(target.key, target.author, target.key, null) != Role.OTHER) return false
|
||||
ui.pace()
|
||||
val opened = comments.readThread(target.key, target.author) { page, _, thread ->
|
||||
if (!thread.complete || thread.original.target != target || thread.original.own ||
|
||||
thread.replies.any { it.target.text == text } || page.hasKuaishouCommentDraft()) return@readThread false
|
||||
thread.original.reply?.let { ui.click(it) } == true
|
||||
} == true
|
||||
if (!opened) return false
|
||||
prepared = ui.await(5_000) {
|
||||
ui.inspect(traverseHiddenParents = true) { page ->
|
||||
val editor = readEditor(page, target) ?: return@inspect null
|
||||
if (!editor.input.isStillBlankAndFocused() || editor.images.isNotEmpty()) return@inspect null
|
||||
if (requiresImages && editor.picture == null) {
|
||||
throw PlatformException("当前快手回复框未提供可核对的图片入口")
|
||||
}
|
||||
Prepared(target, text, page.windowId, editor.container.retainSource(), editor.input.retainSource())
|
||||
}
|
||||
} ?: throw PlatformException("快手未显示可核对的空白定向回复框")
|
||||
return true
|
||||
}
|
||||
|
||||
fun hasPreparedBaseline(key: String, text: String): Boolean = prepared?.let {
|
||||
it.target.key == key && it.text == text
|
||||
} == true
|
||||
|
||||
fun preparedTarget(text: String): CommentTarget = prepared?.takeIf { it.text == text }?.target
|
||||
?: throw PlatformException("快手回复对象或正文尚未核对")
|
||||
|
||||
fun submit(target: CommentTarget, text: String, attachments: List<TemplatePhoto>, arm: () -> Unit): Boolean {
|
||||
val session = prepared?.takeIf { it.target == target && it.text == text }
|
||||
?: throw PlatformException("快手回复对象或正文已经变化")
|
||||
var staged: StagedPhotos? = null
|
||||
var handedToEditor = false
|
||||
try {
|
||||
val references = photos.readReceiptPixels(attachments) ?: throw PlatformException("无法读取快手回复的绑定图片")
|
||||
if (attachments.isNotEmpty()) {
|
||||
photos.cleanupStaged()
|
||||
val album = photos.stage(attachments)
|
||||
staged = album
|
||||
ui.pace()
|
||||
val opened = ui.inspect(traverseHiddenParents = true) { page ->
|
||||
val draft = checkedEditor(page, session) ?: return@inspect false
|
||||
draft.images.isEmpty() && draft.input.isStillBlankAndFocused() &&
|
||||
draft.picture?.let { ui.click(it) } == true
|
||||
} == true
|
||||
if (!opened) throw PlatformException("未打开快手定向回复的图片选择器")
|
||||
picker.select(album.albumName, references) { handedToEditor = true }
|
||||
}
|
||||
ui.pace()
|
||||
val written = ui.await(4_000) {
|
||||
ui.inspect(traverseHiddenParents = true) { page ->
|
||||
val draft = checkedEditor(page, session) ?: return@inspect null
|
||||
if (draft.images.size != references.size || draft.input.hasDraft()) return@inspect null
|
||||
if (!draft.input.focused) {
|
||||
ui.click(draft.input)
|
||||
return@inspect null
|
||||
}
|
||||
ui.setText(draft.input, text, requireBlankFocusedInput = true)
|
||||
}
|
||||
} == true
|
||||
if (!written) throw PlatformException("未能在快手定向回复框写入正文")
|
||||
ui.pace()
|
||||
val ready = ui.await(4_000) {
|
||||
ui.inspect(traverseHiddenParents = true) { page -> readyDraft(page, session, references.size)?.images }
|
||||
} ?: throw PlatformException("快手未能核对回复草稿和发送按钮")
|
||||
val captured = ui.screenshotPhotos(session.window, ready.map(DraftImage::area))?.takeIf { it.size == ready.size }
|
||||
?.zip(ready) { pixels, image -> pixels.withoutDraftClose(image) }
|
||||
val unchanged = ui.inspect(traverseHiddenParents = true) { page ->
|
||||
readyDraft(page, session, references.size)?.images == ready
|
||||
} == true
|
||||
if (!unchanged || captured == null || !matchPhotos(references, captured)) {
|
||||
throw PlatformException("快手草稿图片与按顺序绑定的图片不一致")
|
||||
}
|
||||
arm()
|
||||
return ui.inspect(traverseHiddenParents = true) { page ->
|
||||
val draft = readyDraft(page, session, references.size)?.takeIf { it.images == ready } ?: return@inspect false
|
||||
ui.click(draft.sendWrapper)
|
||||
} == true
|
||||
} finally {
|
||||
reset()
|
||||
staged?.let { if (handedToEditor) photos.leaveStagedForReview(it) else photos.removeStaged(it) }
|
||||
}
|
||||
}
|
||||
|
||||
fun confirm(key: String, author: String, text: String, attachments: List<TemplatePhoto>, armedAt: Long): CommentPublishResult {
|
||||
val age = System.currentTimeMillis() - armedAt
|
||||
if (armedAt <= 0 || age !in 0..RECHECK_WINDOW_MS) return CommentPublishResult.UNCERTAIN
|
||||
val references = photos.readReceiptPixels(attachments) ?: return CommentPublishResult.UNCERTAIN
|
||||
repeat(RECEIPT_SCREENS) { screen ->
|
||||
val visible = comments.readThread(key, author) { _, _, _ -> true } == true
|
||||
if (visible) {
|
||||
if (!comments.ensureThread(key, author)) return CommentPublishResult.UNCERTAIN
|
||||
val before = ui.await(4_500) { readReceipt(key, author, text, references.size, armedAt) }
|
||||
?: return CommentPublishResult.UNCERTAIN
|
||||
val captured = ui.screenshotPhotos(before.window, before.images) ?: return CommentPublishResult.UNCERTAIN
|
||||
if (readReceipt(key, author, text, references.size, armedAt) != before || !matchPhotos(references, captured)) {
|
||||
return CommentPublishResult.UNCERTAIN
|
||||
}
|
||||
if (inspectRole(key, author, key, before) != Role.OTHER ||
|
||||
inspectRole(key, author, before.key, before) != Role.OWN ||
|
||||
readReceipt(key, author, text, references.size, armedAt) != before) {
|
||||
return CommentPublishResult.UNCERTAIN
|
||||
}
|
||||
diagnostic("快手已核对原评论下的本人回复正文及 ${references.size} 张图片")
|
||||
if (references.isNotEmpty()) photos.cleanupStaged()
|
||||
return CommentPublishResult.CONFIRMED
|
||||
}
|
||||
if (screen == RECEIPT_SCREENS - 1 || !comments.scroll()) return CommentPublishResult.UNCERTAIN
|
||||
}
|
||||
return CommentPublishResult.UNCERTAIN
|
||||
}
|
||||
|
||||
fun hasUnsettledEditor(): Boolean = ui.inspect(traverseHiddenParents = true) { it.hasKuaishouCommentDraft() } == true
|
||||
|
||||
fun reset() {
|
||||
prepared?.close()
|
||||
prepared = null
|
||||
}
|
||||
|
||||
private fun checkedEditor(page: UiPage, session: Prepared): Editor? =
|
||||
readEditor(page, session.target)?.takeIf {
|
||||
page.windowId == session.window && it.container.hasSource(session.container) && it.input.hasSource(session.input)
|
||||
}
|
||||
|
||||
private fun readyDraft(page: UiPage, session: Prepared, count: Int): Editor? {
|
||||
val editor = checkedEditor(page, session)?.takeIf {
|
||||
it.images.size == count && it.input.hasCurrentFocusedText(session.text) { hint ->
|
||||
replyPrompt(hint, session.target.author)
|
||||
} && it.send.enabled && it.sendWrapper.clickable
|
||||
} ?: return null
|
||||
val regions = editor.images.map(DraftImage::area)
|
||||
if (regions.any { it.isEmpty || !page.bounds.contains(it) } || regions.hasOverlap()) return null
|
||||
return editor
|
||||
}
|
||||
|
||||
private fun matchPhotos(references: List<PhotoPixels>, actual: List<PhotoPixels>): Boolean =
|
||||
references.size == actual.size && references.indices.all { PublishedPhotoMatcher.matches(references[it], actual[it]) }
|
||||
|
||||
private fun List<Rect>.hasOverlap(): Boolean = indices.any { index ->
|
||||
subList(0, index).any { Rect.intersects(it, this[index]) }
|
||||
}
|
||||
|
||||
private fun readEditor(page: UiPage, target: CommentTarget): Editor? {
|
||||
if (!page.complete) return null
|
||||
val container = page.nodes.singleOrNull {
|
||||
it.resourceId == "editor_animation_frame" && page.bounds.contains(it.bounds) &&
|
||||
generateSequence(it.directParent(), UiNode::directParent).take(6)
|
||||
.any { ancestor -> ancestor.resourceId == "comment_editor_container" }
|
||||
} ?: return null
|
||||
val members = page.nodes.filter { it.isDescendantOf(container) && container.bounds.contains(it.bounds) }
|
||||
val input = members.singleOrNull {
|
||||
it.resourceId == "editor" && it.className == "android.widget.EditText" && it.editable &&
|
||||
it.directParent()?.resourceId == "edit_container" && replyPrompt(it.hint.ifBlank {
|
||||
if (it.showingHint) it.text else ""
|
||||
}, target.author)
|
||||
} ?: return null
|
||||
val send = members.singleOrNull {
|
||||
it.resourceId == "finish_button" && it.className == "android.widget.Button" && it.labels() == listOf("发送")
|
||||
} ?: return null
|
||||
val wrapper = send.directParent()?.takeIf {
|
||||
it.resourceId == "finish_button_wrapper" && it.directParent()?.resourceId == "operation_buttons_layout" &&
|
||||
it.bounds.contains(send.bounds) && it.bounds.top >= input.bounds.bottom
|
||||
} ?: return null
|
||||
val picture = members.singleOrNull {
|
||||
it.resourceId == "picture_button_layout" && it.labels() == listOf("发布图片") &&
|
||||
it.clickable && it.enabled && it.bounds.top >= input.bounds.bottom && it.bounds.right < wrapper.bounds.left
|
||||
}
|
||||
val images = readDraftImages(members, input) ?: return null
|
||||
return Editor(container, input, send, wrapper, picture, images)
|
||||
}
|
||||
|
||||
private fun readDraftImages(members: List<UiNode>, input: UiNode): List<DraftImage>? {
|
||||
val grids = members.filter { it.resourceId == "multi_picture_recycler_view" }
|
||||
if (grids.isEmpty()) {
|
||||
return emptyList<DraftImage>().takeIf { members.none { it.resourceId in attachmentNodes } }
|
||||
}
|
||||
val grid = grids.singleOrNull()?.takeIf {
|
||||
it.className == "androidx.recyclerview.widget.RecyclerView" && it.bounds.bottom <= input.bounds.top &&
|
||||
it.directParent()?.resourceId == "emotion_preview_parent_layout" && !it.scrollable
|
||||
} ?: return null
|
||||
val tiles = members.filter { it.directParent() === grid }.sortedBy { it.bounds.left }
|
||||
val add = tiles.lastOrNull()?.takeIf { tile ->
|
||||
tile.resourceId == "add_image" && tile.clickable && grid.bounds.contains(tile.bounds) &&
|
||||
members.count { it.directParent() === tile && it.resourceId == "add_image_icon" } == 1
|
||||
}
|
||||
return (if (add != null) tiles.dropLast(1) else tiles).map { item ->
|
||||
if (item.resourceId != "preview_image_layout" || !grid.bounds.contains(item.bounds)) return null
|
||||
val image = members.singleOrNull {
|
||||
it.directParent() === item && it.resourceId == "preview_image" && it.bounds == item.bounds
|
||||
} ?: return null
|
||||
val close = members.singleOrNull {
|
||||
it.directParent() === item && it.resourceId == "preview_close" && it.clickable &&
|
||||
image.bounds.contains(it.bounds) && it.bounds.right == image.bounds.right &&
|
||||
it.bounds.top == image.bounds.top && it.bounds.width() < image.bounds.width() / 2 &&
|
||||
it.bounds.height() < image.bounds.height() / 2
|
||||
} ?: return null
|
||||
DraftImage(Rect(image.bounds), Rect(close.bounds))
|
||||
}
|
||||
}
|
||||
|
||||
private fun PhotoPixels.withoutDraftClose(image: DraftImage): PhotoPixels {
|
||||
val xScale = width.toDouble() / image.area.width()
|
||||
val yScale = height.toDouble() / image.area.height()
|
||||
val left = floor((image.close.left - image.area.left) * xScale).toInt().coerceIn(0, width)
|
||||
val right = ceil((image.close.right - image.area.left) * xScale).toInt().coerceIn(left, width)
|
||||
val top = floor((image.close.top - image.area.top) * yScale).toInt().coerceIn(0, height)
|
||||
val bottom = ceil((image.close.bottom - image.area.top) * yScale).toInt().coerceIn(top, height)
|
||||
val pixels = argb.copyOf()
|
||||
for (row in top until bottom) pixels.fill(0, row * width + left, row * width + right)
|
||||
return copy(argb = pixels)
|
||||
}
|
||||
|
||||
private fun replyPrompt(label: String, author: String): Boolean = author.isNotBlank() &&
|
||||
(label == "回复给: $author" || label == "回复给:$author" || label == "回复给: $author")
|
||||
|
||||
private fun readReceipt(key: String, author: String, text: String, count: Int, armedAt: Long): Receipt? =
|
||||
comments.readThread(key, author) { page, panel, thread ->
|
||||
if (!thread.complete || page.hasKuaishouCommentDraft()) return@readThread null
|
||||
val row = thread.replies.singleOrNull { it.target.text == text } ?: return@readThread null
|
||||
if (!matchesTime(row.time, armedAt, System.currentTimeMillis())) return@readThread null
|
||||
val images = row.photos?.takeIf { it.size == count } ?: return@readThread null
|
||||
val list = panel.list ?: return@readThread null
|
||||
if (images.any { !page.bounds.contains(it.bounds) || !list.bounds.contains(it.bounds) }) return@readThread null
|
||||
val regions = images.map { Rect(it.bounds) }
|
||||
if (regions.any { it.isEmpty } || regions.hasOverlap()) return@readThread null
|
||||
Receipt(page.windowId, row.target.key, regions)
|
||||
}
|
||||
|
||||
private fun inspectRole(key: String, author: String, rowKey: String, expected: Receipt?): Role? {
|
||||
ui.pace()
|
||||
val sourceWindow = comments.readThread(key, author) { page, panel, thread ->
|
||||
if (!thread.complete || (expected != null && page.windowId != expected.window)) return@readThread null
|
||||
val row = if (rowKey == key) thread.original else thread.replies.singleOrNull { it.target.key == rowKey }
|
||||
if (row == null || (rowKey != key && expected?.images != row.photos?.map { Rect(it.bounds) })) {
|
||||
return@readThread null
|
||||
}
|
||||
val bounds = row.body.bounds
|
||||
val list = panel.list ?: return@readThread null
|
||||
if (bounds.isEmpty || !list.bounds.contains(bounds) || !row.container.bounds.contains(bounds)) {
|
||||
return@readThread null
|
||||
}
|
||||
val longClick = AccessibilityNodeInfo.ACTION_LONG_CLICK
|
||||
val shown = if (row.body.supports(longClick)) row.body.act(longClick) else
|
||||
ui.touch(bounds.exactCenterX(), bounds.exactCenterY(), bounds.exactCenterX(), bounds.exactCenterY(), 650)
|
||||
page.windowId.takeIf { shown }
|
||||
} ?: return null
|
||||
val menu = ui.await(3_500) { ui.inspect { readRoleMenu(it, sourceWindow) } } ?: return null
|
||||
val closed = ui.inspect { page -> readRoleMenu(page, sourceWindow) == menu && ui.back() } == true
|
||||
if (!closed || ui.await(3_500) {
|
||||
comments.readThread(key, author) { page, _, thread ->
|
||||
true.takeIf { page.windowId == sourceWindow && thread.complete &&
|
||||
(rowKey == key || thread.replies.count { it.target.key == rowKey } == 1) }
|
||||
}
|
||||
} != true
|
||||
) return null
|
||||
return menu.role
|
||||
}
|
||||
|
||||
private fun readRoleMenu(page: UiPage, previousWindow: Int): RoleMenu? {
|
||||
if (!page.complete || page.windowId == previousWindow || page.hasKuaishouCommentDraft()) return null
|
||||
val sheet = page.nodes.singleOrNull {
|
||||
it.resourceId == "design_bottom_sheet" && it.directParent()?.resourceId == "coordinator" &&
|
||||
page.bounds.contains(it.bounds)
|
||||
} ?: return null
|
||||
val labels = page.nodes.filter {
|
||||
it.resourceId == "item_title" && it.isDescendantOf(sheet) && sheet.bounds.contains(it.bounds)
|
||||
}.map(UiNode::text)
|
||||
if (labels.count { it == "复制评论" } != 1) return null
|
||||
val deletion = labels.count { it == "删除评论" || it == "删除" }
|
||||
val reporting = labels.count { it == "举报评论" }
|
||||
val role = when {
|
||||
deletion == 1 && reporting == 0 -> Role.OWN
|
||||
deletion == 0 && reporting == 1 -> Role.OTHER
|
||||
else -> null
|
||||
}
|
||||
return RoleMenu(page.windowId, role)
|
||||
}
|
||||
|
||||
private fun matchesTime(label: String?, armedAt: Long, now: Long): Boolean {
|
||||
if (armedAt <= 0 || now - armedAt !in 0..RECHECK_WINDOW_MS) return false
|
||||
val age = now - armedAt
|
||||
if (label == "刚刚" || label?.startsWith("刚刚 ") == true) return age <= 65_000L
|
||||
val match = relativeTime.matchEntire(label.orEmpty()) ?: return false
|
||||
val unit = if (match.groupValues[2] == "分钟") 60_000L else 1_000L
|
||||
val displayed = match.groupValues[1].toLong() * unit
|
||||
return age >= displayed - 5_000L && age < displayed + unit + 5_000L
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val RECEIPT_SCREENS = 13
|
||||
val relativeTime = Regex("([1-9]\\d?)\\s*(秒|分钟)前(?:\\s+\\S+)?")
|
||||
val attachmentNodes = setOf("preview_image_layout", "preview_image", "preview_close", "comment_image")
|
||||
}
|
||||
}
|
||||
|
||||
internal fun UiPage.hasKuaishouCommentDraft(): Boolean = nodes.any { node ->
|
||||
node.resourceId == "editor_animation_frame" ||
|
||||
(node.resourceId == "finish_button" && node.enabled && node.labels() == listOf("发送") &&
|
||||
node.directParent()?.resourceId == "comment_editor_bottom_layout")
|
||||
}
|
||||
@@ -54,11 +54,14 @@ object PlatformRegistry {
|
||||
private val xiaohongshu = PlatformSpec("xiaohongshu", "小红书", "com.xingin.xhs", true,
|
||||
supportsReplies = true, contentUnit = "笔记")
|
||||
private val bilibili = PlatformSpec("bilibili", "哔哩哔哩", "tv.danmaku.bili", true, supportsReplies = true)
|
||||
private val kuaishou = PlatformSpec("kuaishou", "快手", "com.smile.gifmaker", true,
|
||||
supportsReplies = true, contentUnit = "作品")
|
||||
|
||||
val platforms: List<PlatformSpec> = listOf(
|
||||
douyin,
|
||||
xiaohongshu,
|
||||
bilibili,
|
||||
kuaishou,
|
||||
)
|
||||
|
||||
fun create(
|
||||
@@ -79,12 +82,18 @@ object PlatformRegistry {
|
||||
bilibili -> UiPage::requireBilibiliCommentAccess
|
||||
else -> null
|
||||
}
|
||||
val ui = AccessibleUi(service, spec.packageName, cancelled, pauseBetweenActions, checkPage)
|
||||
val ui = if (spec == kuaishou) {
|
||||
// The expanded comment list and the reply editor coexist in one native window.
|
||||
AccessibleUi(service, spec.packageName, cancelled, pauseBetweenActions, nodeLimit = 900)
|
||||
} else {
|
||||
AccessibleUi(service, spec.packageName, cancelled, pauseBetweenActions, checkPage)
|
||||
}
|
||||
return when (spec.id) {
|
||||
douyin.id -> DouyinAdapter(spec, ui, PhotoLibrary(service))
|
||||
xiaohongshu.id -> XiaohongshuAdapter(spec, ui, PhotoLibrary(service), noteKind, targetNoteKey,
|
||||
pinnedResumeNoteKey, receiptDiagnostic)
|
||||
bilibili.id -> BilibiliAdapter(spec, ui, PhotoLibrary(service), bilibiliCommentScope, receiptDiagnostic)
|
||||
kuaishou.id -> KuaishouAdapter(spec, ui, PhotoLibrary(service), receiptDiagnostic)
|
||||
else -> throw PlatformException("${spec.label} 暂未接入")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<resources>
|
||||
<string name="app_name">拾见</string>
|
||||
<string name="accessibility_label">拾见任务服务</string>
|
||||
<string name="accessibility_description">在你主动启动任务时按内容类型搜索和浏览视频,并按配置识别、回复匹配的评论。可在拾见任务页暂停。</string>
|
||||
<string name="accessibility_description">在你主动启动任务时按内容类型搜索和浏览作品,并按配置识别、回复匹配的评论。可在拾见任务页暂停。</string>
|
||||
<string name="tab_task">任务</string>
|
||||
<string name="tab_settings">配置</string>
|
||||
<string name="tab_logs">日志</string>
|
||||
|
||||
@@ -8,4 +8,4 @@
|
||||
android:canTakeScreenshot="true"
|
||||
android:description="@string/accessibility_description"
|
||||
android:notificationTimeout="200"
|
||||
android:packageNames="com.ss.android.ugc.aweme,com.xingin.xhs,tv.danmaku.bili" />
|
||||
android:packageNames="com.ss.android.ugc.aweme,com.xingin.xhs,tv.danmaku.bili,com.smile.gifmaker" />
|
||||
|
||||
Reference in New Issue
Block a user