完善哔哩哔哩评论发布与自动回执
分别处理纯文字原评论回复和双图顶层评论,完善相册匹配、最新评论核对与待核对恢复,并记录真机验收结果。
This commit is contained in:
@@ -109,6 +109,7 @@ internal object TaskControl {
|
||||
val platform = PlatformRegistry.create(plan.platformId, service, cancelled,
|
||||
noteKind = plan.xiaohongshuNoteKind, targetNoteKey = plan.xiaohongshuNoteKey,
|
||||
pinnedResumeNoteKey = initial.activeVideo?.videoKey.takeIf { plan.xiaohongshuNoteKey != null },
|
||||
bilibiliCommentScope = plan.bilibiliCommentScope,
|
||||
receiptDiagnostic = { stage -> store.appendLog(stage) }) {
|
||||
val interval = randomIn(plan.actionMillis.first, plan.actionMillis.last)
|
||||
pauseFor(interval.toLong(), cancelled)
|
||||
|
||||
@@ -36,6 +36,7 @@ import com.jieliu.app.data.LocalStore
|
||||
import com.jieliu.app.data.PhotoLibrary
|
||||
import com.jieliu.app.platform.PlatformRegistry
|
||||
import com.jieliu.app.platform.PlatformSpec
|
||||
import com.jieliu.app.task.BilibiliCommentScope
|
||||
import com.jieliu.app.task.ContentType
|
||||
import com.jieliu.app.task.KeywordRule
|
||||
import com.jieliu.app.task.Outcome
|
||||
@@ -273,6 +274,9 @@ class MainActivity : Activity() {
|
||||
val platformSpec = PlatformRegistry.platforms.firstOrNull { it.id == plan.platformId }
|
||||
val platform = platformSpec?.label ?: plan.platformId
|
||||
val contentUnit = platformSpec?.contentUnit ?: "视频"
|
||||
val bilibiliScope = plan.bilibiliCommentScope.takeIf { plan.platformId == "bilibili" && plan.replyMode != ReplyMode.BROWSE }
|
||||
val videoComment = bilibiliScope == BilibiliCommentScope.VIDEO_COMMENT
|
||||
val confirmedLabel = if (videoComment) "已确认发布评论" else "已确认回复"
|
||||
val searchTypes = plan.searchTypes()
|
||||
val completed = checkpoint?.receipts?.size ?: 0
|
||||
val title = when {
|
||||
@@ -284,7 +288,7 @@ class MainActivity : Activity() {
|
||||
}
|
||||
return column().apply {
|
||||
addView(card(title).apply {
|
||||
val modeLabel = if (plan.replyMode == ReplyMode.BROWSE) ReplyMode.BROWSE.label else ReplyMode.TEMPLATES.label
|
||||
val modeLabel = bilibiliScope?.label ?: if (plan.replyMode == ReplyMode.BROWSE) ReplyMode.BROWSE.label else ReplyMode.TEMPLATES.label
|
||||
addView(label("$platform · $modeLabel", 15))
|
||||
addView(label(view.step ?: checkpoint?.message ?: "内容类型 ${searchTypes.size} 个 · 单次 ${plan.limit} 个$contentUnit", 15))
|
||||
val limit = checkpoint?.plan?.limit ?: plan.limit
|
||||
@@ -294,9 +298,9 @@ class MainActivity : Activity() {
|
||||
progressTintList = ColorStateList.valueOf(GREEN)
|
||||
contentDescription = "已处理 $completed 个$contentUnit,共 $limit 个"
|
||||
}, LinearLayout.LayoutParams(-1, dp(18)))
|
||||
addView(label("已处理$contentUnit $completed / $limit · 已确认回复 ${checkpoint?.sentCount ?: 0} 条", 14))
|
||||
addView(label("已处理$contentUnit $completed / $limit · $confirmedLabel ${checkpoint?.sentCount ?: 0} 条", 14))
|
||||
if (plan.replyMode != ReplyMode.BROWSE) checkpoint?.activeVideo?.let { video ->
|
||||
addView(label("当前${contentUnit}已确认回复 ${video.sentCount} / ${plan.repliesPerVideo}", 14))
|
||||
addView(label("当前$contentUnit$confirmedLabel ${video.sentCount} / ${plan.repliesPerVideo}", 14))
|
||||
}
|
||||
val searchType = checkpoint?.keyword ?: searchTypes.firstOrNull()?.name
|
||||
if (searchType != null && checkpoint?.complete != true) addView(label("内容类型 · $searchType", 14))
|
||||
@@ -310,15 +314,23 @@ class MainActivity : Activity() {
|
||||
if (pending != null && !active) {
|
||||
addView(card("到${platform}核对这条评论").apply {
|
||||
addView(label(pending.title, 16, bold = true))
|
||||
pending.targetAuthor?.takeIf { it.isNotBlank() }?.let { addView(label("回复对象 · $it", 14)) }
|
||||
pending.targetAuthor?.takeIf { it.isNotBlank() }?.let {
|
||||
val authorLabel = if (videoComment) "触发评论作者" else "回复对象"
|
||||
addView(label("$authorLabel · $it", 14))
|
||||
}
|
||||
addView(label(pending.text, 15))
|
||||
pending.photos.forEachIndexed { index, photo -> addView(photoPreview(photo, index)) }
|
||||
if (view.canAutomaticallyRecheck) {
|
||||
addView(action("自动核对回复", primary = true) { TaskControl.start(store, resume = true); renderTask() }
|
||||
addView(action(if (videoComment) "自动核对评论" else "自动核对回复", primary = true) { TaskControl.start(store, resume = true); renderTask() }
|
||||
.apply { applyEnabled(view.connected) })
|
||||
}
|
||||
addView(action("确认已发送", primary = !view.canAutomaticallyRecheck) { reconcile(Outcome.USER_CONFIRMED) })
|
||||
addView(action(if (checkpoint?.activeVideo != null) "跳过此回复" else "跳过这条视频") { reconcile(Outcome.SKIPPED) })
|
||||
val skipLabel = when {
|
||||
checkpoint?.activeVideo == null -> "跳过这条视频"
|
||||
videoComment -> "跳过此评论"
|
||||
else -> "跳过此回复"
|
||||
}
|
||||
addView(action(skipLabel) { reconcile(Outcome.SKIPPED) })
|
||||
})
|
||||
}
|
||||
when {
|
||||
@@ -352,6 +364,8 @@ class MainActivity : Activity() {
|
||||
val platform = choices(platformLabels, selectedPlatform)
|
||||
val modes = listOf(ReplyMode.BROWSE, ReplyMode.TEMPLATES)
|
||||
val mode = choices(modes.map { it.label }, if (plan.replyMode == ReplyMode.BROWSE) 0 else 1)
|
||||
val bilibiliScopes = BilibiliCommentScope.entries
|
||||
val bilibiliScope = choices(bilibiliScopes.map { it.label }, plan.bilibiliCommentScope.ordinal)
|
||||
val libraries = ContentFields(plan, restoredTemplates).also {
|
||||
templateFields = it
|
||||
restoredTemplates = null
|
||||
@@ -368,6 +382,11 @@ class MainActivity : Activity() {
|
||||
}
|
||||
val limitCaption = scope.addField("", limit)
|
||||
val comments = card("评论设置").apply { addField("处理方式", mode) }
|
||||
val bilibiliScopeHint = label("", 14)
|
||||
val bilibiliScopeFields = column().apply {
|
||||
addField("评论发布位置", bilibiliScope)
|
||||
addView(bilibiliScopeHint)
|
||||
}.also { comments.addView(it) }
|
||||
val repliesCaption = comments.addField("", repliesPerVideo)
|
||||
val repliesHint = label("", 14).also { comments.addView(it) }
|
||||
val library = card("内容库")
|
||||
@@ -377,21 +396,32 @@ class MainActivity : Activity() {
|
||||
fun updatePlatformCopy(spec: PlatformSpec) {
|
||||
val unit = spec.contentUnit
|
||||
limitCaption.text = "单次任务${unit}上限"
|
||||
repliesCaption.text = "每条${unit}回复上限"
|
||||
val showBilibiliScope = spec.id == "bilibili" && mode.selectedItemPosition == modes.indexOf(ReplyMode.TEMPLATES)
|
||||
val videoComment = showBilibiliScope && bilibiliScopes.getOrNull(bilibiliScope.selectedItemPosition) == BilibiliCommentScope.VIDEO_COMMENT
|
||||
bilibiliScopeFields.visibility = if (showBilibiliScope) View.VISIBLE else View.GONE
|
||||
bilibiliScopeHint.text = if (videoComment) "根据匹配结果在当前视频发布评论,话术绑定的图片会随正文发送。"
|
||||
else "将话术作为文字回复发到命中的原评论下。已绑定的图片会保留。"
|
||||
repliesCaption.text = if (videoComment) "每条${unit}评论发布上限" else "每条${unit}回复上限"
|
||||
val browseOnly = spec.implemented && !spec.supportsReplies
|
||||
repliesHint.text = if (browseOnly) "${spec.label}当前仅支持浏览。"
|
||||
else "达到回复上限或找不到更多匹配评论时,进入下一个$unit。"
|
||||
repliesHint.text = when {
|
||||
browseOnly -> "${spec.label}当前仅支持浏览。"
|
||||
videoComment -> "达到发布上限或找不到更多匹配评论时,进入下一个$unit。"
|
||||
else -> "达到回复上限或找不到更多匹配评论时,进入下一个$unit。"
|
||||
}
|
||||
libraryHint.text = if (browseOnly) "按内容类型搜索$unit。"
|
||||
else "按内容类型搜索$unit,按关键词匹配评论。每个关键词可配置多条话术。"
|
||||
}
|
||||
updatePlatformCopy(specs[selectedPlatform])
|
||||
platform.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
|
||||
val commentSettingsChanged = object : AdapterView.OnItemSelectedListener {
|
||||
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
|
||||
updatePlatformCopy(specs[position])
|
||||
specs.getOrNull(platform.selectedItemPosition)?.let(::updatePlatformCopy)
|
||||
}
|
||||
|
||||
override fun onNothingSelected(parent: AdapterView<*>) = Unit
|
||||
}
|
||||
platform.onItemSelectedListener = commentSettingsChanged
|
||||
mode.onItemSelectedListener = commentSettingsChanged
|
||||
bilibiliScope.onItemSelectedListener = commentSettingsChanged
|
||||
return column().apply {
|
||||
addView(scope)
|
||||
addView(card("动作节奏").apply {
|
||||
@@ -411,10 +441,11 @@ class MainActivity : Activity() {
|
||||
val updated = plan.copy(
|
||||
platformId = spec.id,
|
||||
limit = limit.number("单次任务${spec.contentUnit}上限"),
|
||||
repliesPerVideo = repliesPerVideo.number("每条${spec.contentUnit}回复上限"),
|
||||
repliesPerVideo = repliesPerVideo.number(repliesCaption.text.toString()),
|
||||
watchSeconds = watchMin.number("观看下限")..watchMax.number("观看上限"),
|
||||
actionMillis = actionMin.number("间隔下限")..actionMax.number("间隔上限"),
|
||||
replyMode = replyMode,
|
||||
bilibiliCommentScope = bilibiliScopes[bilibiliScope.selectedItemPosition],
|
||||
contentTypes = libraries.contentTypes,
|
||||
selectedTypeId = libraries.selectedScopeId(),
|
||||
)
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.jieliu.app.data
|
||||
|
||||
import com.jieliu.app.platform.XiaohongshuNoteKind
|
||||
import android.content.Context
|
||||
import com.jieliu.app.task.BilibiliCommentScope
|
||||
import com.jieliu.app.task.ContentType
|
||||
import com.jieliu.app.task.KeywordRule
|
||||
import com.jieliu.app.task.Outcome
|
||||
@@ -169,6 +170,7 @@ class LocalStore(context: Context) : TaskRunStorage {
|
||||
.put("selectedTypeId", selectedTypeId)
|
||||
.put("xiaohongshuNoteKind", xiaohongshuNoteKind.takeUnless { it == XiaohongshuNoteKind.ANY }?.name)
|
||||
.put("xiaohongshuNoteKey", xiaohongshuNoteKey)
|
||||
.put("bilibiliCommentScope", bilibiliCommentScope.name)
|
||||
.put("repliesPerVideo", repliesPerVideo)
|
||||
.put("limit", limit).put("watchMin", watchSeconds.first).put("watchMax", watchSeconds.last)
|
||||
.put("actionMin", actionMillis.first).put("actionMax", actionMillis.last)
|
||||
@@ -207,6 +209,8 @@ class LocalStore(context: Context) : TaskRunStorage {
|
||||
xiaohongshuNoteKind = XiaohongshuNoteKind.entries.firstOrNull { it.name == optionalString("xiaohongshuNoteKind") }
|
||||
?: XiaohongshuNoteKind.ANY,
|
||||
xiaohongshuNoteKey = optionalString("xiaohongshuNoteKey"),
|
||||
bilibiliCommentScope = BilibiliCommentScope.entries.firstOrNull { it.name == optionalString("bilibiliCommentScope") }
|
||||
?: BilibiliCommentScope.REPLY_TO_ORIGINAL,
|
||||
)
|
||||
|
||||
private fun ContentType.toJson() = JSONObject().put("id", id).put("name", name)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.jieliu.app.platform
|
||||
|
||||
import com.jieliu.app.data.PhotoLibrary
|
||||
import com.jieliu.app.task.BilibiliCommentScope
|
||||
import com.jieliu.app.task.PendingComment
|
||||
import com.jieliu.app.task.TemplatePhoto
|
||||
|
||||
@@ -8,11 +9,13 @@ internal class BilibiliAdapter(
|
||||
spec: PlatformSpec,
|
||||
private val ui: AccessibleUi,
|
||||
photos: PhotoLibrary,
|
||||
private val scope: BilibiliCommentScope,
|
||||
diagnostic: (String) -> Unit,
|
||||
) : PlatformAdapter {
|
||||
private val navigation = BilibiliVideoNavigation(spec, ui)
|
||||
private val comments = BilibiliComments(ui, navigation)
|
||||
private val replies = BilibiliReplies(ui, comments, photos, diagnostic)
|
||||
private var openVideo: VideoContext? = null
|
||||
|
||||
override fun launch() = navigation.launch()
|
||||
|
||||
@@ -29,7 +32,7 @@ internal class BilibiliAdapter(
|
||||
}
|
||||
|
||||
override fun openComments(expected: VideoContext): List<String> =
|
||||
comments.open(expected).map(CommentTarget::text)
|
||||
comments.open(expected).map(CommentTarget::text).also { openVideo = expected }
|
||||
|
||||
override fun scanComments(): List<CommentTarget> {
|
||||
comments.leaveThread()
|
||||
@@ -38,8 +41,10 @@ internal class BilibiliAdapter(
|
||||
|
||||
override fun scrollComments(): Boolean = comments.scroll()
|
||||
|
||||
override fun prepareReply(target: CommentTarget, expectedText: String, requiresImages: Boolean): Boolean =
|
||||
replies.prepare(target, expectedText, requiresImages)
|
||||
override fun prepareReply(target: CommentTarget, expectedText: String, requiresImages: Boolean): Boolean = when (scope) {
|
||||
BilibiliCommentScope.REPLY_TO_ORIGINAL -> replies.prepare(target, expectedText, requiresImages)
|
||||
BilibiliCommentScope.VIDEO_COMMENT -> replies.prepareTopLevel(checkNotNull(openVideo), target, expectedText, requiresImages)
|
||||
}
|
||||
|
||||
override fun hasPreparedReplyBaseline(targetKey: String, text: String): Boolean =
|
||||
replies.hasPreparedBaseline(targetKey, text)
|
||||
@@ -55,7 +60,7 @@ internal class BilibiliAdapter(
|
||||
beforeClick()
|
||||
}
|
||||
if (!clicked || armedAt == 0L) return CommentPublishResult.UNCERTAIN
|
||||
return replies.confirm(target.key, target.author, text, photos, armedAt)
|
||||
return confirm(checkNotNull(openVideo), target.key, target.author, text, photos, armedAt)
|
||||
}
|
||||
|
||||
override fun confirmPendingReplyInPlace(video: VideoContext, pending: PendingComment): CommentPublishResult? {
|
||||
@@ -68,12 +73,19 @@ internal class BilibiliAdapter(
|
||||
val author = pending.targetAuthor ?: return CommentPublishResult.UNCERTAIN
|
||||
val armedAt = pending.armedAtEpochMs ?: return CommentPublishResult.UNCERTAIN
|
||||
if (video.key != pending.videoKey || !comments.isOpenFor(video)) return CommentPublishResult.UNCERTAIN
|
||||
return replies.confirm(targetKey, author, pending.text, pending.photos, armedAt)
|
||||
return confirm(video, targetKey, author, pending.text, pending.photos, armedAt)
|
||||
}
|
||||
|
||||
private fun confirm(video: VideoContext, targetKey: String, author: String, text: String,
|
||||
photos: List<TemplatePhoto>, armedAt: Long): CommentPublishResult = when (scope) {
|
||||
BilibiliCommentScope.REPLY_TO_ORIGINAL -> replies.confirm(targetKey, author, text, photos, armedAt)
|
||||
BilibiliCommentScope.VIDEO_COMMENT -> replies.confirmTopLevel(video, text, photos, armedAt)
|
||||
}
|
||||
|
||||
override fun closeComments() {
|
||||
if (replies.hasUnsettledEditor()) throw PlatformException("哔哩哔哩回复框仍打开,请核对草稿后继续")
|
||||
if (replies.hasUnsettledEditor()) throw PlatformException("哔哩哔哩评论编辑框仍打开,请核对草稿后继续")
|
||||
replies.reset()
|
||||
comments.close()
|
||||
openVideo = null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ internal class BilibiliComments(
|
||||
)
|
||||
|
||||
internal data class ThreadRows(val original: Row, val replies: List<Row>, val complete: Boolean)
|
||||
internal data class TopLevelMatches(val rows: List<Row>, val occurrences: Int)
|
||||
|
||||
private data class MainScope(val video: VideoContext, val window: Int, val list: UiNodeSource) : Closeable {
|
||||
override fun close() = list.close()
|
||||
@@ -36,6 +37,17 @@ internal class BilibiliComments(
|
||||
override fun close() = tab.close()
|
||||
}
|
||||
|
||||
private data class SortTransition(
|
||||
val tab: UiNodeSource,
|
||||
val container: UiNodeSource,
|
||||
val changed: Boolean,
|
||||
) : Closeable {
|
||||
override fun close() {
|
||||
tab.close()
|
||||
container.close()
|
||||
}
|
||||
}
|
||||
|
||||
private var main: MainScope? = null
|
||||
private var thread: ThreadScope? = null
|
||||
|
||||
@@ -101,6 +113,117 @@ internal class BilibiliComments(
|
||||
} == true
|
||||
}
|
||||
|
||||
fun openTopLevel(video: VideoContext): Boolean {
|
||||
val scope = main?.takeIf { it.video == video && thread == null } ?: return false
|
||||
ui.pace()
|
||||
return ui.inspect { page ->
|
||||
if (!page.complete) return@inspect false
|
||||
val list = mainList(page, scope) ?: return@inspect false
|
||||
val entry = if (BilibiliComposeComments.isList(page, list)) {
|
||||
BilibiliComposeComments.topLevelEntry(page, list)
|
||||
} else {
|
||||
page.nativeTopLevelEntry(list)
|
||||
}
|
||||
entry != null && ui.click(entry)
|
||||
} == true
|
||||
}
|
||||
|
||||
fun prepareLatestTopLevel(video: VideoContext): Boolean {
|
||||
val scope = main?.takeIf { it.video == video && thread == null } ?: return false
|
||||
repeat(4) { index ->
|
||||
val latest = ui.inspect { page ->
|
||||
val list = mainList(page, scope)?.takeIf { page.complete } ?: return@inspect null
|
||||
if (page.videoTabs()?.second?.selected != true) return@inspect null
|
||||
BilibiliComposeComments.order(page, list)?.latest
|
||||
}
|
||||
if (latest != null) return latest || switchTopLevelOrder(scope)
|
||||
if (index == 3 || !scrollTopLevel(video, towardStart = true)) return false
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun switchTopLevelOrder(scope: MainScope): Boolean {
|
||||
ui.pace()
|
||||
val transition = ui.inspect { page ->
|
||||
val list = mainList(page, scope)?.takeIf { page.complete } ?: return@inspect null
|
||||
val order = BilibiliComposeComments.order(page, list) ?: return@inspect null
|
||||
val tab = page.videoTabs()?.second?.takeIf(UiNode::selected) ?: return@inspect null
|
||||
val container = page.topLevelContainer(list) ?: return@inspect null
|
||||
val proof = SortTransition(tab.retainSource(), container.retainSource(), !order.latest)
|
||||
try {
|
||||
if (order.latest || ui.click(order.control)) proof else {
|
||||
proof.close()
|
||||
null
|
||||
}
|
||||
} catch (error: Throwable) {
|
||||
proof.close()
|
||||
throw error
|
||||
}
|
||||
} ?: return false
|
||||
val current = transition.use { proof ->
|
||||
ui.await(5_000) {
|
||||
ui.inspect { page ->
|
||||
if (main !== scope || thread != null || !page.complete || page.windowId != scope.window ||
|
||||
page.hasEditor() || page.detailHeader() != null
|
||||
) return@inspect null
|
||||
val tab = page.videoTabs()?.second ?: return@inspect null
|
||||
if (!tab.selected || !tab.hasSource(proof.tab)) return@inspect null
|
||||
val list = page.commentList() ?: return@inspect null
|
||||
val container = page.topLevelContainer(list) ?: return@inspect null
|
||||
if (!container.hasSource(proof.container) || BilibiliComposeComments.order(page, list)?.latest != true) {
|
||||
return@inspect null
|
||||
}
|
||||
if (list.hasSource(scope.list)) scope else if (proof.changed) {
|
||||
MainScope(scope.video, scope.window, list.retainSource())
|
||||
} else null
|
||||
}
|
||||
}
|
||||
} ?: return false
|
||||
if (current !== scope) {
|
||||
main = current
|
||||
scope.close()
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
fun <T> readTopLevel(
|
||||
video: VideoContext,
|
||||
text: String,
|
||||
action: (UiPage, TopLevelMatches) -> T,
|
||||
): T? {
|
||||
val scope = main?.takeIf { it.video == video && thread == null && text.isNotBlank() } ?: return null
|
||||
return ui.inspect { page ->
|
||||
if (!page.complete) return@inspect null
|
||||
val list = mainList(page, scope) ?: return@inspect null
|
||||
val rows = page.parsedRows(list, scope.video.key).filter { it.target.text == text }
|
||||
val occurrences = if (BilibiliComposeComments.isList(page, list)) {
|
||||
BilibiliComposeComments.topLevelOccurrences(page, list, text)
|
||||
} else {
|
||||
page.nativeTopLevelOccurrences(list, text)
|
||||
}
|
||||
action(page, TopLevelMatches(rows, maxOf(occurrences, rows.size)))
|
||||
}
|
||||
}
|
||||
|
||||
fun scrollTopLevel(video: VideoContext, towardStart: Boolean = false): Boolean {
|
||||
val scope = main?.takeIf { it.video == video && thread == null } ?: return false
|
||||
if (!towardStart) return scroll()
|
||||
ui.pace()
|
||||
val backward = AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
|
||||
val previous = ui.inspect { page ->
|
||||
val list = mainList(page, scope)?.takeIf { page.complete && it.supports(backward) } ?: return@inspect null
|
||||
val positions = page.parsedRows(list, scope.video.key).map { it.target.key to it.container.bounds.top }
|
||||
positions.takeIf { list.act(backward) }
|
||||
} ?: return false
|
||||
return ui.await(2_500) {
|
||||
ui.inspect { page ->
|
||||
val list = mainList(page, scope) ?: return@inspect null
|
||||
val positions = page.parsedRows(list, scope.video.key).map { it.target.key to it.container.bounds.top }
|
||||
true.takeIf { positions.isNotEmpty() && positions != previous }
|
||||
}
|
||||
} == true
|
||||
}
|
||||
|
||||
fun <T> readOriginal(target: CommentTarget, action: (UiPage, Row) -> T): T? = ui.inspect { page ->
|
||||
if (!page.complete) return@inspect null
|
||||
if (thread != null) {
|
||||
@@ -242,6 +365,31 @@ internal class BilibiliComments(
|
||||
|
||||
private fun UiPage.hasEditor(): Boolean = nodes.any { it.editable && it.focused }
|
||||
|
||||
private fun UiPage.topLevelContainer(list: UiNode): UiNode? =
|
||||
nodes.singleOrNull { it.resourceId == "comment_container" && list.isDescendantOf(it) && it.bounds.contains(list.bounds) }
|
||||
|
||||
private fun UiPage.nativeTopLevelEntry(list: UiNode): UiNode? {
|
||||
val container = topLevelContainer(list) ?: return null
|
||||
val footer = nodes.singleOrNull {
|
||||
it.resourceId == "fake_input_layout" && it.isDescendantOf(container) && !it.isDescendantOf(list) &&
|
||||
container.bounds.contains(it.bounds) && it.bounds.width() >= container.bounds.width() * .75 &&
|
||||
it.bounds.bottom > list.bounds.bottom && it.bounds.top >= list.bounds.bottom - it.bounds.height() / 4
|
||||
} ?: return null
|
||||
return nodes.singleOrNull {
|
||||
it.resourceId == "input" && it.isDescendantOf(footer) && footer.bounds.contains(it.bounds) &&
|
||||
it.description == "文本栏" && BilibiliComposeComments.isTopLevelPrompt(it.text.ifBlank { it.hint }) &&
|
||||
!it.focused && it.biliClick()
|
||||
}
|
||||
}
|
||||
|
||||
private fun UiPage.nativeTopLevelOccurrences(list: UiNode, text: String): Int =
|
||||
nodes.count { body ->
|
||||
body.resourceId in setOf("comment_message", "primary_message") && !body.editable && body.text == text &&
|
||||
body.isDescendantOf(list) && Rect.intersects(body.bounds, list.bounds) &&
|
||||
generateSequence(body.directParent(), UiNode::directParent).takeWhile { it !== list }
|
||||
.none { it.resourceId in setOf("secondary", "replies_recycle_view") }
|
||||
}
|
||||
|
||||
private fun UiPage.rows(list: UiNode, videoKey: String): List<Row> {
|
||||
val parsed = parsedRows(list, videoKey)
|
||||
val counts = parsed.groupingBy { it.target.key }.eachCount()
|
||||
|
||||
@@ -5,6 +5,7 @@ import android.graphics.Rect
|
||||
/** Virtual accessibility nodes observed in the Bilibili 9.21.0 video comment tab and reply detail. */
|
||||
internal object BilibiliComposeComments {
|
||||
internal data class Detail(val header: UiNode, val list: UiNode, val close: UiNode)
|
||||
internal data class Order(val control: UiNode, val latest: Boolean)
|
||||
|
||||
private data class Action(val node: UiNode, val label: UiNode)
|
||||
private data class Identity(val author: UiNode, val body: UiNode)
|
||||
@@ -30,7 +31,7 @@ internal object BilibiliComposeComments {
|
||||
if (header.className != VIEW || header.bounds.width() < compose.bounds.width() * .90 ||
|
||||
!header.bounds.contains(heading.bounds) || !compose.bounds.contains(header.bounds)
|
||||
) return null
|
||||
val list = composeList(page, compose)?.takeIf {
|
||||
val list = composeList(page, compose, staticDetailPanel = panel)?.takeIf {
|
||||
it.bounds.top >= header.bounds.bottom && it.directParent()?.directParent() === panel
|
||||
} ?: return null
|
||||
val close = page.children(header).singleOrNull {
|
||||
@@ -44,6 +45,77 @@ internal object BilibiliComposeComments {
|
||||
|
||||
fun isList(page: UiPage, list: UiNode): Boolean = list(page) === list || detail(page)?.list === list
|
||||
|
||||
fun isTopLevelPrompt(value: String): Boolean = value in TOP_LEVEL_PROMPTS
|
||||
|
||||
fun topLevelEntry(page: UiPage, list: UiNode): UiNode? {
|
||||
if (list(page) !== list || detail(page) != null) return null
|
||||
val content = list.directParent()?.directParent()?.takeIf { it.className == VIEW } ?: return null
|
||||
val footer = page.children(content).singleOrNull {
|
||||
it.className == VIEW && !it.clickable && !it.scrollable && content.bounds.contains(it.bounds) &&
|
||||
it.bounds.width() >= list.bounds.width() * .90 && it.bounds.bottom == content.bounds.bottom &&
|
||||
it.bounds.bottom > list.bounds.bottom && it.bounds.top >= list.bounds.bottom - it.bounds.height() / 4
|
||||
} ?: return null
|
||||
val actions = page.children(footer).filter { it.className == VIEW && it.biliClick() && !it.editable }
|
||||
if (actions.size != 2) return null
|
||||
val input = actions.singleOrNull {
|
||||
footer.bounds.contains(it.bounds) && it.bounds.width() >= footer.bounds.width() * .65 &&
|
||||
it.bounds.left < footer.bounds.centerX() && it.bounds.right > footer.bounds.centerX()
|
||||
} ?: return null
|
||||
val alternate = actions.singleOrNull {
|
||||
it !== input && footer.bounds.contains(it.bounds) && it.bounds.left >= input.bounds.right &&
|
||||
it.bounds.width() <= footer.bounds.width() * .25 && sameLine(it.bounds, input.bounds)
|
||||
} ?: return null
|
||||
if (page.children(alternate).any { it.editable }) return null
|
||||
return input.takeIf {
|
||||
page.children(it).filter { child -> child.text.isNotEmpty() || child.description.isNotEmpty() }
|
||||
.singleOrNull { marker ->
|
||||
marker.className == TEXT_VIEW && !marker.clickable && !marker.editable &&
|
||||
input.bounds.contains(marker.bounds) && isTopLevelPrompt(marker.text) &&
|
||||
(marker.description.isEmpty() || marker.description == marker.text)
|
||||
} != null
|
||||
}
|
||||
}
|
||||
|
||||
fun topLevelOccurrences(page: UiPage, list: UiNode, text: String): Int {
|
||||
if (list(page) !== list) return 0
|
||||
return page.children(list).filter {
|
||||
it.className == VIEW && it.resourceId.isEmpty() && !it.editable && it.bounds.width() >= list.bounds.width() * .90 &&
|
||||
Rect.intersects(it.bounds, list.bounds)
|
||||
}.sumOf { row ->
|
||||
page.children(row).count {
|
||||
it.className == VIEW && !it.clickable && !it.editable && it.text.isEmpty() &&
|
||||
it.description == text && it.bounds.width() >= row.bounds.width() * .50 &&
|
||||
Rect.intersects(it.bounds, list.bounds)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun order(page: UiPage, list: UiNode): Order? {
|
||||
if (list(page) !== list || detail(page) != null) return null
|
||||
val header = page.children(list).singleOrNull {
|
||||
it.className == VIEW && !it.clickable && it.bounds.top == list.bounds.top &&
|
||||
it.bounds.width() >= list.bounds.width() * .90 && list.bounds.contains(it.bounds)
|
||||
} ?: return null
|
||||
val heading = page.children(header).singleOrNull {
|
||||
it.className == TEXT_VIEW && !it.clickable && it.text in ORDER_HEADINGS &&
|
||||
it.bounds.centerX() < header.bounds.centerX() && header.bounds.contains(it.bounds)
|
||||
} ?: return null
|
||||
val control = page.children(header).singleOrNull {
|
||||
it.className == VIEW && it.biliClick() && sameLine(it.bounds, heading.bounds) &&
|
||||
it.bounds.left >= header.bounds.centerX() && header.bounds.contains(it.bounds)
|
||||
} ?: return null
|
||||
val marker = page.children(control).singleOrNull {
|
||||
it.className == TEXT_VIEW && !it.clickable && it.text in ORDER_NAMES && control.bounds.contains(it.bounds)
|
||||
} ?: return null
|
||||
val latest = marker.text == "按时间"
|
||||
val expectedHeading = if (latest) "最新评论" else "热门评论"
|
||||
if (heading.text != expectedHeading) return null
|
||||
val confirms = page.children(control).count {
|
||||
it.className == VIEW && !it.clickable && it.description == marker.text && control.bounds.contains(it.bounds)
|
||||
} == 1
|
||||
return Order(control, latest).takeIf { confirms }
|
||||
}
|
||||
|
||||
fun rows(
|
||||
page: UiPage,
|
||||
list: UiNode,
|
||||
@@ -63,6 +135,11 @@ internal object BilibiliComposeComments {
|
||||
val time = footerTime(page, row, reply.label) ?: return@mapIndexedNotNull null
|
||||
val next = siblings.getOrNull(index + 1)
|
||||
val threadEntry = next?.let { threadEntry(page, list, more.label.bounds, it) }
|
||||
?: next?.takeIf { isReplyPreview(page, list, row.bounds, body.bounds, it) }?.let { preview ->
|
||||
siblings.getOrNull(index + 2)?.takeIf { count ->
|
||||
count.bounds.top in preview.bounds.top..preview.bounds.bottom
|
||||
}?.let { threadEntry(page, list, more.label.bounds, it) } ?: preview
|
||||
}
|
||||
val emptyThread = threadEntry == null && next != null && page.complete &&
|
||||
rowIdentity(page, list, next) != null && next.bounds.top >= more.label.bounds.bottom
|
||||
val own = page.children(row).any {
|
||||
@@ -87,14 +164,28 @@ internal object BilibiliComposeComments {
|
||||
return page.children(list).count { rowIdentity(page, list, it) != null } == nestedCount + 1
|
||||
}
|
||||
|
||||
private fun composeList(page: UiPage, compose: UiNode): UiNode? =
|
||||
private fun composeList(page: UiPage, compose: UiNode, staticDetailPanel: UiNode? = null): UiNode? =
|
||||
page.nodes.singleOrNull {
|
||||
it.className == VIEW && it.resourceId.isEmpty() && it.scrollable && !it.clickable &&
|
||||
it.className == VIEW && it.resourceId.isEmpty() && !it.clickable &&
|
||||
(it.scrollable || staticDetailPanel != null && it.directParent()?.directParent() === staticDetailPanel &&
|
||||
page.children(it).any { child -> page.children(child).any { label -> THREAD_TOTAL.matches(label.text) } }) &&
|
||||
it.isDescendantOf(compose) && it.depth - compose.depth in 2..4 &&
|
||||
compose.bounds.contains(it.bounds) && it.bounds.width() >= compose.bounds.width() * .90 &&
|
||||
it.bounds.height() >= compose.bounds.height() * .45
|
||||
}
|
||||
|
||||
private fun isReplyPreview(page: UiPage, list: UiNode, original: Rect, body: Rect, row: UiNode): Boolean {
|
||||
if (row.className != VIEW || !row.biliClick() || !list.bounds.contains(row.bounds) ||
|
||||
row.bounds.top < original.bottom || row.bounds.width() < list.bounds.width() * .9
|
||||
) return false
|
||||
val children = page.children(row)
|
||||
if (children.any { it.className == BUTTON && it.text.isNotBlank() }) return false
|
||||
return children.count {
|
||||
it.className == VIEW && !it.clickable && it.text.isEmpty() && it.description.isNotBlank() &&
|
||||
it.bounds.left > body.left && it.bounds.width() >= body.width() * .65 && row.bounds.contains(it.bounds)
|
||||
} == 1
|
||||
}
|
||||
|
||||
private fun rowIdentity(page: UiPage, list: UiNode, row: UiNode): Identity? {
|
||||
if (row.className != VIEW || row.directParent() !== list || !row.biliClick() || row.editable ||
|
||||
row.bounds.width() < list.bounds.width() * .90 || !list.bounds.contains(row.bounds)
|
||||
@@ -145,7 +236,7 @@ internal object BilibiliComposeComments {
|
||||
val markers = page.children(action)
|
||||
val text = markers.singleOrNull {
|
||||
it.className == TEXT_VIEW && !it.clickable && action.bounds.contains(it.bounds) &&
|
||||
it.bounds.top >= footer.bottom && it.text.startsWith("共") && (BilibiliLabels.replyCount(it.text) ?: 0) > 0
|
||||
it.bounds.top >= footer.bottom && nestedReplyCount(it.text) > 0
|
||||
} ?: return null
|
||||
return action.takeIf {
|
||||
markers.count { marker -> marker.className == VIEW && !marker.clickable &&
|
||||
@@ -153,13 +244,50 @@ internal object BilibiliComposeComments {
|
||||
}
|
||||
}
|
||||
|
||||
private fun nestedReplyCount(text: String): Int {
|
||||
val label = text.removePrefix("UP主等人").trimStart()
|
||||
return if (label.startsWith("共")) BilibiliLabels.replyCount(label) ?: 0 else 0
|
||||
}
|
||||
|
||||
private fun photos(page: UiPage, row: UiNode, body: Rect, footer: Rect): List<UiNode>? {
|
||||
// An unlabeled content action here can also be a media card or inserted content.
|
||||
val attachment = page.children(row).any {
|
||||
it.className == VIEW && it.biliClick() && it.bounds.centerY() in body.bottom until footer.top &&
|
||||
it.bounds.left >= body.left && row.bounds.contains(it.bounds)
|
||||
if (!page.complete) return null
|
||||
val content = page.children(row).filter {
|
||||
it.bounds.centerY() in body.bottom until footer.top && it.bounds.left >= body.left
|
||||
}
|
||||
return emptyList<UiNode>().takeUnless { attachment }
|
||||
if (content.size > MAX_PHOTOS) return null
|
||||
val thumbnails = content.map { tile ->
|
||||
val bounds = tile.bounds
|
||||
if (tile.className != VIEW || tile.resourceId.isNotEmpty() || !tile.biliClick() || tile.editable ||
|
||||
tile.labels().isNotEmpty() || !row.bounds.contains(bounds) ||
|
||||
bounds.top < body.bottom || bounds.bottom > footer.top ||
|
||||
bounds.width() < body.width() * .10 || bounds.height() < body.width() * .10
|
||||
) return null
|
||||
val layers = page.children(tile)
|
||||
if (layers.size != 2 || layers.any {
|
||||
it.className != VIEW || it.resourceId.isNotEmpty() || it.clickable || it.editable ||
|
||||
it.labels().isNotEmpty()
|
||||
}
|
||||
) return null
|
||||
if (layers.all { it.bounds == bounds }) return@map tile
|
||||
if (layers.count { it.bounds == bounds } != 1) return null
|
||||
|
||||
// This grid can shorten a tile's clickable bounds while drawing the full square image.
|
||||
val rendered = layers.single { it.bounds != bounds }
|
||||
val full = rendered.bounds
|
||||
if (full.left != bounds.left || full.top != bounds.top || full.right != bounds.right ||
|
||||
full.bottom - bounds.bottom !in 1..(full.width() / 8) || full.height() != full.width() ||
|
||||
!row.bounds.contains(full) || full.bottom > footer.top || content.none {
|
||||
it !== tile && it.bounds.top == full.top && it.bounds.bottom == full.bottom &&
|
||||
it.bounds.width() == full.width() && !Rect.intersects(it.bounds, full)
|
||||
}
|
||||
) return null
|
||||
rendered
|
||||
}
|
||||
if (thumbnails.indices.any { index ->
|
||||
thumbnails.take(index).any { Rect.intersects(it.bounds, thumbnails[index].bounds) }
|
||||
}
|
||||
) return null
|
||||
return thumbnails.sortedWith(compareBy({ it.bounds.top }, { it.bounds.left }))
|
||||
}
|
||||
|
||||
private fun sameLine(first: Rect, second: Rect): Boolean =
|
||||
@@ -172,10 +300,14 @@ internal object BilibiliComposeComments {
|
||||
private const val VIEW = "android.view.View"
|
||||
private const val TEXT_VIEW = "android.widget.TextView"
|
||||
private const val BUTTON = "android.widget.Button"
|
||||
private const val MAX_PHOTOS = 9
|
||||
private val CLOSE_LABELS = setOf("关闭", "返回", "关闭评论详情")
|
||||
private val MORE_LABELS = setOf("更多", "更多操作", "更多操作,按钮")
|
||||
private val REPLY_LABELS = setOf("回复", "回复,按钮")
|
||||
private val OWN_LABELS = setOf("我", "我发布的评论", "我发布的回复")
|
||||
private val TOP_LEVEL_PROMPTS = setOf("天青色等烟雨,评论区在等你", "不发没关系,请继续友善哦~", "这里是评论区,不是无人区;-)")
|
||||
private val ORDER_HEADINGS = setOf("热门评论", "最新评论")
|
||||
private val ORDER_NAMES = setOf("按热度", "按时间")
|
||||
private val THREAD_TOTAL = Regex("相关回复共\\s*(\\d+)\\s*条")
|
||||
private val FOOTER_TIME = Regex(
|
||||
"^(?:刚刚|昨天|前天|\\d+\\s*(?:秒|分钟|小时|天|周|月|年)前|" +
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
package com.jieliu.app.platform
|
||||
|
||||
import android.graphics.Rect
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
internal object BilibiliComposeEditor {
|
||||
data class Controls(
|
||||
val surface: UiNode,
|
||||
val input: UiNode,
|
||||
val send: UiNode,
|
||||
val share: UiNode,
|
||||
val shareIndicator: Rect,
|
||||
val photo: UiNode?,
|
||||
)
|
||||
|
||||
fun read(page: UiPage): Controls? {
|
||||
val input = page.nodes.singleOrNull { it.resourceId == "edit" && it.enabled && it.editable } ?: return null
|
||||
val surface = page.nodes.singleOrNull {
|
||||
it.className == "androidx.compose.ui.platform.ComposeView" && input.isDescendantOf(it) &&
|
||||
it.bounds.width() >= page.bounds.width() * .85 && it.bounds.contains(input.bounds)
|
||||
} ?: return null
|
||||
val publish = page.nodes.singleOrNull {
|
||||
it.isDescendantOf(surface) && it.labels() == listOf("发布") &&
|
||||
it.bounds.centerY() > input.bounds.bottom && it.bounds.centerX() > surface.bounds.centerX()
|
||||
} ?: return null
|
||||
val send = publish.nearbyClick()?.takeIf { it.isDescendantOf(surface) && !it.editable } ?: return null
|
||||
val toolbar = send.directParent() ?: return null
|
||||
val shareLabel = page.nodes.singleOrNull {
|
||||
it.isDescendantOf(toolbar) && it.labels() == listOf("转到动态") &&
|
||||
it.bounds.centerX() < surface.bounds.centerX() && it.bounds.centerY() in send.bounds.top until send.bounds.bottom
|
||||
} ?: return null
|
||||
val share = shareLabel.nearbyClick()?.takeIf { it.directParent() === toolbar } ?: return null
|
||||
val side = (shareLabel.bounds.height() * .58).roundToInt()
|
||||
val center = shareLabel.bounds.left - (shareLabel.bounds.height() * .8).roundToInt()
|
||||
val indicator = Rect(center - side, shareLabel.bounds.centerY() - side,
|
||||
center + side, shareLabel.bounds.centerY() + side)
|
||||
if (side < 6 || !surface.bounds.contains(indicator) || indicator.right >= shareLabel.bounds.left) return null
|
||||
|
||||
val slots = page.nodes.filter {
|
||||
it.directParent() === toolbar && it.biliClick() && it.labels().isEmpty() &&
|
||||
it.bounds.left >= share.bounds.right && it.bounds.right <= send.bounds.left &&
|
||||
it.bounds.top == send.bounds.top && it.bounds.bottom == send.bounds.bottom
|
||||
}.sortedBy { it.bounds.left }
|
||||
// Both observed top-level layouts put emoji, mention and photo first. The expanded toolbar
|
||||
// adds an action, a narrow spacer, and insert between photo and publish.
|
||||
val sameWidth = slots.take(4).zipWithNext().all { (left, right) ->
|
||||
left.bounds.width() in (right.bounds.width() * .85).roundToInt()..(right.bounds.width() * 1.15).roundToInt()
|
||||
}
|
||||
val expanded = slots.size == 6 && slots[4].bounds.width() < slots[2].bounds.width() * .55 &&
|
||||
slots[5].bounds.width() >= slots[2].bounds.width() * .85
|
||||
val photo = slots.getOrNull(2).takeIf {
|
||||
(slots.size == 4 || expanded) && sameWidth &&
|
||||
slots.zipWithNext().all { (left, right) -> abs(left.bounds.right - right.bounds.left) <= 2 }
|
||||
}
|
||||
return Controls(surface, input, send, share, indicator, photo)
|
||||
}
|
||||
|
||||
fun draftRegions(page: UiPage, controls: Controls): List<Rect>? {
|
||||
val inSheet = page.nodes.filter { it.isDescendantOf(controls.surface) }
|
||||
val toolbar = controls.send.directParent()?.directParent() ?: return null
|
||||
val sheet = toolbar.directParent()?.takeIf { controls.input.isDescendantOf(it) } ?: return null
|
||||
val inline = inSheet.filter {
|
||||
it.directParent() === sheet && !it.clickable && !it.scrollable && it.className == "android.view.View" &&
|
||||
it.bounds.top >= controls.input.bounds.bottom && it.bounds.bottom == toolbar.bounds.top &&
|
||||
it.bounds.width() >= sheet.bounds.width() * .85
|
||||
}
|
||||
if (inline.isNotEmpty()) return inlinePictures(page, inline.singleOrNull() ?: return null)
|
||||
val strip = inSheet.filter { it.resourceId in setOf("image_set_layout", "picture_list_container") }
|
||||
if (strip.isEmpty()) return emptyList<Rect>().takeIf {
|
||||
inSheet.none {
|
||||
(it.resourceId in DRAFT_PHOTO_IDS || it.description == "删除") && it.bounds.bottom <= toolbar.bounds.top
|
||||
}
|
||||
}
|
||||
val container = strip.singleOrNull() ?: return null
|
||||
return inSheet.filter { it.isDescendantOf(container) && it.resourceId in DRAFT_PHOTO_IDS &&
|
||||
container.bounds.contains(it.bounds) }.sortedWith(compareBy({ it.bounds.top }, { it.bounds.left }))
|
||||
.map { Rect(it.bounds) }
|
||||
}
|
||||
|
||||
private fun inlinePictures(page: UiPage, strip: UiNode): List<Rect>? {
|
||||
val children = page.nodes.filter { it.directParent() === strip }
|
||||
val pictures = children.filter {
|
||||
it.biliClick() && it.labels().isEmpty() && strip.bounds.contains(it.bounds) &&
|
||||
it.bounds.top == strip.bounds.top && it.bounds.bottom == strip.bounds.bottom &&
|
||||
abs(it.bounds.width() - it.bounds.height()) <= 2
|
||||
}.sortedBy { it.bounds.left }
|
||||
if (pictures.isEmpty() || children.size != pictures.size * 2) return null
|
||||
val deleteControls = children.filterNot { it in pictures }
|
||||
val used = mutableSetOf<UiNode>()
|
||||
for (picture in pictures) {
|
||||
val matching = deleteControls.singleOrNull { action ->
|
||||
action.biliClick() && page.nodes.count { marker ->
|
||||
marker.directParent() === action && marker.description == "删除" &&
|
||||
picture.bounds.contains(marker.bounds) && marker.bounds.centerX() > picture.bounds.centerX() &&
|
||||
marker.bounds.centerY() < picture.bounds.centerY()
|
||||
} == 1
|
||||
} ?: return null
|
||||
if (!used.add(matching)) return null
|
||||
}
|
||||
return pictures.map { Rect(it.bounds) }
|
||||
}
|
||||
|
||||
fun shareIsOff(pixel: PhotoPixels): Boolean {
|
||||
val (width, height, argb) = pixel
|
||||
if (width < 12 || height < 12 || argb.size != width * height) return false
|
||||
val background = argb.first()
|
||||
val corners = listOf(argb[width - 1], argb[width * (height - 1)], argb.last())
|
||||
if (corners.any { colorDistance(it, background) > 36 }) return false
|
||||
var inside = 0
|
||||
var insideDifferent = 0
|
||||
var ring = 0
|
||||
var ringDifferent = 0
|
||||
for (index in argb.indices) {
|
||||
val x = ((index % width + .5) * 2 / width) - 1
|
||||
val y = ((index / width + .5) * 2 / height) - 1
|
||||
val radius = x * x + y * y
|
||||
val different = colorDistance(argb[index], background) > 45
|
||||
when {
|
||||
radius <= .20 -> { inside++; if (different) insideDifferent++ }
|
||||
radius in 0.32..0.80 -> { ring++; if (different) ringDifferent++ }
|
||||
}
|
||||
}
|
||||
return inside > 0 && ring > 0 && insideDifferent <= inside * .08 && ringDifferent >= ring * .12
|
||||
}
|
||||
|
||||
private fun colorDistance(first: Int, second: Int): Int = listOf(16, 8, 0).sumOf { shift ->
|
||||
abs((first ushr shift and 255) - (second ushr shift and 255))
|
||||
}
|
||||
|
||||
private val DRAFT_PHOTO_IDS = setOf("comment_image", "image_item", "picture")
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package com.jieliu.app.platform
|
||||
|
||||
import android.graphics.Rect
|
||||
import android.os.SystemClock
|
||||
import android.view.accessibility.AccessibilityNodeInfo
|
||||
import com.jieliu.app.data.StagedPhotos
|
||||
import com.jieliu.app.task.TaskPlan
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.floor
|
||||
|
||||
/** Bilibili 9.21's inline recent-media grid. A check action immediately changes the open draft. */
|
||||
internal class BilibiliInlinePhotoPicker(private val ui: AccessibleUi) {
|
||||
private data class Region(val image: Rect, val badge: Rect)
|
||||
private data class Tile(val check: UiNode, val region: Region, val ordinal: Int, val isPhoto: Boolean)
|
||||
private data class Evidence(val regions: List<Region>, val ordinals: List<Int>, val photos: List<Int>, val draft: List<Rect>)
|
||||
private data class Frame(val grid: UiNode, val tiles: List<Tile>, val evidence: Evidence)
|
||||
private data class Scope(val window: Int, val grid: UiNodeSource)
|
||||
|
||||
fun select(
|
||||
staged: StagedPhotos,
|
||||
references: List<PhotoPixels>,
|
||||
expectedComposer: (UiPage) -> Boolean,
|
||||
readDraftRegions: (UiPage) -> List<Rect>?,
|
||||
beforeAttach: () -> Unit,
|
||||
) {
|
||||
require(staged.albumName.matches(stagedAlbum) && references.size in 1..TaskPlan.MAX_TEMPLATE_PHOTOS &&
|
||||
staged.uris.size == references.size && staged.uris.distinct().size == references.size &&
|
||||
staged.uris.all { uri ->
|
||||
val path = uri.pathSegments
|
||||
uri.scheme == "content" && uri.authority == "media" && path.size == 4 &&
|
||||
path.take(3) == listOf("external_primary", "images", "media") && (path.last().toLongOrNull() ?: 0L) > 0L
|
||||
})
|
||||
fun inspectFrame(scope: Scope? = null, draftSize: Int = 0, inspect: (UiPage, Frame) -> Boolean): Boolean =
|
||||
ui.inspect(traverseHiddenParents = true) { page ->
|
||||
val value = page.frame(scope, draftSize, expectedComposer, readDraftRegions) ?: return@inspect false
|
||||
inspect(page, value)
|
||||
} == true
|
||||
|
||||
val scope = ui.await(5_000) {
|
||||
ui.inspect(traverseHiddenParents = true) { page ->
|
||||
val visible = page.frame(null, 0, expectedComposer, readDraftRegions) ?: return@inspect null
|
||||
if (visible.evidence.ordinals.any { it != 0 }) {
|
||||
throw PlatformException("哔哩哔哩内嵌相册已有选中图片,未修改草稿")
|
||||
}
|
||||
Scope(page.windowId, visible.grid.retainSource())
|
||||
}
|
||||
} ?: throw PlatformException("未核对哔哩哔哩原回复中的完整内嵌相册和空草稿")
|
||||
|
||||
scope.grid.use {
|
||||
val selected = mutableListOf<Int>()
|
||||
val order = ui.await(6_000) {
|
||||
val unselected = captureGrid(scope, references.size) { action -> inspectFrame(scope, 0, action) }
|
||||
?: return@await null
|
||||
val (visible, images) = unselected
|
||||
bilibiliRecentPhotoOrder(references, images)?.map { visible.photos[it] }
|
||||
} ?: throw PlatformException("无法在哔哩哔哩最近图片中唯一核对本次新增的绑定图片")
|
||||
|
||||
for ((index, tileIndex) in order.withIndex()) {
|
||||
ui.pace()
|
||||
val verified = ui.await(5_000) {
|
||||
val (visible, images) = captureGrid(scope, references.size) { action -> inspectFrame(scope, index, action) }
|
||||
?: return@await null
|
||||
val recent = visible.photos.take(references.size)
|
||||
if (!visible.hasOrderedSelection(selected) || recent.toSet() != order.toSet()) {
|
||||
return@await null
|
||||
}
|
||||
val unselected = recent.withIndex().filter { (_, tile) -> visible.ordinals[tile] == 0 }
|
||||
val matches = unselected.filter { (photo, _) -> PublishedPhotoMatcher.matches(references[index], images[photo]) }
|
||||
visible.takeIf { matches.singleOrNull()?.value == tileIndex }
|
||||
} ?: throw PlatformException("哔哩哔哩未能重新核对第 ${index + 1} 张绑定图片")
|
||||
|
||||
val accepted = inspectFrame(scope, index) { _, current ->
|
||||
if (current.evidence != verified || !current.evidence.hasOrderedSelection(selected)) return@inspectFrame false
|
||||
val tile = current.tiles.getOrNull(tileIndex)?.takeIf { it.isPhoto && it.ordinal == 0 }
|
||||
?: return@inspectFrame false
|
||||
if (index == 0) beforeAttach()
|
||||
ui.click(tile.check)
|
||||
}
|
||||
if (!accepted) throw PlatformException("哔哩哔哩未接受第 ${index + 1} 张图片的选中操作")
|
||||
|
||||
selected.add(tileIndex)
|
||||
val settled = ui.await(5_000) {
|
||||
var evidence: Evidence? = null
|
||||
inspectFrame(scope, index + 1) { _, visible ->
|
||||
evidence = visible.evidence.takeIf { it.hasOrderedSelection(selected) }
|
||||
evidence != null
|
||||
}
|
||||
evidence
|
||||
} ?: throw PlatformException("哔哩哔哩未回读第 ${index + 1} 张图片的选中编号和草稿张数")
|
||||
val proven = capture(scope.window, settled.draft) { inspectFrame(scope, index + 1) { _, frame ->
|
||||
frame.evidence == settled
|
||||
} }
|
||||
if (proven == null || !BilibiliReceiptEvidence.matchesOrderedPhotos(references.take(index + 1), proven)) {
|
||||
throw PlatformException("哔哩哔哩草稿的图片内容或顺序与绑定不一致")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var nextCaptureAt = 0L
|
||||
|
||||
private fun capture(window: Int, regions: List<Rect>, unchanged: () -> Boolean): List<PhotoPixels>? = ui.await(2_000) {
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
if (now < nextCaptureAt || !unchanged()) return@await null
|
||||
nextCaptureAt = now + 400L
|
||||
ui.screenshotPhotos(window, regions)?.takeIf { it.size == regions.size && unchanged() }
|
||||
}
|
||||
|
||||
private fun captureGrid(
|
||||
scope: Scope,
|
||||
photoCount: Int,
|
||||
inspect: ((UiPage, Frame) -> Boolean) -> Boolean,
|
||||
): Pair<Evidence, List<PhotoPixels>>? {
|
||||
var evidence: Evidence? = null
|
||||
inspect { _, value -> evidence = value.evidence; true }
|
||||
val snapshot = evidence ?: return null
|
||||
val photoRegions = snapshot.photos.take(photoCount).map { snapshot.regions[it] }
|
||||
val images = capture(scope.window, photoRegions.map(Region::image)) { inspect { _, value -> value.evidence == snapshot } }
|
||||
?: return null
|
||||
return snapshot to images.zip(photoRegions) { pixels, region -> pixels.maskBadge(region) }
|
||||
}
|
||||
|
||||
private fun UiPage.frame(
|
||||
scope: Scope?,
|
||||
draftSize: Int,
|
||||
expectedComposer: (UiPage) -> Boolean,
|
||||
readDraftRegions: (UiPage) -> List<Rect>?,
|
||||
): Frame? {
|
||||
if (!complete || (scope != null && scope.window != windowId) || !expectedComposer(this)) return null
|
||||
val panel = nodes.singleOrNull { it.resourceId == "bottom_tools_fragment" && it.className == "android.widget.FrameLayout" &&
|
||||
bounds.contains(it.bounds) } ?: return null
|
||||
val grid = nodes.singleOrNull { it.resourceId == "media_recycleview" && it.className == "android.widget.GridView" &&
|
||||
it.isDescendantOf(panel) && panel.bounds.contains(it.bounds) } ?: return null
|
||||
if (grid.directParent()?.resourceId != "content_layout" || (scope != null && !grid.hasSource(scope.grid))) return null
|
||||
val draft = readDraftRegions(this)?.takeIf { it.size == draftSize }?.map(::Rect) ?: return null
|
||||
if (draft.any { it.isEmpty || !bounds.contains(it) || it.bottom > grid.bounds.top } || draft.hasOverlap()) return null
|
||||
|
||||
val cells = nodes.filter { it.directParent() === grid }.sortedWith(compareBy({ it.bounds.top }, { it.bounds.left }))
|
||||
if (cells.size !in 2..MAX_RECENT_CELLS + 1) return null
|
||||
val camera = cells.first().takeIf { it.resourceId == "media_layout" && it.isNativeClick() && grid.bounds.contains(it.bounds) }
|
||||
?: return null
|
||||
if (nodes.count { it.resourceId == "media_txt" && it.text == "拍摄" && it.directParent() === camera } != 1) return null
|
||||
val tiles = cells.drop(1).map { cell ->
|
||||
val area = cell.bounds
|
||||
if (cell.resourceId != "image_item_layout" || cell.className != "android.widget.RelativeLayout" ||
|
||||
!grid.bounds.contains(area) || abs(area.width() - area.height()) > maxOf(4, area.width() / 12)) return null
|
||||
val foreground = nodes.singleOrNull { it.resourceId == "foreground_item" && it.directParent() === cell && it.bounds == area }
|
||||
?: return null
|
||||
val image = nodes.singleOrNull { it.resourceId == "image_item" && it.className == "android.widget.ImageView" &&
|
||||
it.directParent() === foreground && it.bounds == area } ?: return null
|
||||
val check = nodes.singleOrNull { it.resourceId == "media_item_check_layout" && it.className == "android.widget.FrameLayout" &&
|
||||
it.directParent() === foreground && it.isNativeClick() && area.contains(it.bounds) } ?: return null
|
||||
val badge = nodes.singleOrNull { it.resourceId == "media_item_check" && it.className == "android.widget.TextView" &&
|
||||
it.directParent() === check && check.bounds.contains(it.bounds) && it.bounds.width() < area.width() / 2 &&
|
||||
it.bounds.height() < area.height() / 2 } ?: return null
|
||||
val ordinal = badgeOrdinal(check, badge) ?: return null
|
||||
val video = nodes.any { it.resourceId in videoIndicators && it.isDescendantOf(foreground) }
|
||||
Tile(check, Region(Rect(image.bounds), Rect(badge.bounds)), ordinal, !video)
|
||||
}
|
||||
if (tiles.map { it.region.image }.hasOverlap()) return null
|
||||
val photos = tiles.indices.filter { tiles[it].isPhoto }
|
||||
return Frame(grid, tiles, Evidence(tiles.map(Tile::region), tiles.map(Tile::ordinal), photos, draft))
|
||||
}
|
||||
|
||||
private fun Evidence.hasOrderedSelection(selected: List<Int>): Boolean {
|
||||
return ordinals.count { it > 0 } == selected.size &&
|
||||
ordinals.indices.all { tile -> ordinals[tile] == selected.indexOf(tile) + 1 }
|
||||
}
|
||||
|
||||
private fun badgeOrdinal(holder: UiNode, badge: UiNode): Int? {
|
||||
val number = badge.text.toIntOrNull()?.takeIf { it in 1..TaskPlan.MAX_TEMPLATE_PHOTOS }
|
||||
// The native inline checker exposes both the sequence number and selected=true.
|
||||
if (number != null) return number.takeIf { badge.selected && holder.checked != false && badge.checked != false }
|
||||
if (badge.text.isNotEmpty() || holder.checked == true || badge.checked == true || holder.selected || badge.selected) return null
|
||||
return 0
|
||||
}
|
||||
|
||||
private fun PhotoPixels.maskBadge(region: Region): PhotoPixels {
|
||||
val badge = Rect(region.badge).apply { inset(-2, -2) }
|
||||
val image = region.image
|
||||
if (!badge.intersect(image)) return this
|
||||
val x = width.toDouble() / image.width()
|
||||
val y = height.toDouble() / image.height()
|
||||
val left = floor((badge.left - image.left) * x).toInt().coerceIn(0, width)
|
||||
val right = ceil((badge.right - image.left) * x).toInt().coerceIn(left, width)
|
||||
val top = floor((badge.top - image.top) * y).toInt().coerceIn(0, height)
|
||||
val bottom = ceil((badge.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 List<Rect>.hasOverlap(): Boolean = indices.any { right -> (0 until right).any { left -> Rect.intersects(this[left], this[right]) } }
|
||||
|
||||
private fun UiNode.isNativeClick(): Boolean = enabled && supports(AccessibilityNodeInfo.ACTION_CLICK)
|
||||
|
||||
private companion object {
|
||||
const val MAX_RECENT_CELLS = 24
|
||||
val stagedAlbum = Regex("SJ-[0-9a-f]{12}")
|
||||
val videoIndicators = setOf("video_layout", "video_duration_txt", "video_size_txt")
|
||||
}
|
||||
}
|
||||
|
||||
internal fun bilibiliRecentPhotoOrder(references: List<PhotoPixels>, recentPhotos: List<PhotoPixels>): List<Int>? {
|
||||
if (references.isEmpty() || references.size > recentPhotos.size) return null
|
||||
// The freshly staged group starts the recent grid. The same photos can also appear later as originals.
|
||||
val fresh = recentPhotos.take(references.size)
|
||||
val order = references.map { expected ->
|
||||
fresh.indices.singleOrNull { PublishedPhotoMatcher.matches(expected, fresh[it]) } ?: return null
|
||||
}
|
||||
return order.takeIf { it.toSet() == references.indices.toSet() }
|
||||
}
|
||||
@@ -2,6 +2,18 @@ package com.jieliu.app.platform
|
||||
|
||||
import com.jieliu.app.task.RECHECK_WINDOW_MS
|
||||
|
||||
internal fun UiPage.requireBilibiliCommentAccess() {
|
||||
val dialog = nodes.singleOrNull { it.resourceId == "v_container" } ?: return
|
||||
val controls = nodes.filter { it.directParent() === dialog && dialog.bounds.contains(it.bounds) }
|
||||
if (controls.count { it.resourceId == "title" && it.text == "请转正答题" && !it.clickable } == 1 &&
|
||||
controls.count { it.resourceId == "content" && it.text == "需要升级成为LV2后才可以评论,先去答题吧" && !it.clickable } == 1 &&
|
||||
controls.count { it.resourceId == "btn_to_answer" && it.text == "前往答题" && it.clickable } == 1 &&
|
||||
controls.count { it.resourceId == "btn_cancel" && it.text == "放弃本次答题" && it.clickable } == 1
|
||||
) {
|
||||
throw PlatformInteractionRestrictedException("哔哩哔哩提示账号需达到 LV2 才能评论")
|
||||
}
|
||||
}
|
||||
|
||||
internal object BilibiliLabels {
|
||||
private val replyCount = Regex("(?:(?:全部|查看|展开|共)\\s*)?(\\d+)\\s*条回复(?:\\s*[>>])?")
|
||||
private val detailTotal = Regex("相关回复(?:共)?\\s*(\\d+)\\s*条")
|
||||
|
||||
@@ -13,13 +13,15 @@ internal class BilibiliReplies(
|
||||
private val photos: PhotoLibrary,
|
||||
private val diagnostic: (String) -> Unit,
|
||||
) {
|
||||
private data class Editor(val container: UiNode, val input: UiNode, val send: UiNode)
|
||||
private data class Editor(val container: UiNode, val input: UiNode, val send: UiNode,
|
||||
val compose: BilibiliComposeEditor.Controls? = null)
|
||||
private data class Prepared(
|
||||
val target: CommentTarget,
|
||||
val text: String,
|
||||
val window: Int,
|
||||
val bar: UiNodeSource,
|
||||
val input: UiNodeSource,
|
||||
val topLevel: Boolean,
|
||||
) : Closeable {
|
||||
override fun close() {
|
||||
bar.close()
|
||||
@@ -33,11 +35,12 @@ internal class BilibiliReplies(
|
||||
private data class RoleMenu(val window: Int, val role: Role)
|
||||
|
||||
private val picker = BilibiliPhotoPicker(ui)
|
||||
private val inlinePicker = BilibiliInlinePhotoPicker(ui)
|
||||
private var prepared: Prepared? = null
|
||||
|
||||
fun prepare(target: CommentTarget, text: String, requiresImages: Boolean): Boolean {
|
||||
check(prepared == null && text.isNotBlank())
|
||||
if (comments.isComposeOriginal(target)) return inspectComposeReply(target, requiresImages)
|
||||
check(!requiresImages) { "哔哩哔哩原评论回复只支持文字。" }
|
||||
val threadOpened = comments.enterThread(target)
|
||||
val baseline = if (threadOpened) {
|
||||
comments.readThread(target) { _, thread -> thread.complete && thread.replies.none { it.target.text == text } } == true
|
||||
@@ -48,75 +51,58 @@ internal class BilibiliReplies(
|
||||
}
|
||||
|
||||
ui.pace()
|
||||
val opened = comments.readOriginal(target) { page, row ->
|
||||
if (page.editorBar() != null || row.own) return@readOriginal false
|
||||
ui.click(row.reply)
|
||||
} == true
|
||||
if (!opened) {
|
||||
val previousWindow = comments.readOriginal(target) { page, row ->
|
||||
page.windowId.takeIf { page.editorBar() == null && !row.own && ui.click(row.reply) }
|
||||
}
|
||||
if (previousWindow == null) {
|
||||
if (threadOpened) comments.leaveThread()
|
||||
return false
|
||||
}
|
||||
prepared = ui.await(5_000) {
|
||||
ui.inspect { page ->
|
||||
val editor = page.replyEditor(target) ?: return@inspect null
|
||||
if (!editor.input.isStillBlankAndFocused() || page.draftPictures(editor)?.isNotEmpty() != false) {
|
||||
return@inspect null
|
||||
}
|
||||
Prepared(target, text, page.windowId, editor.container.retainSource(), editor.input.retainSource())
|
||||
}
|
||||
} ?: throw PlatformException("哔哩哔哩未显示指向原评论的空白回复框")
|
||||
prepareEditor(target, text, previousWindow, topLevel = false, requiresImages = false)
|
||||
return true
|
||||
}
|
||||
|
||||
fun prepareTopLevel(video: VideoContext, target: CommentTarget, text: String, requiresImages: Boolean): Boolean {
|
||||
check(prepared == null && text.isNotBlank())
|
||||
ui.pace()
|
||||
val window = comments.readOriginal(target) { page, row ->
|
||||
page.windowId.takeIf { !row.own && row.more?.let { ui.click(it) } == true }
|
||||
} ?: return false
|
||||
check(consumeRoleMenu(window) == Role.OTHER) { "无法核对哔哩哔哩视频评论的本人标识。" }
|
||||
if (!comments.prepareLatestTopLevel(video)) throw PlatformException("哔哩哔哩未显示按时间排序的原视频评论")
|
||||
val previous = comments.readTopLevel(video, text) { page, matches ->
|
||||
page.windowId.takeIf { page.complete && matches.occurrences == 0 }
|
||||
} ?: return false
|
||||
if (!comments.openTopLevel(video)) return false
|
||||
prepareEditor(target, text, previous, topLevel = true, requiresImages = requiresImages)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun prepareEditor(target: CommentTarget, text: String, previousWindow: Int, topLevel: Boolean, requiresImages: Boolean) {
|
||||
prepared = ui.await(5_000) {
|
||||
ui.inspect(traverseHiddenParents = true) { page ->
|
||||
val editor = page.matchingEditor(target, topLevel) ?: return@inspect null
|
||||
if (editor.compose != null && page.windowId == previousWindow) return@inspect null
|
||||
if (!editor.input.focused || !editor.input.isStillBlankAndFocused() ||
|
||||
page.attachmentRegions(editor)?.isNotEmpty() != false) return@inspect null
|
||||
if (requiresImages && page.photoButton(editor) == null) {
|
||||
throw PlatformException("哔哩哔哩视频评论未显示可核对的图片入口")
|
||||
}
|
||||
Prepared(target, text, page.windowId, editor.container.retainSource(), editor.input.retainSource(), topLevel)
|
||||
}
|
||||
} ?: throw PlatformException(if (topLevel) "哔哩哔哩未显示原视频的空白评论框" else "哔哩哔哩未显示指向原评论的空白回复框")
|
||||
}
|
||||
|
||||
fun hasPreparedBaseline(targetKey: String, text: String): Boolean =
|
||||
prepared?.let { it.target.key == targetKey && it.text == text } == true
|
||||
|
||||
fun preparedTarget(text: String): CommentTarget = prepared?.takeIf { it.text == text }?.target
|
||||
?: throw PlatformException("尚未核对哔哩哔哩的原评论回复框")
|
||||
?: throw PlatformException("尚未核对哔哩哔哩评论草稿")
|
||||
|
||||
fun hasUnsettledEditor(): Boolean = ui.inspect(traverseHiddenParents = true) { page ->
|
||||
page.editorBar() != null || page.composeInput() != null
|
||||
page.editorBar() != null || BilibiliComposeEditor.read(page) != null
|
||||
} == true
|
||||
|
||||
private fun inspectComposeReply(target: CommentTarget, requiresImages: Boolean): Boolean {
|
||||
ui.pace()
|
||||
val originalWindow = comments.readOriginal(target) { page, row ->
|
||||
page.windowId.takeIf { !row.own && ui.click(row.reply) }
|
||||
} ?: return false
|
||||
val hasImageEntry = ui.await(5_000) {
|
||||
ui.inspect(traverseHiddenParents = true) { page ->
|
||||
if (page.windowId == originalWindow) return@inspect null
|
||||
val (surface, input) = page.composeInput() ?: return@inspect null
|
||||
val cue = input.hint.ifBlank { input.text }
|
||||
if (!input.showingHint || !BilibiliLabels.replyPrompt(cue, target.author) ||
|
||||
input.text.isNotBlank() && input.text != cue
|
||||
) return@inspect null
|
||||
page.nodes.any { it.isDescendantOf(surface) && it.labels().any { label ->
|
||||
label in attachmentLabels || label == "图片" || label == "相册"
|
||||
} }
|
||||
}
|
||||
} ?: throw PlatformException("哔哩哔哩未显示指向原评论的空白回复框")
|
||||
diagnostic("哔哩哔哩已核对匹配评论和指向原作者的回复框")
|
||||
val reason = if (requiresImages && !hasImageEntry) "原评论的回复框未提供可核对的图片入口"
|
||||
else "此评论界面的本人回复回执尚未完成核对"
|
||||
throw PlatformException("哔哩哔哩${reason},已在提交前停止")
|
||||
}
|
||||
|
||||
private fun UiPage.composeInput(): Pair<UiNode, UiNode>? {
|
||||
val input = nodes.singleOrNull { it.resourceId == "edit" && it.enabled && it.editable && it.focused } ?: return null
|
||||
val surface = nodes.singleOrNull {
|
||||
it.className == "androidx.compose.ui.platform.ComposeView" && input.isDescendantOf(it)
|
||||
} ?: return null
|
||||
if (surface.bounds.width() < bounds.width() * .85 || !surface.bounds.contains(input.bounds)) return null
|
||||
val publish = nodes.singleOrNull { it.isDescendantOf(surface) && it.text == "发布" &&
|
||||
it.bounds.centerY() > input.bounds.bottom && it.bounds.centerX() > surface.bounds.centerX() }
|
||||
?: return null
|
||||
if (nodes.none { it.isDescendantOf(surface) && it.text == "转到动态" &&
|
||||
it.bounds.centerX() < surface.bounds.centerX() && it.bounds.top <= publish.bounds.centerY() &&
|
||||
it.bounds.bottom >= publish.bounds.centerY() }) return null
|
||||
return surface to input
|
||||
}
|
||||
|
||||
fun reset() {
|
||||
prepared?.close()
|
||||
prepared = null
|
||||
@@ -125,56 +111,59 @@ internal class BilibiliReplies(
|
||||
fun submit(target: CommentTarget, text: String, attachments: List<TemplatePhoto>, arm: () -> Unit): Boolean {
|
||||
val session = prepared?.takeIf { it.target == target && it.text == text }
|
||||
?: throw PlatformException("哔哩哔哩回复对象或正文已变更")
|
||||
check(session.topLevel || attachments.isEmpty()) { "哔哩哔哩原评论回复只支持文字。" }
|
||||
var staged: StagedPhotos? = null
|
||||
var handedToEditor = false
|
||||
try {
|
||||
val references = if (attachments.isNotEmpty()) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
|
||||
throw PlatformException("图片回复核对需要 Android 11 或更新版本")
|
||||
}
|
||||
val canAttach = ui.inspect { page ->
|
||||
val editor = page.checkedEditor(session) ?: return@inspect false
|
||||
page.photoButton(editor) != null && editor.input.isStillBlankAndFocused() && page.draftPictures(editor)?.isEmpty() == true
|
||||
} == true
|
||||
if (!canAttach) {
|
||||
throw PlatformException("哔哩哔哩原评论的回复框未提供可核对的图片入口,已在提交前停止")
|
||||
throw PlatformException("评论图片核对需要 Android 11 或更新版本")
|
||||
}
|
||||
val pixels = photos.readReceiptPixels(attachments) ?: throw PlatformException("无法读取绑定图片")
|
||||
photos.cleanupStaged()
|
||||
val album = photos.stage(attachments)
|
||||
staged = album
|
||||
ui.pace()
|
||||
val opened = ui.inspect { page ->
|
||||
val editor = page.checkedEditor(session) ?: return@inspect false
|
||||
if (!editor.input.isStillBlankAndFocused() || page.draftPictures(editor)?.isEmpty() != true) return@inspect false
|
||||
page.photoButton(editor)?.let { ui.click(it) } == true
|
||||
} == true
|
||||
if (!opened) throw PlatformException("未打开哔哩哔哩原回复的图片选择器")
|
||||
picker.select(album.albumName, pixels) { handedToEditor = true }
|
||||
val isInline = ui.inspect(traverseHiddenParents = true) { page ->
|
||||
val editor = page.checkedEditor(session) ?: return@inspect null
|
||||
if (!editor.input.isStillBlankAndFocused() || page.attachmentRegions(editor)?.isEmpty() != true) return@inspect null
|
||||
(editor.compose != null).takeIf { page.photoButton(editor)?.let { ui.click(it) } == true }
|
||||
} ?: throw PlatformException("未打开哔哩哔哩视频评论的图片选择器")
|
||||
if (isInline) {
|
||||
inlinePicker.select(album, pixels,
|
||||
expectedComposer = { it.checkedEditor(session)?.compose != null },
|
||||
readDraftRegions = { page -> page.checkedEditor(session)?.let { page.attachmentRegions(it) } },
|
||||
) { handedToEditor = true }
|
||||
} else picker.select(album.albumName, pixels) { handedToEditor = true }
|
||||
pixels
|
||||
} else emptyList()
|
||||
|
||||
val wrote = ui.await(5_000) {
|
||||
ui.inspect { page ->
|
||||
ui.inspect(traverseHiddenParents = true) { page ->
|
||||
val editor = page.checkedEditor(session) ?: return@inspect null
|
||||
if (page.draftPictures(editor)?.size != references.size || !editor.input.isStillBlankAndFocused()) return@inspect null
|
||||
if (page.attachmentRegions(editor)?.size != references.size || editor.input.hasDraft()) return@inspect null
|
||||
if (!editor.input.focused) {
|
||||
ui.click(editor.input)
|
||||
return@inspect null
|
||||
}
|
||||
if (!editor.input.isStillBlankAndFocused()) return@inspect null
|
||||
ui.setText(editor.input, text, requireBlankFocusedInput = true)
|
||||
}
|
||||
} == true
|
||||
if (!wrote) throw PlatformException("无法在哔哩哔哩原回复框中写入完整正文")
|
||||
if (!wrote) throw PlatformException("无法在哔哩哔哩评论框中写入完整正文")
|
||||
|
||||
ui.pace()
|
||||
val ready = ui.await(5_000) {
|
||||
ui.inspect { page -> page.readyDraft(session, references.size)?.second }
|
||||
} ?: throw PlatformException("未能回读哔哩哔哩回复正文、图片和发布按钮")
|
||||
if (!verifyImages(ready, references) { ui.inspect { it.readyDraft(session, references.size)?.second } }) {
|
||||
ui.inspect(traverseHiddenParents = true) { page -> page.readyDraft(session, references.size)?.second }
|
||||
} ?: throw PlatformException("未能回读哔哩哔哩评论正文、图片和发布按钮")
|
||||
if (!verifyImages(ready, references) {
|
||||
ui.inspect(traverseHiddenParents = true) { it.readyDraft(session, references.size)?.second }
|
||||
}) {
|
||||
throw PlatformException("哔哩哔哩草稿图片与按顺序绑定的图片不一致")
|
||||
}
|
||||
if (ui.inspect { it.readyDraft(session, references.size)?.second } != ready) {
|
||||
throw PlatformException("哔哩哔哩回复草稿已变更")
|
||||
}
|
||||
verifyShareOff(session, ready, references.size)
|
||||
arm()
|
||||
return ui.inspect { page ->
|
||||
return ui.inspect(traverseHiddenParents = true) { page ->
|
||||
val draft = page.readyDraft(session, references.size)?.takeIf { it.second == ready } ?: return@inspect false
|
||||
ui.click(draft.first.send)
|
||||
} == true
|
||||
@@ -184,6 +173,24 @@ internal class BilibiliReplies(
|
||||
}
|
||||
}
|
||||
|
||||
private fun verifyShareOff(session: Prepared, draft: ImageView, count: Int) {
|
||||
val share = ui.inspect(traverseHiddenParents = true) { page ->
|
||||
val editor = page.readyDraft(session, count)?.takeIf { it.second == draft }?.first ?: return@inspect null
|
||||
val controls = editor.compose ?: return@inspect Pair(false, null)
|
||||
controls.share.checked to Rect(controls.shareIndicator)
|
||||
} ?: throw PlatformException("哔哩哔哩评论草稿已变更")
|
||||
val off = when (share.first) {
|
||||
false -> true
|
||||
true -> false
|
||||
null -> share.second?.let { bounds ->
|
||||
ui.await(1_600) {
|
||||
ui.screenshotPhotos(draft.window, listOf(bounds))?.singleOrNull()?.let(BilibiliComposeEditor::shareIsOff)
|
||||
}
|
||||
} == true
|
||||
}
|
||||
if (!off) throw PlatformException("请核对哔哩哔哩评论框中的「转到动态」开关")
|
||||
}
|
||||
|
||||
fun confirm(key: String, author: String, text: String, attachments: List<TemplatePhoto>, armedAt: Long): CommentPublishResult {
|
||||
val references = photos.readReceiptPixels(attachments) ?: return CommentPublishResult.UNCERTAIN
|
||||
val target = ui.await(4_000) { comments.threadTarget(key, author) } ?: return CommentPublishResult.UNCERTAIN
|
||||
@@ -203,17 +210,57 @@ internal class BilibiliReplies(
|
||||
return CommentPublishResult.CONFIRMED
|
||||
}
|
||||
|
||||
fun confirmTopLevel(video: VideoContext, text: String, attachments: List<TemplatePhoto>, armedAt: Long): CommentPublishResult {
|
||||
val references = photos.readReceiptPixels(attachments) ?: return CommentPublishResult.UNCERTAIN
|
||||
if (ui.await(4_000) { true.takeIf { comments.prepareLatestTopLevel(video) } } != true) {
|
||||
return CommentPublishResult.UNCERTAIN
|
||||
}
|
||||
fun readMatches(): Pair<Int, ReceiptRow?>? = comments.readTopLevel(video, text) { page, matches ->
|
||||
val row = matches.rows.singleOrNull()?.takeIf { matches.occurrences == 1 }
|
||||
matches.occurrences to row?.let { receiptRow(page, it, references.size, armedAt) }
|
||||
}
|
||||
fun observed(): Pair<Int, ReceiptRow?>? = readMatches()?.takeIf { it.first > 1 || it.second != null }
|
||||
fun readReceipt(): ReceiptRow? = readMatches()?.second
|
||||
var candidate = ui.await(5_000, ::observed)
|
||||
for (screen in 2..5) {
|
||||
if (candidate != null || !comments.scrollTopLevel(video)) break
|
||||
candidate = ui.await(2_000, ::observed)
|
||||
}
|
||||
val receipt = candidate?.second ?: return CommentPublishResult.UNCERTAIN
|
||||
diagnostic("哔哩哔哩已在原视频最新评论找到唯一匹配的正文和图片区域")
|
||||
if (!verifyImages(receipt.images, references) { readReceipt()?.takeIf { it == receipt }?.images }) {
|
||||
return CommentPublishResult.UNCERTAIN
|
||||
}
|
||||
if (!receipt.own) {
|
||||
val opened = comments.readTopLevel(video, text) { page, matches ->
|
||||
val row = matches.rows.singleOrNull()?.takeIf { matches.occurrences == 1 } ?: return@readTopLevel false
|
||||
receiptRow(page, row, references.size, armedAt) == receipt && row.more?.let { ui.click(it) } == true
|
||||
} == true
|
||||
if (!opened || consumeRoleMenu(receipt.images.window) != Role.OWN ||
|
||||
ui.await(3_500) { readReceipt()?.takeIf { it == receipt } } == null
|
||||
) {
|
||||
return CommentPublishResult.UNCERTAIN
|
||||
}
|
||||
}
|
||||
diagnostic("哔哩哔哩已核对原视频下的本人评论及全部绑定图片")
|
||||
return CommentPublishResult.CONFIRMED
|
||||
}
|
||||
|
||||
private fun receiptRow(target: CommentTarget, text: String, count: Int, armedAt: Long): ReceiptRow? =
|
||||
comments.readThread(target) { page, thread ->
|
||||
val row = BilibiliReceiptEvidence.uniqueReply(
|
||||
target, thread.original.target, thread.complete, text, thread.replies,
|
||||
) { it.target.text } ?: return@readThread null
|
||||
val time = row.time ?: return@readThread null
|
||||
if (!BilibiliLabels.matchesSubmissionTime(time, armedAt, System.currentTimeMillis())) return@readThread null
|
||||
val pictures = row.images?.takeIf { it.size == count } ?: return@readThread null
|
||||
imageView(page, pictures)?.let { ReceiptRow(row.target.key, row.own, it) }
|
||||
receiptRow(page, row, count, armedAt)
|
||||
}
|
||||
|
||||
private fun receiptRow(page: UiPage, row: BilibiliComments.Row, count: Int, armedAt: Long): ReceiptRow? {
|
||||
val time = row.time ?: return null
|
||||
if (!BilibiliLabels.matchesSubmissionTime(time, armedAt, System.currentTimeMillis())) return null
|
||||
val pictures = row.images?.takeIf { it.size == count } ?: return null
|
||||
return imageView(page, pictures)?.let { ReceiptRow(row.target.key, row.own, it) }
|
||||
}
|
||||
|
||||
private fun inspectRole(
|
||||
target: CommentTarget,
|
||||
expected: ReceiptRow?,
|
||||
@@ -228,9 +275,14 @@ internal class BilibiliReplies(
|
||||
row?.more?.let { ui.click(it) } == true
|
||||
} == true
|
||||
if (!opened) return null
|
||||
val menu = ui.await(3_500) { ui.inspect { it.roleMenu(before.images.window) } } ?: return null
|
||||
val closed = ui.inspect { page -> page.roleMenu(before.images.window) == menu && ui.back() } == true
|
||||
return menu.role.takeIf { closed }
|
||||
return consumeRoleMenu(before.images.window)
|
||||
}
|
||||
|
||||
private fun consumeRoleMenu(previousWindow: Int): Role? {
|
||||
val menu = ui.await(3_500) { ui.inspect { it.roleMenu(previousWindow) } } ?: return null
|
||||
val closed = ui.inspect { page -> page.roleMenu(previousWindow) == menu && ui.back() } == true
|
||||
if (!closed || ui.await(3_500) { ui.inspect { page -> true.takeIf { page.windowId == previousWindow } } } != true) return null
|
||||
return menu.role
|
||||
}
|
||||
|
||||
private fun UiPage.roleMenu(previousWindow: Int): RoleMenu? {
|
||||
@@ -253,8 +305,10 @@ internal class BilibiliReplies(
|
||||
return readBack() == snapshot && BilibiliReceiptEvidence.matchesOrderedPhotos(expected, actual)
|
||||
}
|
||||
|
||||
private fun imageView(page: UiPage, pictures: List<UiNode>): ImageView? {
|
||||
val regions = pictures.map { Rect(it.bounds) }
|
||||
private fun imageView(page: UiPage, pictures: List<UiNode>): ImageView? =
|
||||
imageViewFromRegions(page, pictures.map { Rect(it.bounds) })
|
||||
|
||||
private fun imageViewFromRegions(page: UiPage, regions: List<Rect>): ImageView? {
|
||||
if (regions.any { it.isEmpty || !page.bounds.contains(it) } || regions.indices.any { i ->
|
||||
(0 until i).any { Rect.intersects(regions[it], regions[i]) }
|
||||
}) return null
|
||||
@@ -263,28 +317,37 @@ internal class BilibiliReplies(
|
||||
|
||||
private fun UiPage.readyDraft(session: Prepared, count: Int): Pair<Editor, ImageView>? {
|
||||
val editor = checkedEditor(session) ?: return null
|
||||
if (!editor.send.biliClick() || !editor.input.hasCurrentFocusedText(session.text) { BilibiliLabels.replyPrompt(it, session.target.author) }) {
|
||||
if (!editor.send.biliClick() || editor.compose?.share?.checked == true ||
|
||||
!editor.input.hasCurrentFocusedText(session.text) { cueMatches(it, session.target, session.topLevel) }
|
||||
) {
|
||||
return null
|
||||
}
|
||||
val pictures = draftPictures(editor)?.takeIf { it.size == count } ?: return null
|
||||
return imageView(this, pictures)?.let { editor to it }
|
||||
val regions = attachmentRegions(editor)?.takeIf { it.size == count } ?: return null
|
||||
return imageViewFromRegions(this, regions)?.let { editor to it }
|
||||
}
|
||||
|
||||
private fun UiPage.checkedEditor(session: Prepared): Editor? {
|
||||
if (windowId != session.window) return null
|
||||
return replyEditor(session.target)?.takeIf { it.container.hasSource(session.bar) && it.input.hasSource(session.input) }
|
||||
return matchingEditor(session.target, session.topLevel)
|
||||
?.takeIf { it.container.hasSource(session.bar) && it.input.hasSource(session.input) }
|
||||
}
|
||||
|
||||
private fun UiPage.editorBar(): UiNode? = nodes.singleOrNull { bar ->
|
||||
bar.resourceId == "comment_bar" && nodes.any { it.isDescendantOf(bar) && it.resourceId == "edit" && it.editable }
|
||||
}
|
||||
|
||||
private fun UiPage.replyEditor(target: CommentTarget): Editor? {
|
||||
private fun UiPage.matchingEditor(target: CommentTarget, topLevel: Boolean): Editor? {
|
||||
val compose = BilibiliComposeEditor.read(this)
|
||||
if (compose != null) {
|
||||
val cue = compose.input.hint.ifBlank { compose.input.text.takeIf { compose.input.showingHint }.orEmpty() }
|
||||
if (!cueMatches(cue, target, topLevel)) return null
|
||||
return Editor(compose.surface, compose.input, compose.send, compose)
|
||||
}
|
||||
if (!complete) return null
|
||||
val bar = editorBar() ?: return null
|
||||
val input = nodes.singleOrNull { it.resourceId == "edit" && it.isDescendantOf(bar) && it.editable && it.focused } ?: return null
|
||||
val input = nodes.singleOrNull { it.resourceId == "edit" && it.isDescendantOf(bar) && it.editable } ?: return null
|
||||
if (!listOf(input.hint, input.description, input.text.takeIf { input.showingHint }.orEmpty())
|
||||
.any { BilibiliLabels.replyPrompt(it, target.author) }) return null
|
||||
.any { cueMatches(it, target, topLevel) }) return null
|
||||
val send = nodes.singleOrNull { it.resourceId == "send" && it.isDescendantOf(bar) &&
|
||||
it.labels().any { label -> label == "发布" || label == "发布,按钮" } } ?: return null
|
||||
val shareOptions = nodes.filter { it.isDescendantOf(bar) && it.resourceId in shareContainers }
|
||||
@@ -297,11 +360,21 @@ internal class BilibiliReplies(
|
||||
return Editor(bar, input, send)
|
||||
}
|
||||
|
||||
private fun UiPage.photoButton(editor: Editor): UiNode? = nodes.singleOrNull { node ->
|
||||
private fun cueMatches(cue: String, target: CommentTarget, topLevel: Boolean): Boolean = if (topLevel) {
|
||||
BilibiliComposeComments.isTopLevelPrompt(cue)
|
||||
} else BilibiliLabels.replyPrompt(cue, target.author)
|
||||
|
||||
private fun UiPage.photoButton(editor: Editor): UiNode? = editor.compose?.photo ?: nodes.singleOrNull { node ->
|
||||
node.isDescendantOf(editor.container) && node.biliClick() &&
|
||||
node.labels().any(attachmentLabels::contains)
|
||||
}
|
||||
|
||||
private fun UiPage.attachmentRegions(editor: Editor): List<Rect>? {
|
||||
val compose = editor.compose
|
||||
if (compose != null) return BilibiliComposeEditor.draftRegions(this, compose)
|
||||
return draftPictures(editor)?.map { Rect(it.bounds) }
|
||||
}
|
||||
|
||||
private fun UiPage.draftPictures(editor: Editor): List<UiNode>? {
|
||||
val strips = nodes.filter { it.isDescendantOf(editor.container) && it.resourceId in draftStrips }
|
||||
if (strips.isEmpty()) return emptyList<UiNode>().takeIf {
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.jieliu.app.platform
|
||||
|
||||
import android.accessibilityservice.AccessibilityService
|
||||
import com.jieliu.app.data.PhotoLibrary
|
||||
import com.jieliu.app.task.BilibiliCommentScope
|
||||
import com.jieliu.app.task.PendingComment
|
||||
import com.jieliu.app.task.TemplatePhoto
|
||||
|
||||
@@ -67,18 +68,23 @@ object PlatformRegistry {
|
||||
noteKind: XiaohongshuNoteKind = XiaohongshuNoteKind.ANY,
|
||||
targetNoteKey: String? = null,
|
||||
pinnedResumeNoteKey: String? = null,
|
||||
bilibiliCommentScope: BilibiliCommentScope = BilibiliCommentScope.REPLY_TO_ORIGINAL,
|
||||
receiptDiagnostic: (String) -> Unit = {},
|
||||
pauseBetweenActions: () -> Unit = {},
|
||||
): PlatformAdapter {
|
||||
val spec = platforms.firstOrNull { it.id == platformId }
|
||||
if (spec == null || !spec.implemented) throw PlatformException("${spec?.label ?: platformId} 暂未接入")
|
||||
val checkPage = if (spec == xiaohongshu) UiPage::requireXhsCommentAccess else null
|
||||
val checkPage = when (spec) {
|
||||
xiaohongshu -> UiPage::requireXhsCommentAccess
|
||||
bilibili -> UiPage::requireBilibiliCommentAccess
|
||||
else -> null
|
||||
}
|
||||
val ui = 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), receiptDiagnostic)
|
||||
bilibili.id -> BilibiliAdapter(spec, ui, PhotoLibrary(service), bilibiliCommentScope, receiptDiagnostic)
|
||||
else -> throw PlatformException("${spec.label} 暂未接入")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,11 @@ enum class ReplyMode(val label: String) {
|
||||
DEEPSEEK("匹配评论并回复"),
|
||||
}
|
||||
|
||||
enum class BilibiliCommentScope(val label: String) {
|
||||
REPLY_TO_ORIGINAL("回复原评论(仅文字)"),
|
||||
VIDEO_COMMENT("发布视频评论(可带图片)"),
|
||||
}
|
||||
|
||||
data class TemplatePhoto(val id: String, val displayName: String) {
|
||||
init {
|
||||
require(UUID.matches(id)) { "无效的话术图片标识。" }
|
||||
@@ -45,6 +50,7 @@ data class TaskPlan(
|
||||
val repliesPerVideo: Int = 1,
|
||||
val xiaohongshuNoteKind: XiaohongshuNoteKind = XiaohongshuNoteKind.ANY,
|
||||
val xiaohongshuNoteKey: String? = null,
|
||||
val bilibiliCommentScope: BilibiliCommentScope = BilibiliCommentScope.REPLY_TO_ORIGINAL,
|
||||
) {
|
||||
fun validate() {
|
||||
if (contentTypes == null) validateLegacy() else validateHierarchy(contentTypes)
|
||||
|
||||
@@ -24,6 +24,8 @@ internal class TaskRunner(
|
||||
private val status: (String) -> Unit,
|
||||
) {
|
||||
private val contentUnit = PlatformRegistry.platforms.firstOrNull { it.id == plan.platformId }?.contentUnit ?: "视频"
|
||||
private val bilibili = plan.platformId == "bilibili"
|
||||
private val videoComment = bilibili && plan.bilibiliCommentScope == BilibiliCommentScope.VIDEO_COMMENT
|
||||
|
||||
private data class MatchedReply(
|
||||
val target: CommentTarget,
|
||||
@@ -52,8 +54,9 @@ internal class TaskRunner(
|
||||
}
|
||||
check(checkpoint.pending == null) { "请先核对上一条评论的发送结果。" }
|
||||
val mode = if (plan.replyMode == ReplyMode.BROWSE) ReplyMode.BROWSE else ReplyMode.TEMPLATES
|
||||
val quota = if (mode == ReplyMode.TEMPLATES) " · 每个${contentUnit}最多 ${plan.repliesPerVideo} 条回复" else ""
|
||||
store.appendLog("开始任务 · ${mode.label} · ${plan.limit} 个$contentUnit$quota")
|
||||
val quota = if (mode == ReplyMode.TEMPLATES) " · 每个${contentUnit}最多 ${plan.repliesPerVideo} 条${if (videoComment) "评论" else "回复"}" else ""
|
||||
val modeLabel = if (bilibili && mode == ReplyMode.TEMPLATES) plan.bilibiliCommentScope.label else mode.label
|
||||
store.appendLog("开始任务 · $modeLabel · ${plan.limit} 个$contentUnit$quota")
|
||||
status("正在打开目标应用")
|
||||
platform.launch()
|
||||
var activeTypeId: String? = null
|
||||
@@ -87,7 +90,9 @@ internal class TaskRunner(
|
||||
var screen = 1
|
||||
while (checkpoint.activeVideo != null) {
|
||||
requireRunning(cancelled)
|
||||
val currentType = store.readPlan().findType(type.id)?.takeIf { it.rules.isNotEmpty() } ?: break
|
||||
val latest = store.readPlan()
|
||||
check(hasSameBilibiliScope(latest)) { "哔哩哔哩发布方式已更新,请重新开始任务。" }
|
||||
val currentType = latest.findType(type.id)?.takeIf { it.rules.isNotEmpty() } ?: break
|
||||
status("正在识别评论 · 第 $screen 屏")
|
||||
val reply = findVisibleReply(currentType, candidate.title, checkpoint)
|
||||
if (reply == null) {
|
||||
@@ -98,9 +103,10 @@ internal class TaskRunner(
|
||||
store.appendLog("第 $screen 屏命中评论关键字 ${reply.rule.keyword}")
|
||||
val result = submitReply(candidate, reply) { comment ->
|
||||
val armed = checkpoint.arm(comment)
|
||||
check(store.savePendingIfCurrent(armed) { latest ->
|
||||
latest.findType(type.id)?.let(::KeywordMatcher)?.matchingRule(reply.target.text) == reply.rule
|
||||
}) { "关键字或话术已更新,未提交此回复。请清除当前草稿后继续任务。" }
|
||||
check(store.savePendingIfCurrent(armed) { current ->
|
||||
hasSameBilibiliScope(current) &&
|
||||
current.findType(type.id)?.let(::KeywordMatcher)?.matchingRule(reply.target.text) == reply.rule
|
||||
}) { "关键词、话术或发布方式已更新,尚未提交。请清除草稿后继续。" }
|
||||
checkpoint = armed
|
||||
}
|
||||
val confirmation = if (result == CommentPublishResult.UNCERTAIN && checkpoint.canAutomaticallyRecheck()) {
|
||||
@@ -221,7 +227,8 @@ internal class TaskRunner(
|
||||
requireRunning(cancelled)
|
||||
if (progress.hasHandled(target.key)) continue
|
||||
val rule = matcher.matchingRule(target.text) ?: continue
|
||||
val selection = checkpoint.selectReply(rule, title) ?: continue
|
||||
val configured = checkpoint.selectReply(rule, title) ?: continue
|
||||
val selection = if (bilibili && !videoComment) configured.copy(photos = emptyList()) else configured
|
||||
if (platform.prepareReply(target, selection.text, selection.photos.isNotEmpty())) {
|
||||
return MatchedReply(target, rule, selection)
|
||||
}
|
||||
@@ -231,7 +238,12 @@ internal class TaskRunner(
|
||||
|
||||
private fun submitReply(video: VideoContext, reply: MatchedReply, arm: (PendingComment) -> Unit): CommentPublishResult {
|
||||
val (text, use, photos) = reply.selection
|
||||
status(if (photos.isEmpty()) "正在回复匹配的评论" else "正在准备 ${photos.size} 张图片并回复匹配的评论")
|
||||
status(when {
|
||||
videoComment && photos.isEmpty() -> "正在发布视频评论"
|
||||
videoComment -> "正在准备 ${photos.size} 张图片并发布视频评论"
|
||||
photos.isEmpty() -> "正在回复匹配的评论"
|
||||
else -> "正在准备 ${photos.size} 张图片并回复匹配的评论"
|
||||
})
|
||||
val beforeClick = {
|
||||
requireRunning(cancelled)
|
||||
val armedAt = if (platform.hasPreparedReplyBaseline(reply.target.key, text)) System.currentTimeMillis() else null
|
||||
@@ -243,6 +255,9 @@ internal class TaskRunner(
|
||||
|
||||
private fun TaskPlan.findType(id: String): ContentType? = contentTypes?.firstOrNull { it.id == id }
|
||||
|
||||
private fun hasSameBilibiliScope(latest: TaskPlan): Boolean = !bilibili ||
|
||||
latest.platformId == plan.platformId && latest.bilibiliCommentScope == plan.bilibiliCommentScope
|
||||
|
||||
private companion object {
|
||||
const val MAX_COMMENT_SWIPES = 12
|
||||
const val MIN_RESUME_SEARCH = 12
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.jieliu.app.platform
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class BilibiliInlinePhotoPickerTest {
|
||||
private val vertical = photo { x, _ -> x / 8 % 2 }
|
||||
private val horizontal = photo { _, y -> y / 8 % 2 }
|
||||
private val checkerboard = photo { x, y -> (x / 8 + y / 8) % 2 }
|
||||
|
||||
@Test fun matchesFreshImagesInBindingOrderInsteadOfGridOrder() {
|
||||
assertEquals(listOf(1, 0), bilibiliRecentPhotoOrder(listOf(vertical, horizontal), listOf(horizontal, vertical, checkerboard)))
|
||||
}
|
||||
|
||||
@Test fun allowsOlderCopiesWithAUniqueFreshGroup() {
|
||||
assertEquals(listOf(0, 1), bilibiliRecentPhotoOrder(listOf(vertical, horizontal), listOf(vertical, horizontal, horizontal, vertical)))
|
||||
}
|
||||
|
||||
@Test fun rejectsDuplicatesInTheFreshGroupAndOlderOnlyMatches() {
|
||||
val references = listOf(vertical, horizontal)
|
||||
assertNull(bilibiliRecentPhotoOrder(references, listOf(vertical, vertical, horizontal)))
|
||||
assertNull(bilibiliRecentPhotoOrder(references, listOf(vertical, checkerboard, horizontal)))
|
||||
assertNull(bilibiliRecentPhotoOrder(references, listOf(vertical, checkerboard)))
|
||||
assertNull(bilibiliRecentPhotoOrder(listOf(vertical, vertical), listOf(vertical, horizontal, checkerboard)))
|
||||
}
|
||||
|
||||
private fun photo(dark: (Int, Int) -> Int): PhotoPixels {
|
||||
val side = 48
|
||||
return PhotoPixels(side, side, IntArray(side * side) { index ->
|
||||
if (dark(index % side, index / side) == 0) 0xffab2c1e.toInt() else 0xff2baa95.toInt()
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -16,11 +16,12 @@ import java.util.UUID
|
||||
|
||||
class TaskRunnerTest {
|
||||
@Test fun unsupportedBilibiliAttachmentStopsBeforeAnySendIntent() {
|
||||
val store = RecordingStore(TaskCheckpoint("bilibili-no-picker", plan(firstType).copy(platformId = "bilibili")))
|
||||
val plan = plan(firstType).copy(platformId = "bilibili", bilibiliCommentScope = BilibiliCommentScope.VIDEO_COMMENT)
|
||||
val store = RecordingStore(TaskCheckpoint("bilibili-no-picker", plan))
|
||||
val platform = FakePlatform(store, listOf(listOf(target("original", "API 充值")))).apply {
|
||||
onPrepare = { requiresImages ->
|
||||
assertTrue(requiresImages)
|
||||
throw PlatformException("哔哩哔哩原回复的图片入口不可用")
|
||||
throw PlatformException("哔哩哔哩视频评论的图片入口不可用")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +35,49 @@ class TaskRunnerTest {
|
||||
assertTrue(store.checkpoint.receipts.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun bilibiliOriginalReplyUsesOnlyTextAndKeepsPhotoBindings() {
|
||||
val store = RecordingStore(TaskCheckpoint("bilibili-directed", plan(firstType).copy(platformId = "bilibili")))
|
||||
val platform = FakePlatform(store, listOf(listOf(target("original", "API 充值")))).apply {
|
||||
onPrepare = { requiresImages -> assertFalse(requiresImages) }
|
||||
}
|
||||
|
||||
execute(store, platform)
|
||||
|
||||
val attempt = platform.attempts.single()
|
||||
assertEquals("original", attempt.targetKey)
|
||||
assertEquals("API 充值对应的图文", attempt.text)
|
||||
assertTrue(attempt.photos.isEmpty())
|
||||
assertEquals(photos, store.plan.searchTypes().single().rules.first().phrases.single().photos)
|
||||
assertEquals(Outcome.SENT, store.checkpoint.receipts.single().outcome)
|
||||
}
|
||||
|
||||
@Test fun bilibiliVideoCommentPassesTheBoundPhotosInOrder() {
|
||||
val plan = plan(firstType).copy(platformId = "bilibili", bilibiliCommentScope = BilibiliCommentScope.VIDEO_COMMENT)
|
||||
val store = RecordingStore(TaskCheckpoint("bilibili-video-comment", plan))
|
||||
val platform = FakePlatform(store, listOf(listOf(target("trigger", "API 充值")))).apply {
|
||||
onPrepare = { requiresImages -> assertTrue(requiresImages) }
|
||||
}
|
||||
|
||||
execute(store, platform)
|
||||
|
||||
assertEquals("trigger", platform.attempts.single().targetKey)
|
||||
assertEquals(photos, platform.attempts.single().photos)
|
||||
assertEquals(Outcome.SENT, store.checkpoint.receipts.single().outcome)
|
||||
}
|
||||
|
||||
@Test fun changingBilibiliScopeWhileDraftIsOpenDoesNotArmOrSend() {
|
||||
val store = RecordingStore(TaskCheckpoint("bilibili-mode-change", plan(firstType).copy(platformId = "bilibili")))
|
||||
val platform = FakePlatform(store, listOf(listOf(target("original", "API 充值")))).apply {
|
||||
beforePublish = { store.plan = store.plan.copy(bilibiliCommentScope = BilibiliCommentScope.VIDEO_COMMENT) }
|
||||
}
|
||||
|
||||
execute(store, platform)
|
||||
|
||||
assertTrue(platform.attempts.isEmpty())
|
||||
assertEquals(0, store.pendingWrites)
|
||||
assertNull(store.checkpoint.pending)
|
||||
}
|
||||
|
||||
@Test fun searchesTypeNameAndRepliesInThreadToTheMatchingKeywordAfterScrolling() {
|
||||
val plan = plan(firstType, secondType)
|
||||
val store = RecordingStore(TaskCheckpoint("type-search", plan))
|
||||
|
||||
Reference in New Issue
Block a user