实现回复确认后的点赞和收藏

This commit is contained in:
2026-11-28 22:24:06 +08:00
parent d083c9488b
commit 48dcc6f20e
18 changed files with 641 additions and 29 deletions
+2 -2
View File
@@ -13,8 +13,8 @@ android {
applicationId = "com.jieliu.app"
minSdk = 26
targetSdk = 35
versionCode = 47
versionName = "0.1.46"
versionCode = 48
versionName = "0.1.47"
}
compileOptions {
@@ -45,6 +45,7 @@ import com.jieliu.app.task.BilibiliCommentScope
import com.jieliu.app.task.ContentType
import com.jieliu.app.task.KeywordRule
import com.jieliu.app.task.Outcome
import com.jieliu.app.task.PendingEngagement
import com.jieliu.app.task.ReplyMode
import com.jieliu.app.task.ReplyPhrase
import com.jieliu.app.task.TaskCheckpoint
@@ -450,6 +451,8 @@ class MainActivity : Activity() {
}
val limit = field(plan.limit.toString(), "1–100", number = true)
val repliesPerVideo = field(plan.repliesPerVideo.toString(), "1–${TaskPlan.MAX_REPLIES_PER_VIDEO}", number = true)
val likeOnSuccess = choices(listOf("关闭", "开启"), if (plan.likeOnSuccess) 1 else 0)
val favoriteOnSuccess = choices(listOf("关闭", "开启"), if (plan.favoriteOnSuccess) 1 else 0)
val watchMin = field(plan.watchSeconds.first.toString(), "最短", number = true)
val watchMax = field(plan.watchSeconds.last.toString(), "最长", number = true)
val actionMin = field(plan.actionMillis.first.toString(), "最短", number = true)
@@ -467,6 +470,8 @@ class MainActivity : Activity() {
}.also { comments.addView(it) }
val repliesCaption = comments.addField("", repliesPerVideo)
val repliesHint = label("", 14).also { comments.addView(it) }
comments.addField("确认回复后点赞", likeOnSuccess)
comments.addField("确认回复后收藏", favoriteOnSuccess)
val library = card("内容库")
val libraryHint = label("", 14).also { library.addView(it) }
library.addView(libraries.editor)
@@ -523,6 +528,8 @@ class MainActivity : Activity() {
platformId = spec.id,
limit = limit.number("单次任务${spec.contentUnit}上限"),
repliesPerVideo = repliesPerVideo.number(repliesCaption.text.toString()),
likeOnSuccess = likeOnSuccess.selectedItemPosition == 1,
favoriteOnSuccess = favoriteOnSuccess.selectedItemPosition == 1,
watchSeconds = watchMin.number("观看下限")..watchMax.number("观看上限"),
actionMillis = actionMin.number("间隔下限")..actionMax.number("间隔上限"),
replyMode = replyMode,
@@ -809,7 +816,17 @@ class MainActivity : Activity() {
check(!TaskControl.inProgress) { "请先暂停任务。" }
val checkpoint = checkNotNull(store.readCheckpoint())
check(checkpoint.id == before.id && checkpoint.pending == expected) { "待核对的评论已变化,请重新打开。" }
store.saveCheckpoint(checkpoint.recordReply(outcome))
val updated = checkpoint.recordReply(outcome)
// 人工确认同样算「已确认」,写入回执后补做点赞收藏;未写回执(配额未满)的等视频收尾时由任务流程处理。
val plan = checkpoint.plan
val confirmed = outcome == Outcome.SENT || outcome == Outcome.USER_CONFIRMED
val engagement = if (confirmed && (plan.likeOnSuccess || plan.favoriteOnSuccess) &&
updated.receipts.size > checkpoint.receipts.size
) {
PendingEngagement(expected.videoKey, expected.title, before.contentType?.name.orEmpty(),
plan.likeOnSuccess, plan.favoriteOnSuccess)
} else null
store.saveCheckpoint(updated.copy(pendingEngagement = engagement))
if (expected.photos.isNotEmpty()) Thread { photos.cleanupStaged() }.start()
val message = when {
outcome == Outcome.USER_CONFIRMED -> "用户确认上一条评论已发送"
@@ -1046,7 +1063,11 @@ class MainActivity : Activity() {
@android.annotation.TargetApi(30)
private fun configureEdgeToEdge() = window.setDecorFitsSystemWindows(false)
private fun guardedPage(create: () -> View) = try { create() } catch (_: Exception) { errorPage("无法读取本机数据") }
private fun guardedPage(create: () -> View) = try {
create()
} catch (error: Exception) {
errorPage("无法读取本机数据:${error.message ?: error.javaClass.simpleName}")
}
private fun errorPage(message: String) = column().apply { addView(card(message)) }
@@ -7,6 +7,7 @@ import com.jieliu.app.task.ContentType
import com.jieliu.app.task.KeywordRule
import com.jieliu.app.task.Outcome
import com.jieliu.app.task.PendingComment
import com.jieliu.app.task.PendingEngagement
import com.jieliu.app.task.Receipt
import com.jieliu.app.task.ReplyMode
import com.jieliu.app.task.ReplyPhrase
@@ -87,7 +88,12 @@ class LocalStore(context: Context) : TaskRunStorage {
val activeVideo = if (json.isNull("activeVideo")) null else json.getJSONObject("activeVideo").let {
VideoProgress(it.getString("key"), it.readReplyReceipts())
}
TaskCheckpoint(json.getString("id"), plan, receipts, pending, json.getString("message"), activeVideo)
val pendingEngagement = json.optJSONObject("pendingEngagement")?.let {
PendingEngagement(it.getString("key"), it.getString("title"), it.getString("contentTypeName"),
it.optBoolean("like", false), it.optBoolean("favorite", false))
}
TaskCheckpoint(json.getString("id"), plan, receipts, pending, json.getString("message"), activeVideo,
pendingEngagement)
}
checkpointLoaded = true
return cachedCheckpoint
@@ -110,6 +116,10 @@ class LocalStore(context: Context) : TaskRunStorage {
checkpoint.activeVideo?.let {
body.put("activeVideo", JSONObject().put("key", it.videoKey).put("replies", it.replies.toReplyArray()))
}
checkpoint.pendingEngagement?.let {
body.put("pendingEngagement", JSONObject().put("key", it.videoKey).put("title", it.title)
.put("contentTypeName", it.contentTypeName).put("like", it.like).put("favorite", it.favorite))
}
task.replaceWith(body)
cachedCheckpoint = checkpoint
checkpointLoaded = true
@@ -193,6 +203,7 @@ class LocalStore(context: Context) : TaskRunStorage {
.put("xiaohongshuNoteKey", xiaohongshuNoteKey)
.put("bilibiliCommentScope", bilibiliCommentScope.name)
.put("repliesPerVideo", repliesPerVideo)
.put("likeOnSuccess", likeOnSuccess).put("favoriteOnSuccess", favoriteOnSuccess)
.put("limit", limit).put("watchMin", watchSeconds.first).put("watchMax", watchSeconds.last)
.put("actionMin", actionMillis.first).put("actionMax", actionMillis.last)
.put("mode", replyMode.name).put("model", model).put("instructions", instructions)
@@ -227,6 +238,8 @@ class LocalStore(context: Context) : TaskRunStorage {
},
selectedTypeId = optionalString("selectedTypeId"),
repliesPerVideo = if (isNull("repliesPerVideo")) 1 else getInt("repliesPerVideo"),
likeOnSuccess = optBoolean("likeOnSuccess", false),
favoriteOnSuccess = optBoolean("favoriteOnSuccess", false),
xiaohongshuNoteKind = XiaohongshuNoteKind.entries.firstOrNull { it.name == optionalString("xiaohongshuNoteKind") }
?: XiaohongshuNoteKind.ANY,
xiaohongshuNoteKey = optionalString("xiaohongshuNoteKey"),
@@ -99,10 +99,46 @@ internal class BilibiliAdapter(
BilibiliCommentScope.VIDEO_COMMENT -> replies.confirmTopLevel(video, text, photos, armedAt)
}
/** 回复确认后点击视频页操作栏的点赞和/或收藏。B 站暴露稳定资源 ID,可直接按 ID 查找。 */
override fun engage(video: VideoContext, like: Boolean, favorite: Boolean): EngagementResult {
if (!like && !favorite) return EngagementResult()
fun only(enabled: Boolean, action: EngagementAction) = if (enabled) action else EngagementAction.SKIPPED
val failed = EngagementResult(only(like, EngagementAction.FAILED), only(favorite, EngagementAction.FAILED))
return try {
ui.inspect { page ->
diagnostic("B站互动诊断 节点=${page.nodes.size} complete=${page.complete} " +
"frame_like=${page.visibleByViewId(LIKE_VIEW_ID).size} frame_fav=${page.visibleByViewId(FAVORITE_VIEW_ID).size} " +
"含赞=${page.nodes.count { "赞" in it.description || "赞" in it.text }}")
}
EngagementResult(
only(like, engageActionButton(ui, { page -> page.engageButton(LIKE_VIEW_ID, likeLabel) },
likePendingPrefix, engagementDonePrefix, "点赞", diagnostic)),
only(favorite, engageActionButton(ui, { page -> page.engageButton(FAVORITE_VIEW_ID, favoriteLabel) },
favoritePendingPrefix, engagementDonePrefix, "收藏", diagnostic)),
)
} catch (_: Exception) {
failed
}
}
private fun UiPage.engageButton(viewId: String, label: Regex): UiNode? =
visibleByViewId(viewId).filter { it.enabled && label.matches(it.description) }.maxByOrNull { it.bounds.height() }
override fun closeComments() {
if (replies.hasUnsettledEditor()) throw PlatformException("哔哩哔哩评论编辑框仍打开,请核对草稿后继续")
replies.reset()
comments.close()
openVideo = null
}
private companion object {
// 视频页操作栏的点赞与收藏,描述形如「点赞,626个点赞」,已操作时加「已」前缀。
const val LIKE_VIEW_ID = "frame_like"
const val FAVORITE_VIEW_ID = "frame_fav"
val likeLabel = Regex("^已?点赞[,,]")
val favoriteLabel = Regex("^已?收藏[,,]")
const val likePendingPrefix = "点赞"
const val favoritePendingPrefix = "收藏"
const val engagementDonePrefix = "已"
}
}
@@ -312,16 +312,17 @@ internal class BilibiliComments(
}
val opened = readOriginal(target) { _, row -> row.threadEntry?.let { ui.click(it) } == true } == true
if (!opened) return false
var movedToRoot = false
thread = ui.await(5_000) {
var movedToRoot = 0
thread = ui.await(9_000) {
ui.inspect { page ->
if (page.detailHeader() == null || page.hasEditor()) return@inspect null
val list = page.detailList() ?: return@inspect null
val original = page.threadRows(list, scope.video.key, target)?.original
if (original == null) {
// 原评论常在滚动后才进视图,多滚几次再等。
val backward = AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
if (!movedToRoot && list.supports(backward)) {
movedToRoot = true
if (movedToRoot < 3 && list.supports(backward)) {
movedToRoot++
list.act(backward)
}
return@inspect null
@@ -16,6 +16,7 @@ internal class DouyinAdapter(
private val spec: PlatformSpec,
private val ui: AccessibleUi,
private val photoLibrary: PhotoLibrary,
private val diagnostic: (String) -> Unit = {},
) : PlatformAdapter {
private data class CommentPanel(val video: VideoContext, val windowId: Int)
private data class CommentViewport(val list: UiNode, val bounds: Rect)
@@ -130,8 +131,13 @@ internal class DouyinAdapter(
if (page.commentHeader() != null || page.nativeCommentPanelVisible()) {
throw PlatformException("抖音评论区仍打开,未滑动视频")
}
val current = page.videoContext() ?: page.nativePlayerVideo() ?: return@read null
if (current.key != previous.key) throw PlatformException("抖音已切换到另一条视频,未执行滑动")
val current = page.videoContext() ?: page.nativePlayerVideo()
// 广告商品卡会遮挡作者和标题,读不出内容但播放器仍在时也允许作为滑动起点。
val unidentified = current == null && page.shareButton() != null
if (current == null && !unidentified) return@read null
if (current != null && current.key != previous.key) {
throw PlatformException("抖音已切换到另一条视频,未执行滑动")
}
matchedThisRead = true
if (!matchedPreviousRead) return@read null
val x = page.x(Random.nextDouble(0.44, 0.58).toFloat()).toFloat()
@@ -656,6 +662,82 @@ internal class DouyinAdapter(
}
}
/** 回复确认后点击播放页右侧的点赞和/或收藏,并核对按钮状态前缀已离开「未…」。 */
override fun engage(video: VideoContext, like: Boolean, favorite: Boolean): EngagementResult {
if (!like && !favorite) return EngagementResult()
fun only(enabled: Boolean, action: EngagementAction) = if (enabled) action else EngagementAction.SKIPPED
val failed = EngagementResult(only(like, EngagementAction.FAILED), only(favorite, EngagementAction.FAILED))
return try {
val bound = ui.inspect { page -> page.visiblePlayerVideo()?.key == video.key } == true
diagnostic("互动定位播放页 bound=$bound")
if (bound) EngagementResult(
only(like, engageButton(likeButtonViewId, likeButtonLabel, likePendingPrefix, likeDonePrefix, "点赞")),
only(favorite, engageButton(favoriteButtonViewId, favoriteButtonLabel, favoritePendingPrefix, favoriteDonePrefix, "收藏")),
) else failed
} catch (_: Exception) {
failed
}
}
/** 点击一次操作栏按钮并等待状态前缀翻到 donePrefix。未找到、点击未生效或状态未翻转都算失败。 */
private fun engageButton(
viewId: String,
label: Regex,
pendingPrefix: String,
donePrefix: String,
name: String,
): EngagementAction {
// 评论区刚收起时播放页仍在重排,先按动作间隔等稳定;未翻转则再等一次后重试。
var clicked = false
repeat(2) { attempt ->
ui.pace()
val button = ui.inspect { page ->
// 无障碍树采集在复杂页面上会超时截断,侧边栏按钮可能不在 page.nodes 里,改用资源 ID 直查兜底。
(page.visibleByViewId(viewId).filter { label.matches(it.description) }.maxByOrNull { it.bounds.height() }
?: page.nodes.filter {
it.clickable && it.enabled && label.matches(it.description) &&
it.bounds.centerX() >= page.x(.80f) && it.bounds.centerY() in page.y(.25f)..page.y(.90f)
}.maxByOrNull { it.bounds.height() })
}
if (button == null) {
ui.inspect { page ->
val byLabel = page.nodes.count { label.matches(it.description) }
val byLabelClickable = page.nodes.count { label.matches(it.description) && it.clickable && it.enabled }
val byLabelRegion = page.nodes.count {
label.matches(it.description) && it.bounds.centerX() >= page.x(.80f) &&
it.bounds.centerY() in page.y(.25f)..page.y(.90f)
}
diagnostic("${name}第 ${attempt + 1} 次未找到按钮 · 节点=${page.nodes.size} complete=${page.complete} " +
"页面=${page.bounds} 按标签=$byLabel 可点击=$byLabelClickable 区域=$byLabelRegion")
}
return@repeat
}
diagnostic("${name}第 ${attempt + 1} 次按钮=${button.description}")
if (button.description.startsWith(donePrefix)) return if (clicked) EngagementAction.DONE else EngagementAction.SKIPPED
if (!button.description.startsWith(pendingPrefix)) return EngagementAction.SKIPPED
// 这两个按钮的无障碍 ACTION_CLICK 会被系统接受却不触发业务逻辑,与小红书视频评论按钮一样改用真实触屏。
val x = button.bounds.exactCenterX()
val y = button.bounds.exactCenterY()
val dispatched = ui.touch(x, y, x, y, 85)
diagnostic("${name}第 ${attempt + 1} 次触屏($x,$y)=$dispatched")
if (!dispatched) return@repeat
clicked = true
val flipped = ui.await(2_000) {
ui.inspect { page ->
val current = page.visibleByViewId(viewId).filter { label.matches(it.description) }
.maxByOrNull { it.bounds.height() }
?: page.nodes.filter { label.matches(it.description) }.maxByOrNull { it.bounds.height() }
if (current == null) null else true.takeIf {
!current.description.startsWith(pendingPrefix) && current.description.startsWith(donePrefix)
}
}
}
diagnostic("${name}第 ${attempt + 1} 次核对=$flipped")
if (flipped == true) return EngagementAction.DONE
}
return EngagementAction.FAILED
}
private fun confirmReply(
initial: CommentPanel,
targetKey: String,
@@ -1386,6 +1468,19 @@ internal class DouyinAdapter(
const val RECEIPT_TAG = "ShijianReceipt"
const val MAX_RECEIPT_SCREENS = 13
const val MAX_THREAD_ADJUSTMENTS = 9
// 播放页右侧操作栏按钮描述形如「未点赞,喜欢2053,按钮」,状态前缀随是否已操作变化。
val likeButtonLabel = Regex("^[^,]*,喜欢[^,]*,按钮$")
val favoriteButtonLabel = Regex("^[^,]*,收藏[^,]*,按钮$")
// 与 zvv、e2t 同一套混淆资源 ID;采集截断时靠它们直查按钮。
const val likeButtonViewId = "gr+"
const val favoriteButtonViewId = "d_w"
const val likePendingPrefix = "未点赞"
const val favoritePendingPrefix = "未选中"
const val likeDonePrefix = "已点赞"
const val favoriteDonePrefix = "已选中"
val videoDuration = Regex("[0-9]{2}:[0-5][0-9]")
val expandReply = Regex("展开\\s*[1-9][0-9]*\\s*条回复(?:[,,]按钮)?")
val recentReplyTime = Regex("([1-9][0-9]?)\\s*分钟前")
@@ -6,9 +6,9 @@ import com.jieliu.app.task.TemplatePhoto
internal class KuaishouAdapter(
spec: PlatformSpec,
ui: AccessibleUi,
private val ui: AccessibleUi,
photos: PhotoLibrary,
diagnostic: (String) -> Unit,
private val diagnostic: (String) -> Unit,
) : PlatformAdapter {
private val navigation = KuaishouNavigation(spec, ui)
private val comments = KuaishouComments(ui, navigation::matchesContent, navigation::openCommentPanel)
@@ -71,10 +71,42 @@ internal class KuaishouAdapter(
return replies.confirm(target, author, pending.text, pending.photos, armedAt)
}
/** 回复确认后点击作品页右侧的点赞和/或收藏。快手暴露稳定资源 ID,可直接按 ID 查找。 */
override fun engage(video: VideoContext, like: Boolean, favorite: Boolean): EngagementResult {
if (!like && !favorite) return EngagementResult()
fun only(enabled: Boolean, action: EngagementAction) = if (enabled) action else EngagementAction.SKIPPED
val failed = EngagementResult(only(like, EngagementAction.FAILED), only(favorite, EngagementAction.FAILED))
return try {
// 评论区收起时 openWork 已清空,这里不再用它校验;按钮定位与状态翻转即是把关。
EngagementResult(
only(like, engageActionButton(ui, { page -> page.engageButton(LIKE_VIEW_ID, likeLabel) },
likePendingPrefix, engagementDonePrefix, "点赞", diagnostic)),
only(favorite, engageActionButton(ui, { page -> page.engageButton(FAVORITE_VIEW_ID, favoriteLabel) },
favoritePendingPrefix, engagementDonePrefix, "收藏", diagnostic)),
)
} catch (_: Exception) {
failed
}
}
private fun UiPage.engageButton(viewId: String, label: Regex): UiNode? =
visibleByViewId(viewId).filter { it.enabled && label.matches(it.description) }.maxByOrNull { it.bounds.height() }
override fun closeComments() {
if (replies.hasUnsettledEditor()) throw PlatformException("请核对快手中打开的回复草稿后继续")
replies.reset()
comments.close()
openWork = null
}
private companion object {
// 作品页右侧的点赞与收藏,描述形如「未点赞,点赞4311」,已操作时前缀变「已」。
const val LIKE_VIEW_ID = "like_button"
const val FAVORITE_VIEW_ID = "collect_button"
val likeLabel = Regex("^未?点赞[,,]")
val favoriteLabel = Regex("^未?收藏[,,]")
const val likePendingPrefix = "未点赞"
const val favoritePendingPrefix = "未收藏"
const val engagementDonePrefix = "已"
}
}
@@ -121,12 +121,13 @@ internal class KuaishouComments(
ui.pace()
val closed = ui.inspect { page ->
if (page.hasKuaishouCommentDraft()) return@inspect false
if (readPanel(page) == null && matchesContent(page, session.video)) return@inspect true
if (readPanel(page) == null) return@inspect true
val panel = panel(page) ?: return@inspect false
ui.click(panel.close)
} == true
// 只需确认评论面板已关;再核对作品会因作者/文案识别脆弱而误判。
if (!closed || ui.await(4_000) {
ui.inspect { page -> true.takeIf { readPanel(page) == null && matchesContent(page, session.video) } }
ui.inspect { page -> true.takeIf { readPanel(page) == null } }
} != true
) throw PlatformException("关闭快手评论区后未能核对同一作品")
active = null
@@ -87,6 +87,16 @@ internal class KuaishouNavigation(private val spec: PlatformSpec, private val ui
ui.inspect { page ->
if (page.hasKuaishouCommentDraft()) throw PlatformException("请先处理快手中打开的评论草稿")
if (page.searchEditor() != null) return@inspect "ready"
val entry = page.nodes.singleOrNull {
it.resourceId == "search_content" && it.text.isNotBlank()
}
if (entry != null) {
// 搜索结果页的搜索框不可点击,只能触屏点开。
ui.pace()
val x = entry.bounds.exactCenterX()
val y = entry.bounds.exactCenterY()
return@inspect "moved".takeIf { ui.touch(x, y, x, y, 85) }
}
val control = page.nodes.singleOrNull { it.resourceId == "tabs_panel_close" &&
it.description == "关闭评论区" && it.kuaishouAction() }
?: page.player()?.back
@@ -21,6 +21,81 @@ data class CommentTarget(val key: String, val text: String, val author: String)
enum class CommentPublishResult { CONFIRMED, UNCERTAIN }
/** 单个互动动作的结果。 */
enum class EngagementAction { DONE, SKIPPED, FAILED, UNSUPPORTED }
/** 回复确认后点赞、收藏两项动作各自的完成情况。 */
data class EngagementResult(
val like: EngagementAction = EngagementAction.SKIPPED,
val favorite: EngagementAction = EngagementAction.SKIPPED,
)
/**
* 点击一次操作栏按钮并等待状态前缀翻到 donePrefix。
* 找不到按钮、触屏未派发、状态未翻转都算失败;已是目标状态返回 SKIPPED,不重复点击以免误取消。
* 按钮由 [find] 在每次重试时重新定位,返回的节点只取其描述与坐标,不跨快照持有节点引用。
*/
internal fun engageActionButton(
ui: AccessibleUi,
find: (UiPage) -> UiNode?,
pendingPrefix: String,
donePrefix: String,
name: String,
diagnostic: (String) -> Unit,
): EngagementAction {
var clicked = false
repeat(2) {
ui.pace()
val button = ui.inspect(find)
if (button == null) {
diagnostic("${name}未找到按钮")
return@repeat
}
if (button.description.startsWith(donePrefix)) {
diagnostic("${name}已是目标状态 ${button.description}")
return if (clicked) EngagementAction.DONE else EngagementAction.SKIPPED
}
if (!button.description.startsWith(pendingPrefix)) {
diagnostic("${name}状态无法识别 ${button.description}")
return EngagementAction.SKIPPED
}
// 这类按钮的无障碍 ACTION_CLICK 常被系统接受却不触发业务逻辑,一律用真实触屏。
val x = button.bounds.exactCenterX()
val y = button.bounds.exactCenterY()
val dispatched = ui.touch(x, y, x, y, 85)
diagnostic("${name}触屏($x,$y)=$dispatched")
if (!dispatched) return@repeat
clicked = true
// 小红书等平台的状态翻转有延迟,核对窗口放宽。
val flipped = ui.await(5_000) {
ui.inspect { page ->
val current = find(page)
if (current == null) null else true.takeIf {
!current.description.startsWith(pendingPrefix) && current.description.startsWith(donePrefix)
}
}
}
diagnostic("${name}核对=${flipped == true}")
if (flipped == true) return EngagementAction.DONE
// 部分平台(如小红书)只认无障碍 ACTION_CLICK,触屏打偏时补一次。
val acted = ui.inspect { page -> find(page)?.act(android.view.accessibility.AccessibilityNodeInfo.ACTION_CLICK) }
diagnostic("${name}ACTION_CLICK=$acted")
if (acted == true) {
val flippedByAction = ui.await(5_000) {
ui.inspect { page ->
val current = find(page)
if (current == null) null else true.takeIf {
!current.description.startsWith(pendingPrefix) && current.description.startsWith(donePrefix)
}
}
}
diagnostic("${name}核对2=${flippedByAction == true}")
if (flippedByAction == true) return EngagementAction.DONE
}
}
return EngagementAction.FAILED
}
class PlatformException(message: String, cause: Throwable? = null) : RuntimeException(message, cause)
internal class PlatformInteractionRestrictedException(message: String) : RuntimeException(message)
@@ -46,6 +121,11 @@ interface PlatformAdapter {
fun confirmPendingReply(video: VideoContext, pending: PendingComment): CommentPublishResult = CommentPublishResult.UNCERTAIN
/** Read back from an already bound note. Null means a fresh read-only search is needed. */
fun confirmPendingReplyInPlace(video: VideoContext, pending: PendingComment): CommentPublishResult? = null
/** 回复确认后对当前内容点赞和/或收藏。实现方不得抛出异常,失败由返回值体现。 */
fun engage(video: VideoContext, like: Boolean, favorite: Boolean): EngagementResult = EngagementResult(
like = if (like) EngagementAction.UNSUPPORTED else EngagementAction.SKIPPED,
favorite = if (favorite) EngagementAction.UNSUPPORTED else EngagementAction.SKIPPED,
)
fun closeComments()
}
@@ -89,7 +169,7 @@ object PlatformRegistry {
AccessibleUi(service, spec.packageName, cancelled, pauseBetweenActions, checkPage)
}
return when (spec.id) {
douyin.id -> DouyinAdapter(spec, ui, PhotoLibrary(service))
douyin.id -> DouyinAdapter(spec, ui, PhotoLibrary(service), receiptDiagnostic)
xiaohongshu.id -> XiaohongshuAdapter(spec, ui, PhotoLibrary(service), noteKind, targetNoteKey,
pinnedResumeNoteKey, receiptDiagnostic)
bilibili.id -> BilibiliAdapter(spec, ui, PhotoLibrary(service), bilibiliCommentScope, receiptDiagnostic)
@@ -65,6 +65,7 @@ internal class XiaohongshuAdapter(
private val comments = XiaohongshuComments(ui, ::matchesNote, ::openNoteComments)
private val composer = XiaohongshuReplyComposer(ui, photoLibrary, comments)
private val receipt = XiaohongshuReplyReceipt(ui, photoLibrary, comments, receiptDiagnostic)
private val diagnostic: (String) -> Unit = receiptDiagnostic
override fun launch() = ui.launchTarget(spec.label)
@@ -645,6 +646,33 @@ internal class XiaohongshuAdapter(
if (result == CommentPublishResult.CONFIRMED && photos.isNotEmpty()) photoLibrary.cleanupStaged()
}
/** 回复确认后点击笔记底部工具栏的点赞和/或收藏。状态前缀「已」表示已完成,不重复点击以免误取消。 */
override fun engage(video: VideoContext, like: Boolean, favorite: Boolean): EngagementResult {
if (!like && !favorite) return EngagementResult()
fun only(enabled: Boolean, action: EngagementAction) = if (enabled) action else EngagementAction.SKIPPED
val failed = EngagementResult(only(like, EngagementAction.FAILED), only(favorite, EngagementAction.FAILED))
return try {
val note = activeNote?.takeIf { it.video.key == video.key } ?: return failed
EngagementResult(
only(like, engageActionButton(ui, { page -> page.engagementButton(note, likeLabel) },
likePendingPrefix, engagementDonePrefix, "点赞", diagnostic)),
only(favorite, engageActionButton(ui, { page -> page.engagementButton(note, favoriteLabel) },
favoritePendingPrefix, engagementDonePrefix, "收藏", diagnostic)),
)
} catch (_: Exception) {
failed
}
}
/** 笔记工具栏里的互动按钮。小红书不暴露资源 ID,只能按描述识别。 */
private fun UiPage.engagementButton(note: NoteBinding, label: Regex): UiNode? {
val toolbar = boundNote(note)?.toolbar ?: return null
return nodes.filter {
it.directParent() === toolbar && it.className == "android.widget.Button" && it.isNativeClick() &&
label.matches(it.description)
}.singleOrNull()
}
override fun closeComments() {
val session = commentNote ?: return
if (!session.empty) comments.close()
@@ -686,6 +714,11 @@ internal class XiaohongshuAdapter(
const val COUNTER = "(?:\\s+[0-9]+(?:\\.[0-9]+)?(?:万|亿)?\\+?)?"
val likeLabel = Regex("(?:已)?点赞$COUNTER")
val favoriteLabel = Regex("(?:已)?收藏$COUNTER")
// 工具栏按钮描述形如「点赞 298」,已操作时加「已」前缀。
const val likePendingPrefix = "点赞"
const val favoritePendingPrefix = "收藏"
const val engagementDonePrefix = "已"
val commentLabel = Regex("评论$COUNTER")
val zeroComments = Regex("评论\\s+0")
val whitespace = Regex("\\s+")
@@ -39,6 +39,15 @@ data class PendingComment(
val armedAtEpochMs: Long? = null,
)
/** 人工确认回复后补做的点赞收藏。内容已完成处理,只差互动这一步。 */
data class PendingEngagement(
val videoKey: String,
val title: String,
val contentTypeName: String,
val like: Boolean,
val favorite: Boolean,
)
data class TaskCheckpoint(
val id: String,
val plan: TaskPlan,
@@ -46,8 +55,10 @@ data class TaskCheckpoint(
val pending: PendingComment? = null,
val message: String = "准备启动",
val activeVideo: VideoProgress? = null,
val pendingEngagement: PendingEngagement? = null,
) {
val complete: Boolean get() = receipts.size >= plan.limit && pending == null && activeVideo == null
val complete: Boolean get() = receipts.size >= plan.limit && pending == null && activeVideo == null &&
pendingEngagement == null
val sentCount: Int get() = receipts.sumOf { receipt ->
if (receipt.replies.isEmpty()) {
if (receipt.outcome.isConfirmedReply()) 1 else 0
@@ -62,7 +73,12 @@ data class TaskCheckpoint(
}
val contentType: ContentType? get() {
val types = plan.searchTypes()
return if (complete || types.isEmpty()) null else types[plan.contentTypeIndex(receipts.size)]
// 待补做互动时 complete 为 false,但回执已满,不能再取下一个类型下标。
return if (complete || receipts.size >= plan.limit || types.isEmpty()) {
null
} else {
types[plan.contentTypeIndex(receipts.size)]
}
}
fun canAutomaticallyRecheck(nowEpochMs: Long = System.currentTimeMillis()): Boolean {
@@ -48,6 +48,8 @@ data class TaskPlan(
val contentTypes: List<ContentType>? = null,
val selectedTypeId: String? = null,
val repliesPerVideo: Int = 1,
val likeOnSuccess: Boolean = false,
val favoriteOnSuccess: Boolean = false,
val xiaohongshuNoteKind: XiaohongshuNoteKind = XiaohongshuNoteKind.ANY,
val xiaohongshuNoteKey: String? = null,
val bilibiliCommentScope: BilibiliCommentScope = BilibiliCommentScope.REPLY_TO_ORIGINAL,
@@ -2,6 +2,8 @@ package com.jieliu.app.task
import com.jieliu.app.platform.CommentPublishResult
import com.jieliu.app.platform.CommentTarget
import com.jieliu.app.platform.EngagementAction
import com.jieliu.app.platform.EngagementResult
import com.jieliu.app.platform.PlatformAdapter
import com.jieliu.app.platform.PlatformException
import com.jieliu.app.platform.PlatformInteractionRestrictedException
@@ -42,9 +44,15 @@ internal class TaskRunner(
try {
if (recheckPending) {
val receiptsBefore = checkpoint.receipts.size
val pending = checkNotNull(initial.pending)
if (confirmPending(initial) == CommentPublishResult.CONFIRMED) {
persist(checkpoint.recordReply(Outcome.SENT))
store.appendLog("自动核对回复成功,已确认发送")
engagementFor(checkpoint, receiptsBefore)?.let { (like, favorite) ->
platform.closeComments()
engageContent("已核对的$contentUnit", VideoContext(pending.videoKey, pending.title), like, favorite)
}
} else {
val message = "自动核对未确认,发送结果仍待核对。"
persist(checkpoint.copy(message = message))
@@ -53,6 +61,26 @@ internal class TaskRunner(
return
}
check(checkpoint.pending == null) { "请先核对上一条评论的发送结果。" }
checkpoint.pendingEngagement?.let { engagement ->
if (engagement.like || engagement.favorite) {
status("正在补做${contentUnit}的点赞收藏")
store.appendLog("补做人工确认回复的点赞收藏")
// 人工确认时平台仍停在该内容上,直接原地互动;重新搜索定位在小红书/B 站上并不可靠。
val video = VideoContext(engagement.videoKey, engagement.title)
val onScreen = try {
platform.currentVideo().key == engagement.videoKey
} catch (_: Exception) {
false
}
if (onScreen) {
platform.closeComments()
engageContent("已确认的$contentUnit", video, engagement.like, engagement.favorite)
} else {
store.appendLog("补做互动时已不在原${contentUnit},未执行点赞收藏", warning = true)
}
}
persist(checkpoint.copy(pendingEngagement = null))
}
val mode = if (plan.replyMode == ReplyMode.BROWSE) ReplyMode.BROWSE else ReplyMode.TEMPLATES
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
@@ -76,13 +104,19 @@ internal class TaskRunner(
video = candidate
val number = checkpoint.receipts.size + 1
if (checkpoint.activeVideo == null) watch(candidate, number)
if (checkpoint.activeVideo == null && !watch(candidate, number)) {
// 内容读不出作者和标题(如广告商品卡遮挡),按不可处理内容跳过。
persist(checkpoint.finish(candidate.key, Outcome.NO_REPLY))
store.appendLog("第 $number 条${contentUnit}无法识别内容(如广告商品卡),已跳过")
continue
}
if (mode == ReplyMode.BROWSE) {
persist(checkpoint.finish(candidate.key, Outcome.WATCHED))
continue
}
if (checkpoint.activeVideo == null) persist(checkpoint.startVideo(candidate.key))
val receiptsBefore = checkpoint.receipts.size
val openPanel = store.readPlan().findType(type.id)?.rules?.isNotEmpty() == true
if (openPanel) {
status("正在打开评论区")
@@ -124,7 +158,9 @@ internal class TaskRunner(
else "评论扫描结束,已确认发送 ${progress.sentCount}/${plan.repliesPerVideo} 条"
store.appendLog("第 $number 条$contentUnit$summary")
}
if (openPanel && !checkpoint.complete) platform.closeComments()
val engage = engagementFor(checkpoint, receiptsBefore)
if (openPanel && (!checkpoint.complete || engage != null)) platform.closeComments()
engage?.let { (like, favorite) -> engageContent("第 $number 条$contentUnit", candidate, like, favorite) }
}
store.appendLog("任务完成 · 处理 ${checkpoint.receipts.size} 条 · 确认发送 ${checkpoint.sentCount} 条")
} catch (error: Exception) {
@@ -194,8 +230,7 @@ internal class TaskRunner(
throw error
}
private fun locateVideo(first: VideoContext, checkpoint: TaskCheckpoint): VideoContext {
val resumeKey = checkpoint.activeVideo?.videoKey
private fun locateVideo(first: VideoContext, checkpoint: TaskCheckpoint, resumeKey: String? = checkpoint.activeVideo?.videoKey): VideoContext {
val tried = mutableSetOf<String>()
var candidate = first
val searchLimit = if (resumeKey == null) plan.limit else maxOf(plan.limit, MIN_RESUME_SEARCH)
@@ -210,14 +245,22 @@ internal class TaskRunner(
return candidate
}
private fun watch(video: VideoContext, number: Int) {
/** 观看并核对仍是同一条内容。返回 false 表示内容读不出作者和标题(如广告商品卡遮挡),应跳过。 */
private fun watch(video: VideoContext, number: Int): Boolean {
val duration = randomIn(plan.watchSeconds.first, plan.watchSeconds.last)
val action = if (contentUnit == "视频") "观看" else "浏览"
val item = if (contentUnit == "视频") "第 $number 条" else "第 $number 条$contentUnit"
status("正在$action$item · $duration 秒")
store.appendLog("$action$item · $duration 秒")
pauseFor(duration * 1000L, cancelled)
check(platform.currentVideo().key == video.key) { "${action}期间${contentUnit}已切换,请恢复任务。" }
val current = try {
platform.currentVideo()
} catch (_: Exception) {
null
}
if (current == null) return false
check(current.key == video.key) { "${action}期间${contentUnit}已切换,请恢复任务。" }
return true
}
private fun findVisibleReply(type: ContentType, title: String, checkpoint: TaskCheckpoint): MatchedReply? {
@@ -253,6 +296,42 @@ internal class TaskRunner(
else platform.publishPhotoComment(text, photos, beforeClick)
}
/** 判定本次是否要对内容点赞和/或收藏:该内容已写入回执且回执属于已确认的回复。 */
private fun engagementFor(checkpoint: TaskCheckpoint, receiptsBefore: Int): Pair<Boolean, Boolean>? {
if (!plan.likeOnSuccess && !plan.favoriteOnSuccess) return null
val receipt = checkpoint.receipts.getOrNull(receiptsBefore) ?: return null
val confirmed = receipt.outcome == Outcome.SENT || receipt.outcome == Outcome.USER_CONFIRMED
return if (confirmed) plan.likeOnSuccess to plan.favoriteOnSuccess else null
}
/** 回复确认后对内容点赞和/或收藏。失败只记录日志,不中断任务。 */
private fun engageContent(prefix: String, video: VideoContext, like: Boolean, favorite: Boolean) {
val result = try {
platform.engage(video, like, favorite)
} catch (_: Exception) {
EngagementResult(
like = if (like) EngagementAction.FAILED else EngagementAction.SKIPPED,
favorite = if (favorite) EngagementAction.FAILED else EngagementAction.SKIPPED,
)
}
val parts = mutableListOf<String>()
if (like) parts += when (result.like) {
EngagementAction.DONE -> "已点赞"
EngagementAction.FAILED -> "点赞失败"
EngagementAction.UNSUPPORTED -> "当前平台暂不支持点赞"
EngagementAction.SKIPPED -> "点赞已是当前状态"
}
if (favorite) parts += when (result.favorite) {
EngagementAction.DONE -> "已收藏"
EngagementAction.FAILED -> "收藏失败"
EngagementAction.UNSUPPORTED -> "当前平台暂不支持收藏"
EngagementAction.SKIPPED -> "收藏已是当前状态"
}
if (parts.isEmpty()) return
val failed = result.like == EngagementAction.FAILED || result.favorite == EngagementAction.FAILED
store.appendLog("$prefix${parts.joinToString("、")}", warning = failed)
}
private fun TaskPlan.findType(id: String): ContentType? = contentTypes?.firstOrNull { it.id == id }
private fun hasSameBilibiliScope(latest: TaskPlan): Boolean = !bilibili ||
@@ -2,6 +2,8 @@ package com.jieliu.app.task
import com.jieliu.app.platform.CommentPublishResult
import com.jieliu.app.platform.CommentTarget
import com.jieliu.app.platform.EngagementAction
import com.jieliu.app.platform.EngagementResult
import com.jieliu.app.platform.PlatformAdapter
import com.jieliu.app.platform.PlatformException
import com.jieliu.app.platform.PlatformInteractionRestrictedException
@@ -462,6 +464,152 @@ class TaskRunnerTest {
assertTrue(store.checkpoint.complete)
}
@Test fun engageRunsAfterAConfirmedReplyWhenTogglesAreOn() {
val plan = plan(firstType).copy(likeOnSuccess = true, favoriteOnSuccess = true)
val store = RecordingStore(TaskCheckpoint("engage", plan))
val platform = FakePlatform(store, listOf(listOf(target("original", "API 充值"))))
execute(store, platform)
assertEquals(listOf("video-0"), platform.engagements.map { it.first })
assertEquals(listOf(true to true), platform.engagements.map { it.second to it.third })
assertEquals(Outcome.SENT, store.checkpoint.receipts.single().outcome)
assertTrue(store.logs.any { "已点赞" in it && "已收藏" in it })
}
@Test fun engageIsSkippedWhenBothTogglesAreOff() {
val store = RecordingStore(TaskCheckpoint("no-engage", plan(firstType)))
val platform = FakePlatform(store, listOf(listOf(target("original", "API 充值"))))
execute(store, platform)
assertTrue(platform.engagements.isEmpty())
assertTrue(store.logs.none { "点赞" in it || "收藏" in it })
}
@Test fun engageIsSkippedWithoutAConfirmedReply() {
val plan = plan(firstType).copy(likeOnSuccess = true, favoriteOnSuccess = true)
val store = RecordingStore(TaskCheckpoint("no-reply-engage", plan))
val platform = FakePlatform(store, listOf(listOf(target("unrelated", "键盘"))))
execute(store, platform)
assertTrue(platform.engagements.isEmpty())
assertEquals(Outcome.NO_REPLY, store.checkpoint.receipts.single().outcome)
}
@Test fun engagePassesOnlyTheEnabledActions() {
val plan = plan(firstType).copy(likeOnSuccess = true)
val store = RecordingStore(TaskCheckpoint("like-only", plan))
val platform = FakePlatform(store, listOf(listOf(target("original", "API 充值"))))
execute(store, platform)
assertEquals(listOf(true to false), platform.engagements.map { it.second to it.third })
assertTrue(store.logs.any { "已点赞" in it })
assertTrue(store.logs.none { "收藏" in it })
}
@Test fun engageFailureIsLoggedWithoutInterruptingTheTask() {
val plan = plan(firstType).copy(limit = 2, likeOnSuccess = true, favoriteOnSuccess = true)
val store = RecordingStore(TaskCheckpoint("engage-fail", plan))
val platform = FakePlatform(store).apply {
engageThrows = true
screensForVideo = { video -> listOf(listOf(target("t-${video.key}", "API 充值"))) }
}
execute(store, platform)
assertEquals(2, platform.engagements.size)
assertEquals(2, store.checkpoint.receipts.size)
assertTrue(store.checkpoint.complete)
assertEquals(2, store.logs.count { "点赞失败" in it })
}
@Test fun unsupportedEngagementIsLoggedAndTheTaskStillCompletes() {
val plan = plan(firstType).copy(likeOnSuccess = true, favoriteOnSuccess = true)
val store = RecordingStore(TaskCheckpoint("engage-unsupported", plan))
val platform = FakePlatform(store, listOf(listOf(target("original", "API 充值")))).apply {
engageOutcome = EngagementResult(EngagementAction.UNSUPPORTED, EngagementAction.UNSUPPORTED)
}
execute(store, platform)
assertTrue(store.checkpoint.complete)
assertTrue(store.logs.any { "当前平台暂不支持点赞" in it && "当前平台暂不支持收藏" in it })
}
@Test fun commentsAreClosedBeforeEngagingEvenOnTheLastVideo() {
val plan = plan(firstType).copy(likeOnSuccess = true, favoriteOnSuccess = true)
val store = RecordingStore(TaskCheckpoint("engage-last", plan))
val platform = FakePlatform(store, listOf(listOf(target("original", "API 充值"))))
execute(store, platform)
assertTrue(store.checkpoint.complete)
assertEquals(1, platform.closesComments)
assertEquals(1, platform.engagements.size)
}
@Test fun engageIsNotRunInBrowseMode() {
val plan = plan(firstType).copy(replyMode = ReplyMode.BROWSE, likeOnSuccess = true, favoriteOnSuccess = true)
val store = RecordingStore(TaskCheckpoint("browse-engage", plan))
val platform = FakePlatform(store)
execute(store, platform)
assertEquals(listOf(Outcome.WATCHED), store.checkpoint.receipts.map { it.outcome })
assertTrue(platform.engagements.isEmpty())
}
@Test fun unidentifiableContentIsSkippedWithoutStoppingTheTask() {
val plan = plan(firstType).copy(limit = 3)
val store = RecordingStore(TaskCheckpoint("skip-ad", plan))
val platform = FakePlatform(store).apply {
screensForVideo = { video -> listOf(listOf(target("t-${video.key}", "API 充值"))) }
unidentifiableVideos.add("video-1")
}
execute(store, platform)
assertEquals(3, store.checkpoint.receipts.size)
assertEquals(listOf(Outcome.SENT, Outcome.NO_REPLY, Outcome.SENT), store.checkpoint.receipts.map { it.outcome })
assertTrue(store.checkpoint.complete)
assertTrue(store.logs.any { "无法识别内容" in it })
}
@Test fun pendingEngagementIsRunInPlaceOnTheNextTaskStart() {
val plan = plan(firstType).copy(likeOnSuccess = true, favoriteOnSuccess = true)
val store = RecordingStore(TaskCheckpoint("pending-engage", plan).copy(
receipts = listOf(Receipt("video-0", Outcome.USER_CONFIRMED)),
pendingEngagement = PendingEngagement("video-0", "样片", "大模型充值", like = true, favorite = true),
))
val platform = FakePlatform(store).apply { seedVideo(VideoContext("video-0", "样片")) }
execute(store, platform)
assertEquals(listOf("video-0"), platform.engagements.map { it.first })
assertEquals(listOf(true to true), platform.engagements.map { it.second to it.third })
assertEquals(1, platform.closesComments)
assertNull(store.checkpoint.pendingEngagement)
assertTrue(store.checkpoint.complete)
}
@Test fun pendingEngagementIsSkippedWhenTheVideoIsNoLongerOnScreen() {
val plan = plan(firstType).copy(likeOnSuccess = true, favoriteOnSuccess = true)
val store = RecordingStore(TaskCheckpoint("engage-gone", plan).copy(
receipts = listOf(Receipt("video-0", Outcome.USER_CONFIRMED)),
pendingEngagement = PendingEngagement("video-0", "样片", "大模型充值", like = true, favorite = true),
))
val platform = FakePlatform(store).apply { seedVideo(VideoContext("video-9", "别的")) }
execute(store, platform)
assertTrue(platform.engagements.isEmpty())
assertTrue(store.logs.any { "已不在原视频" in it })
assertNull(store.checkpoint.pendingEngagement)
}
private fun execute(store: RecordingStore, platform: FakePlatform, recheckPending: Boolean = false) {
val initial = store.checkpoint
TaskRunner(store, initial.plan, platform, { false }) {}.run(initial, recheckPending = recheckPending)
@@ -504,6 +652,11 @@ class TaskRunnerTest {
val preparations = mutableListOf<String>()
val preparedTexts = mutableListOf<String>()
val rechecks = mutableListOf<Pair<String, PendingComment>>()
val engagements = mutableListOf<Triple<String, Boolean, Boolean>>()
var engageOutcome = EngagementResult(EngagementAction.DONE, EngagementAction.DONE)
var engageThrows = false
var closesComments = 0
val unidentifiableVideos = mutableSetOf<String>()
val unavailable = mutableSetOf<String>()
var knownBaseline = false
var recheckResult = CommentPublishResult.UNCERTAIN
@@ -538,7 +691,17 @@ class TaskRunnerTest {
return showVideo("样片-$keyword")
}
override fun currentVideo(): VideoContext = video
override fun currentVideo(): VideoContext {
if (video.key in unidentifiableVideos) {
throw PlatformException("抖音播放页未同时暴露分享控件、作者和标题,无法确认当前视频")
}
return video
}
/** 预置当前屏幕上的内容,供补做互动这类不重新搜索的路径使用。 */
fun seedVideo(context: VideoContext) {
video = context
}
override fun nextVideo(previous: VideoContext): VideoContext = showVideo("后续样片")
@@ -594,7 +757,15 @@ class TaskRunnerTest {
return result
}
override fun closeComments() = Unit
override fun engage(video: VideoContext, like: Boolean, favorite: Boolean): EngagementResult {
engagements.add(Triple(video.key, like, favorite))
if (engageThrows) throw PlatformException("点赞收藏不可用")
return engageOutcome
}
override fun closeComments() {
closesComments++
}
private fun showVideo(title: String): VideoContext {
video = VideoContext("video-${nextKey++}", title)