feat:m1测试通过
This commit is contained in:
@@ -150,6 +150,11 @@ class MainActivity : ComponentActivity() {
|
||||
val accepted = com.haorui.app.automation.HaoRuiAccessibilityService.instance?.verifyAccountSandbox() == true
|
||||
com.haorui.app.automation.RunLogger.i("UI", "账号只读核验受理=$accepted")
|
||||
}
|
||||
"testDraft", "testDraftInvalid" -> if (applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE != 0) {
|
||||
val accepted = com.haorui.app.automation.HaoRuiAccessibilityService.instance?.startDraftSandbox(
|
||||
intent.getStringExtra("fixturePath").orEmpty(), intent.getStringExtra("cmd") == "testDraftInvalid") == true
|
||||
com.haorui.app.automation.RunLogger.i("UI", "自有素材草稿回归受理=$accepted")
|
||||
}
|
||||
// ── 装机调试命令(adb 触发,验证 F1/F2 用)─────────
|
||||
"testCredit" -> {
|
||||
val svc = com.haorui.app.automation.HaoRuiAccessibilityService.instance
|
||||
|
||||
@@ -412,6 +412,9 @@ class HaoRuiAccessibilityService : AccessibilityService() {
|
||||
// 装机调试(不动前台):信用分读取 / 互动沙盒
|
||||
addAction("com.haorui.app.ACTION_TEST_CREDIT")
|
||||
addAction("com.haorui.app.ACTION_TEST_INTERACT")
|
||||
// 自有素材草稿回归(debug APK):vivo 真机 activity intent 投递不稳,广播为可靠入口
|
||||
addAction("com.haorui.app.ACTION_TEST_DRAFT")
|
||||
addAction("com.haorui.app.ACTION_TEST_DRAFT_INVALID")
|
||||
// 回归测试:发布模式切换(草稿/正式)
|
||||
addAction("com.haorui.app.ACTION_SET_DRAFT")
|
||||
addAction("com.haorui.app.ACTION_SET_PUBLISH")
|
||||
@@ -613,6 +616,13 @@ class HaoRuiAccessibilityService : AccessibilityService() {
|
||||
RunLogger.i(TAG, "ACTION_TEST_INTERACT 启动结果=$ok")
|
||||
}
|
||||
}
|
||||
// 自有素材草稿回归(debug APK;等价于 cmd=testDraft / testDraftInvalid,走广播不受 intent 投递丢包影响)
|
||||
"com.haorui.app.ACTION_TEST_DRAFT",
|
||||
"com.haorui.app.ACTION_TEST_DRAFT_INVALID" -> {
|
||||
val path = intent.getStringExtra("fixturePath").orEmpty()
|
||||
val accepted = startDraftSandbox(path, intent.action == "com.haorui.app.ACTION_TEST_DRAFT_INVALID")
|
||||
RunLogger.i(TAG, "自有素材草稿回归受理=$accepted(广播 ${intent.action})")
|
||||
}
|
||||
// 回归测试发布模式切换(草稿/正式;autoPublish 无 UI 开关,走广播)
|
||||
"com.haorui.app.ACTION_SET_DRAFT" -> setAutoPublish(false)
|
||||
"com.haorui.app.ACTION_SET_PUBLISH" -> setAutoPublish(true)
|
||||
@@ -622,6 +632,10 @@ class HaoRuiAccessibilityService : AccessibilityService() {
|
||||
|
||||
fun startAutomation() {
|
||||
if (!checkVersionGate()) return
|
||||
if (runCatching { videoDownloader.hasPendingDrafts() }.getOrDefault(true)) {
|
||||
TaskStatusBus.status("存在待核对草稿,素材已保留;请先核对草稿结果")
|
||||
return
|
||||
}
|
||||
// ⚠️ P5-1 挂载点①:信用分门控(credit.gateEnabled)——
|
||||
// fail-open:识别失败不拦截只告警,防 OCR 不稳掐死全天任务。
|
||||
val cfg = latestConfig
|
||||
@@ -682,6 +696,19 @@ class HaoRuiAccessibilityService : AccessibilityService() {
|
||||
|
||||
fun isRunning(): Boolean = scheduler.isRunning
|
||||
|
||||
/** 仅调试 APK 的自有固定素材草稿回归,不启用采集、互动或正式发布。 */
|
||||
fun startDraftSandbox(path: String, invalidDeclaration: Boolean = false): Boolean = synchronized(stepLifecycleLock) {
|
||||
if (applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE == 0 ||
|
||||
!::scheduler.isInitialized || scheduler.isRunning || publisher.isWorking || interactor.isWorking ||
|
||||
frontGuard.creditNavigating || !foregroundCoordinator.isIdle() || latestConfig.toutiao.autoPublish ||
|
||||
latestConfig.crossPlatform.enabled || java.io.File(path).name != "haorui-draft-regression.mp4" ||
|
||||
!videoDownloader.isOwnedMedia(path) || runCatching { videoDownloader.hasPendingDrafts() }.getOrDefault(true)) return@synchronized false
|
||||
val accepted = publisher.submit("浩瑞草稿回归 ${java.util.UUID.randomUUID().toString().take(8)}", path,
|
||||
autoPublish = false, declaration = if (invalidDeclaration) "内容为原创" else "内容无需标注")
|
||||
if (accepted) scheduler.startLaneOnly(LaneScheduler.Lane.PUBLISH)
|
||||
accepted
|
||||
}
|
||||
|
||||
/** 新来源仅可在旧流程的完整安全边界入场,不在详情、编辑或回执中途切换。 */
|
||||
fun tryEnterSourceForeground(sourceId: String): ForegroundCoordinator.Ticket? {
|
||||
if (currentCrossRunGeneration() == null) return null
|
||||
|
||||
@@ -17,6 +17,7 @@ import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import com.haorui.app.automation.selection.DraftReceiptPolicy
|
||||
|
||||
/**
|
||||
* 视频发布状态机。
|
||||
@@ -43,6 +44,15 @@ class PublishMachine(
|
||||
/** 运行期注入真实配置(服务层配置流调用) */
|
||||
fun updateConfig(cfg: ToutiaoConfig) {
|
||||
this.toutiaoConfig = cfg
|
||||
if (phase == Phase.PAUSED && draftAttemptId == null && declaration != cfg.workDeclaration &&
|
||||
cfg.workDeclaration in com.haorui.app.data.model.AppConfig.DECLARATIONS) {
|
||||
declaration = cfg.workDeclaration
|
||||
declarationOpened = false
|
||||
declarationSelected = false
|
||||
declarationVerified = false
|
||||
declarationOptionRetry = 0
|
||||
go(Phase.PREPARE)
|
||||
}
|
||||
}
|
||||
|
||||
enum class Phase {
|
||||
@@ -64,6 +74,8 @@ class PublishMachine(
|
||||
DONE,
|
||||
/** 失败清理 */
|
||||
FAILED,
|
||||
/** 保留任务和素材,等待核对或修正不支持的声明。 */
|
||||
PAUSED,
|
||||
}
|
||||
|
||||
// ── 任务数据 ──────────────────────────────────────────────
|
||||
@@ -89,6 +101,10 @@ class PublishMachine(
|
||||
|
||||
/** 声明选项查找重试(对照原 500ms 轮询直到选项出现) */
|
||||
private var declarationOptionRetry = 0
|
||||
private var declarationOpened = false
|
||||
private var declarationSelected = false
|
||||
private var declarationVerified = false
|
||||
private var draftAttemptId: String? = null
|
||||
|
||||
/**
|
||||
* 提交一个发布任务。
|
||||
@@ -123,6 +139,10 @@ class PublishMachine(
|
||||
this.nullRootStreak = 0
|
||||
this.titleFocused = false
|
||||
this.declarationOptionRetry = 0
|
||||
this.declarationOpened = false
|
||||
this.declarationSelected = false
|
||||
this.declarationVerified = false
|
||||
this.draftAttemptId = null
|
||||
go(Phase.PREPARE)
|
||||
log("提交发布任务:${title.take(24)}…")
|
||||
return true
|
||||
@@ -193,9 +213,14 @@ class PublishMachine(
|
||||
Phase.WAIT_RECEIPT -> doWaitReceipt()
|
||||
Phase.DONE -> doDone()
|
||||
Phase.FAILED -> doFailed()
|
||||
Phase.PAUSED -> Unit
|
||||
}
|
||||
} catch (cancelled: kotlinx.coroutines.CancellationException) {
|
||||
withContext(NonCancellable) { runCatching { sharedSession?.markUnknown("发布步骤已取消,等待作品核对") } }
|
||||
if (draftAttemptId != null) {
|
||||
go(Phase.PAUSED)
|
||||
TaskStatusBus.status("草稿提交已中断,结果待核对,素材已保留")
|
||||
}
|
||||
throw cancelled
|
||||
} finally {
|
||||
busy.set(false)
|
||||
@@ -206,6 +231,10 @@ class PublishMachine(
|
||||
|
||||
private suspend fun doPrepare() {
|
||||
if (pauseForSharedAccount()) return
|
||||
if (declaration !in com.haorui.app.data.model.AppConfig.DECLARATIONS) {
|
||||
pauseForReview("作品声明「$declaration」不受当前版本支持,请在采集设置重新选择")
|
||||
return
|
||||
}
|
||||
if (title.isBlank() || mediaUri.isBlank()) {
|
||||
log("标题或素材为空,任务作废")
|
||||
go(Phase.FAILED)
|
||||
@@ -367,6 +396,8 @@ class PublishMachine(
|
||||
|
||||
val ok = svc.gestures.setText(titleBox, title)
|
||||
runCatching { titleBox.recycle() }
|
||||
|
||||
|
||||
if (!ok) {
|
||||
log("标题写入失败,重试 $titleRetry/3")
|
||||
titleRetry++
|
||||
@@ -488,124 +519,196 @@ class PublishMachine(
|
||||
log("退出子页面达最大层数,可能未回到发布页")
|
||||
}
|
||||
|
||||
/** 作品声明 */
|
||||
/** 只打开一次声明弹层;选项消失且编辑器回读一致后才能提交。 */
|
||||
private suspend fun doSetDeclaration() {
|
||||
if (!declarationOpened && dismissKeyboardIfVisible()) return
|
||||
val root = rootOrNull() ?: return
|
||||
val decl = NodeLocator.byText(root, ToutiaoSelectors.TXT_DECLARATION)
|
||||
if (decl == null) {
|
||||
// 对照原 C1:「未找到作品声明入口;未发布」—— 不带声明发布会合规风险
|
||||
log("未找到作品声明入口;未发布(对照原 C1)")
|
||||
TaskStatusBus.status("未找到作品声明入口;未发布")
|
||||
go(Phase.FAILED)
|
||||
return
|
||||
}
|
||||
svc.gestures.tapNode(decl)
|
||||
runCatching { decl.recycle() }
|
||||
TaskStatusBus.status("已打开作品声明,准备选择:$declaration")
|
||||
delay(700)
|
||||
|
||||
// 对照原:轮询等声明选项出现(u1(f0)),未出现 500ms 重试
|
||||
val opt = NodeLocator.byText(svc.root(), declaration)
|
||||
if (opt == null) {
|
||||
declarationOptionRetry++
|
||||
if (declarationOptionRetry < DECLARATION_OPTION_RETRY_LIMIT) {
|
||||
log("作品声明选项未出现,等待 $declarationOptionRetry/$DECLARATION_OPTION_RETRY_LIMIT")
|
||||
delay(500)
|
||||
try {
|
||||
if (declarationOpened && !declarationSheetOpen(root) && declarationReadback(root) == declaration) {
|
||||
declarationVerified = true
|
||||
log("作品声明回读通过:$declaration")
|
||||
go(Phase.CONFIRM)
|
||||
return
|
||||
}
|
||||
log("未找到作品声明选项「$declaration」(对照原等待超时仍进入下一步,由回读兜底)")
|
||||
declarationOptionRetry = 0
|
||||
go(Phase.CONFIRM)
|
||||
if (!declarationOpened) {
|
||||
val entry = NodeLocator.byText(root, ToutiaoSelectors.TXT_DECLARATION)
|
||||
if (entry == null) { pauseForReview("未找到作品声明入口,任务已暂停"); return }
|
||||
val opened = try { svc.gestures.tapNodeOnce(entry) } finally { entry.recycle() }
|
||||
if (!opened) { pauseForReview("作品声明入口点击结果不明,任务已暂停"); return }
|
||||
declarationOpened = true
|
||||
delay(500)
|
||||
}
|
||||
} finally { root.recycle() }
|
||||
val sheet = rootOrNull() ?: return
|
||||
val options = sheet.findAccessibilityNodeInfosByViewId("${com.haorui.app.automation.Targets.TOUTIAO_PKG}:id/fci").orEmpty()
|
||||
try {
|
||||
val option = options.firstOrNull { it.isVisibleToUser && it.text?.toString() == declaration }
|
||||
if (option != null && svc.gestures.tapNodeOnce(option)) declarationSelected = true
|
||||
if (++declarationOptionRetry >= DECLARATION_OPTION_RETRY_LIMIT) {
|
||||
pauseForReview("作品声明未能完成回读,任务已暂停,素材保留")
|
||||
}
|
||||
} finally { options.forEach { it.recycle() }; sheet.recycle() }
|
||||
}
|
||||
|
||||
private fun declarationReadback(root: AccessibilityNodeInfo): String? {
|
||||
val node = NodeLocator.byId(root, "${com.haorui.app.automation.Targets.TOUTIAO_PKG}:id/jm2")
|
||||
val summary = try { node?.text?.toString() } finally { node?.recycle() }
|
||||
return DraftReceiptPolicy.declarationReadback(declaration, declarationSelected, declarationSheetOpen(root), summary)
|
||||
}
|
||||
|
||||
private suspend fun dismissKeyboardIfVisible(): Boolean {
|
||||
if (svc.currentPackage() != com.haorui.app.automation.Targets.TOUTIAO_PKG) return false
|
||||
val visible = svc.windows.any { window ->
|
||||
window.type == android.view.accessibility.AccessibilityWindowInfo.TYPE_INPUT_METHOD &&
|
||||
!android.graphics.Rect().also(window::getBoundsInScreen).isEmpty
|
||||
}
|
||||
if (!visible) return false
|
||||
svc.gestures.back()
|
||||
delay(300)
|
||||
log("已收起标题输入键盘,等待编辑器布局稳定")
|
||||
return true
|
||||
}
|
||||
|
||||
private fun declarationSheetOpen(root: AccessibilityNodeInfo): Boolean {
|
||||
val nodes = root.findAccessibilityNodeInfosByViewId("${com.haorui.app.automation.Targets.TOUTIAO_PKG}:id/fci").orEmpty()
|
||||
return try { nodes.any { it.isVisibleToUser && it.text?.toString() == "取消" } } finally { nodes.forEach { it.recycle() } }
|
||||
}
|
||||
|
||||
private fun pauseForReview(reason: String) {
|
||||
log(reason)
|
||||
TaskStatusBus.status(reason)
|
||||
go(Phase.PAUSED)
|
||||
svc.stopAutomation()
|
||||
}
|
||||
|
||||
private fun draftEditorMatches(root: AccessibilityNodeInfo): Boolean {
|
||||
if (root.packageName?.toString() != com.haorui.app.automation.Targets.TOUTIAO_PKG || declarationSheetOpen(root)) return false
|
||||
val node = NodeLocator.byId(root, ToutiaoSelectors.ID_PUB_TITLE) ?: return false
|
||||
val matches = try { node.text?.toString() == title } finally { node.recycle() }
|
||||
return matches && declarationReadback(root) == declaration
|
||||
}
|
||||
|
||||
private suspend fun draftReceiptLines(): List<String> {
|
||||
com.haorui.app.overlay.MonitorOverlay.setHidden(true)
|
||||
return try {
|
||||
delay(200)
|
||||
val bitmap = com.haorui.app.ocr.ScreenCapturer(svc).capture() ?: return emptyList()
|
||||
try {
|
||||
val lines = com.haorui.app.ocr.OcrProcessor.recognize(bitmap).flatMap { it.lines }.filter { line ->
|
||||
val box = line.boundingBox
|
||||
box != null && box.centerY() > bitmap.height * 0.35 && box.centerY() < bitmap.height * 0.85 &&
|
||||
box.centerX() > bitmap.width * 0.2 && box.centerX() < bitmap.width * 0.8
|
||||
}.map { it.text }
|
||||
kotlinx.coroutines.currentCoroutineContext().ensureActive()
|
||||
lines.filter { it.contains("保存") && it.contains("草稿") }.forEach { log("草稿回执候选:${it.take(40)}") }
|
||||
lines
|
||||
} finally { bitmap.recycle() }
|
||||
} finally { com.haorui.app.overlay.MonitorOverlay.setHidden(false) }
|
||||
}
|
||||
|
||||
private suspend fun dispatchDraft() {
|
||||
if (draftAttemptId != null) { pauseForReview("草稿已有提交意图,禁止重复点击,等待核对"); return }
|
||||
if (DraftReceiptPolicy.hasSuccess(draftReceiptLines())) {
|
||||
if (++confirmRetry > CONFIRM_MAX_RETRY) pauseForReview("旧草稿提示尚未消失,未发送新草稿")
|
||||
return
|
||||
}
|
||||
declarationOptionRetry = 0
|
||||
val tapped = svc.gestures.tapNode(opt)
|
||||
runCatching { opt.recycle() }
|
||||
if (tapped) {
|
||||
TaskStatusBus.status("已选择作品声明:$declaration;等待回读")
|
||||
log("作品声明已设为「$declaration」")
|
||||
} else {
|
||||
log("作品声明选项 tap 失败,重试一次")
|
||||
val opt2 = NodeLocator.byText(svc.root(), declaration)
|
||||
if (opt2 != null) {
|
||||
svc.gestures.tapNode(opt2)
|
||||
runCatching { opt2.recycle() }
|
||||
TaskStatusBus.status("已选择作品声明:$declaration;等待回读")
|
||||
}
|
||||
}
|
||||
go(Phase.CONFIRM)
|
||||
val fresh = rootOrNull() ?: return
|
||||
try {
|
||||
if (!declarationVerified || !draftEditorMatches(fresh)) { pauseForReview("草稿标题或声明已变化,未发送"); return }
|
||||
val button = NodeLocator.byId(fresh, ToutiaoSelectors.ID_PUB_DRAFT) ?: return
|
||||
try {
|
||||
val id = try { videoDownloader?.beginDraft(mediaUri, title, declaration) }
|
||||
catch (failure: Exception) { log("草稿意图保存失败:${failure.javaClass.simpleName}"); null }
|
||||
if (id == null) { pauseForReview("草稿意图无法保存,未点击存草稿"); return }
|
||||
draftAttemptId = id
|
||||
receiptWaitStartMs = SystemClock.elapsedRealtime()
|
||||
kotlinx.coroutines.currentCoroutineContext().ensureActive()
|
||||
if (!svc.gestures.tapNodeOnce(button)) { pauseForReview("草稿点击结果不明,素材保留,等待核对"); return }
|
||||
go(Phase.WAIT_RECEIPT)
|
||||
TaskStatusBus.status("草稿动作已发送,等待当前编辑器的保存成功提示")
|
||||
} finally { button.recycle() }
|
||||
} finally { fresh.recycle() }
|
||||
}
|
||||
|
||||
/** 点发布 / 存草稿 */
|
||||
private suspend fun doConfirm() {
|
||||
if (pauseForSharedAccount()) return
|
||||
if (dismissKeyboardIfVisible()) return
|
||||
val root = rootOrNull() ?: return
|
||||
eligibilityCheck?.invoke()?.let { reason ->
|
||||
log("点击发布前筛选拒绝:$reason")
|
||||
TaskStatusBus.status("发布前复查跳过:$reason")
|
||||
go(Phase.FAILED)
|
||||
return
|
||||
}
|
||||
|
||||
// 兜底:若此刻不在发布页(可能被子页面/异步跳转带走),先退回
|
||||
val titleBox = NodeLocator.byId(root, ToutiaoSelectors.ID_PUB_TITLE)
|
||||
if (titleBox == null) {
|
||||
log("当前不在发布页,尝试退回")
|
||||
ensureBackToPublisher()
|
||||
return
|
||||
}
|
||||
runCatching { titleBox.recycle() }
|
||||
|
||||
val btnId = if (autoPublish) ToutiaoSelectors.ID_PUB_PUBLISH else ToutiaoSelectors.ID_PUB_DRAFT
|
||||
val btn = NodeLocator.byId(root, btnId)
|
||||
?: NodeLocator.byText(root, if (autoPublish) "发布" else "存草稿")
|
||||
|
||||
if (btn == null) {
|
||||
confirmRetry++
|
||||
// 需要真实结构才能校正选择器
|
||||
if (confirmRetry == 1) {
|
||||
log("CONFIRM 节点树诊断 →\n${NodeLocator.dumpTree(root, maxDepth = 12, maxNodes = 150)}")
|
||||
}
|
||||
// ⚠️ 加重试上限:原先无限 delay(800) 重试,真机实测空转 24 次,
|
||||
// 既不放弃也不上报,白白占住状态机。
|
||||
if (confirmRetry > CONFIRM_MAX_RETRY) {
|
||||
log("未找到${if (autoPublish) "发布" else "存草稿"}按钮,重试 $confirmRetry 次后放弃")
|
||||
try {
|
||||
eligibilityCheck?.invoke()?.let { reason ->
|
||||
log("点击发布前筛选拒绝:$reason")
|
||||
TaskStatusBus.status("发布前复查跳过:$reason")
|
||||
go(Phase.FAILED)
|
||||
return
|
||||
}
|
||||
log("未找到${if (autoPublish) "发布" else "存草稿"}按钮,重试 $confirmRetry/$CONFIRM_MAX_RETRY")
|
||||
delay(800)
|
||||
return
|
||||
}
|
||||
val context = sharedSession
|
||||
val tapped = if (context != null) {
|
||||
val titleNode = NodeLocator.byId(root, ToutiaoSelectors.ID_PUB_TITLE)
|
||||
val exactTitle = titleNode?.text?.toString() == title
|
||||
titleNode?.recycle()
|
||||
context.dispatch(payloadFingerprint(), { exactTitle && svc.currentCrossRunGeneration() == context.generation }) {
|
||||
svc.gestures.tapNodeOnce(btn)
|
||||
|
||||
// 兜底:若此刻不在发布页(可能被子页面/异步跳转带走),先退回
|
||||
val titleBox = NodeLocator.byId(root, ToutiaoSelectors.ID_PUB_TITLE)
|
||||
if (titleBox == null) {
|
||||
log("当前不在发布页,尝试退回")
|
||||
ensureBackToPublisher()
|
||||
return
|
||||
}
|
||||
} else svc.gestures.tapNode(btn)
|
||||
runCatching { btn.recycle() }
|
||||
if (context != null && !tapped) {
|
||||
TaskStatusBus.status(context.reason)
|
||||
go(Phase.FAILED)
|
||||
return
|
||||
}
|
||||
// ⚠️ 二轮审计:tap 失败不能进 WAIT_RECEIPT 干等 30 分钟超时
|
||||
if (!tapped) {
|
||||
log("发布按钮 tap 失败,重试")
|
||||
confirmRetry++
|
||||
if (confirmRetry > CONFIRM_MAX_RETRY) {
|
||||
go(Phase.FAILED)
|
||||
} else {
|
||||
runCatching { titleBox.recycle() }
|
||||
|
||||
if (!declarationVerified || declarationSheetOpen(root) || declarationReadback(root) != declaration) {
|
||||
pauseForReview("作品声明未通过回读,未发送提交动作")
|
||||
return
|
||||
}
|
||||
if (!autoPublish) { dispatchDraft(); return }
|
||||
|
||||
val btnId = if (autoPublish) ToutiaoSelectors.ID_PUB_PUBLISH else ToutiaoSelectors.ID_PUB_DRAFT
|
||||
val btn = NodeLocator.byId(root, btnId)
|
||||
?: NodeLocator.byText(root, if (autoPublish) "发布" else "存草稿")
|
||||
|
||||
if (btn == null) {
|
||||
confirmRetry++
|
||||
// 需要真实结构才能校正选择器
|
||||
if (confirmRetry == 1) {
|
||||
log("CONFIRM 节点树诊断 →\n${NodeLocator.dumpTree(root, maxDepth = 12, maxNodes = 150)}")
|
||||
}
|
||||
// ⚠️ 加重试上限:原先无限 delay(800) 重试,真机实测空转 24 次,
|
||||
// 既不放弃也不上报,白白占住状态机。
|
||||
if (confirmRetry > CONFIRM_MAX_RETRY) {
|
||||
log("未找到${if (autoPublish) "发布" else "存草稿"}按钮,重试 $confirmRetry 次后放弃")
|
||||
go(Phase.FAILED)
|
||||
return
|
||||
}
|
||||
log("未找到${if (autoPublish) "发布" else "存草稿"}按钮,重试 $confirmRetry/$CONFIRM_MAX_RETRY")
|
||||
delay(800)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
receiptWaitStartMs = SystemClock.elapsedRealtime()
|
||||
TaskStatusBus.status("发布动作已发送,等待头条成功回执;确认后才删除素材")
|
||||
go(Phase.WAIT_RECEIPT)
|
||||
val context = sharedSession
|
||||
val tapped = if (context != null) {
|
||||
val titleNode = NodeLocator.byId(root, ToutiaoSelectors.ID_PUB_TITLE)
|
||||
val exactTitle = titleNode?.text?.toString() == title
|
||||
titleNode?.recycle()
|
||||
context.dispatch(payloadFingerprint(), { exactTitle && svc.currentCrossRunGeneration() == context.generation }) {
|
||||
svc.gestures.tapNodeOnce(btn)
|
||||
}
|
||||
} else svc.gestures.tapNode(btn)
|
||||
runCatching { btn.recycle() }
|
||||
if (context != null && !tapped) {
|
||||
TaskStatusBus.status(context.reason)
|
||||
go(Phase.FAILED)
|
||||
return
|
||||
}
|
||||
// ⚠️ 二轮审计:tap 失败不能进 WAIT_RECEIPT 干等 30 分钟超时
|
||||
if (!tapped) {
|
||||
log("发布按钮 tap 失败,重试")
|
||||
confirmRetry++
|
||||
if (confirmRetry > CONFIRM_MAX_RETRY) {
|
||||
go(Phase.FAILED)
|
||||
} else {
|
||||
delay(800)
|
||||
}
|
||||
return
|
||||
}
|
||||
receiptWaitStartMs = SystemClock.elapsedRealtime()
|
||||
TaskStatusBus.status("发布动作已发送,等待头条成功回执;确认后才删除素材")
|
||||
go(Phase.WAIT_RECEIPT)
|
||||
} finally { root.recycle() }
|
||||
}
|
||||
|
||||
private fun pauseForSharedAccount(): Boolean {
|
||||
@@ -617,6 +720,25 @@ class PublishMachine(
|
||||
|
||||
/** 等回执(发布成功 / 发布失败 / 已发布)—— 未确认回执不计数 */
|
||||
private suspend fun doWaitReceipt() {
|
||||
if (!autoPublish) {
|
||||
val root = rootOrNull() ?: return
|
||||
val matches = try { draftEditorMatches(root) } finally { root.recycle() }
|
||||
val lines = if (matches) draftReceiptLines() else emptyList()
|
||||
val fresh = rootOrNull() ?: return
|
||||
val confirmed = try {
|
||||
val titleNode = NodeLocator.byId(fresh, ToutiaoSelectors.ID_PUB_TITLE)
|
||||
val actualTitle = try { titleNode?.text?.toString() } finally { titleNode?.recycle() }
|
||||
matches && draftEditorMatches(fresh) && DraftReceiptPolicy.confirms(title, actualTitle,
|
||||
declaration, declarationReadback(fresh), lines, SystemClock.elapsedRealtime() - receiptWaitStartMs)
|
||||
} finally { fresh.recycle() }
|
||||
if (confirmed) {
|
||||
log("当前标题和声明匹配,收到明确的保存草稿成功提示")
|
||||
go(Phase.DONE)
|
||||
} else if (SystemClock.elapsedRealtime() - receiptWaitStartMs > DRAFT_RECEIPT_TIMEOUT_MS) {
|
||||
pauseForReview("草稿未收到明确保存回执,结果待核对,素材已保留")
|
||||
}
|
||||
return
|
||||
}
|
||||
sharedSession?.let { context ->
|
||||
// M6 作品核对器尚未接通。共享尝试不能进入旧的分享面板/超时成功判定。
|
||||
context.markUnknown("发布动作已派发,等待明确作品回执")
|
||||
@@ -634,7 +756,6 @@ class PublishMachine(
|
||||
// 「发布成功」单条即成功;
|
||||
// 「已发布」必须**同时**看到标题节点(防 feed 里"已发布"字样误判)。
|
||||
val publishOk = NodeLocator.byTextContains(root, ToutiaoSelectors.TXT_PUBLISH_OK)
|
||||
?: if (!autoPublish) NodeLocator.byTextContains(root, "草稿") else null
|
||||
// 兜底:发布成功后头条会自动弹「分享至」面板(引导分享),可作成功信号
|
||||
?: NodeLocator.byTextContains(root, ToutiaoSelectors.TXT_SHARE_TO)
|
||||
if (publishOk != null) {
|
||||
@@ -664,13 +785,6 @@ class PublishMachine(
|
||||
}
|
||||
|
||||
val waited = SystemClock.elapsedRealtime() - receiptWaitStartMs
|
||||
// ⚠️ 草稿模式:存草稿通常**没有成功提示**,不宜按 30 分钟等回执。
|
||||
// 短时间内没检测到失败提示即视为成功,避免状态机长期卡死。
|
||||
if (!autoPublish && waited > DRAFT_RECEIPT_TIMEOUT_MS) {
|
||||
log("草稿模式:${waited / 1000}s 未见失败提示,视为保存成功")
|
||||
go(Phase.DONE)
|
||||
return
|
||||
}
|
||||
|
||||
// 超时判定(原 publish_timeout 默认 30 分钟)
|
||||
if (waited > RECEIPT_TIMEOUT_MS) {
|
||||
@@ -706,6 +820,10 @@ class PublishMachine(
|
||||
svc.stopAutomation()
|
||||
return
|
||||
}
|
||||
if (!autoPublish && (draftAttemptId == null || videoDownloader?.confirmDraft(draftAttemptId!!) != true)) {
|
||||
pauseForReview("草稿回执日志未能确认,素材继续保留")
|
||||
return
|
||||
}
|
||||
// 对照原 m2():BACK 退出发布页 → 删除本地素材 → 进度计数 → 启动休息
|
||||
log("收到成功回执,开始收尾(删素材 + 计数 + 休息)")
|
||||
svc.gestures.back() // performGlobalAction(BACK) 退出发布页
|
||||
@@ -721,13 +839,15 @@ class PublishMachine(
|
||||
}
|
||||
quotaManager?.recordPublish()
|
||||
// 对照原 m2() 的两行输出:过程日志 + 监控窗"进度 X/Y"
|
||||
log("发布成功;" + (if (deleted) "本地素材已删除" else "本地素材记录已清理"))
|
||||
TaskStatusBus.status("发布成功,已清理本地素材;进度 ${quotaManager?.dailyProgress ?: "0/0"}")
|
||||
val outcome = if (autoPublish) "发布成功" else "草稿保存已确认"
|
||||
log("$outcome;" + (if (deleted) "本地素材已删除" else "本地素材记录已清理"))
|
||||
TaskStatusBus.status("$outcome,已清理本地素材;处理进度 ${quotaManager?.dailyProgress ?: "0/0"}")
|
||||
// 启动休息倒计时 + 休息浏览(对照原 X2("发布完成"))
|
||||
restBrowse?.startRest("发布完成")
|
||||
restBrowse?.startRest(if (autoPublish) "发布完成" else "草稿已保存")
|
||||
title = ""
|
||||
mediaUri = ""
|
||||
eligibilityCheck = null
|
||||
draftAttemptId = null
|
||||
reset()
|
||||
}
|
||||
|
||||
@@ -802,7 +922,7 @@ class PublishMachine(
|
||||
/** 发布页自动重开上限(对照原 f1289n0 ≤2) */
|
||||
private const val PUBLISH_REOPEN_LIMIT = 2
|
||||
|
||||
/** 草稿模式回执等待上限:存草稿通常无成功提示,短等即判成功 */
|
||||
/** 草稿回执等待上限:超时进入待核对,不能视为保存成功 */
|
||||
private const val DRAFT_RECEIPT_TIMEOUT_MS = 8L * 1000L
|
||||
|
||||
/** 声明选项等待重试上限(对照原 500ms 轮询) */
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.haorui.app.automation.selection
|
||||
|
||||
/** 已观察到的 18.3.0 草稿回执;“存草稿”按钮、分享弹层和超时都不是成功。 */
|
||||
object DraftReceiptPolicy {
|
||||
const val SUCCESS = "保存草稿成功"
|
||||
private const val MARKERS = "✓✔√☑✅○〇◎●0oOQC©"
|
||||
private val cleanReceipt = Regex("[$MARKERS]?保存草稿成功[!!。]?")
|
||||
|
||||
/**
|
||||
* 真机实测:回执是“⊙ 图标 + 保存草稿成功”胶囊,OCR 会把它与同屏位置卡片文本合并成一行,
|
||||
* 且 ⊙ 图标被误读为 0/O/。 等非汉字字符(“0保存草稿成功”“宁兴·城O保存草稿成功鄞州万达广场小”
|
||||
* “城市广场。保存草稿成功达广场IMAX店”)。判定:
|
||||
* 1. 整行即回执签名(含空格与图标误读容错);
|
||||
* 2. 或行内“保存草稿成功”紧邻的前一字符不是汉字——否定句(“未能…”“出现…后返回”)以汉字承接,仍被拒绝。
|
||||
*/
|
||||
fun hasSuccess(lines: List<String>): Boolean = lines.any { raw ->
|
||||
val line = raw.filterNot(Char::isWhitespace)
|
||||
if (cleanReceipt.matches(line)) return@any true
|
||||
val index = line.indexOf(SUCCESS)
|
||||
index > 0 && line[index - 1].code !in 0x4E00..0x9FFF
|
||||
}
|
||||
|
||||
fun declarationReadback(expected: String, selected: Boolean, sheetOpen: Boolean, summary: String?): String? {
|
||||
if (!selected || sheetOpen) return null
|
||||
return summary?.takeIf { it.isNotBlank() } ?: expected.takeIf { it == "内容无需标注" }
|
||||
}
|
||||
|
||||
fun confirms(expectedTitle: String, actualTitle: String?, expectedDeclaration: String, actualDeclaration: String?,
|
||||
receiptLines: List<String>, elapsedMs: Long): Boolean =
|
||||
expectedTitle.isNotBlank() && actualTitle == expectedTitle && actualDeclaration == expectedDeclaration &&
|
||||
elapsedMs in 0..8_000 && hasSuccess(receiptLines)
|
||||
}
|
||||
@@ -179,6 +179,7 @@ object CreditGateRunner {
|
||||
service: HaoRuiAccessibilityService,
|
||||
region: Rect?,
|
||||
): Int? {
|
||||
if (!service.checkVersionGate()) return null
|
||||
val ticket = service.tryEnterCreditForeground() ?: return null
|
||||
service.frontGuard.creditNavigating = true
|
||||
try {
|
||||
@@ -186,7 +187,8 @@ object CreditGateRunner {
|
||||
if (!service.foregroundCoordinator.isCurrent(ticket)) return@withOverlayHidden null
|
||||
val capturer = ScreenCapturer(service)
|
||||
// 快路径:当前屏已是信用分页(重复检查/误入时省导航)
|
||||
var score = CreditScoreReader.readFromScreen(capturer, region)
|
||||
var score = if (service.currentPackage() == Targets.TOUTIAO_PKG) CreditScoreReader.readFromScreen(capturer, region) else null
|
||||
if (!service.foregroundCoordinator.isCurrent(ticket)) return@withOverlayHidden null
|
||||
if (score == null) {
|
||||
RunLogger.i(TAG, "当前屏未识别到信用分,导航至信用分页(我的→创作中心→全部服务→处罚中心)")
|
||||
if (navigateToCreditPage(service, ticket)) {
|
||||
@@ -195,7 +197,7 @@ object CreditGateRunner {
|
||||
RunLogger.w(TAG, "信用分页导航失败(页面改版或定位失败),按 fail-open 放行")
|
||||
}
|
||||
}
|
||||
score
|
||||
if (service.foregroundCoordinator.isCurrent(ticket) && service.currentPackage() == Targets.TOUTIAO_PKG) score else null
|
||||
}
|
||||
} finally {
|
||||
service.frontGuard.creditNavigating = false
|
||||
@@ -255,9 +257,11 @@ object CreditGateRunner {
|
||||
}
|
||||
// ① 树定位(原生页有 text/desc 节点)
|
||||
val root = service.root()
|
||||
val node = root?.let {
|
||||
NodeLocator.byText(it, label) ?: NodeLocator.byTextContains(it, label)
|
||||
}
|
||||
val node = try {
|
||||
root?.takeIf { it.packageName?.toString() == Targets.TOUTIAO_PKG }?.let {
|
||||
NodeLocator.byText(it, label) ?: NodeLocator.byTextContains(it, label)
|
||||
}
|
||||
} finally { root?.recycle() }
|
||||
if (node != null) {
|
||||
if (!service.foregroundCoordinator.isCurrent(ticket)) {
|
||||
node.recycle()
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.haorui.app.ocr
|
||||
|
||||
/** 18.3.0 处罚中心的信用分卡片;仅接收已核对页面和列位置中的完整分数字样。 */
|
||||
object CreditScoreParser {
|
||||
data class Area(val left: Int, val top: Int, val right: Int, val bottom: Int) {
|
||||
val centerX get() = left / 2.0 + right / 2.0
|
||||
val centerY get() = top / 2.0 + bottom / 2.0
|
||||
fun valid(width: Int, height: Int) = left >= 0 && top >= 0 && right > left && bottom > top && right <= width && bottom <= height
|
||||
fun contains(other: Area) = other.left >= left && other.top >= top && other.right <= right && other.bottom <= bottom
|
||||
}
|
||||
data class Line(val text: String, val bounds: Area)
|
||||
|
||||
private val labelPattern = Regex("信用(?:分|评分)(?:[::]?([0-9Oo]{1,3})分?)?")
|
||||
private val valuePattern = Regex("([0-9Oo]{1,3})分?")
|
||||
|
||||
fun extract(lines: List<Line>, width: Int, height: Int, scoreRegion: Area? = null): Int? {
|
||||
if (width <= 0 || height <= 0 || scoreRegion != null && !scoreRegion.valid(width, height)) return null
|
||||
val visible = lines.filter { it.bounds.valid(width, height) }.map { it.copy(text = normalize(it.text)) }
|
||||
val title = visible.singleOrNull { it.text == "账号处罚中心" && it.bounds.centerY < height * 0.15 } ?: return null
|
||||
val label = visible.singleOrNull {
|
||||
labelPattern.matches(it.text) && it.bounds.top > title.bounds.bottom && it.bounds.bottom < height * 0.45
|
||||
} ?: return null
|
||||
val status = visible.singleOrNull {
|
||||
it.text == "账号状态" && it.bounds.left > label.bounds.right &&
|
||||
kotlin.math.abs(it.bounds.centerY - label.bounds.centerY) < height * 0.035
|
||||
} ?: return null
|
||||
|
||||
val candidates = visible.filter { line ->
|
||||
line.bounds.centerX >= label.bounds.left - width * 0.03 && line.bounds.right < status.bounds.left &&
|
||||
line.bounds.centerY >= label.bounds.centerY && line.bounds.bottom <= label.bounds.bottom + height * 0.06 &&
|
||||
(scoreRegion == null || scoreRegion.contains(line.bounds))
|
||||
}
|
||||
val values = mutableSetOf<Int>()
|
||||
for (line in candidates) {
|
||||
val match = if (line == label) labelPattern.matchEntire(line.text) else valuePattern.matchEntire(line.text)
|
||||
val raw = match?.groupValues?.get(1)?.takeIf { it.isNotEmpty() } ?: continue
|
||||
val value = raw.replace('O', '0').replace('o', '0').toIntOrNull() ?: return null
|
||||
if (value !in 0..100) return null
|
||||
values += value
|
||||
}
|
||||
return values.singleOrNull()
|
||||
}
|
||||
|
||||
private fun normalize(text: String): String = buildString {
|
||||
for (char in text) {
|
||||
if (char.isWhitespace() || Character.isSpaceChar(char)) continue
|
||||
append(if (char in '0'..'9') (char.code - 0xFEE0).toChar() else char)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,145 +1,31 @@
|
||||
package com.haorui.app.ocr
|
||||
|
||||
import android.graphics.Rect
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import com.haorui.app.automation.RunLogger
|
||||
|
||||
/**
|
||||
* 信用分 OCR 文本解析。约束分数范围与匹配上下文,避免把播放时长等无关数字当作信用分。
|
||||
*/
|
||||
/** 读取完整页面的 OCR 行与位置;限定信用分卡片,不记录账户页面全文。 */
|
||||
object CreditScoreReader {
|
||||
|
||||
private const val TAG = "HaoRui-Credit"
|
||||
|
||||
/**
|
||||
* 严格正则(对照原 `CreditScoreParser.f308a` + **matches() 整串语义**):
|
||||
* 整个字符串必须是 `信用分 100` / `100分` / `100` 形,不能从长文里 find。
|
||||
* ⚠️ 2026-10-31 长测实测:原 find() + 「前缀/后缀都可选」会把 **时钟「11:59」**
|
||||
* 的 11 当成信用分,误判 BLOCKED 锁死当天任务。对齐原 matches()。
|
||||
*/
|
||||
private val SCORE_WHOLE = Regex(
|
||||
"""(?:(?:信\s*用\s*分(?:\s*数)?|信\s*用\s*评\s*分)\s*[::]?\s*)?([0-9]{1,3})\s*分?""",
|
||||
)
|
||||
|
||||
/** 宽松正则(对照原 `CreditScoreParser.b`):**必须带「分」**,且处理 O/o 混淆 */
|
||||
private val LOOSE_PATTERN = Regex("""(?<![0-9Oo])([0-9Oo]{1,3})\s*分(?![0-9])""")
|
||||
|
||||
/** 信用分有效范围 */
|
||||
const val MIN_CREDIT = 0
|
||||
const val MAX_CREDIT = 100
|
||||
|
||||
/**
|
||||
* 归一化 OCR 文本(对照原 `CreditScoreParser.extractScoreText` + `b()`):
|
||||
* 全角数字/冒号转半角、去空白、O/o→0。
|
||||
*/
|
||||
private fun normalize(raw: String): String {
|
||||
val sb = StringBuilder(raw.length)
|
||||
var lastWasSpace = false
|
||||
for (ch in raw) {
|
||||
if (Character.isWhitespace(ch) || Character.isSpaceChar(ch)) {
|
||||
if (sb.isNotEmpty()) lastWasSpace = true
|
||||
continue
|
||||
}
|
||||
if (lastWasSpace && sb.isNotEmpty()) sb.append(' ')
|
||||
lastWasSpace = false
|
||||
// 全角数字 0-9 → 半角
|
||||
val c = if (ch in '0'..'9') (ch.code - 0xFEE0).toChar() else ch
|
||||
// 全角冒号/斜杠 → 半角(时长解析用)
|
||||
val c2 = when (c) {
|
||||
':' -> ':'
|
||||
'/' -> '/'
|
||||
else -> c
|
||||
}
|
||||
sb.append(c2)
|
||||
}
|
||||
return sb.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 OCR 文本提取信用分(对照原 `CreditScoreParser.parseScore` / `parseScoreLoose`)。
|
||||
*
|
||||
* 否决链(任一命中返回 null):
|
||||
* 1. 含「扣分/已扣/处罚」
|
||||
* 2. 含负分 `…-N 分…`
|
||||
* 3. 含加分 `…+N 分…`
|
||||
* 4. 多个**不同**数值冲突
|
||||
* 5. 超出 0~100
|
||||
*
|
||||
* 匹配语义(⚠️ 2026-10-31 长测实测必须收紧):
|
||||
* - 严格通道:**整行** matches(原 f308a + matches()),不能从长文 find
|
||||
* - 宽松通道:**必须带「分」**(原 b),否则「11:59」的 11 会误命中
|
||||
*
|
||||
* @param ocrText OCR 识别出的全文
|
||||
* @return 信用分(0~100),未识别/被否决返回 null
|
||||
*/
|
||||
fun extractCreditScore(ocrText: String): Int? {
|
||||
val text = normalize(ocrText)
|
||||
if (text.isEmpty()) return null
|
||||
|
||||
// ── 否决:扣分/处罚/加减分(对照原 parseScore 顶部 if)──
|
||||
val flat = text.replace(" ", "")
|
||||
if (flat.contains("扣分") || flat.contains("已扣") || flat.contains("处罚")) {
|
||||
RunLogger.w(TAG, "OCR 含扣分/处罚字样,否决信用分识别")
|
||||
return null
|
||||
}
|
||||
if (Regex("""[+\+]\s*[0-9Oo]{1,3}\s*分?""").containsMatchIn(flat) ||
|
||||
Regex("""[\--−–—]\s*[0-9Oo]{1,3}\s*分?""").containsMatchIn(flat)
|
||||
) {
|
||||
RunLogger.w(TAG, "OCR 含加减分字样,否决信用分识别")
|
||||
return null
|
||||
}
|
||||
|
||||
// ── 宽松通道:必须带「分」的 token(对照原 parseScoreLoose)──
|
||||
val found = LinkedHashSet<Int>()
|
||||
for (m in LOOSE_PATTERN.findAll(text)) {
|
||||
val v = m.groupValues[1].replace('O', '0').replace('o', '0').toIntOrNull()
|
||||
?: continue
|
||||
if (v in MIN_CREDIT..MAX_CREDIT) found.add(v)
|
||||
}
|
||||
if (found.size > 1) {
|
||||
RunLogger.w(TAG, "OCR 多值冲突 $found,否决信用分识别")
|
||||
return null
|
||||
}
|
||||
if (found.size == 1) {
|
||||
val score = found.first()
|
||||
RunLogger.i(TAG, "识别到信用分: $score(宽松通道)")
|
||||
return score
|
||||
}
|
||||
|
||||
// ── 严格通道:整行 matches(原 f308a + matcher.matches())──
|
||||
// 只在**单行本身就是分数形**时才认,绝不从长文里抠数字
|
||||
for (rawLine in text.split('\n', '|')) {
|
||||
val line = rawLine.trim()
|
||||
if (line.isEmpty()) continue
|
||||
val m = SCORE_WHOLE.matchEntire(line) ?: continue
|
||||
val v = m.groupValues[1].toIntOrNull() ?: continue
|
||||
if (v in MIN_CREDIT..MAX_CREDIT) {
|
||||
RunLogger.i(TAG, "识别到信用分: $v(严格整行)")
|
||||
return v
|
||||
}
|
||||
}
|
||||
RunLogger.w(TAG, "未能从 OCR 文本识别信用分")
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 从截图识别信用分。
|
||||
* @param capturer 截图器
|
||||
* @param region 信用分所在区域(屏幕坐标,null = 全屏搜索)
|
||||
* @return 信用分
|
||||
*/
|
||||
suspend fun readFromScreen(capturer: ScreenCapturer, region: Rect? = null): Int? {
|
||||
val text = capturer.captureAndRecognize(region)
|
||||
// 观测点(装机实测):区分「截屏失败(空文本)」与「截到但正则不中」两种死因
|
||||
if (text.isBlank()) {
|
||||
RunLogger.w(TAG, "OCR 文本为空(截屏失败或无文字内容)")
|
||||
} else {
|
||||
// 校准用:打全文(换行压平),真机正则校准需看完整识别结果
|
||||
RunLogger.i(TAG, "OCR 全文(${text.length} 字)=${text.replace('\n', '|')}")
|
||||
}
|
||||
return extractCreditScore(text)
|
||||
val bitmap = capturer.capture() ?: return null
|
||||
return try {
|
||||
val lines = OcrProcessor.recognize(bitmap).flatMap { block ->
|
||||
block.lines.mapNotNull { line ->
|
||||
val box = line.boundingBox ?: return@mapNotNull null
|
||||
CreditScoreParser.Line(line.text, CreditScoreParser.Area(box.left, box.top, box.right, box.bottom))
|
||||
}
|
||||
}
|
||||
kotlinx.coroutines.currentCoroutineContext().ensureActive()
|
||||
val area = region?.let { CreditScoreParser.Area(it.left, it.top, it.right, it.bottom) }
|
||||
val score = CreditScoreParser.extract(lines, bitmap.width, bitmap.height, area)
|
||||
if (score == null) RunLogger.w(TAG, "未能核对处罚中心信用分卡片(OCR 行数=${lines.size})")
|
||||
else RunLogger.i(TAG, "已核对处罚中心信用分:$score")
|
||||
score
|
||||
} finally { bitmap.recycle() }
|
||||
}
|
||||
}
|
||||
|
||||
object EarningsReader {
|
||||
|
||||
private const val TAG = "HaoRui-Earnings"
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.haorui.app.pipeline
|
||||
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.util.UUID
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.decodeFromString
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
/** 草稿点击前落盘;未得到当前编辑器的明确回执前,缓存清理和失败分支不得删除素材。 */
|
||||
class PendingDraftStore(private val directory: File) {
|
||||
@Serializable
|
||||
data class Attempt(val id: String, val mediaPath: String, val title: String, val declaration: String, val createdAtMs: Long)
|
||||
|
||||
@Synchronized fun begin(mediaPath: String, title: String, declaration: String): Attempt {
|
||||
require(title.isNotBlank() && declaration.isNotBlank())
|
||||
val path = File(mediaPath).canonicalPath
|
||||
require(File(path).isFile)
|
||||
check(attempts().none { it.mediaPath == path }) { "该素材已有待核对草稿" }
|
||||
check(directory.isDirectory || directory.mkdirs())
|
||||
val attempt = Attempt(UUID.randomUUID().toString(), path, title, declaration, System.currentTimeMillis())
|
||||
val temporary = File(directory, "${attempt.id}.tmp")
|
||||
try {
|
||||
FileOutputStream(temporary).use { output ->
|
||||
output.write(Json.encodeToString(attempt).toByteArray(Charsets.UTF_8))
|
||||
output.fd.sync()
|
||||
}
|
||||
check(temporary.renameTo(File(directory, "${attempt.id}.json"))) { "草稿日志保存失败" }
|
||||
} finally { temporary.delete() }
|
||||
return attempt
|
||||
}
|
||||
|
||||
@Synchronized fun attempts(): List<Attempt> {
|
||||
if (!directory.exists()) return emptyList()
|
||||
val files = checkNotNull(directory.listFiles()) { "草稿日志不可读" }
|
||||
return files.filter { it.extension == "json" }.map { file ->
|
||||
Json.decodeFromString<Attempt>(file.readText()).also { check(file.name == "${it.id}.json") }
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized fun protectedPaths(): Set<String> = attempts().map { it.mediaPath }.toSet()
|
||||
|
||||
@Synchronized fun confirm(id: String): Boolean {
|
||||
val attempt = attempts().singleOrNull { it.id == id } ?: return false
|
||||
return File(directory, "${attempt.id}.json").delete()
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,21 @@ class VideoDownloader(private val context: Context) {
|
||||
/** 视频存储目录 */
|
||||
private val videoDir: File = File(context.getExternalFilesDir("videos") ?: context.filesDir, "videos").apply { mkdirs() }
|
||||
|
||||
private val pendingDrafts = PendingDraftStore(File(context.filesDir, "pending-drafts"))
|
||||
|
||||
fun beginDraft(path: String, title: String, declaration: String): String {
|
||||
check(File(path).canonicalFile.parentFile == videoDir.canonicalFile) { "草稿素材不在下载目录" }
|
||||
return pendingDrafts.begin(path, title, declaration).id
|
||||
}
|
||||
|
||||
fun confirmDraft(id: String): Boolean = pendingDrafts.confirm(id)
|
||||
|
||||
fun hasPendingDrafts(): Boolean = pendingDrafts.attempts().isNotEmpty()
|
||||
|
||||
fun isOwnedMedia(path: String): Boolean = runCatching {
|
||||
File(path).isFile && File(path).canonicalFile.parentFile == videoDir.canonicalFile
|
||||
}.getOrDefault(false)
|
||||
|
||||
/**
|
||||
* 已下载内容的 SHA-256 集合(内容级去重)。
|
||||
* ⚠️ 并发安全:管线多协程可能并行下载/查重(第一性审计)→ 线程安全 Set。
|
||||
@@ -304,11 +319,12 @@ class VideoDownloader(private val context: Context) {
|
||||
*/
|
||||
@Synchronized
|
||||
fun clearDownloadCache(exclude: Set<String> = emptySet()): Int {
|
||||
val protected = try { exclude + pendingDrafts.protectedPaths() } catch (_: Exception) { return 0 }
|
||||
var n = 0
|
||||
val cutoff = System.currentTimeMillis() - 24 * 60 * 60 * 1000L
|
||||
videoDir.listFiles()?.forEach { f ->
|
||||
if (f.isFile && (f.name.endsWith(".mp4") || f.name.endsWith(".tmp")) &&
|
||||
f.lastModified() < cutoff && f.absolutePath !in exclude
|
||||
f.lastModified() < cutoff && f.canonicalPath !in protected && f.absolutePath !in protected
|
||||
) {
|
||||
if (f.delete()) n++
|
||||
}
|
||||
@@ -371,6 +387,7 @@ class VideoDownloader(private val context: Context) {
|
||||
fun deleteVideo(filePath: String): Boolean {
|
||||
return try {
|
||||
val f = File(filePath)
|
||||
if (f.canonicalPath in pendingDrafts.protectedPaths()) return false
|
||||
if (f.exists()) f.delete() else false
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
|
||||
Reference in New Issue
Block a user