diff --git a/README.md b/README.md index d696f92..874d938 100644 --- a/README.md +++ b/README.md @@ -55,9 +55,9 @@ powershell -NoProfile -File ./scripts/verify-apk.ps1 选择「小红书」后,可设置单次任务笔记上限和每条笔记回复上限。任务会按内容类型搜索,停留到设定时长后返回结果列表打开下一条笔记。部分 vivo 设备首次会弹出跨应用打开提示,确认是「拾见」打开「小红书」后可选择「始终打开」。若等待超时,返回拾见点「继续任务」。 - 选择「哔哩哔哩」后,任务按普通视频计数。在 vivo Android 12 的哔哩哔哩 9.21.0 上,顶层评论有图片按钮。楼中楼回复填入正文后依然没有图片按钮,「插入内容」打开视频和专栏搜索。拾见会在提交前暂停带图任务,并保留当前视频进度。该设备上的新版回复界面仍待完成实发和自动回执验收。 [哔哩哔哩发图说明](https://www.bilibili.com/opus/752428294212681795) + 选择「哔哩哔哩」并启用评论匹配后,可在「评论发布位置」选择「回复原评论(仅文字)」或「发布视频评论(可带图片)」。两种方式都用命中的评论关键字选择同一话术库。回复原评论时只提交正文,图片绑定仍保留在话术库。发布视频评论时,正文和按配置顺序绑定的图片一起提交到当前视频的评论区。绑定图无法核对时会在提交前暂停。 [哔哩哔哩发图说明](https://www.bilibili.com/opus/752428294212681795) 4. 在「任务」点「开始任务」。保持手机解锁,由拾见打开目标平台。运行期间让目标平台留在前台。在拾见任务页或用通知栏按钮可暂停。登录、验证、页面布局不可识别等中断可在手机处理后点「继续任务」。 -5. 发送后,拾见尝试核对原评论下新增的本人回复,匹配正文和同一回复内的全部绑定图片后登记回执。图文自动核对需要 Android 11 或更新版本,图片比对在手机内存中完成。待核对卡片出现「自动核对回复」时,可让拾见再次查找并核对这条回复。若仍显示待核对,可到原评论下核对正文及图片,再选择「确认已发送」或「跳过此回复」。待核对期间会阻止自动重发。 +5. 发送后,拾见按本次任务选择的位置核对新增的本人评论。定向回复在原评论线程内核对,哔哩哔哩视频评论在同一视频的按时间评论列表中核对。带图评论还需要同一条评论的正文、所有图片和配置顺序一致。图文自动核对需要 Android 11 或更新版本,图片比对在手机内存中完成。可从待核对卡片启动自动核对,或核对后手动确认或跳过。待核对期间会阻止自动重发。 安装完成后,任务可以脱离电脑运行。加载平台内容需要手机网络,话术匹配和选择在拾见本机完成。 @@ -72,7 +72,8 @@ powershell -NoProfile -File ./scripts/verify-apk.ps1 | 每条视频或笔记回复上限 | 默认 1 条,可设为 1–100 条。在匹配回复模式下,已确认发送的回复计入上限。达标、评论列表到末尾或扫描范围内没有更多匹配时,浏览下一条。 | | 观看时长 | 1–300 秒的闭区间,逐视频或笔记取样,默认 5–12 秒。 | | 动作间隔 | 150–30,000 毫秒的闭区间,默认 600–1,800 毫秒。评论滑动在列表内变化起点、距离、轨迹、时长和停留时间,每条内容最多滑动 12 次并在每屏重新读取。 | -| 处理方式 | 「仅浏览」观看视频或浏览笔记。「匹配评论并回复」逐屏读取评论,匹配到当前类型中有可用话术的关键字后回复原评论。同一任务内每条原评论最多尝试一次发送。 | +| 处理方式 | 「仅浏览」观看视频或浏览笔记。评论匹配模式逐屏读取评论,按命中的关键字选话术。同一任务内每条命中的评论最多触发一次提交。 | +| 哔哩哔哩评论发布位置 | 「回复原评论(仅文字)」是旧配置的默认值。「发布视频评论(可带图片)」按视频计入发布上限。两种方式共享话术库,新任务使用保存的发布方式。 | | 话术库 | 每个关键字最多 100 条话术,每条最多 120 个 Unicode 码点。支持 {keyword} 和 {title},分别填入命中的关键字和视频或笔记标题。各库独立随机轮换,有可用替代时避开连续重复。 | | 话术图片 | 每条话术独立绑定最多 9 张 JPEG 或 PNG,可一次多选、逐张调整顺序或移除。单张最多 20 MB,需要 Android 10 或更新版本。编辑原话术时会保留其图片。 | diff --git a/app/build.gradle.kts b/app/build.gradle.kts index b201440..a8428c6 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -13,8 +13,8 @@ android { applicationId = "com.jieliu.app" minSdk = 26 targetSdk = 35 - versionCode = 26 - versionName = "0.1.25" + versionCode = 32 + versionName = "0.1.31" } compileOptions { diff --git a/app/src/main/java/com/jieliu/app/AutomationService.kt b/app/src/main/java/com/jieliu/app/AutomationService.kt index 572e45b..5c70c31 100644 --- a/app/src/main/java/com/jieliu/app/AutomationService.kt +++ b/app/src/main/java/com/jieliu/app/AutomationService.kt @@ -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) diff --git a/app/src/main/java/com/jieliu/app/MainActivity.kt b/app/src/main/java/com/jieliu/app/MainActivity.kt index d813dfe..fc2cc99 100644 --- a/app/src/main/java/com/jieliu/app/MainActivity.kt +++ b/app/src/main/java/com/jieliu/app/MainActivity.kt @@ -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(), ) diff --git a/app/src/main/java/com/jieliu/app/data/LocalStore.kt b/app/src/main/java/com/jieliu/app/data/LocalStore.kt index d144a67..b9fb5d5 100644 --- a/app/src/main/java/com/jieliu/app/data/LocalStore.kt +++ b/app/src/main/java/com/jieliu/app/data/LocalStore.kt @@ -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) diff --git a/app/src/main/java/com/jieliu/app/platform/BilibiliAdapter.kt b/app/src/main/java/com/jieliu/app/platform/BilibiliAdapter.kt index ccc6860..b8b39fa 100644 --- a/app/src/main/java/com/jieliu/app/platform/BilibiliAdapter.kt +++ b/app/src/main/java/com/jieliu/app/platform/BilibiliAdapter.kt @@ -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 = - comments.open(expected).map(CommentTarget::text) + comments.open(expected).map(CommentTarget::text).also { openVideo = expected } override fun scanComments(): List { 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, 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 } } diff --git a/app/src/main/java/com/jieliu/app/platform/BilibiliComments.kt b/app/src/main/java/com/jieliu/app/platform/BilibiliComments.kt index 132dbe4..b1cdb79 100644 --- a/app/src/main/java/com/jieliu/app/platform/BilibiliComments.kt +++ b/app/src/main/java/com/jieliu/app/platform/BilibiliComments.kt @@ -23,6 +23,7 @@ internal class BilibiliComments( ) internal data class ThreadRows(val original: Row, val replies: List, val complete: Boolean) + internal data class TopLevelMatches(val rows: List, 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 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 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 { val parsed = parsedRows(list, videoKey) val counts = parsed.groupingBy { it.target.key }.eachCount() diff --git a/app/src/main/java/com/jieliu/app/platform/BilibiliComposeComments.kt b/app/src/main/java/com/jieliu/app/platform/BilibiliComposeComments.kt index 4ae5f1d..2ba0a3b 100644 --- a/app/src/main/java/com/jieliu/app/platform/BilibiliComposeComments.kt +++ b/app/src/main/java/com/jieliu/app/platform/BilibiliComposeComments.kt @@ -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? { - // 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().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*(?:秒|分钟|小时|天|周|月|年)前|" + diff --git a/app/src/main/java/com/jieliu/app/platform/BilibiliComposeEditor.kt b/app/src/main/java/com/jieliu/app/platform/BilibiliComposeEditor.kt new file mode 100644 index 0000000..4543886 --- /dev/null +++ b/app/src/main/java/com/jieliu/app/platform/BilibiliComposeEditor.kt @@ -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? { + 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().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? { + 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() + 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") +} diff --git a/app/src/main/java/com/jieliu/app/platform/BilibiliInlinePhotoPicker.kt b/app/src/main/java/com/jieliu/app/platform/BilibiliInlinePhotoPicker.kt new file mode 100644 index 0000000..94707cb --- /dev/null +++ b/app/src/main/java/com/jieliu/app/platform/BilibiliInlinePhotoPicker.kt @@ -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, val ordinals: List, val photos: List, val draft: List) + private data class Frame(val grid: UiNode, val tiles: List, val evidence: Evidence) + private data class Scope(val window: Int, val grid: UiNodeSource) + + fun select( + staged: StagedPhotos, + references: List, + expectedComposer: (UiPage) -> Boolean, + readDraftRegions: (UiPage) -> List?, + 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() + 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, unchanged: () -> Boolean): List? = 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>? { + 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?, + ): 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): 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.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, recentPhotos: List): List? { + 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() } +} diff --git a/app/src/main/java/com/jieliu/app/platform/BilibiliLabels.kt b/app/src/main/java/com/jieliu/app/platform/BilibiliLabels.kt index 34df395..0c81dfc 100644 --- a/app/src/main/java/com/jieliu/app/platform/BilibiliLabels.kt +++ b/app/src/main/java/com/jieliu/app/platform/BilibiliLabels.kt @@ -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*条") diff --git a/app/src/main/java/com/jieliu/app/platform/BilibiliReplies.kt b/app/src/main/java/com/jieliu/app/platform/BilibiliReplies.kt index 011263a..757601e 100644 --- a/app/src/main/java/com/jieliu/app/platform/BilibiliReplies.kt +++ b/app/src/main/java/com/jieliu/app/platform/BilibiliReplies.kt @@ -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? { - 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, 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, 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, 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? = 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? = 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): ImageView? { - val regions = pictures.map { Rect(it.bounds) } + private fun imageView(page: UiPage, pictures: List): ImageView? = + imageViewFromRegions(page, pictures.map { Rect(it.bounds) }) + + private fun imageViewFromRegions(page: UiPage, regions: List): 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? { 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? { + 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? { val strips = nodes.filter { it.isDescendantOf(editor.container) && it.resourceId in draftStrips } if (strips.isEmpty()) return emptyList().takeIf { diff --git a/app/src/main/java/com/jieliu/app/platform/PlatformAdapter.kt b/app/src/main/java/com/jieliu/app/platform/PlatformAdapter.kt index 0e1cc27..75430ff 100644 --- a/app/src/main/java/com/jieliu/app/platform/PlatformAdapter.kt +++ b/app/src/main/java/com/jieliu/app/platform/PlatformAdapter.kt @@ -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} 暂未接入") } } diff --git a/app/src/main/java/com/jieliu/app/task/TaskPlan.kt b/app/src/main/java/com/jieliu/app/task/TaskPlan.kt index cc8adad..9127990 100644 --- a/app/src/main/java/com/jieliu/app/task/TaskPlan.kt +++ b/app/src/main/java/com/jieliu/app/task/TaskPlan.kt @@ -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) diff --git a/app/src/main/java/com/jieliu/app/task/TaskRunner.kt b/app/src/main/java/com/jieliu/app/task/TaskRunner.kt index 236b60e..9052ee5 100644 --- a/app/src/main/java/com/jieliu/app/task/TaskRunner.kt +++ b/app/src/main/java/com/jieliu/app/task/TaskRunner.kt @@ -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 diff --git a/app/src/test/java/com/jieliu/app/platform/BilibiliInlinePhotoPickerTest.kt b/app/src/test/java/com/jieliu/app/platform/BilibiliInlinePhotoPickerTest.kt new file mode 100644 index 0000000..8e70576 --- /dev/null +++ b/app/src/test/java/com/jieliu/app/platform/BilibiliInlinePhotoPickerTest.kt @@ -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() + }) + } +} diff --git a/app/src/test/java/com/jieliu/app/task/TaskRunnerTest.kt b/app/src/test/java/com/jieliu/app/task/TaskRunnerTest.kt index 603b658..fd489b6 100644 --- a/app/src/test/java/com/jieliu/app/task/TaskRunnerTest.kt +++ b/app/src/test/java/com/jieliu/app/task/TaskRunnerTest.kt @@ -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)) diff --git a/docs/ui-preview.html b/docs/ui-preview.html index 917045e..bdd0da0 100644 --- a/docs/ui-preview.html +++ b/docs/ui-preview.html @@ -370,6 +370,16 @@ +

达到回复上限或找不到更多匹配评论时,进入下一个视频。

@@ -476,6 +486,9 @@ const byId = id => document.getElementById(id); const scope = byId("search-scope"); const platformPicker = byId("target-platform"); + const replyMode = byId("reply-mode"); + const bilibiliScopeField = byId("bilibili-comment-scope-field"); + const bilibiliScope = byId("bilibili-comment-scope"); const typePicker = byId("content-type"); const rulePicker = byId("keyword-rule"); const phrasePicker = byId("reply-phrase"); @@ -667,13 +680,23 @@ redrawLibrary(); }); } - platformPicker.addEventListener("change", () => { + function updateCommentSettings() { const unit = platformPicker.selectedOptions[0].dataset.unit; + const showBilibiliScope = platformPicker.value === "bilibili" && replyMode.selectedIndex === 1; + const videoComment = showBilibiliScope && bilibiliScope.value === "VIDEO_COMMENT"; + const operation = videoComment ? "发布" : "回复"; + bilibiliScopeField.hidden = !showBilibiliScope; + byId("bilibili-comment-scope-hint").textContent = videoComment + ? "根据匹配结果在当前视频发布评论,话术绑定的图片会随正文发送。" + : "将话术作为文字回复发到命中的原评论下。已绑定的图片会保留。"; byId("content-limit-label").textContent = `单次任务${unit}上限`; - byId("reply-limit-label").textContent = `每条${unit}回复上限`; - byId("reply-scope-hint").textContent = `达到回复上限或找不到更多匹配评论时,进入下一个${unit}。`; + byId("reply-limit-label").textContent = `每条${unit}${videoComment ? "评论发布" : "回复"}上限`; + byId("reply-scope-hint").textContent = `达到${operation}上限或找不到更多匹配评论时,进入下一个${unit}。`; byId("content-scope-hint").textContent = `按内容类型搜索${unit},按关键词匹配评论。每个关键词可配置多条话术。`; - }); + } + for (const picker of [platformPicker, replyMode, bilibiliScope]) { + picker.addEventListener("change", updateCommentSettings); + } byId("save-preview").addEventListener("click", () => { const status = byId("library-status"); const invalid = [byId("video-limit"), byId("replies-per-video")].find(input => !input.validity.valid); @@ -686,9 +709,11 @@ const searchTypes = selectedType ? [selectedType] : types; const type = byId("task-content-type"); const progress = byId("task-progress"); - byId("task-mode").textContent = `${platform.text} · ${byId("reply-mode").value}`; + const modeLabel = bilibiliScopeField.hidden ? replyMode.value : bilibiliScope.selectedOptions[0].text; + const confirmedLabel = !bilibiliScopeField.hidden && bilibiliScope.value === "VIDEO_COMMENT" ? "已确认发布评论" : "已确认回复"; + byId("task-mode").textContent = `${platform.text} · ${modeLabel}`; byId("task-scope").textContent = `内容类型 ${searchTypes.length} 个 · 单次 ${limit} 个${unit}`; - byId("task-summary").textContent = `已处理${unit} 0 / ${limit} · 已确认回复 0 条`; + byId("task-summary").textContent = `已处理${unit} 0 / ${limit} · ${confirmedLabel} 0 条`; progress.max = limit; progress.setAttribute("aria-label", `已处理 0 个${unit},共 ${limit} 个`); type.hidden = searchTypes.length === 0; @@ -700,6 +725,7 @@ invalid?.focus({ preventScroll: true }); status.scrollIntoView({ block: "nearest", inline: "nearest" }); }); + updateCommentSettings(); redrawLibrary(); diff --git a/docs/开发进度.md b/docs/开发进度.md index 61d894a..739f58e 100644 --- a/docs/开发进度.md +++ b/docs/开发进度.md @@ -1,6 +1,26 @@ # 拾见开发进度 -最近更新于 2026-11-27 10:42(UTC+8)。以下按开发轮次倒序记录。 +最近更新于 2026-11-27 11:56(UTC+8)。以下按开发轮次倒序记录。 + +## 2026-11-27 · 哔哩哔哩两种发布方式真机验收 + +- 在 vivo Android 12、哔哩哔哩 9.21.0 上,确认原评论只有一条旧回复时可能只显示可点开的回复预览。拾见 0.1.27 补充回复预览入口和原评论固定列表解析,并处理发布前截图间隔和评论菜单返回后的界面等待。 +- 11:28:50 从「开始任务」启动纯文字回复轮,自动搜索「国外大模型充值」,11:29:20 在第 6 屏匹配到「接码是什么意思」。本轮临时使用该关键词和一条说明接码用途的测试话术。11:29:21 保存提交意图,点击发布后出现账号需达到 LV2 的提示,任务未写入自动 `SENT`。 +- 用户确认账号已具备评论权限后,11:37 重新从「开始任务」启动,在提交前停止。随后在同一原评论下发现唯一一条完整测试正文,零图片,其菜单显示「复制」「删除」,无「举报」。本轮文字实际可见一条,归档保留原始提交意图,未重复发布。同一个运行内的自动回执未通过。权限弹窗只能说明平台展示了限制,发送结果仍需独立核对。 +- 拾见 0.1.28 识别此评论权限弹窗,暂停任务并记录具体原因,保留已写入的提交意图。用真机节点回放验证了限制弹窗及五个不应触发限制的对照页面。离线构建和 72 项 JVM 单测通过,Lint 为 0 错误、3 警告。调试 APK 通过 v2 签名校验,手机安装包与本地 APK 的 SHA-256 一致。 +- 已核对两张绑定图片来自不同文件。11:39:44 从「开始任务」启动双图顶层轮,沿用原有话术和两张图片,临时用「第一次开gpt想用codex」作为该轮匹配关键词。任务自动搜索并在第 1 屏命中。11:40:14 因相册图片核对未通过而在提交前停止,双图实发为 0。 +- 拾见 0.1.29 将相册一一匹配限定在本次两张图应出现的最近位置,每次选图前仍检查对应位置,选图后核对整份草稿的图片内容和顺序。11:45:22 从「开始任务」重跑双图轮,自动搜索、命中、选取两张绑定图并提交。最新评论中出现唯一匹配正文。离线使用生产图片匹配器核对到同一条评论里的两张图均与绑定顺序一致。原任务的自动回执未通过,已保留原始双图待核对记录。 +- 拾见 0.1.30 补充双图评论中可点击区域被缩短时的完整图片图层识别。补充条件包含同一行的方形参考图层、边界和无重叠。真机候选图层只比点击区域向下多 24 像素,用完整区域才能通过绑定图核对。离线回放按顺序找到两张绑定图,交换顺序无法通过。11:51 只读复核时,最新评论首屏已没有目标评论,向下滚动一屏后仍能看到同一条正文。 +- 拾见 0.1.31 为顶层评论回执增加原视频最新评论逐屏核对,单次最多检查五屏。发现同屏多个完全一致的正文时停止确认。11:55:45 从「自动核对评论」启动只读复核,11:56:07 核对原视频下同一条本人评论的正文及两张绑定图的内容和顺序,并写入一条 `SENT`。该回执保存在原双图任务的检查点里,来自后续复核运行。两种方式各实际可见一条,同一个运行内从「开始任务」到回执的验收仍未通过。 +- 手机已恢复验收前的设置及无障碍配置。设备保留双图任务的正式回执,文字提交意图和验证证据已归档。0.1.31 通过 73 项 JVM 单测,Lint 为 0 错误、3 警告。调试包通过 APK v2 签名校验,真机安装包与本地构建文件的 SHA-256 一致。 + +## 2026-11-27 · 拾见 0.1.26 哔哩哔哩两种发布方式 + +- 配置页新增「回复原评论(仅文字)」和「发布视频评论(可带图片)」。沿用关键字匹配、话术轮换和每视频上限。旧配置默认回复原评论,话术里的图片绑定可在视频评论方式中继续使用。发布方式随任务保存在检查点中。 +- 定向回复绑定原评论和回复编辑框。视频评论在已核对的原视频评论区打开顶层编辑框,按顺序选取与绑定图唯一匹配的暂存图。提交前核对正文、草稿图片和「转到动态」开关。回执按发布方式检查原评论线程或原视频的按时间评论列表,证据不足时保留待核对。 +- vivo Android 12、哔哩哔哩 9.21.0。真机检查了顶层相册和按时间排序,手动选中两张合成测试图。原生选中序号为 1 和 2,两个草稿缩略图与绑定顺序一致。用生产匹配器离线核对了 11 个可见相册格和两张草稿图。已清除临时草稿及测试图片,并恢复原排序。两种方式的公开实发和实发后回执待验收。 +- 界面预览在离线 Chrome 的 1440 和 390 像素宽度通过验证,覆盖两种发布方式的保存和切换、发布上限、绑定图顺序及其他平台计数。0.1.26 安装到手机后核对了「评论发布位置」的默认选项、两个原生选项和视频评论发布上限。安装和配置页验证前后的用户配置已核对,原任务检查点保留。 +- 离线构建和 72 项 JVM 单测通过,Lint 为 0 个错误、3 个警告。调试 APK 通过 v2 签名校验,安装包与本地 APK 的 SHA-256 一致。已离线回放真机空白、单图和双图草稿树,并分别解析出 0、1、2 张附件。 ## 2026-11-27 · 拾见 0.1.25 哔哩哔哩双图复查与回执校验