Release Shijian 0.1.20 with Xiaohongshu browsing

This commit is contained in:
2026-11-26 14:37:14 +08:00
parent fed659dab9
commit 110665d602
11 changed files with 586 additions and 71 deletions
+2 -2
View File
@@ -13,8 +13,8 @@ android {
applicationId = "com.jieliu.app"
minSdk = 26
targetSdk = 35
versionCode = 20
versionName = "0.1.19"
versionCode = 21
versionName = "0.1.20"
}
compileOptions {
@@ -9,6 +9,7 @@ import android.os.Looper
import android.view.accessibility.AccessibilityEvent
import com.jieliu.app.data.LocalStore
import com.jieliu.app.platform.PlatformRegistry
import com.jieliu.app.task.ReplyMode
import com.jieliu.app.task.TaskCheckpoint
import com.jieliu.app.task.TaskRunner
import com.jieliu.app.task.pauseFor
@@ -97,6 +98,9 @@ internal object TaskControl {
val spec = checkNotNull(PlatformRegistry.platforms.firstOrNull { it.id == plan.platformId && it.implemented }) {
"当前平台适配尚未实现。"
}
require(spec.supportsReplies || (plan.replyMode == ReplyMode.BROWSE && !rechecking)) {
"${spec.label}当前仅支持浏览,请将处理方式设为「仅浏览」。"
}
check(service.packageManager.getLaunchIntentForPackage(spec.packageName) != null) { "请先安装${spec.label}。" }
val initial = (if (resume) saved!! else TaskCheckpoint(UUID.randomUUID().toString(), plan))
.copy(plan = plan, message = if (rechecking) "正在准备自动核对回复" else "任务准备运行")
@@ -35,6 +35,7 @@ import android.widget.Toast
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.ContentType
import com.jieliu.app.task.KeywordRule
import com.jieliu.app.task.Outcome
@@ -255,8 +256,10 @@ class MainActivity : Activity() {
if (content.childCount == 0) replace(errorPage("无法读取任务检查点"))
return
}
val view = TaskView(checkpoint, TaskControl.isConnected, TaskControl.status, needsNotificationPermission(),
checkpoint?.canAutomaticallyRecheck() == true)
val canAutomaticallyRecheck = checkpoint?.canAutomaticallyRecheck() == true && PlatformRegistry.platforms.any {
it.id == checkpoint.plan.platformId && it.supportsReplies
}
val view = TaskView(checkpoint, TaskControl.isConnected, TaskControl.status, needsNotificationPermission(), canAutomaticallyRecheck)
if (view == taskView) return
taskView = view
replace(guardedPage { taskPage(view) })
@@ -267,7 +270,9 @@ class MainActivity : Activity() {
val checkpoint = view.checkpoint
val active = view.step != null
val plan = checkpoint?.plan ?: store.readPlan()
val platform = PlatformRegistry.platforms.firstOrNull { it.id == plan.platformId }?.label ?: plan.platformId
val platformSpec = PlatformRegistry.platforms.firstOrNull { it.id == plan.platformId }
val platform = platformSpec?.label ?: plan.platformId
val contentUnit = platformSpec?.contentUnit ?: "视频"
val searchTypes = plan.searchTypes()
val completed = checkpoint?.receipts?.size ?: 0
val title = when {
@@ -281,17 +286,17 @@ class MainActivity : Activity() {
addView(card(title).apply {
val modeLabel = 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} 个视频", 15))
addView(label(view.step ?: checkpoint?.message ?: "内容类型 ${searchTypes.size} 个 · 单次 ${plan.limit} 个$contentUnit", 15))
val limit = checkpoint?.plan?.limit ?: plan.limit
addView(ProgressBar(this@MainActivity, null, android.R.attr.progressBarStyleHorizontal).apply {
max = limit
progress = completed
progressTintList = ColorStateList.valueOf(GREEN)
contentDescription = "已处理 $completed 个视频,共 $limit 个"
contentDescription = "已处理 $completed 个$contentUnit,共 $limit 个"
}, LinearLayout.LayoutParams(-1, dp(18)))
addView(label("已处理视频 $completed / $limit · 已确认回复 ${checkpoint?.sentCount ?: 0} 条", 14))
addView(label("已处理$contentUnit $completed / $limit · 已确认回复 ${checkpoint?.sentCount ?: 0} 条", 14))
if (plan.replyMode != ReplyMode.BROWSE) checkpoint?.activeVideo?.let { video ->
addView(label("当前视频已确认回复 ${video.sentCount} / ${plan.repliesPerVideo}", 14))
addView(label("当前${contentUnit}已确认回复 ${video.sentCount} / ${plan.repliesPerVideo}", 14))
}
val searchType = checkpoint?.keyword ?: searchTypes.firstOrNull()?.name
if (searchType != null && checkpoint?.complete != true) addView(label("内容类型 · $searchType", 14))
@@ -336,8 +341,15 @@ class MainActivity : Activity() {
private fun configPage(): View {
val plan = store.readPlan()
val specs = PlatformRegistry.platforms
val platform = choices(specs.map { if (it.implemented) it.label else "${it.label}(待适配)" },
specs.indexOfFirst { it.id == plan.platformId }.coerceAtLeast(0))
val platformLabels = specs.map {
when {
!it.implemented -> "${it.label}(待适配)"
!it.supportsReplies -> "${it.label}(仅浏览)"
else -> it.label
}
}
val selectedPlatform = specs.indexOfFirst { it.id == plan.platformId }.coerceAtLeast(0)
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 libraries = ContentFields(plan, restoredTemplates).also {
@@ -350,36 +362,59 @@ class MainActivity : Activity() {
val watchMax = field(plan.watchSeconds.last.toString(), "最长", number = true)
val actionMin = field(plan.actionMillis.first.toString(), "最短", number = true)
val actionMax = field(plan.actionMillis.last.toString(), "最长", number = true)
val scope = card("任务范围").apply {
addField("平台", platform)
addField("搜索范围", libraries.scope)
}
val limitCaption = scope.addField("", limit)
val comments = card("评论设置").apply { addField("处理方式", mode) }
val repliesCaption = comments.addField("", repliesPerVideo)
val repliesHint = label("", 14).also { comments.addView(it) }
val library = card("内容库")
val libraryHint = label("", 14).also { library.addView(it) }
library.addView(libraries.editor)
fun updatePlatformCopy(spec: PlatformSpec) {
val unit = spec.contentUnit
limitCaption.text = "单次任务${unit}上限"
repliesCaption.text = "每条${unit}回复上限"
val browseOnly = spec.implemented && !spec.supportsReplies
repliesHint.text = if (browseOnly) "${spec.label}当前仅支持浏览。"
else "达到回复上限或找不到更多匹配评论时,进入下一个$unit。"
libraryHint.text = if (browseOnly) "按内容类型搜索$unit。"
else "按内容类型搜索$unit,按关键词匹配评论。每个关键词可配置多条话术。"
}
updatePlatformCopy(specs[selectedPlatform])
platform.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
updatePlatformCopy(specs[position])
}
override fun onNothingSelected(parent: AdapterView<*>) = Unit
}
return column().apply {
addView(card("任务范围").apply {
addField("平台", platform)
addField("搜索范围", libraries.scope)
addField("单次任务视频上限", limit)
})
addView(scope)
addView(card("动作节奏").apply {
addRange("观看时长(秒)", watchMin, watchMax)
addRange("动作间隔(毫秒)", actionMin, actionMax)
})
addView(card("评论设置").apply {
addField("处理方式", mode)
addField("每条视频回复上限", repliesPerVideo)
addView(label("达到回复上限或找不到更多匹配评论时,进入下一个视频。", 14))
})
addView(card("内容库").apply {
addView(label("按内容类型搜索视频,按关键词匹配评论。每个关键词可配置多条话术。", 14))
addView(libraries.editor)
})
addView(comments)
addView(library)
addView(action("保存配置", primary = true) {
check(photoImport == null) { "请等待图片导入完成。" }
val spec = specs[platform.selectedItemPosition]
require(spec.implemented) { "${spec.label}还未适配,请选择抖音。" }
require(spec.implemented) { "${spec.label}还未适配,请选择已接入的平台。" }
val replyMode = modes[mode.selectedItemPosition]
require(replyMode == ReplyMode.BROWSE || spec.supportsReplies) {
"${spec.label}当前仅支持浏览,请将处理方式设为「仅浏览」。"
}
val updated = plan.copy(
platformId = spec.id,
limit = limit.number("单次任务视频上限"),
repliesPerVideo = repliesPerVideo.number("每条视频回复上限"),
limit = limit.number("单次任务${spec.contentUnit}上限"),
repliesPerVideo = repliesPerVideo.number("每条${spec.contentUnit}回复上限"),
watchSeconds = watchMin.number("观看下限")..watchMax.number("观看上限"),
actionMillis = actionMin.number("间隔下限")..actionMax.number("间隔上限"),
replyMode = modes[mode.selectedItemPosition],
replyMode = replyMode,
contentTypes = libraries.contentTypes,
selectedTypeId = libraries.selectedScopeId(),
)
@@ -770,9 +805,11 @@ class MainActivity : Activity() {
background = rounded(SURFACE, 9)
}
private fun LinearLayout.addField(title: String, field: View) {
addView(label(title, 14, bold = true))
private fun LinearLayout.addField(title: String, field: View): TextView {
val caption = label(title, 14, bold = true)
addView(caption)
addView(field, LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = dp(8) })
return caption
}
private fun LinearLayout.addRange(title: String, minimum: EditText, maximum: EditText) {
@@ -460,7 +460,7 @@ internal class UiNode(
private val node: AccessibilityNodeInfo,
val bounds: Rect,
private val parent: UiNode?,
private val depth: Int,
val depth: Int,
) {
val text: String = node.text?.toString()?.trim().orEmpty()
val description: String = node.contentDescription?.toString()?.trim().orEmpty()
@@ -5,11 +5,13 @@ import com.jieliu.app.data.PhotoLibrary
import com.jieliu.app.task.PendingComment
import com.jieliu.app.task.TemplatePhoto
data class PlatformSpec(
data class PlatformSpec @JvmOverloads constructor(
val id: String,
val label: String,
val packageName: String,
val implemented: Boolean,
val supportsReplies: Boolean = false,
val contentUnit: String = "视频",
)
data class VideoContext(val key: String, val title: String)
@@ -43,11 +45,12 @@ interface PlatformAdapter {
}
object PlatformRegistry {
private val douyin = PlatformSpec("douyin", "抖音", "com.ss.android.ugc.aweme", true)
private val douyin = PlatformSpec("douyin", "抖音", "com.ss.android.ugc.aweme", true, supportsReplies = true)
private val xiaohongshu = PlatformSpec("xiaohongshu", "小红书", "com.xingin.xhs", true, contentUnit = "笔记")
val platforms: List<PlatformSpec> = listOf(
douyin,
PlatformSpec("xiaohongshu", "小红书", "com.xingin.xhs", false),
xiaohongshu,
PlatformSpec("bilibili", "哔哩哔哩", "tv.danmaku.bili", false),
)
@@ -57,10 +60,13 @@ object PlatformRegistry {
cancelled: () -> Boolean,
pauseBetweenActions: () -> Unit = {},
): PlatformAdapter {
if (platformId == douyin.id) {
return DouyinAdapter(douyin, AccessibleUi(service, douyin.packageName, cancelled, pauseBetweenActions), PhotoLibrary(service))
}
val spec = platforms.firstOrNull { it.id == platformId }
throw PlatformException("${spec?.label ?: platformId} 暂未接入")
if (spec == null || !spec.implemented) throw PlatformException("${spec?.label ?: platformId} 暂未接入")
val ui = AccessibleUi(service, spec.packageName, cancelled, pauseBetweenActions)
return when (spec.id) {
douyin.id -> DouyinAdapter(spec, ui, PhotoLibrary(service))
xiaohongshu.id -> XiaohongshuAdapter(spec, ui)
else -> throw PlatformException("${spec.label} 暂未接入")
}
}
}
@@ -0,0 +1,421 @@
package com.jieliu.app.platform
import android.graphics.Rect
import android.view.accessibility.AccessibilityNodeInfo
import java.io.Closeable
import java.security.MessageDigest
import kotlin.math.abs
internal class XiaohongshuAdapter(
private val spec: PlatformSpec,
private val ui: AccessibleUi,
) : PlatformAdapter {
private data class SearchHeader(val editor: UiNode, val submit: UiNode)
private data class ResultHeader(val query: UiNode, val tabs: UiNode)
private data class ResultList(val list: UiNode, val viewport: Rect)
private data class CardIdentity(val key: String, val title: String, val author: String)
private data class ResultCard(val action: UiNode, val identity: CardIdentity)
private data class NoteControls(
val author: UiNode,
val more: UiNode,
val toolbar: UiNode,
val caption: UiNode? = null,
)
private class NoteBinding(
val video: VideoContext,
val author: String,
val windowId: Int,
val authorSource: UiNodeSource,
val moreSource: UiNodeSource,
) : Closeable {
override fun close() {
authorSource.close()
moreSource.close()
}
}
private sealed interface ResultStep {
data class Opened(val card: CardIdentity) : ResultStep
data class Scrolled(val positions: Map<String, Int>) : ResultStep
data object End : ResultStep
}
private var keyword: String? = null
private val examinedCards = mutableSetOf<String>()
private var activeNote: NoteBinding? = null
override fun launch() = ui.launchTarget(spec.label)
override fun search(keyword: String): VideoContext {
require(keyword.isNotBlank()) { "小红书搜索词不能为空" }
this.keyword = null
examinedCards.clear()
resetNote()
openSearchEditor()
ui.pace()
val written = awaitPage(4_000, "小红书搜索输入框未获得焦点") { page ->
val editor = page.searchHeader()?.editor ?: return@awaitPage null
if (!editor.hasCurrentInputFocus()) return@awaitPage null
editor.hasQuery(keyword) || ui.setText(editor, keyword)
}
if (!written) throw PlatformException("小红书搜索框未接受无障碍文本输入")
awaitPage(4_000, "小红书搜索框中未回读到完整关键词") { page ->
true.takeIf { page.searchHeader()?.editor?.hasQuery(keyword) == true }
}
ui.pace()
val submitted = awaitPage(4_000, "小红书搜索按钮或关键词已变化") { page ->
val header = page.searchHeader()?.takeIf { it.editor.hasQuery(keyword) } ?: return@awaitPage null
ui.click(header.submit)
}
if (!submitted) throw PlatformException("小红书搜索按钮操作未获系统确认")
this.keyword = keyword
return openNextResult(keyword)
}
private fun openSearchEditor() {
repeat(3) {
if (ui.inspect { it.searchHeader()?.editor?.focused == true } == true) return
ui.pace()
val opened = awaitPage(4_000, "小红书首页未显示可核对的搜索入口") { page ->
val header = page.searchHeader()
if (header != null) return@awaitPage header.editor.focused || ui.click(header.editor)
val results = page.resultHeader()
if (results != null) return@awaitPage ui.click(results.query)
val entry = page.homeSearchEntry()
if (entry != null) return@awaitPage ui.click(entry)
if (page.noteControls() != null && page.nodes.none { it.editable && it.focused }) return@awaitPage ui.back()
null
}
if (!opened) throw PlatformException("小红书未确认已打开搜索框")
val editorReady = ui.await(3_000) {
ui.inspect { page -> true.takeIf { page.searchHeader()?.editor?.hasCurrentInputFocus() == true } }
}
if (editorReady == true) return
}
throw PlatformException("小红书未显示搜索框,请检查当前页面")
}
private fun UiPage.homeSearchEntry(): UiNode? {
if (nodes.none { it.selected && it.className == "android.view.ViewGroup" && it.description == "首页" &&
it.bounds.centerY() >= y(.80f) }) return null
return nodes.singleOrNull { it.className == "android.widget.Button" && it.description == "搜索" &&
it.bounds.centerX() >= x(.72f) && it.bounds.centerY() <= y(.22f) && it.isNativeClick() }
}
private fun UiPage.searchHeader(): SearchHeader? {
val headers = nodes.asSequence().filter { editor ->
editor.className == "android.widget.EditText" && editor.editable && editor.enabled &&
editor.bounds.centerY() <= y(.22f) && editor.bounds.width() >= bounds.width() * .30f
}.mapNotNull { editor ->
val fieldRow = editor.directParent()?.takeIf { it.className == "android.widget.LinearLayout" }
?: return@mapNotNull null
val toolbar = fieldRow.directParent()?.takeIf { it.className == "android.widget.RelativeLayout" }
?: return@mapNotNull null
val back = nodes.singleOrNull { node ->
node.className == "android.widget.ImageView" && node.description == "返回" &&
node.bounds.right <= editor.bounds.left && node.directParent()?.directParent() === toolbar
} ?: return@mapNotNull null
if (back.directParent()?.isNativeClick() != true) return@mapNotNull null
val submit = nodes.singleOrNull { node ->
node.className == "android.widget.Button" && node.text == "搜索" && node.isNativeClick() &&
node.bounds.left >= editor.bounds.right && node.directParent()?.directParent() === fieldRow &&
node.bounds.top < editor.bounds.bottom && node.bounds.bottom > editor.bounds.top
} ?: return@mapNotNull null
SearchHeader(editor, submit)
}
return headers.toList().singleOrNull()
}
private fun UiNode.hasQuery(keyword: String): Boolean = !showingHint &&
(text == keyword || text == "搜索, $keyword")
private fun UiPage.resultHeader(): ResultHeader? {
val back = nodes.singleOrNull { it.className == "android.widget.ImageView" && it.description == "返回" &&
it.bounds.centerX() <= x(.16f) && it.bounds.centerY() <= y(.22f) && it.isNativeClick() } ?: return null
val row = back.directParent()?.takeIf { it.className == "android.view.ViewGroup" } ?: return null
val submit = nodes.singleOrNull { it.directParent() === row && it.className == "android.widget.TextView" &&
it.text == "搜索" && it.bounds.centerX() >= x(.80f) && it.isNativeClick() } ?: return null
val query = nodes.singleOrNull { it.directParent() === row && it !== submit &&
it.className == "android.widget.TextView" && it.text.isNotBlank() && it.isNativeClick() &&
it.bounds.left >= back.bounds.right && it.bounds.right <= submit.bounds.left &&
it.bounds.width() >= bounds.width() * .35f } ?: return null
val tabs = nodes.singleOrNull { strip ->
strip.className == "android.widget.HorizontalScrollView" && strip.bounds.top >= row.bounds.bottom - 2 &&
strip.bounds.centerY() <= y(.28f) && nodes.any { item ->
item.isDescendantOf(strip) && item.className == "android.widget.TextView" &&
item.text in setOf("全部", "视频") && item.selected
}
} ?: return null
return ResultHeader(query, tabs)
}
private fun UiPage.resultList(keyword: String): ResultList? {
val header = resultHeader()?.takeIf { it.query.text == keyword } ?: return null
val list = nodes.singleOrNull { it.className == "androidx.recyclerview.widget.RecyclerView" &&
it.bounds.width() >= bounds.width() * .90f && it.bounds.bottom >= y(.65f) &&
it.bounds.top <= header.tabs.bounds.bottom + 36 } ?: return null
val viewport = Rect(list.bounds)
if (!viewport.intersect(bounds)) return null
viewport.top = maxOf(viewport.top, header.tabs.bounds.bottom)
return ResultList(list, viewport).takeUnless { viewport.isEmpty }
}
private fun UiPage.resultCards(surface: ResultList): List<ResultCard> {
val cards = nodes.asSequence().filter { node ->
node.directParent() === surface.list && node.className == "android.widget.FrameLayout" &&
node.bounds.width() in (surface.viewport.width() * .38f).toInt()..(surface.viewport.width() * .55f).toInt() &&
surface.viewport.contains(node.bounds.centerX(), node.bounds.centerY()) && node.isNativeClick()
}.mapNotNull { card ->
val title = nodes.singleOrNull { node ->
node.isDescendantOf(card) && node.depth == card.depth + 2 && node.isUneditableText() &&
!node.clickable && node.bounds.width() >= card.bounds.width() * .70f &&
surface.viewport.contains(node.bounds)
} ?: return@mapNotNull null
val author = nodes.singleOrNull { node ->
node.isDescendantOf(card) && node.depth == card.depth + 4 && node.isUneditableText() &&
node.isNativeClick() && node.bounds.top >= title.bounds.bottom &&
node.bounds.left < card.bounds.centerX() && surface.viewport.contains(node.bounds)
} ?: return@mapNotNull null
ResultCard(card, CardIdentity(identity(author.text, title.text), title.text, author.text))
}.toList()
val counts = cards.groupingBy { it.identity.key }.eachCount()
return cards.filter { counts[it.identity.key] == 1 }
.sortedWith(compareBy({ it.action.bounds.top }, { it.action.bounds.left }))
}
private fun openNextResult(keyword: String): VideoContext {
repeat(8) {
ui.pace()
val step = awaitPage(9_000, "小红书未显示当前关键词对应的可读笔记结果") { page ->
val surface = page.resultList(keyword) ?: return@awaitPage null
val cards = page.resultCards(surface).takeIf { it.isNotEmpty() } ?: return@awaitPage null
val next = cards.firstOrNull { it.identity.key !in examinedCards }
if (next != null) {
if (!ui.click(next.action)) throw PlatformException("小红书未确认已打开选中的笔记卡片")
return@awaitPage ResultStep.Opened(next.identity)
}
if (!surface.list.scrollable || !ui.scrollUpInside(surface.viewport)) return@awaitPage ResultStep.End
ResultStep.Scrolled(cards.associate { it.identity.key to it.action.bounds.top })
}
when (step) {
is ResultStep.Opened -> bindNote(step.card, keyword)?.let { return it }
is ResultStep.Scrolled -> if (!waitForMovement(step.positions) { page ->
val surface = page.resultList(keyword) ?: return@waitForMovement null
page.resultCards(surface).associate { it.identity.key to it.action.bounds.top }
}) throw PlatformException("小红书未显示更多可核对的笔记")
ResultStep.End -> throw PlatformException("小红书当前搜索结果已浏览完毕")
}
}
throw PlatformException("小红书未找到下一条可核对的笔记")
}
private fun bindNote(card: CardIdentity, keyword: String): VideoContext? {
val binding = awaitNoteBinding(card, 5_000) ?: verifyOrSkipImageNote(card, keyword) ?: return null
resetNote()
activeNote = binding
examinedCards += card.key
return binding.video
}
private fun awaitNoteBinding(card: CardIdentity, timeout: Long, anchor: NoteBinding? = null): NoteBinding? = ui.await(timeout) {
ui.inspect { page ->
val visible = if (anchor == null) page.noteControls() else page.boundNote(anchor)
val detail = visible?.takeIf { it.author.text == card.author } ?: return@inspect null
if (!page.hasNoteText(detail, card.title)) return@inspect null
page.retainNote(card, detail)
}
}
private fun verifyOrSkipImageNote(card: CardIdentity, keyword: String): NoteBinding? {
val shell = ui.inspect { page ->
val detail = page.imageNoteControls()?.takeIf { it.author.text == card.author } ?: return@inspect null
page.retainNote(card, detail)
} ?: throw PlatformException("小红书未能核对笔记详情与选中的结果卡片")
shell.use { anchor ->
revealImageNoteText(card, anchor)?.let { return it }
leaveUnverifiedImageNote(anchor, keyword)
}
examinedCards += card.key
return null
}
private fun revealImageNoteText(card: CardIdentity, anchor: NoteBinding): NoteBinding? {
repeat(2) {
ui.pace()
val adjusted = ui.inspect { page ->
val detail = page.boundNote(anchor)?.takeIf { it.caption == null } ?: return@inspect false
if (page.nodes.any { it.editable && it.focused }) return@inspect false
if (page.hasNoteText(detail, card.title)) return@inspect true
val viewport = Rect(page.bounds).apply {
top = maxOf(top, detail.author.bounds.bottom, detail.more.bounds.bottom)
bottom = minOf(bottom, detail.toolbar.bounds.top)
}
viewport.height() >= page.bounds.height() * .48f && ui.scrollUpInside(viewport)
}
if (adjusted != true) return null
awaitNoteBinding(card, 3_000, anchor)?.let { return it }
}
return null
}
private fun leaveUnverifiedImageNote(anchor: NoteBinding, keyword: String) {
ui.pace()
val left = awaitPage(4_000, "小红书未能安全退出无法核对的图文笔记") { page ->
val detail = page.boundNote(anchor) ?: return@awaitPage null
if (detail.caption != null || page.nodes.any { it.editable && it.focused }) return@awaitPage null
ui.back()
}
if (!left) throw PlatformException("小红书未确认退出无法核对的图文笔记")
awaitPage(6_000, "退出小红书笔记后未核对到同一搜索结果") { page ->
true.takeIf { page.resultList(keyword) != null }
}
}
private fun UiPage.retainNote(card: CardIdentity, detail: NoteControls): NoteBinding =
NoteBinding(VideoContext(card.key, card.title), card.author, windowId,
detail.author.retainSource(), detail.more.retainSource())
override fun currentVideo(): VideoContext {
val note = activeNote ?: throw PlatformException("请先通过小红书搜索打开笔记")
return awaitPage(4_000, "小红书当前笔记已变化") { page ->
note.video.takeIf { page.boundNote(note) != null }
}
}
override fun nextVideo(previous: VideoContext): VideoContext {
val query = keyword ?: throw PlatformException("未找到当前小红书搜索关键词")
val note = activeNote?.takeIf { it.video.key == previous.key }
?: throw PlatformException("小红书上一条笔记仍未核对")
ui.pace()
val left = awaitPage(4_000, "小红书未找到可退出的上一条笔记") { page ->
if (page.boundNote(note) == null || page.nodes.any { it.editable && it.focused }) return@awaitPage null
ui.back()
}
if (!left) throw PlatformException("小红书返回搜索结果的操作未获系统确认")
resetNote()
return openNextResult(query)
}
private fun UiPage.noteControls(): NoteControls? = imageNoteControls() ?: videoNoteControls()
private fun UiPage.imageNoteControls(): NoteControls? {
val author = nodes.singleOrNull { it.resourceId == "nickNameTV" && it.isUneditableText() &&
it.bounds.centerY() <= y(.21f) } ?: return null
val more = nodes.singleOrNull { it.resourceId == "moreOperateIV" && it.className == "android.widget.ImageView" &&
it.bounds.centerX() >= x(.82f) && it.bounds.centerY() <= y(.21f) && it.isNativeClick() } ?: return null
if (author.bounds.top >= more.bounds.bottom || author.bounds.bottom <= more.bounds.top) return null
val prompt = nodes.singleOrNull { it.description == "评论框" && it.className == "android.widget.TextView" &&
it.bounds.centerY() >= y(.76f) && it.bounds.centerX() <= x(.49f) && it.isNativeClick() } ?: return null
val toolbar = prompt.directParent()?.takeIf { it.className == "android.view.ViewGroup" } ?: return null
val buttons = nodes.filter { it.directParent() === toolbar && it.className == "android.widget.Button" && it.isNativeClick() }
if (buttons.count { likeLabel.matches(it.description) } != 1 ||
buttons.count { favoriteLabel.matches(it.description) } != 1) return null
if (buttons.count { commentLabel.matches(it.description) && it.bounds.centerX() >= x(.75f) } != 1) return null
return NoteControls(author, more, toolbar)
}
private fun UiPage.videoNoteControls(): NoteControls? {
val author = nodes.singleOrNull { it.resourceId == "matrixNickNameView" && it.isUneditableText() &&
it.bounds.centerX() <= x(.60f) && it.bounds.centerY() >= y(.60f) } ?: return null
val caption = nodes.singleOrNull { it.resourceId == "noteContentText" && it.isUneditableText() &&
it.bounds.top >= author.bounds.bottom && it.bounds.width() >= bounds.width() * .60f } ?: return null
val share = nodes.singleOrNull { it.className == "android.widget.ImageView" && it.description == "分享" &&
it.bounds.centerX() >= x(.80f) && it.bounds.centerY() <= y(.22f) && it.isNativeClick() } ?: return null
val back = nodes.singleOrNull { it.className == "android.widget.ImageView" && it.description == "返回" &&
it.bounds.centerX() <= x(.18f) && it.bounds.centerY() <= y(.22f) && it.isNativeClick() } ?: return null
if (share.bounds.top > back.bounds.bottom || back.bounds.top > share.bounds.bottom) return null
if (nodes.none { it.className == "android.view.ViewGroup" && it.description in setOf("播放", "暂停") &&
it.bounds.width() >= bounds.width() * .85f && it.bounds.height() >= bounds.height() * .80f }) return null
val comment = nodes.singleOrNull { it.className == "android.widget.Button" && commentLabel.matches(it.description) &&
it.bounds.centerX() >= x(.75f) && it.bounds.top >= caption.bounds.bottom && it.isNativeClick() } ?: return null
return NoteControls(author, share, comment.directParent() ?: return null, caption)
}
private fun UiPage.hasNoteText(detail: NoteControls, title: String): Boolean {
val preview = title.normalizedPostText()
if (detail.caption != null) {
val caption = detail.caption.text.normalizedPostText()
return caption == preview || caption.length >= 16 && preview.startsWith(caption) ||
preview.length >= 16 && caption.startsWith(preview)
}
val visibleText = nodes.filter { node ->
val exposedHeight = minOf(node.bounds.bottom, bounds.bottom, detail.toolbar.bounds.top) - node.bounds.top
node.isUneditableText() && !node.clickable && node.bounds.width() >= bounds.width() * .72f &&
node.bounds.top > detail.more.bounds.bottom &&
exposedHeight >= minOf(node.bounds.height(), (bounds.height() * .08f).toInt())
}
if (visibleText.any { node ->
val text = node.text.normalizedPostText()
text == preview || preview.length >= 16 && text.startsWith(preview)
}) return true
// Search cards may combine the note's title and body into one preview label.
val compactPreview = preview.replace(layoutGaps, "")
return visibleText.filter { it.directParent() != null }.groupBy { it.directParent() }.values.count { parts ->
parts.sortedBy { it.bounds.top }.zipWithNext().any { (titleNode, bodyNode) ->
abs(titleNode.bounds.left - bodyNode.bounds.left) <= 2 &&
abs(titleNode.bounds.right - bodyNode.bounds.right) <= 2 &&
bodyNode.bounds.top in titleNode.bounds.bottom..(titleNode.bounds.bottom + titleNode.bounds.height()) &&
(titleNode.text + "\n" + bodyNode.text).normalizedPostText().replace(layoutGaps, "") == compactPreview
}
} == 1
}
private fun UiPage.boundNote(note: NoteBinding): NoteControls? = noteControls()?.takeIf {
windowId == note.windowId && it.author.text == note.author && it.author.hasSource(note.authorSource) &&
it.more.hasSource(note.moreSource) && (it.caption == null || hasNoteText(it, note.video.title))
}
private fun resetNote() {
activeNote?.close()
activeNote = null
}
override fun openComments(expected: VideoContext): List<String> =
throw PlatformException("小红书评论区暂未开放")
override fun publishComment(text: String, beforeClick: () -> Unit): CommentPublishResult =
throw PlatformException("小红书暂未开放自动回复")
override fun closeComments() = Unit
private fun UiNode.isNativeClick(): Boolean = enabled && supports(AccessibilityNodeInfo.ACTION_CLICK)
private fun UiNode.isUneditableText(): Boolean = className == "android.widget.TextView" &&
!editable && text.isNotBlank()
private fun String.normalizedPostText(): String = replace(whitespace, " ").trim()
.replace(expandCaption, "").trimEnd('…', '.', ' ')
private fun identity(author: String, title: String): String = MessageDigest.getInstance("SHA-256")
.digest("xiaohongshu\u0000$author\u0000$title".toByteArray(Charsets.UTF_8))
.joinToString("") { "%02x".format(it) }
private fun waitForMovement(before: Map<String, Int>, observe: (UiPage) -> Map<String, Int>?): Boolean {
var moved = false
var previous: Map<String, Int>? = null
ui.await(2_500) {
val after = ui.inspect(observe)?.takeIf { it.isNotEmpty() } ?: return@await null
val preceding = previous
previous = after
moved = moved || after.keys != before.keys || after.any { (key, y) -> abs((before[key] ?: y) - y) >= 5 }
true.takeIf { moved && preceding != null && after.keys == preceding.keys &&
after.all { (key, y) -> abs((preceding[key] ?: y) - y) <= 2 } }
}
return moved
}
private fun <T : Any> awaitPage(timeout: Long, failure: String, observe: (UiPage) -> T?): T =
ui.await(timeout) { ui.inspect(observe) } ?: throw PlatformException(failure)
private companion object {
const val COUNTER = "(?:\\s+[0-9]+(?:\\.[0-9]+)?(?:万|亿)?\\+?)?"
val likeLabel = Regex("(?:已)?点赞$COUNTER")
val favoriteLabel = Regex("(?:已)?收藏$COUNTER")
val commentLabel = Regex("评论$COUNTER")
val whitespace = Regex("\\s+")
val layoutGaps = Regex("[\\s\\p{Cc}\\p{Cf}\\p{Z}]+")
val expandCaption = Regex("(?:\\.{3}|…)+\\s*展开(?:全文)?$")
}
}
@@ -4,6 +4,7 @@ import com.jieliu.app.platform.CommentPublishResult
import com.jieliu.app.platform.CommentTarget
import com.jieliu.app.platform.PlatformAdapter
import com.jieliu.app.platform.PlatformException
import com.jieliu.app.platform.PlatformRegistry
import com.jieliu.app.platform.VideoContext
import java.util.concurrent.CancellationException
@@ -21,6 +22,8 @@ internal class TaskRunner(
private val cancelled: () -> Boolean,
private val status: (String) -> Unit,
) {
private val contentUnit = PlatformRegistry.platforms.firstOrNull { it.id == plan.platformId }?.contentUnit ?: "视频"
private data class MatchedReply(
val target: CommentTarget,
val rule: KeywordRule,
@@ -48,8 +51,8 @@ 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) " · 每个视频最多 ${plan.repliesPerVideo} 条回复" else ""
store.appendLog("开始任务 · ${mode.label} · ${plan.limit} 个视频$quota")
val quota = if (mode == ReplyMode.TEMPLATES) " · 每个${contentUnit}最多 ${plan.repliesPerVideo} 条回复" else ""
store.appendLog("开始任务 · ${mode.label} · ${plan.limit} 个$contentUnit$quota")
status("正在打开目标应用")
platform.launch()
var activeTypeId: String? = null
@@ -62,7 +65,7 @@ internal class TaskRunner(
store.appendLog("搜索内容类型 ${type.name}")
platform.search(type.name).also { activeTypeId = type.id }
} else {
status("正在打开下一条视频")
status("正在打开下一条$contentUnit")
platform.nextVideo(video)
}
val candidate = locateVideo(first, checkpoint)
@@ -105,14 +108,14 @@ internal class TaskRunner(
check(confirmation == CommentPublishResult.CONFIRMED) { "请在目标应用里核对这条评论的发送结果。" }
persist(checkpoint.recordReply(Outcome.SENT))
val confirmed = checkpoint.activeVideo?.sentCount ?: plan.repliesPerVideo
store.appendLog("第 $number 条视频已确认 ${confirmed}/${plan.repliesPerVideo} 条回复")
store.appendLog("第 $number 条${contentUnit}已确认 ${confirmed}/${plan.repliesPerVideo} 条回复")
}
}
checkpoint.activeVideo?.let { progress ->
persist(checkpoint.finishVideo())
val summary = if (progress.sentCount == 0) "未找到可回复的匹配评论,已跳过"
else "评论扫描结束,已确认发送 ${progress.sentCount}/${plan.repliesPerVideo} 条"
store.appendLog("第 $number 条视频$summary")
store.appendLog("第 $number 条$contentUnit$summary")
}
if (openPanel && !checkpoint.complete) platform.closeComments()
}
@@ -149,10 +152,10 @@ internal class TaskRunner(
status("正在打开目标应用")
platform.launch()
}
status("正在定位待核对的视频")
status("正在定位待核对的$contentUnit")
val video = locateVideo(platform.search(type.name), checkpoint)
requireRunning(cancelled)
status("正在打开待核对的视频评论区")
status("正在打开待核对的${contentUnit}评论区")
platform.openComments(video)
requireRunning(cancelled)
status("正在核对已发送的回复")
@@ -167,7 +170,8 @@ internal class TaskRunner(
while (if (resumeKey == null) checkpoint.hasSeen(candidate.key) else candidate.key != resumeKey) {
requireRunning(cancelled)
check(tried.add(candidate.key) && tried.size <= searchLimit) {
if (resumeKey == null) "搜索结果反复返回同一批视频" else "暂未重新找到上次的视频,已保留该视频的回复进度。"
if (resumeKey == null) "搜索结果反复返回同一批$contentUnit"
else "暂未重新找到上次的$contentUnit,已保留该${contentUnit}的回复进度。"
}
candidate = platform.nextVideo(candidate)
}
@@ -176,10 +180,12 @@ internal class TaskRunner(
private fun watch(video: VideoContext, number: Int) {
val duration = randomIn(plan.watchSeconds.first, plan.watchSeconds.last)
status("正在观看第 $number 条 · $duration 秒")
store.appendLog("观看第 $number 条 · $duration 秒")
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) { "观看期间视频已切换,请恢复任务。" }
check(platform.currentVideo().key == video.key) { "${action}期间${contentUnit}已切换,请恢复任务。" }
}
private fun findVisibleReply(type: ContentType, title: String, checkpoint: TaskCheckpoint): MatchedReply? {
@@ -8,4 +8,4 @@
android:canTakeScreenshot="true"
android:description="@string/accessibility_description"
android:notificationTimeout="200"
android:packageNames="com.ss.android.ugc.aweme" />
android:packageNames="com.ss.android.ugc.aweme,com.xingin.xhs" />