feat:
1.完成头条账号二维码核验,修复首页导航及停止后重试。 2.补齐共享提交会话、取消恢复和未知素材保护。 3.88 项 JVM、19 项 SQLite 测试通过;真机账号核验、停止、重试通过。
This commit is contained in:
@@ -7,6 +7,10 @@
|
||||
<queries>
|
||||
<package android:name="com.ss.android.article.news" />
|
||||
<package android:name="com.baidu.searchbox" />
|
||||
<package android:name="com.zhihu.android" />
|
||||
<package android:name="com.xingin.xhs" />
|
||||
<package android:name="com.sina.weibo" />
|
||||
<package android:name="com.ss.android.ugc.aweme" />
|
||||
<package android:name="com.android.gallery3d" />
|
||||
</queries>
|
||||
|
||||
|
||||
@@ -55,6 +55,7 @@ class MainActivity : ComponentActivity() {
|
||||
override fun onNewIntent(intent: android.content.Intent) {
|
||||
super.onNewIntent(intent)
|
||||
handleCommand(intent)
|
||||
consumeAccountClipboardRequest()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -67,6 +68,11 @@ class MainActivity : ComponentActivity() {
|
||||
*/
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (com.haorui.app.crossplatform.account.AccountClipboardRequests.shared.hasPending()) {
|
||||
consumeAccountClipboardRequest()
|
||||
return
|
||||
}
|
||||
consumeAccountClipboardRequest()
|
||||
// 前台读取触发点:仅在有待读取标志时处理并记录(避免刷屏)
|
||||
// ⚠️ 二轮审计:消费标志防一次请求读两次(onResume+handleCommand 双触发),
|
||||
// 读取代际号捕获在此刻,submit 回传 —— 跨轮迟到结果会被代际校验拒收。
|
||||
@@ -78,6 +84,41 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (hasFocus) consumeAccountClipboardRequest()
|
||||
}
|
||||
|
||||
private fun consumeAccountClipboardRequest() {
|
||||
if (!hasWindowFocus()) return
|
||||
val requests = com.haorui.app.crossplatform.account.AccountClipboardRequests.shared
|
||||
val request = requests.claim() ?: return
|
||||
fun read(attempt: Int) {
|
||||
window.decorView.postDelayed({
|
||||
if (!requests.isCurrent(request) || !hasWindowFocus()) return@postDelayed
|
||||
val result = runCatching {
|
||||
val manager = getSystemService(CLIPBOARD_SERVICE) as android.content.ClipboardManager
|
||||
if (request.operation == com.haorui.app.crossplatform.account.AccountClipboardRequests.Operation.PREPARE && attempt == 0) {
|
||||
manager.setPrimaryClip(android.content.ClipData.newPlainText(request.nonce, request.nonce))
|
||||
}
|
||||
val clip = manager.primaryClip
|
||||
val item = clip?.takeIf { it.itemCount == 1 }?.getItemAt(0)
|
||||
val text = (item?.text?.toString() ?: item?.coerceToText(this)?.toString())?.takeIf { it.length <= 8192 }
|
||||
if (attempt == 0 || attempt == 4) com.haorui.app.automation.RunLogger.i("AccountClipboard",
|
||||
"operation=${request.operation} attempt=$attempt items=${clip?.itemCount} text=${item?.text != null} uri=${item?.uri != null} readable=${text != null}")
|
||||
if (text == null) return@runCatching null
|
||||
val stamp = clip?.description?.timestamp ?: return@runCatching null
|
||||
com.haorui.app.crossplatform.account.AccountClipboardRequests.Result(text, stamp)
|
||||
}.getOrNull()
|
||||
val waitingForCopy = request.operation == com.haorui.app.crossplatform.account.AccountClipboardRequests.Operation.READ &&
|
||||
(result == null || result.text == request.nonce)
|
||||
if (waitingForCopy && attempt < 4) read(attempt + 1)
|
||||
else if (requests.complete(request, result)) moveTaskToBack(true)
|
||||
}, if (attempt == 0) 900 else 400)
|
||||
}
|
||||
read(0)
|
||||
}
|
||||
|
||||
private fun handleCommand(intent: android.content.Intent?) {
|
||||
if (intent?.action == com.haorui.app.automation.ClipboardBridge.ACTION_CONSUME_CLIP) {
|
||||
// ⚠️ 二轮审计:双触发防护 —— onResume 已消费则不再读(一次请求只读一次)
|
||||
@@ -105,6 +146,10 @@ class MainActivity : ComponentActivity() {
|
||||
com.haorui.app.automation.RunLogger.i("UI", "收到停止命令(intent extra)")
|
||||
com.haorui.app.automation.HaoRuiAccessibilityService.instance?.stopAutomation()
|
||||
}
|
||||
"testAccount" -> if (applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE != 0) {
|
||||
val accepted = com.haorui.app.automation.HaoRuiAccessibilityService.instance?.verifyAccountSandbox() == true
|
||||
com.haorui.app.automation.RunLogger.i("UI", "账号只读核验受理=$accepted")
|
||||
}
|
||||
// ── 装机调试命令(adb 触发,验证 F1/F2 用)─────────
|
||||
"testCredit" -> {
|
||||
val svc = com.haorui.app.automation.HaoRuiAccessibilityService.instance
|
||||
@@ -139,6 +184,8 @@ class MainActivity : ComponentActivity() {
|
||||
private fun consumeClipboardInForeground(gen: Int) {
|
||||
com.haorui.app.automation.RunLogger.i("UI", "前台读取页已就绪,700ms 后读剪贴板")
|
||||
window.decorView.postDelayed({
|
||||
if (gen != com.haorui.app.automation.ClipboardBridge.generation ||
|
||||
com.haorui.app.crossplatform.account.AccountClipboardRequests.shared.hasPending()) return@postDelayed
|
||||
val url = com.haorui.app.automation.ClipboardBridge.readFromClipboard(applicationContext) { msg ->
|
||||
com.haorui.app.automation.RunLogger.i("UI", "前台剪贴板诊断: $msg")
|
||||
}
|
||||
@@ -161,12 +208,12 @@ class MainActivity : ComponentActivity() {
|
||||
@Composable
|
||||
private fun HaoRuiRoot(repository: ConfigRepository) {
|
||||
val saved by repository.config.collectAsState(initial = null)
|
||||
var local by remember { mutableStateOf(AppConfig()) }
|
||||
var local by remember { mutableStateOf<AppConfig?>(null) }
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
// DataStore 首个值到达时灌入本地副本(只灌一次,避免覆盖用户正在编辑的内容)
|
||||
LaunchedEffect(saved) {
|
||||
saved?.let { if (local == AppConfig()) local = it }
|
||||
saved?.let { if (local == null) local = it }
|
||||
}
|
||||
|
||||
fun commit(next: AppConfig) {
|
||||
@@ -174,5 +221,6 @@ private fun HaoRuiRoot(repository: ConfigRepository) {
|
||||
scope.launch { repository.save(next) }
|
||||
}
|
||||
|
||||
HaoRuiApp(config = local, onConfigChange = ::commit)
|
||||
val current = local
|
||||
if (current != null) HaoRuiApp(config = current, onConfigChange = ::commit)
|
||||
}
|
||||
|
||||
@@ -49,6 +49,14 @@ class GestureRunner(private val service: AccessibilityService) {
|
||||
return tapAt(r.centerX(), r.centerY())
|
||||
}
|
||||
|
||||
/** 外部正式提交使用单次坐标派发,拒绝/取消/超时均由提交日志进入核对。 */
|
||||
suspend fun tapNodeOnce(node: AccessibilityNodeInfo): Boolean {
|
||||
val bounds = Rect()
|
||||
node.getBoundsInScreen(bounds)
|
||||
if (bounds.isEmpty) return false
|
||||
return tapAt(bounds.centerX(), bounds.centerY(), retry = false)
|
||||
}
|
||||
|
||||
/**
|
||||
* 坐标点击(带前摇 + 失败重试一次)。
|
||||
* ⚠️ 二轮审计:仅**系统拒绝派发**(手势未开始)才重试 ——
|
||||
@@ -144,6 +152,9 @@ class GestureRunner(private val service: AccessibilityService) {
|
||||
): Boolean {
|
||||
// 对照原 q0:手势期间压悬浮窗,防吃掉长按起点
|
||||
com.haorui.app.overlay.MonitorOverlay.setHidden(true)
|
||||
var heldStroke: GestureDescription.StrokeDescription? = null
|
||||
var releaseAtMs = 0L
|
||||
var finished = false
|
||||
try {
|
||||
val path = Path().apply {
|
||||
moveTo(x(fromX).toFloat(), y(fromY).toFloat())
|
||||
@@ -153,18 +164,30 @@ class GestureRunner(private val service: AccessibilityService) {
|
||||
val desc = GestureDescription.Builder().addStroke(stroke).build()
|
||||
val dispatched = runCatching { service.dispatchGesture(desc, null, null) }.getOrDefault(false)
|
||||
if (!dispatched) return false
|
||||
heldStroke = stroke
|
||||
releaseAtMs = android.os.SystemClock.elapsedRealtime() + holdMs
|
||||
delay(holdMs + continueMs)
|
||||
// 续接收尾段并终结(willContinue=false → 系统随后回调完成)
|
||||
val endPath = Path().apply { moveTo(x(toX).toFloat(), y(toY).toFloat()) }
|
||||
val endStroke = runCatching { stroke.continueStroke(endPath, 0, 50L, false) }.getOrNull() ?: return false
|
||||
return runCatching {
|
||||
service.dispatchGesture(
|
||||
GestureDescription.Builder().addStroke(endStroke).build(), null, null,
|
||||
)
|
||||
}.getOrDefault(false)
|
||||
} finally {
|
||||
runCatching { com.haorui.app.overlay.MonitorOverlay.setHidden(false) }
|
||||
kotlinx.coroutines.withContext(kotlinx.coroutines.NonCancellable) {
|
||||
try {
|
||||
finished = withTimeoutOrNull(GESTURE_TIMEOUT_MS) {
|
||||
val stroke = heldStroke ?: return@withTimeoutOrNull false
|
||||
delay((releaseAtMs - android.os.SystemClock.elapsedRealtime()).coerceAtLeast(0L))
|
||||
val endPath = Path().apply { moveTo(x(toX).toFloat(), y(toY).toFloat()) }
|
||||
val endStroke = stroke.continueStroke(endPath, 0, 50L, false)
|
||||
suspendCancellableCoroutine { cont ->
|
||||
val accepted = service.dispatchGesture(GestureDescription.Builder().addStroke(endStroke).build(),
|
||||
object : AccessibilityService.GestureResultCallback() {
|
||||
override fun onCompleted(g: GestureDescription) { if (cont.isActive) cont.resume(true) }
|
||||
override fun onCancelled(g: GestureDescription) { if (cont.isActive) cont.resume(false) }
|
||||
}, null)
|
||||
if (!accepted && cont.isActive) cont.resume(false)
|
||||
}
|
||||
} ?: false
|
||||
} finally { com.haorui.app.overlay.MonitorOverlay.setHidden(false) }
|
||||
}
|
||||
}
|
||||
return finished
|
||||
}
|
||||
|
||||
// ── 全局动作 ──────────────────────────────────────────────
|
||||
@@ -195,6 +218,8 @@ class GestureRunner(private val service: AccessibilityService) {
|
||||
x1: Float, y1: Float, x2: Float, y2: Float,
|
||||
): StrokeOutcome {
|
||||
com.haorui.app.overlay.MonitorOverlay.setHidden(true)
|
||||
val completed = kotlinx.coroutines.CompletableDeferred<Unit>()
|
||||
var accepted = false
|
||||
try {
|
||||
val path = Path().apply {
|
||||
moveTo(x1, y1)
|
||||
@@ -206,22 +231,27 @@ class GestureRunner(private val service: AccessibilityService) {
|
||||
suspendCancellableCoroutine { cont ->
|
||||
val dispatched = service.dispatchGesture(desc, object : AccessibilityService.GestureResultCallback() {
|
||||
override fun onCompleted(g: GestureDescription) {
|
||||
completed.complete(Unit)
|
||||
if (cont.isActive) cont.resume(StrokeOutcome.COMPLETED)
|
||||
}
|
||||
override fun onCancelled(g: GestureDescription) {
|
||||
completed.complete(Unit)
|
||||
// 已开始被取消 = 可能已部分执行,不能重放
|
||||
if (cont.isActive) cont.resume(StrokeOutcome.UNCERTAIN)
|
||||
}
|
||||
}, null)
|
||||
accepted = dispatched
|
||||
if (!dispatched) completed.complete(Unit)
|
||||
if (!dispatched && cont.isActive) cont.resume(StrokeOutcome.REJECTED)
|
||||
}
|
||||
} ?: StrokeOutcome.UNCERTAIN
|
||||
} finally {
|
||||
// 等手势回调落地后再恢复悬浮窗(对齐原 q0 的 j2+60ms 后恢复)
|
||||
kotlinx.coroutines.withTimeoutOrNull(100L) {
|
||||
kotlinx.coroutines.delay(60)
|
||||
kotlinx.coroutines.withContext(kotlinx.coroutines.NonCancellable) {
|
||||
try {
|
||||
if (accepted) withTimeoutOrNull(GESTURE_TIMEOUT_MS) { completed.await() }
|
||||
delay(60)
|
||||
} finally { com.haorui.app.overlay.MonitorOverlay.setHidden(false) }
|
||||
}
|
||||
com.haorui.app.overlay.MonitorOverlay.setHidden(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,13 @@ import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.CoroutineStart
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import com.haorui.app.crossplatform.schedule.ForegroundCoordinator
|
||||
import com.haorui.app.crossplatform.schedule.CrossRunLifecycle
|
||||
import com.haorui.app.crossplatform.data.CrossPublishTaskStore
|
||||
import com.haorui.app.automation.scheduler.LaneScheduler
|
||||
|
||||
/**
|
||||
@@ -55,6 +62,56 @@ class HaoRuiAccessibilityService : AccessibilityService() {
|
||||
* 而且恢复动作绝不能走主线程(主线程被卡时恢复回调自己也进不来)。
|
||||
*/
|
||||
private val automationScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
val foregroundCoordinator = ForegroundCoordinator()
|
||||
@Volatile
|
||||
private var crossRunSession: CrossRunLifecycle.Session? = null
|
||||
@Volatile private var sharedBudgetRestored = false
|
||||
@Volatile private var hasSharedAccountHistory = true
|
||||
private val stepJobs = java.util.Collections.synchronizedSet(mutableSetOf<Job>())
|
||||
private val stepLifecycleLock = Any()
|
||||
private val _accountVerification = kotlinx.coroutines.flow.MutableStateFlow("头条账号尚未核验")
|
||||
val accountVerification: kotlinx.coroutines.flow.StateFlow<String> = _accountVerification
|
||||
|
||||
/** 停止状态下独占前台,仅核验身份,不开启调度或绑定额度。 */
|
||||
fun verifyAccountSandbox(): Boolean = synchronized(stepLifecycleLock) {
|
||||
if (!::scheduler.isInitialized || scheduler.isRunning || publisher.isWorking || interactor.isWorking ||
|
||||
restBrowse.isResting || frontGuard.creditNavigating) return@synchronized false
|
||||
val ticket = foregroundCoordinator.tryEnterExclusive("ACCOUNT") ?: return@synchronized false
|
||||
val generation = startGeneration
|
||||
_accountVerification.value = "正在核验头条账号"
|
||||
launchForegroundTask {
|
||||
try {
|
||||
val reader = com.haorui.app.crossplatform.account.ToutiaoAccountReader(this@HaoRuiAccessibilityService) {
|
||||
instance === this@HaoRuiAccessibilityService && startGeneration == generation && foregroundCoordinator.isCurrent(ticket)
|
||||
}
|
||||
val verified = reader.verify()
|
||||
_accountVerification.value = if (verified != null) "已核验:${verified.displayName}" else "核验未通过:${reader.failure}"
|
||||
RunLogger.i(TAG, if (verified != null) "当前头条账号核验通过" else "头条账号核验未通过:${reader.failure}")
|
||||
if (startGeneration == generation && foregroundCoordinator.isCurrent(ticket)) bringAppToForeground()
|
||||
} catch (cancelled: kotlin.coroutines.cancellation.CancellationException) {
|
||||
_accountVerification.value = "账号核验已取消"
|
||||
throw cancelled
|
||||
} catch (failure: Exception) {
|
||||
_accountVerification.value = "账号核验中断,请重试"
|
||||
RunLogger.w(TAG, "账号核验中断:${failure.javaClass.simpleName}")
|
||||
} finally { foregroundCoordinator.release(ticket) }
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
private fun launchForegroundTask(block: suspend () -> Unit): Job = synchronized(stepLifecycleLock) {
|
||||
val generation = startGeneration
|
||||
val job = automationScope.launch(start = CoroutineStart.LAZY) {
|
||||
if (generation != startGeneration) return@launch
|
||||
try { block() }
|
||||
catch (ce: kotlin.coroutines.cancellation.CancellationException) { throw ce }
|
||||
catch (t: Exception) { RunLogger.e(TAG, "前台任务失败: ${t.javaClass.simpleName}", t) }
|
||||
}
|
||||
stepJobs.add(job)
|
||||
job.invokeOnCompletion { stepJobs.remove(job) }
|
||||
job.start()
|
||||
job
|
||||
}
|
||||
|
||||
private lateinit var scheduler: LaneScheduler
|
||||
lateinit var collector: CollectMachine
|
||||
@@ -106,6 +163,16 @@ class HaoRuiAccessibilityService : AccessibilityService() {
|
||||
instance = this
|
||||
RunLogger.init(applicationContext)
|
||||
DiagnosticLogger.init(applicationContext)
|
||||
val taskStore = CrossPublishTaskStore.get(applicationContext)
|
||||
crossRunSession = taskStore.runLifecycle.openSession()
|
||||
automationScope.launch {
|
||||
taskStore.runLifecycle.state.collect { state ->
|
||||
state.error?.let {
|
||||
RunLogger.w(TAG, it)
|
||||
TaskStatusBus.status("$it,跨平台任务已暂停")
|
||||
}
|
||||
}
|
||||
}
|
||||
// 进程存活心跳:独立于 RunLogger,用于区分「日志管道死亡」与「进程真死」
|
||||
com.haorui.app.logging.Heartbeat.start(applicationContext)
|
||||
// ⚠️ 2026-10-29 根因修复:必须立刻拉起前台保活服务。
|
||||
@@ -162,13 +229,15 @@ class HaoRuiAccessibilityService : AccessibilityService() {
|
||||
// RestBrowseMachine 全部吃构造默认值,用户配置(配额/休息/重置点/类目/
|
||||
// 滑动上限/声明/封面/浏览)对自动化整体无效。此处统一注入并持续跟随。
|
||||
// ⚠️ 二轮审计:原实现只打日志不替换,AI 改写恒走本地兜底、API 路径从未生效。
|
||||
kotlinx.coroutines.MainScope().launch {
|
||||
automationScope.launch {
|
||||
try {
|
||||
var restored = false
|
||||
var lastResetHour = -1
|
||||
var lastResetMinute = -1
|
||||
ConfigRepository(applicationContext).config.collect { cfg ->
|
||||
latestConfig = cfg
|
||||
foregroundCoordinator.configure(cfg.crossPlatform.enabled)
|
||||
crossRunSession?.configure(cfg.crossPlatform.enabled)
|
||||
val resetChanged = restored && (cfg.reset.hour != lastResetHour || cfg.reset.minute != lastResetMinute)
|
||||
lastResetHour = cfg.reset.hour
|
||||
lastResetMinute = cfg.reset.minute
|
||||
@@ -220,7 +289,7 @@ class HaoRuiAccessibilityService : AccessibilityService() {
|
||||
.putInt("published_count", 0)
|
||||
.putString("segment_state", quotaManager.snapshotState())
|
||||
.apply()
|
||||
automationScope.launch { runDailyResetChain() }
|
||||
launchForegroundTask { runDailyResetChain() }
|
||||
}
|
||||
|
||||
// 三条状态机车道(命名车道,互不阻塞)
|
||||
@@ -233,14 +302,20 @@ class HaoRuiAccessibilityService : AccessibilityService() {
|
||||
|
||||
// 每条车道的 step() 必须包 try/catch:协程内未捕获异常会被
|
||||
// 默认 handler 静默吞掉(OEM 又限制 logcat),导致车道"静默停摆"。
|
||||
fun safeStep(name: String, block: suspend () -> Unit) {
|
||||
automationScope.launch {
|
||||
fun safeStep(lane: LaneScheduler.Lane, block: suspend () -> Unit) = synchronized(stepLifecycleLock) {
|
||||
if (!scheduler.isScheduled(lane)) return@synchronized
|
||||
launchForegroundTask {
|
||||
val ticket = foregroundCoordinator.tryEnterLegacy(lane.name) ?: return@launchForegroundTask
|
||||
try {
|
||||
kotlinx.coroutines.currentCoroutineContext().ensureActive()
|
||||
block()
|
||||
} catch (ce: kotlin.coroutines.cancellation.CancellationException) {
|
||||
RunLogger.w(TAG, "[$name] step 被取消")
|
||||
RunLogger.w(TAG, "[${lane.name}] step 被取消")
|
||||
throw ce
|
||||
} catch (t: Throwable) {
|
||||
RunLogger.e(TAG, "[$name] step 异常: ${t.javaClass.simpleName}:${t.message}", t)
|
||||
RunLogger.e(TAG, "[${lane.name}] step 异常: ${t.javaClass.simpleName}:${t.message}", t)
|
||||
} finally {
|
||||
foregroundCoordinator.release(ticket)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -259,7 +334,7 @@ class HaoRuiAccessibilityService : AccessibilityService() {
|
||||
RunLogger.i(TAG, "前台驱动者冲突(${frontGuard.describe()}),采集车道让路")
|
||||
return@register
|
||||
}
|
||||
safeStep("Collect") { collector.step() }
|
||||
safeStep(LaneScheduler.Lane.COLLECT) { collector.step() }
|
||||
}
|
||||
scheduler.register(LaneScheduler.Lane.PUBLISH) {
|
||||
// ⚠️ 2026-10-30 第一性审计:发布机空闲时消化管线暂存队列
|
||||
@@ -269,14 +344,14 @@ class HaoRuiAccessibilityService : AccessibilityService() {
|
||||
if (publisher.isIdle && frontGuard.maySubmit()) {
|
||||
pipeline.processPending()
|
||||
}
|
||||
safeStep("Publish") { publisher.step() }
|
||||
safeStep(LaneScheduler.Lane.PUBLISH) { publisher.step() }
|
||||
}
|
||||
scheduler.register(LaneScheduler.Lane.INTERACT) { safeStep("Interact") { interactor.step() } }
|
||||
scheduler.register(LaneScheduler.Lane.INTERACT) { safeStep(LaneScheduler.Lane.INTERACT) { interactor.step() } }
|
||||
|
||||
// ⚠️ 2026-10-31:mayRest 此前是死 API,REST 车道裸跑会与信用分导航/互动互踩。
|
||||
// 倒计时播报不驱动前台可照常;浏览动作必须过互斥表。
|
||||
scheduler.register(LaneScheduler.Lane.REST) {
|
||||
safeStep("Rest") { restBrowse.step(mayBrowse = { frontGuard.mayRest() }) }
|
||||
safeStep(LaneScheduler.Lane.REST) { restBrowse.step(mayBrowse = { frontGuard.mayRest() }) }
|
||||
}
|
||||
|
||||
// 看门狗车道:执行恢复链检查(8 个核心检查项)+ 孤儿素材周期回收(P2)
|
||||
@@ -403,6 +478,11 @@ class HaoRuiAccessibilityService : AccessibilityService() {
|
||||
|
||||
override fun onInterrupt() {
|
||||
RunLogger.w(TAG, "无障碍服务被中断")
|
||||
if (foregroundCoordinator.hasSourceOwner()) {
|
||||
stopAutomation()
|
||||
TaskStatusBus.status("来源采集被中断,已暂停并保留本地任务")
|
||||
return
|
||||
}
|
||||
|
||||
// ── 场景 1:互动进行中 → 不强拉车道(对照原 G1 停止本轮互动)──
|
||||
// 强拉会打断 doFinish 收尾(回关计数/退页);让 INTERACT 车道自然跑完。
|
||||
@@ -416,8 +496,7 @@ class HaoRuiAccessibilityService : AccessibilityService() {
|
||||
if (::publisher.isInitialized && publisher.isWorking) {
|
||||
RunLogger.w(TAG, "发布任务进行中被中断,暂停自动化避免重复发布")
|
||||
TaskStatusBus.status("服务中断,发布结果待核对,自动任务已暂停,避免重复发布")
|
||||
scheduler.clearIntent()
|
||||
scheduler.stopAll()
|
||||
stopAutomation()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -444,9 +523,18 @@ class HaoRuiAccessibilityService : AccessibilityService() {
|
||||
}
|
||||
}
|
||||
|
||||
override fun onUnbind(intent: Intent?): Boolean {
|
||||
crossRunSession?.close()
|
||||
stopAutomation()
|
||||
if (instance === this) instance = null
|
||||
return super.onUnbind(intent)
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
runCatching { unregisterReceiver(cmdReceiver) }
|
||||
scheduler.stopAll()
|
||||
crossRunSession?.close()
|
||||
stopAutomation()
|
||||
automationScope.cancel()
|
||||
// ⚠️ 2026-10-29 修复静态引用生命周期竞态:
|
||||
// 重装/服务重绑时,旧实例的 onDestroy 会晚于新实例的 onServiceConnected 执行,
|
||||
// 原来无条件 instance = null 会把刚设好的新实例清掉,
|
||||
@@ -510,7 +598,7 @@ class HaoRuiAccessibilityService : AccessibilityService() {
|
||||
}
|
||||
// ── 装机调试广播(不动前台,被测对象不被测试通道干扰)──
|
||||
"com.haorui.app.ACTION_TEST_CREDIT" -> {
|
||||
automationScope.launch {
|
||||
launchForegroundTask {
|
||||
val msg = com.haorui.app.ocr.CreditGateRunner.readOnce(
|
||||
this@HaoRuiAccessibilityService,
|
||||
)
|
||||
@@ -541,13 +629,13 @@ class HaoRuiAccessibilityService : AccessibilityService() {
|
||||
// 评估完成时校验代际未变,用户的停止意图永不被覆盖(对齐 ClipboardBridge 模式)。
|
||||
val myGen = startGeneration
|
||||
if (cfg.credit.gateEnabled && !dayBlocked) {
|
||||
automationScope.launch {
|
||||
launchForegroundTask {
|
||||
val verdict = com.haorui.app.ocr.CreditGateRunner.evaluate(
|
||||
this@HaoRuiAccessibilityService, cfg.credit.threshold,
|
||||
)
|
||||
if (myGen != startGeneration) {
|
||||
RunLogger.i(TAG, "信用评估完成但启动代际已变(用户已停止),放弃拉起")
|
||||
return@launch
|
||||
return@launchForegroundTask
|
||||
}
|
||||
when (verdict) {
|
||||
com.haorui.app.ocr.CreditGateRunner.Verdict.BLOCKED -> {
|
||||
@@ -558,7 +646,7 @@ class HaoRuiAccessibilityService : AccessibilityService() {
|
||||
if (dayBlocked) {
|
||||
TaskStatusBus.status("今日任务已被禁止启动(信用分门控),等待下次重置解除")
|
||||
} else {
|
||||
scheduler.start()
|
||||
startScheduler(myGen)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -569,19 +657,82 @@ class HaoRuiAccessibilityService : AccessibilityService() {
|
||||
TaskStatusBus.status("今日任务已被禁止启动(信用分门控),等待下次重置解除")
|
||||
return
|
||||
}
|
||||
scheduler.start()
|
||||
startScheduler(myGen)
|
||||
}
|
||||
|
||||
fun stopAutomation() {
|
||||
private fun startScheduler(expectedGeneration: Int) = synchronized(stepLifecycleLock) {
|
||||
if (expectedGeneration != startGeneration || instance !== this) return@synchronized
|
||||
foregroundCoordinator.beginRun()
|
||||
scheduler.start()
|
||||
if (scheduler.isRunning) crossRunSession?.start()
|
||||
}
|
||||
|
||||
fun stopAutomation() = synchronized(stepLifecycleLock) {
|
||||
// F5:递增启动代际,使在途的异步信用评估失效(停止意图优先)
|
||||
startGeneration++
|
||||
foregroundCoordinator.stop()
|
||||
crossRunSession?.stop()
|
||||
// 清除「应该在跑」的意愿,自愈监控据此不再拉起
|
||||
scheduler.clearIntent()
|
||||
scheduler.stopAll()
|
||||
if (::scheduler.isInitialized) {
|
||||
scheduler.clearIntent()
|
||||
scheduler.stopAll()
|
||||
}
|
||||
synchronized(stepJobs) { stepJobs.toList() }.forEach { it.cancel() }
|
||||
}
|
||||
|
||||
fun isRunning(): Boolean = scheduler.isRunning
|
||||
|
||||
/** 新来源仅可在旧流程的完整安全边界入场,不在详情、编辑或回执中途切换。 */
|
||||
fun tryEnterSourceForeground(sourceId: String): ForegroundCoordinator.Ticket? {
|
||||
if (currentCrossRunGeneration() == null) return null
|
||||
val source = com.haorui.app.crossplatform.source.SourceRegistry.find(sourceId) ?: return null
|
||||
val status = com.haorui.app.crossplatform.source.SourceRegistry.executionStatus(
|
||||
sourceId, Targets.versionOf(this, source.packageName), latestConfig.crossPlatform,
|
||||
)
|
||||
if (!status.canExecute) return null
|
||||
return foregroundCoordinator.tryEnterSource(sourceId) {
|
||||
currentCrossRunGeneration() != null && !publisher.isWorking && !interactor.isWorking && !restBrowse.isResting &&
|
||||
!frontGuard.creditNavigating && collector.phase == CollectMachine.Phase.SCAN
|
||||
}
|
||||
}
|
||||
|
||||
/** 来源与后续任务写库使用此代际,不能使用前台 Ticket.generation。 */
|
||||
fun currentCrossRunGeneration(): Long? = crossRunSession?.currentGeneration()
|
||||
|
||||
fun requiresSharedLegacyBudget(): Boolean = latestConfig.crossPlatform.enabled || hasSharedAccountHistory
|
||||
|
||||
fun createLegacyPublishSession(mediaPath: String, payloadHash: String): com.haorui.app.crossplatform.publish.LegacyPublishSession? {
|
||||
val generation = currentCrossRunGeneration() ?: return null
|
||||
val current = { instance === this && currentCrossRunGeneration() == generation && requiresSharedLegacyBudget() }
|
||||
val base = com.haorui.app.crossplatform.publish.StoreLegacyPublishJournal(CrossPublishTaskStore.get(applicationContext))
|
||||
val journal = object : com.haorui.app.crossplatform.publish.LegacyPublishSession.Journal by base {
|
||||
override suspend fun bind(account: String, generation: Long, snapshot: com.haorui.app.crossplatform.model.AccountQuotaSnapshot): Boolean {
|
||||
val bound = base.bind(account, generation, snapshot)
|
||||
if (bound) synchronized(stepLifecycleLock) {
|
||||
hasSharedAccountHistory = true
|
||||
}
|
||||
return bound
|
||||
}
|
||||
}
|
||||
return com.haorui.app.crossplatform.publish.LegacyPublishSession(generation, mediaPath, payloadHash,
|
||||
journal,
|
||||
{ com.haorui.app.crossplatform.account.ToutiaoAccountReader(this, current).verify() },
|
||||
{ quotaManager.submissionBudget(latestConfig.crossPlatform) }, current)
|
||||
}
|
||||
|
||||
/** 混合正式发布等待 M6 健康与作品回执验收,不能绕回旧的独立计数入口。 */
|
||||
fun legacyFormalPublishRejection(): String? = when {
|
||||
!sharedBudgetRestored -> "共享额度恢复中,正式发布暂缓"
|
||||
requiresSharedLegacyBudget() -> "共享发布尚待验收,正式发布已暂停"
|
||||
else -> null
|
||||
}
|
||||
|
||||
fun tryEnterCreditForeground(): ForegroundCoordinator.Ticket? {
|
||||
if (latestConfig.crossPlatform.enabled &&
|
||||
(publisher.isWorking || interactor.isWorking || collector.phase != CollectMachine.Phase.SCAN)) return null
|
||||
return foregroundCoordinator.tryEnterLegacy("CREDIT")
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试/沙盒启动一轮互动(装机死锁防护):
|
||||
* 调度器未运行时用 [LaneScheduler.startLaneOnly] 单车道沙盒驱动
|
||||
@@ -630,7 +781,7 @@ class HaoRuiAccessibilityService : AccessibilityService() {
|
||||
* 日期键与 QuotaManager.effectiveDate 一致 —— 分时段 hour<6 归前一天,
|
||||
* 用 LocalDate.now() 会在凌晨重启误清当日计数。
|
||||
*/
|
||||
private fun restoreRunState() {
|
||||
private suspend fun restoreRunState() {
|
||||
// ⚠️ 日期键必须与 QuotaManager.effectiveDate 一致(二轮审计):
|
||||
// 分时段 hour<6 归前一天,用 LocalDate.now() 会在凌晨重启误清当日计数。
|
||||
val today = quotaManager.todayKey()
|
||||
@@ -661,6 +812,19 @@ class HaoRuiAccessibilityService : AccessibilityService() {
|
||||
RunLogger.i(TAG, "断点续排通道就绪(日期键 $today)")
|
||||
// 锚定完成,武装重置判定(此前 checkDailyReset 一律短路,防启动竞态误触发)
|
||||
quotaManager.armResetChain()
|
||||
try {
|
||||
val store = CrossPublishTaskStore.get(applicationContext)
|
||||
hasSharedAccountHistory = store.hasSharedBudgetHistory()
|
||||
store.legacyBudgetState(quotaManager.todayKey())?.let(quotaManager::mergeSharedLegacyState)
|
||||
sharedBudgetRestored = true
|
||||
foregroundCoordinator.configure(latestConfig.crossPlatform.enabled)
|
||||
crossRunSession?.configure(latestConfig.crossPlatform.enabled)
|
||||
} catch (ce: kotlin.coroutines.cancellation.CancellationException) {
|
||||
throw ce
|
||||
} catch (failure: Exception) {
|
||||
RunLogger.w(TAG, "共享额度恢复失败:${failure.javaClass.simpleName}")
|
||||
TaskStatusBus.status("共享额度未恢复,正式发布已暂停")
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun runDailyResetChain() {
|
||||
@@ -731,16 +895,26 @@ class HaoRuiAccessibilityService : AccessibilityService() {
|
||||
}
|
||||
|
||||
private fun sweepOrphans() {
|
||||
runCatching {
|
||||
// 先取在用素材快照再删 —— 宁可少删不可错删(P2 事务边界)
|
||||
val active = pipeline.activeFilePaths()
|
||||
val n = videoDownloader.clearDownloadCache(active)
|
||||
if (n > 0) RunLogger.i(TAG, "孤儿素材回收: 清理 $n 个陈旧缓存文件(排除在用 ${active.size} 个)")
|
||||
}.onFailure {
|
||||
RunLogger.w(TAG, "孤儿素材回收失败: ${it.message}")
|
||||
automationScope.launch {
|
||||
try {
|
||||
// 先取在用素材快照再删 —— 宁可少删不可错删(P2 事务边界)
|
||||
val protected = CrossPublishTaskStore.get(applicationContext).protectedSubmissionMediaPaths()
|
||||
val active = pipeline.activeFilePaths() + protected
|
||||
val n = videoDownloader.clearDownloadCache(active)
|
||||
if (n > 0) RunLogger.i(TAG, "孤儿素材回收: 清理 $n 个陈旧缓存文件(排除在用 ${active.size} 个)")
|
||||
} catch (ce: kotlin.coroutines.cancellation.CancellationException) {
|
||||
throw ce
|
||||
} catch (failure: Exception) {
|
||||
RunLogger.w(TAG, "孤儿素材回收失败: ${failure.javaClass.simpleName}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun clearUnusedDownloadCache(): Int = kotlinx.coroutines.withContext(Dispatchers.IO) {
|
||||
val protected = CrossPublishTaskStore.get(applicationContext).protectedSubmissionMediaPaths()
|
||||
videoDownloader.clearDownloadCache(pipeline.activeFilePaths() + protected)
|
||||
}
|
||||
|
||||
/** 拉起目标 App(原 RecoveryResumeTask case 16→21 的 HOME+重开逻辑) */
|
||||
fun launchApp(pkg: String) {
|
||||
val pm = packageManager
|
||||
|
||||
@@ -12,6 +12,11 @@ import com.haorui.app.data.model.ToutiaoConfig
|
||||
import com.haorui.app.pipeline.VideoDownloader
|
||||
import com.haorui.app.scheduler.QuotaManager
|
||||
import kotlinx.coroutines.delay
|
||||
import com.haorui.app.crossplatform.publish.LegacyPublishSession
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ensureActive
|
||||
|
||||
/**
|
||||
* 视频发布状态机。
|
||||
@@ -66,6 +71,7 @@ class PublishMachine(
|
||||
private var mediaUri: String = ""
|
||||
private var autoPublish: Boolean = true
|
||||
private var eligibilityCheck: (() -> String?)? = null
|
||||
private var sharedSession: LegacyPublishSession? = null
|
||||
private var declaration: String = ToutiaoSelectors.TXT_DECLARATION_DEFAULT
|
||||
|
||||
private var titleRetry = 0
|
||||
@@ -99,10 +105,15 @@ class PublishMachine(
|
||||
log("发布机非空闲(phase=$phase),拒绝新任务")
|
||||
return false
|
||||
}
|
||||
if (autoPublish) svc.legacyFormalPublishRejection()?.let { reason ->
|
||||
TaskStatusBus.status(reason)
|
||||
return false
|
||||
}
|
||||
this.title = title
|
||||
this.mediaUri = mediaUri
|
||||
this.autoPublish = autoPublish
|
||||
this.eligibilityCheck = eligibilityCheck
|
||||
this.sharedSession = null
|
||||
this.declaration = declaration ?: toutiaoConfig.workDeclaration
|
||||
this.titleRetry = 0
|
||||
this.coverFramesTried = 0
|
||||
@@ -183,6 +194,9 @@ class PublishMachine(
|
||||
Phase.DONE -> doDone()
|
||||
Phase.FAILED -> doFailed()
|
||||
}
|
||||
} catch (cancelled: kotlinx.coroutines.CancellationException) {
|
||||
withContext(NonCancellable) { runCatching { sharedSession?.markUnknown("发布步骤已取消,等待作品核对") } }
|
||||
throw cancelled
|
||||
} finally {
|
||||
busy.set(false)
|
||||
}
|
||||
@@ -191,11 +205,20 @@ class PublishMachine(
|
||||
// ── 各相位实现 ────────────────────────────────────────────
|
||||
|
||||
private suspend fun doPrepare() {
|
||||
if (pauseForSharedAccount()) return
|
||||
if (title.isBlank() || mediaUri.isBlank()) {
|
||||
log("标题或素材为空,任务作废")
|
||||
go(Phase.FAILED)
|
||||
return
|
||||
}
|
||||
if (autoPublish && svc.requiresSharedLegacyBudget()) {
|
||||
val context = sharedSession ?: svc.createLegacyPublishSession(mediaUri, payloadFingerprint()).also { sharedSession = it }
|
||||
if (context == null || (context.state == LegacyPublishSession.State.NEW && !context.prepare())) {
|
||||
TaskStatusBus.status(context?.reason ?: "共享发布运行尚未就绪")
|
||||
go(Phase.FAILED)
|
||||
return
|
||||
}
|
||||
}
|
||||
// ⚠️ 2026-10-29 补齐缺失环节:先用 ACTION_SEND 打开头条发布页并带入视频+标题。
|
||||
// new Intent(ACTION_SEND).setType("video/mp4")
|
||||
// .putExtra(EXTRA_STREAM, uri).putExtra(EXTRA_TEXT, rewritten)
|
||||
@@ -515,6 +538,7 @@ class PublishMachine(
|
||||
|
||||
/** 点发布 / 存草稿 */
|
||||
private suspend fun doConfirm() {
|
||||
if (pauseForSharedAccount()) return
|
||||
val root = rootOrNull() ?: return
|
||||
eligibilityCheck?.invoke()?.let { reason ->
|
||||
log("点击发布前筛选拒绝:$reason")
|
||||
@@ -553,8 +577,21 @@ class PublishMachine(
|
||||
delay(800)
|
||||
return
|
||||
}
|
||||
val tapped = svc.gestures.tapNode(btn)
|
||||
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 失败,重试")
|
||||
@@ -571,8 +608,23 @@ class PublishMachine(
|
||||
go(Phase.WAIT_RECEIPT)
|
||||
}
|
||||
|
||||
private fun pauseForSharedAccount(): Boolean {
|
||||
if (!autoPublish) return false
|
||||
val reason = svc.legacyFormalPublishRejection() ?: return false
|
||||
TaskStatusBus.status(reason)
|
||||
return true
|
||||
}
|
||||
|
||||
/** 等回执(发布成功 / 发布失败 / 已发布)—— 未确认回执不计数 */
|
||||
private suspend fun doWaitReceipt() {
|
||||
sharedSession?.let { context ->
|
||||
// M6 作品核对器尚未接通。共享尝试不能进入旧的分享面板/超时成功判定。
|
||||
context.markUnknown("发布动作已派发,等待明确作品回执")
|
||||
TaskStatusBus.status("发布结果待核对,素材与额度已保留")
|
||||
go(Phase.FAILED)
|
||||
svc.stopAutomation()
|
||||
return
|
||||
}
|
||||
val root = rootOrNull() ?: return
|
||||
|
||||
// ⚠️ 2026-10-29 真机实测:正式发布的回执文案是**「发布成功,分享给朋友一起看」**,
|
||||
@@ -647,6 +699,13 @@ class PublishMachine(
|
||||
}
|
||||
|
||||
private suspend fun doDone() {
|
||||
if (sharedSession != null) {
|
||||
sharedSession?.markUnknown("缺少明确作品核对回执")
|
||||
TaskStatusBus.status("共享发布回执待核对,素材与额度已保留")
|
||||
go(Phase.FAILED)
|
||||
svc.stopAutomation()
|
||||
return
|
||||
}
|
||||
// 对照原 m2():BACK 退出发布页 → 删除本地素材 → 进度计数 → 启动休息
|
||||
log("收到成功回执,开始收尾(删素材 + 计数 + 休息)")
|
||||
svc.gestures.back() // performGlobalAction(BACK) 退出发布页
|
||||
@@ -673,6 +732,17 @@ class PublishMachine(
|
||||
}
|
||||
|
||||
private suspend fun doFailed() {
|
||||
sharedSession?.let { context ->
|
||||
context.markUnknown("发布流程中断,等待核对")
|
||||
log("共享发布已暂停;提交日志和素材保留")
|
||||
TaskStatusBus.status(context.reason.ifBlank { "共享发布已暂停,素材已保留" })
|
||||
title = ""
|
||||
mediaUri = ""
|
||||
eligibilityCheck = null
|
||||
sharedSession = null
|
||||
reset()
|
||||
return
|
||||
}
|
||||
log("发布失败,清理任务态")
|
||||
// ⚠️ 2026-10-30 第一性审计修复:失败也**删素材** ——
|
||||
// 任务不重试,已下载文件留着就是泄漏(对照原 f0 清理链)。
|
||||
@@ -698,6 +768,24 @@ class PublishMachine(
|
||||
reset()
|
||||
}
|
||||
|
||||
private suspend fun payloadFingerprint(): String = withContext(Dispatchers.IO) {
|
||||
val digest = java.security.MessageDigest.getInstance("SHA-256")
|
||||
digest.update(title.toByteArray(Charsets.UTF_8))
|
||||
digest.update(0.toByte())
|
||||
digest.update(declaration.toByteArray(Charsets.UTF_8))
|
||||
digest.update(0.toByte())
|
||||
java.io.File(mediaUri).inputStream().use { input ->
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
while (true) {
|
||||
kotlin.coroutines.coroutineContext.ensureActive()
|
||||
val count = input.read(buffer)
|
||||
if (count < 0) break
|
||||
digest.update(buffer, 0, count)
|
||||
}
|
||||
}
|
||||
digest.digest().joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** 回执等待上限(原 publish_timeout 默认 30 分钟) */
|
||||
private const val RECEIPT_TIMEOUT_MS = 30L * 60L * 1000L
|
||||
|
||||
@@ -72,7 +72,7 @@ class LaneScheduler(private val service: HaoRuiAccessibilityService) {
|
||||
}
|
||||
|
||||
/** 启动全部车道 */
|
||||
fun start() {
|
||||
@Synchronized fun start() {
|
||||
autoWanted = true
|
||||
if (isRunning) return
|
||||
if (!service.checkVersionGate()) {
|
||||
@@ -85,7 +85,7 @@ class LaneScheduler(private val service: HaoRuiAccessibilityService) {
|
||||
}
|
||||
|
||||
/** 启动指定车道 */
|
||||
fun start(lane: Lane) {
|
||||
@Synchronized fun start(lane: Lane) {
|
||||
autoWanted = true
|
||||
if (lane in running) return
|
||||
if (!service.checkVersionGate()) return
|
||||
@@ -100,7 +100,7 @@ class LaneScheduler(private val service: HaoRuiAccessibilityService) {
|
||||
* GO_MY 悬停 → isWorking 恒 true → 之后启动任务 COLLECT 永久让路。
|
||||
* 不能用 [start]:它会置 autoWanted=true,自愈监控误判停摆把全部车道拉起。
|
||||
*/
|
||||
fun startLaneOnly(lane: Lane) {
|
||||
@Synchronized fun startLaneOnly(lane: Lane) {
|
||||
if (lane in running) return
|
||||
if (!service.checkVersionGate()) return
|
||||
schedule(lane)
|
||||
@@ -112,7 +112,7 @@ class LaneScheduler(private val service: HaoRuiAccessibilityService) {
|
||||
* ⚠️ 不清除 [autoWanted] —— 意愿由 [clearIntent] 单独管理,
|
||||
* 否则 `onInterrupt` 里的 stopAll()+start() 会误伤恢复链。
|
||||
*/
|
||||
fun stopAll() {
|
||||
@Synchronized fun stopAll() {
|
||||
jobs.values.forEach { runCatching { it.cancel() } }
|
||||
jobs.clear()
|
||||
running.clear()
|
||||
@@ -121,14 +121,14 @@ class LaneScheduler(private val service: HaoRuiAccessibilityService) {
|
||||
}
|
||||
|
||||
/** 停止单条车道 */
|
||||
fun stop(lane: Lane) {
|
||||
@Synchronized fun stop(lane: Lane) {
|
||||
jobs.remove(lane)?.let { runCatching { it.cancel() } }
|
||||
running.remove(lane)
|
||||
if (running.isEmpty()) isRunning = false
|
||||
}
|
||||
|
||||
/** 清除「应该在跑」的意愿(用户主动停止时调用,自愈监控据此不再拉起) */
|
||||
fun clearIntent() {
|
||||
@Synchronized fun clearIntent() {
|
||||
autoWanted = false
|
||||
}
|
||||
|
||||
@@ -136,7 +136,7 @@ class LaneScheduler(private val service: HaoRuiAccessibilityService) {
|
||||
* 强制重启:不管当前 [isRunning] 状态如何,一律重建全部车道。
|
||||
* 供自愈监控在「意外停摆」时调用(`start()` 遇 isRunning=true 会直接返回,救不了)。
|
||||
*/
|
||||
fun forceRestart() {
|
||||
@Synchronized fun forceRestart() {
|
||||
if (!autoWanted) {
|
||||
RunLogger.w(TAG, "forceRestart 跳过:当前意愿为关,视为用户主动停止")
|
||||
return
|
||||
@@ -151,6 +151,7 @@ class LaneScheduler(private val service: HaoRuiAccessibilityService) {
|
||||
|
||||
/** 某车道已跑过的节拍数(用于退出条件判定与自愈监控) */
|
||||
fun tickOf(lane: Lane): Long = ticks[lane] ?: 0L
|
||||
fun isScheduled(lane: Lane): Boolean = lane in running
|
||||
|
||||
/** 柦车道上一拍的时间戳(诊断用) */
|
||||
fun lastTickOf(lane: Lane): Long = lastTickMs[lane] ?: 0L
|
||||
|
||||
@@ -8,6 +8,7 @@ import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import com.haorui.app.automation.RunLogger
|
||||
import com.haorui.app.data.model.AppConfig
|
||||
import com.haorui.app.crossplatform.model.CrossPlatformConfigCodec
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
@@ -41,7 +42,7 @@ class ConfigRepository(private val context: Context) {
|
||||
/** 整份覆盖写入 */
|
||||
suspend fun save(cfg: AppConfig) {
|
||||
context.configStore.edit { prefs ->
|
||||
prefs[keyConfig] = json.encodeToString(AppConfig.serializer(), cfg)
|
||||
prefs[keyConfig] = json.encodeToString(AppConfig.serializer(), cfg.copy(crossPlatform = cfg.crossPlatform.normalized()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,7 +94,7 @@ class ConfigRepository(private val context: Context) {
|
||||
segment = out.segment.copy(dailyTotal = 28),
|
||||
)
|
||||
}
|
||||
return out
|
||||
return out.copy(crossPlatform = out.crossPlatform.normalized())
|
||||
}
|
||||
|
||||
private val migratedLogged = java.util.concurrent.atomic.AtomicBoolean(false)
|
||||
@@ -188,7 +189,7 @@ class ConfigRepository(private val context: Context) {
|
||||
"browse_stay_max" to c.browse.stayMaxSec.toString(),
|
||||
|
||||
"collect_mode" to c.collectMode,
|
||||
)
|
||||
) + CrossPlatformConfigCodec.toFlatMap(c.crossPlatform)
|
||||
|
||||
private fun buildFromExportMap(m: Map<String, String>): AppConfig {
|
||||
fun s(k: String, d: String) = m[k] ?: d
|
||||
@@ -282,6 +283,7 @@ class ConfigRepository(private val context: Context) {
|
||||
stayMaxSec = i("browse_stay_max", d.browse.stayMaxSec),
|
||||
),
|
||||
collectMode = s("collect_mode", d.collectMode),
|
||||
crossPlatform = CrossPlatformConfigCodec.fromFlatMap(m),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.haorui.app.data.model
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
import com.haorui.app.crossplatform.model.CrossPlatformConfig
|
||||
|
||||
/**
|
||||
* 浩瑞配置模型。集中维护采集、发布、互动与服务参数,保留扁平配置导入导出的键名兼容。
|
||||
@@ -153,6 +154,7 @@ data class AppConfig(
|
||||
val ai: AiConfig = AiConfig(),
|
||||
val browse: BrowseConfig = BrowseConfig(),
|
||||
val collectMode: String = CollectMode.TOUTIAO.name,
|
||||
val crossPlatform: CrossPlatformConfig = CrossPlatformConfig(),
|
||||
) {
|
||||
companion object {
|
||||
const val PRESET_VERSION = "haorui-0.1.0"
|
||||
|
||||
@@ -179,15 +179,17 @@ object CreditGateRunner {
|
||||
service: HaoRuiAccessibilityService,
|
||||
region: Rect?,
|
||||
): Int? {
|
||||
val ticket = service.tryEnterCreditForeground() ?: return null
|
||||
service.frontGuard.creditNavigating = true
|
||||
try {
|
||||
return withOverlayHidden {
|
||||
if (!service.foregroundCoordinator.isCurrent(ticket)) return@withOverlayHidden null
|
||||
val capturer = ScreenCapturer(service)
|
||||
// 快路径:当前屏已是信用分页(重复检查/误入时省导航)
|
||||
var score = CreditScoreReader.readFromScreen(capturer, region)
|
||||
if (score == null) {
|
||||
RunLogger.i(TAG, "当前屏未识别到信用分,导航至信用分页(我的→创作中心→全部服务→处罚中心)")
|
||||
if (navigateToCreditPage(service)) {
|
||||
if (navigateToCreditPage(service, ticket)) {
|
||||
score = CreditScoreReader.readFromScreen(capturer, region)
|
||||
} else {
|
||||
RunLogger.w(TAG, "信用分页导航失败(页面改版或定位失败),按 fail-open 放行")
|
||||
@@ -197,6 +199,7 @@ object CreditGateRunner {
|
||||
}
|
||||
} finally {
|
||||
service.frontGuard.creditNavigating = false
|
||||
service.foregroundCoordinator.release(ticket)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,20 +210,21 @@ object CreditGateRunner {
|
||||
* (如视频详情页,底部 tab 不可见)→ back 退到有 tab 的页面再找。
|
||||
* @return 是否走完全部四跳
|
||||
*/
|
||||
private suspend fun navigateToCreditPage(service: HaoRuiAccessibilityService): Boolean {
|
||||
private suspend fun navigateToCreditPage(service: HaoRuiAccessibilityService, ticket: com.haorui.app.crossplatform.schedule.ForegroundCoordinator.Ticket): Boolean {
|
||||
if (!service.foregroundCoordinator.isCurrent(ticket)) return false
|
||||
// 前台必须是头条(对照 InteractMachine.doGoMy 同款语义)
|
||||
if (service.currentPackage() != Targets.TOUTIAO_PKG) {
|
||||
RunLogger.i(TAG, "前台非头条(pkg=${service.currentPackage()}),先拉起头条")
|
||||
service.launchApp(Targets.TOUTIAO_PKG)
|
||||
delay(2500)
|
||||
}
|
||||
if (!tapTarget(service, ToutiaoSelectors.TXT_ME, backOnFail = true, preferBottom = true)) return false
|
||||
if (!tapTarget(service, ticket, ToutiaoSelectors.TXT_ME, backOnFail = true, preferBottom = true)) return false
|
||||
delay(1500)
|
||||
if (!tapTarget(service, TXT_CREATION_CENTER)) return false
|
||||
if (!tapTarget(service, ticket, TXT_CREATION_CENTER)) return false
|
||||
delay(1500)
|
||||
if (!tapTarget(service, TXT_ALL_SERVICES)) return false
|
||||
if (!tapTarget(service, ticket, TXT_ALL_SERVICES)) return false
|
||||
delay(1500)
|
||||
if (!tapTarget(service, TXT_PENALTY_CENTER)) return false
|
||||
if (!tapTarget(service, ticket, TXT_PENALTY_CENTER)) return false
|
||||
delay(2000) // 等信用分页渲染(Lynx)
|
||||
return true
|
||||
}
|
||||
@@ -232,14 +236,17 @@ object CreditGateRunner {
|
||||
*/
|
||||
private suspend fun tapTarget(
|
||||
service: HaoRuiAccessibilityService,
|
||||
ticket: com.haorui.app.crossplatform.schedule.ForegroundCoordinator.Ticket,
|
||||
label: String,
|
||||
backOnFail: Boolean = false,
|
||||
preferBottom: Boolean = false,
|
||||
): Boolean {
|
||||
repeat(3) { attempt ->
|
||||
if (!service.foregroundCoordinator.isCurrent(ticket)) return false
|
||||
// back 兜底从第 2 次开始:首跳失败可能是页面未渲染完(不应急于退页)
|
||||
if (attempt > 0) {
|
||||
if (backOnFail) {
|
||||
if (!service.foregroundCoordinator.isCurrent(ticket)) return false
|
||||
service.gestures.back()
|
||||
delay(1200) // 等页面退出动画
|
||||
} else {
|
||||
@@ -252,6 +259,10 @@ object CreditGateRunner {
|
||||
NodeLocator.byText(it, label) ?: NodeLocator.byTextContains(it, label)
|
||||
}
|
||||
if (node != null) {
|
||||
if (!service.foregroundCoordinator.isCurrent(ticket)) {
|
||||
node.recycle()
|
||||
return false
|
||||
}
|
||||
val ok = service.gestures.tapNode(node)
|
||||
runCatching { node.recycle() }
|
||||
if (ok) {
|
||||
@@ -260,7 +271,7 @@ object CreditGateRunner {
|
||||
}
|
||||
}
|
||||
// ② OCR boundingBox 定位(Lynx 页无树节点,文字仍在像素里)
|
||||
if (tapByOcr(service, label, preferBottom)) return true
|
||||
if (tapByOcr(service, ticket, label, preferBottom)) return true
|
||||
RunLogger.w(TAG, "「$label」定位失败(第 ${attempt + 1}/3 次)")
|
||||
}
|
||||
return false
|
||||
@@ -278,6 +289,7 @@ object CreditGateRunner {
|
||||
*/
|
||||
private suspend fun tapByOcr(
|
||||
service: HaoRuiAccessibilityService,
|
||||
ticket: com.haorui.app.crossplatform.schedule.ForegroundCoordinator.Ticket,
|
||||
label: String,
|
||||
preferBottom: Boolean = false,
|
||||
): Boolean {
|
||||
@@ -331,6 +343,7 @@ object CreditGateRunner {
|
||||
TAG,
|
||||
"OCR 定位「$label」@$cx,$cy(质量级=${best.quality} 行内精修=${best.refinedCx != null} bbox=${best.box.flattenToString()})",
|
||||
)
|
||||
if (!service.foregroundCoordinator.isCurrent(ticket)) return false
|
||||
return service.gestures.tapAt(cx, cy)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,11 @@ import com.haorui.app.data.model.ResetConfig
|
||||
import com.haorui.app.data.model.ToutiaoConfig
|
||||
import java.time.Instant
|
||||
import java.time.LocalTime
|
||||
import java.time.ZoneId
|
||||
import java.time.Clock
|
||||
import com.haorui.app.crossplatform.model.AccountQuotaSnapshot
|
||||
import com.haorui.app.crossplatform.model.LegacyBudgetState
|
||||
import com.haorui.app.crossplatform.model.CrossPlatformConfig
|
||||
import com.haorui.app.crossplatform.model.CrossSubmissionBudget
|
||||
|
||||
/**
|
||||
* 发布配额管理器。管理每日总量、时段额度、休息与重置快照。
|
||||
@@ -16,6 +20,7 @@ class QuotaManager(
|
||||
segmentConfig: SegmentConfig,
|
||||
resetConfig: ResetConfig,
|
||||
toutiaoConfig: ToutiaoConfig = ToutiaoConfig(),
|
||||
private val clock: Clock = Clock.systemDefaultZone(),
|
||||
) {
|
||||
companion object {
|
||||
private const val TAG = "HaoRui-Quota"
|
||||
@@ -112,7 +117,7 @@ class QuotaManager(
|
||||
val currentSegment: Int
|
||||
get() {
|
||||
// ⚠️ 二轮审计:两次取时钟会跨边界错归时段 → 一次取 now
|
||||
val now = LocalTime.now()
|
||||
val now = LocalTime.now(clock)
|
||||
val minutes = now.hour * 60 + now.minute
|
||||
return when {
|
||||
minutes < 360 -> 3 // 00-06
|
||||
@@ -144,7 +149,7 @@ class QuotaManager(
|
||||
}
|
||||
|
||||
// 休息期检查(两种模式统一生效)
|
||||
val now = System.currentTimeMillis()
|
||||
val now = clock.millis()
|
||||
if (now < restUntilMs) {
|
||||
return false
|
||||
}
|
||||
@@ -196,7 +201,7 @@ class QuotaManager(
|
||||
@Synchronized
|
||||
fun waitSeconds(): Long {
|
||||
checkDailyReset()
|
||||
val now = System.currentTimeMillis()
|
||||
val now = clock.millis()
|
||||
return maxOf(0, (restUntilMs - now) / 1000)
|
||||
}
|
||||
|
||||
@@ -212,12 +217,12 @@ class QuotaManager(
|
||||
val seg = currentSegment
|
||||
segmentCounts[seg]++
|
||||
dailyCount++
|
||||
lastPublishAtMs = System.currentTimeMillis()
|
||||
lastPublishAtMs = clock.millis()
|
||||
|
||||
// 设置随机休息期(对齐原 X2():分时段取 segment_N_rest_min/max,否则 rest_min/rest_max)
|
||||
val restRange = restRange()
|
||||
val restSec = (restRange.first..restRange.second).random()
|
||||
restUntilMs = System.currentTimeMillis() + restSec * 1000L
|
||||
restUntilMs = clock.millis() + restSec * 1000L
|
||||
|
||||
log("发布 #$dailyCount (时段${seg + 1}: ${segmentCounts[seg]}/${segmentQuota(seg)}), 休息 ${restSec}s")
|
||||
onRecorded?.invoke(dailyCount)
|
||||
@@ -239,7 +244,7 @@ class QuotaManager(
|
||||
fun initDaily(count: Int) {
|
||||
dailyCount = maxOf(0, count)
|
||||
currentDate = effectiveDate()
|
||||
lastResetAtMs = lastResetPointMs(System.currentTimeMillis())
|
||||
lastResetAtMs = lastResetPointMs(clock.millis())
|
||||
log("发布计数已恢复: $dailyCount/$dailyTotal")
|
||||
}
|
||||
|
||||
@@ -279,7 +284,7 @@ class QuotaManager(
|
||||
*/
|
||||
@Synchronized
|
||||
fun snapshotState(): String {
|
||||
val remainRest = maxOf(0L, (restUntilMs - System.currentTimeMillis()) / 1000)
|
||||
val remainRest = maxOf(0L, (restUntilMs - clock.millis()) / 1000)
|
||||
return segmentCounts.joinToString(",") + "|" + remainRest + "|" + lastResetAtMs
|
||||
}
|
||||
|
||||
@@ -300,12 +305,12 @@ class QuotaManager(
|
||||
}
|
||||
parts.getOrNull(1)?.toLongOrNull()?.let { remainSec ->
|
||||
if (remainSec > 0) {
|
||||
restUntilMs = System.currentTimeMillis() + remainSec * 1000L
|
||||
restUntilMs = clock.millis() + remainSec * 1000L
|
||||
log("休息期已恢复: 剩余 ${remainSec}s")
|
||||
}
|
||||
}
|
||||
lastResetAtMs = parts.getOrNull(2)?.toLongOrNull()
|
||||
?.takeIf { it > 0 } ?: lastResetPointMs(System.currentTimeMillis())
|
||||
?.takeIf { it > 0 } ?: lastResetPointMs(clock.millis())
|
||||
}
|
||||
|
||||
// ── 内部逻辑 ──────────────────────────────────────────────
|
||||
@@ -319,9 +324,8 @@ class QuotaManager(
|
||||
* 与日界自动重置共用同一标记,天然去重(无双触发竞态)。
|
||||
* - 重置动作链(信用分检查/每日互动)经 [onDailyReset] 回调移交服务层。
|
||||
*/
|
||||
private fun checkDailyReset() {
|
||||
private fun checkDailyReset(nowMs: Long = clock.millis()) {
|
||||
if (!resetArmed) return // 启动竞态防护:restoreRunState 锚定前不判定
|
||||
val nowMs = System.currentTimeMillis()
|
||||
val rp = lastResetPointMs(nowMs)
|
||||
if (rp > lastResetAtMs) {
|
||||
lastResetAtMs = rp
|
||||
@@ -347,7 +351,7 @@ class QuotaManager(
|
||||
* 重置触发判定与快照锚定共用此口径,保证「跨重启不误清、不漏重置」。
|
||||
*/
|
||||
private fun lastResetPointMs(nowMs: Long): Long {
|
||||
val zone = ZoneId.systemDefault()
|
||||
val zone = clock.zone
|
||||
val now = Instant.ofEpochMilli(nowMs).atZone(zone)
|
||||
var rp = now.toLocalDate().atTime(boundaryTime()).atZone(zone)
|
||||
if (rp.toInstant().toEpochMilli() > nowMs) {
|
||||
@@ -364,8 +368,46 @@ class QuotaManager(
|
||||
* 默认重置点(00:00 / 分时段 06:00)下与原 effectiveDate() 行为完全一致。
|
||||
*/
|
||||
private fun effectiveDate(): String {
|
||||
val ms = lastResetPointMs(System.currentTimeMillis())
|
||||
return Instant.ofEpochMilli(ms).atZone(ZoneId.systemDefault()).toLocalDate().toString()
|
||||
val ms = lastResetPointMs(clock.millis())
|
||||
return Instant.ofEpochMilli(ms).atZone(clock.zone).toLocalDate().toString()
|
||||
}
|
||||
|
||||
@Synchronized fun accountSnapshot(): AccountQuotaSnapshot {
|
||||
check(resetArmed) { "旧配额恢复尚未完成" }
|
||||
val now = clock.millis()
|
||||
checkDailyReset(now)
|
||||
val local = Instant.ofEpochMilli(now).atZone(clock.zone)
|
||||
val start = lastResetPointMs(now)
|
||||
val nextReset = Instant.ofEpochMilli(start).atZone(clock.zone).plusDays(1).toInstant().toEpochMilli()
|
||||
val slot = local.hour / 6
|
||||
val segment = (slot + 3) % 4
|
||||
val day = Instant.ofEpochMilli(start).atZone(clock.zone).toLocalDate().toString()
|
||||
val nextWindow = local.toLocalDate().atStartOfDay(clock.zone).plusHours((slot + 1) * 6L).toInstant().toEpochMilli()
|
||||
return AccountQuotaSnapshot(now, if (segmentConfig.enabled) minOf(nextReset, nextWindow) else nextReset,
|
||||
day, dailyTotal, dailyCount, "$day:$segment", if (segmentConfig.enabled) segmentQuota(segment) else null,
|
||||
segmentCounts[segment], segmentCounts.toList(), restUntilMs)
|
||||
}
|
||||
|
||||
@Synchronized fun sharedRestUntil(): Long {
|
||||
val range = restRange()
|
||||
return clock.millis() + (range.first.coerceAtLeast(0)..range.second.coerceAtLeast(0)).random().toLong() * 1000L
|
||||
}
|
||||
|
||||
@Synchronized fun submissionBudget(config: CrossPlatformConfig): CrossSubmissionBudget {
|
||||
val snapshot = accountSnapshot()
|
||||
val normalized = config.normalized()
|
||||
return CrossSubmissionBudget(snapshot.dayKey, snapshot.totalLimit, snapshot.legacyUsed,
|
||||
normalized.articleDailyLimit, normalized.videoDailyLimit, snapshot, normalized.publishGapMinutes * 60_000L)
|
||||
}
|
||||
|
||||
@Synchronized fun mergeSharedLegacyState(state: LegacyBudgetState) {
|
||||
checkDailyReset()
|
||||
restUntilMs = maxOf(restUntilMs, state.restUntilMs)
|
||||
if (state.dayKey == effectiveDate()) {
|
||||
dailyCount = maxOf(dailyCount, state.used)
|
||||
for (segment in 0..3) segmentCounts[segment] = maxOf(segmentCounts[segment], state.windows["${state.dayKey}:$segment"] ?: 0)
|
||||
}
|
||||
onRecorded?.invoke(dailyCount)
|
||||
}
|
||||
|
||||
/** 取指定时段的配额 */
|
||||
|
||||
@@ -188,8 +188,20 @@ class RecoveryChain(
|
||||
* @return 恢复动作数量(0 = 一切正常)
|
||||
*/
|
||||
fun runOnce(): Int {
|
||||
// 新来源持有整条采集会话期间,恢复链不能把来源页面当成错误页面拉回。
|
||||
if (service.foregroundCoordinator.hasSourceOwner()) return 0
|
||||
val ticket = service.foregroundCoordinator.tryEnterLegacy("RECOVERY") ?: return 0
|
||||
try {
|
||||
return runChecks(ticket)
|
||||
} finally {
|
||||
service.foregroundCoordinator.release(ticket)
|
||||
}
|
||||
}
|
||||
|
||||
private fun runChecks(ticket: com.haorui.app.crossplatform.schedule.ForegroundCoordinator.Ticket): Int {
|
||||
var recoveryCount = 0
|
||||
for (action in actions) {
|
||||
if (!service.foregroundCoordinator.isCurrent(ticket)) break
|
||||
val hasIssue = try {
|
||||
action.detector()
|
||||
} catch (e: Exception) {
|
||||
@@ -197,6 +209,7 @@ class RecoveryChain(
|
||||
continue
|
||||
}
|
||||
if (!hasIssue) continue
|
||||
if (!service.foregroundCoordinator.isCurrent(ticket)) break
|
||||
|
||||
RunLogger.w(TAG, "发现异常: ${action.name}")
|
||||
if (!action.recoverable) {
|
||||
|
||||
@@ -3,6 +3,8 @@ package com.haorui.app.ui.nav
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Home
|
||||
import androidx.compose.material.icons.filled.AutoAwesome
|
||||
import androidx.compose.material.icons.filled.Assignment
|
||||
import androidx.compose.material.icons.filled.Person
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
@@ -19,12 +21,14 @@ import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.navigation.NavGraph.Companion.findStartDestination
|
||||
@@ -34,6 +38,13 @@ import androidx.navigation.compose.currentBackStackEntryAsState
|
||||
import androidx.navigation.compose.rememberNavController
|
||||
import com.haorui.app.automation.HaoRuiAccessibilityService
|
||||
import com.haorui.app.automation.Targets
|
||||
import com.haorui.app.crossplatform.data.CrossPublishTaskStore
|
||||
import com.haorui.app.crossplatform.ui.CrossAutomationScreen
|
||||
import com.haorui.app.crossplatform.ui.CrossTasksScreen
|
||||
import com.haorui.app.crossplatform.ui.SourcesScreen
|
||||
import com.haorui.app.crossplatform.ui.TopicFiltersScreen
|
||||
import com.haorui.app.crossplatform.ui.TopicsScreen
|
||||
import com.haorui.app.crossplatform.ui.rememberSourceVersions
|
||||
import com.haorui.app.data.model.AppConfig
|
||||
import com.haorui.app.data.model.CollectMode
|
||||
import com.haorui.app.ui.screens.A11yScreen
|
||||
@@ -52,6 +63,11 @@ import kotlinx.coroutines.launch
|
||||
object Routes {
|
||||
const val HOME = "home"
|
||||
const val COLLECT = "collect"
|
||||
const val TOPICS = "topics"
|
||||
const val TASKS = "tasks"
|
||||
const val CROSS_SOURCES = "cross_sources"
|
||||
const val CROSS_FILTERS = "cross_filters"
|
||||
const val CROSS_AUTOMATION = "cross_automation"
|
||||
const val INTERACT = "interact"
|
||||
const val MINE = "mine"
|
||||
const val TOUTIAO = "toutiao"
|
||||
@@ -65,6 +81,11 @@ object Routes {
|
||||
val titles = mapOf(
|
||||
HOME to "浩瑞",
|
||||
COLLECT to "采集",
|
||||
TOPICS to "热点",
|
||||
TASKS to "任务",
|
||||
CROSS_SOURCES to "来源 App 管理",
|
||||
CROSS_FILTERS to "选题筛选",
|
||||
CROSS_AUTOMATION to "自动化设置",
|
||||
INTERACT to "互动",
|
||||
MINE to "我的",
|
||||
TOUTIAO to "头条采集设置",
|
||||
@@ -90,12 +111,12 @@ object Routes {
|
||||
)
|
||||
|
||||
/** 底部 tab */
|
||||
val tabs = listOf(HOME, COLLECT, INTERACT, MINE)
|
||||
val tabs = listOf(HOME, TOPICS, TASKS, INTERACT, MINE)
|
||||
|
||||
/** 路由 → 所属 tab(用于返回键回落) */
|
||||
fun tabOf(route: String): String = when (route) {
|
||||
TOUTIAO, BAIDU -> COLLECT
|
||||
API, BROWSE, LOGS, A11Y -> MINE
|
||||
TOUTIAO, BAIDU, COLLECT, API, BROWSE, LOGS, A11Y, CROSS_AUTOMATION -> MINE
|
||||
CROSS_SOURCES, CROSS_FILTERS -> TOPICS
|
||||
else -> route
|
||||
}
|
||||
}
|
||||
@@ -104,17 +125,24 @@ private data class TabDef(val route: String, val label: String, val icon: ImageV
|
||||
|
||||
private val tabDefs = listOf(
|
||||
TabDef(Routes.HOME, "首页", Icons.Filled.Home),
|
||||
TabDef(Routes.COLLECT, "采集", Icons.Filled.PlayArrow),
|
||||
TabDef(Routes.TOPICS, "热点", Icons.Filled.AutoAwesome),
|
||||
TabDef(Routes.TASKS, "任务", Icons.Filled.Assignment),
|
||||
TabDef(Routes.INTERACT, "互动", Icons.Filled.Settings),
|
||||
TabDef(Routes.MINE, "我的", Icons.Filled.Person),
|
||||
)
|
||||
|
||||
/**
|
||||
* 浩瑞主壳:顶栏 + 内容 + 底部 4 tab
|
||||
* 浩瑞主壳:顶栏 + 内容 + 底部五栏导航。
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun HaoRuiApp(config: AppConfig, onConfigChange: (AppConfig) -> Unit) {
|
||||
val context = LocalContext.current.applicationContext
|
||||
val taskStore = remember(context) { CrossPublishTaskStore.get(context) }
|
||||
val crossTasks by taskStore.tasks.collectAsState()
|
||||
val crossTasksLoaded by taskStore.isLoaded.collectAsState()
|
||||
val crossTasksError by taskStore.loadError.collectAsState()
|
||||
val sourceVersions = rememberSourceVersions()
|
||||
val nav = rememberNavController()
|
||||
val snackbar = remember { SnackbarHostState() }
|
||||
val scope = rememberCoroutineScope()
|
||||
@@ -171,7 +199,7 @@ fun HaoRuiApp(config: AppConfig, onConfigChange: (AppConfig) -> Unit) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
// ⚠️ 2026-10-29:去掉顶栏标题文字(用户要求)。
|
||||
// tab 页(首页/采集/互动/我的)完全无顶栏;
|
||||
// 主导航页完全无顶栏;
|
||||
// 子页只保留返回箭头,不显示任何标题文字。
|
||||
if (!onTab) {
|
||||
CenterAlignedTopAppBar(
|
||||
@@ -189,7 +217,7 @@ fun HaoRuiApp(config: AppConfig, onConfigChange: (AppConfig) -> Unit) {
|
||||
NavigationBar(containerColor = MaterialTheme.colorScheme.surface) {
|
||||
tabDefs.forEach { tab ->
|
||||
NavigationBarItem(
|
||||
selected = currentRoute == tab.route,
|
||||
selected = Routes.tabOf(currentRoute) == tab.route,
|
||||
onClick = {
|
||||
nav.navigate(tab.route) {
|
||||
popUpTo(nav.graph.findStartDestination().id) { saveState = true }
|
||||
@@ -217,8 +245,25 @@ fun HaoRuiApp(config: AppConfig, onConfigChange: (AppConfig) -> Unit) {
|
||||
onToggleRun = ::setRunning,
|
||||
onNavigate = { nav.navigate(it) },
|
||||
onConfigChange = onConfigChange,
|
||||
crossTasks = crossTasks,
|
||||
crossTasksLoaded = crossTasksLoaded,
|
||||
)
|
||||
}
|
||||
composable(Routes.TOPICS) {
|
||||
TopicsScreen(config, crossTasks, crossTasksLoaded, crossTasksError) { nav.navigate(it) }
|
||||
}
|
||||
composable(Routes.TASKS) {
|
||||
CrossTasksScreen(crossTasks, crossTasksLoaded, crossTasksError) { nav.navigate(it) }
|
||||
}
|
||||
composable(Routes.CROSS_SOURCES) {
|
||||
SourcesScreen(config, sourceVersions, onConfigChange, ::toast)
|
||||
}
|
||||
composable(Routes.CROSS_FILTERS) {
|
||||
TopicFiltersScreen(config, onConfigChange, ::toast)
|
||||
}
|
||||
composable(Routes.CROSS_AUTOMATION) {
|
||||
CrossAutomationScreen(config, onConfigChange, { nav.navigate(it) }, ::toast)
|
||||
}
|
||||
composable(Routes.COLLECT) {
|
||||
CollectScreen(
|
||||
config = config,
|
||||
|
||||
@@ -33,6 +33,8 @@ import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.haorui.app.data.model.AppConfig
|
||||
import com.haorui.app.data.model.CollectMode
|
||||
import com.haorui.app.crossplatform.model.CrossPublishTask
|
||||
import com.haorui.app.crossplatform.ui.CrossWorkspaceOverview
|
||||
import com.haorui.app.ui.components.CheckRow
|
||||
import com.haorui.app.ui.components.NumberField
|
||||
import com.haorui.app.ui.components.DropdownField
|
||||
@@ -69,6 +71,8 @@ fun HomeScreen(
|
||||
onToggleRun: (Boolean) -> Unit,
|
||||
onNavigate: (String) -> Unit,
|
||||
onConfigChange: (AppConfig) -> Unit,
|
||||
crossTasks: List<CrossPublishTask> = emptyList(),
|
||||
crossTasksLoaded: Boolean = false,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
@@ -78,7 +82,9 @@ fun HomeScreen(
|
||||
verticalArrangement = Arrangement.spacedBy(18.dp),
|
||||
) {
|
||||
|
||||
// ── ① 状态大卡:唯一的启动/停止入口 ──────────────
|
||||
CrossWorkspaceOverview(config, crossTasks, crossTasksLoaded, onNavigate)
|
||||
|
||||
// 唯一的既有视频启动/停止入口。
|
||||
RunStatusCard(
|
||||
running = running,
|
||||
config = config,
|
||||
@@ -91,7 +97,7 @@ fun HomeScreen(
|
||||
title = "开始使用前,请先完成这三步",
|
||||
steps = listOf(
|
||||
"在「我的」开启无障碍服务(必需)" to "a11y",
|
||||
"在「采集」设置采集参数" to "toutiao",
|
||||
"在「我的」进入既有视频采集设置" to "collect",
|
||||
"在「我的」配置大模型 Key(可选)" to "api",
|
||||
),
|
||||
onNavigate = onNavigate,
|
||||
@@ -149,8 +155,8 @@ private fun RunStatusCard(
|
||||
}
|
||||
|
||||
Text(
|
||||
text = if (running) "正在自动采集并发布内容。可锁屏等待,任务会继续执行。"
|
||||
else "点击下方按钮启动当日任务。启动前请确认已完成上方三步准备。",
|
||||
text = if (running) "头条视频任务正在运行,请保持手机解锁与页面可操作。"
|
||||
else "下方启动的是既有头条视频流程,请先确认采集参数、发布模式与无障碍连接。",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
@@ -223,7 +229,7 @@ private fun RunStatusCard(
|
||||
)
|
||||
|
||||
PrimaryButton(
|
||||
label = if (running) "停止任务" else "启动任务",
|
||||
label = if (running) "停止头条视频任务" else "启动头条视频任务",
|
||||
onClick = { onToggleRun(!running) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
danger = running,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.haorui.app.ui.screens
|
||||
|
||||
import com.haorui.app.crossplatform.ui.CrossSettingsEntries
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
@@ -10,6 +12,7 @@ import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
@@ -33,6 +36,7 @@ import androidx.compose.material.icons.Icons
|
||||
import com.haorui.app.ui.components.QuickAction
|
||||
import com.haorui.app.ui.components.FieldHelp
|
||||
import com.haorui.app.logging.LogExporter
|
||||
import kotlinx.coroutines.launch
|
||||
import com.haorui.app.ui.components.GuideBanner
|
||||
import com.haorui.app.ui.components.Section
|
||||
import com.haorui.app.ui.components.NumberField
|
||||
@@ -49,6 +53,7 @@ fun MineScreen(
|
||||
) {
|
||||
// 去重索引条数:从下载器实时读取,可被「清空」按钮更新
|
||||
val context = androidx.compose.ui.platform.LocalContext.current
|
||||
val cacheScope = androidx.compose.runtime.rememberCoroutineScope()
|
||||
var dedupCount by remember {
|
||||
mutableStateOf(
|
||||
com.haorui.app.automation.HaoRuiAccessibilityService.instance?.videoDownloader?.downloadedCount ?: 0
|
||||
@@ -59,6 +64,8 @@ fun MineScreen(
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(18.dp),
|
||||
) {
|
||||
CrossSettingsEntries(onNavigate)
|
||||
|
||||
Section(
|
||||
title = "系统设置",
|
||||
help = "影响任务能否正常运行的关键配置",
|
||||
@@ -111,9 +118,10 @@ fun MineScreen(
|
||||
onToast("已清空 $n 条去重记录")
|
||||
}, Modifier.weight(1f), danger = true)
|
||||
HaoRuiButton("清除下载缓存", {
|
||||
val dl = com.haorui.app.automation.HaoRuiAccessibilityService.instance?.videoDownloader
|
||||
val n = dl?.clearDownloadCache() ?: 0
|
||||
onToast("已删除 $n 个下载缓存文件")
|
||||
cacheScope.launch {
|
||||
val result = runCatching { com.haorui.app.automation.HaoRuiAccessibilityService.instance?.clearUnusedDownloadCache() ?: 0 }
|
||||
onToast(result.fold({ "已删除 $it 个下载缓存文件" }, { "缓存清理未完成,请稍后重试" }))
|
||||
}
|
||||
}, Modifier.weight(1f), danger = true)
|
||||
}
|
||||
FieldHelp("清空后已发内容可能被重复采集发布,请谨慎操作")
|
||||
@@ -326,6 +334,9 @@ fun A11yScreen(onToast: (String) -> Unit) {
|
||||
// 真实连接状态:来自无障碍服务单例(非写死假值)
|
||||
var connected by remember { mutableStateOf(com.haorui.app.automation.HaoRuiAccessibilityService.isConnected()) }
|
||||
var probeLog by remember { mutableStateOf("尚未运行探测。") }
|
||||
var accountService by remember { mutableStateOf(com.haorui.app.automation.HaoRuiAccessibilityService.instance) }
|
||||
val emptyAccountState = remember { kotlinx.coroutines.flow.MutableStateFlow("头条账号尚未核验") }
|
||||
val accountStatus by (accountService?.accountVerification ?: emptyAccountState).collectAsState()
|
||||
|
||||
val context = androidx.compose.ui.platform.LocalContext.current
|
||||
val lifecycleOwner = androidx.lifecycle.compose.LocalLifecycleOwner.current
|
||||
@@ -336,6 +347,7 @@ fun A11yScreen(onToast: (String) -> Unit) {
|
||||
val observer = androidx.lifecycle.LifecycleEventObserver { _, event ->
|
||||
if (event == androidx.lifecycle.Lifecycle.Event.ON_RESUME) {
|
||||
connected = com.haorui.app.automation.HaoRuiAccessibilityService.isConnected()
|
||||
accountService = com.haorui.app.automation.HaoRuiAccessibilityService.instance
|
||||
}
|
||||
}
|
||||
lifecycleOwner.lifecycle.addObserver(observer)
|
||||
@@ -373,6 +385,7 @@ fun A11yScreen(onToast: (String) -> Unit) {
|
||||
// 手动刷新兜底:ON_RESUME 万一未触发时使用
|
||||
HaoRuiButton("刷新连接状态", {
|
||||
connected = com.haorui.app.automation.HaoRuiAccessibilityService.isConnected()
|
||||
accountService = com.haorui.app.automation.HaoRuiAccessibilityService.instance
|
||||
onToast(if (connected) "无障碍服务已连接" else "无障碍服务未连接")
|
||||
}, Modifier.weight(1f))
|
||||
}
|
||||
@@ -380,6 +393,18 @@ fun A11yScreen(onToast: (String) -> Unit) {
|
||||
FieldHelp("开启步骤:点上方按钮 → 找到【浩瑞自动发布】→ 打开开关 → 返回本页")
|
||||
}
|
||||
}
|
||||
Section(title = "头条账号", help = "停止任务后核验当前登录账号") {
|
||||
StatusBanner(accountStatus, if (accountStatus.startsWith("已核验")) StatusLevel.OK else StatusLevel.NEUTRAL)
|
||||
HaoRuiButton("核验头条账号", {
|
||||
val service = com.haorui.app.automation.HaoRuiAccessibilityService.instance
|
||||
accountService = service
|
||||
onToast(when {
|
||||
service == null -> "请先开启浩瑞无障碍服务"
|
||||
service.verifyAccountSandbox() -> "正在核验头条账号"
|
||||
else -> "请先停止当前任务,再核验账号"
|
||||
})
|
||||
})
|
||||
}
|
||||
Section(title = "探测工具") {
|
||||
StatusBanner("仅限已核对的今日头条 18.3.0。只保存计数,不调用接口或发布。", StatusLevel.WARN)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
|
||||
Reference in New Issue
Block a user