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:
@@ -1,6 +1,6 @@
|
|||||||
# 拾见
|
# 拾见
|
||||||
|
|
||||||
拾见是独立运行的安卓 APK。首个适配平台为抖音标准版。任务按关键词搜索和浏览视频,评论优先从该关键词的本地话术组中随机选取,可启用 DeepSeek 兜底。小红书和哔哩哔哩已列在平台注册表中,界面标注为待适配。
|
拾见是独立运行的安卓 APK。首个适配平台为抖音标准版。任务以内容类型名称为搜索词,逐屏读取评论正文。命中关键字后,从该关键字的话术库中随机选取一条话术和对应图片,回复到命中的原评论下。小红书和哔哩哔哩已列在平台注册表中,界面标注为待适配。
|
||||||
|
|
||||||
## 界面
|
## 界面
|
||||||
|
|
||||||
@@ -8,8 +8,8 @@
|
|||||||
|
|
||||||
| 页面 | 可以做什么 |
|
| 页面 | 可以做什么 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| 任务 | 开启无障碍服务,开始、暂停、继续任务,查看关键词、处理数量和发送结果。安卓 13 及以上可开启通知栏暂停按钮。 |
|
| 任务 | 开启无障碍服务,开始、暂停、继续任务,查看当前内容类型、处理数量和回复结果。安卓 13 及以上可开启通知栏暂停按钮。 |
|
||||||
| 配置 | 选择平台和评论方式,填写关键词、话术、任务数量、观看与动作区间,以及 DeepSeek 设置。 |
|
| 配置 | 选择平台、搜索范围和处理方式,维护内容类型、各类型的关键字、各关键字的话术与图片,并设置任务数量和动作区间。 |
|
||||||
| 日志 | 查看最近 150 条本机记录,包括搜索、观看、发送确认和中断原因。 |
|
| 日志 | 查看最近 150 条本机记录,包括搜索、观看、发送确认和中断原因。 |
|
||||||
|
|
||||||
## 构建环境
|
## 构建环境
|
||||||
@@ -51,34 +51,36 @@ powershell -NoProfile -File ./scripts/verify-apk.ps1
|
|||||||
~~~
|
~~~
|
||||||
|
|
||||||
2. 打开「拾见 → 任务 → 打开无障碍设置」,在系统中开启「拾见任务服务」。若较新系统把侧载应用的开关置灰,查看应用详情菜单是否提供「允许受限设置」,再返回无障碍设置。具体入口因厂商而异。[Android 官方帮助](https://support.google.com/android/answer/12623953?hl=zh-Hans)
|
2. 打开「拾见 → 任务 → 打开无障碍设置」,在系统中开启「拾见任务服务」。若较新系统把侧载应用的开关置灰,查看应用详情菜单是否提供「允许受限设置」,再返回无障碍设置。具体入口因厂商而异。[Android 官方帮助](https://support.google.com/android/answer/12623953?hl=zh-Hans)
|
||||||
3. 在「配置」填写关键词、处理方式及对应参数,点「保存配置」。首次可用默认的「仅浏览」模式,数量设为 1,检查抖音的搜索和播放页能否识别。
|
3. 在「配置」创建内容类型并填写实际要搜索的名称,例如「大模型充值」。在该类型中添加评论关键字,例如「付款方式」和「账号订阅」,分别维护话术和图片。选择搜索范围、处理方式和任务参数,点「保存配置」。可以先用「仅浏览」模式验证搜索和播放。
|
||||||
4. 在「任务」点「开始任务」。保持手机解锁并让抖音留在前台。在拾见任务页或用通知栏按钮可暂停。登录、验证、页面布局不可识别等中断可在手机处理后点「继续任务」。
|
4. 在「任务」点「开始任务」。保持手机解锁并让抖音留在前台。在拾见任务页或用通知栏按钮可暂停。登录、验证、页面布局不可识别等中断可在手机处理后点「继续任务」。
|
||||||
5. 如果显示「等待核对」,检查抖音评论区里是否已有页面所显示的评论,再选择「确认已发送」或「跳过这条视频」。跳过计入任务处理数量。检查点会保留待核对条目,应用不会自动重发它。
|
5. 抖音发布后,拾见核对原评论下新增的本人回复,匹配正文和全部绑定图片后自动登记回执。图文自动核对需要 Android 11 或更新版本,图片比对在手机内存中完成。待核对卡片出现「自动核对回复」时,可让拾见再次查找并核对这条回复。若仍显示待核对,可到原评论下核对正文及图片,再选择「确认已发送」或「跳过此回复」。待核对期间会阻止自动重发。
|
||||||
|
|
||||||
安装完成后,任务可以脱离电脑运行。抖音内容和 DeepSeek 请求仍需要手机网络。
|
安装完成后,任务可以脱离电脑运行。加载抖音内容需要手机网络,话术匹配和选择在拾见本机完成。
|
||||||
|
|
||||||
## 配置项
|
## 配置项
|
||||||
|
|
||||||
| 配置 | 说明 |
|
| 配置 | 说明 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| 目标平台 | 首版实现抖音标准版,包名 com.ss.android.ugc.aweme。 |
|
| 目标平台 | 首版实现抖音标准版,包名 com.ss.android.ugc.aweme。 |
|
||||||
| 搜索关键词 | 每行一个,最多 30 个。示例为「国外大模型充值」。任务总数按关键词顺序尽量均分,余数优先分给前面的关键词,总数少于关键词数时只处理排在前面的关键词。 |
|
| 内容类型 | 类型名称直接用于抖音搜索。「全部类型」按类型顺序尽量均分任务总数,余数优先分给前面的类型。也可只运行一个类型。 |
|
||||||
| 单次任务总数 | 跨关键词共处理 1–100 条。 |
|
| 评论关键字 | 每个类型可增删改多条关键字。每个关键字对应独立话术库。匹配基于评论正文,兼容全角半角、英文字母大小写和常见中英文空格;重叠时优先选更长的匹配。 |
|
||||||
|
| 单次任务视频上限 | 共处理 1–100 个视频。浏览完成或扫描后没有可回复的评论也计入进度。 |
|
||||||
|
| 每条视频回复上限 | 默认 1 条,可设为 1–100 条。在匹配回复模式下,已确认发送的回复计入上限。达标、评论列表到末尾或扫描范围内没有更多匹配时,浏览下一个视频。 |
|
||||||
| 观看时长 | 1–300 秒的闭区间,逐视频取样,默认 5–12 秒。 |
|
| 观看时长 | 1–300 秒的闭区间,逐视频取样,默认 5–12 秒。 |
|
||||||
| 动作间隔 | 150–30,000 毫秒的闭区间,逐动作取样,默认 600–1,800 毫秒。视频滑动起止点和时长也在播放器允许范围内取样。 |
|
| 动作间隔 | 150–30,000 毫秒的闭区间,默认 600–1,800 毫秒。评论滑动在评论列表内变化起点、距离、轨迹、时长和停留时间,每个视频最多滑动 12 次并在每屏重新读取。 |
|
||||||
| 处理方式 | 「仅浏览」「随机使用话术并发送」「话术优先,DeepSeek 兜底」。发送模式优先查找当前搜索关键词的分组,其次查找通用组。仍无可用回复时跳过视频并记日志。 |
|
| 处理方式 | 「仅浏览」只观看视频。「匹配评论并回复」逐屏读取评论,匹配到当前类型中有可用话术的关键字时回复原评论。同一任务内每条原评论最多尝试一次发送。 |
|
||||||
| 话术分组 | 在配置页选择「通用」或一个已配置的关键词,再逐行编辑。原有话术自动作为通用话术读取。每组独立随机洗牌,用完重洗,同一组有多条时避开上一轮最后使用的模板。每组最多 100 条,每条最多 120 个 Unicode 码点。支持 {keyword} 和 {title}。 |
|
| 话术库 | 每个关键字最多 100 条话术,每条最多 120 个 Unicode 码点。支持 {keyword} 和 {title},分别填入命中的关键字和视频标题。各库独立随机轮换,有可用替代时避开连续重复。 |
|
||||||
| 话术图片 | 在「绑定到话术」选择具体一行,点「选择本机图片」,手动选一张 JPEG 或 PNG,最后点「保存配置」。每条话术可绑定一张图片,支持更换和移除。文件最多 20 MB,需要 Android 10 或更新版本。改写已绑定话术后需重新绑定。 |
|
| 话术图片 | 每条话术独立绑定最多 9 张 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 加密保存在应用私有目录。任务快照保存普通配置,启动或恢复时读取当前已保存密钥。 |
|
|
||||||
|
|
||||||
配置修改在下次新任务生效。恢复会沿用任务快照、处理进度和已记录的抽取进度。
|
保存后,关键字、话术和图片从下一次评论识别起生效,同时在提交前核对命中的话术库。搜索范围、类型名称、视频及回复上限和动作区间用于下次新任务。恢复保留搜索计划、处理进度和已记录的抽取进度。
|
||||||
|
|
||||||
## 恢复和兼容性
|
## 恢复和兼容性
|
||||||
|
|
||||||
发送前,应用先把视频指纹和待提交内容写入本地检查点。文字评论在确认编辑区已清空且评论列表新增匹配正文时自动记录回执。图文评论写入同一个抖音编辑框,点击一次发送后由任务页显示正文和所绑定的图片,供用户同时核对两者。中途退出或回执不明确时,任务保留待核对记录。恢复会重新搜索当前关键词,用视频指纹跳过已处理条目。指纹基于可见作者和标题。同作者、同标题的不同视频可能合并,标题变化也可能改变指纹。
|
发送前,应用核对原评论对象和编辑框,把视频指纹、原评论标识、回复正文和图片列表写入本地检查点。回执不明确时,任务保留待核对记录,任务页显示原评论作者与待核对的图文。恢复时先定位同一未完成视频并跳过已尝试的原评论,也会跳过已结束处理的视频。视频指纹基于可见作者和标题,同作者、同标题的不同视频可能合并,标题变化也可能改变指纹。
|
||||||
|
|
||||||
拾见为手动选定的图片保存本机私有副本。图文任务使用快照中的绑定,选图时只尝试本次创建的单图临时相册。图库权限、相册布局或编辑框附件无法确认时,任务会停在当步并记录原因。用户核对完成后,拾见清理未使用的临时相册图片。选图基于 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/res/layout、MainActivity.kt | 页面结构、参数控件和任务操作。 |
|
||||||
| app/src/main/java/com/jieliu/app/AutomationService.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/platform | 平台接口、注册表、节点和手势操作、抖音适配器。 |
|
||||||
| app/src/main/java/com/jieliu/app/task | 关键词分配、随机节奏、话术、DeepSeek 和恢复规则。 |
|
| app/src/main/java/com/jieliu/app/task | 内容类型调度、评论关键字匹配、话术轮换和恢复规则。 |
|
||||||
| app/src/main/java/com/jieliu/app/data | 配置、发送检查点、运行日志和密钥。 |
|
| app/src/main/java/com/jieliu/app/data | 配置、图片、发送检查点和运行日志。 |
|
||||||
| docs/技术调研.md | 前期技术选型、通用组件评估和设计依据。 |
|
| 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.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.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 单测通过。
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ android {
|
|||||||
applicationId = "com.jieliu.app"
|
applicationId = "com.jieliu.app"
|
||||||
minSdk = 26
|
minSdk = 26
|
||||||
targetSdk = 35
|
targetSdk = 35
|
||||||
versionCode = 8
|
versionCode = 20
|
||||||
versionName = "0.1.7"
|
versionName = "0.1.19"
|
||||||
}
|
}
|
||||||
|
|
||||||
compileOptions {
|
compileOptions {
|
||||||
|
|||||||
@@ -9,8 +9,6 @@ import android.os.Looper
|
|||||||
import android.view.accessibility.AccessibilityEvent
|
import android.view.accessibility.AccessibilityEvent
|
||||||
import com.jieliu.app.data.LocalStore
|
import com.jieliu.app.data.LocalStore
|
||||||
import com.jieliu.app.platform.PlatformRegistry
|
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.TaskCheckpoint
|
||||||
import com.jieliu.app.task.TaskRunner
|
import com.jieliu.app.task.TaskRunner
|
||||||
import com.jieliu.app.task.pauseFor
|
import com.jieliu.app.task.pauseFor
|
||||||
@@ -84,29 +82,24 @@ internal object TaskControl {
|
|||||||
check(active == null) { "任务正在运行。" }
|
check(active == null) { "任务正在运行。" }
|
||||||
val service = checkNotNull(connected) { "请先在系统设置中开启「拾见任务服务」。" }
|
val service = checkNotNull(connected) { "请先在系统设置中开启「拾见任务服务」。" }
|
||||||
val saved = store.readCheckpoint()
|
val saved = store.readCheckpoint()
|
||||||
|
val rechecking = resume && saved?.pending != null
|
||||||
val plan = if (resume) {
|
val plan = if (resume) {
|
||||||
checkNotNull(saved) { "当前没有可恢复的任务。" }
|
checkNotNull(saved) { "当前没有可恢复的任务。" }
|
||||||
check(!saved.complete) { "任务已经完成。" }
|
check(!saved.complete) { "任务已经完成。" }
|
||||||
check(saved.pending == null) { "请先核对待确认的评论。" }
|
check(!rechecking || saved.canAutomaticallyRecheck()) { "这条回复需要人工核对。" }
|
||||||
saved.plan
|
saved.plan.migrateContentTypes()
|
||||||
} else {
|
} else {
|
||||||
check(saved == null || saved.complete) { "请先继续或放弃已有任务。" }
|
check(saved == null || saved.complete) { "请先继续或放弃已有任务。" }
|
||||||
store.readPlan()
|
store.readPlan()
|
||||||
}
|
}
|
||||||
plan.validate()
|
plan.validate()
|
||||||
|
require(plan.searchTypes().isNotEmpty()) { "请先配置一个要搜索的内容类型。" }
|
||||||
val spec = checkNotNull(PlatformRegistry.platforms.firstOrNull { it.id == plan.platformId && it.implemented }) {
|
val spec = checkNotNull(PlatformRegistry.platforms.firstOrNull { it.id == plan.platformId && it.implemented }) {
|
||||||
"当前平台适配尚未实现。"
|
"当前平台适配尚未实现。"
|
||||||
}
|
}
|
||||||
check(service.packageManager.getLaunchIntentForPackage(spec.packageName) != null) { "请先安装${spec.label}。" }
|
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))
|
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 run = Run(service, store, initial)
|
||||||
val cancelled = { run.cancelled }
|
val cancelled = { run.cancelled }
|
||||||
val platform = PlatformRegistry.create(plan.platformId, service, cancelled) {
|
val platform = PlatformRegistry.create(plan.platformId, service, cancelled) {
|
||||||
@@ -115,7 +108,7 @@ internal object TaskControl {
|
|||||||
}
|
}
|
||||||
run.work = Runnable {
|
run.work = Runnable {
|
||||||
try {
|
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 {
|
} finally {
|
||||||
main.post {
|
main.post {
|
||||||
if (active === run) {
|
if (active === run) {
|
||||||
|
|||||||
@@ -15,9 +15,7 @@ import android.os.Bundle
|
|||||||
import android.os.Handler
|
import android.os.Handler
|
||||||
import android.os.Looper
|
import android.os.Looper
|
||||||
import android.provider.Settings
|
import android.provider.Settings
|
||||||
import android.text.Editable
|
|
||||||
import android.text.InputType
|
import android.text.InputType
|
||||||
import android.text.TextWatcher
|
|
||||||
import android.view.Gravity
|
import android.view.Gravity
|
||||||
import android.view.View
|
import android.view.View
|
||||||
import android.view.WindowInsets
|
import android.view.WindowInsets
|
||||||
@@ -25,7 +23,6 @@ import android.view.inputmethod.InputMethodManager
|
|||||||
import android.widget.AdapterView
|
import android.widget.AdapterView
|
||||||
import android.widget.ArrayAdapter
|
import android.widget.ArrayAdapter
|
||||||
import android.widget.Button
|
import android.widget.Button
|
||||||
import android.widget.CheckBox
|
|
||||||
import android.widget.EditText
|
import android.widget.EditText
|
||||||
import android.widget.FrameLayout
|
import android.widget.FrameLayout
|
||||||
import android.widget.ImageView
|
import android.widget.ImageView
|
||||||
@@ -38,25 +35,46 @@ import android.widget.Toast
|
|||||||
import com.jieliu.app.data.LocalStore
|
import com.jieliu.app.data.LocalStore
|
||||||
import com.jieliu.app.data.PhotoLibrary
|
import com.jieliu.app.data.PhotoLibrary
|
||||||
import com.jieliu.app.platform.PlatformRegistry
|
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.Outcome
|
||||||
import com.jieliu.app.task.ReplyMode
|
import com.jieliu.app.task.ReplyMode
|
||||||
|
import com.jieliu.app.task.ReplyPhrase
|
||||||
import com.jieliu.app.task.TaskCheckpoint
|
import com.jieliu.app.task.TaskCheckpoint
|
||||||
import com.jieliu.app.task.TaskPlan
|
import com.jieliu.app.task.TaskPlan
|
||||||
import com.jieliu.app.task.TemplatePhoto
|
import com.jieliu.app.task.TemplatePhoto
|
||||||
|
import com.jieliu.app.task.normalizeKeyword
|
||||||
|
import java.util.UUID
|
||||||
|
import java.util.concurrent.FutureTask
|
||||||
|
|
||||||
class MainActivity : Activity() {
|
class MainActivity : Activity() {
|
||||||
private enum class Tab { TASK, SETTINGS, LOGS }
|
private enum class Tab { TASK, SETTINGS, LOGS }
|
||||||
|
|
||||||
private data class TaskView(
|
private data class TaskView(
|
||||||
val checkpoint: TaskCheckpoint?, val connected: Boolean, val step: String?, val notificationsOff: Boolean,
|
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 store: LocalStore get() = (application as ShijianApp).store
|
||||||
private val photos by lazy { PhotoLibrary(applicationContext) }
|
private val photos by lazy { PhotoLibrary(applicationContext) }
|
||||||
private val handler = Handler(Looper.getMainLooper())
|
private val handler = Handler(Looper.getMainLooper())
|
||||||
private val refresh = object : Runnable {
|
private val refresh = object : Runnable {
|
||||||
override fun run() {
|
override fun run() {
|
||||||
|
finishPhotoImport()
|
||||||
renderCurrent()
|
renderCurrent()
|
||||||
handler.postDelayed(this, 600L)
|
handler.postDelayed(this, 600L)
|
||||||
}
|
}
|
||||||
@@ -66,15 +84,25 @@ class MainActivity : Activity() {
|
|||||||
private lateinit var tabs: List<Button>
|
private lateinit var tabs: List<Button>
|
||||||
private var selected = Tab.TASK
|
private var selected = Tab.TASK
|
||||||
private var configView: View? = null
|
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 photoTarget: PhotoTarget? = null
|
||||||
private var importingPhoto = false
|
private var photoImport: PhotoImport? = null
|
||||||
private var taskView: TaskView? = null
|
private var taskView: TaskView? = null
|
||||||
private var logVersion = -1L
|
private var logVersion = -1L
|
||||||
|
|
||||||
override fun onCreate(state: Bundle?) {
|
override fun onCreate(state: Bundle?) {
|
||||||
super.onCreate(state)
|
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()
|
if (Build.VERSION.SDK_INT in 30..34) configureEdgeToEdge()
|
||||||
setContentView(R.layout.activity_main)
|
setContentView(R.layout.activity_main)
|
||||||
val root = findViewById<View>(R.id.root)
|
val root = findViewById<View>(R.id.root)
|
||||||
@@ -95,45 +123,89 @@ class MainActivity : Activity() {
|
|||||||
override fun onSaveInstanceState(outState: Bundle) {
|
override fun onSaveInstanceState(outState: Bundle) {
|
||||||
outState.putInt("tab", selected.ordinal)
|
outState.putInt("tab", selected.ordinal)
|
||||||
photoTarget?.let {
|
photoTarget?.let {
|
||||||
outState.putString("photoGroup", it.group)
|
outState.putString("photoTypeId", it.typeId)
|
||||||
outState.putString("photoPhrase", it.phrase)
|
outState.putString("photoRuleId", it.ruleId)
|
||||||
|
outState.putString("photoPhraseId", it.phraseId)
|
||||||
}
|
}
|
||||||
super.onSaveInstanceState(outState)
|
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")
|
@Suppress("DEPRECATION")
|
||||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||||
super.onActivityResult(requestCode, resultCode, data)
|
super.onActivityResult(requestCode, resultCode, data)
|
||||||
if (requestCode != PICK_TEMPLATE_PHOTO) return
|
if (requestCode != PICK_TEMPLATE_PHOTO) return
|
||||||
val target = photoTarget ?: return
|
val target = photoTarget ?: return
|
||||||
photoTarget = null
|
photoTarget = null
|
||||||
val uri = data?.data?.takeIf { resultCode == RESULT_OK } ?: return
|
if (resultCode != RESULT_OK || data == null) return
|
||||||
val fields = templateFields ?: return
|
val fields = templateFields
|
||||||
importingPhoto = true
|
val remaining = fields?.remainingFor(target)
|
||||||
fields.renderPhoto()
|
if (fields == null || remaining == null) {
|
||||||
Thread {
|
toast("找不到这条话术,请重新选择图片。")
|
||||||
val imported = runCatching { photos.importPhoto(uri) }
|
return
|
||||||
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()
|
|
||||||
}
|
}
|
||||||
}.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")
|
@Suppress("DEPRECATION")
|
||||||
private fun choosePhoto(group: String, phrase: String) {
|
private fun choosePhoto(target: PhotoTarget) {
|
||||||
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
|
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
|
||||||
addCategory(Intent.CATEGORY_OPENABLE)
|
addCategory(Intent.CATEGORY_OPENABLE)
|
||||||
type = "image/*"
|
type = "image/*"
|
||||||
putExtra(Intent.EXTRA_MIME_TYPES, arrayOf("image/jpeg", "image/png"))
|
putExtra(Intent.EXTRA_MIME_TYPES, arrayOf("image/jpeg", "image/png"))
|
||||||
putExtra(Intent.EXTRA_LOCAL_ONLY, true)
|
putExtra(Intent.EXTRA_LOCAL_ONLY, true)
|
||||||
|
putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
|
||||||
}
|
}
|
||||||
photoTarget = PhotoTarget(group, phrase)
|
photoTarget = target
|
||||||
try {
|
try {
|
||||||
startActivityForResult(intent, PICK_TEMPLATE_PHOTO)
|
startActivityForResult(intent, PICK_TEMPLATE_PHOTO)
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
@@ -183,7 +255,8 @@ class MainActivity : Activity() {
|
|||||||
if (content.childCount == 0) replace(errorPage("无法读取任务检查点"))
|
if (content.childCount == 0) replace(errorPage("无法读取任务检查点"))
|
||||||
return
|
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
|
if (view == taskView) return
|
||||||
taskView = view
|
taskView = view
|
||||||
replace(guardedPage { taskPage(view) })
|
replace(guardedPage { taskPage(view) })
|
||||||
@@ -195,6 +268,7 @@ class MainActivity : Activity() {
|
|||||||
val active = view.step != null
|
val active = view.step != null
|
||||||
val plan = checkpoint?.plan ?: store.readPlan()
|
val plan = checkpoint?.plan ?: store.readPlan()
|
||||||
val platform = PlatformRegistry.platforms.firstOrNull { it.id == plan.platformId }?.label ?: plan.platformId
|
val platform = PlatformRegistry.platforms.firstOrNull { it.id == plan.platformId }?.label ?: plan.platformId
|
||||||
|
val searchTypes = plan.searchTypes()
|
||||||
val completed = checkpoint?.receipts?.size ?: 0
|
val completed = checkpoint?.receipts?.size ?: 0
|
||||||
val title = when {
|
val title = when {
|
||||||
active -> "运行中"
|
active -> "运行中"
|
||||||
@@ -205,18 +279,22 @@ class MainActivity : Activity() {
|
|||||||
}
|
}
|
||||||
return column().apply {
|
return column().apply {
|
||||||
addView(card(title).apply {
|
addView(card(title).apply {
|
||||||
addView(label("$platform · ${plan.replyMode.label}", 15))
|
val modeLabel = if (plan.replyMode == ReplyMode.BROWSE) ReplyMode.BROWSE.label else ReplyMode.TEMPLATES.label
|
||||||
addView(label(view.step ?: checkpoint?.message ?: "关键词 ${plan.keywords.size} 个 · 单次 ${plan.limit} 条", 15))
|
addView(label("$platform · $modeLabel", 15))
|
||||||
|
addView(label(view.step ?: checkpoint?.message ?: "内容类型 ${searchTypes.size} 个 · 单次 ${plan.limit} 个视频", 15))
|
||||||
val limit = checkpoint?.plan?.limit ?: plan.limit
|
val limit = checkpoint?.plan?.limit ?: plan.limit
|
||||||
addView(ProgressBar(this@MainActivity, null, android.R.attr.progressBarStyleHorizontal).apply {
|
addView(ProgressBar(this@MainActivity, null, android.R.attr.progressBarStyleHorizontal).apply {
|
||||||
max = limit
|
max = limit
|
||||||
progress = completed
|
progress = completed
|
||||||
progressTintList = ColorStateList.valueOf(GREEN)
|
progressTintList = ColorStateList.valueOf(GREEN)
|
||||||
contentDescription = "已处理 $completed 条,共 $limit 条"
|
contentDescription = "已处理 $completed 个视频,共 $limit 个"
|
||||||
}, LinearLayout.LayoutParams(-1, dp(18)))
|
}, LinearLayout.LayoutParams(-1, dp(18)))
|
||||||
addView(label("已处理 $completed / $limit · 已确认发送 ${checkpoint?.sentCount ?: 0}", 14))
|
addView(label("已处理视频 $completed / $limit · 已确认回复 ${checkpoint?.sentCount ?: 0} 条", 14))
|
||||||
val keyword = checkpoint?.keyword ?: plan.keywords.firstOrNull()
|
if (plan.replyMode != ReplyMode.BROWSE) checkpoint?.activeVideo?.let { video ->
|
||||||
if (keyword != null && checkpoint?.complete != true) addView(label("关键词 $keyword", 14))
|
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) {
|
if (!view.connected) {
|
||||||
addView(card("无障碍服务未连接").apply {
|
addView(card("无障碍服务未连接").apply {
|
||||||
@@ -227,10 +305,15 @@ class MainActivity : Activity() {
|
|||||||
if (pending != null && !active) {
|
if (pending != null && !active) {
|
||||||
addView(card("到${platform}核对这条评论").apply {
|
addView(card("到${platform}核对这条评论").apply {
|
||||||
addView(label(pending.title, 16, bold = true))
|
addView(label(pending.title, 16, bold = true))
|
||||||
|
pending.targetAuthor?.takeIf { it.isNotBlank() }?.let { addView(label("回复对象 · $it", 14)) }
|
||||||
addView(label(pending.text, 15))
|
addView(label(pending.text, 15))
|
||||||
pending.photo?.let { addView(photoPreview(it)) }
|
pending.photos.forEachIndexed { index, photo -> addView(photoPreview(photo, index)) }
|
||||||
addView(action("确认已发送", primary = true) { reconcile(Outcome.USER_CONFIRMED) })
|
if (view.canAutomaticallyRecheck) {
|
||||||
addView(action("跳过这条视频") { reconcile(Outcome.SKIPPED) })
|
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 {
|
when {
|
||||||
@@ -255,198 +338,270 @@ class MainActivity : Activity() {
|
|||||||
val specs = PlatformRegistry.platforms
|
val specs = PlatformRegistry.platforms
|
||||||
val platform = choices(specs.map { if (it.implemented) it.label else "${it.label}(待适配)" },
|
val platform = choices(specs.map { if (it.implemented) it.label else "${it.label}(待适配)" },
|
||||||
specs.indexOfFirst { it.id == plan.platformId }.coerceAtLeast(0))
|
specs.indexOfFirst { it.id == plan.platformId }.coerceAtLeast(0))
|
||||||
val mode = choices(ReplyMode.entries.map { it.label }, plan.replyMode.ordinal)
|
val modes = listOf(ReplyMode.BROWSE, ReplyMode.TEMPLATES)
|
||||||
val keywords = field(plan.keywords.joinToString("\n"), "每行一个关键词", multiline = true)
|
val mode = choices(modes.map { it.label }, if (plan.replyMode == ReplyMode.BROWSE) 0 else 1)
|
||||||
val templates = TemplateFields(keywords, plan).also { templateFields = it }
|
val libraries = ContentFields(plan, restoredTemplates).also {
|
||||||
|
templateFields = it
|
||||||
|
restoredTemplates = null
|
||||||
|
}
|
||||||
val limit = field(plan.limit.toString(), "1–100", number = true)
|
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 watchMin = field(plan.watchSeconds.first.toString(), "最短", number = true)
|
||||||
val watchMax = field(plan.watchSeconds.last.toString(), "最长", number = true)
|
val watchMax = field(plan.watchSeconds.last.toString(), "最长", number = true)
|
||||||
val actionMin = field(plan.actionMillis.first.toString(), "最短", number = true)
|
val actionMin = field(plan.actionMillis.first.toString(), "最短", number = true)
|
||||||
val actionMax = field(plan.actionMillis.last.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 {
|
return column().apply {
|
||||||
addView(card("任务范围").apply {
|
addView(card("任务范围").apply {
|
||||||
addField("平台", platform)
|
addField("平台", platform)
|
||||||
addField("搜索关键词", keywords)
|
addField("搜索范围", libraries.scope)
|
||||||
addField("单次任务总数", limit)
|
addField("单次任务视频上限", limit)
|
||||||
})
|
})
|
||||||
addView(card("动作节奏").apply {
|
addView(card("动作节奏").apply {
|
||||||
addRange("观看时长(秒)", watchMin, watchMax)
|
addRange("观看时长(秒)", watchMin, watchMax)
|
||||||
addRange("动作间隔(毫秒)", actionMin, actionMax)
|
addRange("动作间隔(毫秒)", actionMin, actionMax)
|
||||||
})
|
})
|
||||||
addView(card("评论").apply {
|
addView(card("评论设置").apply {
|
||||||
addField("处理方式", mode)
|
addField("处理方式", mode)
|
||||||
addField("话术分组", templates.group)
|
addField("每条视频回复上限", repliesPerVideo)
|
||||||
addField("话术库", templates.editor)
|
addView(label("达到回复上限或找不到更多匹配评论时,进入下一个视频。", 14))
|
||||||
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))
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
addView(card("DeepSeek").apply {
|
addView(card("内容库").apply {
|
||||||
addView(label("启用兜底后,没有可用话术时才调用 DeepSeek。请求包含关键词、视频标题和可见评论样本。缺少话术且未设置 API Key 时跳过该视频。", 14))
|
addView(label("按内容类型搜索视频,按关键词匹配评论。每个关键词可配置多条话术。", 14))
|
||||||
addField("API Key", key)
|
addView(libraries.editor)
|
||||||
addView(removeKey)
|
|
||||||
addField("模型", model)
|
|
||||||
addField("生成说明", instructions)
|
|
||||||
})
|
})
|
||||||
addView(action("保存配置", primary = true) {
|
addView(action("保存配置", primary = true) {
|
||||||
check(!importingPhoto) { "请等待图片导入完成。" }
|
check(photoImport == null) { "请等待图片导入完成。" }
|
||||||
val spec = specs[platform.selectedItemPosition]
|
val spec = specs[platform.selectedItemPosition]
|
||||||
require(spec.implemented) { "${spec.label}还未适配,请选择抖音。" }
|
require(spec.implemented) { "${spec.label}还未适配,请选择抖音。" }
|
||||||
val replacementKey = if (removeKey.isChecked) "" else key.value().ifBlank { null }
|
val updated = plan.copy(
|
||||||
require(replacementKey == null || replacementKey.length <= 256 && replacementKey.all { it.code in 33..126 }) {
|
|
||||||
"API Key 包含无效字符。"
|
|
||||||
}
|
|
||||||
val activeKeywords = keywords.lines()
|
|
||||||
val updated = TaskPlan(
|
|
||||||
platformId = spec.id,
|
platformId = spec.id,
|
||||||
keywords = activeKeywords,
|
limit = limit.number("单次任务视频上限"),
|
||||||
templates = templates.lines(null),
|
repliesPerVideo = repliesPerVideo.number("每条视频回复上限"),
|
||||||
limit = limit.number("单次任务总数"),
|
|
||||||
watchSeconds = watchMin.number("观看下限")..watchMax.number("观看上限"),
|
watchSeconds = watchMin.number("观看下限")..watchMax.number("观看上限"),
|
||||||
actionMillis = actionMin.number("间隔下限")..actionMax.number("间隔上限"),
|
actionMillis = actionMin.number("间隔下限")..actionMax.number("间隔上限"),
|
||||||
replyMode = ReplyMode.entries[mode.selectedItemPosition],
|
replyMode = modes[mode.selectedItemPosition],
|
||||||
model = model.value().ifBlank { TaskPlan().model },
|
contentTypes = libraries.contentTypes,
|
||||||
instructions = instructions.value(),
|
selectedTypeId = libraries.selectedScopeId(),
|
||||||
keywordTemplates = activeKeywords.mapNotNull { keyword ->
|
|
||||||
templates.lines(keyword).takeIf { it.isNotEmpty() }?.let { keyword to it }
|
|
||||||
}.toMap(),
|
|
||||||
templatePhotos = templates.photoBindings(activeKeywords),
|
|
||||||
)
|
)
|
||||||
store.saveSettings(updated, replacementKey)
|
store.saveSettings(updated, null)
|
||||||
templates.retainSavedBindings(updated.templatePhotos)
|
if (!TaskControl.inProgress) runCatching {
|
||||||
runCatching {
|
|
||||||
val checkpoint = store.readCheckpoint()
|
val checkpoint = store.readCheckpoint()
|
||||||
photos.pruneImports(
|
photos.pruneImports(
|
||||||
updated.photoIds() + checkpoint?.takeUnless { it.complete }?.plan?.photoIds().orEmpty() +
|
updated.photoIds() + checkpoint?.takeUnless { it.complete }?.plan?.photoIds().orEmpty() +
|
||||||
listOfNotNull(checkpoint?.pending?.photo?.id),
|
checkpoint?.pending?.photos.orEmpty().map(TemplatePhoto::id),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
key.text.clear()
|
toast("配置已保存。关键词、话术和图片在下次读取评论时生效。")
|
||||||
key.hint = if (store.hasApiKey()) "已设置,留空沿用" else "粘贴 API Key"
|
|
||||||
removeKey.isChecked = false
|
|
||||||
toast("配置已保存,下次新任务生效。")
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private inner class TemplateFields(private val keywords: EditText, plan: TaskPlan) {
|
private inner class ContentFields(plan: TaskPlan, restored: TemplateDraft?) {
|
||||||
private val drafts = mutableMapOf<String?, String>(null to plan.templates.joinToString("\n"))
|
var contentTypes: List<ContentType> = restored?.types ?: plan.contentTypes.orEmpty()
|
||||||
private val bindings = plan.templatePhotos.mapValues { (_, values) -> values.toMutableMap() }.toMutableMap()
|
private set
|
||||||
private var options: List<String?> = listOf(null)
|
private var typeId = restored?.typeId
|
||||||
private var selectedKeyword: String? = null
|
private var ruleId = restored?.ruleId
|
||||||
val group = choices(listOf("通用"), 0)
|
private var phraseId = restored?.phraseId
|
||||||
val editor = field(drafts[null].orEmpty(), "每行一条话术", multiline = true)
|
private var scopeIds = listOf<String?>(null)
|
||||||
private var photoOptions = emptyList<String>()
|
val scope = choices(listOf("全部内容类型"), 0)
|
||||||
private var drawnPhoto: Triple<PhotoTarget?, TemplatePhoto?, Boolean>? = null
|
val editor = column()
|
||||||
val photoPhrase = choices(listOf("先填写一条话术"), 0)
|
private val photoControls = column()
|
||||||
val photoControls = column()
|
private var drawnPhoto: Triple<PhotoTarget?, List<TemplatePhoto>, Boolean>? = null
|
||||||
|
|
||||||
init {
|
init {
|
||||||
plan.keywordTemplates.forEach { (keyword, lines) -> drafts[keyword] = lines.joinToString("\n") }
|
renderScope(if (restored != null) restored.scopeId else plan.selectedTypeId)
|
||||||
updateOptions()
|
renderEditor()
|
||||||
group.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
|
|
||||||
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
|
|
||||||
if (position in options.indices) show(options[position])
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onNothingSelected(parent: AdapterView<*>) = Unit
|
fun selectedScopeId() = scopeIds.getOrNull(scope.selectedItemPosition)
|
||||||
}
|
|
||||||
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 lines(keyword: String?): List<String> =
|
fun snapshot() = TemplateDraft(contentTypes, selectedScopeId(), typeId, ruleId, phraseId)
|
||||||
(if (selectedKeyword == keyword) editor.text.toString() else drafts[keyword].orEmpty()).nonblankLines()
|
|
||||||
|
|
||||||
fun photoBindings(activeKeywords: List<String>): Map<String, Map<String, TemplatePhoto>> =
|
fun remainingFor(target: PhotoTarget): Int? =
|
||||||
(listOf("") + activeKeywords).mapNotNull { key ->
|
findPhrase(target)?.let { (TaskPlan.MAX_TEMPLATE_PHOTOS - it.photos.size).coerceAtLeast(0) }
|
||||||
val phrases = lines(key.ifEmpty { null }).toSet()
|
|
||||||
bindings[key]?.filterKeys { it in phrases }?.takeIf { it.isNotEmpty() }?.let { key to it }
|
|
||||||
}.toMap()
|
|
||||||
|
|
||||||
fun retainSavedBindings(saved: Map<String, Map<String, TemplatePhoto>>) {
|
fun append(target: PhotoTarget, incoming: List<TemplatePhoto>): Boolean {
|
||||||
bindings.clear()
|
val current = findPhrase(target) ?: return false
|
||||||
saved.forEach { (key, photos) -> bindings[key] = photos.toMutableMap() }
|
if (current.photos.size + incoming.size > TaskPlan.MAX_TEMPLATE_PHOTOS) return false
|
||||||
renderPhoto()
|
updatePhrase(target, current.copy(photos = current.photos + incoming))
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
return true
|
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() {
|
fun renderPhoto() {
|
||||||
val target = photoOptions.getOrNull(photoPhrase.selectedItemPosition)
|
val target = typeId?.let { type -> ruleId?.let { rule -> phraseId?.let { PhotoTarget(type, rule, it) } } }
|
||||||
?.let { PhotoTarget(selectedKeyword.orEmpty(), it) }
|
val current = target?.let(::findPhrase)
|
||||||
val photo = target?.let { bindings[it.group]?.get(it.phrase) }
|
val entries = current?.photos.orEmpty()
|
||||||
val state = Triple(target, photo, importingPhoto)
|
val importing = photoImport != null
|
||||||
|
val state = Triple(target, entries, importing)
|
||||||
if (drawnPhoto == state) return
|
if (drawnPhoto == state) return
|
||||||
drawnPhoto = state
|
drawnPhoto = state
|
||||||
photoControls.removeAllViews()
|
photoControls.removeAllViews()
|
||||||
if (target == null) return
|
if (target == null || current == null) return
|
||||||
if (photo != null) photoControls.addView(photoPreview(photo))
|
photoControls.addView(label("已绑定 ${entries.size} / ${TaskPlan.MAX_TEMPLATE_PHOTOS} 张图片", 14))
|
||||||
photoControls.addView(action(if (importingPhoto) "正在导入图片…" else if (photo == null) "选择本机图片" else "更换图片") {
|
entries.forEachIndexed { index, photo ->
|
||||||
choosePhoto(target.group, target.phrase)
|
photoControls.addView(photoPreview(photo, index))
|
||||||
}.apply { applyEnabled(!importingPhoto) })
|
val operations = listOf(
|
||||||
if (photo != null) photoControls.addView(action("移除图片") {
|
Triple("上移", index > 0, index - 1),
|
||||||
bindings[target.group]?.remove(target.phrase)
|
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()
|
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()
|
photoControls.addView(action(if (importing) "正在导入图片…" else "添加本机图片") { choosePhoto(target) }
|
||||||
renderPhoto()
|
.apply { applyEnabled(!importing && entries.size < TaskPlan.MAX_TEMPLATE_PHOTOS) })
|
||||||
}
|
photoControls.addView(label("支持 JPEG 和 PNG。修改名称、关键词或话术时,保留已绑定图片。", 14))
|
||||||
|
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -458,22 +613,30 @@ class MainActivity : Activity() {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun photoPreview(photo: TemplatePhoto) = column().apply {
|
private fun photoPreview(photo: TemplatePhoto, index: Int) = column().apply {
|
||||||
addView(label("图片 · ${photo.displayName}", 14))
|
addView(label("图片 ${index + 1} · ${photo.displayName}", 14))
|
||||||
photos.thumbnail(photo)?.let { bitmap ->
|
val bitmap = photos.thumbnail(photo)
|
||||||
|
if (bitmap == null) {
|
||||||
|
addView(label("图片缺失或无法预览。", 14, color = ALERT))
|
||||||
|
} else {
|
||||||
addView(ImageView(this@MainActivity).apply {
|
addView(ImageView(this@MainActivity).apply {
|
||||||
setImageBitmap(bitmap)
|
setImageBitmap(bitmap)
|
||||||
adjustViewBounds = true
|
adjustViewBounds = true
|
||||||
scaleType = ImageView.ScaleType.FIT_CENTER
|
scaleType = ImageView.ScaleType.FIT_CENTER
|
||||||
contentDescription = "已绑定图片预览"
|
contentDescription = "第 ${index + 1} 张图片预览"
|
||||||
}, LinearLayout.LayoutParams(dp(96), dp(76)))
|
}, LinearLayout.LayoutParams(dp(96), dp(76)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun reconcile(outcome: Outcome) {
|
private fun reconcile(outcome: Outcome) {
|
||||||
|
val before = checkNotNull(store.readCheckpoint())
|
||||||
|
val expected = checkNotNull(before.pending) { "当前没有待核对的评论。" }
|
||||||
|
val photoCount = expected.photos.size
|
||||||
val prompt = when {
|
val prompt = when {
|
||||||
|
outcome != Outcome.USER_CONFIRMED && before.activeVideo != null -> "跳过当前回复并继续核对后的任务进度?"
|
||||||
outcome != Outcome.USER_CONFIRMED -> "跳过这条视频并计入本次进度?"
|
outcome != Outcome.USER_CONFIRMED -> "跳过这条视频并计入本次进度?"
|
||||||
store.readCheckpoint()?.pending?.photo != null -> "已在目标应用看到这条评论的文字和图片?"
|
photoCount == 1 -> "已在目标应用看到这条评论的文字和图片?"
|
||||||
|
photoCount > 1 -> "已在目标应用看到这条评论的文字和全部 $photoCount 张图片?"
|
||||||
else -> "已在目标应用看到这条评论?"
|
else -> "已在目标应用看到这条评论?"
|
||||||
}
|
}
|
||||||
AlertDialog.Builder(this).setMessage(prompt)
|
AlertDialog.Builder(this).setMessage(prompt)
|
||||||
@@ -481,10 +644,15 @@ class MainActivity : Activity() {
|
|||||||
.setPositiveButton("确认") { _, _ -> perform {
|
.setPositiveButton("确认") { _, _ -> perform {
|
||||||
check(!TaskControl.inProgress) { "请先暂停任务。" }
|
check(!TaskControl.inProgress) { "请先暂停任务。" }
|
||||||
val checkpoint = checkNotNull(store.readCheckpoint())
|
val checkpoint = checkNotNull(store.readCheckpoint())
|
||||||
val pending = checkNotNull(checkpoint.pending) { "当前没有待核对的评论。" }
|
check(checkpoint.id == before.id && checkpoint.pending == expected) { "待核对的评论已变化,请重新打开。" }
|
||||||
store.saveCheckpoint(checkpoint.finish(pending.videoKey, outcome))
|
store.saveCheckpoint(checkpoint.recordReply(outcome))
|
||||||
if (pending.photo != null) Thread { photos.cleanupStaged() }.start()
|
if (expected.photos.isNotEmpty()) Thread { photos.cleanupStaged() }.start()
|
||||||
store.appendLog(if (outcome == Outcome.USER_CONFIRMED) "用户确认上一条评论已发送" else "用户跳过待核对的视频")
|
val message = when {
|
||||||
|
outcome == Outcome.USER_CONFIRMED -> "用户确认上一条评论已发送"
|
||||||
|
checkpoint.activeVideo != null -> "用户跳过待核对的回复"
|
||||||
|
else -> "用户跳过待核对的视频"
|
||||||
|
}
|
||||||
|
store.appendLog(message)
|
||||||
renderTask()
|
renderTask()
|
||||||
} }.show()
|
} }.show()
|
||||||
}
|
}
|
||||||
@@ -530,17 +698,68 @@ class MainActivity : Activity() {
|
|||||||
setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
|
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
|
isSingleLine = !multiline
|
||||||
inputType = when {
|
inputType = when {
|
||||||
number -> InputType.TYPE_CLASS_NUMBER
|
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
|
multiline -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE
|
||||||
else -> InputType.TYPE_CLASS_TEXT
|
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 }
|
if (multiline) { minLines = 2; maxLines = 6; gravity = Gravity.TOP }
|
||||||
setText(value)
|
setText(value)
|
||||||
this.hint = hint
|
this.hint = hint
|
||||||
@@ -615,8 +834,6 @@ class MainActivity : Activity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun EditText.value() = text.toString().trim()
|
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 EditText.number(label: String) = requireNotNull(value().toIntOrNull()) { "请填写有效的$label。" }
|
||||||
private fun dp(value: Int) = (resources.displayMetrics.density * value + .5f).toInt()
|
private fun dp(value: Int) = (resources.displayMetrics.density * value + .5f).toInt()
|
||||||
private fun toast(message: String) = Toast.makeText(this, message, Toast.LENGTH_LONG).show()
|
private fun toast(message: String) = Toast.makeText(this, message, Toast.LENGTH_LONG).show()
|
||||||
|
|||||||
@@ -1,16 +1,22 @@
|
|||||||
package com.jieliu.app.data
|
package com.jieliu.app.data
|
||||||
|
|
||||||
import android.content.Context
|
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.Outcome
|
||||||
import com.jieliu.app.task.PendingComment
|
import com.jieliu.app.task.PendingComment
|
||||||
import com.jieliu.app.task.Receipt
|
import com.jieliu.app.task.Receipt
|
||||||
import com.jieliu.app.task.ReplyMode
|
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.TaskCheckpoint
|
||||||
import com.jieliu.app.task.TaskPlan
|
import com.jieliu.app.task.TaskPlan
|
||||||
import com.jieliu.app.task.TaskRunStorage
|
import com.jieliu.app.task.TaskRunStorage
|
||||||
import com.jieliu.app.task.TemplatePhoto
|
import com.jieliu.app.task.TemplatePhoto
|
||||||
import com.jieliu.app.task.TemplateUse
|
import com.jieliu.app.task.TemplateUse
|
||||||
|
import com.jieliu.app.task.VideoProgress
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONException
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.FileOutputStream
|
import java.io.FileOutputStream
|
||||||
@@ -31,7 +37,8 @@ class LocalStore(context: Context) : TaskRunStorage {
|
|||||||
@Volatile var logVersion: Long = 0
|
@Volatile var logVersion: Long = 0
|
||||||
private set
|
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
|
@Synchronized fun hasApiKey(): Boolean = settings.readJson()?.has("deepSeekKey") == true
|
||||||
|
|
||||||
@@ -56,15 +63,27 @@ class LocalStore(context: Context) : TaskRunStorage {
|
|||||||
val entries = json.getJSONArray("receipts")
|
val entries = json.getJSONArray("receipts")
|
||||||
val receipts = List(entries.length()) { index ->
|
val receipts = List(entries.length()) { index ->
|
||||||
val entry = entries.getJSONObject(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 {
|
val pending = json.optJSONObject("pending")?.let {
|
||||||
PendingComment(
|
PendingComment(
|
||||||
it.getString("key"), it.getString("title"), it.getString("text"), it.readTemplateUse(),
|
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
|
checkpointLoaded = true
|
||||||
return cachedCheckpoint
|
return cachedCheckpoint
|
||||||
@@ -73,19 +92,31 @@ class LocalStore(context: Context) : TaskRunStorage {
|
|||||||
@Synchronized override fun saveCheckpoint(checkpoint: TaskCheckpoint) {
|
@Synchronized override fun saveCheckpoint(checkpoint: TaskCheckpoint) {
|
||||||
val receipts = JSONArray(checkpoint.receipts.map {
|
val receipts = JSONArray(checkpoint.receipts.map {
|
||||||
JSONObject().put("key", it.videoKey).put("outcome", it.outcome.name)
|
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())
|
val body = JSONObject().put("id", checkpoint.id).put("plan", checkpoint.plan.toJson())
|
||||||
.put("receipts", receipts).put("message", checkpoint.message)
|
.put("receipts", receipts).put("message", checkpoint.message)
|
||||||
checkpoint.pending?.let {
|
checkpoint.pending?.let {
|
||||||
body.put("pending", JSONObject().put("key", it.videoKey).put("title", it.title).put("text", it.text)
|
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)
|
task.replaceWith(body)
|
||||||
cachedCheckpoint = checkpoint
|
cachedCheckpoint = checkpoint
|
||||||
checkpointLoaded = true
|
checkpointLoaded = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Synchronized override fun savePendingIfCurrent(checkpoint: TaskCheckpoint, matchesPlan: (TaskPlan) -> Boolean): Boolean {
|
||||||
|
if (!matchesPlan(readPlan())) return false
|
||||||
|
saveCheckpoint(checkpoint)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
@Synchronized fun clearCheckpoint() {
|
@Synchronized fun clearCheckpoint() {
|
||||||
Files.deleteIfExists(task.toPath())
|
Files.deleteIfExists(task.toPath())
|
||||||
cachedCheckpoint = null
|
cachedCheckpoint = null
|
||||||
@@ -131,8 +162,11 @@ class LocalStore(context: Context) : TaskRunStorage {
|
|||||||
.put("platform", platformId).put("keywords", JSONArray(keywords)).put("templates", JSONArray(templates))
|
.put("platform", platformId).put("keywords", JSONArray(keywords)).put("templates", JSONArray(templates))
|
||||||
.put("keywordTemplates", JSONObject(keywordTemplates.mapValues { (_, lines) -> JSONArray(lines) }))
|
.put("keywordTemplates", JSONObject(keywordTemplates.mapValues { (_, lines) -> JSONArray(lines) }))
|
||||||
.put("templatePhotos", JSONObject(templatePhotos.mapValues { (_, photos) ->
|
.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("limit", limit).put("watchMin", watchSeconds.first).put("watchMax", watchSeconds.last)
|
||||||
.put("actionMin", actionMillis.first).put("actionMax", actionMillis.last)
|
.put("actionMin", actionMillis.first).put("actionMax", actionMillis.last)
|
||||||
.put("mode", replyMode.name).put("model", model).put("instructions", instructions)
|
.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 ->
|
templatePhotos = if (isNull("templatePhotos")) emptyMap() else getJSONObject("templatePhotos").let { groups ->
|
||||||
groups.keys().asSequence().associateWith { group ->
|
groups.keys().asSequence().associateWith { group ->
|
||||||
val photos = groups.getJSONObject(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 TemplatePhoto.toJson() = JSONObject().put("id", id).put("displayName", displayName)
|
||||||
|
|
||||||
private fun JSONObject.toTemplatePhoto() = TemplatePhoto(getString("id"), getString("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 {
|
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)
|
private fun JSONArray.strings() = List(length(), ::getString)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import android.content.ContentValues
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.graphics.Bitmap
|
import android.graphics.Bitmap
|
||||||
import android.graphics.BitmapFactory
|
import android.graphics.BitmapFactory
|
||||||
|
import android.graphics.ImageDecoder
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
@@ -16,6 +17,7 @@ import android.provider.MediaStore
|
|||||||
import android.provider.MediaStore.MediaColumns
|
import android.provider.MediaStore.MediaColumns
|
||||||
import android.provider.OpenableColumns
|
import android.provider.OpenableColumns
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
|
import com.jieliu.app.task.TaskPlan
|
||||||
import com.jieliu.app.task.TemplatePhoto
|
import com.jieliu.app.task.TemplatePhoto
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.FileOutputStream
|
import java.io.FileOutputStream
|
||||||
@@ -24,7 +26,7 @@ import java.nio.file.LinkOption.NOFOLLOW_LINKS
|
|||||||
import java.nio.file.StandardCopyOption.ATOMIC_MOVE
|
import java.nio.file.StandardCopyOption.ATOMIC_MOVE
|
||||||
import java.util.UUID
|
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) {
|
class PhotoLibrary(context: Context) {
|
||||||
private val app = context.applicationContext
|
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 或更新版本。")
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) error("暂存话术图片需要 Android 10 或更新版本。")
|
||||||
val source = checkNotNull(importedFile(photo)) { "找不到所选话术图片,请重新选择。" }
|
require(photos.size in 1..TaskPlan.MAX_TEMPLATE_PHOTOS &&
|
||||||
stageImage(source)
|
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) {
|
fun removeStaged(staged: StagedPhotos): Unit = synchronized(lock) {
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && activeStages.remove(staged)) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
deleteStageSafely(staged.uri)
|
staged.uris.filter(activeStages::remove).forEach(::deleteStageSafely)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun leaveStagedForReview(staged: StagedPhoto) = synchronized(lock) {
|
fun leaveStagedForReview(staged: StagedPhotos) = synchronized(lock) {
|
||||||
activeStages.remove(staged)
|
activeStages.removeAll(staged.uris.toSet())
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Sweep only this app's staging rows. Keep current stages and call after any previous send is reconciled. */
|
/** 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)
|
@TargetApi(Build.VERSION_CODES.Q)
|
||||||
private fun stageImage(source: File): StagedPhoto {
|
private fun stageImages(sources: List<File>): StagedPhotos {
|
||||||
val format = Format.entries.single { it.extension == source.extension }
|
|
||||||
val albumName = "SJ-${UUID.randomUUID().toString().replace("-", "").take(12)}"
|
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 {
|
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.MIME_TYPE, format.mime)
|
||||||
put(MediaColumns.RELATIVE_PATH, "${Environment.DIRECTORY_PICTURES}/$albumName/")
|
put(MediaColumns.RELATIVE_PATH, "${Environment.DIRECTORY_PICTURES}/$albumName/")
|
||||||
put(MediaColumns.IS_PENDING, 1)
|
put(MediaColumns.IS_PENDING, 1)
|
||||||
}
|
}
|
||||||
val uri = checkNotNull(resolver.insert(imageCollection(), values)) { "无法在系统相册中暂存图片。" }
|
val uri = checkNotNull(resolver.insert(imageCollection(), values)) { "无法在系统相册中暂存图片。" }
|
||||||
var committed = false
|
stagedUris.add(uri)
|
||||||
try {
|
|
||||||
val target = checkNotNull(resolver.openOutputStream(uri, "w")) { "无法写入暂存图片。" }
|
val target = checkNotNull(resolver.openOutputStream(uri, "w")) { "无法写入暂存图片。" }
|
||||||
target.use { stream -> source.inputStream().use { it.copyTo(stream) } }
|
target.use { stream -> source.inputStream().use { it.copyTo(stream) } }
|
||||||
|
}
|
||||||
val visible = ContentValues().apply { put(MediaColumns.IS_PENDING, 0) }
|
val visible = ContentValues().apply { put(MediaColumns.IS_PENDING, 0) }
|
||||||
|
stagedUris.forEach { uri ->
|
||||||
check(resolver.update(uri, visible, null, null) == 1) { "无法使暂存图片在系统相册中显示。" }
|
check(resolver.update(uri, visible, null, null) == 1) { "无法使暂存图片在系统相册中显示。" }
|
||||||
val staged = StagedPhoto(albumName, uri)
|
}
|
||||||
activeStages.add(staged)
|
activeStages.addAll(stagedUris)
|
||||||
committed = true
|
committed = true
|
||||||
return staged
|
return StagedPhotos(albumName, stagedUris.toList())
|
||||||
} finally {
|
} 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
|
if (cursor.getString(3) != app.packageName) continue
|
||||||
val albumName = STAGE_PATH.matchEntire(cursor.getString(1).orEmpty())?.groupValues?.get(1) ?: continue
|
val albumName = STAGE_PATH.matchEntire(cursor.getString(1).orEmpty())?.groupValues?.get(1) ?: continue
|
||||||
val name = cursor.getString(2)
|
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))
|
val uri = ContentUris.withAppendedId(collection, cursor.getLong(0))
|
||||||
if (StagedPhoto(albumName, uri) !in activeStages) add(uri)
|
if (uri !in activeStages) add(uri)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}.orEmpty()
|
}.orEmpty()
|
||||||
@@ -216,7 +250,8 @@ class PhotoLibrary(context: Context) {
|
|||||||
@TargetApi(Build.VERSION_CODES.Q)
|
@TargetApi(Build.VERSION_CODES.Q)
|
||||||
private fun imageCollection(): Uri = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
|
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) {
|
private enum class Format(val mime: String, val extension: String) {
|
||||||
JPEG("image/jpeg", "jpg"),
|
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 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 STAGE_PATH = Regex("${Environment.DIRECTORY_PICTURES}/(SJ-[0-9a-f]{12})/")
|
||||||
val lock = Any()
|
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.AccessibilityService
|
||||||
import android.accessibilityservice.GestureDescription
|
import android.accessibilityservice.GestureDescription
|
||||||
|
import android.annotation.TargetApi
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.Paint
|
||||||
import android.graphics.Path
|
import android.graphics.Path
|
||||||
|
import android.graphics.Picture
|
||||||
import android.graphics.Rect
|
import android.graphics.Rect
|
||||||
|
import android.os.Build
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.os.Handler
|
import android.os.Handler
|
||||||
import android.os.Looper
|
import android.os.Looper
|
||||||
import android.os.SystemClock
|
import android.os.SystemClock
|
||||||
|
import android.view.Display
|
||||||
import android.view.accessibility.AccessibilityNodeInfo
|
import android.view.accessibility.AccessibilityNodeInfo
|
||||||
import android.view.accessibility.AccessibilityWindowInfo
|
import android.view.accessibility.AccessibilityWindowInfo
|
||||||
import java.io.Closeable
|
import java.io.Closeable
|
||||||
import java.util.ArrayDeque
|
import java.util.ArrayDeque
|
||||||
import java.util.concurrent.CancellationException
|
import java.util.concurrent.CancellationException
|
||||||
|
import java.util.concurrent.CompletableFuture
|
||||||
import java.util.concurrent.CountDownLatch
|
import java.util.concurrent.CountDownLatch
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
|
import java.util.concurrent.TimeoutException
|
||||||
import kotlin.math.roundToInt
|
import kotlin.math.roundToInt
|
||||||
|
import kotlin.random.Random
|
||||||
|
|
||||||
/** Uses fresh, target-package-scoped nodes and recycles every reference after each read or action. */
|
/** Uses fresh, target-package-scoped nodes and recycles every reference after each read or action. */
|
||||||
@Suppress("DEPRECATION")
|
@Suppress("DEPRECATION")
|
||||||
@@ -59,6 +68,153 @@ internal class AccessibleUi(
|
|||||||
return capture(root).use(action)
|
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? {
|
private fun targetRoot(): AccessibilityNodeInfo? {
|
||||||
val active = service.rootInActiveWindow
|
val active = service.rootInActiveWindow
|
||||||
if (active?.packageName?.toString() == packageName) return active
|
if (active?.packageName?.toString() == packageName) return active
|
||||||
@@ -155,8 +311,61 @@ internal class AccessibleUi(
|
|||||||
moveTo(fromX, fromY)
|
moveTo(fromX, fromY)
|
||||||
if (fromX != toX || fromY != toY) lineTo(toX, toY)
|
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()
|
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()
|
.build()
|
||||||
val done = CountDownLatch(1)
|
val done = CountDownLatch(1)
|
||||||
var completed = false
|
var completed = false
|
||||||
@@ -171,10 +380,10 @@ internal class AccessibleUi(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!service.dispatchGesture(gesture, callback, mainHandler)) return false
|
if (!service.dispatchGesture(gesture, callback, mainHandler)) return false
|
||||||
val deadline = SystemClock.elapsedRealtime() + durationMs + 2_000
|
val deadline = SystemClock.elapsedRealtime() + stroke.duration + 2_000
|
||||||
try {
|
try {
|
||||||
while (SystemClock.elapsedRealtime() < deadline) {
|
while (SystemClock.elapsedRealtime() < deadline) {
|
||||||
checkCancelled()
|
if (interruptible) checkCancelled()
|
||||||
if (done.await(75, TimeUnit.MILLISECONDS)) return completed
|
if (done.await(75, TimeUnit.MILLISECONDS)) return completed
|
||||||
}
|
}
|
||||||
} catch (error: InterruptedException) {
|
} catch (error: InterruptedException) {
|
||||||
@@ -205,16 +414,48 @@ internal class UiPage(
|
|||||||
val windowId: Int,
|
val windowId: Int,
|
||||||
val bounds: Rect,
|
val bounds: Rect,
|
||||||
val nodes: List<UiNode>,
|
val nodes: List<UiNode>,
|
||||||
private val references: List<AccessibilityNodeInfo>,
|
private val references: MutableList<AccessibilityNodeInfo>,
|
||||||
) : Closeable {
|
) : Closeable {
|
||||||
fun x(fraction: Float): Int = bounds.left + (bounds.width() * fraction).roundToInt()
|
fun x(fraction: Float): Int = bounds.left + (bounds.width() * fraction).roundToInt()
|
||||||
fun y(fraction: Float): Int = bounds.top + (bounds.height() * 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() {
|
override fun close() {
|
||||||
references.forEach { it.recycle() }
|
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(
|
internal class UiNode(
|
||||||
private val node: AccessibilityNodeInfo,
|
private val node: AccessibilityNodeInfo,
|
||||||
val bounds: Rect,
|
val bounds: Rect,
|
||||||
@@ -232,6 +473,11 @@ internal class UiNode(
|
|||||||
val focused: Boolean = node.isFocused
|
val focused: Boolean = node.isFocused
|
||||||
val selected: Boolean = node.isSelected
|
val selected: Boolean = node.isSelected
|
||||||
val showingHint: Boolean = node.isShowingHintText
|
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 labels(): List<String> = listOf(text, description).filter { it.isNotEmpty() }.distinct()
|
||||||
fun hasDraft(): Boolean = text.isNotBlank() && !showingHint
|
fun hasDraft(): Boolean = text.isNotBlank() && !showingHint
|
||||||
@@ -239,6 +485,37 @@ internal class UiNode(
|
|||||||
node.isEnabled && node.isEditable && !node.isPassword
|
node.isEnabled && node.isEditable && !node.isPassword
|
||||||
fun isStillBlankAndFocused(): Boolean = hasCurrentInputFocus() &&
|
fun isStillBlankAndFocused(): Boolean = hasCurrentInputFocus() &&
|
||||||
(node.isShowingHintText || node.text.isNullOrBlank())
|
(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 directParent(): UiNode? = parent?.takeIf { it.depth == depth - 1 }
|
||||||
fun isDescendantOf(ancestor: UiNode): Boolean = generateSequence(parent) { it.parent }.any { it === ancestor }
|
fun isDescendantOf(ancestor: UiNode): Boolean = generateSequence(parent) { it.parent }.any { it === ancestor }
|
||||||
fun supports(action: Int): Boolean = node.actionList.any { it.id == action }
|
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 android.accessibilityservice.AccessibilityService
|
||||||
import com.jieliu.app.data.PhotoLibrary
|
import com.jieliu.app.data.PhotoLibrary
|
||||||
|
import com.jieliu.app.task.PendingComment
|
||||||
import com.jieliu.app.task.TemplatePhoto
|
import com.jieliu.app.task.TemplatePhoto
|
||||||
|
|
||||||
data class PlatformSpec(
|
data class PlatformSpec(
|
||||||
@@ -13,6 +14,8 @@ data class PlatformSpec(
|
|||||||
|
|
||||||
data class VideoContext(val key: String, val title: String)
|
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 }
|
enum class CommentPublishResult { CONFIRMED, UNCERTAIN }
|
||||||
|
|
||||||
class PlatformException(message: String, cause: Throwable? = null) : RuntimeException(message, cause)
|
class PlatformException(message: String, cause: Throwable? = null) : RuntimeException(message, cause)
|
||||||
@@ -24,10 +27,18 @@ interface PlatformAdapter {
|
|||||||
fun currentVideo(): VideoContext
|
fun currentVideo(): VideoContext
|
||||||
fun nextVideo(previous: VideoContext): VideoContext
|
fun nextVideo(previous: VideoContext): VideoContext
|
||||||
fun openComments(expected: VideoContext): List<String>
|
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 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("当前平台不支持发布图片评论")
|
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()
|
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 }
|
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(
|
data class PendingComment(
|
||||||
val videoKey: String,
|
val videoKey: String,
|
||||||
val title: String,
|
val title: String,
|
||||||
val text: String,
|
val text: String,
|
||||||
val templateUse: TemplateUse? = null,
|
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(
|
data class TaskCheckpoint(
|
||||||
@@ -24,37 +45,149 @@ data class TaskCheckpoint(
|
|||||||
val receipts: List<Receipt> = emptyList(),
|
val receipts: List<Receipt> = emptyList(),
|
||||||
val pending: PendingComment? = null,
|
val pending: PendingComment? = null,
|
||||||
val message: String = "准备启动",
|
val message: String = "准备启动",
|
||||||
|
val activeVideo: VideoProgress? = null,
|
||||||
) {
|
) {
|
||||||
val complete: Boolean get() = receipts.size >= plan.limit && pending == null
|
val complete: Boolean get() = receipts.size >= plan.limit && pending == null && activeVideo == null
|
||||||
val sentCount: Int get() = receipts.count { it.outcome in setOf(Outcome.SENT, Outcome.USER_CONFIRMED) }
|
val sentCount: Int get() = receipts.sumOf { receipt ->
|
||||||
val keyword: String? get() = if (complete) null else plan.keywords[plan.keywordIndex(receipts.size)]
|
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 {
|
fun arm(comment: PendingComment): TaskCheckpoint {
|
||||||
check(!complete && pending == null && !hasSeen(comment.videoKey))
|
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 = "已记录提交意图,正在确认发送结果")
|
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 {
|
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) {
|
if (outcome == Outcome.WATCHED || outcome == Outcome.NO_REPLY) {
|
||||||
check(pending == null)
|
check(pending == null)
|
||||||
} else {
|
} else {
|
||||||
check(pending?.videoKey == videoKey)
|
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 {
|
val status = when {
|
||||||
updated.size >= plan.limit -> "任务已完成"
|
updated.size >= plan.limit -> "任务已完成"
|
||||||
outcome == Outcome.SKIPPED -> "已核对并跳过,等待继续"
|
outcome == Outcome.SKIPPED -> "已核对并跳过,等待继续"
|
||||||
outcome == Outcome.USER_CONFIRMED -> "已人工确认,等待继续"
|
outcome == Outcome.USER_CONFIRMED -> "已人工确认,等待继续"
|
||||||
outcome == Outcome.SENT -> "已确认发送"
|
outcome == Outcome.SENT -> "已确认发送"
|
||||||
outcome == Outcome.NO_REPLY -> "无可用话术,已跳过视频"
|
outcome == Outcome.NO_REPLY -> if (plan.contentTypes == null) "无可用话术,已跳过视频" else "未找到可回复的匹配评论,已跳过视频"
|
||||||
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 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? {
|
fun selectTemplate(keyword: String, title: String): TemplateSelection? {
|
||||||
for ((group, lines) in listOf(keyword to plan.keywordTemplates[keyword].orEmpty(), "" to plan.templates)) {
|
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 }
|
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 picked = order[position]
|
||||||
val text = plan.renderTemplate(picked.value, keyword, title) ?: continue
|
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
|
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
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
package com.jieliu.app.task
|
package com.jieliu.app.task
|
||||||
|
|
||||||
|
import java.util.UUID
|
||||||
|
|
||||||
enum class ReplyMode(val label: String) {
|
enum class ReplyMode(val label: String) {
|
||||||
BROWSE("仅浏览"),
|
BROWSE("仅浏览"),
|
||||||
TEMPLATES("随机使用话术并发送"),
|
TEMPLATES("匹配评论并回复"),
|
||||||
DEEPSEEK("话术优先,DeepSeek 兜底"),
|
DEEPSEEK("匹配评论并回复"),
|
||||||
}
|
}
|
||||||
|
|
||||||
data class TemplatePhoto(val id: String, val displayName: String) {
|
data class TemplatePhoto(val id: String, val displayName: String) {
|
||||||
@@ -36,26 +38,15 @@ data class TaskPlan(
|
|||||||
val model: String = "deepseek-flash",
|
val model: String = "deepseek-flash",
|
||||||
val instructions: String = "根据视频内容提供一句具体、有帮助的中文评论。",
|
val instructions: String = "根据视频内容提供一句具体、有帮助的中文评论。",
|
||||||
val keywordTemplates: Map<String, List<String>> = emptyMap(),
|
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() {
|
fun validate() {
|
||||||
require(keywords.size in 1..MAX_KEYWORDS && keywords.all { it.isNotBlank() && it.length <= 120 }) {
|
if (contentTypes == null) validateLegacy() else validateHierarchy(contentTypes)
|
||||||
"请填写 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() }) {
|
|
||||||
"请在关键词组或通用组至少填写一条话术。"
|
|
||||||
}
|
|
||||||
require(limit in 1..100) { "单次任务数量须为 1–100。" }
|
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) {
|
require(watchSeconds.first in 1..300 && watchSeconds.last in watchSeconds.first..300) {
|
||||||
"观看区间须在 1–300 秒之间,且下限不大于上限。"
|
"观看区间须在 1–300 秒之间,且下限不大于上限。"
|
||||||
}
|
}
|
||||||
@@ -66,20 +57,91 @@ data class TaskPlan(
|
|||||||
require(instructions.length <= 1000) { "DeepSeek 话术说明最多 1000 字符。" }
|
require(instructions.length <= 1000) { "DeepSeek 话术说明最多 1000 字符。" }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun photoIds(): Set<String> = templatePhotos.values.asSequence()
|
private fun validateLegacy() {
|
||||||
.flatMap { it.values.asSequence() }
|
require(selectedTypeId == null) { "所选内容类型不存在。" }
|
||||||
.map(TemplatePhoto::id)
|
require(keywords.size in 1..MAX_KEYWORDS && keywords.all { it.isNotBlank() && it.length <= 120 }) {
|
||||||
.toSet()
|
"请填写 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 {
|
private fun validateHierarchy(types: List<ContentType>) {
|
||||||
require(itemIndex in 0 until limit)
|
require(selectedTypeId == null || types.any { it.id == selectedTypeId }) { "所选内容类型不存在。" }
|
||||||
val perKeyword = limit / keywords.size
|
require(types.all { normalizeKeyword(it.name).isNotEmpty() && it.name.length <= 120 }) {
|
||||||
val extra = limit % keywords.size
|
"内容类型名称不能为空,每个最多 120 字符。"
|
||||||
val extraItems = (perKeyword + 1) * extra
|
}
|
||||||
|
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) {
|
return if (itemIndex < extraItems) {
|
||||||
itemIndex / (perKeyword + 1)
|
itemIndex / (perGroup + 1)
|
||||||
} else {
|
} else {
|
||||||
extra + (itemIndex - extraItems) / perKeyword
|
extra + (itemIndex - extraItems) / perGroup
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,8 +155,18 @@ data class TaskPlan(
|
|||||||
companion object {
|
companion object {
|
||||||
const val MAX_KEYWORDS = 30
|
const val MAX_KEYWORDS = 30
|
||||||
const val MAX_COMMENT = 120
|
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 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? {
|
fun commentText(text: String): String? {
|
||||||
val singleLine = text.replace(Regex("[\\p{Cc}\\s]+"), " ").trim()
|
val singleLine = text.replace(Regex("[\\p{Cc}\\s]+"), " ").trim()
|
||||||
if (singleLine.isEmpty()) return null
|
if (singleLine.isEmpty()) return null
|
||||||
|
|||||||
@@ -1,13 +1,16 @@
|
|||||||
package com.jieliu.app.task
|
package com.jieliu.app.task
|
||||||
|
|
||||||
import com.jieliu.app.platform.CommentPublishResult
|
import com.jieliu.app.platform.CommentPublishResult
|
||||||
|
import com.jieliu.app.platform.CommentTarget
|
||||||
import com.jieliu.app.platform.PlatformAdapter
|
import com.jieliu.app.platform.PlatformAdapter
|
||||||
import com.jieliu.app.platform.PlatformException
|
import com.jieliu.app.platform.PlatformException
|
||||||
import com.jieliu.app.platform.VideoContext
|
import com.jieliu.app.platform.VideoContext
|
||||||
import java.util.concurrent.CancellationException
|
import java.util.concurrent.CancellationException
|
||||||
|
|
||||||
interface TaskRunStorage {
|
interface TaskRunStorage {
|
||||||
|
fun readPlan(): TaskPlan
|
||||||
fun saveCheckpoint(checkpoint: TaskCheckpoint)
|
fun saveCheckpoint(checkpoint: TaskCheckpoint)
|
||||||
|
fun savePendingIfCurrent(checkpoint: TaskCheckpoint, matchesPlan: (TaskPlan) -> Boolean): Boolean
|
||||||
fun appendLog(message: String, warning: Boolean = false)
|
fun appendLog(message: String, warning: Boolean = false)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -15,11 +18,16 @@ internal class TaskRunner(
|
|||||||
private val store: TaskRunStorage,
|
private val store: TaskRunStorage,
|
||||||
private val plan: TaskPlan,
|
private val plan: TaskPlan,
|
||||||
private val platform: PlatformAdapter,
|
private val platform: PlatformAdapter,
|
||||||
private val modelReply: ((String, String, List<String>) -> String)?,
|
|
||||||
private val cancelled: () -> Boolean,
|
private val cancelled: () -> Boolean,
|
||||||
private val status: (String) -> Unit,
|
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
|
var checkpoint = initial
|
||||||
fun persist(next: TaskCheckpoint) {
|
fun persist(next: TaskCheckpoint) {
|
||||||
store.saveCheckpoint(next)
|
store.saveCheckpoint(next)
|
||||||
@@ -27,82 +35,94 @@ internal class TaskRunner(
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
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) { "请先核对上一条评论的发送结果。" }
|
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("正在打开目标应用")
|
status("正在打开目标应用")
|
||||||
platform.launch()
|
platform.launch()
|
||||||
var activeKeyword: String? = null
|
var activeTypeId: String? = null
|
||||||
var video: VideoContext? = null
|
var video: VideoContext? = null
|
||||||
while (!checkpoint.complete) {
|
while (!checkpoint.complete) {
|
||||||
requireRunning(cancelled)
|
requireRunning(cancelled)
|
||||||
val keyword = checkNotNull(checkpoint.keyword)
|
val type = checkNotNull(checkpoint.contentType)
|
||||||
var candidate: VideoContext = if (keyword != activeKeyword || video == null) {
|
val first = if (type.id != activeTypeId || video == null) {
|
||||||
status("正在搜索 $keyword")
|
status("正在搜索 ${type.name}")
|
||||||
store.appendLog("搜索关键词 $keyword")
|
store.appendLog("搜索内容类型 ${type.name}")
|
||||||
platform.search(keyword).also { activeKeyword = keyword }
|
platform.search(type.name).also { activeTypeId = type.id }
|
||||||
} else {
|
} else {
|
||||||
status("正在打开下一条视频")
|
status("正在打开下一条视频")
|
||||||
platform.nextVideo(video)
|
platform.nextVideo(video)
|
||||||
}
|
}
|
||||||
val visited = mutableSetOf<String>()
|
val candidate = locateVideo(first, checkpoint)
|
||||||
while (checkpoint.hasSeen(candidate.key)) {
|
|
||||||
check(visited.add(candidate.key) && visited.size <= plan.limit) { "搜索结果反复返回同一批视频" }
|
|
||||||
candidate = platform.nextVideo(candidate)
|
|
||||||
}
|
|
||||||
video = candidate
|
video = candidate
|
||||||
|
|
||||||
val watchSeconds = randomIn(plan.watchSeconds.first, plan.watchSeconds.last)
|
val number = checkpoint.receipts.size + 1
|
||||||
status("正在观看第 ${checkpoint.receipts.size + 1} 条 · ${watchSeconds} 秒")
|
if (checkpoint.activeVideo == null) watch(candidate, number)
|
||||||
store.appendLog("观看第 ${checkpoint.receipts.size + 1} 条 · ${watchSeconds} 秒")
|
if (mode == ReplyMode.BROWSE) {
|
||||||
pauseFor(watchSeconds * 1000L, cancelled)
|
|
||||||
check(platform.currentVideo().key == candidate.key) { "观看期间视频已切换,请恢复任务。" }
|
|
||||||
|
|
||||||
if (plan.replyMode == ReplyMode.BROWSE) {
|
|
||||||
persist(checkpoint.finish(candidate.key, Outcome.WATCHED))
|
persist(checkpoint.finish(candidate.key, Outcome.WATCHED))
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
val template = checkpoint.selectTemplate(keyword, candidate.title)
|
if (checkpoint.activeVideo == null) persist(checkpoint.startVideo(candidate.key))
|
||||||
val canGenerate = plan.replyMode == ReplyMode.DEEPSEEK && modelReply != null
|
val openPanel = store.readPlan().findType(type.id)?.rules?.isNotEmpty() == true
|
||||||
val openPanel = template != null || canGenerate
|
if (openPanel) {
|
||||||
val samples = if (openPanel) {
|
|
||||||
status("正在打开评论区")
|
status("正在打开评论区")
|
||||||
platform.openComments(candidate)
|
platform.openComments(candidate)
|
||||||
} else {
|
var screen = 1
|
||||||
emptyList()
|
while (checkpoint.activeVideo != null) {
|
||||||
}
|
requireRunning(cancelled)
|
||||||
status("正在准备评论")
|
val currentType = store.readPlan().findType(type.id)?.takeIf { it.rules.isNotEmpty() } ?: break
|
||||||
val text = template?.text ?: if (canGenerate) generateReply(keyword, candidate.title, samples) else null
|
status("正在识别评论 · 第 $screen 屏")
|
||||||
if (text == null) {
|
val reply = findVisibleReply(currentType, candidate.title, checkpoint)
|
||||||
val number = checkpoint.receipts.size + 1
|
if (reply == null) {
|
||||||
val reason = if (plan.replyMode == ReplyMode.DEEPSEEK && modelReply == null) {
|
if (screen > MAX_COMMENT_SWIPES || !platform.scrollComments()) break
|
||||||
"无可用话术,DeepSeek 密钥不可用"
|
screen++
|
||||||
} else {
|
|
||||||
"无可用回复内容"
|
|
||||||
}
|
|
||||||
persist(checkpoint.finish(candidate.key, Outcome.NO_REPLY))
|
|
||||||
store.appendLog("第 $number 条$reason,已跳过", warning = true)
|
|
||||||
if (openPanel && !checkpoint.complete) platform.closeComments()
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
val photo = template?.photo
|
store.appendLog("第 $screen 屏命中评论关键字 ${reply.rule.keyword}")
|
||||||
status(if (photo == null) "正在提交并回读评论" else "正在准备并提交图文评论")
|
val result = submitReply(candidate, reply) { comment ->
|
||||||
val beforeClick = {
|
val armed = checkpoint.arm(comment)
|
||||||
requireRunning(cancelled)
|
check(store.savePendingIfCurrent(armed) { latest ->
|
||||||
persist(checkpoint.arm(PendingComment(candidate.key, candidate.title, text, template?.use, photo)))
|
latest.findType(type.id)?.let(::KeywordMatcher)?.matchingRule(reply.target.text) == reply.rule
|
||||||
|
}) { "关键字或话术已更新,未提交此回复。请清除当前草稿后继续任务。" }
|
||||||
|
checkpoint = armed
|
||||||
}
|
}
|
||||||
val result = if (photo == null) platform.publishComment(text, beforeClick)
|
val confirmation = if (result == CommentPublishResult.UNCERTAIN && checkpoint.canAutomaticallyRecheck()) {
|
||||||
else platform.publishPhotoComment(text, photo, beforeClick)
|
confirmPending(checkpoint, inCurrentRun = true)
|
||||||
if (result == CommentPublishResult.UNCERTAIN) {
|
} else result
|
||||||
error("请在目标应用里核对这条评论的发送结果。")
|
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} 条评论发送")
|
checkpoint.activeVideo?.let { progress ->
|
||||||
if (!checkpoint.complete) platform.closeComments()
|
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} 条")
|
store.appendLog("任务完成 · 处理 ${checkpoint.receipts.size} 条 · 确认发送 ${checkpoint.sentCount} 条")
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
val message = when {
|
val message = when {
|
||||||
|
recheckPending && checkpoint.pending != null -> {
|
||||||
|
if (cancelled() || error is CancellationException) "自动核对已暂停,发送结果仍待核对。"
|
||||||
|
else "自动核对未确认,发送结果仍待核对。"
|
||||||
|
}
|
||||||
checkpoint.pending != null -> "发送结果待核对,请在目标应用确认后继续。"
|
checkpoint.pending != null -> "发送结果待核对,请在目标应用确认后继续。"
|
||||||
cancelled() || error is CancellationException -> "任务已暂停,可从检查点继续。"
|
cancelled() || error is CancellationException -> "任务已暂停,可从检查点继续。"
|
||||||
error is PlatformException || error is IllegalStateException -> error.message ?: "任务中断"
|
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? {
|
private fun confirmPending(checkpoint: TaskCheckpoint, inCurrentRun: Boolean = false): CommentPublishResult {
|
||||||
try {
|
check(checkpoint.canAutomaticallyRecheck()) { "这条回复的自动核对期限已过。" }
|
||||||
val generated = checkNotNull(modelReply).invoke(keyword, title, comments)
|
val pending = checkNotNull(checkpoint.pending)
|
||||||
|
val type = checkNotNull(checkpoint.contentType)
|
||||||
requireRunning(cancelled)
|
requireRunning(cancelled)
|
||||||
return TaskPlan.commentText(generated)
|
if (inCurrentRun) {
|
||||||
} catch (error: CancellationException) {
|
store.appendLog("本次任务继续核对已提交回复")
|
||||||
throw error
|
} else {
|
||||||
} catch (error: Exception) {
|
store.appendLog("开始自动核对一条待确认回复")
|
||||||
|
status("正在打开目标应用")
|
||||||
|
platform.launch()
|
||||||
|
}
|
||||||
|
status("正在定位待核对的视频")
|
||||||
|
val video = locateVideo(platform.search(type.name), checkpoint)
|
||||||
requireRunning(cancelled)
|
requireRunning(cancelled)
|
||||||
val detail = if (error is IllegalStateException) error.message else error.javaClass.simpleName
|
status("正在打开待核对的视频评论区")
|
||||||
store.appendLog("DeepSeek 生成失败($detail)", warning = true)
|
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
|
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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,9 +2,8 @@
|
|||||||
<resources>
|
<resources>
|
||||||
<string name="app_name">拾见</string>
|
<string name="app_name">拾见</string>
|
||||||
<string name="accessibility_label">拾见任务服务</string>
|
<string name="accessibility_label">拾见任务服务</string>
|
||||||
<string name="accessibility_description">在你主动启动任务时识别所选应用的页面、输入搜索词并按配置浏览或发送评论。可在拾见的任务页暂停。</string>
|
<string name="accessibility_description">在你主动启动任务时按内容类型搜索和浏览视频,并按配置识别、回复匹配的评论。可在拾见任务页暂停。</string>
|
||||||
<string name="tab_task">任务</string>
|
<string name="tab_task">任务</string>
|
||||||
<string name="tab_settings">配置</string>
|
<string name="tab_settings">配置</string>
|
||||||
<string name="tab_logs">日志</string>
|
<string name="tab_logs">日志</string>
|
||||||
<string name="clear_deepseek_key">清除已保存的 API Key</string>
|
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
android:accessibilityFlags="flagReportViewIds|flagRetrieveInteractiveWindows|flagIncludeNotImportantViews"
|
android:accessibilityFlags="flagReportViewIds|flagRetrieveInteractiveWindows|flagIncludeNotImportantViews"
|
||||||
android:canPerformGestures="true"
|
android:canPerformGestures="true"
|
||||||
android:canRetrieveWindowContent="true"
|
android:canRetrieveWindowContent="true"
|
||||||
|
android:canTakeScreenshot="true"
|
||||||
android:description="@string/accessibility_description"
|
android:description="@string/accessibility_description"
|
||||||
android:notificationTimeout="200"
|
android:notificationTimeout="200"
|
||||||
android:packageNames="com.ss.android.ugc.aweme" />
|
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
|
package com.jieliu.app.task
|
||||||
|
|
||||||
import com.jieliu.app.platform.CommentPublishResult
|
import com.jieliu.app.platform.CommentPublishResult
|
||||||
|
import com.jieliu.app.platform.CommentTarget
|
||||||
import com.jieliu.app.platform.PlatformAdapter
|
import com.jieliu.app.platform.PlatformAdapter
|
||||||
import com.jieliu.app.platform.VideoContext
|
import com.jieliu.app.platform.VideoContext
|
||||||
import org.junit.Assert.assertEquals
|
import org.junit.Assert.assertEquals
|
||||||
@@ -8,204 +9,445 @@ import org.junit.Assert.assertFalse
|
|||||||
import org.junit.Assert.assertNull
|
import org.junit.Assert.assertNull
|
||||||
import org.junit.Assert.assertTrue
|
import org.junit.Assert.assertTrue
|
||||||
import org.junit.Test
|
import org.junit.Test
|
||||||
|
import java.util.UUID
|
||||||
|
|
||||||
class TaskRunnerTest {
|
class TaskRunnerTest {
|
||||||
@Test fun keywordAndCommonRepliesBypassTheModelAndAreJournaledBeforeConfirmedSend() {
|
@Test fun searchesTypeNameAndRepliesInThreadToTheMatchingKeywordAfterScrolling() {
|
||||||
val plan = fastPlan(ReplyMode.DEEPSEEK).copy(
|
val plan = plan(firstType, secondType)
|
||||||
keywords = listOf("台灯", "整理"),
|
val store = RecordingStore(TaskCheckpoint("type-search", plan))
|
||||||
keywordTemplates = mapOf("台灯" to listOf("专属建议")),
|
val platform = FakePlatform(store, listOf(
|
||||||
templates = listOf("通用建议"),
|
listOf(target("first", "有谁讨论键盘吗")),
|
||||||
limit = 2,
|
listOf(target("second", "想了解大模型 API 充值")),
|
||||||
)
|
))
|
||||||
val store = RecordingStore(TaskCheckpoint("local", plan))
|
|
||||||
val platform = FakePlatform(store)
|
|
||||||
var modelCalls = 0
|
|
||||||
|
|
||||||
execute(store, platform) { _, _, _ ->
|
execute(store, platform)
|
||||||
modelCalls++
|
|
||||||
"模型建议"
|
|
||||||
}
|
|
||||||
|
|
||||||
assertEquals(0, modelCalls)
|
assertEquals(listOf("大模型充值"), platform.searches)
|
||||||
assertEquals(listOf("专属建议", "通用建议"), platform.attempts)
|
assertEquals(1, platform.swipes)
|
||||||
assertEquals(platform.attempts, platform.pendingAtSend.map { it?.text })
|
val attempt = platform.attempts.single()
|
||||||
val uses = listOf(TemplateUse("台灯", 0), TemplateUse("", 0))
|
assertEquals("second", attempt.targetKey)
|
||||||
assertEquals(uses, platform.pendingAtSend.map { it?.templateUse })
|
assertEquals("测试用户", attempt.targetAuthor)
|
||||||
assertEquals(uses, store.checkpoint.receipts.map { it.templateUse })
|
assertEquals("API 充值对应的图文", attempt.text)
|
||||||
assertEquals(listOf(Outcome.SENT, Outcome.SENT), store.checkpoint.receipts.map { it.outcome })
|
assertEquals(photos, attempt.photos)
|
||||||
assertEquals(2, store.checkpoint.sentCount)
|
assertEquals(apiRule.id, attempt.templateUse?.group)
|
||||||
assertNull(store.checkpoint.pending)
|
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)
|
assertTrue(store.checkpoint.complete)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test fun missingLocalRepliesUseTheModelInDeepSeekMode() {
|
@Test fun noMatchAndEmptyWinningLibraryNeverSend() {
|
||||||
val store = RecordingStore(TaskCheckpoint("model", fastPlan(ReplyMode.DEEPSEEK)))
|
val broaderType = firstType.copy(rules = firstType.rules + rule("API 充值服务"))
|
||||||
val platform = FakePlatform(store)
|
val store = RecordingStore(TaskCheckpoint("no-match", plan(broaderType, secondType)))
|
||||||
val requests = mutableListOf<Triple<String, String, List<String>>>()
|
val platform = FakePlatform(store, listOf(
|
||||||
|
listOf(target("first", "想看看键盘"), target("second", "需要 API 充值服务")),
|
||||||
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)
|
|
||||||
|
|
||||||
execute(store, platform)
|
execute(store, platform)
|
||||||
|
|
||||||
assertEquals(listOf("专属建议"), platform.attempts)
|
assertEquals(Outcome.NO_REPLY, store.checkpoint.receipts.single().outcome)
|
||||||
val pending = checkNotNull(store.checkpoint.pending)
|
assertTrue(platform.preparations.isEmpty())
|
||||||
assertEquals(pending, platform.pendingAtSend.single())
|
assertTrue(platform.attempts.isEmpty())
|
||||||
assertEquals(TemplateUse("台灯", 0), pending.templateUse)
|
assertTrue(store.logs.any { "已跳过" in it })
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test fun imageTemplateUsesImagePublisherAndKeepsThePhotoWhenTheReceiptIsUncertain() {
|
@Test fun disappearingTargetDoesNotBlockAnotherVisibleMatch() {
|
||||||
val photo = TemplatePhoto("c49b0088-a509-4c2d-b7e8-8455f6bf7f39", "桌面.png")
|
val store = RecordingStore(TaskCheckpoint("missing", plan(firstType)))
|
||||||
val plan = fastPlan(ReplyMode.TEMPLATES).copy(
|
val platform = FakePlatform(store, listOf(listOf(
|
||||||
keywordTemplates = mapOf("台灯" to listOf("专属建议")),
|
target("stale", "API充值"),
|
||||||
templatePhotos = mapOf("台灯" to mapOf("专属建议" to photo)),
|
target("visible", "付款方式是什么"),
|
||||||
)
|
))).apply { unavailable.add("stale") }
|
||||||
val store = RecordingStore(TaskCheckpoint("photo", plan))
|
|
||||||
val platform = FakePlatform(store, CommentPublishResult.UNCERTAIN)
|
|
||||||
|
|
||||||
execute(store, platform)
|
execute(store, platform)
|
||||||
|
|
||||||
assertEquals(listOf(photo), platform.photoAttempts)
|
assertEquals(listOf("stale", "visible"), platform.preparations)
|
||||||
assertEquals(listOf("专属建议"), platform.attempts)
|
assertEquals("visible", platform.attempts.single().targetKey)
|
||||||
assertEquals(photo, platform.pendingAtSend.single()?.photo)
|
assertEquals("付款方式对应的话术", platform.attempts.single().text)
|
||||||
assertEquals(photo, store.checkpoint.pending?.photo)
|
|
||||||
assertTrue(store.checkpoint.receipts.isEmpty())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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())
|
assertTrue(platform.attempts.isEmpty())
|
||||||
assertNull(store.checkpoint.pending)
|
assertNull(store.checkpoint.pending)
|
||||||
assertEquals(Outcome.NO_REPLY, store.checkpoint.receipts.single().outcome)
|
assertTrue(store.checkpoint.message.contains("未提交"))
|
||||||
assertNull(store.checkpoint.receipts.single().templateUse)
|
assertTrue(store.checkpoint.receipts.isEmpty())
|
||||||
assertEquals(0, store.checkpoint.sentCount)
|
|
||||||
assertTrue(store.checkpoint.complete)
|
|
||||||
assertTrue(store.logs.any { (message, _) -> "跳过" in message })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun fastPlan(mode: ReplyMode) = TaskPlan(
|
@Test fun uncertainTargetedReplyKeepsTheParentAndAllImagesAndDoesNotRetry() {
|
||||||
keywords = listOf("台灯"),
|
val store = RecordingStore(TaskCheckpoint("uncertain", plan(firstType)))
|
||||||
limit = 1,
|
val platform = FakePlatform(store, listOf(listOf(target("match", "API 充值"))), CommentPublishResult.UNCERTAIN)
|
||||||
// This fixture calls the runner directly, after input validation would normally run.
|
|
||||||
watchSeconds = 0..0,
|
|
||||||
replyMode = mode,
|
|
||||||
)
|
|
||||||
|
|
||||||
private fun execute(
|
execute(store, platform)
|
||||||
store: RecordingStore,
|
|
||||||
platform: FakePlatform,
|
val pending = checkNotNull(store.checkpoint.pending)
|
||||||
model: ((String, String, List<String>) -> String)? = null,
|
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
|
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 {
|
private class RecordingStore(initial: TaskCheckpoint) : TaskRunStorage {
|
||||||
var checkpoint = initial
|
var checkpoint = initial
|
||||||
private set
|
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) {
|
override fun saveCheckpoint(checkpoint: TaskCheckpoint) {
|
||||||
this.checkpoint = checkpoint
|
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) {
|
override fun appendLog(message: String, warning: Boolean) {
|
||||||
logs.add(message to warning)
|
logs.add(message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private class FakePlatform(
|
private class FakePlatform(
|
||||||
private val store: RecordingStore,
|
private val store: RecordingStore,
|
||||||
|
private val screens: List<List<CommentTarget>> = listOf(emptyList()),
|
||||||
private val result: CommentPublishResult = CommentPublishResult.CONFIRMED,
|
private val result: CommentPublishResult = CommentPublishResult.CONFIRMED,
|
||||||
) : PlatformAdapter {
|
) : PlatformAdapter {
|
||||||
val attempts = mutableListOf<String>()
|
val attempts = mutableListOf<PendingComment>()
|
||||||
val pendingAtSend = mutableListOf<PendingComment?>()
|
val searches = mutableListOf<String>()
|
||||||
val photoAttempts = mutableListOf<TemplatePhoto>()
|
val openedVideos = mutableListOf<String>()
|
||||||
val comments = listOf("模拟评论样本")
|
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
|
var launches = 0
|
||||||
private set
|
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 nextKey = 0
|
||||||
|
private var currentScreen = 0
|
||||||
|
private var currentScreens = screens
|
||||||
|
private var replyTarget: CommentTarget? = null
|
||||||
private lateinit var video: VideoContext
|
private lateinit var video: VideoContext
|
||||||
|
|
||||||
override fun launch() {
|
override fun launch() {
|
||||||
launches++
|
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 currentVideo(): VideoContext = video
|
||||||
|
|
||||||
override fun nextVideo(previous: VideoContext): VideoContext = showVideo("后续样片")
|
override fun nextVideo(previous: VideoContext): VideoContext = showVideo("后续样片")
|
||||||
|
|
||||||
override fun openComments(expected: VideoContext): List<String> = comments
|
override fun openComments(expected: VideoContext): List<String> {
|
||||||
|
commentPanels++
|
||||||
override fun publishComment(text: String, beforeClick: () -> Unit): CommentPublishResult {
|
openedVideos.add(expected.key)
|
||||||
beforeClick()
|
currentScreen = 0
|
||||||
pendingAtSend.add(store.checkpoint.pending)
|
currentScreens = screensForVideo?.invoke(expected) ?: screens
|
||||||
attempts.add(text)
|
replyTarget = null
|
||||||
return result
|
return emptyList()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun publishPhotoComment(text: String, photo: TemplatePhoto, beforeClick: () -> Unit): CommentPublishResult {
|
override fun scanComments(): List<CommentTarget> = currentScreens[currentScreen]
|
||||||
photoAttempts.add(photo)
|
|
||||||
return publishComment(text, beforeClick)
|
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
|
override fun closeComments() = Unit
|
||||||
@@ -215,4 +457,25 @@ class TaskRunnerTest {
|
|||||||
return video
|
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
|
package com.jieliu.app.task
|
||||||
|
|
||||||
import org.junit.Assert.assertEquals
|
import org.junit.Assert.assertEquals
|
||||||
import org.junit.Assert.assertNull
|
|
||||||
import org.junit.Assert.assertThrows
|
import org.junit.Assert.assertThrows
|
||||||
import org.junit.Test
|
import org.junit.Test
|
||||||
|
import java.util.UUID
|
||||||
|
|
||||||
class TemplatePhotoTest {
|
class TemplatePhotoTest {
|
||||||
private val lampPhoto = TemplatePhoto("16d3b229-bb28-43e6-a8d0-c4f587c04a63", "台灯.jpg")
|
private val lampPhoto = TemplatePhoto("16d3b229-bb28-43e6-a8d0-c4f587c04a63", "台灯.jpg")
|
||||||
private val commonPhoto = TemplatePhoto("4fa2bb0a-70cf-45a4-87fe-d83fbd856ac1", "参考图.png")
|
private val commonPhoto = TemplatePhoto("4fa2bb0a-70cf-45a4-87fe-d83fbd856ac1", "参考图.png")
|
||||||
|
private val deskPhoto = TemplatePhoto("34f80961-52ed-43ca-aeb6-58e3880997b9", "桌面.jpg")
|
||||||
|
|
||||||
@Test fun bindingUsesTheRawPhraseAndStaysInItsGroup() {
|
@Test fun bindingUsesTheRawPhraseAndStaysInItsGroup() {
|
||||||
val phrase = "{title}的摆放建议"
|
val phrase = "{title}的摆放建议"
|
||||||
@@ -15,7 +16,7 @@ class TemplatePhotoTest {
|
|||||||
keywords = listOf("灯具", "书架"),
|
keywords = listOf("灯具", "书架"),
|
||||||
templates = listOf(phrase),
|
templates = listOf(phrase),
|
||||||
keywordTemplates = mapOf("灯具" to 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()
|
plan.validate()
|
||||||
val checkpoint = TaskCheckpoint("photo-bindings", plan)
|
val checkpoint = TaskCheckpoint("photo-bindings", plan)
|
||||||
@@ -23,28 +24,29 @@ class TemplatePhotoTest {
|
|||||||
val keyword = checkNotNull(checkpoint.selectTemplate("灯具", "台灯"))
|
val keyword = checkNotNull(checkpoint.selectTemplate("灯具", "台灯"))
|
||||||
val common = checkNotNull(checkpoint.selectTemplate("书架", "书架"))
|
val common = checkNotNull(checkpoint.selectTemplate("书架", "书架"))
|
||||||
assertEquals("台灯的摆放建议", keyword.text)
|
assertEquals("台灯的摆放建议", keyword.text)
|
||||||
assertEquals(lampPhoto, keyword.photo)
|
assertEquals(listOf(lampPhoto, deskPhoto), keyword.photos)
|
||||||
assertEquals(commonPhoto, common.photo)
|
assertEquals(listOf(commonPhoto), common.photos)
|
||||||
assertEquals(setOf(lampPhoto.id, commonPhoto.id), plan.photoIds())
|
assertEquals(setOf(lampPhoto.id, deskPhoto.id, commonPhoto.id), plan.photoIds())
|
||||||
assertNull(checkNotNull(checkpoint.copy(plan = plan.copy(templatePhotos = emptyMap()))
|
val legacy = checkpoint.copy(plan = plan.copy(templatePhotos = emptyMap()))
|
||||||
.selectTemplate("灯具", "台灯")).photo)
|
assertEquals(emptyList<TemplatePhoto>(), checkNotNull(legacy.selectTemplate("灯具", "台灯")).photos)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test fun photosKeepTheTextRotationAndAnArmedDraftAcrossResume() {
|
@Test fun photosKeepTheTextRotationAndAnArmedDraftAcrossResume() {
|
||||||
val phrases = listOf("{title}的角度", "色温建议", "{title}的角度")
|
val phrases = listOf("{title}的角度", "色温建议", "{title}的角度")
|
||||||
val plainPlan = TaskPlan(keywords = listOf("灯具"), keywordTemplates = mapOf("灯具" to phrases), limit = 4)
|
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)
|
var checkpoint = TaskCheckpoint("photo-rotation", photoPlan)
|
||||||
repeat(photoPlan.limit) { index ->
|
repeat(photoPlan.limit) { index ->
|
||||||
val expected = checkpoint.copy(plan = plainPlan).selectTemplate("灯具", "台灯")
|
val expected = checkpoint.copy(plan = plainPlan).selectTemplate("灯具", "台灯")
|
||||||
val picked = checkNotNull(checkpoint.selectTemplate("灯具", "台灯"))
|
val picked = checkNotNull(checkpoint.selectTemplate("灯具", "台灯"))
|
||||||
assertEquals(expected, picked.copy(photo = null))
|
assertEquals(expected, picked.copy(photos = emptyList()))
|
||||||
assertEquals(if (picked.use.index == 0) lampPhoto else null, picked.photo)
|
assertEquals(if (picked.use.index == 0) orderedPhotos else emptyList(), picked.photos)
|
||||||
|
|
||||||
val videoKey = "video-$index"
|
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 = "发送结果待核对")
|
val resumed = armed.copy(message = "发送结果待核对")
|
||||||
assertEquals(picked.photo, resumed.pending?.photo)
|
assertEquals(picked.photos, resumed.pending?.photos)
|
||||||
checkpoint = resumed.finish(videoKey, Outcome.SKIPPED)
|
checkpoint = resumed.finish(videoKey, Outcome.SKIPPED)
|
||||||
assertEquals(picked.use, checkpoint.receipts.last().templateUse)
|
assertEquals(picked.use, checkpoint.receipts.last().templateUse)
|
||||||
}
|
}
|
||||||
@@ -53,10 +55,10 @@ class TemplatePhotoTest {
|
|||||||
@Test fun invalidPhotoMetadataAndOrphanedBindingsAreRejected() {
|
@Test fun invalidPhotoMetadataAndOrphanedBindingsAreRejected() {
|
||||||
val plan = TaskPlan(keywords = listOf("灯具"), keywordTemplates = mapOf("灯具" to listOf("观察细节")))
|
val plan = TaskPlan(keywords = listOf("灯具"), keywordTemplates = mapOf("灯具" to listOf("观察细节")))
|
||||||
assertThrows(IllegalArgumentException::class.java) {
|
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) {
|
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.uppercase(), "图片.jpg") }
|
||||||
assertThrows(IllegalArgumentException::class.java) { TemplatePhoto(lampPhoto.id, "\n") }
|
assertThrows(IllegalArgumentException::class.java) { TemplatePhoto(lampPhoto.id, "\n") }
|
||||||
@@ -64,4 +66,18 @@ class TemplatePhotoTest {
|
|||||||
assertEquals("图片", TemplatePhoto.sanitizeDisplayName("\t"))
|
assertEquals("图片", TemplatePhoto.sanitizeDisplayName("\t"))
|
||||||
assertEquals("🙂".repeat(120), TemplatePhoto.sanitizeDisplayName("🙂".repeat(121)))
|
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
@@ -150,8 +150,27 @@
|
|||||||
margin-top: 7px;
|
margin-top: 7px;
|
||||||
}
|
}
|
||||||
|
|
||||||
#photo-binding [hidden] { display: none; }
|
[hidden] { display: none !important; }
|
||||||
#photo-binding button { border: 0; cursor: pointer; }
|
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"] {
|
.action.primary, .app-nav [aria-current="page"] {
|
||||||
color: #fff;
|
color: #fff;
|
||||||
@@ -222,22 +241,6 @@
|
|||||||
font-size: 14px;
|
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; }
|
code { font-size: .92em; overflow-wrap: anywhere; }
|
||||||
|
|
||||||
.entries {
|
.entries {
|
||||||
@@ -283,7 +286,7 @@
|
|||||||
<span class="mark" aria-hidden="true"><i></i><i></i><i></i></span>
|
<span class="mark" aria-hidden="true"><i></i><i></i><i></i></span>
|
||||||
<div>
|
<div>
|
||||||
<h1>拾见 · 界面预览</h1>
|
<h1>拾见 · 界面预览</h1>
|
||||||
<p>离线预览,可编辑话术并试用本机图片绑定。日志为演示数据。</p>
|
<p>离线预览,可编辑内容库并试用图片绑定。修改仅在本页保留。</p>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
@@ -296,10 +299,10 @@
|
|||||||
<div class="card">
|
<div class="card">
|
||||||
<h3>准备运行</h3>
|
<h3>准备运行</h3>
|
||||||
<p class="mode">抖音 · 仅浏览</p>
|
<p class="mode">抖音 · 仅浏览</p>
|
||||||
<p>关键词 1 个 · 单次 3 条</p>
|
<p>内容类型 1 个 · 单次 3 个视频</p>
|
||||||
<progress value="0" max="3" aria-label="已处理 0 条,共 3 条"></progress>
|
<progress value="0" max="3" aria-label="已处理 0 个视频,共 3 个"></progress>
|
||||||
<p class="summary">已处理 0 / 3 · 已确认发送 0</p>
|
<p class="summary">已处理视频 0 / 3 · 已确认回复 0 条</p>
|
||||||
<p>关键词 国外大模型充值</p>
|
<p>内容类型 · 模型服务</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<h3>无障碍服务未连接</h3>
|
<h3>无障碍服务未连接</h3>
|
||||||
@@ -308,6 +311,13 @@
|
|||||||
</div>
|
</div>
|
||||||
<span class="action primary" aria-disabled="true">开始任务</span>
|
<span class="action primary" aria-disabled="true">开始任务</span>
|
||||||
<span class="action">启用通知栏暂停按钮</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>
|
</div>
|
||||||
<nav class="app-nav" aria-label="任务页导航">
|
<nav class="app-nav" aria-label="任务页导航">
|
||||||
<a href="#task" aria-current="page">任务</a>
|
<a href="#task" aria-current="page">任务</a>
|
||||||
@@ -326,8 +336,8 @@
|
|||||||
<h3>任务范围</h3>
|
<h3>任务范围</h3>
|
||||||
<dl class="fields">
|
<dl class="fields">
|
||||||
<div><dt>平台</dt><dd class="control select">抖音</dd></div>
|
<div><dt>平台</dt><dd class="control select">抖音</dd></div>
|
||||||
<div><dt>搜索关键词</dt><dd class="control multiline">国外大模型充值</dd></div>
|
<div><dt><label for="search-scope">搜索范围</label></dt><dd><select id="search-scope" class="control settings-input"></select></dd></div>
|
||||||
<div><dt>单次任务总数</dt><dd class="control">3</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>
|
</dl>
|
||||||
</div>
|
</div>
|
||||||
<div class="card">
|
<div class="card">
|
||||||
@@ -344,57 +354,60 @@
|
|||||||
</dl>
|
</dl>
|
||||||
</div>
|
</div>
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<h3>评论</h3>
|
<h3>评论设置</h3>
|
||||||
<dl class="fields">
|
<dl class="fields">
|
||||||
<div>
|
<div>
|
||||||
<dt><label for="reply-mode">处理方式</label></dt>
|
<dt><label for="reply-mode">处理方式</label></dt>
|
||||||
<dd><select id="reply-mode" class="control settings-input">
|
<dd><select id="reply-mode" class="control settings-input">
|
||||||
<option>仅浏览</option>
|
<option>仅浏览</option>
|
||||||
<option>随机使用话术并发送</option>
|
<option>匹配评论并回复</option>
|
||||||
<option>话术优先,DeepSeek 兜底</option>
|
|
||||||
</select></dd>
|
</select></dd>
|
||||||
</div>
|
</div>
|
||||||
<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>
|
||||||
<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>
|
|
||||||
</dl>
|
</dl>
|
||||||
<p class="hint">先从当前关键词分组随机选一条。该分组为空时使用通用分组。支持 <code>{keyword}</code> 和 <code>{title}</code>。</p>
|
<p class="hint">达到回复上限或找不到更多匹配评论时,进入下一个视频。</p>
|
||||||
<dl class="fields">
|
</div>
|
||||||
<div>
|
<div class="card" id="content-library">
|
||||||
<dt><label for="photo-phrase">绑定到话术</label></dt>
|
<h3>内容库</h3>
|
||||||
<dd><select id="photo-phrase" class="control settings-input" disabled></select></dd>
|
<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>
|
</div>
|
||||||
</dl>
|
|
||||||
<div id="photo-binding" hidden>
|
<div id="photo-binding" hidden>
|
||||||
<p id="photo-name" class="hint" hidden></p>
|
<p id="photo-count" class="hint"></p>
|
||||||
<img id="photo-thumbnail" alt="已绑定图片预览" width="96" height="76" style="object-fit: contain" hidden>
|
<div id="photo-items"></div>
|
||||||
<input id="template-photo" type="file" accept="image/jpeg,image/png" hidden>
|
<input id="template-photo" type="file" accept="image/jpeg,image/png" multiple hidden>
|
||||||
<button id="photo-choose" type="button" class="action">选择本机图片</button>
|
<button id="photo-choose" type="button" class="action">添加本机图片</button>
|
||||||
<button id="photo-remove" type="button" class="action" hidden>移除图片</button>
|
<p id="photo-status" class="hint" role="status" hidden></p>
|
||||||
|
<p class="hint">支持 JPEG 和 PNG。修改名称、关键词或话术时,保留已绑定图片。</p>
|
||||||
</div>
|
</div>
|
||||||
<p class="hint">每条话术可绑定一张本机照片。改写话术后需重新绑定。</p>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="card">
|
<button type="button" class="action primary" id="save-preview">保存配置</button>
|
||||||
<h3>DeepSeek</h3>
|
<p id="library-status" role="status" hidden></p>
|
||||||
<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>
|
|
||||||
</div>
|
</div>
|
||||||
<nav class="app-nav" aria-label="配置页导航">
|
<nav class="app-nav" aria-label="配置页导航">
|
||||||
<a href="#task">任务</a>
|
<a href="#task">任务</a>
|
||||||
@@ -412,9 +425,11 @@
|
|||||||
<div class="card">
|
<div class="card">
|
||||||
<h3>运行日志</h3>
|
<h3>运行日志</h3>
|
||||||
<ul class="entries">
|
<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 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: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: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: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: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>
|
<li><time datetime="2026-11-25T15:18:47+08:00">11-25 15:18:47</time> 运行 观看第 2 条 · 11 秒</li>
|
||||||
@@ -431,77 +446,228 @@
|
|||||||
</figure>
|
</figure>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</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>
|
<script>
|
||||||
const groups = document.getElementById("template-group");
|
const byId = id => document.getElementById(id);
|
||||||
const editor = document.getElementById("template-editor");
|
const scope = byId("search-scope");
|
||||||
const photoPhrase = document.getElementById("photo-phrase");
|
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 photoBinding = document.getElementById("photo-binding");
|
||||||
const photoName = document.getElementById("photo-name");
|
const photoCount = document.getElementById("photo-count");
|
||||||
const thumbnail = document.getElementById("photo-thumbnail");
|
const photoItems = document.getElementById("photo-items");
|
||||||
const fileInput = document.getElementById("template-photo");
|
const fileInput = document.getElementById("template-photo");
|
||||||
const choosePhoto = document.getElementById("photo-choose");
|
const choosePhoto = document.getElementById("photo-choose");
|
||||||
const removePhoto = document.getElementById("photo-remove");
|
const photoStatus = document.getElementById("photo-status");
|
||||||
const drafts = new Map([["keyword-0", "这条视频里提到的方式适用于哪些地区?"]]);
|
const maxPhotos = 9;
|
||||||
const photos = new Map();
|
const types = [{ id: "model-services", name: "模型服务", rules: [
|
||||||
let activeGroup = groups.value;
|
{ 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;
|
let photoTarget;
|
||||||
|
|
||||||
const photoKey = () => JSON.stringify([activeGroup, photoPhrase.value]);
|
const fillPicker = (picker, options, selected, placeholder) => {
|
||||||
const redrawPhoto = () => {
|
picker.replaceChildren(...(options.length ? options.map(([id, title]) => new Option(title, id)) : [new Option(placeholder, "")]));
|
||||||
const attachment = photos.get(photoKey());
|
if (options.some(([id]) => id === selected)) picker.value = selected;
|
||||||
photoBinding.hidden = photoPhrase.disabled;
|
picker.disabled = !options.length;
|
||||||
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 redrawPhrases = () => {
|
const setStatus = (message = "") => {
|
||||||
const previous = photoPhrase.value;
|
photoStatus.textContent = message;
|
||||||
const phrases = [...new Set(editor.value.split(/\r?\n/).map(line => line.trim()).filter(Boolean))];
|
photoStatus.hidden = !message;
|
||||||
photoPhrase.replaceChildren(...(phrases.length ? phrases.map(phrase => new Option(phrase, phrase)) :
|
};
|
||||||
[new Option("先填写一条话术", "")]));
|
const photoItem = (phrase, entry, index) => {
|
||||||
if (phrases.includes(previous)) photoPhrase.value = previous;
|
const item = document.createElement("div");
|
||||||
photoPhrase.disabled = !phrases.length;
|
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();
|
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", () => {
|
choosePhoto.addEventListener("click", () => {
|
||||||
photoTarget = photoKey();
|
photoTarget = activePhrase();
|
||||||
fileInput.click();
|
fileInput.click();
|
||||||
});
|
});
|
||||||
fileInput.addEventListener("change", () => {
|
fileInput.addEventListener("change", () => {
|
||||||
const file = fileInput.files[0];
|
const stillPresent = types.some(type => type.rules.some(rule => rule.phrases.includes(photoTarget)));
|
||||||
if (photoTarget && file && ["image/jpeg", "image/png"].includes(file.type)) {
|
if (stillPresent && fileInput.files.length) {
|
||||||
const previous = photos.get(photoTarget);
|
const current = photoTarget.photos;
|
||||||
if (previous) URL.revokeObjectURL(previous.url);
|
const available = maxPhotos - current.length;
|
||||||
photos.set(photoTarget, { name: file.name, url: URL.createObjectURL(file) });
|
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;
|
photoTarget = undefined;
|
||||||
fileInput.value = "";
|
fileInput.value = "";
|
||||||
redrawPhoto();
|
redrawPhoto();
|
||||||
});
|
});
|
||||||
removePhoto.addEventListener("click", () => {
|
for (const picker of [typePicker, rulePicker, phrasePicker]) {
|
||||||
const key = photoKey();
|
picker.addEventListener("change", () => {
|
||||||
const attachment = photos.get(key);
|
setStatus();
|
||||||
if (attachment) URL.revokeObjectURL(attachment.url);
|
redrawLibrary();
|
||||||
photos.delete(key);
|
|
||||||
redrawPhoto();
|
|
||||||
});
|
});
|
||||||
photoPhrase.addEventListener("change", redrawPhoto);
|
}
|
||||||
editor.addEventListener("input", redrawPhrases);
|
byId("save-preview").addEventListener("click", () => {
|
||||||
|
const status = byId("library-status");
|
||||||
editor.value = drafts.get(activeGroup) ?? "";
|
const invalid = [byId("video-limit"), byId("replies-per-video")].find(input => !input.validity.valid);
|
||||||
redrawPhrases();
|
status.textContent = invalid ? `${invalid.labels[0].textContent}须为 1–100 的整数。` : "预览配置已更新。";
|
||||||
groups.addEventListener("change", () => {
|
status.classList.toggle("error", Boolean(invalid));
|
||||||
drafts.set(activeGroup, editor.value);
|
status.hidden = false;
|
||||||
activeGroup = groups.value;
|
invalid?.focus();
|
||||||
editor.value = drafts.get(activeGroup) ?? "";
|
|
||||||
redrawPhrases();
|
|
||||||
});
|
});
|
||||||
|
redrawLibrary();
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+99
-1
@@ -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 单条图文实发验收
|
## 2026-11-26 · 拾见 0.1.7 单条图文实发验收
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user