Release Shijian 0.1.19 with automatic Douyin reply receipts

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