Release Shijian 0.1.19 with automatic Douyin reply receipts

Add content type rules, reply quotas, and multi-image templates. Verify published replies in the original comment thread and record automatic receipts. Document uninterrupted physical-device acceptance.
This commit is contained in:
2026-11-26 14:00:16 +08:00
parent af6aa07c3a
commit fed659dab9
23 changed files with 3611 additions and 770 deletions
+36 -20
View File
@@ -1,6 +1,6 @@
# 拾见
拾见是独立运行的安卓 APK。首个适配平台为抖音标准版。任务按关键词搜索和浏览视频,评论优先从该关键词的本地话术组中随机选取,可启用 DeepSeek 兜底。小红书和哔哩哔哩已列在平台注册表中,界面标注为待适配。
拾见是独立运行的安卓 APK。首个适配平台为抖音标准版。任务以内容类型名称为搜索词,逐屏读取评论正文。命中关键字后,从该关键字的话术库中随机选取一条话术和对应图片,回复到命中的原评论下。小红书和哔哩哔哩已列在平台注册表中,界面标注为待适配。
## 界面
@@ -8,8 +8,8 @@
| 页面 | 可以做什么 |
| --- | --- |
| 任务 | 开启无障碍服务,开始、暂停、继续任务,查看关键词、处理数量和发送结果。安卓 13 及以上可开启通知栏暂停按钮。 |
| 配置 | 选择平台和评论方式,填写关键词、话术、任务数量、观看与动作区间,以及 DeepSeek 设置。 |
| 任务 | 开启无障碍服务,开始、暂停、继续任务,查看当前内容类型、处理数量和回复结果。安卓 13 及以上可开启通知栏暂停按钮。 |
| 配置 | 选择平台、搜索范围和处理方式,维护内容类型、各类型的关键字、各关键字的话术与图片,并设置任务数量和动作区间。 |
| 日志 | 查看最近 150 条本机记录,包括搜索、观看、发送确认和中断原因。 |
## 构建环境
@@ -51,34 +51,36 @@ powershell -NoProfile -File ./scripts/verify-apk.ps1
~~~
2. 打开「拾见 → 任务 → 打开无障碍设置」,在系统中开启「拾见任务服务」。若较新系统把侧载应用的开关置灰,查看应用详情菜单是否提供「允许受限设置」,再返回无障碍设置。具体入口因厂商而异。[Android 官方帮助](https://support.google.com/android/answer/12623953?hl=zh-Hans)
3. 在「配置」填写关键词、处理方式及对应参数,点「保存配置」。首次可用默认的「仅浏览」模式,数量设为 1,检查抖音的搜索和播放页能否识别。
3. 在「配置」创建内容类型并填写实际要搜索的名称,例如「大模型充值」。在该类型中添加评论关键字,例如「付款方式」和「账号订阅」,分别维护话术和图片。选择搜索范围、处理方式和任务参数,点「保存配置」。可以先用「仅浏览」模式验证搜索和播放。
4. 在「任务」点「开始任务」。保持手机解锁并让抖音留在前台。在拾见任务页或用通知栏按钮可暂停。登录、验证、页面布局不可识别等中断可在手机处理后点「继续任务」。
5. 如果显示「等待核对」,检查抖音评论区里是否已有页面所显示的评论,再选择「确认已发送」或「跳过这条视频」。跳过计入任务处理数量。检查点会保留待核对条目,应用不会自动重发它。
5. 抖音发布后,拾见核对原评论下新增的本人回复,匹配正文和全部绑定图片后自动登记回执。图文自动核对需要 Android 11 或更新版本,图片比对在手机内存中完成。待核对卡片出现「自动核对回复」时,可让拾见再次查找并核对这条回复。若仍显示待核对,可到原评论下核对正文及图片,再选择「确认已发送」或「跳过此回复」。待核对期间会阻止自动重发。
安装完成后,任务可以脱离电脑运行。抖音内容和 DeepSeek 请求仍需要手机网络。
安装完成后,任务可以脱离电脑运行。加载抖音内容需要手机网络,话术匹配和选择在拾见本机完成。
## 配置项
| 配置 | 说明 |
| --- | --- |
| 目标平台 | 首版实现抖音标准版,包名 com.ss.android.ugc.aweme。 |
| 搜索关键词 | 每行一个,最多 30 个。示例为「国外大模型充值」。任务总数按关键词顺序尽量均分,余数优先分给前面的关键词,总数少于关键词数时只处理排在前面的关键词。 |
| 单次任务总数 | 跨关键词共处理 1–100 条。 |
| 内容类型 | 类型名称直接用于抖音搜索。「全部类型」按类型顺序尽量均分任务总数,余数优先分给前面的类型。也可只运行一个类型。 |
| 评论关键字 | 每个类型可增删改多条关键字。每个关键字对应独立话术库。匹配基于评论正文,兼容全角半角、英文字母大小写和常见中英文空格;重叠时优先选更长的匹配。 |
| 单次任务视频上限 | 共处理 1–100 个视频。浏览完成或扫描后没有可回复的评论也计入进度。 |
| 每条视频回复上限 | 默认 1 条,可设为 1–100 条。在匹配回复模式下,已确认发送的回复计入上限。达标、评论列表到末尾或扫描范围内没有更多匹配时,浏览下一个视频。 |
| 观看时长 | 1–300 秒的闭区间,逐视频取样,默认 5–12 秒。 |
| 动作间隔 | 150–30,000 毫秒的闭区间,逐动作取样,默认 600–1,800 毫秒。视频滑动起止点和时长也在播放器允许范围内取样。 |
| 处理方式 | 「仅浏览」「随机使用话术并发送」「话术优先,DeepSeek 兜底」。发送模式优先查找当前搜索关键词的分组,其次查找通用组。仍无可用回复时跳过视频并记日志。 |
| 话术分组 | 在配置页选择「通用」或一个已配置的关键词,再逐行编辑。原有话术自动作为通用话术读取。每组独立随机洗牌,用完重洗,同一组有多条时避开上一轮最后使用的模板。每组最多 100 条,每条最多 120 个 Unicode 码点。支持 {keyword} 和 {title}。 |
| 话术图片 | 在「绑定到话术」选择具体一行,点「选择本机图片」,手动选一张 JPEG 或 PNG,最后点「保存配置」。每条话术可绑定一张图片,支持更换和移除。文件最多 20 MB,需要 Android 10 或更新版本。改写已绑定话术后需重新绑定。 |
| DeepSeek | 选择兜底模式并设置 API Key 后,关键词组和通用组均无可用话术时才调用。默认模型 deepseek-flash,生成说明可编辑。请求包含关键词、视频标题和最多 4 条可见评论样本。密钥缺失或生成失败时跳过对应视频,并记录原因。[DeepSeek API 文档](https://api-docs.deepseek.com/api/create-chat-completion/) |
| 密钥 | 使用系统 Android Keystore 加密保存在应用私有目录。任务快照保存普通配置,启动或恢复时读取当前已保存密钥。 |
| 动作间隔 | 150–30,000 毫秒的闭区间,默认 600–1,800 毫秒。评论滑动在评论列表内变化起点、距离、轨迹、时长和停留时间,每个视频最多滑动 12 次并在每屏重新读取。 |
| 处理方式 | 「仅浏览」只观看视频。「匹配评论并回复」逐屏读取评论,匹配到当前类型中有可用话术的关键字时回复原评论。同一任务内每条原评论最多尝试一次发送。 |
| 话术库 | 每个关键字最多 100 条话术,每条最多 120 个 Unicode 码点。支持 {keyword} 和 {title},分别填入命中的关键字和视频标题。各库独立随机轮换,有可用替代时避开连续重复。 |
| 话术图片 | 每条话术独立绑定最多 9 张 JPEG 或 PNG,可一次多选、逐张调整顺序或移除。单张最多 20 MB,需要 Android 10 或更新版本。编辑原话术时会保留其图片。 |
配置修改在下次新任务生效。恢复会沿用任务快照、处理进度和已记录的抽取进度。
保存后,关键字、话术和图片从下一次评论识别起生效,同时在提交前核对命中的话术库。搜索范围、类型名称、视频及回复上限和动作区间用于下次新任务。恢复保留搜索计划、处理进度和已记录的抽取进度。
## 恢复和兼容性
发送前,应用先把视频指纹和待提交内容写入本地检查点。文字评论在确认编辑区已清空且评论列表新增匹配正文时自动记录回执。图文评论写入同一个抖音编辑框,点击一次发送后由任务页显示正文和所绑定的图片,供用户同时核对两者。中途退出或回执不明确时,任务保留待核对记录。恢复会重新搜索当前关键词,用视频指纹跳过已处理条目。指纹基于可见作者和标题。同作者、同标题的不同视频可能合并,标题变化也可能改变指纹。
发送前,应用核对原评论对象和编辑框,把视频指纹、原评论标识、回复正文和图片列表写入本地检查点。回执不明确时,任务保留待核对记录,任务页显示原评论作者与待核对的图文。恢复时先定位同一未完成视频并跳过已尝试的原评论,也会跳过已结束处理的视频。视频指纹基于可见作者和标题,同作者、同标题的不同视频可能合并,标题变化也可能改变指纹。
拾见为手动选定的图片保存本机私有副本。图文任务使用快照中的绑定,选图时只尝试本次创建的单图临时相册。图库权限、相册布局或编辑框附件无法确认时,任务会停在当步并记录原因。用户核对完成后,拾见清理未使用的临时相册图片。选图基于 Android 系统文件选择器,临时相册基于系统媒体库。[Android 文件选择器](https://developer.android.com/training/data-storage/shared/documents-files) · [Android 媒体库](https://developer.android.com/training/data-storage/shared/media)
旧配置的搜索关键词迁移为同名内容类型和首条评论关键字,保留原分组话术及对应图片。原分组没有话术时,原通用话术随该组迁入。旧版已有的发送待核对记录仍可核对。
拾见为手动选定的图片保存本机私有副本。回复选图时只使用本次创建的临时相册,并在提交前核对选中的图片数和编辑框中的附件总数。图库权限、相册布局或附件数量无法确认时,任务会停在当步并记录原因。用户核对完成后,拾见清理临时相册图片。选图基于 Android 系统文件选择器,临时相册基于系统媒体库。[Android 文件选择器](https://developer.android.com/training/data-storage/shared/documents-files) · [Android 媒体库](https://developer.android.com/training/data-storage/shared/media)
抖音页面识别依据无障碍节点及控件语义,受安装版本、登录状态及服务端布局影响。若搜索、播放器或评论区域缺少可读节点,任务会在相应环节暂停,并在日志记录原因。
@@ -91,14 +93,28 @@ powershell -NoProfile -File ./scripts/verify-apk.ps1
| app/src/main/res/layout、MainActivity.kt | 页面结构、参数控件和任务操作。 |
| app/src/main/java/com/jieliu/app/AutomationService.kt | 无障碍服务连接、任务生命周期、暂停通知。 |
| app/src/main/java/com/jieliu/app/platform | 平台接口、注册表、节点和手势操作、抖音适配器。 |
| app/src/main/java/com/jieliu/app/task | 关键词分配、随机节奏、话术、DeepSeek 和恢复规则。 |
| app/src/main/java/com/jieliu/app/data | 配置、发送检查点、运行日志和密钥。 |
| app/src/main/java/com/jieliu/app/task | 内容类型调度、评论关键字匹配、话术轮换和恢复规则。 |
| app/src/main/java/com/jieliu/app/data | 配置、图片、发送检查点和运行日志。 |
| docs/技术调研.md | 前期技术选型、通用组件评估和设计依据。 |
扩展平台时实现 PlatformAdapter,在 PlatformRegistry 注册包名和适配实例,并同步更新 manifest 的应用可见性和无障碍事件包名。针对该平台实际取证搜索、播放、评论编辑和发送确认四组 UI 节点。
扩展平台时实现 PlatformAdapter,在 PlatformRegistry 注册包名和适配实例,并同步更新 manifest 的应用可见性和无障碍事件包名。需要验证搜索、播放、评论列表读取、原评论定位、回复编辑及发送确认的无障碍节点。
## 本机验收
0.1.6 通过 APK 构建、APK v2 调试签名和 12 项 JVM 单元测试。在 vivo Android 12、抖音 39.8.0 上完成单条和三条真机验收,覆盖关键词搜索、视频播放、本地分组话术写入、实际评论发布和自动回执。使用 0.6–1.8 秒动作间隔的三条任务用时 1 分 11 秒,拾见记录「处理 3 条 · 确认发送 3 条」。历次真机结果见[开发进度](docs/开发进度.md)。
0.1.7 通过离线构建、APK v2 调试签名和 16 项 JVM 单测。图文功能已在 vivo 真机验证本机选图、绑定存储、检查点恢复及抖音实际发布。单条实发在同一评论中核对了正文和绑定图片,并在拾见录入人工确认回执。
0.1.8 通过离线构建、APK v2 调试签名和 17 项 JVM 单元测试。vivo 真机验证了旧单图配置迁移,以及 9 张合成图和文字进入同一条抖音评论并通过发送前校验。多图验证停在发送前。
0.1.9 通过离线构建、APK v2 调试签名、26 项 JVM 单元测试和桌面、手机尺寸的离线界面验证。原评论回复框回读、图文回复位置和结果核对待真机联调。
0.1.10 在 vivo Android 12、抖音 39.8.0 上验证旧配置迁移、恢复任务后逐屏匹配,以及文字分别与 2 张、7 张图片进入同一个原评论回复草稿。使用用户保存的配置实发 1 条定向图文回复,逐项核对原评论、发布正文和绑定图片后,记录 1 条人工确认回执。新版 APK 已覆盖安装并通过签名校验及 26 项 JVM 单元测试。
0.1.11 在同一视频的两条不同原评论下实发 2 条图文回复,逐条核对后确认回执。达到每视频 2 条上限后,恢复任务时自行打开了下一条视频。另在真机验证无匹配时连续跳过两个视频,发布数为 0。新版覆盖安装、APK v2 签名校验和 35 项 JVM 单元测试通过。
0.1.12 修复抖音深层播放及评论控件的识别。真机从原任务 2/3 恢复,在第 3 个视频中命中已配置的评论关键字并实发 1 条图文回复。在原评论下核对同一条回复中的正文和绑定图后录入人工确认回执,任务完成 3/3。APK v2 签名校验和 35 项 JVM 单元测试通过。
0.1.18 支持展开原评论的回复分页,重新定位本人回复,并在手机内存中比对该回复里的图片。真机实发 1 条图文回复,升级后用自动核对对同一条回复写入 `SENT` 回执。待核对清空,任务完成 7/7。这次发布和回执分两段验收。APK v2 签名校验和 43 项 JVM 单测通过。
0.1.19 在 vivo Android 12、抖音 39.8.0 上完成连续真机验收。单次启动后自动搜索、匹配原评论、实发 1 条图文回复,在同一回复内核对正文及 1 张绑定图后自动写入 `SENT`。启动至回执用时 89 秒,待核对为 0。APK v2 签名校验和 45 项 JVM 单测通过。
+2 -2
View File
@@ -13,8 +13,8 @@ android {
applicationId = "com.jieliu.app"
minSdk = 26
targetSdk = 35
versionCode = 8
versionName = "0.1.7"
versionCode = 20
versionName = "0.1.19"
}
compileOptions {
@@ -9,8 +9,6 @@ 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.DeepSeekReplies
import com.jieliu.app.task.ReplyMode
import com.jieliu.app.task.TaskCheckpoint
import com.jieliu.app.task.TaskRunner
import com.jieliu.app.task.pauseFor
@@ -84,29 +82,24 @@ internal object TaskControl {
check(active == null) { "任务正在运行。" }
val service = checkNotNull(connected) { "请先在系统设置中开启「拾见任务服务」。" }
val saved = store.readCheckpoint()
val rechecking = resume && saved?.pending != null
val plan = if (resume) {
checkNotNull(saved) { "当前没有可恢复的任务。" }
check(!saved.complete) { "任务已经完成。" }
check(saved.pending == null) { "请先核对待确认的评论。" }
saved.plan
check(!rechecking || saved.canAutomaticallyRecheck()) { "这条回复需要人工核对。" }
saved.plan.migrateContentTypes()
} else {
check(saved == null || saved.complete) { "请先继续或放弃已有任务。" }
store.readPlan()
}
plan.validate()
require(plan.searchTypes().isNotEmpty()) { "请先配置一个要搜索的内容类型。" }
val spec = checkNotNull(PlatformRegistry.platforms.firstOrNull { it.id == plan.platformId && it.implemented }) {
"当前平台适配尚未实现。"
}
check(service.packageManager.getLaunchIntentForPackage(spec.packageName) != null) { "请先安装${spec.label}。" }
val modelReply: ((String, String, List<String>) -> String)? = if (plan.replyMode == ReplyMode.DEEPSEEK) {
runCatching(store::readApiKey).getOrNull()?.let { key ->
DeepSeekReplies(key).let { client ->
{ keyword, title, comments -> client.generate(plan, keyword, title, comments) }
}
}
} else null
val initial = (if (resume) saved!! else TaskCheckpoint(UUID.randomUUID().toString(), plan))
.copy(message = "任务准备运行")
.copy(plan = plan, message = if (rechecking) "正在准备自动核对回复" else "任务准备运行")
val run = Run(service, store, initial)
val cancelled = { run.cancelled }
val platform = PlatformRegistry.create(plan.platformId, service, cancelled) {
@@ -115,7 +108,7 @@ internal object TaskControl {
}
run.work = Runnable {
try {
TaskRunner(store, plan, platform, modelReply, cancelled) { run.status = it }.run(initial)
TaskRunner(store, plan, platform, cancelled) { run.status = it }.run(initial, recheckPending = rechecking)
} finally {
main.post {
if (active === run) {
+412 -195
View File
@@ -15,9 +15,7 @@ import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import android.view.WindowInsets
@@ -25,7 +23,6 @@ import android.view.inputmethod.InputMethodManager
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.ImageView
@@ -38,25 +35,46 @@ 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.task.ContentType
import com.jieliu.app.task.KeywordRule
import com.jieliu.app.task.Outcome
import com.jieliu.app.task.ReplyMode
import com.jieliu.app.task.ReplyPhrase
import com.jieliu.app.task.TaskCheckpoint
import com.jieliu.app.task.TaskPlan
import com.jieliu.app.task.TemplatePhoto
import com.jieliu.app.task.normalizeKeyword
import java.util.UUID
import java.util.concurrent.FutureTask
class MainActivity : Activity() {
private enum class Tab { TASK, SETTINGS, LOGS }
private data class TaskView(
val checkpoint: TaskCheckpoint?, val connected: Boolean, val step: String?, val notificationsOff: Boolean,
val canAutomaticallyRecheck: Boolean,
)
private data class PhotoTarget(val group: String, val phrase: String)
private data class PhotoTarget(val typeId: String, val ruleId: String, val phraseId: String)
private data class TemplateDraft(
val types: List<ContentType>,
val scopeId: String?,
val typeId: String?,
val ruleId: String?,
val phraseId: String?,
)
private data class PhotoImport(
val target: PhotoTarget,
val results: FutureTask<List<TemplatePhoto?>>,
val overLimit: Int,
)
private data class RetainedTemplates(val draft: TemplateDraft?, val photoImport: PhotoImport?)
private val store: LocalStore get() = (application as ShijianApp).store
private val photos by lazy { PhotoLibrary(applicationContext) }
private val handler = Handler(Looper.getMainLooper())
private val refresh = object : Runnable {
override fun run() {
finishPhotoImport()
renderCurrent()
handler.postDelayed(this, 600L)
}
@@ -66,15 +84,25 @@ class MainActivity : Activity() {
private lateinit var tabs: List<Button>
private var selected = Tab.TASK
private var configView: View? = null
private var templateFields: TemplateFields? = null
private var templateFields: ContentFields? = null
private var restoredTemplates: TemplateDraft? = null
private var photoTarget: PhotoTarget? = null
private var importingPhoto = false
private var photoImport: PhotoImport? = null
private var taskView: TaskView? = null
private var logVersion = -1L
override fun onCreate(state: Bundle?) {
super.onCreate(state)
state?.getString("photoPhrase")?.let { photoTarget = PhotoTarget(state.getString("photoGroup").orEmpty(), it) }
@Suppress("DEPRECATION")
val retained = lastNonConfigurationInstance as? RetainedTemplates
restoredTemplates = retained?.draft
photoImport = retained?.photoImport
if (state != null) {
val typeId = state.getString("photoTypeId")
val ruleId = state.getString("photoRuleId")
val phraseId = state.getString("photoPhraseId")
if (typeId != null && ruleId != null && phraseId != null) photoTarget = PhotoTarget(typeId, ruleId, phraseId)
}
if (Build.VERSION.SDK_INT in 30..34) configureEdgeToEdge()
setContentView(R.layout.activity_main)
val root = findViewById<View>(R.id.root)
@@ -95,45 +123,89 @@ class MainActivity : Activity() {
override fun onSaveInstanceState(outState: Bundle) {
outState.putInt("tab", selected.ordinal)
photoTarget?.let {
outState.putString("photoGroup", it.group)
outState.putString("photoPhrase", it.phrase)
outState.putString("photoTypeId", it.typeId)
outState.putString("photoRuleId", it.ruleId)
outState.putString("photoPhraseId", it.phraseId)
}
super.onSaveInstanceState(outState)
}
@Deprecated("Activity non-configuration state retains in-memory photo edits and imports")
override fun onRetainNonConfigurationInstance(): Any =
RetainedTemplates(templateFields?.snapshot() ?: restoredTemplates, photoImport)
@Suppress("DEPRECATION")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode != PICK_TEMPLATE_PHOTO) return
val target = photoTarget ?: return
photoTarget = null
val uri = data?.data?.takeIf { resultCode == RESULT_OK } ?: return
val fields = templateFields ?: return
importingPhoto = true
fields.renderPhoto()
Thread {
val imported = runCatching { photos.importPhoto(uri) }
runOnUiThread {
if (isDestroyed) return@runOnUiThread
importingPhoto = false
imported.onSuccess { photo ->
if (fields.bind(target, photo)) toast("已绑定图片,点「保存配置」后生效。")
else toast("对应话术已变更,请重新选择图片。")
}.onFailure { error -> toast(error.message ?: "图片导入失败。") }
fields.renderPhoto()
if (resultCode != RESULT_OK || data == null) return
val fields = templateFields
val remaining = fields?.remainingFor(target)
if (fields == null || remaining == null) {
toast("找不到这条话术,请重新选择图片。")
return
}
}.start()
val uris = buildList {
data.clipData?.let { clip ->
for (index in 0 until clip.itemCount) clip.getItemAt(index).uri?.let(::add)
}
data.data?.let(::add)
}.distinct()
if (uris.isEmpty()) return
if (remaining == 0) {
toast("每条话术最多绑定 ${TaskPlan.MAX_TEMPLATE_PHOTOS} 张图片。")
return
}
val library = photos
val work = FutureTask {
uris.take(remaining).map { uri ->
try {
library.importPhoto(uri)
} catch (_: Exception) {
null
}
}
}
photoImport = PhotoImport(target, work, (uris.size - remaining).coerceAtLeast(0))
fields.renderPhoto()
Thread(work, "template-photo-import").start()
}
private fun finishPhotoImport() {
val batch = photoImport?.takeIf { it.results.isDone } ?: return
val fields = templateFields ?: return
photoImport = null
val results = runCatching { batch.results.get() }.getOrElse {
fields.renderPhoto()
toast("图片导入失败。")
return
}
val imported = results.filterNotNull()
if (imported.isNotEmpty() && !fields.append(batch.target, imported)) {
toast("找不到这条话术,图片未绑定。")
} else {
toast(buildList {
if (imported.isNotEmpty()) add("已绑定 ${imported.size} 张图片,点「保存配置」后生效。")
val failed = results.size - imported.size
if (failed > 0) add("$failed 张图片无法导入。")
if (batch.overLimit > 0) add("超出数量上限的 ${batch.overLimit} 张图片未导入。")
}.joinToString(" "))
}
fields.renderPhoto()
}
@Suppress("DEPRECATION")
private fun choosePhoto(group: String, phrase: String) {
private fun choosePhoto(target: PhotoTarget) {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "image/*"
putExtra(Intent.EXTRA_MIME_TYPES, arrayOf("image/jpeg", "image/png"))
putExtra(Intent.EXTRA_LOCAL_ONLY, true)
putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
}
photoTarget = PhotoTarget(group, phrase)
photoTarget = target
try {
startActivityForResult(intent, PICK_TEMPLATE_PHOTO)
} catch (error: Exception) {
@@ -183,7 +255,8 @@ class MainActivity : Activity() {
if (content.childCount == 0) replace(errorPage("无法读取任务检查点"))
return
}
val view = TaskView(checkpoint, TaskControl.isConnected, TaskControl.status, needsNotificationPermission())
val view = TaskView(checkpoint, TaskControl.isConnected, TaskControl.status, needsNotificationPermission(),
checkpoint?.canAutomaticallyRecheck() == true)
if (view == taskView) return
taskView = view
replace(guardedPage { taskPage(view) })
@@ -195,6 +268,7 @@ class MainActivity : Activity() {
val active = view.step != null
val plan = checkpoint?.plan ?: store.readPlan()
val platform = PlatformRegistry.platforms.firstOrNull { it.id == plan.platformId }?.label ?: plan.platformId
val searchTypes = plan.searchTypes()
val completed = checkpoint?.receipts?.size ?: 0
val title = when {
active -> "运行中"
@@ -205,18 +279,22 @@ class MainActivity : Activity() {
}
return column().apply {
addView(card(title).apply {
addView(label("$platform · ${plan.replyMode.label}", 15))
addView(label(view.step ?: checkpoint?.message ?: "关键词 ${plan.keywords.size} 个 · 单次 ${plan.limit} 条", 15))
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))
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 个视频,共 $limit 个"
}, LinearLayout.LayoutParams(-1, dp(18)))
addView(label("已处理 $completed / $limit · 已确认发送 ${checkpoint?.sentCount ?: 0}", 14))
val keyword = checkpoint?.keyword ?: plan.keywords.firstOrNull()
if (keyword != null && checkpoint?.complete != true) addView(label("关键词 $keyword", 14))
addView(label("已处理视频 $completed / $limit · 已确认回复 ${checkpoint?.sentCount ?: 0} 条", 14))
if (plan.replyMode != ReplyMode.BROWSE) checkpoint?.activeVideo?.let { video ->
addView(label("当前视频已确认回复 ${video.sentCount} / ${plan.repliesPerVideo}", 14))
}
val searchType = checkpoint?.keyword ?: searchTypes.firstOrNull()?.name
if (searchType != null && checkpoint?.complete != true) addView(label("内容类型 · $searchType", 14))
})
if (!view.connected) {
addView(card("无障碍服务未连接").apply {
@@ -227,10 +305,15 @@ 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)) }
addView(label(pending.text, 15))
pending.photo?.let { addView(photoPreview(it)) }
addView(action("确认已发送", primary = true) { reconcile(Outcome.USER_CONFIRMED) })
addView(action("跳过这条视频") { reconcile(Outcome.SKIPPED) })
pending.photos.forEachIndexed { index, photo -> addView(photoPreview(photo, index)) }
if (view.canAutomaticallyRecheck) {
addView(action("自动核对回复", 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) })
})
}
when {
@@ -255,198 +338,270 @@ class MainActivity : Activity() {
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 mode = choices(ReplyMode.entries.map { it.label }, plan.replyMode.ordinal)
val keywords = field(plan.keywords.joinToString("\n"), "每行一个关键词", multiline = true)
val templates = TemplateFields(keywords, plan).also { templateFields = it }
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 {
templateFields = it
restoredTemplates = null
}
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 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)
val actionMax = field(plan.actionMillis.last.toString(), "最长", number = true)
val key = field("", if (store.hasApiKey()) "已设置,留空沿用" else "粘贴 API Key", secret = true)
val removeKey = CheckBox(this).apply { setText(R.string.clear_deepseek_key) }
val model = field(plan.model, "deepseek-flash")
val instructions = field(plan.instructions, "描述希望生成的评论", multiline = true)
return column().apply {
addView(card("任务范围").apply {
addField("平台", platform)
addField("搜索关键词", keywords)
addField("单次任务总数", limit)
addField("搜索范围", libraries.scope)
addField("单次任务视频上限", limit)
})
addView(card("动作节奏").apply {
addRange("观看时长(秒)", watchMin, watchMax)
addRange("动作间隔(毫秒)", actionMin, actionMax)
})
addView(card("评论").apply {
addView(card("评论设置").apply {
addField("处理方式", mode)
addField("话术分组", templates.group)
addField("话术库", templates.editor)
addView(label("先从当前关键词分组随机选一条。该分组为空时使用通用分组。支持 {keyword} 和 {title}。", 14))
if (Build.VERSION.SDK_INT >= 29) {
addField("绑定到话术", templates.photoPhrase)
addView(templates.photoControls)
addView(label("每条话术可绑定一张本机照片。改写话术后需重新绑定。", 14))
} else {
addView(label("图片评论需要 Android 10 或更新版本。", 14))
}
addField("每条视频回复上限", repliesPerVideo)
addView(label("达到回复上限或找不到更多匹配评论时,进入下一个视频。", 14))
})
addView(card("DeepSeek").apply {
addView(label("启用兜底后,没有可用话术时才调用 DeepSeek。请求包含关键词、视频标题和可见评论样本。缺少话术且未设置 API Key 时跳过该视频。", 14))
addField("API Key", key)
addView(removeKey)
addField("模型", model)
addField("生成说明", instructions)
addView(card("内容库").apply {
addView(label("按内容类型搜索视频,按关键词匹配评论。每个关键词可配置多条话术。", 14))
addView(libraries.editor)
})
addView(action("保存配置", primary = true) {
check(!importingPhoto) { "请等待图片导入完成。" }
check(photoImport == null) { "请等待图片导入完成。" }
val spec = specs[platform.selectedItemPosition]
require(spec.implemented) { "${spec.label}还未适配,请选择抖音。" }
val replacementKey = if (removeKey.isChecked) "" else key.value().ifBlank { null }
require(replacementKey == null || replacementKey.length <= 256 && replacementKey.all { it.code in 33..126 }) {
"API Key 包含无效字符。"
}
val activeKeywords = keywords.lines()
val updated = TaskPlan(
val updated = plan.copy(
platformId = spec.id,
keywords = activeKeywords,
templates = templates.lines(null),
limit = limit.number("单次任务总数"),
limit = limit.number("单次任务视频上限"),
repliesPerVideo = repliesPerVideo.number("每条视频回复上限"),
watchSeconds = watchMin.number("观看下限")..watchMax.number("观看上限"),
actionMillis = actionMin.number("间隔下限")..actionMax.number("间隔上限"),
replyMode = ReplyMode.entries[mode.selectedItemPosition],
model = model.value().ifBlank { TaskPlan().model },
instructions = instructions.value(),
keywordTemplates = activeKeywords.mapNotNull { keyword ->
templates.lines(keyword).takeIf { it.isNotEmpty() }?.let { keyword to it }
}.toMap(),
templatePhotos = templates.photoBindings(activeKeywords),
replyMode = modes[mode.selectedItemPosition],
contentTypes = libraries.contentTypes,
selectedTypeId = libraries.selectedScopeId(),
)
store.saveSettings(updated, replacementKey)
templates.retainSavedBindings(updated.templatePhotos)
runCatching {
store.saveSettings(updated, null)
if (!TaskControl.inProgress) runCatching {
val checkpoint = store.readCheckpoint()
photos.pruneImports(
updated.photoIds() + checkpoint?.takeUnless { it.complete }?.plan?.photoIds().orEmpty() +
listOfNotNull(checkpoint?.pending?.photo?.id),
checkpoint?.pending?.photos.orEmpty().map(TemplatePhoto::id),
)
}
key.text.clear()
key.hint = if (store.hasApiKey()) "已设置,留空沿用" else "粘贴 API Key"
removeKey.isChecked = false
toast("配置已保存,下次新任务生效。")
toast("配置已保存。关键词、话术和图片在下次读取评论时生效。")
})
}
}
private inner class TemplateFields(private val keywords: EditText, plan: TaskPlan) {
private val drafts = mutableMapOf<String?, String>(null to plan.templates.joinToString("\n"))
private val bindings = plan.templatePhotos.mapValues { (_, values) -> values.toMutableMap() }.toMutableMap()
private var options: List<String?> = listOf(null)
private var selectedKeyword: String? = null
val group = choices(listOf("通用"), 0)
val editor = field(drafts[null].orEmpty(), "每行一条话术", multiline = true)
private var photoOptions = emptyList<String>()
private var drawnPhoto: Triple<PhotoTarget?, TemplatePhoto?, Boolean>? = null
val photoPhrase = choices(listOf("先填写一条话术"), 0)
val photoControls = column()
private inner class ContentFields(plan: TaskPlan, restored: TemplateDraft?) {
var contentTypes: List<ContentType> = restored?.types ?: plan.contentTypes.orEmpty()
private set
private var typeId = restored?.typeId
private var ruleId = restored?.ruleId
private var phraseId = restored?.phraseId
private var scopeIds = listOf<String?>(null)
val scope = choices(listOf("全部内容类型"), 0)
val editor = column()
private val photoControls = column()
private var drawnPhoto: Triple<PhotoTarget?, List<TemplatePhoto>, Boolean>? = null
init {
plan.keywordTemplates.forEach { (keyword, lines) -> drafts[keyword] = lines.joinToString("\n") }
updateOptions()
group.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
if (position in options.indices) show(options[position])
renderScope(if (restored != null) restored.scopeId else plan.selectedTypeId)
renderEditor()
}
override fun onNothingSelected(parent: AdapterView<*>) = Unit
}
keywords.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(text: CharSequence?, start: Int, count: Int, after: Int) = Unit
override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) = Unit
override fun afterTextChanged(text: Editable?) = updateOptions()
})
photoPhrase.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) = renderPhoto()
override fun onNothingSelected(parent: AdapterView<*>) = renderPhoto()
}
editor.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(text: CharSequence?, start: Int, count: Int, after: Int) = Unit
override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) = Unit
override fun afterTextChanged(text: Editable?) = updatePhotoChoices()
})
updatePhotoChoices()
}
fun selectedScopeId() = scopeIds.getOrNull(scope.selectedItemPosition)
fun lines(keyword: String?): List<String> =
(if (selectedKeyword == keyword) editor.text.toString() else drafts[keyword].orEmpty()).nonblankLines()
fun snapshot() = TemplateDraft(contentTypes, selectedScopeId(), typeId, ruleId, phraseId)
fun photoBindings(activeKeywords: List<String>): Map<String, Map<String, TemplatePhoto>> =
(listOf("") + activeKeywords).mapNotNull { key ->
val phrases = lines(key.ifEmpty { null }).toSet()
bindings[key]?.filterKeys { it in phrases }?.takeIf { it.isNotEmpty() }?.let { key to it }
}.toMap()
fun remainingFor(target: PhotoTarget): Int? =
findPhrase(target)?.let { (TaskPlan.MAX_TEMPLATE_PHOTOS - it.photos.size).coerceAtLeast(0) }
fun retainSavedBindings(saved: Map<String, Map<String, TemplatePhoto>>) {
bindings.clear()
saved.forEach { (key, photos) -> bindings[key] = photos.toMutableMap() }
renderPhoto()
}
fun bind(target: PhotoTarget, photo: TemplatePhoto): Boolean {
if (target.group.isNotEmpty() && target.group !in keywords.lines() ||
target.phrase !in lines(target.group.ifEmpty { null })
) return false
bindings.getOrPut(target.group) { mutableMapOf() }[target.phrase] = photo
fun append(target: PhotoTarget, incoming: List<TemplatePhoto>): Boolean {
val current = findPhrase(target) ?: return false
if (current.photos.size + incoming.size > TaskPlan.MAX_TEMPLATE_PHOTOS) return false
updatePhrase(target, current.copy(photos = current.photos + incoming))
return true
}
private fun renderScope(previous: String?) {
scopeIds = listOf(null) + contentTypes.map(ContentType::id)
scope.adapter = choiceAdapter(listOf("全部内容类型") + contentTypes.map(ContentType::name))
scope.setSelection(scopeIds.indexOf(previous).coerceAtLeast(0))
}
private fun renderEditor() {
val type = contentTypes.find { it.id == typeId } ?: contentTypes.firstOrNull()
val rule = type?.rules?.let { rules -> rules.find { it.id == ruleId } ?: rules.firstOrNull() }
val phrase = rule?.phrases?.let { phrases -> phrases.find { it.id == phraseId } ?: phrases.firstOrNull() }
typeId = type?.id
ruleId = rule?.id
phraseId = phrase?.id
editor.removeAllViews()
editor.addField("内容类型", libraryChoices(contentTypes.map { it.id to it.name }, typeId, "请先新增内容类型") {
typeId = it
ruleId = null
phraseId = null
renderEditor()
})
editor.addView(libraryActions("内容类型", type != null, { editType(null) }, { editType(checkNotNull(type)) }) {
val target = checkNotNull(type)
confirmDelete("删除「${target.name}」及其中的关键词、话术和图片绑定?") {
val previous = selectedScopeId()
contentTypes = contentTypes.filterNot { it.id == target.id }
renderScope(previous)
renderEditor()
}
})
if (type == null) return
editor.addField("关键词", libraryChoices(type.rules.map { it.id to it.keyword }, ruleId, "请先新增关键词") {
ruleId = it
phraseId = null
renderEditor()
})
editor.addView(libraryActions("关键词", rule != null, { editRule(type, null) }, { editRule(type, checkNotNull(rule)) }) {
val target = checkNotNull(rule)
confirmDelete("删除关键词「${target.keyword}」及其话术和图片绑定?") {
val latest = findType(type.id) ?: return@confirmDelete
updateType(latest.copy(rules = latest.rules.filterNot { it.id == target.id }))
renderEditor()
}
})
if (rule == null) return
editor.addField("回复话术", libraryChoices(rule.phrases.mapIndexed { index, item ->
item.id to "${index + 1}. ${item.text.replace('\n', ' ')}"
}, phraseId, "请先新增话术") {
phraseId = it
renderEditor()
})
editor.addView(libraryActions("话术", phrase != null, { editPhrase(type, rule, null) }, { editPhrase(type, rule, checkNotNull(phrase)) }) {
val target = checkNotNull(phrase)
confirmDelete("删除这条话术及其图片绑定?") {
val latestType = findType(type.id) ?: return@confirmDelete
val latestRule = latestType.rules.find { it.id == rule.id } ?: return@confirmDelete
updateRule(latestType, latestRule.copy(phrases = latestRule.phrases.filterNot { it.id == target.id }))
renderEditor()
}
})
if (Build.VERSION.SDK_INT >= 29) {
editor.addView(photoControls)
renderPhoto()
} else {
editor.addView(label("图片回复需要 Android 10 或更新版本。", 14))
}
}
private fun editType(existing: ContentType?) {
editLibraryText(if (existing == null) "新增内容类型" else "编辑内容类型", existing?.name.orEmpty(), "内容类型名称") { name ->
require(name.length <= 120 && normalizeKeyword(name).isNotEmpty()) { "内容类型名称最多 120 个字符。" }
val previous = selectedScopeId()
val updated = if (existing == null) ContentType(UUID.randomUUID().toString(), name)
else checkNotNull(findType(existing.id)).copy(name = name)
if (existing == null) contentTypes = contentTypes + updated else updateType(updated)
typeId = updated.id
renderScope(previous)
renderEditor()
}
}
private fun editRule(type: ContentType, existing: KeywordRule?) {
editLibraryText(if (existing == null) "新增关键词" else "编辑关键词", existing?.keyword.orEmpty(), "一个关键词") { keyword ->
val latest = checkNotNull(findType(type.id))
require(keyword.length <= 120 && keyword.none { it == '\n' || it == '\r' }) { "每个关键词最多 120 个字符,请填一行。" }
val normalized = normalizeKeyword(keyword)
require(normalized.isNotEmpty()) { "请输入有效关键词。" }
require(latest.rules.none { it.id != existing?.id && normalizeKeyword(it.keyword) == normalized }) {
"这个内容类型已有相同的关键词。"
}
val updated = if (existing == null) KeywordRule(UUID.randomUUID().toString(), keyword)
else checkNotNull(latest.rules.find { it.id == existing.id }).copy(keyword = keyword)
updateRule(latest, updated)
ruleId = updated.id
renderEditor()
}
}
private fun editPhrase(type: ContentType, rule: KeywordRule, existing: ReplyPhrase?) {
editLibraryText(if (existing == null) "新增话术" else "编辑话术", existing?.text.orEmpty(), "输入回复文字", multiline = true) { text ->
val latestType = checkNotNull(findType(type.id))
val latestRule = checkNotNull(latestType.rules.find { it.id == rule.id })
require(text.codePointCount(0, text.length) <= TaskPlan.MAX_COMMENT) { "每条话术最多 ${TaskPlan.MAX_COMMENT} 个字符。" }
require(existing != null || latestRule.phrases.size < TaskPlan.MAX_RULE_PHRASES) {
"每个关键词最多 ${TaskPlan.MAX_RULE_PHRASES} 条话术。"
}
val updated = if (existing == null) ReplyPhrase(UUID.randomUUID().toString(), text)
else checkNotNull(latestRule.phrases.find { it.id == existing.id }).copy(text = text)
val phrases = if (existing == null) latestRule.phrases + updated else latestRule.phrases.map {
if (it.id == updated.id) updated else it
}
updateRule(latestType, latestRule.copy(phrases = phrases))
phraseId = updated.id
renderEditor()
}
}
private fun updateType(updated: ContentType) {
contentTypes = contentTypes.map { if (it.id == updated.id) updated else it }
}
private fun updateRule(type: ContentType, updated: KeywordRule) {
val rules = if (type.rules.none { it.id == updated.id }) type.rules + updated
else type.rules.map { if (it.id == updated.id) updated else it }
updateType(type.copy(rules = rules))
}
private fun findType(id: String): ContentType? = contentTypes.find { it.id == id }
private fun findPhrase(target: PhotoTarget): ReplyPhrase? = findType(target.typeId)
?.rules?.find { it.id == target.ruleId }?.phrases?.find { it.id == target.phraseId }
private fun updatePhrase(target: PhotoTarget, updated: ReplyPhrase) {
val type = findType(target.typeId) ?: return
val rule = type.rules.find { it.id == target.ruleId } ?: return
updateRule(type, rule.copy(phrases = rule.phrases.map { if (it.id == target.phraseId) updated else it }))
}
fun renderPhoto() {
val target = photoOptions.getOrNull(photoPhrase.selectedItemPosition)
?.let { PhotoTarget(selectedKeyword.orEmpty(), it) }
val photo = target?.let { bindings[it.group]?.get(it.phrase) }
val state = Triple(target, photo, importingPhoto)
val target = typeId?.let { type -> ruleId?.let { rule -> phraseId?.let { PhotoTarget(type, rule, it) } } }
val current = target?.let(::findPhrase)
val entries = current?.photos.orEmpty()
val importing = photoImport != null
val state = Triple(target, entries, importing)
if (drawnPhoto == state) return
drawnPhoto = state
photoControls.removeAllViews()
if (target == null) return
if (photo != null) photoControls.addView(photoPreview(photo))
photoControls.addView(action(if (importingPhoto) "正在导入图片…" else if (photo == null) "选择本机图片" else "更换图片") {
choosePhoto(target.group, target.phrase)
}.apply { applyEnabled(!importingPhoto) })
if (photo != null) photoControls.addView(action("移除图片") {
bindings[target.group]?.remove(target.phrase)
if (target == null || current == null) return
photoControls.addView(label("已绑定 ${entries.size} / ${TaskPlan.MAX_TEMPLATE_PHOTOS} 张图片", 14))
entries.forEachIndexed { index, photo ->
photoControls.addView(photoPreview(photo, index))
val operations = listOf(
Triple("上移", index > 0, index - 1),
Triple("下移", index < entries.lastIndex, index + 1),
Triple("移除图片", true, null),
)
photoControls.addView(buttonRow(operations.map { (title, available, movedTo) ->
action(title) {
val latest = findPhrase(target) ?: return@action
if (latest.photos != entries || photoImport != null) return@action
val reordered = entries.toMutableList()
val selectedPhoto = reordered.removeAt(index)
if (movedTo != null) reordered.add(movedTo, selectedPhoto)
updatePhrase(target, latest.copy(photos = reordered))
renderPhoto()
}.apply { applyEnabled(!importingPhoto) })
}.apply {
contentDescription = if (movedTo == null) "移除第 ${index + 1} 张图片" else "${title}第 ${index + 1} 张图片"
applyEnabled(available && !importing)
}
private fun updatePhotoChoices() {
if (Build.VERSION.SDK_INT < 29) return
val previous = photoOptions.getOrNull(photoPhrase.selectedItemPosition)
val current = lines(selectedKeyword).distinct()
if (photoOptions != current) {
photoOptions = current
photoPhrase.adapter = choiceAdapter(current.ifEmpty { listOf("先填写一条话术") })
photoPhrase.setSelection(current.indexOf(previous).coerceAtLeast(0))
}))
}
photoPhrase.isEnabled = current.isNotEmpty()
renderPhoto()
}
private fun show(keyword: String?) {
if (selectedKeyword == keyword) return
drafts[selectedKeyword] = editor.text.toString()
selectedKeyword = keyword
editor.setText(drafts[keyword].orEmpty())
}
private fun updateOptions() {
val updated = listOf(null) + keywords.lines()
if (options == updated) return
options = updated
val position = options.indexOf(selectedKeyword).coerceAtLeast(0)
show(options[position])
group.adapter = choiceAdapter(options.map { if (it == null) "通用" else "关键词 · $it" })
group.setSelection(position)
photoControls.addView(action(if (importing) "正在导入图片…" else "添加本机图片") { choosePhoto(target) }
.apply { applyEnabled(!importing && entries.size < TaskPlan.MAX_TEMPLATE_PHOTOS) })
photoControls.addView(label("支持 JPEG 和 PNG。修改名称、关键词或话术时,保留已绑定图片。", 14))
}
}
@@ -458,22 +613,30 @@ class MainActivity : Activity() {
})
}
private fun photoPreview(photo: TemplatePhoto) = column().apply {
addView(label("图片 · ${photo.displayName}", 14))
photos.thumbnail(photo)?.let { bitmap ->
private fun photoPreview(photo: TemplatePhoto, index: Int) = column().apply {
addView(label("图片 ${index + 1} · ${photo.displayName}", 14))
val bitmap = photos.thumbnail(photo)
if (bitmap == null) {
addView(label("图片缺失或无法预览。", 14, color = ALERT))
} else {
addView(ImageView(this@MainActivity).apply {
setImageBitmap(bitmap)
adjustViewBounds = true
scaleType = ImageView.ScaleType.FIT_CENTER
contentDescription = "已绑定图片预览"
contentDescription = "第 ${index + 1} 张图片预览"
}, LinearLayout.LayoutParams(dp(96), dp(76)))
}
}
private fun reconcile(outcome: Outcome) {
val before = checkNotNull(store.readCheckpoint())
val expected = checkNotNull(before.pending) { "当前没有待核对的评论。" }
val photoCount = expected.photos.size
val prompt = when {
outcome != Outcome.USER_CONFIRMED && before.activeVideo != null -> "跳过当前回复并继续核对后的任务进度?"
outcome != Outcome.USER_CONFIRMED -> "跳过这条视频并计入本次进度?"
store.readCheckpoint()?.pending?.photo != null -> "已在目标应用看到这条评论的文字和图片?"
photoCount == 1 -> "已在目标应用看到这条评论的文字和图片?"
photoCount > 1 -> "已在目标应用看到这条评论的文字和全部 $photoCount 张图片?"
else -> "已在目标应用看到这条评论?"
}
AlertDialog.Builder(this).setMessage(prompt)
@@ -481,10 +644,15 @@ class MainActivity : Activity() {
.setPositiveButton("确认") { _, _ -> perform {
check(!TaskControl.inProgress) { "请先暂停任务。" }
val checkpoint = checkNotNull(store.readCheckpoint())
val pending = checkNotNull(checkpoint.pending) { "当前没有待核对的评论。" }
store.saveCheckpoint(checkpoint.finish(pending.videoKey, outcome))
if (pending.photo != null) Thread { photos.cleanupStaged() }.start()
store.appendLog(if (outcome == Outcome.USER_CONFIRMED) "用户确认上一条评论已发送" else "用户跳过待核对的视频")
check(checkpoint.id == before.id && checkpoint.pending == expected) { "待核对的评论已变化,请重新打开。" }
store.saveCheckpoint(checkpoint.recordReply(outcome))
if (expected.photos.isNotEmpty()) Thread { photos.cleanupStaged() }.start()
val message = when {
outcome == Outcome.USER_CONFIRMED -> "用户确认上一条评论已发送"
checkpoint.activeVideo != null -> "用户跳过待核对的回复"
else -> "用户跳过待核对的视频"
}
store.appendLog(message)
renderTask()
} }.show()
}
@@ -530,17 +698,68 @@ class MainActivity : Activity() {
setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
}
private fun field(value: String, hint: String, multiline: Boolean = false, number: Boolean = false, secret: Boolean = false) = EditText(this).apply {
private fun libraryChoices(entries: List<Pair<String, String>>, selectedId: String?, placeholder: String, select: (String) -> Unit): Spinner =
choices(entries.map { it.second }.ifEmpty { listOf(placeholder) }, entries.indexOfFirst { it.first == selectedId }.coerceAtLeast(0)).apply {
isEnabled = entries.isNotEmpty()
onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
entries.getOrNull(position)?.first?.takeIf { it != selectedId }?.let(select)
}
override fun onNothingSelected(parent: AdapterView<*>) = Unit
}
}
private fun libraryActions(entity: String, hasSelection: Boolean, add: () -> Unit, edit: () -> Unit, delete: () -> Unit) =
buttonRow(listOf(
action("新增", click = add).apply { contentDescription = "新增$entity" },
action("编辑", click = edit).apply {
contentDescription = "编辑$entity"
applyEnabled(hasSelection)
},
action("删除", click = delete).apply {
contentDescription = "删除$entity"
applyEnabled(hasSelection)
},
))
private fun buttonRow(buttons: List<Button>) = LinearLayout(this).apply {
buttons.forEach { button ->
addView(button, LinearLayout.LayoutParams(0, -2, 1f).apply { marginEnd = dp(4) })
}
}
private fun editLibraryText(title: String, value: String, hint: String, multiline: Boolean = false, save: (String) -> Unit) {
val input = field(value, hint, multiline).apply { contentDescription = hint }
val fields = column().apply {
setPadding(dp(20), dp(12), dp(20), 0)
addView(input, LinearLayout.LayoutParams(-1, -2))
}
val dialog = AlertDialog.Builder(this).setTitle(title).setView(fields)
.setNegativeButton("取消", null).setPositiveButton("完成", null).show()
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
perform {
val text = input.value()
require(text.isNotBlank()) { "请填写$hint。" }
save(text)
dialog.dismiss()
}
}
input.requestFocus()
}
private fun confirmDelete(prompt: String, delete: () -> Unit) {
AlertDialog.Builder(this).setMessage(prompt).setNegativeButton("取消", null)
.setPositiveButton("删除") { _, _ -> perform(delete) }.show()
}
private fun field(value: String, hint: String, multiline: Boolean = false, number: Boolean = false) = EditText(this).apply {
isSingleLine = !multiline
inputType = when {
number -> InputType.TYPE_CLASS_NUMBER
secret -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
multiline -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE
else -> InputType.TYPE_CLASS_TEXT
}
importantForAutofill = if (secret) View.IMPORTANT_FOR_AUTOFILL_NO else View.IMPORTANT_FOR_AUTOFILL_AUTO
isSaveEnabled = !secret
if (secret) typeface = Typeface.DEFAULT
if (multiline) { minLines = 2; maxLines = 6; gravity = Gravity.TOP }
setText(value)
this.hint = hint
@@ -615,8 +834,6 @@ class MainActivity : Activity() {
}
private fun EditText.value() = text.toString().trim()
private fun EditText.lines() = text.toString().nonblankLines()
private fun String.nonblankLines() = lineSequence().map(String::trim).filter(String::isNotEmpty).distinct().toList()
private fun EditText.number(label: String) = requireNotNull(value().toIntOrNull()) { "请填写有效的$label。" }
private fun dp(value: Int) = (resources.displayMetrics.density * value + .5f).toInt()
private fun toast(message: String) = Toast.makeText(this, message, Toast.LENGTH_LONG).show()
@@ -1,16 +1,22 @@
package com.jieliu.app.data
import android.content.Context
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.Receipt
import com.jieliu.app.task.ReplyMode
import com.jieliu.app.task.ReplyPhrase
import com.jieliu.app.task.ReplyReceipt
import com.jieliu.app.task.TaskCheckpoint
import com.jieliu.app.task.TaskPlan
import com.jieliu.app.task.TaskRunStorage
import com.jieliu.app.task.TemplatePhoto
import com.jieliu.app.task.TemplateUse
import com.jieliu.app.task.VideoProgress
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
@@ -31,7 +37,8 @@ class LocalStore(context: Context) : TaskRunStorage {
@Volatile var logVersion: Long = 0
private set
@Synchronized fun readPlan(): TaskPlan = settings.readJson()?.getJSONObject("plan")?.toPlan() ?: TaskPlan()
@Synchronized override fun readPlan(): TaskPlan =
(settings.readJson()?.getJSONObject("plan")?.toPlan() ?: TaskPlan()).migrateContentTypes()
@Synchronized fun hasApiKey(): Boolean = settings.readJson()?.has("deepSeekKey") == true
@@ -56,15 +63,27 @@ class LocalStore(context: Context) : TaskRunStorage {
val entries = json.getJSONArray("receipts")
val receipts = List(entries.length()) { index ->
val entry = entries.getJSONObject(index)
Receipt(entry.getString("key"), Outcome.valueOf(entry.getString("outcome")), entry.readTemplateUse())
Receipt(
entry.getString("key"), Outcome.valueOf(entry.getString("outcome")), entry.readTemplateUse(),
entry.optionalString("targetKey"), entry.readReplyReceipts(),
)
}
val pending = json.optJSONObject("pending")?.let {
PendingComment(
it.getString("key"), it.getString("title"), it.getString("text"), it.readTemplateUse(),
if (it.isNull("photo")) null else it.getJSONObject("photo").toTemplatePhoto(),
when {
!it.isNull("photos") -> it.getJSONArray("photos").toTemplatePhotos()
!it.isNull("photo") -> listOf(it.getJSONObject("photo").toTemplatePhoto())
else -> emptyList()
},
it.optionalString("targetKey"), it.optionalString("targetAuthor"),
(it.opt("armedAtEpochMs") as? Number)?.toLong(),
)
}
TaskCheckpoint(json.getString("id"), plan, receipts, pending, json.getString("message"))
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)
}
checkpointLoaded = true
return cachedCheckpoint
@@ -73,19 +92,31 @@ class LocalStore(context: Context) : TaskRunStorage {
@Synchronized override fun saveCheckpoint(checkpoint: TaskCheckpoint) {
val receipts = JSONArray(checkpoint.receipts.map {
JSONObject().put("key", it.videoKey).put("outcome", it.outcome.name)
.put("templateUse", it.templateUse?.toJson())
.put("templateUse", it.templateUse?.toJson()).put("targetKey", it.targetKey)
.put("replies", it.replies.takeIf { replies -> replies.isNotEmpty() }?.toReplyArray())
})
val body = JSONObject().put("id", checkpoint.id).put("plan", checkpoint.plan.toJson())
.put("receipts", receipts).put("message", checkpoint.message)
checkpoint.pending?.let {
body.put("pending", JSONObject().put("key", it.videoKey).put("title", it.title).put("text", it.text)
.put("templateUse", it.templateUse?.toJson()).put("photo", it.photo?.toJson()))
.put("templateUse", it.templateUse?.toJson()).put("photos", it.photos.toPhotoArray())
.put("targetKey", it.targetKey).put("targetAuthor", it.targetAuthor)
.put("armedAtEpochMs", it.armedAtEpochMs))
}
checkpoint.activeVideo?.let {
body.put("activeVideo", JSONObject().put("key", it.videoKey).put("replies", it.replies.toReplyArray()))
}
task.replaceWith(body)
cachedCheckpoint = checkpoint
checkpointLoaded = true
}
@Synchronized override fun savePendingIfCurrent(checkpoint: TaskCheckpoint, matchesPlan: (TaskPlan) -> Boolean): Boolean {
if (!matchesPlan(readPlan())) return false
saveCheckpoint(checkpoint)
return true
}
@Synchronized fun clearCheckpoint() {
Files.deleteIfExists(task.toPath())
cachedCheckpoint = null
@@ -131,8 +162,11 @@ class LocalStore(context: Context) : TaskRunStorage {
.put("platform", platformId).put("keywords", JSONArray(keywords)).put("templates", JSONArray(templates))
.put("keywordTemplates", JSONObject(keywordTemplates.mapValues { (_, lines) -> JSONArray(lines) }))
.put("templatePhotos", JSONObject(templatePhotos.mapValues { (_, photos) ->
JSONObject(photos.mapValues { (_, photo) -> photo.toJson() })
JSONObject(photos.mapValues { (_, binding) -> binding.toPhotoArray() })
}))
.put("contentTypes", contentTypes?.let { JSONArray(it.map { type -> type.toJson() }) })
.put("selectedTypeId", selectedTypeId)
.put("repliesPerVideo", repliesPerVideo)
.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)
@@ -153,20 +187,73 @@ class LocalStore(context: Context) : TaskRunStorage {
templatePhotos = if (isNull("templatePhotos")) emptyMap() else getJSONObject("templatePhotos").let { groups ->
groups.keys().asSequence().associateWith { group ->
val photos = groups.getJSONObject(group)
photos.keys().asSequence().associateWith { phrase -> photos.getJSONObject(phrase).toTemplatePhoto() }
photos.keys().asSequence().associateWith { phrase ->
when (val binding = photos.get(phrase)) {
is JSONArray -> binding.toTemplatePhotos()
is JSONObject -> listOf(binding.toTemplatePhoto())
else -> throw JSONException("无法读取话术图片。")
}
}
}
},
contentTypes = if (isNull("contentTypes")) null else getJSONArray("contentTypes").let { types ->
List(types.length()) { types.getJSONObject(it).toContentType() }
},
selectedTypeId = optionalString("selectedTypeId"),
repliesPerVideo = if (isNull("repliesPerVideo")) 1 else getInt("repliesPerVideo"),
)
private fun ContentType.toJson() = JSONObject().put("id", id).put("name", name)
.put("rules", JSONArray(rules.map { it.toJson() }))
private fun KeywordRule.toJson() = JSONObject().put("id", id).put("keyword", keyword)
.put("phrases", JSONArray(phrases.map { it.toJson() }))
private fun ReplyPhrase.toJson() = JSONObject().put("id", id).put("text", text).put("photos", photos.toPhotoArray())
private fun JSONObject.toContentType(): ContentType {
val rules = getJSONArray("rules")
return ContentType(getString("id"), getString("name"), List(rules.length()) { rules.getJSONObject(it).toKeywordRule() })
}
private fun JSONObject.toKeywordRule(): KeywordRule {
val phrases = getJSONArray("phrases")
return KeywordRule(getString("id"), getString("keyword"), List(phrases.length()) { phrases.getJSONObject(it).toReplyPhrase() })
}
private fun JSONObject.toReplyPhrase() = ReplyPhrase(
getString("id"), getString("text"), if (isNull("photos")) emptyList() else getJSONArray("photos").toTemplatePhotos(),
)
private fun TemplatePhoto.toJson() = JSONObject().put("id", id).put("displayName", displayName)
private fun JSONObject.toTemplatePhoto() = TemplatePhoto(getString("id"), getString("displayName"))
private fun TemplateUse.toJson() = JSONObject().put("group", group).put("index", index)
private fun List<TemplatePhoto>.toPhotoArray() = JSONArray(map { it.toJson() })
private fun JSONArray.toTemplatePhotos() = List(length()) { getJSONObject(it).toTemplatePhoto() }
private fun TemplateUse.toJson() = JSONObject().put("group", group).put("index", index).put("phraseId", phraseId)
private fun JSONObject.readTemplateUse() = optJSONObject("templateUse")?.let {
TemplateUse(it.getString("group"), it.getInt("index"))
TemplateUse(it.getString("group"), it.getInt("index"), it.optionalString("phraseId"))
}
private fun List<ReplyReceipt>.toReplyArray() = JSONArray(map { reply ->
JSONObject().put("targetKey", reply.targetKey).put("outcome", reply.outcome.name)
.put("templateUse", reply.templateUse?.toJson())
})
private fun JSONObject.readReplyReceipts(): List<ReplyReceipt> {
if (isNull("replies")) return emptyList()
val replies = getJSONArray("replies")
return List(replies.length()) { index ->
val reply = replies.getJSONObject(index)
ReplyReceipt(reply.getString("targetKey"), Outcome.valueOf(reply.getString("outcome")), reply.readTemplateUse())
}
}
private fun JSONObject.optionalString(key: String): String? = if (isNull(key)) null else getString(key)
private fun JSONArray.strings() = List(length(), ::getString)
}
@@ -7,6 +7,7 @@ import android.content.ContentValues
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import android.os.Bundle
@@ -16,6 +17,7 @@ import android.provider.MediaStore
import android.provider.MediaStore.MediaColumns
import android.provider.OpenableColumns
import android.util.Log
import com.jieliu.app.task.TaskPlan
import com.jieliu.app.task.TemplatePhoto
import java.io.File
import java.io.FileOutputStream
@@ -24,7 +26,7 @@ import java.nio.file.LinkOption.NOFOLLOW_LINKS
import java.nio.file.StandardCopyOption.ATOMIC_MOVE
import java.util.UUID
data class StagedPhoto(val albumName: String, val uri: Uri)
data class StagedPhotos(val albumName: String, val uris: List<Uri>)
class PhotoLibrary(context: Context) {
private val app = context.applicationContext
@@ -78,20 +80,41 @@ class PhotoLibrary(context: Context) {
}
}
fun stage(photo: TemplatePhoto): StagedPhoto = synchronized(lock) {
@TargetApi(Build.VERSION_CODES.P)
internal fun receiptThumbnail(photo: TemplatePhoto): Bitmap? = synchronized(lock) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) return@synchronized null
val source = importedFile(photo) ?: return@synchronized null
try {
ImageDecoder.decodeBitmap(ImageDecoder.createSource(source)) { decoder, info, _ ->
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
val width = info.size.width
val height = info.size.height
val scale = minOf(1.0, THUMBNAIL_SIDE.toDouble() / maxOf(width, height))
decoder.setTargetSize((width * scale).toInt().coerceAtLeast(1), (height * scale).toInt().coerceAtLeast(1))
}
} catch (_: Exception) {
null
}
}
fun stage(photos: List<TemplatePhoto>): StagedPhotos = synchronized(lock) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) error("暂存话术图片需要 Android 10 或更新版本。")
val source = checkNotNull(importedFile(photo)) { "找不到所选话术图片,请重新选择。" }
stageImage(source)
require(photos.size in 1..TaskPlan.MAX_TEMPLATE_PHOTOS &&
photos.map(TemplatePhoto::id).distinct().size == photos.size) { "本条话术的图片列表有误。" }
val sources = photos.map { photo ->
checkNotNull(importedFile(photo)) { "找不到所选话术图片,请重新选择。" }
}
stageImages(sources)
}
fun removeStaged(staged: StagedPhoto): Unit = synchronized(lock) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && activeStages.remove(staged)) {
deleteStageSafely(staged.uri)
fun removeStaged(staged: StagedPhotos): Unit = synchronized(lock) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
staged.uris.filter(activeStages::remove).forEach(::deleteStageSafely)
}
}
fun leaveStagedForReview(staged: StagedPhoto) = synchronized(lock) {
activeStages.remove(staged)
fun leaveStagedForReview(staged: StagedPhotos) = synchronized(lock) {
activeStages.removeAll(staged.uris.toSet())
}
/** Sweep only this app's staging rows. Keep current stages and call after any previous send is reconciled. */
@@ -148,28 +171,35 @@ class PhotoLibrary(context: Context) {
}
@TargetApi(Build.VERSION_CODES.Q)
private fun stageImage(source: File): StagedPhoto {
val format = Format.entries.single { it.extension == source.extension }
private fun stageImages(sources: List<File>): StagedPhotos {
val albumName = "SJ-${UUID.randomUUID().toString().replace("-", "").take(12)}"
val stagedUris = mutableListOf<Uri>()
var committed = false
try {
// Insert the group in binding order so the gallery uses the same order for newly staged rows.
for (index in sources.indices) {
val source = sources[index]
val format = Format.entries.single { it.extension == source.extension }
val values = ContentValues().apply {
put(MediaColumns.DISPLAY_NAME, stageFileName(albumName, format))
put(MediaColumns.DISPLAY_NAME, stageFileName(albumName, format, index + 1))
put(MediaColumns.MIME_TYPE, format.mime)
put(MediaColumns.RELATIVE_PATH, "${Environment.DIRECTORY_PICTURES}/$albumName/")
put(MediaColumns.IS_PENDING, 1)
}
val uri = checkNotNull(resolver.insert(imageCollection(), values)) { "无法在系统相册中暂存图片。" }
var committed = false
try {
stagedUris.add(uri)
val target = checkNotNull(resolver.openOutputStream(uri, "w")) { "无法写入暂存图片。" }
target.use { stream -> source.inputStream().use { it.copyTo(stream) } }
}
val visible = ContentValues().apply { put(MediaColumns.IS_PENDING, 0) }
stagedUris.forEach { uri ->
check(resolver.update(uri, visible, null, null) == 1) { "无法使暂存图片在系统相册中显示。" }
val staged = StagedPhoto(albumName, uri)
activeStages.add(staged)
}
activeStages.addAll(stagedUris)
committed = true
return staged
return StagedPhotos(albumName, stagedUris.toList())
} finally {
if (!committed) deleteStageSafely(uri)
if (!committed) stagedUris.forEach(::deleteStageSafely)
}
}
@@ -190,9 +220,13 @@ class PhotoLibrary(context: Context) {
if (cursor.getString(3) != app.packageName) continue
val albumName = STAGE_PATH.matchEntire(cursor.getString(1).orEmpty())?.groupValues?.get(1) ?: continue
val name = cursor.getString(2)
if (Format.entries.none { stageFileName(albumName, it) == name }) continue
if (Format.entries.none { format ->
name == "shijian-stage-$albumName.${format.extension}" ||
(1..TaskPlan.MAX_TEMPLATE_PHOTOS).any { name == stageFileName(albumName, format, it) }
}
) continue
val uri = ContentUris.withAppendedId(collection, cursor.getLong(0))
if (StagedPhoto(albumName, uri) !in activeStages) add(uri)
if (uri !in activeStages) add(uri)
}
}
}.orEmpty()
@@ -216,7 +250,8 @@ class PhotoLibrary(context: Context) {
@TargetApi(Build.VERSION_CODES.Q)
private fun imageCollection(): Uri = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
private fun stageFileName(albumName: String, format: Format): String = "shijian-stage-$albumName.${format.extension}"
private fun stageFileName(albumName: String, format: Format, number: Int): String =
"shijian-stage-$albumName-${number.toString().padStart(2, '0')}.${format.extension}"
private enum class Format(val mime: String, val extension: String) {
JPEG("image/jpeg", "jpg"),
@@ -234,6 +269,6 @@ class PhotoLibrary(context: Context) {
val IMPORT_NAME = Regex("([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})[.](jpg|png)")
val STAGE_PATH = Regex("${Environment.DIRECTORY_PICTURES}/(SJ-[0-9a-f]{12})/")
val lock = Any()
val activeStages = mutableSetOf<StagedPhoto>()
val activeStages = mutableSetOf<Uri>()
}
}
@@ -2,21 +2,30 @@ package com.jieliu.app.platform
import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.GestureDescription
import android.annotation.TargetApi
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Paint
import android.graphics.Path
import android.graphics.Picture
import android.graphics.Rect
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.view.Display
import android.view.accessibility.AccessibilityNodeInfo
import android.view.accessibility.AccessibilityWindowInfo
import java.io.Closeable
import java.util.ArrayDeque
import java.util.concurrent.CancellationException
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
import kotlin.math.roundToInt
import kotlin.random.Random
/** Uses fresh, target-package-scoped nodes and recycles every reference after each read or action. */
@Suppress("DEPRECATION")
@@ -59,6 +68,153 @@ internal class AccessibleUi(
return capture(root).use(action)
}
fun screenshotPhotos(windowId: Int, regions: List<Rect>): List<PhotoPixels>? {
checkCancelled()
if (regions.isEmpty()) return emptyList()
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R || Looper.myLooper() == Looper.getMainLooper() ||
regions.size > MAX_SCREENSHOT_REGIONS
) return null
val crops = regions.map(::Rect)
if (crops.any { it.isEmpty }) return null
return capturePhotoRegions(windowId, crops)
}
@TargetApi(Build.VERSION_CODES.R)
private fun capturePhotoRegions(windowId: Int, crops: List<Rect>): List<PhotoPixels>? {
val response = CompletableFuture<AccessibilityService.ScreenshotResult?>()
val deadline = SystemClock.elapsedRealtime() + SCREENSHOT_TIMEOUT_MS
try {
val bounds = screenshotTargetBounds(windowId, crops) ?: return null
if (SystemClock.elapsedRealtime() >= deadline) return null
checkCancelled()
service.takeScreenshot(Display.DEFAULT_DISPLAY, { it.run() }, object : AccessibilityService.TakeScreenshotCallback {
override fun onSuccess(screenshot: AccessibilityService.ScreenshotResult) {
if (!response.complete(screenshot)) screenshot.hardwareBuffer.close()
}
override fun onFailure(errorCode: Int) {
response.complete(null)
}
})
var screenshot: AccessibilityService.ScreenshotResult? = null
while (true) {
checkCancelled()
val remaining = deadline - SystemClock.elapsedRealtime()
if (remaining <= 0) return null
try {
screenshot = response.get(minOf(70L, remaining), TimeUnit.MILLISECONDS)
break
} catch (_: TimeoutException) {
// Poll cancellation while Android completes the capture.
}
}
screenshot ?: return null
checkCancelled()
if (screenshotTargetBounds(windowId, crops) != bounds || SystemClock.elapsedRealtime() >= deadline) return null
val hardware = Bitmap.wrapHardwareBuffer(screenshot.hardwareBuffer, screenshot.colorSpace) ?: return null
try {
val display = Rect(0, 0, hardware.width, hardware.height)
if (crops.any { !display.contains(it) }) return null
return readPhotoCrops(hardware, crops, deadline)
} finally {
hardware.recycle()
}
} catch (error: InterruptedException) {
Thread.currentThread().interrupt()
throw CancellationException("任务已停止")
} catch (error: CancellationException) {
throw error
} catch (_: RuntimeException) {
return null
} finally {
// A result arriving after cancellation/timeout is closed by onSuccess instead.
response.complete(null)
response.getNow(null)?.hardwareBuffer?.close()
}
}
@TargetApi(Build.VERSION_CODES.R)
private fun screenshotTargetBounds(windowId: Int, crops: List<Rect>): Rect? {
val root = targetRoot() ?: return null
val bounds = try {
if (root.windowId != windowId) return null
Rect().also(root::getBoundsInScreen)
} finally {
root.recycle()
}
if (crops.any { !bounds.contains(it) }) return null
val windows = service.windows
try {
val target = windows.singleOrNull {
it.id == windowId && it.type == AccessibilityWindowInfo.TYPE_APPLICATION && it.displayId == Display.DEFAULT_DISPLAY
} ?: return null
val above = Rect()
val covered = windows.any { window ->
if (window.displayId != target.displayId || window.layer <= target.layer) return@any false
window.getBoundsInScreen(above)
crops.any { Rect.intersects(above, it) }
}
return bounds.takeUnless { covered }
} finally {
windows.forEach { it.recycle() }
}
}
@TargetApi(Build.VERSION_CODES.P)
private fun readPhotoCrops(hardware: Bitmap, crops: List<Rect>, deadline: Long): List<PhotoPixels>? {
val columns = minOf(4, crops.size)
val rows = (crops.size + columns - 1) / columns
val width = columns * SCREENSHOT_CROP_SIDE
val height = rows * SCREENSHOT_CROP_SIDE
val cells = crops.mapIndexed { index, crop ->
val longest = maxOf(crop.width(), crop.height())
val scale = minOf(1f, SCREENSHOT_CROP_SIDE.toFloat() / longest)
val left = index % columns * SCREENSHOT_CROP_SIDE
val top = index / columns * SCREENSHOT_CROP_SIDE
Rect(left, top, left + (crop.width() * scale).roundToInt().coerceAtLeast(1),
top + (crop.height() * scale).roundToInt().coerceAtLeast(1))
}
val picture = Picture()
try {
val canvas = picture.beginRecording(width, height)
try {
val paint = Paint(Paint.FILTER_BITMAP_FLAG)
crops.forEachIndexed { index, crop ->
checkCancelled()
canvas.drawBitmap(hardware, crop, cells[index], paint)
}
} finally {
picture.endRecording()
}
if (SystemClock.elapsedRealtime() >= deadline) return null
// The recorded hardware draw reads back only the small crop atlas.
val cropped = Bitmap.createBitmap(picture, width, height, Bitmap.Config.ARGB_8888)
try {
return cells.map { cell ->
checkCancelled()
if (SystemClock.elapsedRealtime() >= deadline) return null
val pixels = IntArray(cell.width() * cell.height())
cropped.getPixels(pixels, 0, cell.width(), cell.left, cell.top, cell.width(), cell.height())
PhotoPixels(cell.width(), cell.height(), pixels)
}
} finally {
cropped.recycle()
}
} finally {
// Discard recorded commands that reference the full hardware bitmap.
picture.beginRecording(1, 1)
picture.endRecording()
}
}
private companion object {
const val SCREENSHOT_TIMEOUT_MS = 2_500L
const val MAX_SCREENSHOT_REGIONS = 32
const val SCREENSHOT_CROP_SIDE = 192
}
private fun targetRoot(): AccessibilityNodeInfo? {
val active = service.rootInActiveWindow
if (active?.packageName?.toString() == packageName) return active
@@ -155,8 +311,61 @@ internal class AccessibleUi(
moveTo(fromX, fromY)
if (fromX != toX || fromY != toY) lineTo(toX, toY)
}
return dispatchStroke(GestureDescription.StrokeDescription(path, 0L, durationMs))
}
fun scrollUpInside(viewport: Rect): Boolean {
checkCancelled()
if (viewport.isEmpty) return false
val width = viewport.width().toFloat()
val height = viewport.height().toFloat()
val startX = viewport.left + width * Random.nextDouble(.32, .60).toFloat()
val startY = viewport.top + height * Random.nextDouble(.70, .86).toFloat()
val endY = viewport.top + height * Random.nextDouble(.23, .42).toFloat()
val drift = width * Random.nextDouble(-.035, .035).toFloat()
val curve = width * Random.nextDouble(-.028, .028).toFloat()
val duration = Random.nextLong(390, 601)
val distances = floatArrayOf(0f, .16f, .85f, 1f)
val phaseDurations = longArrayOf(duration * 3 / 10, duration * 4 / 10, duration * 3 / 10)
var lastStroke: GestureDescription.StrokeDescription? = null
var lastX = startX
var lastY = startY
try {
for (phase in phaseDurations.indices) {
checkCancelled()
val distance = distances[phase + 1]
val x = startX + drift * distance
val y = startY + (endY - startY) * distance
val yStep = y - lastY
val path = Path().apply {
moveTo(lastX, lastY)
cubicTo(lastX + curve, lastY + yStep * .26f, x + curve, lastY + yStep * .78f, x, y)
}
val keepDown = phase != phaseDurations.lastIndex
val stroke = lastStroke?.continueStroke(path, 0L, phaseDurations[phase], keepDown)
?: GestureDescription.StrokeDescription(path, 0L, phaseDurations[phase], keepDown)
if (!dispatchStroke(stroke, interruptible = false)) return false
lastStroke = stroke.takeIf { keepDown }
lastX = x
lastY = y
}
} finally {
// If stopped between phases, end the continued touch without moving it further.
lastStroke?.let { stroke ->
val release = Path().apply { moveTo(lastX, lastY) }
val gesture = GestureDescription.Builder()
.addStroke(GestureDescription.StrokeDescription(path, 0L, durationMs))
.addStroke(stroke.continueStroke(release, 0L, 1L, false))
.build()
service.dispatchGesture(gesture, null, mainHandler)
}
}
checkCancelled()
return true
}
private fun dispatchStroke(stroke: GestureDescription.StrokeDescription, interruptible: Boolean = true): Boolean {
val gesture = GestureDescription.Builder()
.addStroke(stroke)
.build()
val done = CountDownLatch(1)
var completed = false
@@ -171,10 +380,10 @@ internal class AccessibleUi(
}
}
if (!service.dispatchGesture(gesture, callback, mainHandler)) return false
val deadline = SystemClock.elapsedRealtime() + durationMs + 2_000
val deadline = SystemClock.elapsedRealtime() + stroke.duration + 2_000
try {
while (SystemClock.elapsedRealtime() < deadline) {
checkCancelled()
if (interruptible) checkCancelled()
if (done.await(75, TimeUnit.MILLISECONDS)) return completed
}
} catch (error: InterruptedException) {
@@ -205,16 +414,48 @@ internal class UiPage(
val windowId: Int,
val bounds: Rect,
val nodes: List<UiNode>,
private val references: List<AccessibilityNodeInfo>,
private val references: MutableList<AccessibilityNodeInfo>,
) : Closeable {
fun x(fraction: Float): Int = bounds.left + (bounds.width() * fraction).roundToInt()
fun y(fraction: Float): Int = bounds.top + (bounds.height() * fraction).roundToInt()
fun visibleByViewId(resourceId: String): List<UiNode> {
val root = references.first()
val owner = root.packageName?.toString() ?: return emptyList()
val id = "$owner:id/$resourceId"
val matches = root.findAccessibilityNodeInfosByViewId(id)
if (matches.size > 64) {
matches.forEach { it.recycle() }
return emptyList()
}
return matches.mapNotNull { node ->
val rect = Rect().also(node::getBoundsInScreen)
if (node.windowId == windowId && node.packageName?.toString() == owner && node.isVisibleToUser &&
node.viewIdResourceName == id && !rect.isEmpty && Rect.intersects(bounds, rect)
) {
references.add(node)
UiNode(node, rect, parent = null, depth = 0)
} else {
node.recycle()
null
}
}
}
override fun close() {
references.forEach { it.recycle() }
}
}
@Suppress("DEPRECATION")
internal class UiNodeSource(node: AccessibilityNodeInfo) : Closeable {
private val source = AccessibilityNodeInfo.obtain(node)
fun matches(node: AccessibilityNodeInfo): Boolean = source == node
override fun close() = source.recycle()
}
internal class UiNode(
private val node: AccessibilityNodeInfo,
val bounds: Rect,
@@ -232,6 +473,11 @@ internal class UiNode(
val focused: Boolean = node.isFocused
val selected: Boolean = node.isSelected
val showingHint: Boolean = node.isShowingHintText
val scrollable: Boolean = node.isScrollable
val horizontalItemCount: Int?
get() = node.collectionInfo?.takeIf { it.rowCount == 1 && it.columnCount > 0 }?.columnCount
val horizontalItemIndex: Int?
get() = node.collectionItemInfo?.takeIf { it.rowIndex == 0 && it.columnIndex >= 0 }?.columnIndex
fun labels(): List<String> = listOf(text, description).filter { it.isNotEmpty() }.distinct()
fun hasDraft(): Boolean = text.isNotBlank() && !showingHint
@@ -239,6 +485,37 @@ internal class UiNode(
node.isEnabled && node.isEditable && !node.isPassword
fun isStillBlankAndFocused(): Boolean = hasCurrentInputFocus() &&
(node.isShowingHintText || node.text.isNullOrBlank())
fun hasCurrentFocusedText(expected: String, matchesHint: (String) -> Boolean): Boolean {
if (!hasCurrentInputFocus() || node.isShowingHintText || node.text?.toString() != expected) return false
val hint = node.hintText?.toString()?.trim().orEmpty()
return hint.isEmpty() || matchesHint(hint)
}
fun retainSource(): UiNodeSource = UiNodeSource(node)
fun hasSource(source: UiNodeSource): Boolean = source.matches(node)
fun retainVisibleNativeAncestor(resourceId: String, maxParents: Int): UiNodeSource? =
findNativeAncestor(maxParents) { ancestor ->
if (ancestor.isVisibleToUser && ancestor.viewIdResourceName == "${node.packageName}:id/$resourceId") {
UiNodeSource(ancestor)
} else null
}
fun hasNativeAncestor(source: UiNodeSource, maxParents: Int): Boolean =
findNativeAncestor(maxParents) { ancestor -> true.takeIf { source.matches(ancestor) } } == true
@Suppress("DEPRECATION")
private fun <T : Any> findNativeAncestor(maxParents: Int, probe: (AccessibilityNodeInfo) -> T?): T? {
var ancestor = node.parent
repeat(maxParents) { index ->
val current = ancestor ?: return null
try {
probe(current)?.let { return it }
ancestor = if (index + 1 < maxParents) current.parent else null
} finally {
current.recycle()
}
}
return null
}
fun directParent(): UiNode? = parent?.takeIf { it.depth == depth - 1 }
fun isDescendantOf(ancestor: UiNode): Boolean = generateSequence(parent) { it.parent }.any { it === ancestor }
fun supports(action: Int): Boolean = node.actionList.any { it.id == action }
File diff suppressed because it is too large Load Diff
@@ -2,6 +2,7 @@ package com.jieliu.app.platform
import android.accessibilityservice.AccessibilityService
import com.jieliu.app.data.PhotoLibrary
import com.jieliu.app.task.PendingComment
import com.jieliu.app.task.TemplatePhoto
data class PlatformSpec(
@@ -13,6 +14,8 @@ data class PlatformSpec(
data class VideoContext(val key: String, val title: String)
data class CommentTarget(val key: String, val text: String, val author: String)
enum class CommentPublishResult { CONFIRMED, UNCERTAIN }
class PlatformException(message: String, cause: Throwable? = null) : RuntimeException(message, cause)
@@ -24,10 +27,18 @@ interface PlatformAdapter {
fun currentVideo(): VideoContext
fun nextVideo(previous: VideoContext): VideoContext
fun openComments(expected: VideoContext): List<String>
fun scanComments(): List<CommentTarget> = emptyList()
fun scrollComments(): Boolean = false
/** False means no reply control was activated and scanning may continue. */
fun prepareReply(target: CommentTarget, expectedText: String): Boolean = false
fun publishComment(text: String, beforeClick: () -> Unit): CommentPublishResult
fun publishPhotoComment(text: String, photo: TemplatePhoto, beforeClick: () -> Unit): CommentPublishResult {
fun publishPhotoComment(text: String, photos: List<TemplatePhoto>, beforeClick: () -> Unit): CommentPublishResult {
throw PlatformException("当前平台不支持发布图片评论")
}
/** True when the prepared target has a known baseline with no matching own reply. */
fun hasPreparedReplyBaseline(targetKey: String, text: String): Boolean = false
/** Read back one previously armed reply. This must never prepare or submit a comment. */
fun confirmPendingReply(video: VideoContext, pending: PendingComment): CommentPublishResult = CommentPublishResult.UNCERTAIN
fun closeComments()
}
@@ -0,0 +1,167 @@
package com.jieliu.app.platform
import kotlin.math.abs
import kotlin.math.min
import kotlin.math.roundToInt
import kotlin.math.sqrt
internal data class PhotoPixels(val width: Int, val height: Int, val argb: IntArray)
internal object PublishedPhotoMatcher {
private const val GRID = 24
private const val MIN_SIDE = 12
private const val MIN_CORRELATION = .85
private const val MAX_COLOR_ERROR = 11.0
private const val MIN_LUMA_VARIANCE = 49.0
fun matches(reference: PhotoPixels, published: PhotoPixels): Boolean {
if (!reference.isUsable() || !published.isUsable()) return false
val publishedBounds = published.bounds()
val croppedReference = reference.bounds().centered(publishedBounds.aspect)
if (compare(reference, croppedReference, published, publishedBounds)) return true
val referenceBounds = reference.bounds()
val fittedContent = publishedBounds.centered(referenceBounds.aspect)
return fittedContent != publishedBounds && plainGutters(published, fittedContent) &&
compare(reference, referenceBounds, published, fittedContent)
}
private fun compare(reference: PhotoPixels, referenceBounds: Box, published: PhotoPixels, publishedBounds: Box): Boolean {
if (min(referenceBounds.width, referenceBounds.height) < MIN_SIDE ||
min(publishedBounds.width, publishedBounds.height) < MIN_SIDE) return false
val expected = grid(reference, referenceBounds)
if (sameImage(expected, grid(published, publishedBounds))) return true
// Accessibility bounds and the drawn thumbnail can differ by a pixel after rounding.
for (dy in -1..1) {
for (dx in -1..1) {
if ((dx != 0 || dy != 0) && sameImage(expected, grid(published, publishedBounds.shifted(dx, dy)))) return true
}
}
return false
}
private fun grid(image: PhotoPixels, bounds: Box): IntArray {
val result = IntArray(GRID * GRID)
val dx = bounds.width / GRID
val dy = bounds.height / GRID
for (row in 0 until GRID) {
for (col in 0 until GRID) {
val nearTopOrBottom = row < 2 || row >= GRID - 2
val nearLeftOrRight = col < 2 || col >= GRID - 2
if (nearTopOrBottom && nearLeftOrRight) continue // Rounded thumbnail corners may contain the UI background.
val x = bounds.left + (col + .5) * dx
val y = bounds.top + (row + .5) * dy
result[row * GRID + col] = average(
pixel(image, x - dx * .25, y - dy * .25), pixel(image, x + dx * .25, y - dy * .25),
pixel(image, x - dx * .25, y + dy * .25), pixel(image, x + dx * .25, y + dy * .25),
)
}
}
return result
}
private fun sameImage(expected: IntArray, actual: IntArray): Boolean {
var count = 0
var error = 0
var sumExpected = 0.0
var sumActual = 0.0
var squareExpected = 0.0
var squareActual = 0.0
var product = 0.0
for (index in expected.indices) {
val left = expected[index]
val right = actual[index]
if (channel(left, 24) < 245 || channel(right, 24) < 245) continue
error += abs(channel(left, 16) - channel(right, 16)) + abs(channel(left, 8) - channel(right, 8)) +
abs(channel(left, 0) - channel(right, 0))
val lumaExpected = luma(left)
val lumaActual = luma(right)
count++
sumExpected += lumaExpected
sumActual += lumaActual
squareExpected += lumaExpected * lumaExpected
squareActual += lumaActual * lumaActual
product += lumaExpected * lumaActual
}
if (count < GRID * GRID * 3 / 4 || error.toDouble() / (3 * count) > MAX_COLOR_ERROR) return false
val varianceExpected = squareExpected / count - (sumExpected / count) * (sumExpected / count)
val varianceActual = squareActual / count - (sumActual / count) * (sumActual / count)
if (min(varianceExpected, varianceActual) < MIN_LUMA_VARIANCE) return false
val covariance = product / count - (sumExpected / count) * (sumActual / count)
return covariance / sqrt(varianceExpected * varianceActual) >= MIN_CORRELATION
}
private fun plainGutters(image: PhotoPixels, content: Box): Boolean {
if (content.left > 2.0) {
return plainStripe(image, content.left / 2, horizontal = false) &&
plainStripe(image, image.width - content.left / 2, horizontal = false)
}
if (content.top > 2.0) {
return plainStripe(image, content.top / 2, horizontal = true) &&
plainStripe(image, image.height - content.top / 2, horizontal = true)
}
return true
}
private fun plainStripe(image: PhotoPixels, across: Double, horizontal: Boolean): Boolean {
val length = if (horizontal) image.width else image.height
val center = if (horizontal) pixel(image, length * .5, across) else pixel(image, across, length * .5)
for (index in 1..7) {
val at = length * index / 8.0
val sample = if (horizontal) pixel(image, at, across) else pixel(image, across, at)
if (abs(channel(sample, 16) - channel(center, 16)) > 16 || abs(channel(sample, 8) - channel(center, 8)) > 16 ||
abs(channel(sample, 0) - channel(center, 0)) > 16) return false
}
return true
}
private fun pixel(image: PhotoPixels, x: Double, y: Double): Int {
val column = (x - .5).coerceIn(0.0, (image.width - 1).toDouble())
val row = (y - .5).coerceIn(0.0, (image.height - 1).toDouble())
val left = column.toInt()
val top = row.toInt()
val right = min(left + 1, image.width - 1)
val bottom = min(top + 1, image.height - 1)
val a = image.argb[top * image.width + left]
val b = image.argb[top * image.width + right]
val c = image.argb[bottom * image.width + left]
val d = image.argb[bottom * image.width + right]
val fx = column - left
val fy = row - top
fun blend(shift: Int): Int {
val upper = channel(a, shift) * (1 - fx) + channel(b, shift) * fx
val lower = channel(c, shift) * (1 - fx) + channel(d, shift) * fx
return (upper * (1 - fy) + lower * fy).roundToInt()
}
return packed(blend(24), blend(16), blend(8), blend(0))
}
private fun average(a: Int, b: Int, c: Int, d: Int): Int {
fun mean(shift: Int) = (channel(a, shift) + channel(b, shift) + channel(c, shift) + channel(d, shift) + 2) / 4
return packed(mean(24), mean(16), mean(8), mean(0))
}
private fun packed(alpha: Int, red: Int, green: Int, blue: Int) =
(alpha shl 24) or (red shl 16) or (green shl 8) or blue
private fun channel(color: Int, shift: Int) = (color ushr shift) and 255
private fun luma(color: Int) = .299 * channel(color, 16) + .587 * channel(color, 8) + .114 * channel(color, 0)
private fun PhotoPixels.isUsable() = width >= MIN_SIDE && height >= MIN_SIDE && width.toLong() * height == argb.size.toLong()
private fun PhotoPixels.bounds() = Box(0.0, 0.0, width.toDouble(), height.toDouble())
private data class Box(val left: Double, val top: Double, val width: Double, val height: Double) {
val aspect: Double get() = width / height
fun centered(aspect: Double): Box {
val fittedWidth = min(width, height * aspect)
val fittedHeight = min(height, width / aspect)
return Box(left + (width - fittedWidth) / 2, top + (height - fittedHeight) / 2, fittedWidth, fittedHeight)
}
fun shifted(dx: Int, dy: Int) = copy(left = left + dx, top = top + dy)
}
}
@@ -0,0 +1,55 @@
package com.jieliu.app.task
import java.text.Normalizer
import java.util.Locale
data class ContentType(val id: String, val name: String, val rules: List<KeywordRule> = emptyList())
data class KeywordRule(val id: String, val keyword: String, val phrases: List<ReplyPhrase> = emptyList())
data class ReplyPhrase(val id: String, val text: String, val photos: List<TemplatePhoto> = emptyList())
private val keywordWhitespace = Regex("""[\p{Z}\s\u0085]+""")
fun normalizeKeyword(value: String): String {
val normalized = Normalizer.normalize(value, Normalizer.Form.NFKC)
.lowercase(Locale.ROOT).replace(keywordWhitespace, " ").trim()
return buildString(normalized.length) {
for (index in normalized.indices) {
val char = normalized[index]
if (char != ' ' || (!isHan(normalized.codePointBefore(index)) && !isHan(normalized.codePointAt(index + 1)))) {
append(char)
}
}
}
}
private fun isHan(codePoint: Int): Boolean = Character.UnicodeScript.of(codePoint) == Character.UnicodeScript.HAN
class KeywordMatcher(type: ContentType) {
private val rules = type.rules.mapNotNull { rule ->
normalizeKeyword(rule.keyword).takeIf(String::isNotEmpty)?.let { it to rule }
}.sortedByDescending { (keyword, _) -> keyword.codePointCount(0, keyword.length) }
fun matchingRule(text: String): KeywordRule? {
val normalized = normalizeKeyword(text)
return rules.firstOrNull { (keyword, _) -> containsKeyword(normalized, keyword) }?.second
}
private fun containsKeyword(text: String, keyword: String): Boolean {
val checkLeft = isLatinAlphanumeric(keyword.codePointAt(0))
val checkRight = isLatinAlphanumeric(keyword.codePointBefore(keyword.length))
var start = text.indexOf(keyword)
while (start >= 0) {
val end = start + keyword.length
val leftMatches = !checkLeft || start == 0 || !isLatinAlphanumeric(text.codePointBefore(start))
val rightMatches = !checkRight || end == text.length || !isLatinAlphanumeric(text.codePointAt(end))
if (leftMatches && rightMatches) return true
start = text.indexOf(keyword, start + 1)
}
return false
}
private fun isLatinAlphanumeric(codePoint: Int): Boolean = Character.isDigit(codePoint) ||
(Character.isLetter(codePoint) && Character.UnicodeScript.of(codePoint) == Character.UnicodeScript.LATIN)
}
@@ -4,18 +4,39 @@ import kotlin.random.Random
enum class Outcome { WATCHED, SENT, USER_CONFIRMED, SKIPPED, NO_REPLY }
data class TemplateUse(val group: String, val index: Int)
data class TemplateUse(val group: String, val index: Int, val phraseId: String? = null)
data class TemplateSelection(val text: String, val use: TemplateUse, val photo: TemplatePhoto? = null)
data class TemplateSelection(val text: String, val use: TemplateUse, val photos: List<TemplatePhoto> = emptyList())
data class Receipt(val videoKey: String, val outcome: Outcome, val templateUse: TemplateUse? = null)
data class Receipt(
val videoKey: String,
val outcome: Outcome,
val templateUse: TemplateUse? = null,
val targetKey: String? = null,
val replies: List<ReplyReceipt> = emptyList(),
)
data class ReplyReceipt(val targetKey: String, val outcome: Outcome, val templateUse: TemplateUse? = null) {
init {
require(targetKey.isNotBlank() && (outcome.isConfirmedReply() || outcome == Outcome.SKIPPED))
}
}
data class VideoProgress(val videoKey: String, val replies: List<ReplyReceipt> = emptyList()) {
val sentCount: Int get() = replies.count { it.outcome.isConfirmedReply() }
fun hasHandled(targetKey: String): Boolean = replies.any { it.targetKey == targetKey }
}
data class PendingComment(
val videoKey: String,
val title: String,
val text: String,
val templateUse: TemplateUse? = null,
val photo: TemplatePhoto? = null,
val photos: List<TemplatePhoto> = emptyList(),
val targetKey: String? = null,
val targetAuthor: String? = null,
val armedAtEpochMs: Long? = null,
)
data class TaskCheckpoint(
@@ -24,37 +45,149 @@ data class TaskCheckpoint(
val receipts: List<Receipt> = emptyList(),
val pending: PendingComment? = null,
val message: String = "准备启动",
val activeVideo: VideoProgress? = null,
) {
val complete: Boolean get() = receipts.size >= plan.limit && pending == null
val sentCount: Int get() = receipts.count { it.outcome in setOf(Outcome.SENT, Outcome.USER_CONFIRMED) }
val keyword: String? get() = if (complete) null else plan.keywords[plan.keywordIndex(receipts.size)]
val complete: Boolean get() = receipts.size >= plan.limit && pending == null && activeVideo == null
val sentCount: Int get() = receipts.sumOf { receipt ->
if (receipt.replies.isEmpty()) {
if (receipt.outcome.isConfirmedReply()) 1 else 0
} else {
receipt.replies.count { it.outcome.isConfirmedReply() }
}
} + (activeVideo?.sentCount ?: 0)
val keyword: String? get() = when {
complete -> null
plan.contentTypes != null -> contentType?.name
else -> plan.keywords[plan.keywordIndex(receipts.size)]
}
val contentType: ContentType? get() {
val types = plan.searchTypes()
return if (complete || types.isEmpty()) null else types[plan.contentTypeIndex(receipts.size)]
}
fun canAutomaticallyRecheck(nowEpochMs: Long = System.currentTimeMillis()): Boolean {
val claim = pending ?: return false
val video = activeVideo ?: return false
val target = claim.targetKey?.takeIf { it.isNotBlank() } ?: return false
val armedAt = claim.armedAtEpochMs ?: return false
return receipts.size < plan.limit && video.videoKey == claim.videoKey && !hasSeen(claim.videoKey) &&
!video.hasHandled(target) && armedAt > 0 && armedAt <= nowEpochMs && nowEpochMs - armedAt <= RECHECK_WINDOW_MS
}
fun arm(comment: PendingComment): TaskCheckpoint {
check(!complete && pending == null && !hasSeen(comment.videoKey))
activeVideo?.let { video ->
val targetKey = checkNotNull(comment.targetKey)
check(video.videoKey == comment.videoKey && targetKey.isNotBlank() && !video.hasHandled(targetKey))
}
return copy(pending = comment, message = "已记录提交意图,正在确认发送结果")
}
fun startVideo(videoKey: String): TaskCheckpoint {
check(!complete && pending == null && !hasSeen(videoKey))
val video = activeVideo ?: return copy(activeVideo = VideoProgress(videoKey))
check(video.videoKey == videoKey)
return this
}
fun recordReply(outcome: Outcome): TaskCheckpoint {
require(outcome.isConfirmedReply() || outcome == Outcome.SKIPPED)
val comment = checkNotNull(pending)
val video = activeVideo ?: return finish(comment.videoKey, outcome)
val targetKey = checkNotNull(comment.targetKey)
check(video.videoKey == comment.videoKey && !video.hasHandled(targetKey))
val updated = video.copy(replies = video.replies + ReplyReceipt(targetKey, outcome, comment.templateUse))
val status = when (outcome) {
Outcome.SKIPPED -> "已跳过该评论,等待继续"
Outcome.USER_CONFIRMED -> "已人工确认,等待继续"
else -> "已确认发送"
}
val next = copy(activeVideo = updated, pending = null, message = status)
return if (updated.sentCount >= plan.repliesPerVideo) next.finishVideo() else next
}
fun finishVideo(): TaskCheckpoint {
val video = checkNotNull(activeVideo)
check(!complete && pending == null && !hasSeen(video.videoKey))
val outcome = when {
video.replies.any { it.outcome == Outcome.SENT } -> Outcome.SENT
video.sentCount > 0 -> Outcome.USER_CONFIRMED
video.replies.isNotEmpty() -> Outcome.SKIPPED
else -> Outcome.NO_REPLY
}
return finishReceipt(Receipt(video.videoKey, outcome, replies = video.replies))
}
fun finish(videoKey: String, outcome: Outcome): TaskCheckpoint {
check(!complete && !hasSeen(videoKey))
check(!complete && activeVideo == null && !hasSeen(videoKey))
if (outcome == Outcome.WATCHED || outcome == Outcome.NO_REPLY) {
check(pending == null)
} else {
check(pending?.videoKey == videoKey)
}
val updated = receipts + Receipt(videoKey, outcome, pending?.templateUse)
return finishReceipt(Receipt(videoKey, outcome, pending?.templateUse, pending?.targetKey))
}
private fun finishReceipt(receipt: Receipt): TaskCheckpoint {
val updated = receipts + receipt
val outcome = receipt.outcome
val status = when {
updated.size >= plan.limit -> "任务已完成"
outcome == Outcome.SKIPPED -> "已核对并跳过,等待继续"
outcome == Outcome.USER_CONFIRMED -> "已人工确认,等待继续"
outcome == Outcome.SENT -> "已确认发送"
outcome == Outcome.NO_REPLY -> "无可用话术,已跳过视频"
outcome == Outcome.NO_REPLY -> if (plan.contentTypes == null) "无可用话术,已跳过视频" else "未找到可回复的匹配评论,已跳过视频"
else -> "已完成观看"
}
return copy(pending = null, receipts = updated, message = status)
return copy(pending = null, receipts = updated, message = status, activeVideo = null)
}
fun hasSeen(videoKey: String): Boolean = receipts.any { it.videoKey == videoKey }
fun selectReply(rule: KeywordRule, title: String): TemplateSelection? {
val options = rule.phrases.mapIndexedNotNull { index, phrase ->
plan.renderTemplate(phrase.text, rule.keyword, title)?.let { text ->
phrase.id to TemplateSelection(text, TemplateUse(rule.id, index, phrase.id), phrase.photos)
}
}.toMap()
if (options.isEmpty()) return null
val used = mutableSetOf<String>()
var last: String? = null
var round = 0
for (use in recordedTemplateUses()) {
val phraseId = use.phraseId ?: continue
if (use.group != rule.id || phraseId !in options) continue
if (!used.add(phraseId)) {
// A repeated ID marks a new cycle even if a mid-run edit changed the number of phrases.
used.clear()
used.add(phraseId)
round++
}
last = phraseId
}
if (used.size == options.size) {
used.clear()
round++
}
val texts = options.mapValues { (_, option) -> normalizeKeyword(option.text) }
val usedTexts = used.map(texts::getValue).toSet()
val lastText = last?.let(texts::getValue)
val available = options.keys.filterNot { it in used }.sorted()
.shuffled(Random("$id\n${rule.id}\n$round".hashCode()))
val priority = compareBy<String> { it == last }
.thenBy { texts.getValue(it) in usedTexts }
.thenBy { texts.getValue(it) == lastText }
val picked = available.minWithOrNull(priority)
return picked?.let(options::getValue)
}
private fun recordedTemplateUses(): Sequence<TemplateUse> = receipts.asSequence().flatMap { receipt ->
if (receipt.replies.isEmpty()) sequenceOf(receipt.templateUse).filterNotNull()
else receipt.replies.asSequence().mapNotNull(ReplyReceipt::templateUse)
} + activeVideo?.replies.orEmpty().asSequence().mapNotNull(ReplyReceipt::templateUse)
fun selectTemplate(keyword: String, title: String): TemplateSelection? {
for ((group, lines) in listOf(keyword to plan.keywordTemplates[keyword].orEmpty(), "" to plan.templates)) {
val options = lines.withIndex().filter { TaskPlan.commentText(it.value) != null }.distinctBy { it.value }
@@ -73,8 +206,15 @@ data class TaskCheckpoint(
}
val picked = order[position]
val text = plan.renderTemplate(picked.value, keyword, title) ?: continue
return TemplateSelection(text, TemplateUse(group, picked.index), plan.templatePhotos[group]?.get(picked.value))
val photos = plan.templatePhotos[group]?.get(picked.value).orEmpty()
return TemplateSelection(text, TemplateUse(group, picked.index), photos)
}
return null
}
private companion object {
const val RECHECK_WINDOW_MS = 30 * 60 * 1_000L
}
}
private fun Outcome.isConfirmedReply(): Boolean = this == Outcome.SENT || this == Outcome.USER_CONFIRMED
+102 -30
View File
@@ -1,9 +1,11 @@
package com.jieliu.app.task
import java.util.UUID
enum class ReplyMode(val label: String) {
BROWSE("仅浏览"),
TEMPLATES("随机使用话术并发送"),
DEEPSEEK("话术优先,DeepSeek 兜底"),
TEMPLATES("匹配评论并回复"),
DEEPSEEK("匹配评论并回复"),
}
data class TemplatePhoto(val id: String, val displayName: String) {
@@ -36,26 +38,15 @@ data class TaskPlan(
val model: String = "deepseek-flash",
val instructions: String = "根据视频内容提供一句具体、有帮助的中文评论。",
val keywordTemplates: Map<String, List<String>> = emptyMap(),
val templatePhotos: Map<String, Map<String, TemplatePhoto>> = emptyMap(),
val templatePhotos: Map<String, Map<String, List<TemplatePhoto>>> = emptyMap(),
val contentTypes: List<ContentType>? = null,
val selectedTypeId: String? = null,
val repliesPerVideo: Int = 1,
) {
fun validate() {
require(keywords.size in 1..MAX_KEYWORDS && keywords.all { it.isNotBlank() && it.length <= 120 }) {
"请填写 1–$MAX_KEYWORDS 个关键词,每个最多 120 字符。"
}
require(keywordTemplates.keys.all { it in keywords }) { "话术分组必须对应已配置的关键词。" }
require((keywordTemplates.values + listOf(templates)).all { group ->
group.size <= 100 && group.all { it.isNotBlank() && it.codePointCount(0, it.length) <= MAX_COMMENT }
}) {
"每组最多 100 条话术,每条最多 $MAX_COMMENT 字。"
}
require(templatePhotos.all { (group, photos) ->
val templatesInGroup = if (group.isEmpty()) templates else keywordTemplates[group]
templatesInGroup != null && photos.keys.all { it in templatesInGroup }
}) { "图片必须关联到现有的话术。" }
require(replyMode != ReplyMode.TEMPLATES || templates.isNotEmpty() || keywordTemplates.values.any { it.isNotEmpty() }) {
"请在关键词组或通用组至少填写一条话术。"
}
if (contentTypes == null) validateLegacy() else validateHierarchy(contentTypes)
require(limit in 1..100) { "单次任务数量须为 1–100。" }
require(repliesPerVideo in 1..MAX_REPLIES_PER_VIDEO) { "每条视频回复数量须为 1–$MAX_REPLIES_PER_VIDEO。" }
require(watchSeconds.first in 1..300 && watchSeconds.last in watchSeconds.first..300) {
"观看区间须在 1–300 秒之间,且下限不大于上限。"
}
@@ -66,20 +57,91 @@ data class TaskPlan(
require(instructions.length <= 1000) { "DeepSeek 话术说明最多 1000 字符。" }
}
fun photoIds(): Set<String> = templatePhotos.values.asSequence()
.flatMap { it.values.asSequence() }
.map(TemplatePhoto::id)
.toSet()
private fun validateLegacy() {
require(selectedTypeId == null) { "所选内容类型不存在。" }
require(keywords.size in 1..MAX_KEYWORDS && keywords.all { it.isNotBlank() && it.length <= 120 }) {
"请填写 1–$MAX_KEYWORDS 个关键词,每个最多 120 字符。"
}
require(keywordTemplates.keys.all { it in keywords }) { "话术分组必须对应已配置的关键词。" }
require((keywordTemplates.values + listOf(templates)).all { group ->
group.size <= MAX_RULE_PHRASES && group.all { it.isNotBlank() && it.codePointCount(0, it.length) <= MAX_COMMENT }
}) { "每组最多 $MAX_RULE_PHRASES 条话术,每条最多 $MAX_COMMENT 字。" }
require(templatePhotos.all { (group, photos) ->
val templatesInGroup = if (group.isEmpty()) templates else keywordTemplates[group]
templatesInGroup != null && photos.keys.all { it in templatesInGroup }
}) { "图片必须关联到现有的话术。" }
require(templatePhotos.values.all { group -> group.values.all { it.isNotEmpty() && validPhotos(it) } }) {
"每条话术可绑定 1–$MAX_TEMPLATE_PHOTOS 张不同的图片。"
}
require(replyMode != ReplyMode.TEMPLATES || templates.isNotEmpty() || keywordTemplates.values.any { it.isNotEmpty() }) {
"请在关键词组或通用组至少填写一条话术。"
}
}
fun keywordIndex(itemIndex: Int): Int {
require(itemIndex in 0 until limit)
val perKeyword = limit / keywords.size
val extra = limit % keywords.size
val extraItems = (perKeyword + 1) * extra
private fun validateHierarchy(types: List<ContentType>) {
require(selectedTypeId == null || types.any { it.id == selectedTypeId }) { "所选内容类型不存在。" }
require(types.all { normalizeKeyword(it.name).isNotEmpty() && it.name.length <= 120 }) {
"内容类型名称不能为空,每个最多 120 字符。"
}
val rules = types.flatMap(ContentType::rules)
require(rules.all { normalizeKeyword(it.keyword).isNotEmpty() && it.keyword.length <= 120 }) {
"关键词不能为空,每个最多 120 字符。"
}
require(types.all { type -> type.rules.distinctBy { normalizeKeyword(it.keyword) }.size == type.rules.size }) {
"同一内容类型内的关键词不能重复。"
}
val phrases = rules.flatMap(KeywordRule::phrases)
require(rules.all { it.phrases.size <= MAX_RULE_PHRASES } && phrases.all {
commentText(it.text) != null && it.text.codePointCount(0, it.text.length) <= MAX_COMMENT
}) { "每个关键词最多 $MAX_RULE_PHRASES 条话术,每条须在 1–$MAX_COMMENT 字内。" }
require(phrases.all { validPhotos(it.photos) }) { "每条话术最多可绑定 $MAX_TEMPLATE_PHOTOS 张不同的图片。" }
val ids = types.map(ContentType::id) + rules.map(KeywordRule::id) + phrases.map(ReplyPhrase::id)
require(ids.all(String::isNotBlank) && ids.toSet().size == ids.size) { "内容类型、关键词和话术的标识必须唯一。" }
}
fun migrateContentTypes(): TaskPlan {
if (contentTypes != null) return this
val occurrences = mutableMapOf<String, Int>()
val migrated = keywords.map { keyword ->
val occurrence = occurrences.getOrDefault(keyword, 0)
occurrences[keyword] = occurrence + 1
val typeId = legacyId("type", keyword, occurrence.toString())
val ruleId = legacyId("rule", typeId)
val specific = keywordTemplates[keyword].orEmpty().filter { commentText(it) != null }
val group = if (specific.isEmpty()) "" else keyword
val phrases = (if (specific.isEmpty()) templates.filter { commentText(it) != null } else specific)
.distinct().map { phrase ->
ReplyPhrase(legacyId("phrase", ruleId, phrase), phrase, templatePhotos[group]?.get(phrase).orEmpty())
}
ContentType(typeId, keyword, listOf(KeywordRule(ruleId, keyword, phrases)))
}
return copy(contentTypes = migrated)
}
fun searchTypes(): List<ContentType> = contentTypes.orEmpty().let { types ->
if (selectedTypeId == null) types else types.filter { it.id == selectedTypeId }
}
fun photoIds(): Set<String> {
val legacy = templatePhotos.values.asSequence().flatMap { it.values.asSequence() }.flatten()
val current = contentTypes.orEmpty().asSequence().flatMap { it.rules.asSequence() }
.flatMap { it.phrases.asSequence() }.flatMap { it.photos.asSequence() }
return (legacy + current).map(TemplatePhoto::id).toSet()
}
fun contentTypeIndex(itemIndex: Int): Int = allocatedIndex(itemIndex, searchTypes().size)
fun keywordIndex(itemIndex: Int): Int = allocatedIndex(itemIndex, keywords.size)
private fun allocatedIndex(itemIndex: Int, groups: Int): Int {
require(itemIndex in 0 until limit && groups > 0)
val perGroup = limit / groups
val extra = limit % groups
val extraItems = (perGroup + 1) * extra
return if (itemIndex < extraItems) {
itemIndex / (perKeyword + 1)
itemIndex / (perGroup + 1)
} else {
extra + (itemIndex - extraItems) / perKeyword
extra + (itemIndex - extraItems) / perGroup
}
}
@@ -93,8 +155,18 @@ data class TaskPlan(
companion object {
const val MAX_KEYWORDS = 30
const val MAX_COMMENT = 120
const val MAX_TEMPLATE_PHOTOS = 9
const val MAX_RULE_PHRASES = 100
const val MAX_REPLIES_PER_VIDEO = 100
private val PLACEHOLDERS = Regex("""\{keyword\}|\{title\}""")
private fun validPhotos(photos: List<TemplatePhoto>): Boolean =
photos.size <= MAX_TEMPLATE_PHOTOS && photos.distinctBy(TemplatePhoto::id).size == photos.size
private fun legacyId(vararg parts: String): String =
UUID.nameUUIDFromBytes(("shijian-legacy\n" + parts.joinToString("\n") { "${it.length}:$it" })
.toByteArray(Charsets.UTF_8)).toString()
fun commentText(text: String): String? {
val singleLine = text.replace(Regex("[\\p{Cc}\\s]+"), " ").trim()
if (singleLine.isEmpty()) return null
@@ -1,13 +1,16 @@
package com.jieliu.app.task
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.VideoContext
import java.util.concurrent.CancellationException
interface TaskRunStorage {
fun readPlan(): TaskPlan
fun saveCheckpoint(checkpoint: TaskCheckpoint)
fun savePendingIfCurrent(checkpoint: TaskCheckpoint, matchesPlan: (TaskPlan) -> Boolean): Boolean
fun appendLog(message: String, warning: Boolean = false)
}
@@ -15,11 +18,16 @@ internal class TaskRunner(
private val store: TaskRunStorage,
private val plan: TaskPlan,
private val platform: PlatformAdapter,
private val modelReply: ((String, String, List<String>) -> String)?,
private val cancelled: () -> Boolean,
private val status: (String) -> Unit,
) {
fun run(initial: TaskCheckpoint) {
private data class MatchedReply(
val target: CommentTarget,
val rule: KeywordRule,
val selection: TemplateSelection,
)
fun run(initial: TaskCheckpoint, recheckPending: Boolean = false) {
var checkpoint = initial
fun persist(next: TaskCheckpoint) {
store.saveCheckpoint(next)
@@ -27,82 +35,94 @@ internal class TaskRunner(
}
try {
if (recheckPending) {
if (confirmPending(initial) == CommentPublishResult.CONFIRMED) {
persist(checkpoint.recordReply(Outcome.SENT))
store.appendLog("自动核对回复成功,已确认发送")
} else {
val message = "自动核对未确认,发送结果仍待核对。"
persist(checkpoint.copy(message = message))
store.appendLog(message, warning = true)
}
return
}
check(checkpoint.pending == null) { "请先核对上一条评论的发送结果。" }
store.appendLog("开始任务 · ${plan.replyMode.label} · 上限 ${plan.limit} 条")
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")
status("正在打开目标应用")
platform.launch()
var activeKeyword: String? = null
var activeTypeId: String? = null
var video: VideoContext? = null
while (!checkpoint.complete) {
requireRunning(cancelled)
val keyword = checkNotNull(checkpoint.keyword)
var candidate: VideoContext = if (keyword != activeKeyword || video == null) {
status("正在搜索 $keyword")
store.appendLog("搜索关键词 $keyword")
platform.search(keyword).also { activeKeyword = keyword }
val type = checkNotNull(checkpoint.contentType)
val first = if (type.id != activeTypeId || video == null) {
status("正在搜索 ${type.name}")
store.appendLog("搜索内容类型 ${type.name}")
platform.search(type.name).also { activeTypeId = type.id }
} else {
status("正在打开下一条视频")
platform.nextVideo(video)
}
val visited = mutableSetOf<String>()
while (checkpoint.hasSeen(candidate.key)) {
check(visited.add(candidate.key) && visited.size <= plan.limit) { "搜索结果反复返回同一批视频" }
candidate = platform.nextVideo(candidate)
}
val candidate = locateVideo(first, checkpoint)
video = candidate
val watchSeconds = randomIn(plan.watchSeconds.first, plan.watchSeconds.last)
status("正在观看第 ${checkpoint.receipts.size + 1} 条 · ${watchSeconds} 秒")
store.appendLog("观看第 ${checkpoint.receipts.size + 1} 条 · ${watchSeconds} 秒")
pauseFor(watchSeconds * 1000L, cancelled)
check(platform.currentVideo().key == candidate.key) { "观看期间视频已切换,请恢复任务。" }
if (plan.replyMode == ReplyMode.BROWSE) {
val number = checkpoint.receipts.size + 1
if (checkpoint.activeVideo == null) watch(candidate, number)
if (mode == ReplyMode.BROWSE) {
persist(checkpoint.finish(candidate.key, Outcome.WATCHED))
continue
}
val template = checkpoint.selectTemplate(keyword, candidate.title)
val canGenerate = plan.replyMode == ReplyMode.DEEPSEEK && modelReply != null
val openPanel = template != null || canGenerate
val samples = if (openPanel) {
if (checkpoint.activeVideo == null) persist(checkpoint.startVideo(candidate.key))
val openPanel = store.readPlan().findType(type.id)?.rules?.isNotEmpty() == true
if (openPanel) {
status("正在打开评论区")
platform.openComments(candidate)
} else {
emptyList()
}
status("正在准备评论")
val text = template?.text ?: if (canGenerate) generateReply(keyword, candidate.title, samples) else null
if (text == null) {
val number = checkpoint.receipts.size + 1
val reason = if (plan.replyMode == ReplyMode.DEEPSEEK && modelReply == null) {
"无可用话术,DeepSeek 密钥不可用"
} else {
"无可用回复内容"
}
persist(checkpoint.finish(candidate.key, Outcome.NO_REPLY))
store.appendLog("第 $number 条$reason,已跳过", warning = true)
if (openPanel && !checkpoint.complete) platform.closeComments()
var screen = 1
while (checkpoint.activeVideo != null) {
requireRunning(cancelled)
val currentType = store.readPlan().findType(type.id)?.takeIf { it.rules.isNotEmpty() } ?: break
status("正在识别评论 · 第 $screen 屏")
val reply = findVisibleReply(currentType, candidate.title, checkpoint)
if (reply == null) {
if (screen > MAX_COMMENT_SWIPES || !platform.scrollComments()) break
screen++
continue
}
val photo = template?.photo
status(if (photo == null) "正在提交并回读评论" else "正在准备并提交图文评论")
val beforeClick = {
requireRunning(cancelled)
persist(checkpoint.arm(PendingComment(candidate.key, candidate.title, text, template?.use, photo)))
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
}) { "关键字或话术已更新,未提交此回复。请清除当前草稿后继续任务。" }
checkpoint = armed
}
val result = if (photo == null) platform.publishComment(text, beforeClick)
else platform.publishPhotoComment(text, photo, beforeClick)
if (result == CommentPublishResult.UNCERTAIN) {
error("请在目标应用里核对这条评论的发送结果。")
val confirmation = if (result == CommentPublishResult.UNCERTAIN && checkpoint.canAutomaticallyRecheck()) {
confirmPending(checkpoint, inCurrentRun = true)
} else result
check(confirmation == CommentPublishResult.CONFIRMED) { "请在目标应用里核对这条评论的发送结果。" }
persist(checkpoint.recordReply(Outcome.SENT))
val confirmed = checkpoint.activeVideo?.sentCount ?: plan.repliesPerVideo
store.appendLog("第 $number 条视频已确认 ${confirmed}/${plan.repliesPerVideo} 条回复")
}
persist(checkpoint.finish(candidate.key, Outcome.SENT))
store.appendLog("已确认第 ${checkpoint.receipts.size} 条评论发送")
if (!checkpoint.complete) platform.closeComments()
}
checkpoint.activeVideo?.let { progress ->
persist(checkpoint.finishVideo())
val summary = if (progress.sentCount == 0) "未找到可回复的匹配评论,已跳过"
else "评论扫描结束,已确认发送 ${progress.sentCount}/${plan.repliesPerVideo} 条"
store.appendLog("第 $number 条视频$summary")
}
if (openPanel && !checkpoint.complete) platform.closeComments()
}
store.appendLog("任务完成 · 处理 ${checkpoint.receipts.size} 条 · 确认发送 ${checkpoint.sentCount} 条")
} catch (error: Exception) {
val message = when {
recheckPending && checkpoint.pending != null -> {
if (cancelled() || error is CancellationException) "自动核对已暂停,发送结果仍待核对。"
else "自动核对未确认,发送结果仍待核对。"
}
checkpoint.pending != null -> "发送结果待核对,请在目标应用确认后继续。"
cancelled() || error is CancellationException -> "任务已暂停,可从检查点继续。"
error is PlatformException || error is IllegalStateException -> error.message ?: "任务中断"
@@ -117,19 +137,81 @@ internal class TaskRunner(
}
}
private fun generateReply(keyword: String, title: String, comments: List<String>): String? {
try {
val generated = checkNotNull(modelReply).invoke(keyword, title, comments)
private fun confirmPending(checkpoint: TaskCheckpoint, inCurrentRun: Boolean = false): CommentPublishResult {
check(checkpoint.canAutomaticallyRecheck()) { "这条回复的自动核对期限已过。" }
val pending = checkNotNull(checkpoint.pending)
val type = checkNotNull(checkpoint.contentType)
requireRunning(cancelled)
return TaskPlan.commentText(generated)
} catch (error: CancellationException) {
throw error
} catch (error: Exception) {
if (inCurrentRun) {
store.appendLog("本次任务继续核对已提交回复")
} else {
store.appendLog("开始自动核对一条待确认回复")
status("正在打开目标应用")
platform.launch()
}
status("正在定位待核对的视频")
val video = locateVideo(platform.search(type.name), checkpoint)
requireRunning(cancelled)
val detail = if (error is IllegalStateException) error.message else error.javaClass.simpleName
store.appendLog("DeepSeek 生成失败($detail)", warning = true)
status("正在打开待核对的视频评论区")
platform.openComments(video)
requireRunning(cancelled)
status("正在核对已发送的回复")
return platform.confirmPendingReply(video, pending).also { requireRunning(cancelled) }
}
private fun locateVideo(first: VideoContext, checkpoint: TaskCheckpoint): VideoContext {
val resumeKey = checkpoint.activeVideo?.videoKey
val tried = mutableSetOf<String>()
var candidate = first
val searchLimit = if (resumeKey == null) plan.limit else maxOf(plan.limit, MIN_RESUME_SEARCH)
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 "暂未重新找到上次的视频,已保留该视频的回复进度。"
}
candidate = platform.nextVideo(candidate)
}
return candidate
}
private fun watch(video: VideoContext, number: Int) {
val duration = randomIn(plan.watchSeconds.first, plan.watchSeconds.last)
status("正在观看第 $number 条 · $duration 秒")
store.appendLog("观看第 $number 条 · $duration 秒")
pauseFor(duration * 1000L, cancelled)
check(platform.currentVideo().key == video.key) { "观看期间视频已切换,请恢复任务。" }
}
private fun findVisibleReply(type: ContentType, title: String, checkpoint: TaskCheckpoint): MatchedReply? {
val progress = checkNotNull(checkpoint.activeVideo)
val matcher = KeywordMatcher(type)
for (target in platform.scanComments()) {
requireRunning(cancelled)
if (progress.hasHandled(target.key)) continue
val rule = matcher.matchingRule(target.text) ?: continue
val selection = checkpoint.selectReply(rule, title) ?: continue
if (platform.prepareReply(target, selection.text)) return MatchedReply(target, rule, selection)
}
return null
}
private fun submitReply(video: VideoContext, reply: MatchedReply, arm: (PendingComment) -> Unit): CommentPublishResult {
val (text, use, photos) = reply.selection
status(if (photos.isEmpty()) "正在回复匹配的评论" else "正在准备 ${photos.size} 张图片并回复匹配的评论")
val beforeClick = {
requireRunning(cancelled)
val armedAt = if (platform.hasPreparedReplyBaseline(reply.target.key, text)) System.currentTimeMillis() else null
arm(PendingComment(video.key, video.title, text, use, photos, reply.target.key, reply.target.author, armedAt))
}
return if (photos.isEmpty()) platform.publishComment(text, beforeClick)
else platform.publishPhotoComment(text, photos, beforeClick)
}
private fun TaskPlan.findType(id: String): ContentType? = contentTypes?.firstOrNull { it.id == id }
private companion object {
const val MAX_COMMENT_SWIPES = 12
const val MIN_RESUME_SEARCH = 12
}
}
+1 -2
View File
@@ -2,9 +2,8 @@
<resources>
<string name="app_name">拾见</string>
<string name="accessibility_label">拾见任务服务</string>
<string name="accessibility_description">在你主动启动任务时识别所选应用的页面、输入搜索词并按配置浏览或发送评论。可在拾见的任务页暂停。</string>
<string name="accessibility_description">在你主动启动任务时按内容类型搜索和浏览视频,并按配置识别、回复匹配的评论。可在拾见任务页暂停。</string>
<string name="tab_task">任务</string>
<string name="tab_settings">配置</string>
<string name="tab_logs">日志</string>
<string name="clear_deepseek_key">清除已保存的 API Key</string>
</resources>
@@ -5,6 +5,7 @@
android:accessibilityFlags="flagReportViewIds|flagRetrieveInteractiveWindows|flagIncludeNotImportantViews"
android:canPerformGestures="true"
android:canRetrieveWindowContent="true"
android:canTakeScreenshot="true"
android:description="@string/accessibility_description"
android:notificationTimeout="200"
android:packageNames="com.ss.android.ugc.aweme" />
@@ -0,0 +1,81 @@
package com.jieliu.app.platform
import kotlin.math.cos
import kotlin.math.sin
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class PublishedPhotoMatcherTest {
@Test fun recognizesCenterCropWithRoundedCornersAndColorVariation() {
val reference = photo(180, 100) { x, y -> pattern(x, y) }
val published = photo(100, 100) { x, y ->
val corner = (x < .07 || x > .93) && (y < .07 || y > .93)
if (corner) rgb(247, 247, 247) else pattern(.5 + (x - .5) * 100 / 180, y, colorShift = 8)
}
assertTrue(PublishedPhotoMatcher.matches(reference, published))
}
@Test fun recognizesCenteredFitWithPlainGutters() {
val reference = photo(160, 80) { x, y -> pattern(x, y) }
val published = photo(80, 80) { x, y ->
if (y < .25 || y > .75) rgb(25, 25, 25) else pattern(x, (y - .25) * 2)
}
assertTrue(PublishedPhotoMatcher.matches(reference, published))
}
@Test fun apparentLetterboxingWithPatternedGuttersIsNotATrustworthyFit() {
val reference = photo(160, 80) { x, y -> pattern(x, y) }
val published = photo(80, 80) { x, y ->
if (y < .25 || y > .75) {
if (x < .5) rgb(220, 225, 210) else rgb(32, 12, 22)
} else {
pattern(x, (y - .25) * 2)
}
}
assertFalse(PublishedPhotoMatcher.matches(reference, published))
}
@Test fun allowsOnePixelOfBoundsRounding() {
val size = 40
val reference = photo(size, size) { x, y -> pattern(x, y) }
val published = photo(size, size) { x, y ->
pattern((x - 1.0 / size).coerceAtLeast(.5 / size), (y + 1.0 / size).coerceAtMost(1 - .5 / size))
}
assertTrue(PublishedPhotoMatcher.matches(reference, published))
}
@Test fun rejectsDifferentPatternOrColorEvenWithTheSameSize() {
val reference = photo(80, 80) { x, y -> pattern(x, y) }
val flipped = photo(80, 80) { x, y -> pattern(1 - x, y) }
val recolored = photo(80, 80) { x, y -> pattern(x, y, colorShift = 27) }
assertFalse(PublishedPhotoMatcher.matches(reference, flipped))
assertFalse(PublishedPhotoMatcher.matches(reference, recolored))
}
@Test fun rejectsMissingFlatTransparentAndTooSmallEvidence() {
val solid = photo(64, 64) { _, _ -> rgb(127, 127, 127) }
val transparent = photo(64, 64) { x, y -> pattern(x, y) and 0x00ffffff }
val tooSmall = photo(8, 8) { x, y -> pattern(x, y) }
assertFalse(PublishedPhotoMatcher.matches(solid, solid))
assertFalse(PublishedPhotoMatcher.matches(transparent, transparent))
assertFalse(PublishedPhotoMatcher.matches(tooSmall, tooSmall))
assertFalse(PublishedPhotoMatcher.matches(solid, PhotoPixels(64, 64, IntArray(10))))
}
private fun photo(width: Int, height: Int, draw: (Double, Double) -> Int) = PhotoPixels(
width, height, IntArray(width * height) { index ->
draw((index % width + .5) / width, (index / width + .5) / height)
},
)
private fun pattern(x: Double, y: Double, colorShift: Int = 0): Int {
val red = (116 + 44 * sin(10 * x + 3 * y) + 21 * cos(10 * y)).toInt() + colorShift
val green = (111 + 39 * cos(7 * x - 4 * y) + 17 * sin(17 * y)).toInt() + colorShift
val blue = (102 + 34 * sin(7 * x + 8 * y) + 20 * cos(16 * x)).toInt() + colorShift
return rgb(red, green, blue)
}
private fun rgb(red: Int, green: Int, blue: Int) =
(255 shl 24) or (red.coerceIn(0, 255) shl 16) or (green.coerceIn(0, 255) shl 8) or blue.coerceIn(0, 255)
}
@@ -0,0 +1,145 @@
package com.jieliu.app.task
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Test
class ContentRulesTest {
private val firstPhoto = TemplatePhoto("16d3b229-bb28-43e6-a8d0-c4f587c04a63", "第一张.jpg")
private val secondPhoto = TemplatePhoto("4fa2bb0a-70cf-45a4-87fe-d83fbd856ac1", "第二张.png")
@Test fun matchingPrefersTheLongestLiteralEvenWithAnEmptyLibrary() {
val short = KeywordRule("short", "API", listOf(ReplyPhrase("short-reply", "简要说明")))
val long = KeywordRule("long", "API 充值")
val matcher = KeywordMatcher(ContentType("type", "模型", listOf(short, long)))
assertEquals(long, matcher.matchingRule("请问 api充值 有变化吗?"))
assertEquals(long, matcher.matchingRule("关于API 充 值"))
assertEquals(short, matcher.matchingRule("这个API可以用"))
assertNull(matcher.matchingRule("xAPI充值 sampleAPIs"))
}
@Test fun matchingPreservesSpacesBetweenLatinWordsAndUsesDeclaredTieOrder() {
val twoWords = KeywordRule("two-words", "API TOKEN")
val first = KeywordRule("first", "AI")
val second = KeywordRule("second", "ML")
val matcher = KeywordMatcher(ContentType("type", "模型", listOf(twoWords, first, second)))
assertEquals(twoWords, matcher.matchingRule("查看API\tTOKEN的配置"))
assertNull(matcher.matchingRule("APITOKEN or AI2"))
assertEquals(first, matcher.matchingRule("ML 和 AI 都用到"))
assertEquals("𠀀ai", normalizeKeyword("𠀀 AI"))
assertEquals("api token", normalizeKeyword(" API Token "))
}
@Test fun migrationPreservesSpecificAndCommonPhotosAndIdsAcrossReordering() {
val specific = "{title}的专属建议"
val common = "{keyword}的通用建议"
val legacy = TaskPlan(
keywords = listOf("灯具", "书架"),
templates = listOf(common),
keywordTemplates = mapOf("灯具" to listOf(specific)),
templatePhotos = mapOf("灯具" to mapOf(specific to listOf(firstPhoto, secondPhoto)),
"" to mapOf(common to listOf(secondPhoto))),
)
val migrated = legacy.migrateContentTypes().also(TaskPlan::validate)
val types = migrated.searchTypes()
assertEquals(legacy.keywords, types.map(ContentType::name))
assertEquals(specific, types[0].rules.single().phrases.single().text)
assertEquals(listOf(firstPhoto, secondPhoto), types[0].rules.single().phrases.single().photos)
assertEquals(common, types[1].rules.single().phrases.single().text)
assertEquals(listOf(secondPhoto), types[1].rules.single().phrases.single().photos)
assertEquals(legacy.templates, migrated.templates)
assertEquals(setOf(firstPhoto.id, secondPhoto.id), migrated.photoIds())
assertEquals(migrated, migrated.migrateContentTypes())
assertEquals(types, legacy.copy(keywords = legacy.keywords.reversed()).migrateContentTypes().searchTypes().reversed())
val defaultType = TaskPlan().migrateContentTypes().searchTypes().single()
assertEquals(TaskPlan().keywords.single(), defaultType.name)
assertEquals(defaultType.name, defaultType.rules.single().keyword)
}
@Test fun scheduledTypesFollowScopeAndLegacyBudgetAllocation() {
val types = listOf(ContentType("a", "甲"), ContentType("b", "乙"), ContentType("c", "丙"))
val all = TaskPlan(limit = 5, contentTypes = types, replyMode = ReplyMode.TEMPLATES)
all.validate()
assertEquals(listOf(0, 0, 1, 1, 2), (0 until all.limit).map(all::contentTypeIndex))
assertEquals("甲", TaskCheckpoint("all", all).keyword)
val scoped = all.copy(selectedTypeId = "b")
assertEquals(listOf(types[1]), scoped.searchTypes())
assertEquals(List(scoped.limit) { 0 }, (0 until scoped.limit).map(scoped::contentTypeIndex))
assertEquals(types[1], TaskCheckpoint("selected", scoped).contentType)
assertEquals("乙", TaskCheckpoint("selected", scoped).keyword)
assertThrows(IllegalArgumentException::class.java) { all.copy(selectedTypeId = "missing").validate() }
}
@Test fun validationRejectsNormalizedDuplicatesAndRepeatedIdsOrPhotos() {
val first = KeywordRule("rule-1", "API 充值")
val duplicate = KeywordRule("rule-2", "api充值")
val firstType = ContentType("type-1", "模型", listOf(first))
val secondType = ContentType("type-2", "工具", listOf(duplicate))
val valid = TaskPlan(contentTypes = listOf(firstType, secondType))
valid.validate()
assertThrows(IllegalArgumentException::class.java) {
valid.copy(contentTypes = listOf(firstType.copy(rules = listOf(first, duplicate)))).validate()
}
assertThrows(IllegalArgumentException::class.java) {
valid.copy(contentTypes = listOf(firstType, secondType.copy(id = firstType.id))).validate()
}
assertThrows(IllegalArgumentException::class.java) {
valid.copy(contentTypes = listOf(firstType, secondType.copy(rules = listOf(duplicate.copy(id = first.id))))).validate()
}
val repeated = ReplyPhrase("same-photo", "建议", listOf(firstPhoto, firstPhoto.copy(displayName = "重复.png")))
val repeatedRule = first.copy(phrases = listOf(repeated))
assertThrows(IllegalArgumentException::class.java) {
valid.copy(contentTypes = listOf(firstType.copy(rules = listOf(repeatedRule)))).validate()
}
val photoPhrase = repeated.copy(photos = listOf(firstPhoto, secondPhoto))
val photoPlan = valid.copy(contentTypes = listOf(firstType.copy(rules = listOf(first.copy(phrases = listOf(photoPhrase))))))
photoPlan.validate()
assertEquals(setOf(firstPhoto.id, secondPhoto.id), photoPlan.photoIds())
}
@Test fun rotationUsesStableIdsAndDeprioritizesDuplicateRenderedText() {
val rule = KeywordRule("rule", "型号", listOf(
ReplyPhrase("first", "{title}", listOf(firstPhoto, secondPhoto)),
ReplyPhrase("duplicate", "同一正文"),
ReplyPhrase("different", "{keyword}的差异"),
))
val plan = TaskPlan(contentTypes = listOf(ContentType("type", "评测", listOf(rule))), limit = 8)
val first = TemplateUse(rule.id, 0, "first")
val start = TaskCheckpoint("reply-cycle", plan).arm(PendingComment(
"a", "同一正文", "同一正文", first, listOf(firstPhoto, secondPhoto), "comment-a", "作者甲",
))
assertEquals("作者甲", start.pending?.targetAuthor)
assertEquals(listOf(firstPhoto, secondPhoto), start.pending?.photos)
val recorded = start.finish("a", Outcome.SENT)
assertEquals("comment-a", recorded.receipts.single().targetKey)
val second = checkNotNull(recorded.selectReply(rule, "同一正文"))
assertEquals("different", second.use.phraseId)
assertEquals("型号的差异", second.text)
val reordered = rule.copy(phrases = rule.phrases.reversed())
assertEquals(second.use.phraseId, recorded.selectReply(reordered, "同一正文")?.use?.phraseId)
var checkpoint = recorded.arm(PendingComment("b", "同一正文", second.text, second.use)).finish("b", Outcome.SENT)
val third = checkNotNull(checkpoint.selectReply(rule, "同一正文"))
assertEquals("duplicate", third.use.phraseId)
checkpoint = checkpoint.arm(PendingComment("c", "同一正文", third.text, third.use)).finish("c", Outcome.SENT)
assertNotEquals(third.use.phraseId, checkpoint.selectReply(rule, "同一正文")?.use?.phraseId)
val edited = rule.copy(phrases = listOf(rule.phrases[0], ReplyPhrase("new", "新话术")))
assertEquals("new", checkpoint.selectReply(edited, "同一正文")?.use?.phraseId)
assertNull(checkpoint.selectReply(rule.copy(phrases = emptyList()), "同一正文"))
}
@Test fun anEmptyEditableLibraryCanBeSavedAndPhraseLimitIsEnforced() {
TaskPlan(contentTypes = emptyList(), replyMode = ReplyMode.TEMPLATES).validate()
val maximum = List(TaskPlan.MAX_RULE_PHRASES) { ReplyPhrase("phrase-$it", "样例 $it") }
val rule = KeywordRule("rule", "关键词", maximum)
val type = ContentType("type", "内容类型", listOf(rule))
val plan = TaskPlan(contentTypes = listOf(type))
plan.validate()
val overLimit = rule.copy(phrases = maximum + ReplyPhrase("extra", "额外一条"))
assertThrows(IllegalArgumentException::class.java) {
plan.copy(contentTypes = listOf(type.copy(rules = listOf(overLimit)))).validate()
}
}
}
@@ -1,6 +1,7 @@
package com.jieliu.app.task
import com.jieliu.app.platform.CommentPublishResult
import com.jieliu.app.platform.CommentTarget
import com.jieliu.app.platform.PlatformAdapter
import com.jieliu.app.platform.VideoContext
import org.junit.Assert.assertEquals
@@ -8,204 +9,445 @@ import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.UUID
class TaskRunnerTest {
@Test fun keywordAndCommonRepliesBypassTheModelAndAreJournaledBeforeConfirmedSend() {
val plan = fastPlan(ReplyMode.DEEPSEEK).copy(
keywords = listOf("台灯", "整理"),
keywordTemplates = mapOf("台灯" to listOf("专属建议")),
templates = listOf("通用建议"),
limit = 2,
)
val store = RecordingStore(TaskCheckpoint("local", plan))
val platform = FakePlatform(store)
var modelCalls = 0
@Test fun searchesTypeNameAndRepliesInThreadToTheMatchingKeywordAfterScrolling() {
val plan = plan(firstType, secondType)
val store = RecordingStore(TaskCheckpoint("type-search", plan))
val platform = FakePlatform(store, listOf(
listOf(target("first", "有谁讨论键盘吗")),
listOf(target("second", "想了解大模型 API 充值")),
))
execute(store, platform) { _, _, _ ->
modelCalls++
"模型建议"
}
execute(store, platform)
assertEquals(0, modelCalls)
assertEquals(listOf("专属建议", "通用建议"), platform.attempts)
assertEquals(platform.attempts, platform.pendingAtSend.map { it?.text })
val uses = listOf(TemplateUse("台灯", 0), TemplateUse("", 0))
assertEquals(uses, platform.pendingAtSend.map { it?.templateUse })
assertEquals(uses, store.checkpoint.receipts.map { it.templateUse })
assertEquals(listOf(Outcome.SENT, Outcome.SENT), store.checkpoint.receipts.map { it.outcome })
assertEquals(2, store.checkpoint.sentCount)
assertNull(store.checkpoint.pending)
assertEquals(listOf("大模型充值"), platform.searches)
assertEquals(1, platform.swipes)
val attempt = platform.attempts.single()
assertEquals("second", attempt.targetKey)
assertEquals("测试用户", attempt.targetAuthor)
assertEquals("API 充值对应的图文", attempt.text)
assertEquals(photos, attempt.photos)
assertEquals(apiRule.id, attempt.templateUse?.group)
assertEquals(apiRule.phrases.single().id, attempt.templateUse?.phraseId)
assertEquals(listOf(Outcome.SENT), store.checkpoint.receipts.map { it.outcome })
assertTrue(platform.rechecks.isEmpty())
assertTrue(store.checkpoint.complete)
}
@Test fun missingLocalRepliesUseTheModelInDeepSeekMode() {
val store = RecordingStore(TaskCheckpoint("model", fastPlan(ReplyMode.DEEPSEEK)))
val platform = FakePlatform(store)
val requests = mutableListOf<Triple<String, String, List<String>>>()
execute(store, platform) { keyword, title, comments ->
requests.add(Triple(keyword, title, comments))
"模型建议"
}
assertEquals(listOf(Triple("台灯", "样片-台灯", platform.comments)), requests)
assertEquals(listOf("模型建议"), platform.attempts)
assertEquals("模型建议", platform.pendingAtSend.single()?.text)
assertNull(platform.pendingAtSend.single()?.templateUse)
assertEquals(Outcome.SENT, store.checkpoint.receipts.single().outcome)
assertNull(store.checkpoint.receipts.single().templateUse)
}
@Test fun templateOnlyModeWithNoApplicablePoolSkipsWithoutModelOrPublishing() {
val plan = fastPlan(ReplyMode.TEMPLATES).copy(
keywords = listOf("台灯", "整理"),
keywordTemplates = mapOf("整理" to listOf("整理建议")),
)
val store = RecordingStore(TaskCheckpoint("no-pool", plan))
val platform = FakePlatform(store)
var modelCalls = 0
execute(store, platform) { _, _, _ ->
modelCalls++
"模型建议"
}
assertEquals(0, modelCalls)
assertSkippedWithLog(store, platform)
}
@Test fun modelFailureWithoutALocalReplySkipsWithALog() {
val store = RecordingStore(TaskCheckpoint("model-unavailable", fastPlan(ReplyMode.DEEPSEEK)))
val platform = FakePlatform(store)
var modelCalls = 0
execute(store, platform) { _, _, _ ->
modelCalls++
error("模拟模型故障")
}
assertEquals(1, modelCalls)
assertSkippedWithLog(store, platform)
}
@Test fun uncertainSendRetainsItsJournalAndCannotLaunchOnResume() {
val plan = fastPlan(ReplyMode.TEMPLATES).copy(keywordTemplates = mapOf("台灯" to listOf("专属建议")))
val store = RecordingStore(TaskCheckpoint("uncertain", plan))
val platform = FakePlatform(store, CommentPublishResult.UNCERTAIN)
@Test fun noMatchAndEmptyWinningLibraryNeverSend() {
val broaderType = firstType.copy(rules = firstType.rules + rule("API 充值服务"))
val store = RecordingStore(TaskCheckpoint("no-match", plan(broaderType, secondType)))
val platform = FakePlatform(store, listOf(
listOf(target("first", "想看看键盘"), target("second", "需要 API 充值服务")),
))
execute(store, platform)
assertEquals(listOf("专属建议"), platform.attempts)
val pending = checkNotNull(store.checkpoint.pending)
assertEquals(pending, platform.pendingAtSend.single())
assertEquals(TemplateUse("台灯", 0), pending.templateUse)
assertTrue(store.checkpoint.receipts.isEmpty())
assertFalse(store.checkpoint.complete)
assertTrue(store.logs.any { (message, warning) -> warning && "核对" in message })
val resumed = RecordingStore(store.checkpoint)
val nextPlatform = FakePlatform(resumed)
execute(resumed, nextPlatform)
assertEquals(0, nextPlatform.launches)
assertTrue(nextPlatform.attempts.isEmpty())
assertEquals(pending, resumed.checkpoint.pending)
assertEquals(Outcome.NO_REPLY, store.checkpoint.receipts.single().outcome)
assertTrue(platform.preparations.isEmpty())
assertTrue(platform.attempts.isEmpty())
assertTrue(store.logs.any { "已跳过" in it })
}
@Test fun imageTemplateUsesImagePublisherAndKeepsThePhotoWhenTheReceiptIsUncertain() {
val photo = TemplatePhoto("c49b0088-a509-4c2d-b7e8-8455f6bf7f39", "桌面.png")
val plan = fastPlan(ReplyMode.TEMPLATES).copy(
keywordTemplates = mapOf("台灯" to listOf("专属建议")),
templatePhotos = mapOf("台灯" to mapOf("专属建议" to photo)),
)
val store = RecordingStore(TaskCheckpoint("photo", plan))
val platform = FakePlatform(store, CommentPublishResult.UNCERTAIN)
@Test fun disappearingTargetDoesNotBlockAnotherVisibleMatch() {
val store = RecordingStore(TaskCheckpoint("missing", plan(firstType)))
val platform = FakePlatform(store, listOf(listOf(
target("stale", "API充值"),
target("visible", "付款方式是什么"),
))).apply { unavailable.add("stale") }
execute(store, platform)
assertEquals(listOf(photo), platform.photoAttempts)
assertEquals(listOf("专属建议"), platform.attempts)
assertEquals(photo, platform.pendingAtSend.single()?.photo)
assertEquals(photo, store.checkpoint.pending?.photo)
assertTrue(store.checkpoint.receipts.isEmpty())
assertEquals(listOf("stale", "visible"), platform.preparations)
assertEquals("visible", platform.attempts.single().targetKey)
assertEquals("付款方式对应的话术", platform.attempts.single().text)
}
private fun assertSkippedWithLog(store: RecordingStore, platform: FakePlatform) {
@Test fun reloadsChangedKeywordPhraseAndPhotosBetweenCommentScreens() {
val store = RecordingStore(TaskCheckpoint("live-edit", plan(firstType)))
val replacement = apiRule.copy(
keyword = "订阅价格",
phrases = listOf(apiRule.phrases.single().copy(text = "新话术 {keyword}", photos = photos.reversed())),
)
val platform = FakePlatform(store, listOf(
listOf(target("first", "无匹配内容")),
listOf(target("second", "请问订阅价格")),
)).apply {
onScroll = { store.plan = plan(firstType.copy(rules = listOf(replacement))) }
}
execute(store, platform)
assertEquals("新话术 订阅价格", platform.attempts.single().text)
assertEquals(photos.reversed(), platform.attempts.single().photos)
assertEquals("API 充值", store.checkpoint.plan.contentTypes?.first()?.rules?.first()?.keyword)
}
@Test fun editImmediatelyBeforeSubmitPreventsClickAndLeavesNoSendIntent() {
val store = RecordingStore(TaskCheckpoint("edit-before-send", plan(firstType)))
val platform = FakePlatform(store, listOf(listOf(target("match", "API 充值")))).apply {
beforePublish = {
val updatedRule = apiRule.copy(phrases = apiRule.phrases.map { it.copy(photos = photos.reversed()) })
store.plan = plan(firstType.copy(rules = listOf(updatedRule)))
}
}
execute(store, platform)
assertEquals(listOf("match"), platform.preparations)
assertTrue(platform.attempts.isEmpty())
assertNull(store.checkpoint.pending)
assertEquals(Outcome.NO_REPLY, store.checkpoint.receipts.single().outcome)
assertNull(store.checkpoint.receipts.single().templateUse)
assertEquals(0, store.checkpoint.sentCount)
assertTrue(store.checkpoint.complete)
assertTrue(store.logs.any { (message, _) -> "跳过" in message })
assertTrue(store.checkpoint.message.contains("未提交"))
assertTrue(store.checkpoint.receipts.isEmpty())
}
private fun fastPlan(mode: ReplyMode) = TaskPlan(
keywords = listOf("台灯"),
limit = 1,
// This fixture calls the runner directly, after input validation would normally run.
watchSeconds = 0..0,
replyMode = mode,
)
@Test fun uncertainTargetedReplyKeepsTheParentAndAllImagesAndDoesNotRetry() {
val store = RecordingStore(TaskCheckpoint("uncertain", plan(firstType)))
val platform = FakePlatform(store, listOf(listOf(target("match", "API 充值"))), CommentPublishResult.UNCERTAIN)
private fun execute(
store: RecordingStore,
platform: FakePlatform,
model: ((String, String, List<String>) -> String)? = null,
) {
execute(store, platform)
val pending = checkNotNull(store.checkpoint.pending)
assertEquals(pending, platform.attempts.single())
assertEquals("match", pending.targetKey)
assertEquals(photos, pending.photos)
assertNull(pending.armedAtEpochMs)
assertTrue(platform.rechecks.isEmpty())
assertTrue(store.checkpoint.receipts.isEmpty())
assertFalse(store.checkpoint.complete)
val resumed = FakePlatform(store)
execute(store, resumed)
assertEquals(0, resumed.launches)
assertTrue(resumed.attempts.isEmpty())
assertEquals(pending, store.checkpoint.pending)
}
@Test fun uncertainReplyIsReadBackOnceWithinTheTaskWithoutSubmittingAgain() {
val store = RecordingStore(TaskCheckpoint("inline-recheck", plan(firstType)))
val platform = FakePlatform(store, listOf(listOf(target("match", "API 充值"))), CommentPublishResult.UNCERTAIN).apply {
knownBaseline = true
recheckResult = CommentPublishResult.CONFIRMED
}
execute(store, platform)
assertEquals(1, platform.launches)
assertEquals(listOf("大模型充值", "大模型充值"), platform.searches)
assertEquals(listOf("video-0", "video-0"), platform.openedVideos)
assertEquals(listOf("API 充值对应的图文"), platform.preparedTexts)
assertEquals(1, platform.publishCalls)
assertEquals(1, store.pendingWrites)
assertEquals(listOf("video-0" to platform.attempts.single()), platform.rechecks)
assertNull(store.checkpoint.pending)
assertEquals(Outcome.SENT, store.checkpoint.receipts.single().replies.single().outcome)
assertEquals(1, store.checkpoint.sentCount)
assertTrue(store.logs.contains("本次任务继续核对已提交回复"))
assertTrue(store.logs.contains("第 1 条视频已确认 1/1 条回复"))
assertFalse(store.logs.contains("开始自动核对一条待确认回复"))
}
@Test fun aPublishExceptionAfterArmingLeavesThePendingClaimWithoutReadback() {
val store = RecordingStore(TaskCheckpoint("publish-exception", plan(firstType)))
val platform = FakePlatform(store, listOf(listOf(target("match", "API 充值")))).apply {
knownBaseline = true
afterPublish = { error("合成发送异常") }
}
execute(store, platform)
assertEquals(1, platform.publishCalls)
assertEquals(1, store.pendingWrites)
assertEquals(platform.attempts.single(), store.checkpoint.pending)
assertTrue(store.checkpoint.canAutomaticallyRecheck())
assertTrue(platform.rechecks.isEmpty())
assertTrue(store.checkpoint.receipts.isEmpty())
}
@Test fun automaticRecheckFindsTheActiveVideoAndRecordsOnlyTheExistingReply() {
val plan = plan(firstType).copy(limit = 3, repliesPerVideo = 2)
val store = RecordingStore(TaskCheckpoint("auto-recheck", plan))
val matching = listOf(listOf(target("original", "API 充值"), target("other", "付款方式")))
val original = FakePlatform(store, result = CommentPublishResult.UNCERTAIN).apply {
knownBaseline = true
screensForVideo = { video -> if (video.key == "video-0") listOf(emptyList()) else matching }
}
execute(store, original)
val pending = checkNotNull(store.checkpoint.pending)
assertEquals("video-1", pending.videoKey)
assertTrue(store.checkpoint.canAutomaticallyRecheck())
assertEquals(listOf("video-1" to pending), original.rechecks)
val resumed = FakePlatform(store, matching).apply { recheckResult = CommentPublishResult.CONFIRMED }
execute(store, resumed, recheckPending = true)
assertEquals(listOf("大模型充值"), resumed.searches)
assertEquals(listOf("video-1"), resumed.openedVideos)
assertEquals(listOf("video-1" to pending), resumed.rechecks)
assertTrue(resumed.preparations.isEmpty())
assertTrue(resumed.attempts.isEmpty())
assertNull(store.checkpoint.pending)
assertEquals("video-1", store.checkpoint.activeVideo?.videoKey)
val recorded = checkNotNull(store.checkpoint.activeVideo).replies.single()
assertEquals(Outcome.SENT, recorded.outcome)
assertEquals(pending.targetKey, recorded.targetKey)
}
@Test fun inconclusiveAutomaticRecheckKeepsTheClaimAndLegacyClaimsDoNotLaunch() {
val plan = plan(firstType)
val pending = PendingComment("video-0", "先前视频", "已提交的话术", targetKey = "original",
armedAtEpochMs = System.currentTimeMillis())
val initial = TaskCheckpoint("pending", plan).startVideo(pending.videoKey).arm(pending)
val store = RecordingStore(initial)
val platform = FakePlatform(store)
execute(store, platform, recheckPending = true)
assertEquals(listOf("video-0" to pending), platform.rechecks)
assertTrue(platform.attempts.isEmpty())
assertEquals(pending, store.checkpoint.pending)
assertTrue(store.checkpoint.receipts.isEmpty())
val legacy = RecordingStore(initial.copy(pending = pending.copy(armedAtEpochMs = null)))
val untouched = FakePlatform(legacy)
execute(legacy, untouched, recheckPending = true)
assertEquals(0, untouched.launches)
assertEquals(pending.copy(armedAtEpochMs = null), legacy.checkpoint.pending)
}
@Test fun browseUsesOnlySelectedTypeWithoutOpeningTheCommentPanel() {
val plan = plan(firstType, secondType).copy(selectedTypeId = secondType.id, replyMode = ReplyMode.BROWSE)
val store = RecordingStore(TaskCheckpoint("browse", plan))
val platform = FakePlatform(store)
execute(store, platform)
assertEquals(listOf(secondType.name), platform.searches)
assertEquals(0, platform.commentPanels)
assertEquals(Outcome.WATCHED, store.checkpoint.receipts.single().outcome)
}
@Test fun anEndlessCommentListHasABoundedSearch() {
val store = RecordingStore(TaskCheckpoint("bounded", plan(firstType)))
val platform = FakePlatform(store, List(25) { listOf(target(it.toString(), "不含配置关键词")) })
execute(store, platform)
assertEquals(12, platform.swipes)
assertEquals(Outcome.NO_REPLY, store.checkpoint.receipts.single().outcome)
assertTrue(platform.attempts.isEmpty())
}
@Test fun reachesEachVideoQuotaAndKeepsDistinctRepliesInTheirOwnVideo() {
val store = RecordingStore(TaskCheckpoint("quota", plan(firstType).copy(limit = 2, repliesPerVideo = 2)))
val platform = FakePlatform(store).apply {
screensForVideo = { video ->
if (video.key == "video-0") {
listOf(listOf(target("a", "付款方式"), target("b", "付款方式"), target("extra", "付款方式")))
} else {
listOf(listOf(target("c", "付款方式")))
}
}
}
execute(store, platform)
assertEquals(listOf("a", "b", "c"), platform.attempts.map { it.targetKey })
assertEquals(listOf("video-0", "video-1"), platform.openedVideos)
assertEquals(listOf(listOf("a", "b"), listOf("c")), store.checkpoint.receipts.map { video ->
video.replies.map { it.targetKey }
})
assertEquals(3, store.checkpoint.sentCount)
assertTrue(store.checkpoint.complete)
assertTrue(store.logs.any { "1/2 条" in it && "评论扫描结束" in it })
}
@Test fun emptyOrUnmatchedShortCommentSectionsAdvanceToTheNextVideo() {
val store = RecordingStore(TaskCheckpoint("short-lists", plan(firstType).copy(limit = 3, repliesPerVideo = 3)))
val platform = FakePlatform(store).apply {
screensForVideo = { video ->
listOf(when (video.key) {
"video-0" -> emptyList()
"video-1" -> listOf(target("unrelated", "键盘"))
else -> listOf(target("match", "付款方式"))
})
}
}
execute(store, platform)
assertEquals(listOf("video-0", "video-1", "video-2"), platform.openedVideos)
assertEquals(listOf(Outcome.NO_REPLY, Outcome.NO_REPLY, Outcome.SENT), store.checkpoint.receipts.map { it.outcome })
assertEquals("match", platform.attempts.single().targetKey)
assertEquals(0, platform.swipes)
}
@Test fun manualConfirmationBelowQuotaResumesTheSameVideoWithoutReplyingToTheSameTarget() {
val store = RecordingStore(TaskCheckpoint("resume-quota", plan(firstType).copy(limit = 2, repliesPerVideo = 2)))
val remaining = listOf(listOf(target("first", "付款方式"), target("second", "付款方式")))
val firstRun = FakePlatform(store, result = CommentPublishResult.UNCERTAIN).apply {
screensForVideo = { video -> if (video.key == "video-0") listOf(emptyList()) else remaining }
}
execute(store, firstRun)
assertEquals("video-1", store.checkpoint.activeVideo?.videoKey)
assertEquals("first", store.checkpoint.pending?.targetKey)
store.saveCheckpoint(store.checkpoint.recordReply(Outcome.USER_CONFIRMED))
val secondRun = FakePlatform(store, remaining)
execute(store, secondRun)
assertEquals(listOf("video-1"), secondRun.openedVideos)
assertEquals(listOf("second"), secondRun.preparations)
assertEquals(listOf(Outcome.USER_CONFIRMED, Outcome.SENT), store.checkpoint.receipts.last().replies.map { it.outcome })
assertEquals(2, store.checkpoint.sentCount)
assertNull(store.checkpoint.activeVideo)
assertTrue(store.checkpoint.complete)
}
@Test fun aReplyAtTheLastScreenDoesNotResetTheVideoScanningLimit() {
val store = RecordingStore(TaskCheckpoint("bounded-after-reply", plan(firstType).copy(repliesPerVideo = 2)))
val platform = FakePlatform(store, List(24) { screen ->
if (screen >= 12) listOf(target("reply-$screen", "付款方式")) else emptyList()
})
execute(store, platform)
assertEquals(12, platform.swipes)
assertEquals(listOf("reply-12"), platform.attempts.map { it.targetKey })
assertEquals(1, store.checkpoint.sentCount)
assertTrue(store.checkpoint.complete)
}
private fun execute(store: RecordingStore, platform: FakePlatform, recheckPending: Boolean = false) {
val initial = store.checkpoint
TaskRunner(store, initial.plan, platform, model, { false }) {}.run(initial)
TaskRunner(store, initial.plan, platform, { false }) {}.run(initial, recheckPending = recheckPending)
}
private class RecordingStore(initial: TaskCheckpoint) : TaskRunStorage {
var checkpoint = initial
private set
val logs = mutableListOf<Pair<String, Boolean>>()
var plan = initial.plan
val logs = mutableListOf<String>()
var pendingWrites = 0
private set
override fun readPlan() = plan
override fun saveCheckpoint(checkpoint: TaskCheckpoint) {
this.checkpoint = checkpoint
}
override fun savePendingIfCurrent(checkpoint: TaskCheckpoint, matchesPlan: (TaskPlan) -> Boolean): Boolean {
if (!matchesPlan(readPlan())) return false
pendingWrites++
saveCheckpoint(checkpoint)
return true
}
override fun appendLog(message: String, warning: Boolean) {
logs.add(message to warning)
logs.add(message)
}
}
private class FakePlatform(
private val store: RecordingStore,
private val screens: List<List<CommentTarget>> = listOf(emptyList()),
private val result: CommentPublishResult = CommentPublishResult.CONFIRMED,
) : PlatformAdapter {
val attempts = mutableListOf<String>()
val pendingAtSend = mutableListOf<PendingComment?>()
val photoAttempts = mutableListOf<TemplatePhoto>()
val comments = listOf("模拟评论样本")
val attempts = mutableListOf<PendingComment>()
val searches = mutableListOf<String>()
val openedVideos = mutableListOf<String>()
val preparations = mutableListOf<String>()
val preparedTexts = mutableListOf<String>()
val rechecks = mutableListOf<Pair<String, PendingComment>>()
val unavailable = mutableSetOf<String>()
var knownBaseline = false
var recheckResult = CommentPublishResult.UNCERTAIN
var onScroll: () -> Unit = {}
var beforePublish: () -> Unit = {}
var afterPublish: () -> Unit = {}
var screensForVideo: ((VideoContext) -> List<List<CommentTarget>>)? = null
var launches = 0
private set
var swipes = 0
private set
var commentPanels = 0
private set
var publishCalls = 0
private set
private val firstVideoBySearch = mutableMapOf<String, Int>()
private var nextKey = 0
private var currentScreen = 0
private var currentScreens = screens
private var replyTarget: CommentTarget? = null
private lateinit var video: VideoContext
override fun launch() {
launches++
}
override fun search(keyword: String): VideoContext = showVideo("样片-$keyword")
override fun search(keyword: String): VideoContext {
searches.add(keyword)
nextKey = firstVideoBySearch.getOrPut(keyword) { nextKey }
return showVideo("样片-$keyword")
}
override fun currentVideo(): VideoContext = video
override fun nextVideo(previous: VideoContext): VideoContext = showVideo("后续样片")
override fun openComments(expected: VideoContext): List<String> = comments
override fun publishComment(text: String, beforeClick: () -> Unit): CommentPublishResult {
beforeClick()
pendingAtSend.add(store.checkpoint.pending)
attempts.add(text)
return result
override fun openComments(expected: VideoContext): List<String> {
commentPanels++
openedVideos.add(expected.key)
currentScreen = 0
currentScreens = screensForVideo?.invoke(expected) ?: screens
replyTarget = null
return emptyList()
}
override fun publishPhotoComment(text: String, photo: TemplatePhoto, beforeClick: () -> Unit): CommentPublishResult {
photoAttempts.add(photo)
return publishComment(text, beforeClick)
override fun scanComments(): List<CommentTarget> = currentScreens[currentScreen]
override fun scrollComments(): Boolean {
if (currentScreen == currentScreens.lastIndex) return false
currentScreen++
swipes++
onScroll()
return true
}
override fun prepareReply(target: CommentTarget, expectedText: String): Boolean {
preparations.add(target.key)
if (target.key in unavailable) return false
preparedTexts.add(expectedText)
replyTarget = target
return true
}
override fun hasPreparedReplyBaseline(targetKey: String, text: String): Boolean =
knownBaseline && replyTarget?.key == targetKey && preparedTexts.lastOrNull() == text
override fun confirmPendingReply(video: VideoContext, pending: PendingComment): CommentPublishResult {
rechecks.add(video.key to pending)
return recheckResult
}
override fun publishComment(text: String, beforeClick: () -> Unit): CommentPublishResult =
publishPhotoComment(text, emptyList(), beforeClick)
override fun publishPhotoComment(text: String, photos: List<TemplatePhoto>, beforeClick: () -> Unit): CommentPublishResult {
publishCalls++
val target = checkNotNull(replyTarget)
beforePublish()
beforeClick()
val journal = checkNotNull(store.checkpoint.pending)
check(journal.targetKey == target.key && journal.text == text && journal.photos == photos)
attempts.add(journal)
afterPublish()
return result
}
override fun closeComments() = Unit
@@ -215,4 +457,25 @@ class TaskRunnerTest {
return video
}
}
private companion object {
val photos = listOf(TemplatePhoto(id("photo1"), "一.png"), TemplatePhoto(id("photo2"), "二.png"))
val apiRule = rule("API 充值", "API 充值对应的图文", photos)
val firstType = ContentType(id("大模型充值"), "大模型充值", listOf(apiRule, rule("付款方式", "付款方式对应的话术")))
val secondType = ContentType(id("键盘外设"), "键盘外设", listOf(rule("键盘", "另一个类型的话术")))
fun plan(vararg types: ContentType) = TaskPlan(
contentTypes = types.toList(),
limit = 1,
watchSeconds = 0..0, // The runner fixture skips UI time-range validation.
replyMode = ReplyMode.TEMPLATES,
)
fun target(key: String, text: String) = CommentTarget(key, text, "测试用户")
fun rule(keyword: String, text: String? = null, photos: List<TemplatePhoto> = emptyList()) =
KeywordRule(id("rule-$keyword"), keyword, text?.let { listOf(ReplyPhrase(id("phrase-$keyword"), it, photos)) }.orEmpty())
fun id(value: String) = UUID.nameUUIDFromBytes(value.toByteArray()).toString()
}
}
@@ -1,13 +1,14 @@
package com.jieliu.app.task
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Test
import java.util.UUID
class TemplatePhotoTest {
private val lampPhoto = TemplatePhoto("16d3b229-bb28-43e6-a8d0-c4f587c04a63", "台灯.jpg")
private val commonPhoto = TemplatePhoto("4fa2bb0a-70cf-45a4-87fe-d83fbd856ac1", "参考图.png")
private val deskPhoto = TemplatePhoto("34f80961-52ed-43ca-aeb6-58e3880997b9", "桌面.jpg")
@Test fun bindingUsesTheRawPhraseAndStaysInItsGroup() {
val phrase = "{title}的摆放建议"
@@ -15,7 +16,7 @@ class TemplatePhotoTest {
keywords = listOf("灯具", "书架"),
templates = listOf(phrase),
keywordTemplates = mapOf("灯具" to listOf(phrase)),
templatePhotos = mapOf("灯具" to mapOf(phrase to lampPhoto), "" to mapOf(phrase to commonPhoto)),
templatePhotos = mapOf("灯具" to mapOf(phrase to listOf(lampPhoto, deskPhoto)), "" to mapOf(phrase to listOf(commonPhoto))),
)
plan.validate()
val checkpoint = TaskCheckpoint("photo-bindings", plan)
@@ -23,28 +24,29 @@ class TemplatePhotoTest {
val keyword = checkNotNull(checkpoint.selectTemplate("灯具", "台灯"))
val common = checkNotNull(checkpoint.selectTemplate("书架", "书架"))
assertEquals("台灯的摆放建议", keyword.text)
assertEquals(lampPhoto, keyword.photo)
assertEquals(commonPhoto, common.photo)
assertEquals(setOf(lampPhoto.id, commonPhoto.id), plan.photoIds())
assertNull(checkNotNull(checkpoint.copy(plan = plan.copy(templatePhotos = emptyMap()))
.selectTemplate("灯具", "台灯")).photo)
assertEquals(listOf(lampPhoto, deskPhoto), keyword.photos)
assertEquals(listOf(commonPhoto), common.photos)
assertEquals(setOf(lampPhoto.id, deskPhoto.id, commonPhoto.id), plan.photoIds())
val legacy = checkpoint.copy(plan = plan.copy(templatePhotos = emptyMap()))
assertEquals(emptyList<TemplatePhoto>(), checkNotNull(legacy.selectTemplate("灯具", "台灯")).photos)
}
@Test fun photosKeepTheTextRotationAndAnArmedDraftAcrossResume() {
val phrases = listOf("{title}的角度", "色温建议", "{title}的角度")
val plainPlan = TaskPlan(keywords = listOf("灯具"), keywordTemplates = mapOf("灯具" to phrases), limit = 4)
val photoPlan = plainPlan.copy(templatePhotos = mapOf("灯具" to mapOf(phrases.first() to lampPhoto)))
val orderedPhotos = listOf(deskPhoto, lampPhoto)
val photoPlan = plainPlan.copy(templatePhotos = mapOf("灯具" to mapOf(phrases.first() to orderedPhotos)))
var checkpoint = TaskCheckpoint("photo-rotation", photoPlan)
repeat(photoPlan.limit) { index ->
val expected = checkpoint.copy(plan = plainPlan).selectTemplate("灯具", "台灯")
val picked = checkNotNull(checkpoint.selectTemplate("灯具", "台灯"))
assertEquals(expected, picked.copy(photo = null))
assertEquals(if (picked.use.index == 0) lampPhoto else null, picked.photo)
assertEquals(expected, picked.copy(photos = emptyList()))
assertEquals(if (picked.use.index == 0) orderedPhotos else emptyList(), picked.photos)
val videoKey = "video-$index"
val armed = checkpoint.arm(PendingComment(videoKey, "台灯", picked.text, picked.use, picked.photo))
val armed = checkpoint.arm(PendingComment(videoKey, "台灯", picked.text, picked.use, picked.photos))
val resumed = armed.copy(message = "发送结果待核对")
assertEquals(picked.photo, resumed.pending?.photo)
assertEquals(picked.photos, resumed.pending?.photos)
checkpoint = resumed.finish(videoKey, Outcome.SKIPPED)
assertEquals(picked.use, checkpoint.receipts.last().templateUse)
}
@@ -53,10 +55,10 @@ class TemplatePhotoTest {
@Test fun invalidPhotoMetadataAndOrphanedBindingsAreRejected() {
val plan = TaskPlan(keywords = listOf("灯具"), keywordTemplates = mapOf("灯具" to listOf("观察细节")))
assertThrows(IllegalArgumentException::class.java) {
plan.copy(templatePhotos = mapOf("灯具" to mapOf("观察细节 " to lampPhoto))).validate()
plan.copy(templatePhotos = mapOf("灯具" to mapOf("观察细节 " to listOf(lampPhoto)))).validate()
}
assertThrows(IllegalArgumentException::class.java) {
plan.copy(templatePhotos = mapOf("书架" to mapOf("观察细节" to lampPhoto))).validate()
plan.copy(templatePhotos = mapOf("书架" to mapOf("观察细节" to listOf(lampPhoto)))).validate()
}
assertThrows(IllegalArgumentException::class.java) { TemplatePhoto(lampPhoto.id.uppercase(), "图片.jpg") }
assertThrows(IllegalArgumentException::class.java) { TemplatePhoto(lampPhoto.id, "\n") }
@@ -64,4 +66,18 @@ class TemplatePhotoTest {
assertEquals("图片", TemplatePhoto.sanitizeDisplayName("\t"))
assertEquals("🙂".repeat(120), TemplatePhoto.sanitizeDisplayName("🙂".repeat(121)))
}
@Test fun onlyNonemptyUniquePhotoListsUpToNineAreValidBindings() {
val phrase = "观察细节"
val plan = TaskPlan(templates = listOf(phrase))
val maximum = List(TaskPlan.MAX_TEMPLATE_PHOTOS) { index ->
lampPhoto.copy(id = UUID(0, index.toLong()).toString())
}
plan.copy(templatePhotos = mapOf("" to mapOf(phrase to maximum))).validate()
for (photos in listOf(emptyList(), maximum + deskPhoto, listOf(lampPhoto, lampPhoto.copy(displayName = "同一张.png")))) {
assertThrows(IllegalArgumentException::class.java) {
plan.copy(templatePhotos = mapOf("" to mapOf(phrase to photos))).validate()
}
}
}
}
@@ -0,0 +1,109 @@
package com.jieliu.app.task
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
class VideoReplyQuotaTest {
@Test fun confirmedRepliesConsumeQuotaOnceAndAHandledTargetCannotBeRepeated() {
val first = TaskCheckpoint("quota", TaskPlan(limit = 2, repliesPerVideo = 2)).startVideo("video")
assertSame(first, first.startVideo("video"))
assertThrows(IllegalStateException::class.java) { first.startVideo("another-video") }
val skipped = first.arm(pending("video", "skipped")).recordReply(Outcome.SKIPPED)
assertEquals(0, skipped.sentCount)
assertTrue(skipped.activeVideo?.hasHandled("skipped") == true)
assertThrows(IllegalStateException::class.java) { skipped.arm(pending("video", "skipped")) }
assertThrows(IllegalStateException::class.java) { skipped.arm(pending("another-video", "target")) }
val sent = skipped.arm(pending("video", "first-send")).recordReply(Outcome.SENT)
assertEquals(1, sent.sentCount)
assertEquals(1, sent.activeVideo?.sentCount)
assertTrue(sent.receipts.isEmpty())
assertFalse(sent.hasSeen("video"))
assertNull(sent.pending)
val finalPending = sent.arm(pending("video", "second-send"))
assertThrows(IllegalStateException::class.java) { finalPending.finishVideo() }
val closed = finalPending.recordReply(Outcome.USER_CONFIRMED)
assertNull(closed.activeVideo)
assertNull(closed.pending)
assertEquals(2, closed.sentCount)
assertFalse(closed.complete)
assertTrue(closed.hasSeen("video"))
val receipt = closed.receipts.single()
assertEquals(Outcome.SENT, receipt.outcome)
assertEquals(listOf("skipped", "first-send", "second-send"), receipt.replies.map(ReplyReceipt::targetKey))
assertEquals(listOf(Outcome.SKIPPED, Outcome.SENT, Outcome.USER_CONFIRMED), receipt.replies.map(ReplyReceipt::outcome))
}
@Test fun closingBelowQuotaPreservesPartialAndEmptyOutcomes() {
val active = TaskCheckpoint("partial", TaskPlan(limit = 1, repliesPerVideo = 4)).startVideo("video")
val skipped = active.arm(pending("video", "target")).recordReply(Outcome.SKIPPED).finishVideo()
assertEquals(Outcome.SKIPPED, skipped.receipts.single().outcome)
assertEquals(1, skipped.receipts.single().replies.size)
assertEquals(0, skipped.sentCount)
assertTrue(skipped.complete)
val confirmed = active.arm(pending("video", "target")).recordReply(Outcome.USER_CONFIRMED).finishVideo()
assertEquals(Outcome.USER_CONFIRMED, confirmed.receipts.single().outcome)
assertEquals(1, confirmed.sentCount)
assertEquals(Outcome.NO_REPLY, active.finishVideo().receipts.single().outcome)
}
@Test fun oldPendingAndReceiptsCoexistWithNestedAndActiveReplies() {
val old = TaskCheckpoint("legacy", TaskPlan(limit = 5)).arm(PendingComment("legacy-video", "标题", "旧评论"))
val afterReview = old.recordReply(Outcome.USER_CONFIRMED)
assertEquals(1, afterReview.sentCount)
assertNull(afterReview.activeVideo)
assertTrue(afterReview.receipts.single().replies.isEmpty())
val newPlan = afterReview.plan.copy(repliesPerVideo = 2)
val secondVideo = afterReview.copy(plan = newPlan).startVideo("new-video")
.arm(pending("new-video", "new-a")).recordReply(Outcome.SENT)
.arm(pending("new-video", "new-b")).recordReply(Outcome.SENT)
val third = secondVideo.startVideo("active-video").arm(pending("active-video", "active-a")).recordReply(Outcome.SENT)
assertEquals(4, third.sentCount)
assertEquals(4, third.finishVideo().sentCount)
assertEquals(2, secondVideo.receipts.last().replies.size)
}
@Test fun rotationIncludesLegacyCompletedAndActiveRepliesWithoutReadingTheSummaryTwice() {
val rule = KeywordRule("rule", "关键词", listOf(
ReplyPhrase("a", "第一条"), ReplyPhrase("b", "第二条"),
ReplyPhrase("c", "第三条"), ReplyPhrase("d", "第四条"),
))
val plan = TaskPlan(limit = 5, repliesPerVideo = 2)
val completed = listOf(
Receipt("legacy", Outcome.SENT, TemplateUse(rule.id, 0, "a")),
Receipt("nested", Outcome.SENT, TemplateUse(rule.id, 3, "d"), replies = listOf(
ReplyReceipt("nested-target", Outcome.SENT, TemplateUse(rule.id, 1, "b")),
)),
)
val active = TaskCheckpoint("rotation", plan, receipts = completed).startVideo("video")
.arm(pending("video", "active-a", TemplateUse(rule.id, 2, "c"))).recordReply(Outcome.SENT)
val expected = checkNotNull(active.selectReply(rule, "标题"))
assertEquals("d", expected.use.phraseId)
val replay = active.copy(message = "恢复已有视频").selectReply(rule, "标题")
assertEquals(expected, replay)
val closed = active.arm(pending("video", "active-b", expected.use)).recordReply(Outcome.SENT)
assertNotEquals("d", closed.selectReply(rule, "标题")?.use?.phraseId)
}
@Test fun quotaIsValidatedAndDefaultsToOne() {
assertEquals(1, TaskPlan().repliesPerVideo)
TaskPlan(repliesPerVideo = TaskPlan.MAX_REPLIES_PER_VIDEO).validate()
assertThrows(IllegalArgumentException::class.java) { TaskPlan(repliesPerVideo = 0).validate() }
assertThrows(IllegalArgumentException::class.java) {
TaskPlan(repliesPerVideo = TaskPlan.MAX_REPLIES_PER_VIDEO + 1).validate()
}
}
private fun pending(videoKey: String, targetKey: String, templateUse: TemplateUse? = null) =
PendingComment(videoKey, "标题", "合成回复", templateUse, targetKey = targetKey)
}
+282 -116
View File
@@ -150,8 +150,27 @@
margin-top: 7px;
}
#photo-binding [hidden] { display: none; }
#photo-binding button { border: 0; cursor: pointer; }
[hidden] { display: none !important; }
button.action { border: 0; cursor: pointer; }
button.action:disabled { opacity: .48; cursor: default; }
#photo-items { display: grid; gap: 10px; margin-top: 8px; }
.photo-item img { display: block; width: 96px; height: 76px; object-fit: contain; }
.library-actions, .photo-actions { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 4px; }
.library-level { margin-top: 14px; }
.library-level label { display: block; margin-bottom: 4px; font-size: 14px; font-weight: 700; }
#photo-binding { margin-top: 14px; }
dialog {
width: min(390px, calc(100% - 32px));
padding: 20px;
border: 1px solid var(--line);
border-radius: 18px;
color: var(--ink);
}
dialog::backdrop { background: #172a2460; }
dialog h2 { margin-bottom: 12px; font-size: 20px; }
dialog .library-actions { grid-template-columns: repeat(2, minmax(0, 1fr)); margin-top: 10px; }
#library-status { margin: 6px 0 0; color: var(--muted); font-size: 14px; }
#library-error, #library-status.error { color: var(--alert); font-size: 14px; }
.action.primary, .app-nav [aria-current="page"] {
color: #fff;
@@ -222,22 +241,6 @@
font-size: 14px;
}
.checkbox {
display: flex;
gap: 8px;
align-items: center;
min-height: 32px;
font-size: 14px;
}
.checkbox::before {
content: "";
width: 15px;
height: 15px;
flex: 0 0 15px;
border: 1.5px solid var(--muted);
border-radius: 3px;
}
code { font-size: .92em; overflow-wrap: anywhere; }
.entries {
@@ -283,7 +286,7 @@
<span class="mark" aria-hidden="true"><i></i><i></i><i></i></span>
<div>
<h1>拾见 · 界面预览</h1>
<p>离线预览,可编辑话术并试用本机图片绑定。日志为演示数据。</p>
<p>离线预览,可编辑内容库并试用图片绑定。修改仅在本页保留。</p>
</div>
</header>
@@ -296,10 +299,10 @@
<div class="card">
<h3>准备运行</h3>
<p class="mode">抖音 · 仅浏览</p>
<p>关键词 1 个 · 单次 3 条</p>
<progress value="0" max="3" aria-label="已处理 0 条,共 3 条"></progress>
<p class="summary">已处理 0 / 3 · 已确认发送 0</p>
<p>关键词 国外大模型充值</p>
<p>内容类型 1 个 · 单次 3 个视频</p>
<progress value="0" max="3" aria-label="已处理 0 个视频,共 3 个"></progress>
<p class="summary">已处理视频 0 / 3 · 已确认回复 0 条</p>
<p>内容类型 · 模型服务</p>
</div>
<div class="card">
<h3>无障碍服务未连接</h3>
@@ -308,6 +311,13 @@
</div>
<span class="action primary" aria-disabled="true">开始任务</span>
<span class="action">启用通知栏暂停按钮</span>
<details class="card" id="pending-receipt-preview">
<summary>等待核对状态</summary>
<p>到抖音核对这条评论</p>
<span class="action primary">自动核对回复</span>
<span class="action primary">确认已发送</span>
<span class="action">跳过此回复</span>
</details>
</div>
<nav class="app-nav" aria-label="任务页导航">
<a href="#task" aria-current="page">任务</a>
@@ -326,8 +336,8 @@
<h3>任务范围</h3>
<dl class="fields">
<div><dt>平台</dt><dd class="control select">抖音</dd></div>
<div><dt>搜索关键词</dt><dd class="control multiline">国外大模型充值</dd></div>
<div><dt>单次任务总数</dt><dd class="control">3</dd></div>
<div><dt><label for="search-scope">搜索范围</label></dt><dd><select id="search-scope" class="control settings-input"></select></dd></div>
<div><dt><label for="video-limit">单次任务视频上限</label></dt><dd><input id="video-limit" class="control settings-input" type="number" inputmode="numeric" min="1" max="100" value="3" required></dd></div>
</dl>
</div>
<div class="card">
@@ -344,57 +354,60 @@
</dl>
</div>
<div class="card">
<h3>评论</h3>
<h3>评论设置</h3>
<dl class="fields">
<div>
<dt><label for="reply-mode">处理方式</label></dt>
<dd><select id="reply-mode" class="control settings-input">
<option>仅浏览</option>
<option>随机使用话术并发送</option>
<option>话术优先,DeepSeek 兜底</option>
<option>匹配评论并回复</option>
</select></dd>
</div>
<div>
<dt><label for="template-group">话术分组</label></dt>
<dd><select id="template-group" class="control settings-input">
<option value="common">通用</option>
<option value="keyword-0">关键词 · 国外大模型充值</option>
</select></dd>
</div>
<div>
<dt><label for="template-editor">话术库</label></dt>
<dd><textarea id="template-editor" class="control multiline settings-input" rows="2" placeholder="每行一条话术" autocomplete="off"></textarea></dd>
</div>
<div><dt><label for="replies-per-video">每条视频回复上限</label></dt><dd><input id="replies-per-video" class="control settings-input" type="number" inputmode="numeric" min="1" max="100" value="1" required></dd></div>
</dl>
<p class="hint">先从当前关键词分组随机选一条。该分组为空时使用通用分组。支持 <code>{keyword}</code> 和 <code>{title}</code>。</p>
<dl class="fields">
<div>
<dt><label for="photo-phrase">绑定到话术</label></dt>
<dd><select id="photo-phrase" class="control settings-input" disabled></select></dd>
<p class="hint">达到回复上限或找不到更多匹配评论时,进入下一个视频。</p>
</div>
<div class="card" id="content-library">
<h3>内容库</h3>
<p class="hint">按内容类型搜索视频,按关键词匹配评论。每个关键词可配置多条话术。</p>
<div class="library-level" id="type-level">
<label for="content-type">内容类型</label>
<select id="content-type" class="control settings-input"></select>
<div class="library-actions">
<button type="button" class="action" data-level="type" data-action="add" aria-label="新增内容类型">新增</button>
<button type="button" class="action" data-level="type" data-action="edit" aria-label="编辑内容类型">编辑</button>
<button type="button" class="action" data-level="type" data-action="delete" aria-label="删除内容类型">删除</button>
</div>
</div>
<div class="library-level" id="rule-level">
<label for="keyword-rule">关键词</label>
<select id="keyword-rule" class="control settings-input"></select>
<div class="library-actions">
<button type="button" class="action" data-level="rule" data-action="add" aria-label="新增关键词">新增</button>
<button type="button" class="action" data-level="rule" data-action="edit" aria-label="编辑关键词">编辑</button>
<button type="button" class="action" data-level="rule" data-action="delete" aria-label="删除关键词">删除</button>
</div>
</div>
<div class="library-level" id="phrase-level">
<label for="reply-phrase">回复话术</label>
<select id="reply-phrase" class="control settings-input"></select>
<div class="library-actions">
<button type="button" class="action" data-level="phrase" data-action="add" aria-label="新增话术">新增</button>
<button type="button" class="action" data-level="phrase" data-action="edit" aria-label="编辑话术">编辑</button>
<button type="button" class="action" data-level="phrase" data-action="delete" aria-label="删除话术">删除</button>
</div>
</div>
</dl>
<div id="photo-binding" hidden>
<p id="photo-name" class="hint" hidden></p>
<img id="photo-thumbnail" alt="已绑定图片预览" width="96" height="76" style="object-fit: contain" hidden>
<input id="template-photo" type="file" accept="image/jpeg,image/png" hidden>
<button id="photo-choose" type="button" class="action">选择本机图片</button>
<button id="photo-remove" type="button" class="action" hidden>移除图片</button>
<p id="photo-count" class="hint"></p>
<div id="photo-items"></div>
<input id="template-photo" type="file" accept="image/jpeg,image/png" multiple hidden>
<button id="photo-choose" type="button" class="action">添加本机图片</button>
<p id="photo-status" class="hint" role="status" hidden></p>
<p class="hint">支持 JPEG 和 PNG。修改名称、关键词或话术时,保留已绑定图片。</p>
</div>
<p class="hint">每条话术可绑定一张本机照片。改写话术后需重新绑定。</p>
</div>
<div class="card">
<h3>DeepSeek</h3>
<p class="hint">启用兜底后,没有可用话术时才调用 DeepSeek。请求包含关键词、视频标题和可见评论样本。缺少话术且未设置 API Key 时跳过该视频。</p>
<dl class="fields">
<div><dt>API Key</dt><dd class="control hint">粘贴 API Key</dd></div>
</dl>
<div class="checkbox">清除已保存的 API Key</div>
<dl class="fields">
<div><dt>模型</dt><dd class="control">deepseek-flash</dd></div>
<div><dt>生成说明</dt><dd class="control multiline">根据视频内容提供一句具体、有帮助的中文评论。</dd></div>
</dl>
</div>
<span class="action primary">保存配置</span>
<button type="button" class="action primary" id="save-preview">保存配置</button>
<p id="library-status" role="status" hidden></p>
</div>
<nav class="app-nav" aria-label="配置页导航">
<a href="#task">任务</a>
@@ -412,9 +425,11 @@
<div class="card">
<h3>运行日志</h3>
<ul class="entries">
<li><time datetime="2026-11-26T12:56:05+08:00">11-26 12:56:05</time> 运行 任务完成 · 处理 1 条 · 确认发送 1 条</li>
<li><time datetime="2026-11-26T12:56:05+08:00">11-26 12:56:05</time> 运行 第 1 条视频已确认 1/1 条回复</li>
<li class="warning"><time datetime="2026-11-25T15:22:14+08:00">11-25 15:22:14</time> 异常 抖音评论未回读到完整内容或未看到唯一发送按钮</li>
<li><time datetime="2026-11-25T15:22:01+08:00">11-25 15:22:01</time> 运行 搜索关键词 国外大模型充值</li>
<li><time datetime="2026-11-25T15:22:00+08:00">11-25 15:22:00</time> 运行 开始任务 · 话术优先,DeepSeek 兜底 · 上限 3 条</li>
<li><time datetime="2026-11-25T15:22:01+08:00">11-25 15:22:01</time> 运行 搜索内容类型 模型服务</li>
<li><time datetime="2026-11-25T15:22:00+08:00">11-25 15:22:00</time> 运行 开始任务 · 匹配评论并回复 · 上限 3 条</li>
<li><time datetime="2026-11-25T15:19:09+08:00">11-25 15:19:09</time> 运行 任务完成 · 处理 3 条 · 确认发送 0 条</li>
<li><time datetime="2026-11-25T15:19:02+08:00">11-25 15:19:02</time> 运行 观看第 3 条 · 7 秒</li>
<li><time datetime="2026-11-25T15:18:47+08:00">11-25 15:18:47</time> 运行 观看第 2 条 · 11 秒</li>
@@ -431,77 +446,228 @@
</figure>
</div>
</main>
<dialog id="library-editor" aria-labelledby="editor-title">
<form id="library-form">
<h2 id="editor-title"></h2>
<input id="library-value" class="control settings-input" autocomplete="off">
<textarea id="library-phrase-text" class="control multiline settings-input" rows="3" autocomplete="off" hidden></textarea>
<p id="library-error" role="alert" hidden></p>
<div class="library-actions">
<button type="button" class="action" id="edit-cancel">取消</button>
<button type="submit" class="action primary">完成</button>
</div>
</form>
</dialog>
<dialog id="library-delete" aria-labelledby="delete-message">
<p id="delete-message"></p>
<div class="library-actions">
<button type="button" class="action" id="delete-cancel">取消</button>
<button type="button" class="action primary" id="delete-confirm">删除</button>
</div>
</dialog>
<script>
const groups = document.getElementById("template-group");
const editor = document.getElementById("template-editor");
const photoPhrase = document.getElementById("photo-phrase");
const byId = id => document.getElementById(id);
const scope = byId("search-scope");
const typePicker = byId("content-type");
const rulePicker = byId("keyword-rule");
const phrasePicker = byId("reply-phrase");
const editDialog = byId("library-editor");
const deleteDialog = byId("library-delete");
const singleLine = byId("library-value");
const multiLine = byId("library-phrase-text");
const editError = byId("library-error");
const photoBinding = document.getElementById("photo-binding");
const photoName = document.getElementById("photo-name");
const thumbnail = document.getElementById("photo-thumbnail");
const photoCount = document.getElementById("photo-count");
const photoItems = document.getElementById("photo-items");
const fileInput = document.getElementById("template-photo");
const choosePhoto = document.getElementById("photo-choose");
const removePhoto = document.getElementById("photo-remove");
const drafts = new Map([["keyword-0", "这条视频里提到的方式适用于哪些地区?"]]);
const photos = new Map();
let activeGroup = groups.value;
const photoStatus = document.getElementById("photo-status");
const maxPhotos = 9;
const types = [{ id: "model-services", name: "模型服务", rules: [
{ id: "model-recharge", keyword: "国外大模型充值", phrases: [
{ id: "recharge-regions", text: "这条视频里提到的方式适用于哪些地区?", photos: [] },
] },
] }];
const pick = (list, picker) => list.find(item => item.id === picker.value);
const activeType = () => pick(types, typePicker);
const activeRule = () => pick(activeType()?.rules ?? [], rulePicker);
const activePhrase = () => pick(activeRule()?.phrases ?? [], phrasePicker);
const normalizeKeyword = keyword => keyword.normalize("NFKC").toLowerCase().trim().replace(/\s+/gu, " ");
const levels = {
type: { picker: typePicker, name: "内容类型", key: "name", entries: () => types, extra: () => ({ rules: [] }) },
rule: { picker: rulePicker, name: "关键词", key: "keyword", entries: () => activeType()?.rules ?? [], extra: () => ({ phrases: [] }) },
phrase: { picker: phrasePicker, name: "话术", key: "text", entries: () => activeRule()?.phrases ?? [], extra: () => ({ photos: [] }) },
};
let nextId = 0;
let editing;
let deleting;
let photoTarget;
const photoKey = () => JSON.stringify([activeGroup, photoPhrase.value]);
const redrawPhoto = () => {
const attachment = photos.get(photoKey());
photoBinding.hidden = photoPhrase.disabled;
photoName.hidden = thumbnail.hidden = removePhoto.hidden = !attachment;
if (attachment) {
photoName.textContent = "图片 · " + attachment.name;
thumbnail.src = attachment.url;
} else {
thumbnail.removeAttribute("src");
}
choosePhoto.textContent = attachment ? "更换图片" : "选择本机图片";
const fillPicker = (picker, options, selected, placeholder) => {
picker.replaceChildren(...(options.length ? options.map(([id, title]) => new Option(title, id)) : [new Option(placeholder, "")]));
if (options.some(([id]) => id === selected)) picker.value = selected;
picker.disabled = !options.length;
};
const redrawPhrases = () => {
const previous = photoPhrase.value;
const phrases = [...new Set(editor.value.split(/\r?\n/).map(line => line.trim()).filter(Boolean))];
photoPhrase.replaceChildren(...(phrases.length ? phrases.map(phrase => new Option(phrase, phrase)) :
[new Option("先填写一条话术", "")]));
if (phrases.includes(previous)) photoPhrase.value = previous;
photoPhrase.disabled = !phrases.length;
const setStatus = (message = "") => {
photoStatus.textContent = message;
photoStatus.hidden = !message;
};
const photoItem = (phrase, entry, index) => {
const item = document.createElement("div");
item.className = "photo-item";
const name = document.createElement("p");
name.textContent = `图片 ${index + 1} · ${entry.name}`;
const thumbnail = document.createElement("img");
thumbnail.alt = `第 ${index + 1} 张图片预览`;
thumbnail.src = entry.url;
const actions = document.createElement("div");
actions.className = "photo-actions";
for (const [title, position, disabled] of [["上移", index - 1, index === 0], ["下移", index + 1, index === phrase.photos.length - 1], ["移除图片", null, false]]) {
const button = document.createElement("button");
button.type = "button";
button.className = "action";
button.textContent = title;
button.setAttribute("aria-label", `${title === "移除图片" ? "移除" : title}第 ${index + 1} 张图片`);
button.disabled = disabled;
button.addEventListener("click", () => {
const [selected] = phrase.photos.splice(index, 1);
if (position === null) URL.revokeObjectURL(selected.url);
else phrase.photos.splice(position, 0, selected);
setStatus();
redrawPhoto();
});
actions.append(button);
}
item.append(name, thumbnail, actions);
return item;
};
const redrawPhoto = () => {
const phrase = activePhrase();
const entries = phrase?.photos ?? [];
photoBinding.hidden = !phrase;
photoCount.textContent = `已绑定 ${entries.length} / ${maxPhotos} 张图片`;
photoItems.replaceChildren(...entries.map((entry, index) => photoItem(phrase, entry, index)));
choosePhoto.disabled = entries.length >= maxPhotos;
};
const redrawLibrary = (typeId = typePicker.value, ruleId = rulePicker.value, phraseId = phrasePicker.value) => {
const typeOptions = types.map(type => [type.id, type.name]);
fillPicker(scope, [["", "全部内容类型"], ...typeOptions], scope.value, "");
fillPicker(typePicker, typeOptions, typeId, "请先新增内容类型");
fillPicker(rulePicker, (activeType()?.rules ?? []).map(rule => [rule.id, rule.keyword]), ruleId, "请先新增关键词");
fillPicker(phrasePicker, (activeRule()?.phrases ?? []).map((phrase, index) => [phrase.id, `${index + 1}. ${phrase.text.replace(/\s+/gu, " ")}`]), phraseId, "请先新增话术");
byId("rule-level").hidden = !activeType();
byId("phrase-level").hidden = !activeRule();
for (const button of document.querySelectorAll("[data-level][data-action]")) {
button.disabled = button.dataset.action !== "add" && levels[button.dataset.level].picker.disabled;
}
redrawPhoto();
};
for (const button of document.querySelectorAll("[data-level][data-action]")) {
button.addEventListener("click", () => {
const level = button.dataset.level;
const config = levels[level];
const entries = config.entries();
const existing = pick(entries, config.picker);
if (button.dataset.action === "delete") {
if (!existing) return;
const messages = {
type: () => `删除「${existing.name}」及其中的关键词、话术和图片绑定?`,
rule: () => `删除关键词「${existing.keyword}」及其话术和图片绑定?`,
phrase: () => "删除这条话术及其图片绑定?",
};
deleting = { entries, existing };
byId("delete-message").textContent = messages[level]();
deleteDialog.showModal();
return;
}
const edit = button.dataset.action === "edit";
editing = { level, config, entries, item: edit ? existing : undefined };
byId("editor-title").textContent = `${edit ? "编辑" : "新增"}${config.name}`;
const isPhrase = level === "phrase";
singleLine.hidden = isPhrase;
multiLine.hidden = !isPhrase;
editError.hidden = true;
const field = isPhrase ? multiLine : singleLine;
field.value = editing.item?.[config.key] ?? "";
field.placeholder = isPhrase ? "输入回复文字" : level === "type" ? "内容类型名称" : "一个关键词";
field.setAttribute("aria-label", field.placeholder);
editDialog.showModal();
field.focus();
});
}
byId("edit-cancel").addEventListener("click", () => editDialog.close());
byId("delete-cancel").addEventListener("click", () => deleteDialog.close());
byId("library-form").addEventListener("submit", event => {
event.preventDefault();
const { level, config, entries, item } = editing;
const field = level === "phrase" ? multiLine : singleLine;
const value = field.value.trim();
const error = !value ? `请填写${field.placeholder}。`
: level === "type" && value.length > 120 ? "内容类型名称最多 120 个字符。"
: level === "rule" && (value.length > 120 || /[\r\n]/u.test(value)) ? "每个关键词最多 120 个字符,请填一行。"
: level === "rule" && entries.some(entry => entry !== item && normalizeKeyword(entry.keyword) === normalizeKeyword(value)) ? "这个内容类型已有相同的关键词。"
: level === "phrase" && [...value].length > 120 ? "每条话术最多 120 个字符。"
: level === "phrase" && !item && entries.length >= 100 ? "每个关键词最多 100 条话术。" : "";
if (error) {
editError.textContent = error;
editError.hidden = false;
return;
}
const updated = item ?? { id: `preview-${++nextId}`, ...config.extra() };
updated[config.key] = value;
if (!item) entries.push(updated);
editDialog.close();
setStatus();
redrawLibrary(level === "type" ? updated.id : typePicker.value,
level === "rule" ? updated.id : rulePicker.value, level === "phrase" ? updated.id : phrasePicker.value);
});
byId("delete-confirm").addEventListener("click", () => {
const { entries, existing } = deleting;
const affected = existing.rules ? existing.rules.flatMap(rule => rule.phrases) : existing.phrases ?? [existing];
for (const phrase of affected) phrase.photos.forEach(photo => URL.revokeObjectURL(photo.url));
entries.splice(entries.indexOf(existing), 1);
deleteDialog.close();
setStatus();
redrawLibrary();
});
choosePhoto.addEventListener("click", () => {
photoTarget = photoKey();
photoTarget = activePhrase();
fileInput.click();
});
fileInput.addEventListener("change", () => {
const file = fileInput.files[0];
if (photoTarget && file && ["image/jpeg", "image/png"].includes(file.type)) {
const previous = photos.get(photoTarget);
if (previous) URL.revokeObjectURL(previous.url);
photos.set(photoTarget, { name: file.name, url: URL.createObjectURL(file) });
const stillPresent = types.some(type => type.rules.some(rule => rule.phrases.includes(photoTarget)));
if (stillPresent && fileInput.files.length) {
const current = photoTarget.photos;
const available = maxPhotos - current.length;
const selected = [...fileInput.files].slice(0, available);
const imported = selected.filter(file => ["image/jpeg", "image/png"].includes(file.type));
current.push(...imported.map(file => ({ name: file.name, url: URL.createObjectURL(file) })));
const issues = [];
if (selected.length > imported.length) issues.push(`${selected.length - imported.length} 张图片无法导入。`);
if (fileInput.files.length > available) issues.push(`超出数量上限的 ${fileInput.files.length - available} 张图片未导入。`);
setStatus(issues.join(" "));
}
photoTarget = undefined;
fileInput.value = "";
redrawPhoto();
});
removePhoto.addEventListener("click", () => {
const key = photoKey();
const attachment = photos.get(key);
if (attachment) URL.revokeObjectURL(attachment.url);
photos.delete(key);
redrawPhoto();
for (const picker of [typePicker, rulePicker, phrasePicker]) {
picker.addEventListener("change", () => {
setStatus();
redrawLibrary();
});
photoPhrase.addEventListener("change", redrawPhoto);
editor.addEventListener("input", redrawPhrases);
editor.value = drafts.get(activeGroup) ?? "";
redrawPhrases();
groups.addEventListener("change", () => {
drafts.set(activeGroup, editor.value);
activeGroup = groups.value;
editor.value = drafts.get(activeGroup) ?? "";
redrawPhrases();
}
byId("save-preview").addEventListener("click", () => {
const status = byId("library-status");
const invalid = [byId("video-limit"), byId("replies-per-video")].find(input => !input.validity.valid);
status.textContent = invalid ? `${invalid.labels[0].textContent}须为 1–100 的整数。` : "预览配置已更新。";
status.classList.toggle("error", Boolean(invalid));
status.hidden = false;
invalid?.focus();
});
redrawLibrary();
</script>
</body>
</html>
+99 -1
View File
@@ -1,6 +1,104 @@
# 拾见开发进度
最近更新于 2026-11-26 10:05(UTC+8)。以下按开发轮次倒序记录。
最近更新于 2026-11-26 13:50(UTC+8)。以下按开发轮次倒序记录。
## 2026-11-26 · 拾见 0.1.19 连续实发验收
- 发送前核对原评论的旧回复,跳过基线不完整或已有相同正文的候选。绑定图无法读取时停止提交。发布后等待评论编辑框收起,再核对本人回复。
- 首次回读证据不足且已保存可靠发送记录时,由同一次任务重新搜索并复核原回复。复核只读取已发布内容,同一次任务最多触发一次该条回复的发送。
- vivo Android 12、抖音 39.8.0。沿用手机保存的 3 组关键词、话术及绑定图,在原检查点增加一个验收视频名额。13:48:23 单次启动后自动打开抖音并搜索,13:49:37 在第 8 个视频的评论区第 8 屏命中关键词,实发 1 条定向图文回复。
- 13:49:52 在命中原评论下核对同一条本人回复的正文及 1 张绑定图,同一次任务自动写入 `SENT`。从启动日志到回执用时 89 秒。任务完成 8/8,新增回执 1 条,待核对为 0。启动后全程只读观察,无单独复核启动或人工确认。
- 离线构建、APK v2 签名校验和 45 项 JVM 单测通过。Lint 为 0 个错误、2 个兼容性警告。0.1.19 已覆盖安装,原配置和历史回执已保留,无障碍设置已恢复,任务服务和暂存图已清理。
## 2026-11-26 · 拾见 0.1.18 分页后继续定位图片
- 原评论位于长列表中时,展开两页后,新回复可能仍在屏幕底部。增加同一评论串内的有限调整次数,使读完分页后仍能继续定位完整正文及图片。
- 13:33 在 vivo Android 12、抖音 39.8.0 上启动对 13:06 已发布回复的自动复核。拾见重新搜索并定位原视频及原评论,自动展开两级回复分页并调整位置。在同一条本人回复中核对完整正文和 1 张绑定图。
- 13:34:35 拾见自动写入 1 条 `SENT` 回执,任务完成 7/7,待核对为 0,后台任务已停止。本轮共实发 1 条,复核期间未再次发布。首次实发和自动回执分两段验收,最新版本从一次启动到实发并记回执的连续真机流程仍待验证。
- 离线构建、APK v2 签名校验和 43 项 JVM 单测通过。Lint 为 0 个错误、2 个兼容性警告。0.1.18 已覆盖安装,校验安装包与本机产物一致。原配置和历史回执已保留,暂存图片已清理,无障碍设置已恢复。
## 2026-11-26 · 拾见 0.1.17 原生回复展开回退
- 复核时沿原评论的回复行定位分页控件。常规节点读取缺少控件时,用原生控件 ID 查找并核对归属。确认标签仍在同一评论串内后,点击标签中心展开。
- 离线构建、APK v2 签名和 43 项 JVM 单测通过。13:30 真机验证已点开两级回复分页,并看到同一条已发布回复的原生节点。新回复的正文和图片仍在屏幕底部,待核对记录保留。
## 2026-11-26 · 拾见 0.1.16 调整图文回执的可视范围
- 按原评论作者仍可见的范围计算滚动距离,让原评论和回复图片同时进入可视范围。日期控件被裁切时,读取同一条本人回复的无障碍描述。符合发送前基线的近期回执可在 30 分钟内复核。
- 离线构建、APK v2 签名和 43 项 JVM 单测通过。13:24 真机继续核对同一条回复,定位到原评论,仍有一页子回复未打开,待核对记录保留。此轮没有新的发布。
## 2026-11-26 · 拾见 0.1.15 读取折叠的后续回复
- 0.1.14 复核到正确的原评论。抖音把新回复折叠在该评论串的「展开更多」后。0.1.15 新增识别此控件。13:20 真机对同一条回复复核时,已自动展开并读到正文,图片下方仍被裁切,回执保留待核对。
## 2026-11-26 · 拾见 0.1.14 展开评论区并复核回执
- 原评论下有多条旧回复时,半屏评论区容易把原评论或新回复挤出视野。先核对抖音原生「放大评论区」控件,再在同一条评论串内调整位置,重新核对原评论身份、本人回复、正文及图片。
- 发送前能排除已有相同正文的回复时,记录提交时间。新增「自动核对回复」,可对近期待核对项重新定位原视频和原评论,校验本人回复的发布时间、正文及图片。该操作只核对既有回复。
- 离线构建、APK v2 签名校验及 43 项 JVM 单测通过。离线预览在 1440 和 390 像素宽度下通过自动核对入口和日志检查。
- 13:15 在真机启动对同一条已发布回复的复核。拾见定位到原视频和原评论,回复仍折叠在「展开更多」中,待核对保留。为旧版测试记录补入实际提交时间,未写入回执或再次发布。
## 2026-11-26 · 拾见 0.1.13 抖音图文自动回执
- 发送前读取命中原评论的旧回复,必要时展开其回复列表。发送后定位原评论及紧邻的本人子回复,校验完整正文,并逐张比对该回复里的图片。原评论被滚出视野时,重新打开同一视频的评论区定位。
- Android 11 及以上通过无障碍截图在内存中读取图片区域。允许平台缩放和裁剪造成的像素差异。旧回复无法完整核对、页面变化或图片不足以比对时保留待核对记录,避免重复发送。
- 离线构建、APK v2 签名校验和 41 项 JVM 单测通过,其中 6 项覆盖图片比对。Lint 为 0 个错误、2 个兼容性警告。离线预览在 1440 和 390 像素宽度下验证新增的回执日志示例。
- 0.1.13 已覆盖安装到 vivo Android 12 真机。13:00 使用手机已保存的配置启动实发验收,测试检查点只增加一个视频名额,每个视频最多回复 1 条。
- 前三条新增测试视频均未找到可回复的匹配评论,拾见自动跳过。13:06 在下一条视频的评论区第 3 屏命中,实发 1 条图文回复。放大评论区后,人工观察原评论下的同一条本人回复,核对正文与绑定图。拾见仍保留待核对记录。
## 2026-11-26 · 拾见 0.1.12 深层播放控件识别
- 恢复旧任务(2/3 个视频已处理)时复现抖音滑动起点核对失败,两次均停在发送前。真机节点记录显示,分享、作者、标题及评论控件位于较深的播放器节点内。
- 滑动前重新读取两次相同的视频身份。常规节点读取缺少锚点时,沿同一播放器容器核对分享、作者和标题,再确定滑动起点。手动验证下一条视频的评论区存在符合已保存配置的原评论。
- 评论入口的常规节点读取失效时,在已核对身份的播放器内查找唯一的原生评论控件。离线 APK 构建、APK v2 签名校验和 35 项 JVM 单测通过。Lint 为 0 个错误、1 个已有警告。0.1.12 已覆盖安装到原应用。
- 12:45–12:46 在 vivo Android 12、抖音 39.8.0 上使用手机原配置恢复任务,自动滑到第 3 个视频,在评论区第 1 屏命中关键字并实发 1 条定向回复。重新打开评论区,在命中的原评论下核对到标记「我」的子回复,正文与话术一致,同一回复内的一张图与绑定原图匹配。
- 12:48 在拾见登记人工确认回执 `USER_CONFIRMED`。原任务完成 3/3,待核对为空,后台任务已停止。原配置和历史回执均已保留,暂存图片已清理,无障碍设置已恢复。
## 2026-11-26 · 拾见 0.1.11 每条视频回复上限
- 「配置」新增「每条视频回复上限」,默认 1 条,可设为 1–100 条。按视频分别累计已确认的回复。达标、评论列表到末尾或扫描范围内没有更多匹配时,继续浏览下一个视频。检查点保留当前视频及逐条回复状态,恢复后跳过已处理的原评论。
- 回执核对到原评论下新增「我」回复且正文、图片数量匹配时可自动确认。评论折叠、原评论被裁切或证据不足时保留待核对状态。可跳过该回复后继续扫描同一视频。
- 35 项 JVM 单测通过,覆盖多条回复计数、短评论区跳过、达标换视频、恢复去重、旧记录兼容。静态界面在 1440 px 和 390 px 下验证两个上限可独立设置,默认值和非法值处理正确。
- 12:02、12:04 用原配置的话术和绑定图,在同一抖音视频的两条不同原评论下分别实发 1 条图文回复。在原评论下核对对应正文和各自的图片,记录 2 条人工确认回执。12:05 在达到 2 条上限后恢复任务,拾见自行打开下一条视频。
- 12:06–12:08 单独测试无匹配分支。拾见扫描第一个视频后自动切到第二个视频,两条视频都记为 `NO_REPLY`,实际发布 0 条。
- 真机发布测试在隔离的验收应用内完成,验收应用和暂存图已清理。正式 0.1.11 APK 已覆盖安装并通过 APK v2 签名校验,Lint 为 0 个错误、1 个已有警告。核对了正式应用的原配置和检查点,真机配置页可见新字段及旧配置的默认值 1。
## 2026-11-26 · 拾见 0.1.10 定向图文实发
- 11:35–11:36 在 vivo Android 12、抖音 39.8.0 上沿用用户保存的内容类型、关键字、话术和绑定图片。首个视频未命中并跳过,在第二个视频的评论区第 7 屏命中关键字,实发 1 条定向回复。
- 重新定位命中的原评论后,在紧接该评论的子回复中核对到「我」标记、完全匹配的正文及一张图片。该图片缩略图与绑定原图经居中裁剪对齐后匹配。
- 11:40 在拾见确认回执,新增 1 条 `USER_CONFIRMED`,待核对记录清空。原配置仍为单次 3 条,本轮已处理 2 条并暂停,确认发送 1 条。核对了原配置及无障碍设置,已清理暂存图。
## 2026-11-26 · 使用用户保存的配置复验
- 11:28–11:29 在 vivo Android 12、抖音 39.8.0 上读取手机当前配置,使用已保存的内容类型、评论关键字、话术及一张绑定图片。首个视频的评论区第 1 屏命中关键字,按原评论定位回复框,图文通过发送前校验。
- 真机回读的草稿正文与配置话术一致,所选临时图片的 SHA-256 与绑定原图一致。测试拦截发送,实际发布 0 条。实际发布记录和回执仍待验收。
- 清理本次草稿及暂存图片,恢复 0.1.10 APK 和原任务检查点,核对原配置及无障碍设置。
## 2026-11-26 · 拾见 0.1.10 定向回复真机联调
- vivo Android 12、抖音 39.8.0。升级后配置页可直接读取旧版内容类型、话术和原有的一张绑定图片。
- 真机确认评论行的「回复」入口会打开带原评论作者的输入框。写入正文后抖音会隐藏作者提示,应用改为从写入前确认的原生输入框和外层容器持续校验焦点、正文及附件。
- 抖音相册默认单选,显式开启「多选」后可将两张合成图带回同一个定向回复。回复框的列表总数会包含末尾「添加图片」格,已改为验证末尾节点属于照片或添加控件后计算实际照片数。
- 11:13 恢复此前的测试检查点,按内容类型搜索,在评论区第 3 屏命中关键字,将测试文字与 2 张图片填入同一个原评论回复框。11:16 复测 7 张图片,横向滚动到附件列表末尾,完整图文通过发送前校验。两轮均由联调包拦截发送,实际发布 0 条。另验证了无匹配时跳过视频,确认发送为 0。
- 清除测试草稿、图片和测试配置,逐份核对用户原设置、检查点、日志的 SHA-256,并恢复无障碍设置。0.1.10 APK 已覆盖安装,安装包与本机产物哈希一致。
- 离线构建、APK v2 签名校验和 26 项 JVM 单元测试通过。Lint 为 0 个错误、1 个已有警告。实际发布及发布后回执留待另行验收。
## 2026-11-26 · 拾见 0.1.9 按内容类型匹配原评论
- 配置页按内容类型、评论关键字、话术和绑定图片管理资源。增删改在保存后生效。原关键词和图文绑定可迁移到同名类型,改名或改写话术会保留图片。
- 任务用类型名称搜索。抖音评论列表使用分段变速曲线滑动,限制在列表可视区域内,并在每屏读取评论正文。匹配兼容全角半角和中英文空格,重叠时优先选更长的词。每个视频最多回复一次,最多滑动 12 次。
- 同一关键字库按已使用话术分散抽取,图片按所选话术绑定顺序使用。提交前重新校验当前库和原评论身份,保存带原评论作者的待核对记录。现阶段定向回复提交后保留人工核对,下一轮真机联调验证原评论下的自动回读。
- 离线 Chrome 在 1440 px 和 390 px 宽度验证配置层级、内容改名、同类型重复关键字保护、跨类型隔离、批量选图、图片排序和移除。
- 离线构建及 APK v2 签名校验通过。26 项 JVM 单测全部通过,覆盖关键词匹配、跨类型隔离、话术轮换、运行中改配置、提交前复核和待核对恢复。Lint 为 0 个错误、1 个已有警告。
- 真机联调待开始,需验证 Android 配置迁移、抖音回复对象回读、滑动后的评论刷新、原评论下的图文位置和发送回执。
## 2026-11-26 · 拾见 0.1.8 每条话术绑定多张图片
- 每个关键词组可维护多条话术,每条独立绑定最多 9 张本机图片。支持批量添加、逐张预览、调整顺序和移除。保存后,新任务快照保留完整图片列表,待核对页面列出全部绑定图片。
- Android 真机使用合成配置验证旧单图绑定、旧待核对记录、纯文字配置兼容,以及新版多图的顺序回写。离线 Chrome 验证桌面和移动预览、批量绑定、跨话术隔离、排序和移除。
- 10:35 在 vivo Android 12 上使用禁止发送的测试包恢复任务。拾见按绑定顺序选中 9 张合成图,并将测试文字和全部图片带入同一条抖音评论草稿。临时相册选中数量和编辑框附件总数均通过校验,实际发布 0 条。测试资源已清理,原配置和检查点已恢复。
- 最终 APK 通过离线构建、17 项 JVM 单测及 APK v2 签名校验。Lint 为 0 个错误、1 个已有警告。已覆盖安装真机。
## 2026-11-26 · 拾见 0.1.7 单条图文实发验收