Compare commits
2
Commits
b5ac4ca4d4
...
1dae7453be
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1dae7453be | ||
|
|
db850a78c8 |
@@ -0,0 +1,39 @@
|
||||
package com.haorui.app.crossplatform
|
||||
|
||||
import android.app.Instrumentation
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import com.haorui.app.MainActivity
|
||||
import java.net.URI
|
||||
import java.security.MessageDigest
|
||||
|
||||
/** 仅测试 APK:读取刚复制的头条主页链接形态,不授权账号或操作发布。 */
|
||||
internal object AccountClipboardProbe {
|
||||
fun read(instrumentation: Instrumentation): String = with(instrumentation) {
|
||||
val activity = startActivitySync(Intent(targetContext, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
waitForIdleSync()
|
||||
val deadline = System.nanoTime() + 5_000_000_000L
|
||||
while (!activity.hasWindowFocus() && System.nanoTime() < deadline) Thread.sleep(50)
|
||||
Thread.sleep(900)
|
||||
var raw = ""
|
||||
var metadata = ""
|
||||
runOnMainSync {
|
||||
val manager = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
val clip = manager.primaryClip
|
||||
raw = clip?.takeIf { it.itemCount == 1 }?.getItemAt(0)?.coerceToText(activity)?.toString().orEmpty()
|
||||
metadata = "focus=${activity.hasWindowFocus()}, items=${clip?.itemCount}, length=${raw.length}"
|
||||
}
|
||||
val candidate = Regex("https?://[^\\s]+", RegexOption.IGNORE_CASE).find(raw)?.value ?: return "No profile link ($metadata)"
|
||||
val uri = URI(candidate)
|
||||
val parts = uri.path.split('/').filter { it.isNotBlank() }
|
||||
val shape = parts.joinToString("/") { if (it.length > 16 || it.all(Char::isDigit)) "<id:${it.length}>" else it }
|
||||
val query = uri.rawQuery.orEmpty().split('&').filter { it.isNotBlank() }.joinToString(",") { part ->
|
||||
val p = part.split('=', limit = 2)
|
||||
"${p[0]}:${p.getOrElse(1) { "" }.length}:${p.getOrElse(1) { "" }.all(Char::isDigit)}"
|
||||
}
|
||||
if (uri.host !in setOf("www.toutiao.com", "m.toutiao.com", "toutiao.com")) return "Profile host: ${uri.scheme}://${uri.host}/$shape; query shape=$query"
|
||||
val digest = MessageDigest.getInstance("SHA-256").digest(uri.path.toByteArray()).joinToString("") { "%02x".format(it) }
|
||||
"Profile link: ${uri.scheme}://${uri.host}/$shape; pathSha256=$digest"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.haorui.app.crossplatform
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Instrumentation
|
||||
import android.content.Context
|
||||
import android.os.Bundle
|
||||
import org.junit.runner.JUnitCore
|
||||
|
||||
/** 无界面数据库回归,只使用独立临时目录,不读写真实任务库。 */
|
||||
class StoreInstrumentation : Instrumentation() {
|
||||
companion object { lateinit var appContext: Context }
|
||||
private var accountClipProbe = false
|
||||
override fun onCreate(arguments: Bundle?) { super.onCreate(arguments); accountClipProbe = arguments?.getString("probe") == "accountClip"; start() }
|
||||
override fun onStart() {
|
||||
appContext = targetContext
|
||||
try {
|
||||
if (accountClipProbe) {
|
||||
finish(Activity.RESULT_OK, Bundle().apply { putString("stream", "\n${AccountClipboardProbe.read(this@StoreInstrumentation)}\n") })
|
||||
return
|
||||
}
|
||||
val result = JUnitCore.runClasses(StoreTransactionTest::class.java)
|
||||
finish(if (result.wasSuccessful()) Activity.RESULT_OK else Activity.RESULT_CANCELED, Bundle().apply {
|
||||
putString("stream", "\nSQLite tests: ${result.runCount}, failures: ${result.failureCount}\n" + result.failures.joinToString("\n") { it.trace })
|
||||
})
|
||||
} catch (t: Throwable) {
|
||||
finish(Activity.RESULT_CANCELED, Bundle().apply { putString("stream", "Database test failed: ${t.stackTraceToString()}") })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
package com.haorui.app.crossplatform
|
||||
|
||||
import android.content.Context
|
||||
import android.content.ContextWrapper
|
||||
import android.database.DatabaseErrorHandler
|
||||
import android.database.sqlite.SQLiteDatabase
|
||||
import android.database.sqlite.SQLiteOpenHelper
|
||||
import com.haorui.app.crossplatform.data.CrossPublishTaskStore
|
||||
import com.haorui.app.crossplatform.model.*
|
||||
import com.haorui.app.crossplatform.publish.*
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.flow.first
|
||||
import org.junit.After
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
import java.util.UUID
|
||||
|
||||
class StoreTransactionTest {
|
||||
private lateinit var directory: File
|
||||
private lateinit var isolated: Context
|
||||
private lateinit var store: CrossPublishTaskStore
|
||||
private val stores = mutableListOf<CrossPublishTaskStore>()
|
||||
|
||||
@Before fun setUp() {
|
||||
directory = File(StoreInstrumentation.appContext.cacheDir, "store-test-${UUID.randomUUID()}").apply { mkdirs() }
|
||||
isolated = object : ContextWrapper(StoreInstrumentation.appContext) {
|
||||
override fun getApplicationContext(): Context = this
|
||||
override fun getDatabasePath(name: String) = File(directory, name)
|
||||
override fun openOrCreateDatabase(name: String, mode: Int, factory: SQLiteDatabase.CursorFactory?): SQLiteDatabase =
|
||||
SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), factory)
|
||||
override fun openOrCreateDatabase(name: String, mode: Int, factory: SQLiteDatabase.CursorFactory?, errorHandler: DatabaseErrorHandler?): SQLiteDatabase =
|
||||
SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name).path, factory, errorHandler)
|
||||
}
|
||||
store = openStore()
|
||||
}
|
||||
|
||||
// 反射仅存在于测试 APK,避免为测试在生产代码暴露数据库重定向入口。
|
||||
private fun openStore(): CrossPublishTaskStore = CrossPublishTaskStore::class.java
|
||||
.getDeclaredConstructor(Context::class.java).apply { isAccessible = true }
|
||||
.newInstance(isolated).also { stores.add(it) }
|
||||
|
||||
private fun closeStore(value: CrossPublishTaskStore) {
|
||||
val type = CrossPublishTaskStore::class.java
|
||||
(type.getDeclaredField("scope").apply { isAccessible = true }.get(value) as CoroutineScope).cancel()
|
||||
(type.getDeclaredField("helper").apply { isAccessible = true }.get(value) as SQLiteOpenHelper).close()
|
||||
stores.remove(value)
|
||||
}
|
||||
|
||||
@After fun tearDown() {
|
||||
stores.toList().forEach(::closeStore)
|
||||
check(directory.parentFile == StoreInstrumentation.appContext.cacheDir && directory.name.startsWith("store-test-"))
|
||||
directory.deleteRecursively()
|
||||
}
|
||||
|
||||
private fun task(id: String, event: String, generation: Long) = CrossPublishTask(
|
||||
id, "test-account", event, CrossContentKind.ARTICLE, "数据库回归内容", "zhihu", "https://www.zhihu.com/question/1",
|
||||
runGeneration = generation, publishedAtMs = System.currentTimeMillis() - 1000, expiresAtMs = System.currentTimeMillis() + 3_600_000,
|
||||
)
|
||||
private suspend fun ready(id: String, generation: Long) {
|
||||
assertTrue(store.enqueue(task(id, "event-$id", generation)))
|
||||
assertTrue(store.transition(id, CrossTaskState.DISCOVERED, CrossTaskState.FILTERED, generation))
|
||||
assertTrue(store.prepare(id, generation, "测试正文", "", "{\"source\":\"test-fixture\"}", "", "a".repeat(64)))
|
||||
assertTrue(store.transition(id, CrossTaskState.PREPARED, CrossTaskState.READY, generation))
|
||||
}
|
||||
private fun snapshot(total: Int = 2, used: Int = 0, windowLimit: Int? = null, windowUsed: Int = 0,
|
||||
day: String = "2026-11-13") : AccountQuotaSnapshot {
|
||||
val now = System.currentTimeMillis()
|
||||
return AccountQuotaSnapshot(now, now + 60_000, day, total, used, "$day:2", windowLimit, windowUsed, listOf(0, 0, windowUsed, 0), 0)
|
||||
}
|
||||
private fun budget(total: Int = 2, snapshot: AccountQuotaSnapshot = snapshot(total)) =
|
||||
CrossSubmissionBudget(snapshot.dayKey, total, snapshot.legacyUsed, 2, 2, snapshot)
|
||||
private suspend fun intent(id: String, generation: Long): CrossSubmissionAttempt {
|
||||
ready(id, generation)
|
||||
assertEquals(id, store.claimNextReady(generation, "test-account")!!.id)
|
||||
assertTrue(store.bindLegacyAccount("test-account", generation, snapshot()))
|
||||
return store.beginSubmission(id, generation, CrossSubmissionMode.PUBLISH, budget())!!
|
||||
}
|
||||
|
||||
@Test fun eventIdentityIsSharedByArticleAndVideo() = runBlocking {
|
||||
val generation = store.beginRun()
|
||||
assertTrue(store.enqueue(task("one", "shared-event", generation)))
|
||||
assertFalse(store.enqueue(task("two", "shared-event", generation).copy(contentKind = CrossContentKind.VIDEO)))
|
||||
assertNull(store.find("two"))
|
||||
}
|
||||
|
||||
@Test fun clickAndReceiptAreDurablyIdempotent() = runBlocking {
|
||||
val generation = store.beginRun()
|
||||
val attempt = intent("one", generation)
|
||||
assertTrue(store.claimSubmissionClick(attempt.id, generation, budget()))
|
||||
assertFalse(store.claimSubmissionClick(attempt.id, generation, budget()))
|
||||
assertTrue(store.recordReceipt(attempt.id, "verified-receipt", snapshot().period))
|
||||
assertTrue(store.recordReceipt(attempt.id, "verified-receipt", snapshot().period))
|
||||
assertFalse(store.recordReceipt(attempt.id, "different-receipt", snapshot().period))
|
||||
assertEquals(CrossTaskState.SUBMITTED, store.find("one")!!.state)
|
||||
assertEquals(1L, store.budgetUsage("test-account", "2026-11-13").totalUsed)
|
||||
}
|
||||
|
||||
@Test fun reopeningPreservesUnknownReservationUntilExplicitReconciliation() = runBlocking {
|
||||
val generation = store.beginRun()
|
||||
val attempt = intent("one", generation)
|
||||
assertTrue(store.claimSubmissionClick(attempt.id, generation, budget()))
|
||||
closeStore(store)
|
||||
store = openStore()
|
||||
assertEquals(CrossTaskState.RESULT_UNKNOWN, store.find("one")!!.state)
|
||||
val next = store.beginRun()
|
||||
assertFalse(store.resumeTask("one", next))
|
||||
assertNull(store.claimNextReady(next, "test-account"))
|
||||
assertEquals(1L, store.budgetUsage("test-account", "2026-11-14").totalUsed)
|
||||
assertTrue(store.confirmNotSubmitted(attempt.id, "checked-no-submission"))
|
||||
assertEquals(0L, store.budgetUsage("test-account", "2026-11-14").totalUsed)
|
||||
}
|
||||
|
||||
@Test fun editorRecoveryRequiresPageCheckAndNewGeneration() = runBlocking {
|
||||
val generation = store.beginRun()
|
||||
ready("one", generation)
|
||||
assertNotNull(store.claimNextReady(generation, "test-account"))
|
||||
closeStore(store)
|
||||
store = openStore()
|
||||
assertEquals(CrossTaskState.PAUSED, store.find("one")!!.state)
|
||||
val next = store.beginRun()
|
||||
assertFalse(store.resumeTask("one", next))
|
||||
assertTrue(store.resumeAfterPageCheck("one", next, "page-and-payload-rechecked"))
|
||||
assertEquals(next, store.claimNextReady(next, "test-account")!!.runGeneration)
|
||||
assertNull(store.beginSubmission("one", generation, CrossSubmissionMode.PUBLISH, budget()))
|
||||
}
|
||||
|
||||
@Test fun concurrentReservationsCannotExceedSharedLimit() = runBlocking {
|
||||
val generation = store.beginRun()
|
||||
assertTrue(store.bindLegacyAccount("test-account", generation, snapshot(1)))
|
||||
ready("one", generation); ready("two", generation)
|
||||
assertNotNull(store.claimNextReady(generation, "test-account"))
|
||||
assertNotNull(store.claimNextReady(generation, "test-account"))
|
||||
val attempts = listOf("one", "two").map { id -> async(Dispatchers.Default) {
|
||||
store.beginSubmission(id, generation, CrossSubmissionMode.PUBLISH, budget(1))
|
||||
} }.awaitAll()
|
||||
assertEquals(1, attempts.count { it != null })
|
||||
assertEquals(1L, store.budgetUsage("test-account", "2026-11-13").totalUsed)
|
||||
}
|
||||
|
||||
@Test fun stopInvalidatesWritersAndKeepsUnknownSubmissionQuotaAndAssets() = runBlocking {
|
||||
val generation = store.beginRun()
|
||||
assertTrue(store.enqueue(task("asset", "event-asset", generation)))
|
||||
val asset = CrossAsset("media", "asset", 1, "/isolated-fixture.mp4", "b".repeat(64), 42, "test-rights")
|
||||
assertTrue(store.saveAsset(asset, generation))
|
||||
val attempt = intent("one", generation)
|
||||
store.pauseRun()
|
||||
assertFalse(store.claimSubmissionClick(attempt.id, generation, budget()))
|
||||
assertFalse(store.enqueue(task("late", "event-late", generation)))
|
||||
assertFalse(store.transition("asset", CrossTaskState.DISCOVERED, CrossTaskState.FILTERED, generation))
|
||||
assertFalse(store.saveAsset(asset.copy(localPath = "/late.mp4"), generation))
|
||||
assertEquals(CrossTaskState.PAUSED, store.find("asset")!!.state)
|
||||
assertEquals(CrossTaskState.RESULT_UNKNOWN, store.find("one")!!.state)
|
||||
assertEquals(CrossAttemptState.UNKNOWN, store.attempts("one").single().state)
|
||||
assertEquals(asset, store.assets("asset").single())
|
||||
assertEquals(1L, store.budgetUsage("test-account", "2026-11-14").totalUsed)
|
||||
assertTrue(store.recordReceipt(attempt.id, "late-verified-receipt", snapshot().period))
|
||||
}
|
||||
|
||||
@Test fun newRunCannotSilentlyAdoptOldReadyOrEditingTasks() = runBlocking {
|
||||
val old = store.beginRun()
|
||||
ready("editing", old)
|
||||
assertNotNull(store.claimNextReady(old, "test-account"))
|
||||
ready("ready", old)
|
||||
val next = store.beginRun()
|
||||
assertEquals(CrossTaskState.PAUSED, store.find("ready")!!.state)
|
||||
assertEquals(CrossTaskState.READY, store.find("ready")!!.resumeState)
|
||||
assertEquals(CrossTaskState.EDITING, store.find("editing")!!.resumeState)
|
||||
assertNull(store.claimNextReady(next, "test-account"))
|
||||
assertFalse(store.resumeTask("editing", next))
|
||||
assertTrue(store.resumeTask("ready", next))
|
||||
assertEquals(next, store.claimNextReady(next, "test-account")!!.runGeneration)
|
||||
assertNull(store.beginSubmission("editing", old, CrossSubmissionMode.DRAFT))
|
||||
}
|
||||
|
||||
@Test fun processRecoveryPausesPreparedWorkAndRejectsStaleAssetWritesAfterResume() = runBlocking {
|
||||
val old = store.beginRun()
|
||||
ready("one", old)
|
||||
closeStore(store)
|
||||
store = openStore()
|
||||
assertEquals(CrossTaskState.PAUSED, store.find("one")!!.state)
|
||||
val next = store.beginRun()
|
||||
assertTrue(store.resumeTask("one", next))
|
||||
val asset = CrossAsset("media", "one", 1, "/fixture.mp4", "b".repeat(64), 42, "test-rights")
|
||||
assertFalse(store.saveAsset(asset, old))
|
||||
assertTrue(store.saveAsset(asset, next))
|
||||
}
|
||||
|
||||
@Test fun serviceSessionStopIsPersistedByTheStoreScope() = runBlocking {
|
||||
val lifecycle = store.runLifecycle
|
||||
val session = lifecycle.openSession()
|
||||
withTimeout(5_000) { lifecycle.state.first { !it.pending } }
|
||||
session.configure(true)
|
||||
session.start()
|
||||
val generation = withTimeout(5_000) { lifecycle.state.first { it.generation != null } }.generation!!
|
||||
ready("one", generation)
|
||||
session.close()
|
||||
assertNull(session.currentGeneration())
|
||||
withTimeout(5_000) { lifecycle.state.first { !it.pending } }
|
||||
assertEquals(CrossTaskState.PAUSED, store.find("one")!!.state)
|
||||
assertFalse(store.enqueue(task("late", "event-late", generation)))
|
||||
assertTrue(store.currentGeneration() > generation)
|
||||
}
|
||||
|
||||
@Test fun legacyAndCrossReservationsCompeteForTheLastTotalAndWindowSlot() = runBlocking {
|
||||
for (window in listOf(false, true)) {
|
||||
val generation = store.beginRun()
|
||||
val s = snapshot(total = if (window) 20 else 1, windowLimit = if (window) 1 else null)
|
||||
assertTrue(store.bindLegacyAccount("test-account", generation, s))
|
||||
val id = "cross-$window"
|
||||
ready(id, generation)
|
||||
assertNotNull(store.claimNextReady(generation, "test-account"))
|
||||
val b = budget(s.totalLimit, s)
|
||||
val results = listOf(
|
||||
async(Dispatchers.Default) { store.beginSubmission(id, generation, CrossSubmissionMode.PUBLISH, b) != null },
|
||||
async(Dispatchers.Default) { store.beginLegacySubmission("test-account", generation, "/fixture-$window.mp4", if (window) "b".repeat(64) else "c".repeat(64), b) != null },
|
||||
).awaitAll()
|
||||
assertEquals(1, results.count { it })
|
||||
// 前一轮未知提交必须明确核对未提交,才能进入另一个独立场景。
|
||||
store.attempts(id).forEach { store.confirmNotSubmitted(it.id, "isolated-fixture-not-submitted") }
|
||||
val db = database()
|
||||
val ids = db.rawQuery("SELECT id FROM legacy_submissions WHERE state IN ('INTENT','UNKNOWN')", null).use { c -> buildList { while (c.moveToNext()) add(c.getString(0)) } }
|
||||
ids.forEach { assertTrue(store.confirmLegacyNotSubmitted(it, "isolated-fixture-not-submitted")) }
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun legacyReceiptProjectsAbsoluteCountsWithoutDoubleCounting() = runBlocking {
|
||||
val generation = store.beginRun()
|
||||
val s = snapshot(total = 5, used = 2, windowLimit = 4, windowUsed = 1)
|
||||
assertTrue(store.bindLegacyAccount("test-account", generation, s))
|
||||
val reservation = store.beginLegacySubmission("test-account", generation, "/fixture.mp4", "d".repeat(64), budget(5, s))!!
|
||||
assertTrue(store.claimLegacySubmissionClick(reservation.id, generation, budget(5, s)))
|
||||
assertFalse(store.claimLegacySubmissionClick(reservation.id, generation, budget(5, s)))
|
||||
val rest = System.currentTimeMillis() + 60_000
|
||||
val first = store.recordLegacyReceipt(reservation.id, "verified-legacy-receipt", s, rest)!!
|
||||
assertEquals(3, first.used)
|
||||
assertEquals(2, first.windows[s.windowKey])
|
||||
assertEquals(rest, first.restUntilMs)
|
||||
assertEquals(first, store.recordLegacyReceipt(reservation.id, "verified-legacy-receipt", s, rest))
|
||||
assertNull(store.recordLegacyReceipt(reservation.id, "different-receipt", s, rest))
|
||||
assertEquals(3L, store.budgetUsage("test-account", s.dayKey).totalUsed)
|
||||
assertTrue(store.protectedLegacyMediaPaths().isEmpty())
|
||||
// 旧对象重启后仍是 2;更小的基线不能把库中 3 覆盖掉,休息期也不能丢失。
|
||||
assertTrue(store.bindLegacyAccount("test-account", generation, s))
|
||||
assertNull(store.beginLegacySubmission("test-account", generation, "/next.mp4", "e".repeat(64), budget(5, s)))
|
||||
assertEquals(first, store.legacyBudgetState(s.dayKey))
|
||||
}
|
||||
|
||||
@Test fun unknownLegacySubmissionKeepsQuotaAndMediaAcrossRestartAndDayBoundary() = runBlocking {
|
||||
val generation = store.beginRun()
|
||||
assertTrue(store.bindLegacyAccount("test-account", generation, snapshot(1)))
|
||||
val reservation = store.beginLegacySubmission("test-account", generation, "/retained.mp4", "f".repeat(64), budget(1))!!
|
||||
assertTrue(store.claimLegacySubmissionClick(reservation.id, generation, budget(1)))
|
||||
closeStore(store)
|
||||
store = openStore()
|
||||
assertEquals(CrossAttemptState.UNKNOWN, store.legacySubmission(reservation.id)!!.state)
|
||||
assertEquals(setOf("/retained.mp4"), store.protectedLegacyMediaPaths())
|
||||
val next = store.beginRun()
|
||||
val tomorrow = snapshot(1, day = "2026-11-14")
|
||||
assertTrue(store.bindLegacyAccount("test-account", next, tomorrow))
|
||||
assertEquals(1L, store.budgetUsage("test-account", tomorrow.dayKey).totalUsed)
|
||||
assertNull(store.beginLegacySubmission("test-account", next, "/new.mp4", "a".repeat(64), budget(1, tomorrow)))
|
||||
assertFalse(store.claimLegacySubmissionClick(reservation.id, next, budget(1, tomorrow)))
|
||||
assertTrue(store.confirmLegacyNotSubmitted(reservation.id, "verified-no-work-or-submission"))
|
||||
assertEquals(0L, store.budgetUsage("test-account", tomorrow.dayKey).totalUsed)
|
||||
assertTrue(store.protectedLegacyMediaPaths().isEmpty())
|
||||
}
|
||||
|
||||
@Test fun missingStaleAndMismatchedAccountSnapshotsCannotReserveOrClick() = runBlocking {
|
||||
val generation = store.beginRun()
|
||||
ready("one", generation)
|
||||
assertNotNull(store.claimNextReady(generation, "test-account"))
|
||||
assertNull(store.beginSubmission("one", generation, CrossSubmissionMode.PUBLISH, budget()))
|
||||
val s = snapshot()
|
||||
assertTrue(store.bindLegacyAccount("test-account", generation, s))
|
||||
assertFalse(store.bindLegacyAccount("another-account", generation, s))
|
||||
assertNull(store.beginSubmission("one", generation, CrossSubmissionMode.PUBLISH, budget().copy(quotaSnapshot = null)))
|
||||
val stale = s.copy(capturedAtMs = s.capturedAtMs - 6_000)
|
||||
assertNull(store.beginLegacySubmission("test-account", generation, "/fixture.mp4", "a".repeat(64), budget(snapshot = stale)))
|
||||
assertNull(store.beginLegacySubmission("another-account", generation, "/fixture.mp4", "a".repeat(64), budget()))
|
||||
val reservation = store.beginLegacySubmission("test-account", generation, "/fixture.mp4", "a".repeat(64), budget())!!
|
||||
database().execSQL("UPDATE legacy_submissions SET valid_until=0 WHERE id=?", arrayOf(reservation.id))
|
||||
assertFalse(store.claimLegacySubmissionClick(reservation.id, generation, budget()))
|
||||
assertEquals(1L, store.budgetUsage("test-account", s.dayKey).totalUsed)
|
||||
}
|
||||
|
||||
@Test fun legacyDraftDoesNotNeedOrReserveFormalBudget() = runBlocking {
|
||||
val generation = store.beginRun()
|
||||
ready("draft", generation)
|
||||
assertNotNull(store.claimNextReady(generation, "test-account"))
|
||||
val attempt = store.beginSubmission("draft", generation, CrossSubmissionMode.DRAFT)!!
|
||||
assertTrue(store.claimSubmissionClick(attempt.id, generation))
|
||||
assertTrue(store.recordReceipt(attempt.id, "verified-draft"))
|
||||
assertEquals(0L, store.budgetUsage("test-account", "2026-11-13").totalUsed)
|
||||
}
|
||||
|
||||
@Test fun versionOneMigrationPreservesTasksAssetsAndHeldQuota() = runBlocking {
|
||||
val generation = store.beginRun()
|
||||
val attempt = intent("one", generation)
|
||||
val asset = CrossAsset("media", "one", 1, "/preserved.mp4", "b".repeat(64), 42, "fixture-rights")
|
||||
// 素材先前处于可写状态;这里直接写入隔离库模拟已有 v1 记录。
|
||||
database().execSQL("INSERT INTO assets VALUES(?,?,?,?,?,?,?)", arrayOf(asset.id, asset.taskId, asset.revision, asset.localPath, asset.sha256, asset.sizeBytes, asset.rightsRef))
|
||||
closeStore(store)
|
||||
SQLiteDatabase.openDatabase(isolated.getDatabasePath("crossplatform_tasks.db").path, null, SQLiteDatabase.OPEN_READWRITE).use { db ->
|
||||
db.execSQL("ALTER TABLE quota_ledger RENAME TO quota_v2_fixture")
|
||||
db.execSQL("CREATE TABLE quota_ledger(attempt_id TEXT PRIMARY KEY REFERENCES attempts(id),account_key TEXT NOT NULL,day_key TEXT NOT NULL,kind TEXT NOT NULL,state TEXT NOT NULL)")
|
||||
db.execSQL("INSERT INTO quota_ledger SELECT attempt_id,account_key,day_key,kind,state FROM quota_v2_fixture")
|
||||
db.execSQL("DROP TABLE quota_v2_fixture")
|
||||
db.execSQL("CREATE INDEX account_quota ON quota_ledger(account_key,day_key,state)")
|
||||
db.execSQL("DROP TABLE legacy_submissions")
|
||||
db.execSQL("DROP TABLE budget_windows")
|
||||
db.execSQL("DROP TABLE account_binding")
|
||||
db.version = 1
|
||||
}
|
||||
store = openStore()
|
||||
assertEquals(CrossTaskState.RESULT_UNKNOWN, store.find("one")!!.state)
|
||||
assertEquals(asset, store.assets("one").single())
|
||||
assertTrue(store.protectedSubmissionMediaPaths().contains(asset.localPath))
|
||||
assertTrue(store.hasSharedBudgetHistory())
|
||||
assertEquals(CrossAttemptState.UNKNOWN, store.attempts("one").single().state)
|
||||
assertEquals(1L, store.budgetUsage("test-account", "2026-11-14").totalUsed)
|
||||
assertTrue(store.recordReceipt(attempt.id, "verified-after-migration", snapshot().period))
|
||||
assertEquals(1L, store.budgetUsage("test-account", "2026-11-13").totalUsed)
|
||||
}
|
||||
|
||||
private fun database(): SQLiteDatabase = (CrossPublishTaskStore::class.java.getDeclaredField("helper")
|
||||
.apply { isAccessible = true }.get(store) as SQLiteOpenHelper).writableDatabase
|
||||
|
||||
@Test fun finalClickRechecksRestAndNewGapAfterAnotherReceipt() = runBlocking {
|
||||
val generation = store.beginRun()
|
||||
assertTrue(store.bindLegacyAccount("test-account", generation, snapshot(5)))
|
||||
ready("one", generation); ready("two", generation)
|
||||
assertNotNull(store.claimNextReady(generation, "test-account"))
|
||||
assertNotNull(store.claimNextReady(generation, "test-account"))
|
||||
val b = budget(5)
|
||||
val first = store.beginSubmission("one", generation, CrossSubmissionMode.PUBLISH, b)!!
|
||||
val second = store.beginSubmission("two", generation, CrossSubmissionMode.PUBLISH, b)!!
|
||||
val legacy = store.beginLegacySubmission("test-account", generation, "/waiting.mp4", "a".repeat(64), b)!!
|
||||
assertFalse(store.claimSubmissionClick(first.id, generation))
|
||||
assertTrue(store.claimSubmissionClick(first.id, generation, b))
|
||||
assertTrue(store.recordReceipt(first.id, "verified-first", snapshot(5).period))
|
||||
// 预占时尚无回执;一次点击许可发放前必须再次执行新链路间隔规则。
|
||||
assertFalse(store.claimSubmissionClick(second.id, generation, budget(5).copy(minGapMs = 3_600_000)))
|
||||
assertFalse(store.attempts("two").single().clickClaimed)
|
||||
// 旧链路不使用新间隔,但仍遵守任何一条链路产生的账户休息期。
|
||||
assertTrue(store.bindLegacyAccount("test-account", generation, snapshot(5).copy(restUntilMs = System.currentTimeMillis() + 60_000)))
|
||||
assertFalse(store.claimLegacySubmissionClick(legacy.id, generation, budget(5)))
|
||||
assertFalse(store.claimSubmissionClick(second.id, generation, budget(5)))
|
||||
assertEquals(3L, store.budgetUsage("test-account", "2026-11-13").totalUsed)
|
||||
}
|
||||
|
||||
@Test fun reconcilingLegacySuccessAfterRestartChargesTheVerifiedSubmissionDayOnce() = runBlocking {
|
||||
val generation = store.beginRun()
|
||||
val before = snapshot(1)
|
||||
assertTrue(store.bindLegacyAccount("test-account", generation, before))
|
||||
val reservation = store.beginLegacySubmission("test-account", generation, "/previous.mp4", "a".repeat(64), budget(1, before))!!
|
||||
assertTrue(store.claimLegacySubmissionClick(reservation.id, generation, budget(1, before)))
|
||||
store.pauseRun()
|
||||
val next = store.beginRun()
|
||||
val tomorrow = snapshot(1, day = "2026-11-14")
|
||||
assertTrue(store.bindLegacyAccount("test-account", next, tomorrow))
|
||||
assertNotNull(store.recordLegacyReceipt(reservation.id, "verified-previous-day", tomorrow, 0, before.period))
|
||||
assertNotNull(store.recordLegacyReceipt(reservation.id, "verified-previous-day", tomorrow, 0, before.period))
|
||||
assertEquals(1L, store.budgetUsage("test-account", "2026-11-13").totalUsed)
|
||||
assertEquals(0L, store.budgetUsage("test-account", "2026-11-14").totalUsed)
|
||||
assertNotNull(store.beginLegacySubmission("test-account", next, "/today.mp4", "b".repeat(64), budget(1, tomorrow)))
|
||||
}
|
||||
|
||||
@Test fun cancelledSessionAfterIntentCommitReleasesOnlyItsUnclickedReservation() = runBlocking {
|
||||
val generation = store.beginRun()
|
||||
val account = "tt:" + "a".repeat(64)
|
||||
val journal = StoreLegacyPublishJournal(store)
|
||||
val cancelling = object : LegacyPublishSession.Journal by journal {
|
||||
override suspend fun reserve(id: String, account: String, generation: Long, path: String, hash: String, budget: CrossSubmissionBudget): Boolean {
|
||||
assertTrue(journal.reserve(id, account, generation, path, hash, budget))
|
||||
throw CancellationException("simulated return-value loss after SQLite commit")
|
||||
}
|
||||
}
|
||||
val session = LegacyPublishSession(generation, "/cancelled-before-click.mp4", "d".repeat(64), cancelling,
|
||||
{ VerifiedAccount(account, "fixture", System.currentTimeMillis(), "operation") }, { budget() }, { true })
|
||||
assertTrue(session.prepare())
|
||||
try { session.dispatch("d".repeat(64), { true }) { error("must not click") }; fail() } catch (_: CancellationException) { }
|
||||
assertEquals(CrossAttemptState.NOT_SUBMITTED, store.legacySubmission(session.attemptId)!!.state)
|
||||
assertEquals(0L, store.budgetUsage(account, "2026-11-13").totalUsed)
|
||||
}
|
||||
|
||||
@Test fun cancelledSessionAfterClaimCommitKeepsDurableUnknownQuotaAndMedia() = runBlocking {
|
||||
val generation = store.beginRun()
|
||||
val account = "tt:" + "a".repeat(64)
|
||||
val journal = StoreLegacyPublishJournal(store)
|
||||
val cancelling = object : LegacyPublishSession.Journal by journal {
|
||||
override suspend fun claim(id: String, generation: Long, budget: CrossSubmissionBudget): Boolean {
|
||||
assertTrue(journal.claim(id, generation, budget))
|
||||
throw CancellationException("simulated return-value loss after click-claim commit")
|
||||
}
|
||||
}
|
||||
val session = LegacyPublishSession(generation, "/cancelled-after-claim.mp4", "d".repeat(64), cancelling,
|
||||
{ VerifiedAccount(account, "fixture", System.currentTimeMillis(), "operation") }, { budget() }, { true })
|
||||
assertTrue(session.prepare())
|
||||
try { session.dispatch("d".repeat(64), { true }) { error("must not click") }; fail() } catch (_: CancellationException) { }
|
||||
assertEquals(CrossAttemptState.UNKNOWN, store.legacySubmission(session.attemptId)!!.state)
|
||||
assertFalse(store.releaseUnclickedLegacySubmission(session.attemptId, generation))
|
||||
closeStore(store)
|
||||
store = openStore()
|
||||
assertEquals(1L, store.budgetUsage(account, "2026-11-14").totalUsed)
|
||||
assertTrue(store.protectedSubmissionMediaPaths().contains("/cancelled-after-claim.mp4"))
|
||||
}
|
||||
}
|
||||
+245
@@ -0,0 +1,245 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
========================================================================
|
||||
jai-imageio
|
||||
========================================================================
|
||||
|
||||
Copyright (c) 2005 Sun Microsystems, Inc.
|
||||
Copyright © 2010-2014 University of Manchester
|
||||
Copyright © 2010-2015 Stian Soiland-Reyes
|
||||
Copyright © 2015 Peter Hull
|
||||
All Rights Reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
- Redistribution of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
- Redistribution in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in
|
||||
the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
|
||||
Neither the name of Sun Microsystems, Inc. or the names of
|
||||
contributors may be used to endorse or promote products derived
|
||||
from this software without specific prior written permission.
|
||||
|
||||
This software is provided "AS IS," without a warranty of any
|
||||
kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
|
||||
WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
|
||||
EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
|
||||
NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
|
||||
USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
|
||||
DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
|
||||
ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
|
||||
CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
|
||||
REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
|
||||
INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
You acknowledge that this software is not designed or intended for
|
||||
use in the design, construction, operation or maintenance of any
|
||||
nuclear facility.
|
||||
@@ -0,0 +1,17 @@
|
||||
--------------------------------------------------------------------------------
|
||||
NOTICES FOR BARCODE4J
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Barcode4J
|
||||
Copyright 2002-2010 Jeremias Märki
|
||||
Copyright 2005-2006 Dietmar Bürkle
|
||||
|
||||
Portions of this software were contributed under section 5 of the
|
||||
Apache License. Contributors are listed under:
|
||||
http://barcode4j.sourceforge.net/contributors.html
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
NOTICES FOR JCOMMANDER
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Copyright 2010 Cedric Beust [email protected]
|
||||
@@ -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,58 +519,123 @@ 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)
|
||||
try {
|
||||
if (declarationOpened && !declarationSheetOpen(root) && declarationReadback(root) == declaration) {
|
||||
declarationVerified = true
|
||||
log("作品声明回读通过:$declaration")
|
||||
go(Phase.CONFIRM)
|
||||
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")
|
||||
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
|
||||
}
|
||||
log("未找到作品声明选项「$declaration」(对照原等待超时仍进入下一步,由回读兜底)")
|
||||
declarationOptionRetry = 0
|
||||
go(Phase.CONFIRM)
|
||||
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
|
||||
try {
|
||||
eligibilityCheck?.invoke()?.let { reason ->
|
||||
log("点击发布前筛选拒绝:$reason")
|
||||
TaskStatusBus.status("发布前复查跳过:$reason")
|
||||
@@ -556,6 +652,12 @@ class PublishMachine(
|
||||
}
|
||||
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 "存草稿")
|
||||
@@ -606,6 +708,7 @@ class PublishMachine(
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.haorui.app.crossplatform.account
|
||||
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
|
||||
/** 账号读取专用请求,不与旧采集剪贴板队列共用;超时回调不能交给下一次核验。 */
|
||||
class AccountClipboardRequests {
|
||||
enum class Operation { PREPARE, READ }
|
||||
data class Result(val text: String, val timestampMs: Long)
|
||||
class Request internal constructor(val owner: Long, val id: Long, val operation: Operation, val nonce: String) {
|
||||
val result = CompletableDeferred<Result?>()
|
||||
internal var claimed = false
|
||||
}
|
||||
private var sequence = 0L
|
||||
private var ownerSequence = 0L
|
||||
private var pending: Request? = null
|
||||
|
||||
@Synchronized fun newOwner(): Long = ++ownerSequence
|
||||
@Synchronized fun hasPending(): Boolean = pending != null
|
||||
|
||||
@Synchronized fun begin(owner: Long, operation: Operation, nonce: String): Request {
|
||||
require(owner > 0 && nonce.isNotBlank())
|
||||
pending?.result?.complete(null)
|
||||
return Request(owner, ++sequence, operation, nonce).also { pending = it }
|
||||
}
|
||||
|
||||
@Synchronized fun claim(): Request? = pending?.takeIf { !it.claimed }?.also { it.claimed = true }
|
||||
|
||||
@Synchronized fun isCurrent(request: Request): Boolean = pending === request && !request.result.isCompleted
|
||||
|
||||
@Synchronized fun complete(request: Request, result: Result?): Boolean {
|
||||
if (!isCurrent(request)) return false
|
||||
pending = null
|
||||
request.result.complete(result)
|
||||
return true
|
||||
}
|
||||
|
||||
@Synchronized fun cancel(owner: Long) {
|
||||
if (pending?.owner != owner) return
|
||||
pending?.result?.complete(null)
|
||||
pending = null
|
||||
}
|
||||
|
||||
companion object { val shared = AccountClipboardRequests() }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.haorui.app.crossplatform.account
|
||||
|
||||
import com.google.zxing.BinaryBitmap
|
||||
import com.google.zxing.DecodeHintType
|
||||
import com.google.zxing.RGBLuminanceSource
|
||||
import com.google.zxing.common.HybridBinarizer
|
||||
import com.google.zxing.qrcode.QRCodeReader
|
||||
|
||||
/** 只解码本机名片截图裁剪的像素,不打开二维码链接。 */
|
||||
object ProfileQrDecoder {
|
||||
fun decode(width: Int, height: Int, pixels: IntArray): String? {
|
||||
if (width < 32 || height < 32 || width.toLong() * height != pixels.size.toLong() || pixels.size > 16_777_216) return null
|
||||
return runCatching {
|
||||
QRCodeReader().decode(BinaryBitmap(HybridBinarizer(RGBLuminanceSource(width, height, pixels))),
|
||||
mapOf(DecodeHintType.TRY_HARDER to true)).text.takeIf { it.length <= 8192 }
|
||||
}.getOrNull()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.haorui.app.crossplatform.account
|
||||
|
||||
import java.net.URI
|
||||
import java.net.URLDecoder
|
||||
import java.security.MessageDigest
|
||||
|
||||
/** 仅处理已从自身主页复制的 18.3.0 链接;链接解析本身不构成账号核验。 */
|
||||
object ToutiaoAccountIdentity {
|
||||
fun keyFromProfileLink(text: String): String? = runCatching {
|
||||
if (text.length > 8192) return null
|
||||
val links = Regex("https?://[^\\s\"<>]+", RegexOption.IGNORE_CASE).findAll(text).toList()
|
||||
if (links.size != 1) return null
|
||||
val uri = URI(links.single().value)
|
||||
if (uri.scheme != "https" || uri.host != "profile.zjurl.cn" || uri.userInfo != null || uri.port != -1 ||
|
||||
uri.fragment != null || uri.rawPath?.trimEnd('/') != "/rogue/ugc/profile") return null
|
||||
val pairs = uri.rawQuery?.split('&')?.map { part ->
|
||||
val pieces = part.split('=', limit = 2)
|
||||
URLDecoder.decode(pieces[0], "UTF-8") to URLDecoder.decode(pieces.getOrElse(1) { "" }, "UTF-8")
|
||||
} ?: return null
|
||||
val ids = pairs.filter { it.first == "user_id" }
|
||||
if (ids.size != 1) return null
|
||||
val id = ids.single().second.takeIf { it.matches(Regex("[1-9][0-9]{4,23}")) } ?: return null
|
||||
"tt:" + MessageDigest.getInstance("SHA-256").digest("toutiao:user:$id".toByteArray(Charsets.UTF_8)).joinToString("") { "%02x".format(it) }
|
||||
}.getOrNull()
|
||||
|
||||
fun copiedAfterArm(armed: AccountClipboardRequests.Result, copied: AccountClipboardRequests.Result, nonce: String): Boolean =
|
||||
armed.text == nonce && armed.timestampMs > 0 && copied.text != nonce && copied.timestampMs > armed.timestampMs
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
package com.haorui.app.crossplatform.account
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.content.Intent
|
||||
import android.graphics.Rect
|
||||
import android.os.Build
|
||||
import android.view.accessibility.AccessibilityNodeInfo
|
||||
import com.haorui.app.MainActivity
|
||||
import com.haorui.app.automation.HaoRuiAccessibilityService
|
||||
import com.haorui.app.automation.NodeLocator
|
||||
import com.haorui.app.automation.Targets
|
||||
import com.haorui.app.crossplatform.publish.VerifiedAccount
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import java.util.UUID
|
||||
|
||||
/** 每次核验使用两次独立名片/链接取证,始终检查自身资料指纹;不复用旧核验或昵称作为身份。 */
|
||||
class ToutiaoAccountReader(private val service: HaoRuiAccessibilityService, private val isCurrent: () -> Boolean) {
|
||||
private val requests = AccountClipboardRequests.shared
|
||||
private val owner = requests.newOwner()
|
||||
var failure: String = "账号读取尚未完成"
|
||||
private set
|
||||
|
||||
suspend fun verify(): VerifiedAccount? {
|
||||
if (!Targets.isToutiaoCompatible(service)) { failure = "头条版本尚未适配"; return null }
|
||||
return try {
|
||||
withTimeoutOrNull(60_000) {
|
||||
checkCurrent()
|
||||
service.startActivity(Intent().setComponent(ComponentName(Targets.TOUTIAO_PKG, "com.ss.android.article.news.activity.MainActivity"))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
|
||||
if (!awaitHomeNavigation()) {
|
||||
logNavigationFailure()
|
||||
return@withTimeoutOrNull reject("未能打开头条主页")
|
||||
}
|
||||
if (ownName() == null && !tapMine()) return@withTimeoutOrNull reject("未能进入自己的资料页")
|
||||
if (!await { ownName() != null }) return@withTimeoutOrNull reject("未能核对自身资料入口")
|
||||
val name = ownName() ?: return@withTimeoutOrNull null
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) return@withTimeoutOrNull verifyCards(name)
|
||||
var key: String? = null
|
||||
repeat(2) {
|
||||
val nonce = "haorui-account:${UUID.randomUUID()}"
|
||||
val armed = exchange(AccountClipboardRequests.Operation.PREPARE, nonce) ?: return@withTimeoutOrNull reject("前台剪贴板准备失败")
|
||||
if (armed.text != nonce || !await { ownName() == name }) return@withTimeoutOrNull reject("准备后账号页面已变化")
|
||||
if (!tapId("hs2") || !await { nodeExists(text = "分享至") }) return@withTimeoutOrNull reject("自身主页分享入口不可用")
|
||||
var found = nodeExists(text = "复制链接")
|
||||
repeat(3) {
|
||||
if (!found) {
|
||||
if (!scrollShareRow()) return@withTimeoutOrNull reject("主页复制链接入口不可用")
|
||||
delay(400)
|
||||
found = nodeExists(text = "复制链接")
|
||||
}
|
||||
}
|
||||
if (!found || !tapText("复制链接") || !await { ownName() == name }) return@withTimeoutOrNull reject("复制后账号页面已变化")
|
||||
// 主页链接可能异步写入;在头条仍持有前台时等待并复核。
|
||||
delay(2_500)
|
||||
checkCurrent()
|
||||
if (ownName() != name) return@withTimeoutOrNull reject("复制完成前账号页面已变化")
|
||||
val copied = exchange(AccountClipboardRequests.Operation.READ, nonce) ?: return@withTimeoutOrNull reject("前台账号链接读取失败")
|
||||
if (!await { ownName() == name } || !ToutiaoAccountIdentity.copiedAfterArm(armed, copied, nonce)) return@withTimeoutOrNull reject("账号链接未更新或页面已变化")
|
||||
val currentKey = ToutiaoAccountIdentity.keyFromProfileLink(copied.text) ?: return@withTimeoutOrNull reject("账号链接格式尚未核验")
|
||||
if (key != null && key != currentKey) return@withTimeoutOrNull reject("两次核验的账号不一致")
|
||||
key = currentKey
|
||||
}
|
||||
checkCurrent()
|
||||
VerifiedAccount(key!!, name, System.currentTimeMillis(), UUID.randomUUID().toString())
|
||||
}.also { if (it == null && failure == "账号读取尚未完成") failure = "账号核验超时" }
|
||||
} finally { requests.cancel(owner) }
|
||||
}
|
||||
|
||||
private fun reject(reason: String): VerifiedAccount? {
|
||||
failure = reason
|
||||
val window = service.root()
|
||||
val pkg = try { window?.packageName?.toString() } finally { window?.recycle() }
|
||||
com.haorui.app.automation.RunLogger.i("AccountRead", "reason=$reason package=$pkg")
|
||||
return null
|
||||
}
|
||||
|
||||
private suspend fun closeShares(): Boolean {
|
||||
repeat(2) {
|
||||
checkCurrent()
|
||||
if (!nodeExists("分享至")) return true
|
||||
val card = nodeExists("扫码关注我 获取更多信息")
|
||||
service.gestures.back()
|
||||
// 先等弹层确实消失或名片退回普通分享页,再决定是否需要第二次返回。
|
||||
if (!await { !nodeExists("分享至") || (card && !nodeExists("扫码关注我 获取更多信息")) }) return false
|
||||
}
|
||||
return !nodeExists("分享至")
|
||||
}
|
||||
|
||||
private suspend fun verifyCards(name: String): VerifiedAccount? {
|
||||
var key: String? = null
|
||||
repeat(2) {
|
||||
if (ownName() != name || !tapId("hs2") || !await { nodeExists("分享至") }) return reject("自身主页分享入口不可用")
|
||||
var found = nodeExists("名片分享")
|
||||
repeat(3) {
|
||||
if (!found) {
|
||||
if (!scrollShareRow()) return reject("名片分享入口不可用")
|
||||
delay(400)
|
||||
found = nodeExists("名片分享")
|
||||
}
|
||||
}
|
||||
if (!found || !tapText("名片分享") || !await { cardQrBounds(name) != null }) return reject("自身名片信息未能核对")
|
||||
var currentKey: String? = null
|
||||
repeat(3) {
|
||||
if (currentKey == null) {
|
||||
checkCurrent()
|
||||
delay(450)
|
||||
val bounds = cardQrBounds(name) ?: return reject("名片页面已变化")
|
||||
com.haorui.app.overlay.MonitorOverlay.setHidden(true)
|
||||
val bitmap = try { com.haorui.app.ocr.ScreenCapturer(service).capture() }
|
||||
finally { com.haorui.app.overlay.MonitorOverlay.setHidden(false) }
|
||||
if (bitmap != null) try {
|
||||
checkCurrent()
|
||||
if (cardQrBounds(name) != bounds || bounds.left < 0 || bounds.top < 0 || bounds.right > bitmap.width || bounds.bottom > bitmap.height) return reject("名片截图与页面不一致")
|
||||
currentKey = withContext(Dispatchers.Default) {
|
||||
val pixels = IntArray(bounds.width() * bounds.height())
|
||||
bitmap.getPixels(pixels, 0, bounds.width(), bounds.left, bounds.top, bounds.width(), bounds.height())
|
||||
ProfileQrDecoder.decode(bounds.width(), bounds.height(), pixels)?.let(ToutiaoAccountIdentity::keyFromProfileLink)
|
||||
}
|
||||
} finally { bitmap.recycle() }
|
||||
}
|
||||
}
|
||||
if (currentKey == null) return reject("名片二维码身份无法核验")
|
||||
if (key != null && key != currentKey) return reject("两次核验的账号不一致")
|
||||
key = currentKey
|
||||
if (!closeShares()) return reject("名片弹层未能关闭")
|
||||
if (!await { ownName() == name }) return reject("名片返回后账号页面已变化")
|
||||
}
|
||||
checkCurrent()
|
||||
return VerifiedAccount(key!!, name, System.currentTimeMillis(), UUID.randomUUID().toString())
|
||||
}
|
||||
|
||||
private fun cardQrBounds(name: String): Rect? {
|
||||
val root = root() ?: return null
|
||||
return try {
|
||||
val frame = NodeLocator.byId(root, id("kr")) ?: return null
|
||||
try {
|
||||
val sameName = findText(frame, name)?.also { it.recycle() } != null
|
||||
val caption = findText(frame, "扫码关注我 获取更多信息")?.also { it.recycle() } != null
|
||||
if (!sameName || !caption) return null
|
||||
val bounds = Rect().also(frame::getBoundsInScreen)
|
||||
// 18.3.0 名片的二维码位于下半部;排除上方头像及其可能包含的二维码。
|
||||
if (bounds.width() <= 0 || bounds.height() < 128) null else Rect(bounds.left, bounds.centerY(), bounds.right, bounds.bottom)
|
||||
} finally { frame.recycle() }
|
||||
} finally { root.recycle() }
|
||||
}
|
||||
private fun checkCurrent() { if (!isCurrent()) throw CancellationException("账号核验运行已失效") }
|
||||
private suspend fun await(predicate: () -> Boolean): Boolean {
|
||||
repeat(25) { checkCurrent(); if (predicate()) return true; delay(200) }
|
||||
return false
|
||||
}
|
||||
private fun root(): AccessibilityNodeInfo? {
|
||||
checkCurrent()
|
||||
val root = service.root() ?: return null
|
||||
if (root.packageName?.toString() == Targets.TOUTIAO_PKG) return root
|
||||
root.recycle(); return null
|
||||
}
|
||||
private fun ownName(): String? {
|
||||
val root = root() ?: return null
|
||||
return try {
|
||||
// 弹层打开时头条仍暴露背景资料节点;必须先关闭分享/名片弹层。
|
||||
findText(root, "分享至")?.let { it.recycle(); return null }
|
||||
val edit = NodeLocator.byId(root, id("hno")) ?: return null
|
||||
val own = edit.contentDescription?.toString() == "编辑资料"
|
||||
edit.recycle()
|
||||
if (!own) return null
|
||||
val node = NodeLocator.byId(root, id("hqt")) ?: return null
|
||||
node.text?.toString()?.trim()?.takeIf { it.isNotBlank() }.also { node.recycle() }
|
||||
} finally { root.recycle() }
|
||||
}
|
||||
private fun nodeExists(text: String): Boolean {
|
||||
val root = root() ?: return false
|
||||
return try { findText(root, text)?.also { it.recycle() } != null } finally { root.recycle() }
|
||||
}
|
||||
private fun findText(root: AccessibilityNodeInfo, text: String): AccessibilityNodeInfo? {
|
||||
val nodes = root.findAccessibilityNodeInfosByText(text).orEmpty()
|
||||
var selected: AccessibilityNodeInfo? = null
|
||||
nodes.forEach { node -> if (selected == null && (node.text?.toString() == text || node.contentDescription?.toString() == text)) selected = node else node.recycle() }
|
||||
return selected ?: NodeLocator.byText(root, text) ?: NodeLocator.byDesc(root, text)
|
||||
}
|
||||
|
||||
private fun mineNode(root: AccessibilityNodeInfo): AccessibilityNodeInfo? {
|
||||
findText(root, "我的")?.let { return it }
|
||||
val indexed = root.findAccessibilityNodeInfosByViewId(id("llm")).orEmpty()
|
||||
val nodes = if (indexed.isNotEmpty()) indexed else NodeLocator.all(root, com.haorui.app.automation.Selector.ResId(id("llm")), limit = 8)
|
||||
return try {
|
||||
val screen = Rect().also(root::getBoundsInScreen)
|
||||
val candidates = nodes.map { it to Rect().also(it::getBoundsInScreen) }.filter { (node, rect) ->
|
||||
node.isEnabled && node.isClickable && !rect.isEmpty && rect.top > screen.top + screen.height() * 3 / 4
|
||||
}.sortedBy { it.second.left }
|
||||
// 18.3.0 底栏为首页/视频/赚钱/商城/我的。仅接受覆盖整行的五个相邻项。
|
||||
val aligned = candidates.size == 5 && candidates.first().second.left <= screen.left + screen.width() / 20 &&
|
||||
candidates.last().second.right >= screen.right - screen.width() / 20 &&
|
||||
candidates.all { kotlin.math.abs(it.second.centerY() - candidates.first().second.centerY()) <= 12 } &&
|
||||
candidates.zipWithNext().all { (left, right) -> right.second.left >= left.second.right - 2 }
|
||||
if (aligned) AccessibilityNodeInfo.obtain(candidates.last().first) else null
|
||||
} finally { nodes.forEach { it.recycle() } }
|
||||
}
|
||||
|
||||
private fun homeNavigationReady(): Boolean {
|
||||
val root = root() ?: return false
|
||||
return try {
|
||||
findText(root, "分享至")?.let { it.recycle(); return false }
|
||||
mineNode(root)?.also { it.recycle() } != null
|
||||
} finally { root.recycle() }
|
||||
}
|
||||
|
||||
private suspend fun awaitHomeNavigation(): Boolean {
|
||||
repeat(25) {
|
||||
checkCurrent()
|
||||
// startActivity 返回时可能仍在浩瑞;弹层清理必须等头条实际恢复后执行。
|
||||
if (nodeExists("分享至") && !closeShares()) return false
|
||||
if (ownName() != null || homeNavigationReady()) return true
|
||||
delay(200)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun logNavigationFailure() {
|
||||
val root = root() ?: return
|
||||
try {
|
||||
val bounds = Rect().also(root::getBoundsInScreen)
|
||||
val nodes = root.findAccessibilityNodeInfosByViewId(id("llm")).orEmpty()
|
||||
try {
|
||||
val items = nodes.joinToString(";") { node ->
|
||||
val rect = Rect().also(node::getBoundsInScreen)
|
||||
"${rect.flattenToString()},visible=${node.isVisibleToUser},clickable=${node.isClickable},enabled=${node.isEnabled}"
|
||||
}
|
||||
com.haorui.app.automation.RunLogger.i("AccountRead", "navigation root=${root.className} bounds=${bounds.flattenToString()} footer=${nodes.size} items=$items")
|
||||
} finally { nodes.forEach { it.recycle() } }
|
||||
} finally { root.recycle() }
|
||||
}
|
||||
|
||||
private suspend fun tapMine(): Boolean {
|
||||
val root = root() ?: return false
|
||||
val node = try { mineNode(root) } finally { root.recycle() } ?: return false
|
||||
return try {
|
||||
checkCurrent()
|
||||
val parent = NodeLocator.clickableAncestor(node)
|
||||
try { service.gestures.tapNodeOnce(parent ?: node) } finally { parent?.recycle() }
|
||||
} finally { node.recycle() }
|
||||
}
|
||||
private suspend fun tapText(text: String): Boolean {
|
||||
val root = root() ?: return false
|
||||
val node = try { findText(root, text) } finally { root.recycle() } ?: return false
|
||||
return try {
|
||||
checkCurrent()
|
||||
if (text in setOf("复制链接", "名片分享")) {
|
||||
val parent = NodeLocator.clickableAncestor(node)
|
||||
try { service.gestures.tapNodeOnce(parent ?: node) } finally { parent?.recycle() }
|
||||
} else service.gestures.tapNode(node)
|
||||
} finally { node.recycle() }
|
||||
}
|
||||
private suspend fun tapId(value: String): Boolean {
|
||||
val root = root() ?: return false
|
||||
val node = try { NodeLocator.byId(root, id(value)) } finally { root.recycle() } ?: return false
|
||||
return try { checkCurrent(); service.gestures.tapNode(node) } finally { node.recycle() }
|
||||
}
|
||||
private fun scrollShareRow(): Boolean {
|
||||
val root = root() ?: return false
|
||||
return try {
|
||||
val row = NodeLocator.byId(root, id("onk")) ?: return false
|
||||
try { checkCurrent(); row.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD) } finally { row.recycle() }
|
||||
} finally { root.recycle() }
|
||||
}
|
||||
private suspend fun exchange(operation: AccountClipboardRequests.Operation, nonce: String): AccountClipboardRequests.Result? {
|
||||
checkCurrent()
|
||||
val request = requests.begin(owner, operation, nonce)
|
||||
return try {
|
||||
service.startActivity(Intent(service, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP))
|
||||
withTimeoutOrNull(8_000) { request.result.await() }
|
||||
} finally { requests.cancel(owner) }
|
||||
}
|
||||
private fun id(value: String) = "${Targets.TOUTIAO_PKG}:id/$value"
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package com.haorui.app.crossplatform.data
|
||||
|
||||
import android.content.ContentValues
|
||||
import android.database.sqlite.SQLiteDatabase
|
||||
import com.haorui.app.crossplatform.model.*
|
||||
import java.util.UUID
|
||||
|
||||
/** 只在任务库持有写事务时调用;旧视频和新任务使用同一账户预算。 */
|
||||
internal object AccountBudgetTransactions {
|
||||
fun create(db: SQLiteDatabase) {
|
||||
db.execSQL("CREATE TABLE account_binding(id INTEGER PRIMARY KEY CHECK(id=1),account_key TEXT NOT NULL,rest_until INTEGER NOT NULL DEFAULT 0)")
|
||||
db.execSQL("CREATE TABLE budget_windows(account_key TEXT NOT NULL,day_key TEXT NOT NULL,window_key TEXT NOT NULL,legacy_used INTEGER NOT NULL,PRIMARY KEY(account_key,day_key,window_key))")
|
||||
db.execSQL("""CREATE TABLE legacy_submissions(id TEXT PRIMARY KEY,account_key TEXT NOT NULL,run_generation INTEGER NOT NULL,day_key TEXT NOT NULL,window_key TEXT NOT NULL,media_path TEXT NOT NULL,payload_hash TEXT NOT NULL,state TEXT NOT NULL,click_claimed INTEGER NOT NULL,created_at INTEGER NOT NULL,valid_until INTEGER NOT NULL,receipt_ref TEXT NOT NULL DEFAULT '',settled_at INTEGER NOT NULL DEFAULT 0,rest_until INTEGER NOT NULL DEFAULT 0)""")
|
||||
db.execSQL("CREATE INDEX legacy_account_state ON legacy_submissions(account_key,state)")
|
||||
}
|
||||
|
||||
fun fresh(snapshot: AccountQuotaSnapshot, now: Long) =
|
||||
now >= snapshot.capturedAtMs && now - snapshot.capturedAtMs <= 5_000 && now < snapshot.validUntilMs
|
||||
|
||||
fun boundAccount(db: SQLiteDatabase): String? = db.rawQuery("SELECT account_key FROM account_binding WHERE id=1", null).use {
|
||||
if (it.moveToFirst()) it.getString(0) else null
|
||||
}
|
||||
|
||||
fun bind(db: SQLiteDatabase, account: String, snapshot: AccountQuotaSnapshot, now: Long): Boolean {
|
||||
require(account.isNotBlank())
|
||||
if (!fresh(snapshot, now)) return false
|
||||
val bound = boundAccount(db)
|
||||
if (bound != null && bound != account) return false
|
||||
db.insertWithOnConflict("account_binding", null, ContentValues().apply {
|
||||
put("id", 1); put("account_key", account); put("rest_until", snapshot.restUntilMs)
|
||||
}, SQLiteDatabase.CONFLICT_IGNORE)
|
||||
synchronize(db, account, snapshot)
|
||||
return true
|
||||
}
|
||||
|
||||
fun synchronize(db: SQLiteDatabase, account: String, snapshot: AccountQuotaSnapshot): AccountQuotaSnapshot {
|
||||
check(boundAccount(db) == account)
|
||||
db.insertWithOnConflict("budgets", null, ContentValues().apply {
|
||||
put("account_key", account); put("day_key", snapshot.dayKey); put("legacy_used", snapshot.legacyUsed)
|
||||
}, SQLiteDatabase.CONFLICT_IGNORE)
|
||||
db.execSQL("UPDATE budgets SET legacy_used=MAX(legacy_used,?) WHERE account_key=? AND day_key=?", arrayOf(snapshot.legacyUsed, account, snapshot.dayKey))
|
||||
snapshot.segmentCounts.forEachIndexed { segment, used ->
|
||||
val window = "${snapshot.dayKey}:$segment"
|
||||
db.insertWithOnConflict("budget_windows", null, ContentValues().apply {
|
||||
put("account_key", account); put("day_key", snapshot.dayKey); put("window_key", window); put("legacy_used", used)
|
||||
}, SQLiteDatabase.CONFLICT_IGNORE)
|
||||
db.execSQL("UPDATE budget_windows SET legacy_used=MAX(legacy_used,?) WHERE account_key=? AND day_key=? AND window_key=?", arrayOf(used, account, snapshot.dayKey, window))
|
||||
}
|
||||
db.execSQL("UPDATE account_binding SET rest_until=MAX(rest_until,?) WHERE id=1", arrayOf(snapshot.restUntilMs))
|
||||
val state = state(db, account, snapshot.dayKey)
|
||||
return snapshot.copy(legacyUsed = state.used, legacyWindowUsed = state.windows[snapshot.windowKey] ?: 0, restUntilMs = state.restUntilMs)
|
||||
}
|
||||
|
||||
fun state(db: SQLiteDatabase, account: String, day: String): LegacyBudgetState {
|
||||
val used = db.rawQuery("SELECT legacy_used FROM budgets WHERE account_key=? AND day_key=?", arrayOf(account, day)).use { if (it.moveToFirst()) it.getInt(0) else 0 }
|
||||
val windows = db.rawQuery("SELECT window_key,legacy_used FROM budget_windows WHERE account_key=? AND day_key=?", arrayOf(account, day)).use { c ->
|
||||
buildMap { while (c.moveToNext()) put(c.getString(0), c.getInt(1)) }
|
||||
}
|
||||
val rest = db.rawQuery("SELECT rest_until FROM account_binding WHERE account_key=?", arrayOf(account)).use { if (it.moveToFirst()) it.getLong(0) else 0 }
|
||||
return LegacyBudgetState(day, used, windows, rest)
|
||||
}
|
||||
|
||||
fun legacyEntries(db: SQLiteDatabase, account: String): List<CrossQuotaEntry> = db.rawQuery(
|
||||
"SELECT day_key,window_key,state,settled_at,rest_until,id FROM legacy_submissions WHERE account_key=? AND state!='NOT_SUBMITTED'", arrayOf(account),
|
||||
).use { c -> buildList { while (c.moveToNext()) add(CrossQuotaEntry(c.getString(0), CrossContentKind.VIDEO,
|
||||
if (c.getString(2) == "CONFIRMED") CrossReservationState.SETTLED else CrossReservationState.RESERVED,
|
||||
legacy = true, windowKey = c.getString(1), settledAtMs = c.getLong(3), restUntilMs = c.getLong(4), attemptId = c.getString(5))) } }
|
||||
|
||||
fun beginLegacy(db: SQLiteDatabase, account: String, generation: Long, mediaPath: String, payloadHash: String,
|
||||
budget: CrossSubmissionBudget, entries: List<CrossQuotaEntry>, now: Long, id: String): LegacyPublishReservation? {
|
||||
require(id.isNotBlank())
|
||||
require(mediaPath.isNotBlank() && payloadHash.matches(Regex("[a-fA-F0-9]{64}")))
|
||||
legacy(db, id)?.let { previous ->
|
||||
return previous.takeIf { it.accountKey == account && it.runGeneration == generation && it.mediaPath == mediaPath &&
|
||||
it.payloadHash == payloadHash && it.state == CrossAttemptState.INTENT && !it.clickClaimed }
|
||||
}
|
||||
val snapshot = budget.quotaSnapshot ?: return null
|
||||
if (snapshot.dayKey != budget.dayKey || !fresh(snapshot, now) || boundAccount(db) != account) return null
|
||||
val normalized = synchronize(db, account, snapshot)
|
||||
if (CrossTaskPolicy.budgetRejection(budget.copy(legacySubmittedCount = normalized.legacyUsed, quotaSnapshot = normalized), null, entries, now) != null) return null
|
||||
val duplicate = db.rawQuery("SELECT 1 FROM legacy_submissions WHERE account_key=? AND payload_hash=? AND state!='NOT_SUBMITTED' LIMIT 1", arrayOf(account, payloadHash)).use { it.moveToFirst() }
|
||||
if (duplicate) return null
|
||||
db.insertOrThrow("legacy_submissions", null, ContentValues().apply {
|
||||
put("id", id); put("account_key", account); put("run_generation", generation); put("day_key", snapshot.dayKey)
|
||||
put("window_key", snapshot.windowKey); put("media_path", mediaPath); put("payload_hash", payloadHash)
|
||||
put("state", "INTENT"); put("click_claimed", 0); put("created_at", now)
|
||||
put("valid_until", minOf(snapshot.validUntilMs, snapshot.capturedAtMs + 5_001))
|
||||
})
|
||||
return legacy(db, id)
|
||||
}
|
||||
|
||||
fun legacy(db: SQLiteDatabase, id: String): LegacyPublishReservation? = db.rawQuery(
|
||||
"SELECT id,account_key,run_generation,day_key,window_key,media_path,payload_hash,state,click_claimed FROM legacy_submissions WHERE id=?", arrayOf(id),
|
||||
).use { if (it.moveToFirst()) LegacyPublishReservation(it.getString(0), it.getString(1), it.getLong(2), it.getString(3), it.getString(4), it.getString(5), it.getString(6), CrossAttemptState.valueOf(it.getString(7)), it.getInt(8) == 1) else null }
|
||||
|
||||
fun claimLegacy(db: SQLiteDatabase, id: String, generation: Long, now: Long): Boolean = db.update("legacy_submissions",
|
||||
ContentValues().apply { put("click_claimed", 1) },
|
||||
"id=? AND run_generation=? AND state='INTENT' AND click_claimed=0 AND valid_until>? AND account_key=(SELECT account_key FROM account_binding WHERE id=1 AND rest_until<=?)",
|
||||
arrayOf(id, generation.toString(), now.toString(), now.toString())) == 1
|
||||
|
||||
fun markLegacyUnknown(db: SQLiteDatabase, id: String): Boolean = db.update("legacy_submissions",
|
||||
ContentValues().apply { put("state", "UNKNOWN") }, "id=? AND state IN ('INTENT','UNKNOWN')", arrayOf(id)) == 1
|
||||
|
||||
/** 回执核对器给出实际提交日界/时段。绝对基线只加一次,之后用其投影回旧配额。 */
|
||||
fun settleLegacy(db: SQLiteDatabase, id: String, receipt: String, snapshot: AccountQuotaSnapshot, period: SubmissionBudgetPeriod, restUntil: Long, now: Long): LegacyBudgetState? {
|
||||
require(receipt.isNotBlank() && restUntil >= 0)
|
||||
val attempt = legacy(db, id) ?: return null
|
||||
if (attempt.state == CrossAttemptState.CONFIRMED) {
|
||||
val matches = db.rawQuery("SELECT receipt_ref FROM legacy_submissions WHERE id=?", arrayOf(id)).use { it.moveToFirst(); it.getString(0) == receipt }
|
||||
return if (matches) state(db, attempt.accountKey, attempt.dayKey) else null
|
||||
}
|
||||
if (attempt.state !in setOf(CrossAttemptState.INTENT, CrossAttemptState.UNKNOWN) || !attempt.clickClaimed ||
|
||||
boundAccount(db) != attempt.accountKey || !fresh(snapshot, now)) return null
|
||||
synchronize(db, attempt.accountKey, snapshot)
|
||||
db.insertWithOnConflict("budgets", null, ContentValues().apply {
|
||||
put("account_key", attempt.accountKey); put("day_key", period.dayKey); put("legacy_used", 0)
|
||||
}, SQLiteDatabase.CONFLICT_IGNORE)
|
||||
db.insertWithOnConflict("budget_windows", null, ContentValues().apply {
|
||||
put("account_key", attempt.accountKey); put("day_key", period.dayKey); put("window_key", period.windowKey); put("legacy_used", 0)
|
||||
}, SQLiteDatabase.CONFLICT_IGNORE)
|
||||
db.execSQL("UPDATE budgets SET legacy_used=legacy_used+1 WHERE account_key=? AND day_key=?", arrayOf(attempt.accountKey, period.dayKey))
|
||||
db.execSQL("UPDATE budget_windows SET legacy_used=legacy_used+1 WHERE account_key=? AND day_key=? AND window_key=?", arrayOf(attempt.accountKey, period.dayKey, period.windowKey))
|
||||
db.update("legacy_submissions", ContentValues().apply {
|
||||
put("state", "CONFIRMED"); put("receipt_ref", receipt); put("day_key", period.dayKey); put("window_key", period.windowKey)
|
||||
put("settled_at", now); put("rest_until", restUntil)
|
||||
}, "id=?", arrayOf(id))
|
||||
db.execSQL("UPDATE account_binding SET rest_until=MAX(rest_until,?) WHERE id=1", arrayOf(restUntil))
|
||||
return state(db, attempt.accountKey, period.dayKey)
|
||||
}
|
||||
|
||||
fun releaseLegacy(db: SQLiteDatabase, id: String, evidence: String): Boolean {
|
||||
require(evidence.isNotBlank())
|
||||
return db.update("legacy_submissions", ContentValues().apply { put("state", "NOT_SUBMITTED"); put("receipt_ref", evidence) },
|
||||
"id=? AND state IN ('INTENT','UNKNOWN')", arrayOf(id)) == 1
|
||||
}
|
||||
|
||||
fun releaseUnclicked(db: SQLiteDatabase, id: String, generation: Long): Boolean = db.update("legacy_submissions", ContentValues().apply {
|
||||
put("state", "NOT_SUBMITTED"); put("receipt_ref", "local-click-never-claimed:$id")
|
||||
}, "id=? AND run_generation=? AND click_claimed=0 AND state IN ('INTENT','UNKNOWN')", arrayOf(id, generation.toString())) == 1
|
||||
}
|
||||
@@ -0,0 +1,427 @@
|
||||
package com.haorui.app.crossplatform.data
|
||||
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.database.Cursor
|
||||
import android.database.sqlite.SQLiteDatabase
|
||||
import android.database.sqlite.SQLiteOpenHelper
|
||||
import com.haorui.app.crossplatform.model.*
|
||||
import com.haorui.app.crossplatform.schedule.CrossRunLifecycle
|
||||
import com.haorui.app.crossplatform.schedule.CrossRunPersistence
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.util.UUID
|
||||
|
||||
/** 本机任务与提交日志。正式提交必须先持久化意图,再领取一次点击许可。 */
|
||||
class CrossPublishTaskStore private constructor(context: Context) : CrossRunPersistence {
|
||||
companion object {
|
||||
@Volatile private var instance: CrossPublishTaskStore? = null
|
||||
fun get(context: Context): CrossPublishTaskStore = instance ?: synchronized(this) {
|
||||
instance ?: CrossPublishTaskStore(context.applicationContext).also { instance = it }
|
||||
}
|
||||
}
|
||||
|
||||
private val helper = TaskDatabase(context)
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
private val mutex = Mutex()
|
||||
private val _tasks = MutableStateFlow<List<CrossPublishTask>>(emptyList())
|
||||
val tasks: StateFlow<List<CrossPublishTask>> = _tasks.asStateFlow()
|
||||
private val _loaded = MutableStateFlow(false)
|
||||
val isLoaded: StateFlow<Boolean> = _loaded.asStateFlow()
|
||||
private val _error = MutableStateFlow<String?>(null)
|
||||
val loadError: StateFlow<String?> = _error.asStateFlow()
|
||||
private val initialization = scope.async { writeInternal { recoverDatabase(it) } }
|
||||
val runLifecycle by lazy { CrossRunLifecycle(this, scope) }
|
||||
|
||||
init {
|
||||
scope.launch {
|
||||
runCatching { initialization.await(); _loaded.value = true }
|
||||
.onFailure { _error.value = "本机任务库加载失败:${it.javaClass.simpleName}" }
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun find(id: String): CrossPublishTask? = read { task(it, id) }
|
||||
|
||||
suspend fun findEvent(id: String): CrossEvent? = read { db ->
|
||||
db.query("events", null, "id=?", arrayOf(id), null, null, null).use { c ->
|
||||
if (c.moveToFirst()) CrossEvent(c.s("id"), c.s("category"), c.s("fact_json"), c.s("source_urls_json"), c.l("updated_at")) else null
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun enqueue(value: CrossPublishTask): Boolean = write { db ->
|
||||
require(value.id.isNotBlank() && value.accountKey.isNotBlank() && value.eventId.isNotBlank())
|
||||
require(value.publicationVersion > 0 && value.revision > 0 && value.state == CrossTaskState.DISCOVERED)
|
||||
if (value.runGeneration > 0 && !active(db, value.runGeneration)) return@write false
|
||||
val event = ContentValues().apply {
|
||||
put("id", value.eventId); put("category", ""); put("fact_json", ""); put("source_urls_json", ""); put("updated_at", value.updatedAtMs)
|
||||
}
|
||||
db.insertWithOnConflict("events", null, event, SQLiteDatabase.CONFLICT_IGNORE)
|
||||
db.insertWithOnConflict("tasks", null, values(value), SQLiteDatabase.CONFLICT_IGNORE) != -1L
|
||||
}
|
||||
|
||||
suspend fun saveEvent(event: CrossEvent) = write { db ->
|
||||
require(event.id.isNotBlank())
|
||||
val v = ContentValues().apply {
|
||||
put("id", event.id); put("category", event.category); put("fact_json", event.factPacketJson)
|
||||
put("source_urls_json", event.sourceUrlsJson); put("updated_at", event.updatedAtMs)
|
||||
}
|
||||
db.insertWithOnConflict("events", null, v, SQLiteDatabase.CONFLICT_IGNORE)
|
||||
db.update("events", v, "id=?", arrayOf(event.id))
|
||||
Unit
|
||||
}
|
||||
|
||||
suspend fun saveAsset(asset: CrossAsset, generation: Long): Boolean = write { db ->
|
||||
require(asset.id.isNotBlank() && asset.localPath.isNotBlank() && asset.sizeBytes >= 0)
|
||||
require(asset.sha256.matches(Regex("[a-fA-F0-9]{64}")))
|
||||
val t = task(db, asset.taskId) ?: return@write false
|
||||
if (!active(db, generation) || t.runGeneration != generation || t.revision != asset.revision ||
|
||||
t.state == CrossTaskState.PAUSED || t.state in externalStates) return@write false
|
||||
db.insertWithOnConflict("assets", null, ContentValues().apply {
|
||||
put("id", asset.id); put("task_id", asset.taskId); put("revision", asset.revision)
|
||||
put("local_path", asset.localPath); put("sha256", asset.sha256); put("size_bytes", asset.sizeBytes); put("rights_ref", asset.rightsRef)
|
||||
}, SQLiteDatabase.CONFLICT_REPLACE) != -1L
|
||||
}
|
||||
|
||||
suspend fun assets(taskId: String): List<CrossAsset> = read { db ->
|
||||
db.query("assets", null, "task_id=?", arrayOf(taskId), null, null, "id").use { c ->
|
||||
buildList { while (c.moveToNext()) add(CrossAsset(c.s("id"), c.s("task_id"), c.i("revision"), c.s("local_path"), c.s("sha256"), c.l("size_bytes"), c.s("rights_ref"))) }
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun beginRun(): Long = write { db ->
|
||||
interruptTasks(db, "旧运行已结束,等待重新检查", "旧运行提交结果待核对")
|
||||
val generation = readGeneration(db) + 1
|
||||
setControl(db, generation, true)
|
||||
generation
|
||||
}
|
||||
|
||||
/** 中断提交后的状态继续占用额度;停止不删除素材。 */
|
||||
override suspend fun pauseRun(): Long = write { db ->
|
||||
val next = readGeneration(db) + 1
|
||||
setControl(db, next, false)
|
||||
interruptTasks(db, "运行已停止", "提交期间停止,结果待核对")
|
||||
next
|
||||
}
|
||||
|
||||
suspend fun currentGeneration(): Long = read { readGeneration(it) }
|
||||
|
||||
/** 调用方必须已现场核验稳定账号身份;持久化绑定不能代替下次现场核验。 */
|
||||
suspend fun bindLegacyAccount(accountKey: String, generation: Long, snapshot: AccountQuotaSnapshot): Boolean = write { db ->
|
||||
active(db, generation) && AccountBudgetTransactions.bind(db, accountKey, snapshot, System.currentTimeMillis())
|
||||
}
|
||||
|
||||
suspend fun boundAccountKey(): String? = read { AccountBudgetTransactions.boundAccount(it) }
|
||||
|
||||
suspend fun hasSharedBudgetHistory(): Boolean = read { db ->
|
||||
AccountBudgetTransactions.boundAccount(db) != null || db.rawQuery(
|
||||
"SELECT 1 FROM quota_ledger WHERE state!='RELEASED' UNION ALL SELECT 1 FROM budgets WHERE legacy_used>0 LIMIT 1", null,
|
||||
).use { it.moveToFirst() }
|
||||
}
|
||||
|
||||
suspend fun legacyBudgetState(dayKey: String): LegacyBudgetState? = read { db ->
|
||||
AccountBudgetTransactions.boundAccount(db)?.let { AccountBudgetTransactions.state(db, it, dayKey) }
|
||||
}
|
||||
|
||||
suspend fun beginLegacySubmission(accountKey: String, generation: Long, mediaPath: String, payloadHash: String,
|
||||
budget: CrossSubmissionBudget, attemptId: String = UUID.randomUUID().toString()): LegacyPublishReservation? = write { db ->
|
||||
if (!active(db, generation)) return@write null
|
||||
AccountBudgetTransactions.beginLegacy(db, accountKey, generation, mediaPath, payloadHash, budget, ledger(db, accountKey), System.currentTimeMillis(), attemptId)
|
||||
}
|
||||
|
||||
suspend fun legacySubmission(id: String): LegacyPublishReservation? = read { AccountBudgetTransactions.legacy(it, id) }
|
||||
|
||||
suspend fun claimLegacySubmissionClick(id: String, generation: Long, budget: CrossSubmissionBudget): Boolean = write { db ->
|
||||
if (!active(db, generation)) return@write false
|
||||
val reservation = AccountBudgetTransactions.legacy(db, id) ?: return@write false
|
||||
val now = System.currentTimeMillis()
|
||||
val normalized = refreshBudget(db, reservation.accountKey, budget, now) ?: return@write false
|
||||
if (normalized.dayKey != reservation.dayKey || normalized.quotaSnapshot!!.windowKey != reservation.windowKey ||
|
||||
CrossTaskPolicy.budgetRejection(normalized, null, ledger(db, reservation.accountKey).filter { it.attemptId != id }, now) != null) return@write false
|
||||
AccountBudgetTransactions.claimLegacy(db, id, generation, now)
|
||||
}
|
||||
|
||||
suspend fun markLegacySubmissionUnknown(id: String): Boolean = write { AccountBudgetTransactions.markLegacyUnknown(it, id) }
|
||||
|
||||
suspend fun recordLegacyReceipt(id: String, receiptRef: String, currentSnapshot: AccountQuotaSnapshot, restUntilMs: Long,
|
||||
submissionPeriod: SubmissionBudgetPeriod = currentSnapshot.period): LegacyBudgetState? = write { db ->
|
||||
AccountBudgetTransactions.settleLegacy(db, id, receiptRef, currentSnapshot, submissionPeriod, restUntilMs, System.currentTimeMillis())
|
||||
}
|
||||
|
||||
suspend fun confirmLegacyNotSubmitted(id: String, evidenceRef: String): Boolean = write { AccountBudgetTransactions.releaseLegacy(it, id, evidenceRef) }
|
||||
|
||||
suspend fun releaseUnclickedLegacySubmission(id: String, generation: Long): Boolean = write { AccountBudgetTransactions.releaseUnclicked(it, id, generation) }
|
||||
|
||||
suspend fun protectedLegacyMediaPaths(): Set<String> = read { db ->
|
||||
db.rawQuery("SELECT media_path FROM legacy_submissions WHERE state IN ('INTENT','UNKNOWN')", null).use { c -> buildSet { while (c.moveToNext()) add(c.getString(0)) } }
|
||||
}
|
||||
|
||||
suspend fun protectedSubmissionMediaPaths(): Set<String> = read { db ->
|
||||
db.rawQuery("""SELECT media_path FROM legacy_submissions WHERE state IN ('INTENT','UNKNOWN')
|
||||
UNION SELECT media_path FROM tasks WHERE state IN ('SUBMIT_INTENT','RESULT_UNKNOWN') AND media_path!=''
|
||||
UNION SELECT assets.local_path FROM assets JOIN tasks ON tasks.id=assets.task_id WHERE tasks.state IN ('SUBMIT_INTENT','RESULT_UNKNOWN')""", null
|
||||
).use { c -> buildSet { while (c.moveToNext()) add(c.getString(0)) } }
|
||||
}
|
||||
|
||||
suspend fun transition(id: String, expectedState: CrossTaskState, targetState: CrossTaskState, generation: Long, reason: String = "", readyLimit: Int = 10): Boolean = write { db ->
|
||||
if (!active(db, generation) || !CrossTaskPolicy.canTransition(expectedState, targetState)) return@write false
|
||||
val t = task(db, id) ?: return@write false
|
||||
if (t.state != expectedState || t.runGeneration != generation) return@write false
|
||||
if (targetState in setOf(CrossTaskState.PREPARED, CrossTaskState.READY) && CrossTaskPolicy.preparationRejection(t, System.currentTimeMillis()) != null) return@write false
|
||||
if (targetState == CrossTaskState.READY) {
|
||||
if (CrossTaskPolicy.preparationRejection(t, System.currentTimeMillis()) != null) return@write false
|
||||
val readyCount = db.rawQuery("SELECT COUNT(*) FROM tasks WHERE state='READY'", null).use { it.moveToFirst(); it.getInt(0) }
|
||||
if (readyLimit <= 0 || readyCount >= readyLimit) return@write false
|
||||
}
|
||||
updateState(db, t, targetState, reason, if (targetState == CrossTaskState.PAUSED) expectedState else null)
|
||||
true
|
||||
}
|
||||
|
||||
suspend fun prepare(id: String, generation: Long, bodyText: String, mediaPath: String, evidenceJson: String, rightsRef: String, payloadHash: String): Boolean = write { db ->
|
||||
val t = task(db, id) ?: return@write false
|
||||
if (!active(db, generation) || t.runGeneration != generation || t.state != CrossTaskState.FILTERED) return@write false
|
||||
val prepared = t.copy(bodyText = bodyText, mediaPath = mediaPath, evidenceJson = evidenceJson, rightsRef = rightsRef, payloadHash = payloadHash)
|
||||
if (CrossTaskPolicy.preparationRejection(prepared, System.currentTimeMillis()) != null) return@write false
|
||||
db.update("tasks", values(prepared.copy(state = CrossTaskState.PREPARED, updatedAtMs = System.currentTimeMillis())), "id=?", arrayOf(id)) == 1
|
||||
}
|
||||
|
||||
suspend fun resumeTask(id: String, generation: Long, readyLimit: Int = 10): Boolean = write { db ->
|
||||
if (!active(db, generation)) return@write false
|
||||
val t = task(db, id) ?: return@write false
|
||||
if (t.state != CrossTaskState.PAUSED) return@write false
|
||||
val next = t.resumeState ?: return@write false
|
||||
if (next !in setOf(CrossTaskState.DISCOVERED, CrossTaskState.FILTERED, CrossTaskState.PREPARED, CrossTaskState.READY, CrossTaskState.RETRY_WAIT)) return@write false
|
||||
if (next in setOf(CrossTaskState.PREPARED, CrossTaskState.READY) && CrossTaskPolicy.preparationRejection(t, System.currentTimeMillis()) != null) return@write false
|
||||
if (next == CrossTaskState.READY && !hasReadyCapacity(db, readyLimit)) return@write false
|
||||
db.update("tasks", ContentValues().apply {
|
||||
put("state", next.name); put("run_generation", generation); put("reason", ""); putNull("resume_state"); put("updated_at", System.currentTimeMillis())
|
||||
}, "id=?", arrayOf(id)) == 1
|
||||
}
|
||||
|
||||
/** 中断编辑/明确未提交之后,协调器核对页面和成品才可显式重新排队。 */
|
||||
suspend fun resumeAfterPageCheck(id: String, generation: Long, pageCheckRef: String, readyLimit: Int = 10): Boolean = write { db ->
|
||||
require(pageCheckRef.isNotBlank())
|
||||
if (!active(db, generation)) return@write false
|
||||
val t = task(db, id) ?: return@write false
|
||||
if (t.state != CrossTaskState.PAUSED || t.resumeState !in setOf(null, CrossTaskState.EDITING)) return@write false
|
||||
val unresolved = db.rawQuery("SELECT COUNT(*) FROM attempts WHERE task_id=? AND state IN ('INTENT','UNKNOWN','CONFIRMED')", arrayOf(id)).use { it.moveToFirst(); it.getInt(0) }
|
||||
if (unresolved != 0 || !hasReadyCapacity(db, readyLimit) || CrossTaskPolicy.preparationRejection(t, System.currentTimeMillis()) != null) return@write false
|
||||
db.update("tasks", ContentValues().apply {
|
||||
put("state", CrossTaskState.READY.name); put("run_generation", generation); put("reason", "页面及成品已核对:$pageCheckRef")
|
||||
putNull("resume_state"); put("updated_at", System.currentTimeMillis())
|
||||
}, "id=?", arrayOf(id)) == 1
|
||||
}
|
||||
|
||||
suspend fun claimNextReady(generation: Long, accountKey: String): CrossPublishTask? = write { db ->
|
||||
if (!active(db, generation)) return@write null
|
||||
val candidate = db.query("tasks", null, "state='READY' AND account_key=? AND run_generation=?", arrayOf(accountKey, generation.toString()), null, null, "created_at,id").use { c ->
|
||||
var found: CrossPublishTask? = null
|
||||
while (c.moveToNext() && found == null) {
|
||||
val t = row(c)
|
||||
if (CrossTaskPolicy.preparationRejection(t, System.currentTimeMillis()) == null) found = t
|
||||
else updateState(db, t, CrossTaskState.SKIPPED, "成品信息缺失或已过期")
|
||||
}
|
||||
found
|
||||
} ?: return@write null
|
||||
val claimed = candidate.copy(state = CrossTaskState.EDITING, runGeneration = generation, updatedAtMs = System.currentTimeMillis())
|
||||
db.update("tasks", values(claimed), "id=? AND state='READY'", arrayOf(candidate.id))
|
||||
claimed
|
||||
}
|
||||
|
||||
/** PUBLISH 必须提供共享额度快照;草稿不占正式提交额度。 */
|
||||
suspend fun beginSubmission(id: String, generation: Long, mode: CrossSubmissionMode, budget: CrossSubmissionBudget? = null): CrossSubmissionAttempt? = write { db ->
|
||||
val t = task(db, id) ?: return@write null
|
||||
val now = System.currentTimeMillis()
|
||||
if (!CrossTaskPolicy.canBeginSubmission(t, generation, readGeneration(db), active(db, generation), now)) return@write null
|
||||
if (mode == CrossSubmissionMode.PUBLISH) {
|
||||
val b = budget ?: return@write null
|
||||
val normalized = refreshBudget(db, t.accountKey, b, now) ?: return@write null
|
||||
if (CrossTaskPolicy.budgetRejection(normalized, t.contentKind, ledger(db, t.accountKey), now) != null) return@write null
|
||||
}
|
||||
val attempt = CrossSubmissionAttempt(UUID.randomUUID().toString(), id, t.revision, generation, mode, CrossAttemptState.INTENT, false, if (mode == CrossSubmissionMode.PUBLISH) budget!!.dayKey else null, now)
|
||||
db.insertOrThrow("attempts", null, ContentValues().apply {
|
||||
put("id", attempt.id); put("task_id", id); put("revision", t.revision); put("run_generation", generation)
|
||||
put("mode", mode.name); put("state", attempt.state.name); put("click_claimed", 0)
|
||||
put("budget_day", attempt.budgetDayKey); put("created_at", now); put("receipt_ref", "")
|
||||
})
|
||||
if (mode == CrossSubmissionMode.PUBLISH) db.insertOrThrow("quota_ledger", null, ContentValues().apply {
|
||||
put("attempt_id", attempt.id); put("account_key", t.accountKey); put("day_key", budget!!.dayKey)
|
||||
put("kind", t.contentKind.name); put("state", CrossReservationState.RESERVED.name)
|
||||
put("window_key", budget.quotaSnapshot!!.windowKey)
|
||||
put("valid_until", minOf(budget.quotaSnapshot.validUntilMs, budget.quotaSnapshot.capturedAtMs + 5_001))
|
||||
})
|
||||
updateState(db, t, CrossTaskState.SUBMIT_INTENT, "提交意图已保存,等待一次点击许可")
|
||||
attempt
|
||||
}
|
||||
|
||||
suspend fun claimSubmissionClick(attemptId: String, generation: Long, budget: CrossSubmissionBudget? = null): Boolean = write { db ->
|
||||
val a = attempt(db, attemptId) ?: return@write false
|
||||
val t = task(db, a.taskId) ?: return@write false
|
||||
if (!active(db, generation) || a.runGeneration != generation || a.state != CrossAttemptState.INTENT || t.state != CrossTaskState.SUBMIT_INTENT) return@write false
|
||||
if (a.mode == CrossSubmissionMode.PUBLISH) {
|
||||
val now = System.currentTimeMillis()
|
||||
val normalized = refreshBudget(db, t.accountKey, budget ?: return@write false, now) ?: return@write false
|
||||
val valid = db.rawQuery("SELECT 1 FROM quota_ledger WHERE attempt_id=? AND valid_until>? AND day_key=? AND window_key=?", arrayOf(attemptId, now.toString(), normalized.dayKey, normalized.quotaSnapshot!!.windowKey)).use { it.moveToFirst() }
|
||||
if (!valid) return@write false
|
||||
if (CrossTaskPolicy.budgetRejection(normalized, t.contentKind, ledger(db, t.accountKey).filter { it.attemptId != attemptId }, now) != null) return@write false
|
||||
}
|
||||
db.update("attempts", ContentValues().apply { put("click_claimed", 1) }, "id=? AND click_claimed=0 AND state='INTENT'", arrayOf(attemptId)) == 1
|
||||
}
|
||||
|
||||
suspend fun markSubmissionUnknown(attemptId: String, reason: String): Boolean = write { db ->
|
||||
val a = attempt(db, attemptId) ?: return@write false
|
||||
val t = task(db, a.taskId) ?: return@write false
|
||||
if (a.state !in setOf(CrossAttemptState.INTENT, CrossAttemptState.UNKNOWN)) return@write false
|
||||
db.update("attempts", ContentValues().apply { put("state", CrossAttemptState.UNKNOWN.name) }, "id=?", arrayOf(attemptId))
|
||||
updateState(db, t, CrossTaskState.RESULT_UNKNOWN, reason)
|
||||
true
|
||||
}
|
||||
|
||||
/** 由作品/草稿核对器提供明确回执,正式提交还须提供核对后的额度日界。 */
|
||||
suspend fun recordReceipt(attemptId: String, receiptRef: String, submissionPeriod: SubmissionBudgetPeriod? = null, restUntilMs: Long = 0): Boolean = write { db ->
|
||||
require(receiptRef.isNotBlank())
|
||||
require(restUntilMs >= 0)
|
||||
val a = attempt(db, attemptId) ?: return@write false
|
||||
val t = task(db, a.taskId) ?: return@write false
|
||||
if (a.state == CrossAttemptState.CONFIRMED) return@write a.receiptRef == receiptRef
|
||||
if (a.state !in setOf(CrossAttemptState.INTENT, CrossAttemptState.UNKNOWN)) return@write false
|
||||
if (a.mode == CrossSubmissionMode.PUBLISH && submissionPeriod == null) return@write false
|
||||
db.update("attempts", ContentValues().apply { put("state", CrossAttemptState.CONFIRMED.name); put("receipt_ref", receiptRef) }, "id=?", arrayOf(attemptId))
|
||||
if (a.mode == CrossSubmissionMode.PUBLISH) db.update("quota_ledger", ContentValues().apply {
|
||||
put("state", CrossReservationState.SETTLED.name); put("day_key", submissionPeriod!!.dayKey)
|
||||
put("window_key", submissionPeriod.windowKey); put("settled_at", System.currentTimeMillis()); put("rest_until", restUntilMs)
|
||||
}, "attempt_id=? AND state='RESERVED'", arrayOf(attemptId))
|
||||
if (a.mode == CrossSubmissionMode.PUBLISH) db.execSQL("UPDATE account_binding SET rest_until=MAX(rest_until,?) WHERE account_key=?", arrayOf(restUntilMs, t.accountKey))
|
||||
updateState(db, t, if (a.mode == CrossSubmissionMode.PUBLISH) CrossTaskState.SUBMITTED else CrossTaskState.DRAFT_SAVED, "回执已核对")
|
||||
db.update("tasks", ContentValues().apply { put("receipt_ref", receiptRef) }, "id=?", arrayOf(t.id))
|
||||
true
|
||||
}
|
||||
|
||||
/** 仅在明确核对未提交后释放预占;不会自动回到 READY。 */
|
||||
suspend fun confirmNotSubmitted(attemptId: String, evidenceRef: String): Boolean = write { db ->
|
||||
require(evidenceRef.isNotBlank())
|
||||
val a = attempt(db, attemptId) ?: return@write false
|
||||
val t = task(db, a.taskId) ?: return@write false
|
||||
if (a.state !in setOf(CrossAttemptState.INTENT, CrossAttemptState.UNKNOWN)) return@write false
|
||||
db.update("attempts", ContentValues().apply { put("state", CrossAttemptState.NOT_SUBMITTED.name); put("receipt_ref", evidenceRef) }, "id=?", arrayOf(attemptId))
|
||||
db.update("quota_ledger", ContentValues().apply { put("state", CrossReservationState.RELEASED.name) }, "attempt_id=? AND state='RESERVED'", arrayOf(attemptId))
|
||||
updateState(db, t, CrossTaskState.PAUSED, "已核对未提交,需重新检查页面和成品")
|
||||
true
|
||||
}
|
||||
|
||||
suspend fun attempts(taskId: String): List<CrossSubmissionAttempt> = read { db ->
|
||||
db.query("attempts", null, "task_id=?", arrayOf(taskId), null, null, "created_at,id").use { c -> buildList { while (c.moveToNext()) add(attemptRow(c)) } }
|
||||
}
|
||||
|
||||
suspend fun budgetUsage(accountKey: String, dayKey: String): CrossBudgetUsage = read { db ->
|
||||
val entries = ledger(db, accountKey)
|
||||
val baseline = db.rawQuery("SELECT legacy_used FROM budgets WHERE account_key=? AND day_key=?", arrayOf(accountKey, dayKey)).use { if (it.moveToFirst()) it.getInt(0) else 0 }
|
||||
CrossBudgetUsage(baseline, entries.count { it.state == CrossReservationState.RESERVED }, entries.count { !it.legacy && it.state == CrossReservationState.SETTLED && it.dayKey == dayKey })
|
||||
}
|
||||
|
||||
private suspend fun <T> read(block: (SQLiteDatabase) -> T): T {
|
||||
initialization.await()
|
||||
return withContext(Dispatchers.IO) { mutex.withLock { block(helper.readableDatabase) } }
|
||||
}
|
||||
|
||||
private suspend fun <T> write(block: (SQLiteDatabase) -> T): T { initialization.await(); return writeInternal(block) }
|
||||
|
||||
private suspend fun <T> writeInternal(block: (SQLiteDatabase) -> T): T = withContext(Dispatchers.IO) {
|
||||
mutex.withLock {
|
||||
val db = helper.writableDatabase
|
||||
db.beginTransaction()
|
||||
val result = try { block(db).also { db.setTransactionSuccessful() } } finally { db.endTransaction() }
|
||||
_tasks.value = db.query("tasks", null, null, null, null, null, "created_at DESC,id").use { c -> buildList { while (c.moveToNext()) add(row(c)) } }
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
private fun recoverDatabase(db: SQLiteDatabase) {
|
||||
setControl(db, readGeneration(db) + 1, false)
|
||||
interruptTasks(db, "运行中断,需重新检查;编辑任务须先核对页面", "进程中断,提交结果待核对")
|
||||
}
|
||||
|
||||
private fun interruptTasks(db: SQLiteDatabase, reason: String, unknownReason: String) {
|
||||
db.execSQL("UPDATE tasks SET resume_state=state,state='PAUSED',reason=?,updated_at=? WHERE state IN ('DISCOVERED','FILTERED','PREPARED','READY','RETRY_WAIT','EDITING')", arrayOf(reason, System.currentTimeMillis()))
|
||||
unknownIntents(db, unknownReason)
|
||||
}
|
||||
|
||||
private fun unknownIntents(db: SQLiteDatabase, reason: String) {
|
||||
db.execSQL("UPDATE legacy_submissions SET state='UNKNOWN' WHERE state='INTENT'")
|
||||
db.execSQL("UPDATE attempts SET state='UNKNOWN' WHERE state='INTENT'")
|
||||
db.execSQL("UPDATE tasks SET state='RESULT_UNKNOWN',reason=?,updated_at=? WHERE state='SUBMIT_INTENT'", arrayOf(reason, System.currentTimeMillis()))
|
||||
}
|
||||
|
||||
private fun readGeneration(db: SQLiteDatabase): Long = db.rawQuery("SELECT generation FROM run_control WHERE id=1", null).use { it.moveToFirst(); it.getLong(0) }
|
||||
private fun active(db: SQLiteDatabase, generation: Long): Boolean = db.rawQuery("SELECT generation,active FROM run_control WHERE id=1", null).use { it.moveToFirst(); it.getLong(0) == generation && it.getInt(1) == 1 }
|
||||
private fun setControl(db: SQLiteDatabase, generation: Long, active: Boolean) { db.execSQL("UPDATE run_control SET generation=?,active=? WHERE id=1", arrayOf(generation, if (active) 1 else 0)) }
|
||||
|
||||
private fun refreshBudget(db: SQLiteDatabase, account: String, budget: CrossSubmissionBudget, now: Long): CrossSubmissionBudget? {
|
||||
val snapshot = budget.quotaSnapshot ?: return null
|
||||
if (AccountBudgetTransactions.boundAccount(db) != account || snapshot.dayKey != budget.dayKey || !AccountBudgetTransactions.fresh(snapshot, now)) return null
|
||||
val normalized = AccountBudgetTransactions.synchronize(db, account, snapshot)
|
||||
return budget.copy(legacySubmittedCount = maxOf(budget.legacySubmittedCount, normalized.legacyUsed), quotaSnapshot = normalized)
|
||||
}
|
||||
|
||||
private fun ledger(db: SQLiteDatabase, account: String): List<CrossQuotaEntry> = db.query("quota_ledger", null, "account_key=? AND state!='RELEASED'", arrayOf(account), null, null, null).use { c ->
|
||||
buildList { while (c.moveToNext()) add(CrossQuotaEntry(c.s("day_key"), CrossContentKind.valueOf(c.s("kind")), CrossReservationState.valueOf(c.s("state")),
|
||||
windowKey = c.s("window_key"), settledAtMs = c.l("settled_at"), restUntilMs = c.l("rest_until"), attemptId = c.s("attempt_id"))) }
|
||||
} + AccountBudgetTransactions.legacyEntries(db, account)
|
||||
|
||||
private fun updateState(db: SQLiteDatabase, t: CrossPublishTask, state: CrossTaskState, reason: String, resume: CrossTaskState? = null) {
|
||||
db.update("tasks", ContentValues().apply { put("state", state.name); put("reason", reason); put("resume_state", resume?.name); put("updated_at", System.currentTimeMillis()) }, "id=?", arrayOf(t.id))
|
||||
}
|
||||
private fun hasReadyCapacity(db: SQLiteDatabase, limit: Int): Boolean = limit > 0 && db.rawQuery("SELECT COUNT(*) FROM tasks WHERE state='READY'", null).use { it.moveToFirst(); it.getInt(0) < limit }
|
||||
private fun task(db: SQLiteDatabase, id: String): CrossPublishTask? = db.query("tasks", null, "id=?", arrayOf(id), null, null, null).use { if (it.moveToFirst()) row(it) else null }
|
||||
private fun attempt(db: SQLiteDatabase, id: String): CrossSubmissionAttempt? = db.query("attempts", null, "id=?", arrayOf(id), null, null, null).use { if (it.moveToFirst()) attemptRow(it) else null }
|
||||
private fun Cursor.s(name: String): String = getString(getColumnIndexOrThrow(name)) ?: ""
|
||||
private fun Cursor.l(name: String): Long = getLong(getColumnIndexOrThrow(name))
|
||||
private fun Cursor.i(name: String): Int = getInt(getColumnIndexOrThrow(name))
|
||||
private fun row(c: Cursor) = CrossPublishTask(c.s("id"), c.s("account_key"), c.s("event_id"), CrossContentKind.valueOf(c.s("kind")), c.s("title"), c.s("source_platform"), c.s("source_url"), CrossTaskState.valueOf(c.s("state")), c.s("body_text"), c.s("media_path"), c.s("evidence_json"), c.s("rights_ref"), c.s("payload_hash"), c.i("publication_version"), c.i("revision"), c.l("run_generation"), if (c.isNull(c.getColumnIndexOrThrow("published_at"))) null else c.l("published_at"), c.l("expires_at"), c.l("created_at"), c.l("updated_at"), c.s("reason"), c.s("receipt_ref"), c.s("resume_state").takeIf { it.isNotBlank() }?.let(CrossTaskState::valueOf))
|
||||
private fun attemptRow(c: Cursor) = CrossSubmissionAttempt(c.s("id"), c.s("task_id"), c.i("revision"), c.l("run_generation"), CrossSubmissionMode.valueOf(c.s("mode")), CrossAttemptState.valueOf(c.s("state")), c.i("click_claimed") == 1, c.s("budget_day").takeIf { it.isNotBlank() }, c.l("created_at"), c.s("receipt_ref"))
|
||||
private fun values(t: CrossPublishTask) = ContentValues().apply {
|
||||
put("id", t.id); put("account_key", t.accountKey); put("event_id", t.eventId); put("kind", t.contentKind.name); put("title", t.title)
|
||||
put("source_platform", t.sourcePlatform); put("source_url", t.sourceUrl); put("state", t.state.name); put("body_text", t.bodyText); put("media_path", t.mediaPath)
|
||||
put("evidence_json", t.evidenceJson); put("rights_ref", t.rightsRef); put("payload_hash", t.payloadHash); put("publication_version", t.publicationVersion); put("revision", t.revision)
|
||||
put("run_generation", t.runGeneration); put("published_at", t.publishedAtMs); put("expires_at", t.expiresAtMs); put("created_at", t.createdAtMs); put("updated_at", t.updatedAtMs)
|
||||
put("reason", t.reason); put("receipt_ref", t.receiptRef); put("resume_state", t.resumeState?.name)
|
||||
}
|
||||
private val externalStates get() = setOf(CrossTaskState.SUBMIT_INTENT, CrossTaskState.SUBMITTED, CrossTaskState.RESULT_UNKNOWN, CrossTaskState.DRAFT_SAVED)
|
||||
}
|
||||
|
||||
private class TaskDatabase(context: Context) : SQLiteOpenHelper(context, "crossplatform_tasks.db", null, 2) {
|
||||
override fun onConfigure(db: SQLiteDatabase) { db.setForeignKeyConstraintsEnabled(true) }
|
||||
override fun onCreate(db: SQLiteDatabase) {
|
||||
db.execSQL("CREATE TABLE run_control(id INTEGER PRIMARY KEY CHECK(id=1),generation INTEGER NOT NULL,active INTEGER NOT NULL)")
|
||||
db.execSQL("INSERT INTO run_control VALUES(1,0,0)")
|
||||
db.execSQL("CREATE TABLE events(id TEXT PRIMARY KEY,category TEXT NOT NULL,fact_json TEXT NOT NULL,source_urls_json TEXT NOT NULL,updated_at INTEGER NOT NULL)")
|
||||
db.execSQL("""CREATE TABLE tasks(id TEXT PRIMARY KEY,account_key TEXT NOT NULL,event_id TEXT NOT NULL REFERENCES events(id),kind TEXT NOT NULL,title TEXT NOT NULL,source_platform TEXT NOT NULL,source_url TEXT NOT NULL,state TEXT NOT NULL,body_text TEXT NOT NULL,media_path TEXT NOT NULL,evidence_json TEXT NOT NULL,rights_ref TEXT NOT NULL,payload_hash TEXT NOT NULL,publication_version INTEGER NOT NULL,revision INTEGER NOT NULL,run_generation INTEGER NOT NULL,published_at INTEGER,expires_at INTEGER NOT NULL,created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL,reason TEXT NOT NULL,receipt_ref TEXT NOT NULL,resume_state TEXT,UNIQUE(account_key,event_id,publication_version))""")
|
||||
db.execSQL("CREATE INDEX task_queue ON tasks(state,account_key,created_at)")
|
||||
db.execSQL("CREATE TABLE assets(id TEXT PRIMARY KEY,task_id TEXT NOT NULL REFERENCES tasks(id),revision INTEGER NOT NULL,local_path TEXT NOT NULL,sha256 TEXT NOT NULL,size_bytes INTEGER NOT NULL,rights_ref TEXT NOT NULL)")
|
||||
db.execSQL("CREATE TABLE attempts(id TEXT PRIMARY KEY,task_id TEXT NOT NULL REFERENCES tasks(id),revision INTEGER NOT NULL,run_generation INTEGER NOT NULL,mode TEXT NOT NULL,state TEXT NOT NULL,click_claimed INTEGER NOT NULL,budget_day TEXT,created_at INTEGER NOT NULL,receipt_ref TEXT NOT NULL)")
|
||||
db.execSQL("CREATE INDEX task_attempts ON attempts(task_id,created_at)")
|
||||
db.execSQL("CREATE TABLE budgets(account_key TEXT NOT NULL,day_key TEXT NOT NULL,legacy_used INTEGER NOT NULL,PRIMARY KEY(account_key,day_key))")
|
||||
db.execSQL("CREATE TABLE quota_ledger(attempt_id TEXT PRIMARY KEY REFERENCES attempts(id),account_key TEXT NOT NULL,day_key TEXT NOT NULL,kind TEXT NOT NULL,state TEXT NOT NULL)")
|
||||
db.execSQL("CREATE INDEX account_quota ON quota_ledger(account_key,day_key,state)")
|
||||
addAccountBudgetSchema(db)
|
||||
}
|
||||
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
|
||||
check(oldVersion == 1 && newVersion == 2) { "不支持的任务库迁移:$oldVersion → $newVersion" }
|
||||
addAccountBudgetSchema(db)
|
||||
}
|
||||
private fun addAccountBudgetSchema(db: SQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE quota_ledger ADD COLUMN window_key TEXT NOT NULL DEFAULT ''")
|
||||
db.execSQL("ALTER TABLE quota_ledger ADD COLUMN settled_at INTEGER NOT NULL DEFAULT 0")
|
||||
db.execSQL("ALTER TABLE quota_ledger ADD COLUMN rest_until INTEGER NOT NULL DEFAULT 0")
|
||||
db.execSQL("ALTER TABLE quota_ledger ADD COLUMN valid_until INTEGER NOT NULL DEFAULT 0")
|
||||
AccountBudgetTransactions.create(db)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.haorui.app.crossplatform.model
|
||||
|
||||
/** 与 QuotaManager 同一日界、时段和时钟的一次原子快照。 */
|
||||
data class AccountQuotaSnapshot(
|
||||
val capturedAtMs: Long,
|
||||
val validUntilMs: Long,
|
||||
val dayKey: String,
|
||||
val totalLimit: Int,
|
||||
val legacyUsed: Int,
|
||||
val windowKey: String,
|
||||
val windowLimit: Int?,
|
||||
val legacyWindowUsed: Int,
|
||||
val segmentCounts: List<Int>,
|
||||
val restUntilMs: Long,
|
||||
) {
|
||||
val period: SubmissionBudgetPeriod get() = SubmissionBudgetPeriod(dayKey, windowKey)
|
||||
init {
|
||||
require(capturedAtMs > 0 && validUntilMs > capturedAtMs && dayKey.isNotBlank() && windowKey.isNotBlank())
|
||||
require(totalLimit >= 0 && legacyUsed >= 0 && legacyWindowUsed >= 0)
|
||||
require(windowLimit == null || windowLimit >= 0)
|
||||
require(segmentCounts.size == 4 && segmentCounts.all { it >= 0 })
|
||||
}
|
||||
}
|
||||
|
||||
/** 回执核对器给出的实际提交归属,独立于核对时刻的当前额度快照。 */
|
||||
data class SubmissionBudgetPeriod(val dayKey: String, val windowKey: String) {
|
||||
init { require(dayKey.isNotBlank() && windowKey.isNotBlank()) }
|
||||
}
|
||||
|
||||
data class LegacyPublishReservation(
|
||||
val id: String,
|
||||
val accountKey: String,
|
||||
val runGeneration: Long,
|
||||
val dayKey: String,
|
||||
val windowKey: String,
|
||||
val mediaPath: String,
|
||||
val payloadHash: String,
|
||||
val state: CrossAttemptState,
|
||||
val clickClaimed: Boolean,
|
||||
)
|
||||
|
||||
/** 绝对计数用于恢复与幂等投影,不再对同一回执调用 recordPublish()。 */
|
||||
data class LegacyBudgetState(val dayKey: String, val used: Int, val windows: Map<String, Int>, val restUntilMs: Long)
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.haorui.app.crossplatform.model
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
import java.util.Locale
|
||||
|
||||
/** 新链路独立配置。来源选择不等于来源能力已验收。 */
|
||||
@Serializable
|
||||
data class CrossPlatformConfig(
|
||||
val enabled: Boolean = false,
|
||||
val mode: String = MODE_DRY_RUN,
|
||||
val zhihuEnabled: Boolean = false,
|
||||
val xiaohongshuEnabled: Boolean = false,
|
||||
val weiboEnabled: Boolean = false,
|
||||
val douyinEnabled: Boolean = false,
|
||||
val articleEnabled: Boolean = true,
|
||||
val videoEnabled: Boolean = true,
|
||||
val scanIntervalMinutes: Int = 10,
|
||||
val maxAgeHours: Int = 24,
|
||||
val articleDailyLimit: Int = 2,
|
||||
val videoDailyLimit: Int = 2,
|
||||
val publishGapMinutes: Int = 60,
|
||||
val readyQueueLimit: Int = 10,
|
||||
val videoMaxMiB: Int = 500,
|
||||
val videoMinSeconds: Int = 20,
|
||||
val videoMaxSeconds: Int = 4000,
|
||||
val likesGateEnabled: Boolean = false,
|
||||
val likesMin: Int = 1000,
|
||||
val fansGateEnabled: Boolean = false,
|
||||
val fansMax: Int = 500_000,
|
||||
val categories: List<String> = DEFAULT_CATEGORIES,
|
||||
) {
|
||||
fun normalized(): CrossPlatformConfig {
|
||||
val maximumDuration = videoMaxSeconds.coerceIn(20, 4000)
|
||||
return copy(
|
||||
mode = if (mode.trim().uppercase(Locale.ROOT) == MODE_AUTO) MODE_AUTO else MODE_DRY_RUN,
|
||||
scanIntervalMinutes = scanIntervalMinutes.coerceIn(5, 120),
|
||||
maxAgeHours = maxAgeHours.coerceIn(1, 72),
|
||||
articleDailyLimit = articleDailyLimit.coerceIn(0, 28),
|
||||
videoDailyLimit = videoDailyLimit.coerceIn(0, 28),
|
||||
publishGapMinutes = publishGapMinutes.coerceIn(60, 1440),
|
||||
readyQueueLimit = readyQueueLimit.coerceIn(1, 10),
|
||||
videoMaxMiB = videoMaxMiB.coerceIn(1, 500),
|
||||
videoMinSeconds = videoMinSeconds.coerceIn(20, maximumDuration),
|
||||
videoMaxSeconds = maximumDuration,
|
||||
likesMin = likesMin.coerceIn(0, 1_000_000_000),
|
||||
fansMax = fansMax.coerceIn(0, 1_000_000_000),
|
||||
categories = categories.map { it.trim() }.filter { it in CATEGORY_CATALOGUE }.distinct(),
|
||||
)
|
||||
}
|
||||
|
||||
fun sourceEnabled(id: String): Boolean = when (id) {
|
||||
"zhihu" -> zhihuEnabled
|
||||
"xiaohongshu" -> xiaohongshuEnabled
|
||||
"weibo" -> weiboEnabled
|
||||
"douyin" -> douyinEnabled
|
||||
else -> false
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val MODE_DRY_RUN = "DRY_RUN"
|
||||
const val MODE_AUTO = "AUTO"
|
||||
/** 兼容已有配置,仅作初次或缺失字段时的选中项。 */
|
||||
val DEFAULT_CATEGORIES = listOf("民生生活", "社会现象", "职场", "教育")
|
||||
val CATEGORY_CATALOGUE = DEFAULT_CATEGORIES + listOf(
|
||||
"生活", "科技数码", "体育", "三农", "美食", "旅游", "汽车",
|
||||
"文化历史", "宠物", "家居", "健康科普", "影视娱乐", "游戏", "财经",
|
||||
)
|
||||
val CATEGORIES = CATEGORY_CATALOGUE
|
||||
}
|
||||
}
|
||||
|
||||
/** 与历史扁平预设共同导入导出,新字段均使用独立前缀。 */
|
||||
object CrossPlatformConfigCodec {
|
||||
private const val PREFIX = "cross_platform_"
|
||||
|
||||
fun toFlatMap(config: CrossPlatformConfig): Map<String, String> {
|
||||
val c = config.normalized()
|
||||
return mapOf(
|
||||
"enabled" to c.enabled.toString(), "mode" to c.mode,
|
||||
"zhihu_enabled" to c.zhihuEnabled.toString(),
|
||||
"xiaohongshu_enabled" to c.xiaohongshuEnabled.toString(),
|
||||
"weibo_enabled" to c.weiboEnabled.toString(), "douyin_enabled" to c.douyinEnabled.toString(),
|
||||
"article_enabled" to c.articleEnabled.toString(), "video_enabled" to c.videoEnabled.toString(),
|
||||
"scan_interval_minutes" to c.scanIntervalMinutes.toString(), "max_age_hours" to c.maxAgeHours.toString(),
|
||||
"article_daily_limit" to c.articleDailyLimit.toString(), "video_daily_limit" to c.videoDailyLimit.toString(),
|
||||
"publish_gap_minutes" to c.publishGapMinutes.toString(), "ready_queue_limit" to c.readyQueueLimit.toString(),
|
||||
"video_max_mib" to c.videoMaxMiB.toString(), "video_min_seconds" to c.videoMinSeconds.toString(),
|
||||
"video_max_seconds" to c.videoMaxSeconds.toString(),
|
||||
"likes_gate_enabled" to c.likesGateEnabled.toString(), "likes_min" to c.likesMin.toString(),
|
||||
"fans_gate_enabled" to c.fansGateEnabled.toString(), "fans_max" to c.fansMax.toString(),
|
||||
"categories" to c.categories.joinToString("|"),
|
||||
).mapKeys { (key, _) -> PREFIX + key }
|
||||
}
|
||||
|
||||
fun fromFlatMap(map: Map<String, String>): CrossPlatformConfig {
|
||||
val d = CrossPlatformConfig()
|
||||
var validEncoding = true
|
||||
fun value(key: String): String? = map[PREFIX + key]
|
||||
fun b(key: String, default: Boolean): Boolean {
|
||||
val raw = value(key) ?: return default
|
||||
return raw.toBooleanStrictOrNull() ?: run { validEncoding = false; default }
|
||||
}
|
||||
fun i(key: String, default: Int): Int {
|
||||
val raw = value(key) ?: return default
|
||||
return raw.toIntOrNull() ?: run { validEncoding = false; default }
|
||||
}
|
||||
val decoded = CrossPlatformConfig(
|
||||
enabled = b("enabled", d.enabled), mode = value("mode") ?: d.mode,
|
||||
zhihuEnabled = b("zhihu_enabled", d.zhihuEnabled),
|
||||
xiaohongshuEnabled = b("xiaohongshu_enabled", d.xiaohongshuEnabled),
|
||||
weiboEnabled = b("weibo_enabled", d.weiboEnabled), douyinEnabled = b("douyin_enabled", d.douyinEnabled),
|
||||
articleEnabled = b("article_enabled", d.articleEnabled), videoEnabled = b("video_enabled", d.videoEnabled),
|
||||
scanIntervalMinutes = i("scan_interval_minutes", d.scanIntervalMinutes),
|
||||
maxAgeHours = i("max_age_hours", d.maxAgeHours),
|
||||
articleDailyLimit = i("article_daily_limit", d.articleDailyLimit),
|
||||
videoDailyLimit = i("video_daily_limit", d.videoDailyLimit),
|
||||
publishGapMinutes = i("publish_gap_minutes", d.publishGapMinutes),
|
||||
readyQueueLimit = i("ready_queue_limit", d.readyQueueLimit),
|
||||
videoMaxMiB = i("video_max_mib", d.videoMaxMiB),
|
||||
videoMinSeconds = i("video_min_seconds", d.videoMinSeconds),
|
||||
videoMaxSeconds = i("video_max_seconds", d.videoMaxSeconds),
|
||||
likesGateEnabled = b("likes_gate_enabled", d.likesGateEnabled), likesMin = i("likes_min", d.likesMin),
|
||||
fansGateEnabled = b("fans_gate_enabled", d.fansGateEnabled), fansMax = i("fans_max", d.fansMax),
|
||||
categories = value("categories")?.split('|') ?: d.categories,
|
||||
).normalized()
|
||||
return if (validEncoding) decoded else decoded.copy(enabled = false, mode = CrossPlatformConfig.MODE_DRY_RUN)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package com.haorui.app.crossplatform.model
|
||||
|
||||
enum class CrossContentKind(val displayName: String) { ARTICLE("图文"), VIDEO("视频") }
|
||||
|
||||
enum class CrossTaskState(val displayName: String) {
|
||||
DISCOVERED("已发现"), FILTERED("筛选通过"), PREPARED("成品已准备"), READY("待发布"),
|
||||
EDITING("编辑中"), SUBMIT_INTENT("提交待确认"), SUBMITTED("已提交"),
|
||||
RETRY_WAIT("等待重试"), SKIPPED("已跳过"), DRAFT_SAVED("已存草稿"),
|
||||
RESULT_UNKNOWN("结果待核对"), PAUSED("已暂停")
|
||||
}
|
||||
|
||||
data class CrossPublishTask(
|
||||
val id: String,
|
||||
val accountKey: String,
|
||||
val eventId: String,
|
||||
val contentKind: CrossContentKind,
|
||||
val title: String,
|
||||
val sourcePlatform: String,
|
||||
val sourceUrl: String,
|
||||
val state: CrossTaskState = CrossTaskState.DISCOVERED,
|
||||
val bodyText: String = "",
|
||||
val mediaPath: String = "",
|
||||
val evidenceJson: String = "",
|
||||
val rightsRef: String = "",
|
||||
val payloadHash: String = "",
|
||||
val publicationVersion: Int = 1,
|
||||
val revision: Int = 1,
|
||||
val runGeneration: Long = 0,
|
||||
val publishedAtMs: Long? = null,
|
||||
val expiresAtMs: Long = 0,
|
||||
val createdAtMs: Long = System.currentTimeMillis(),
|
||||
val updatedAtMs: Long = createdAtMs,
|
||||
val reason: String = "",
|
||||
val receiptRef: String = "",
|
||||
val resumeState: CrossTaskState? = null,
|
||||
)
|
||||
|
||||
data class CrossEvent(
|
||||
val id: String,
|
||||
val category: String,
|
||||
val factPacketJson: String,
|
||||
val sourceUrlsJson: String,
|
||||
val updatedAtMs: Long = System.currentTimeMillis(),
|
||||
)
|
||||
|
||||
data class CrossAsset(
|
||||
val id: String,
|
||||
val taskId: String,
|
||||
val revision: Int,
|
||||
val localPath: String,
|
||||
val sha256: String,
|
||||
val sizeBytes: Long,
|
||||
val rightsRef: String,
|
||||
)
|
||||
|
||||
enum class CrossSubmissionMode { DRAFT, PUBLISH }
|
||||
enum class CrossAttemptState { INTENT, UNKNOWN, CONFIRMED, NOT_SUBMITTED }
|
||||
|
||||
data class CrossSubmissionAttempt(
|
||||
val id: String,
|
||||
val taskId: String,
|
||||
val revision: Int,
|
||||
val runGeneration: Long,
|
||||
val mode: CrossSubmissionMode,
|
||||
val state: CrossAttemptState,
|
||||
val clickClaimed: Boolean,
|
||||
val budgetDayKey: String?,
|
||||
val createdAtMs: Long,
|
||||
val receiptRef: String = "",
|
||||
)
|
||||
|
||||
data class CrossSubmissionBudget(
|
||||
val dayKey: String,
|
||||
val totalLimit: Int,
|
||||
val legacySubmittedCount: Int,
|
||||
val articleLimit: Int,
|
||||
val videoLimit: Int,
|
||||
val quotaSnapshot: AccountQuotaSnapshot? = null,
|
||||
val minGapMs: Long = 0,
|
||||
) {
|
||||
init {
|
||||
require(dayKey.isNotBlank())
|
||||
require(totalLimit >= 0 && legacySubmittedCount >= 0 && articleLimit >= 0 && videoLimit >= 0)
|
||||
require(minGapMs >= 0)
|
||||
}
|
||||
}
|
||||
|
||||
enum class CrossReservationState { RESERVED, SETTLED, RELEASED }
|
||||
|
||||
data class CrossQuotaEntry(
|
||||
val dayKey: String,
|
||||
val contentKind: CrossContentKind,
|
||||
val state: CrossReservationState,
|
||||
val legacy: Boolean = false,
|
||||
val windowKey: String = "",
|
||||
val settledAtMs: Long = 0,
|
||||
val restUntilMs: Long = 0,
|
||||
val attemptId: String = "",
|
||||
)
|
||||
|
||||
data class CrossBudgetUsage(val legacyUsed: Int, val reserved: Int, val settledToday: Int) {
|
||||
val totalUsed: Long get() = legacyUsed.toLong() + reserved + settledToday
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.haorui.app.crossplatform.model
|
||||
|
||||
/** 纯状态规则;涉及外部提交的状态仅由任务库专用事务改变。 */
|
||||
object CrossTaskPolicy {
|
||||
private val transitions = mapOf(
|
||||
CrossTaskState.DISCOVERED to setOf(CrossTaskState.FILTERED, CrossTaskState.SKIPPED, CrossTaskState.PAUSED),
|
||||
CrossTaskState.FILTERED to setOf(CrossTaskState.PREPARED, CrossTaskState.SKIPPED, CrossTaskState.RETRY_WAIT, CrossTaskState.PAUSED),
|
||||
CrossTaskState.PREPARED to setOf(CrossTaskState.READY, CrossTaskState.SKIPPED, CrossTaskState.PAUSED),
|
||||
CrossTaskState.READY to setOf(CrossTaskState.SKIPPED, CrossTaskState.PAUSED),
|
||||
CrossTaskState.EDITING to setOf(CrossTaskState.READY, CrossTaskState.PAUSED, CrossTaskState.SKIPPED),
|
||||
CrossTaskState.RETRY_WAIT to setOf(CrossTaskState.FILTERED, CrossTaskState.SKIPPED, CrossTaskState.PAUSED),
|
||||
)
|
||||
|
||||
fun canTransition(from: CrossTaskState, to: CrossTaskState): Boolean = to in transitions[from].orEmpty()
|
||||
|
||||
fun preparationRejection(task: CrossPublishTask, nowMs: Long): String? = when {
|
||||
task.accountKey.isBlank() || task.eventId.isBlank() -> "账号或事件身份缺失"
|
||||
task.title.isBlank() || task.sourceUrl.isBlank() -> "标题或来源链接缺失"
|
||||
task.publishedAtMs == null || task.publishedAtMs <= 0 || task.publishedAtMs > nowMs -> "发布时间未知或无效"
|
||||
task.expiresAtMs == Long.MAX_VALUE || task.expiresAtMs <= nowMs || task.expiresAtMs <= task.publishedAtMs -> "内容有效期缺失或已过期"
|
||||
!task.payloadHash.matches(Regex("[a-fA-F0-9]{64}")) -> "缺少有效成品指纹"
|
||||
task.evidenceJson.isBlank() -> "事实依据缺失"
|
||||
task.contentKind == CrossContentKind.ARTICLE && task.bodyText.isBlank() -> "文章正文缺失"
|
||||
task.contentKind == CrossContentKind.VIDEO && (task.mediaPath.isBlank() || task.rightsRef.isBlank()) -> "视频文件或素材许可缺失"
|
||||
else -> null
|
||||
}
|
||||
|
||||
fun canBeginSubmission(task: CrossPublishTask, requestedGeneration: Long, activeGeneration: Long, active: Boolean, nowMs: Long): Boolean =
|
||||
active && requestedGeneration == activeGeneration && task.runGeneration == activeGeneration &&
|
||||
task.state == CrossTaskState.EDITING && preparationRejection(task, nowMs) == null
|
||||
|
||||
fun recoverState(state: CrossTaskState): CrossTaskState = when (state) {
|
||||
CrossTaskState.SUBMIT_INTENT -> CrossTaskState.RESULT_UNKNOWN
|
||||
CrossTaskState.EDITING -> CrossTaskState.PAUSED
|
||||
else -> state
|
||||
}
|
||||
|
||||
fun budgetRejection(budget: CrossSubmissionBudget, kind: CrossContentKind?, entries: List<CrossQuotaEntry>, nowMs: Long = System.currentTimeMillis()): String? {
|
||||
val snapshot = budget.quotaSnapshot
|
||||
if (snapshot != null) {
|
||||
if (snapshot.dayKey != budget.dayKey || nowMs < snapshot.capturedAtMs || nowMs - snapshot.capturedAtMs > 5_000 || nowMs >= snapshot.validUntilMs) return "账户额度快照已失效"
|
||||
if (nowMs < maxOf(snapshot.restUntilMs, entries.maxOfOrNull { it.restUntilMs } ?: 0)) return "账户仍在发布休息期"
|
||||
if (kind != null && entries.any { it.settledAtMs > 0 && nowMs - it.settledAtMs < budget.minGapMs }) return "新链路发布间隔未到"
|
||||
}
|
||||
// 旧视频已结算记录通过绝对基线计数,不能再次加到账本总数。
|
||||
val held = entries.filter { it.state == CrossReservationState.RESERVED || (!it.legacy && it.state == CrossReservationState.SETTLED && it.dayKey == budget.dayKey) }
|
||||
val total = minOf(budget.totalLimit, snapshot?.totalLimit ?: budget.totalLimit)
|
||||
if (maxOf(budget.legacySubmittedCount, snapshot?.legacyUsed ?: 0).toLong() + held.size >= total) return "账户共享总额度已用完"
|
||||
if (snapshot?.windowLimit != null && snapshot.legacyWindowUsed.toLong() + held.count {
|
||||
it.state == CrossReservationState.RESERVED || it.windowKey.isBlank() || it.windowKey == snapshot.windowKey
|
||||
} >= snapshot.windowLimit) return "账户当前时段额度已用完"
|
||||
if (kind == null) return null
|
||||
val limit = if (kind == CrossContentKind.ARTICLE) budget.articleLimit else budget.videoLimit
|
||||
if (held.count { !it.legacy && it.contentKind == kind } >= limit) return "该内容类型的每日额度已用完"
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package com.haorui.app.crossplatform.publish
|
||||
|
||||
import com.haorui.app.crossplatform.model.*
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.util.UUID
|
||||
|
||||
class VerifiedAccount internal constructor(val accountKey: String, val displayName: String, val verifiedAtMs: Long, val operationId: String) {
|
||||
init {
|
||||
require(accountKey.matches(Regex("tt:[a-f0-9]{64}")) && displayName.isNotBlank() && verifiedAtMs > 0 && operationId.isNotBlank())
|
||||
}
|
||||
}
|
||||
|
||||
/** 实际发布器的唯一提交入口。异常返回保留媒体,不能回到旧的删文件失败分支。 */
|
||||
class LegacyPublishSession(
|
||||
val generation: Long,
|
||||
val mediaPath: String,
|
||||
val payloadHash: String,
|
||||
private val journal: Journal,
|
||||
private val verifyAccount: suspend () -> VerifiedAccount?,
|
||||
private val budget: () -> CrossSubmissionBudget,
|
||||
private val isCurrent: () -> Boolean,
|
||||
private val now: () -> Long = System::currentTimeMillis,
|
||||
) {
|
||||
interface Journal {
|
||||
suspend fun bind(account: String, generation: Long, snapshot: AccountQuotaSnapshot): Boolean
|
||||
suspend fun reserve(id: String, account: String, generation: Long, path: String, hash: String, budget: CrossSubmissionBudget): Boolean
|
||||
suspend fun claim(id: String, generation: Long, budget: CrossSubmissionBudget): Boolean
|
||||
suspend fun unknown(id: String)
|
||||
suspend fun releaseUnclicked(id: String, generation: Long): Boolean
|
||||
suspend fun settle(id: String, receiptRef: String, snapshot: AccountQuotaSnapshot, restUntilMs: Long, period: SubmissionBudgetPeriod): LegacyBudgetState?
|
||||
}
|
||||
enum class State { NEW, VERIFIED, RESERVED, CLICK_CLAIMED, UNKNOWN, CONFIRMED, NOT_SUBMITTED, PAUSED }
|
||||
val attemptId: String = UUID.randomUUID().toString()
|
||||
@Volatile var state = State.NEW
|
||||
private set
|
||||
@Volatile var reason = ""
|
||||
private set
|
||||
private val mutex = Mutex()
|
||||
private var account: VerifiedAccount? = null
|
||||
init { require(generation > 0 && mediaPath.isNotBlank() && payloadHash.matches(Regex("[a-f0-9]{64}"))) }
|
||||
|
||||
suspend fun prepare(): Boolean = mutex.withLock {
|
||||
if (state != State.NEW || !isCurrent()) return@withLock pause("运行已停止或提交上下文已失效")
|
||||
val verified = verifyAccount() ?: return@withLock pause("无法核验当前头条账号")
|
||||
if (!isCurrent() || verified.accountKey.isBlank() || verified.operationId.isBlank() ||
|
||||
now() < verified.verifiedAtMs || now() - verified.verifiedAtMs > 5_000) return@withLock pause("账号核验已失效")
|
||||
val snapshot = budget().quotaSnapshot ?: return@withLock pause("共享额度快照尚未恢复")
|
||||
if (!journal.bind(verified.accountKey, generation, snapshot)) return@withLock pause("账号与共享额度记录不一致")
|
||||
if (!isCurrent()) return@withLock pause("运行已停止")
|
||||
account = verified
|
||||
state = State.VERIFIED
|
||||
true
|
||||
}
|
||||
|
||||
/** 意图 ID 在 IO 事务之前生成;取消导致返回值丢失时仍能找到并处理该条日志。 */
|
||||
suspend fun dispatch(currentPayloadHash: String, identityStillValid: () -> Boolean, click: suspend () -> Boolean): Boolean = mutex.withLock {
|
||||
if (state != State.VERIFIED) return@withLock false
|
||||
if (!isCurrent() || !identityStillValid() || currentPayloadHash != payloadHash) return@withLock pause("账号、成品或运行上下文已变化")
|
||||
val verified = account ?: return@withLock pause("缺少当前账号核验")
|
||||
if (now() < verified.verifiedAtMs || now() - verified.verifiedAtMs > 120_000) return@withLock pause("账号核验已过期")
|
||||
try {
|
||||
state = State.RESERVED
|
||||
if (!journal.reserve(attemptId, verified.accountKey, generation, mediaPath, payloadHash, budget())) {
|
||||
return@withLock pause("共享额度不足或提交意图无法保存")
|
||||
}
|
||||
if (!isCurrent() || !identityStillValid() || !journal.claim(attemptId, generation, budget())) {
|
||||
releaseBeforeClick()
|
||||
return@withLock false
|
||||
}
|
||||
state = State.CLICK_CLAIMED
|
||||
if (!isCurrent() || !identityStillValid()) {
|
||||
keepUnknown("点击许可发放后运行已停止")
|
||||
return@withLock false
|
||||
}
|
||||
// click 只能派发一次;失败、超时、取消均不得重放。
|
||||
if (!click()) {
|
||||
keepUnknown("点击结果不明,等待作品核对")
|
||||
return@withLock false
|
||||
}
|
||||
true
|
||||
} catch (cancelled: CancellationException) {
|
||||
withContext(NonCancellable) { runCatching { finishInterrupted() } }
|
||||
throw cancelled
|
||||
} catch (failure: Exception) {
|
||||
withContext(NonCancellable) { runCatching { finishInterrupted() } }
|
||||
reason = "提交中断:${failure.javaClass.simpleName},等待核对"
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun markUnknown(reason: String) = mutex.withLock {
|
||||
if (state in setOf(State.RESERVED, State.CLICK_CLAIMED, State.UNKNOWN)) keepUnknown(reason)
|
||||
}
|
||||
|
||||
/** 只接受核对器给出的明确回执;页面消失/分享面板/超时不调用本方法。 */
|
||||
suspend fun confirm(receiptRef: String, currentSnapshot: AccountQuotaSnapshot, restUntilMs: Long,
|
||||
period: SubmissionBudgetPeriod): LegacyBudgetState? = mutex.withLock {
|
||||
if (state !in setOf(State.CLICK_CLAIMED, State.UNKNOWN, State.CONFIRMED)) return@withLock null
|
||||
val settled = journal.settle(attemptId, receiptRef, currentSnapshot, restUntilMs, period) ?: return@withLock null
|
||||
state = State.CONFIRMED
|
||||
settled
|
||||
}
|
||||
|
||||
val retainsMedia: Boolean get() = state != State.CONFIRMED && state != State.NOT_SUBMITTED
|
||||
|
||||
private fun pause(reason: String): Boolean {
|
||||
this.reason = reason
|
||||
state = State.PAUSED
|
||||
return false
|
||||
}
|
||||
|
||||
private suspend fun releaseBeforeClick() {
|
||||
if (journal.releaseUnclicked(attemptId, generation)) {
|
||||
state = State.NOT_SUBMITTED
|
||||
reason = "点击未派发,预占已释放"
|
||||
} else keepUnknown("提交意图状态待核对")
|
||||
}
|
||||
|
||||
private suspend fun finishInterrupted() {
|
||||
if (state == State.RESERVED) releaseBeforeClick()
|
||||
else if (state in setOf(State.CLICK_CLAIMED, State.UNKNOWN)) keepUnknown("提交中断,等待作品核对")
|
||||
}
|
||||
|
||||
private suspend fun keepUnknown(reason: String) {
|
||||
state = State.UNKNOWN
|
||||
this.reason = reason
|
||||
journal.unknown(attemptId)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.haorui.app.crossplatform.publish
|
||||
|
||||
import com.haorui.app.crossplatform.data.CrossPublishTaskStore
|
||||
import com.haorui.app.crossplatform.model.*
|
||||
|
||||
class StoreLegacyPublishJournal(private val store: CrossPublishTaskStore) : LegacyPublishSession.Journal {
|
||||
override suspend fun bind(account: String, generation: Long, snapshot: AccountQuotaSnapshot) = store.bindLegacyAccount(account, generation, snapshot)
|
||||
override suspend fun reserve(id: String, account: String, generation: Long, path: String, hash: String, budget: CrossSubmissionBudget) =
|
||||
store.beginLegacySubmission(account, generation, path, hash, budget, id) != null
|
||||
override suspend fun claim(id: String, generation: Long, budget: CrossSubmissionBudget) = store.claimLegacySubmissionClick(id, generation, budget)
|
||||
override suspend fun unknown(id: String) { store.markLegacySubmissionUnknown(id) }
|
||||
override suspend fun releaseUnclicked(id: String, generation: Long) = store.releaseUnclickedLegacySubmission(id, generation)
|
||||
override suspend fun settle(id: String, receiptRef: String, snapshot: AccountQuotaSnapshot, restUntilMs: Long, period: SubmissionBudgetPeriod) =
|
||||
store.recordLegacyReceipt(id, receiptRef, snapshot, restUntilMs, period)
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.haorui.app.crossplatform.schedule
|
||||
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** 运行代际由持久化任务库分配,与服务启动计数和前台票据代际分别维护。 */
|
||||
interface CrossRunPersistence {
|
||||
suspend fun beginRun(): Long
|
||||
suspend fun pauseRun(): Long
|
||||
}
|
||||
|
||||
/**
|
||||
* 串行落库启停意图。作用域属于任务库,服务销毁不能取消已排队的停止事务。
|
||||
* 停止立即撤销内存中的运行许可;只有最新启动事务完成后才公开数据库代际。
|
||||
*/
|
||||
class CrossRunLifecycle(private val persistence: CrossRunPersistence, scope: CoroutineScope) {
|
||||
data class State(val generation: Long? = null, val pending: Boolean = false, val error: String? = null)
|
||||
private data class Operation(val revision: Long, val start: Boolean)
|
||||
|
||||
private val lock = Any()
|
||||
private val operations = Channel<Operation>(Channel.UNLIMITED)
|
||||
private var revision = 0L
|
||||
private var current: Session? = null
|
||||
private var enabled = false
|
||||
private var wanted = false
|
||||
private var desired = false
|
||||
private val _state = MutableStateFlow(State())
|
||||
val state = _state.asStateFlow()
|
||||
|
||||
init {
|
||||
scope.launch {
|
||||
for (operation in operations) {
|
||||
try {
|
||||
val generation = if (operation.start) persistence.beginRun() else persistence.pauseRun()
|
||||
synchronized(lock) {
|
||||
if (operation.revision == revision) {
|
||||
_state.value = State(generation = generation.takeIf { operation.start })
|
||||
}
|
||||
}
|
||||
} catch (cancelled: CancellationException) {
|
||||
throw cancelled
|
||||
} catch (failure: Exception) {
|
||||
synchronized(lock) {
|
||||
if (operation.revision == revision) {
|
||||
_state.value = State(error = "本地任务启停保存失败:${failure.javaClass.simpleName}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 新服务接管时先中断旧会话;旧实例的迟到 stop/close 不能影响新实例。 */
|
||||
fun openSession(): Session = synchronized(lock) {
|
||||
Session().also {
|
||||
current = it
|
||||
enabled = false
|
||||
wanted = false
|
||||
reconcile(force = true)
|
||||
}
|
||||
}
|
||||
|
||||
inner class Session internal constructor() {
|
||||
fun configure(moduleEnabled: Boolean) = synchronized(lock) {
|
||||
if (current !== this) return@synchronized
|
||||
enabled = moduleEnabled
|
||||
reconcile()
|
||||
}
|
||||
|
||||
fun start() = synchronized(lock) {
|
||||
if (current !== this) return@synchronized
|
||||
wanted = true
|
||||
reconcile()
|
||||
}
|
||||
|
||||
fun stop() = synchronized(lock) {
|
||||
if (current !== this) return@synchronized
|
||||
wanted = false
|
||||
reconcile()
|
||||
}
|
||||
|
||||
fun close() = synchronized(lock) {
|
||||
if (current !== this) return@synchronized
|
||||
current = null
|
||||
wanted = false
|
||||
reconcile()
|
||||
}
|
||||
|
||||
fun currentGeneration(): Long? = synchronized(lock) {
|
||||
_state.value.generation.takeIf { current === this && enabled && wanted }
|
||||
}
|
||||
}
|
||||
|
||||
private fun reconcile(force: Boolean = false) {
|
||||
val next = current != null && enabled && wanted
|
||||
if (!force && next == desired && _state.value.error == null) return
|
||||
desired = next
|
||||
_state.value = State(pending = true)
|
||||
check(operations.trySend(Operation(++revision, next)).isSuccess)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.haorui.app.crossplatform.schedule
|
||||
|
||||
/**
|
||||
* 记录实际在途的前台操作。释放只接受原票据,停止不会提前释放仍在执行的操作。
|
||||
* 新功能关闭时只记录既有步骤,不改变其并发判定;启用后每次仅允许一个步骤入场。
|
||||
*/
|
||||
class ForegroundCoordinator {
|
||||
data class Ticket internal constructor(val id: Long, val generation: Long, val owner: String, val source: Boolean, val exclusive: Boolean = false)
|
||||
private var sequence = 0L
|
||||
private var generation = 0L
|
||||
private var enabled = false
|
||||
private var wanted = false
|
||||
private val active = linkedMapOf<Long, Ticket>()
|
||||
|
||||
@Synchronized fun configure(enabled: Boolean) {
|
||||
if (this.enabled && !enabled) generation++
|
||||
this.enabled = enabled
|
||||
}
|
||||
|
||||
@Synchronized fun beginRun() { wanted = true }
|
||||
|
||||
@Synchronized fun stop() {
|
||||
wanted = false
|
||||
generation++
|
||||
// 在途操作的 finally 负责释放;不能让新运行与尚未完成的旧点击重叠。
|
||||
}
|
||||
|
||||
@Synchronized fun tryEnterLegacy(owner: String): Ticket? {
|
||||
if (active.values.any { it.source || it.exclusive } || (enabled && active.isNotEmpty())) return null
|
||||
return Ticket(++sequence, generation, owner, false).also { active[it.id] = it }
|
||||
}
|
||||
|
||||
@Synchronized fun tryEnterExclusive(owner: String): Ticket? {
|
||||
if (active.isNotEmpty()) return null
|
||||
return Ticket(++sequence, generation, owner, false, exclusive = true).also { active[it.id] = it }
|
||||
}
|
||||
|
||||
/** legacyIdle 必须检查所有状态机的安全边界,检查在入场锁内执行。 */
|
||||
@Synchronized fun tryEnterSource(sourceId: String, legacyIdle: () -> Boolean): Ticket? {
|
||||
if (!enabled || !wanted || active.isNotEmpty() || !legacyIdle()) return null
|
||||
return Ticket(++sequence, generation, "SOURCE:$sourceId", true).also { active[it.id] = it }
|
||||
}
|
||||
|
||||
@Synchronized fun isCurrent(ticket: Ticket): Boolean =
|
||||
active[ticket.id] === ticket && ticket.generation == generation && (!ticket.source || enabled && wanted)
|
||||
|
||||
@Synchronized fun release(ticket: Ticket): Boolean {
|
||||
if (active[ticket.id] !== ticket) return false
|
||||
active.remove(ticket.id)
|
||||
return true
|
||||
}
|
||||
|
||||
@Synchronized fun hasSourceOwner(): Boolean = active.values.any { it.source }
|
||||
@Synchronized fun isIdle(): Boolean = active.isEmpty()
|
||||
@Synchronized fun describe(): String = active.values.joinToString("+") { it.owner }.ifEmpty { "NONE" }
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.haorui.app.crossplatform.source
|
||||
|
||||
import com.haorui.app.crossplatform.model.CrossPlatformConfig
|
||||
|
||||
enum class SourceCapability { HOT_LIST, DETAIL, SHARE_LINK, MEDIA_IMPORT }
|
||||
|
||||
data class SourceDefinition(
|
||||
val id: String,
|
||||
val label: String,
|
||||
val packageName: String,
|
||||
val verifiedVersions: Set<String> = emptySet(),
|
||||
val capabilities: Set<SourceCapability> = emptySet(),
|
||||
) {
|
||||
val verified: Boolean get() = verifiedVersions.isNotEmpty() && capabilities.isNotEmpty()
|
||||
}
|
||||
|
||||
data class SourceAvailability(val canExecute: Boolean, val reason: String)
|
||||
|
||||
/** 验收结果由随版本发布的适配代码维护,不从用户预设中导入。 */
|
||||
object SourceRegistry {
|
||||
val definitions: List<SourceDefinition> = listOf(
|
||||
SourceDefinition("zhihu", "知乎", "com.zhihu.android"),
|
||||
SourceDefinition("xiaohongshu", "小红书", "com.xingin.xhs"),
|
||||
SourceDefinition("weibo", "微博", "com.sina.weibo"),
|
||||
SourceDefinition("douyin", "抖音", "com.ss.android.ugc.aweme"),
|
||||
)
|
||||
|
||||
fun find(id: String): SourceDefinition? = definitions.firstOrNull { it.id == id }
|
||||
|
||||
fun executionStatus(
|
||||
id: String,
|
||||
installedVersion: String?,
|
||||
config: CrossPlatformConfig,
|
||||
requiredCapability: SourceCapability = SourceCapability.HOT_LIST,
|
||||
): SourceAvailability {
|
||||
val source = find(id) ?: return SourceAvailability(false, "未知来源")
|
||||
if (!config.enabled) return SourceAvailability(false, "跨平台模块未启用")
|
||||
if (!config.sourceEnabled(id)) return SourceAvailability(false, "来源未启用")
|
||||
if (installedVersion.isNullOrBlank()) return SourceAvailability(false, "未安装来源 App 或无法读取版本")
|
||||
if (installedVersion !in source.verifiedVersions) return SourceAvailability(false, "当前版本尚未完成真机适配")
|
||||
if (requiredCapability !in source.capabilities) return SourceAvailability(false, "所需采集能力尚未验收")
|
||||
return SourceAvailability(true, "可执行")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,466 @@
|
||||
package com.haorui.app.crossplatform.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Article
|
||||
import androidx.compose.material.icons.filled.ChevronRight
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.VideoLibrary
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.MutableState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.saveable.Saver
|
||||
import androidx.compose.runtime.saveable.mapSaver
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.toMutableStateMap
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import com.haorui.app.automation.Targets
|
||||
import com.haorui.app.crossplatform.model.CrossContentKind
|
||||
import com.haorui.app.crossplatform.model.CrossPlatformConfig
|
||||
import com.haorui.app.crossplatform.model.CrossPublishTask
|
||||
import com.haorui.app.crossplatform.model.CrossTaskState
|
||||
import com.haorui.app.crossplatform.source.SourceRegistry
|
||||
import com.haorui.app.data.model.AppConfig
|
||||
import com.haorui.app.ui.components.FieldHelp
|
||||
import com.haorui.app.ui.components.Section
|
||||
import com.haorui.app.ui.components.StatusBanner
|
||||
import com.haorui.app.ui.components.StatusLevel
|
||||
import com.haorui.app.ui.nav.Routes
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.decodeFromString
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
private val draftCodec = Json { ignoreUnknownKeys = true }
|
||||
private val configDraftSaver = Saver<MutableState<CrossPlatformConfig>, String>(
|
||||
save = { draftCodec.encodeToString(it.value) },
|
||||
restore = { raw -> runCatching { mutableStateOf(draftCodec.decodeFromString<CrossPlatformConfig>(raw)) }.getOrNull() },
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun rememberConfigDraft(value: CrossPlatformConfig): MutableState<CrossPlatformConfig> =
|
||||
rememberSaveable(value, saver = configDraftSaver) { mutableStateOf(value) }
|
||||
|
||||
/** Read installation state when the activity resumes, including a return from installing a source app. */
|
||||
@Composable
|
||||
fun rememberSourceVersions(): Map<String, String?> {
|
||||
val context = LocalContext.current.applicationContext
|
||||
val owner = LocalLifecycleOwner.current
|
||||
var versions by remember { mutableStateOf<Map<String, String?>>(emptyMap()) }
|
||||
DisposableEffect(context, owner) {
|
||||
fun refresh() {
|
||||
versions = SourceRegistry.definitions.associate { it.id to Targets.versionOf(context, it.packageName) }
|
||||
}
|
||||
refresh()
|
||||
val observer = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_RESUME) refresh() }
|
||||
owner.lifecycle.addObserver(observer)
|
||||
onDispose { owner.lifecycle.removeObserver(observer) }
|
||||
}
|
||||
return versions
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun CrossWorkspaceOverview(config: AppConfig, tasks: List<CrossPublishTask>, loaded: Boolean, onNavigate: (String) -> Unit) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text("浩瑞", style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
|
||||
Text("手机里的创作工作台", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Surface(color = MaterialTheme.colorScheme.primaryContainer, shape = RoundedCornerShape(20.dp)) {
|
||||
Column(Modifier.fillMaxWidth().padding(18.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text("内容发现 · 创作 · 发布", style = MaterialTheme.typography.titleLarge)
|
||||
Text("跨平台来源待真机适配,当前不会自动采集或发布。既有头条视频任务从下方启动。", style = MaterialTheme.typography.bodyMedium)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||
OverviewMetric("来源选择", SourceRegistry.definitions.count { config.crossPlatform.sourceEnabled(it.id) }.toString())
|
||||
OverviewMetric("本地任务", if (loaded) tasks.size.toString() else "—")
|
||||
OverviewMetric("待核对", if (loaded) tasks.count { it.state in unknownStates }.toString() else "—")
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
TextButton({ onNavigate(Routes.TOPICS) }, Modifier.weight(1f)) { Text("热点候选") }
|
||||
TextButton({ onNavigate(Routes.TASKS) }, Modifier.weight(1f)) { Text("创作任务") }
|
||||
TextButton({ onNavigate(Routes.CROSS_AUTOMATION) }, Modifier.weight(1f)) { Text("自动化设置") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun OverviewMetric(label: String, value: String) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(value, style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.SemiBold)
|
||||
Text(label, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun CrossSettingsEntries(onNavigate: (String) -> Unit) {
|
||||
Section(title = "创作工作台", help = "来源、选题与发布设置;尚未验收的采集能力保持禁用") {
|
||||
SettingsLink("来源 App 管理", "安装版本与适配状态", { onNavigate(Routes.CROSS_SOURCES) })
|
||||
SettingsLink("选题筛选", "内容分类、点赞、粉丝与时效", { onNavigate(Routes.CROSS_FILTERS) })
|
||||
SettingsLink("自动化设置", "作品形式、每日额度与草稿模式", { onNavigate(Routes.CROSS_AUTOMATION) })
|
||||
SettingsLink("既有视频采集设置", "头条 / 百度配置、时段与每日重置", { onNavigate(Routes.COLLECT) })
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SettingsLink(label: String, description: String, onClick: () -> Unit) {
|
||||
Surface(onClick = onClick, shape = RoundedCornerShape(12.dp), color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = .45f)) {
|
||||
Row(Modifier.fillMaxWidth().padding(14.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(label, style = MaterialTheme.typography.titleSmall)
|
||||
Text(description, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
Icon(Icons.Filled.ChevronRight, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ScreenColumn(content: @Composable () -> Unit) {
|
||||
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
|
||||
content()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ScreenHeading(title: String, subtitle: String) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Text(title, style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
|
||||
Text(subtitle, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ToggleRow(title: String, description: String, value: Boolean, enabled: Boolean = true, onChange: (Boolean) -> Unit) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(title, style = MaterialTheme.typography.titleSmall)
|
||||
Text(description, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
Switch(checked = value, onCheckedChange = onChange, enabled = enabled)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SourcesScreen(config: AppConfig, versions: Map<String, String?>, onConfigChange: (AppConfig) -> Unit, onToast: (String) -> Unit) {
|
||||
var draft by rememberConfigDraft(config.crossPlatform)
|
||||
var interval by rememberSaveable(config.crossPlatform.scanIntervalMinutes) { mutableStateOf(config.crossPlatform.scanIntervalMinutes.toString()) }
|
||||
val intervalValid = validNumber(interval, 5..120)
|
||||
ScreenColumn {
|
||||
ScreenHeading("来源 App", "在本机管理来源选择,安装与适配状态分别显示")
|
||||
StatusBanner("来源均待真机适配。勾选仅保存使用偏好,不代表已接通。", StatusLevel.WARN)
|
||||
Section(title = "内容来源") {
|
||||
SourceRegistry.definitions.forEach { source ->
|
||||
val installed = versions[source.id]
|
||||
val reason = SourceRegistry.executionStatus(source.id, installed, draft).reason
|
||||
ToggleRow(source.label, "${installed?.let { "已安装 $it" } ?: "未安装或版本不可读"} · ${if (source.verified) reason else "待真机适配"}", draft.sourceEnabled(source.id)) { checked ->
|
||||
draft = when (source.id) {
|
||||
"zhihu" -> draft.copy(zhihuEnabled = checked)
|
||||
"xiaohongshu" -> draft.copy(xiaohongshuEnabled = checked)
|
||||
"weibo" -> draft.copy(weiboEnabled = checked)
|
||||
"douyin" -> draft.copy(douyinEnabled = checked)
|
||||
else -> draft
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Section(title = "采集节奏") {
|
||||
ValidatedNumberField("每来源采集间隔", interval, "分钟", 5..120, { interval = it })
|
||||
FieldHelp("按顺序使用手机屏幕;来源登录失效或需要验证时暂停该来源。")
|
||||
}
|
||||
Button(onClick = {
|
||||
onConfigChange(config.copy(crossPlatform = config.crossPlatform.copy(
|
||||
zhihuEnabled = draft.zhihuEnabled, xiaohongshuEnabled = draft.xiaohongshuEnabled,
|
||||
weiboEnabled = draft.weiboEnabled, douyinEnabled = draft.douyinEnabled,
|
||||
scanIntervalMinutes = interval.toInt(),
|
||||
)))
|
||||
onToast("来源设置已提交保存")
|
||||
}, enabled = intervalValid, modifier = Modifier.fillMaxWidth()) { Text("保存来源设置") }
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun TopicFiltersScreen(config: AppConfig, onConfigChange: (AppConfig) -> Unit, onToast: (String) -> Unit) {
|
||||
var draft by rememberConfigDraft(config.crossPlatform)
|
||||
var maxAge by rememberSaveable(config.crossPlatform.maxAgeHours) { mutableStateOf(config.crossPlatform.maxAgeHours.toString()) }
|
||||
var likes by rememberSaveable(config.crossPlatform.likesMin) { mutableStateOf(config.crossPlatform.likesMin.toString()) }
|
||||
var fans by rememberSaveable(config.crossPlatform.fansMax) { mutableStateOf(config.crossPlatform.fansMax.toString()) }
|
||||
val valid = validNumber(maxAge, 1..72) && validNumber(likes, 0..1_000_000_000) && validNumber(fans, 0..1_000_000_000)
|
||||
ScreenColumn {
|
||||
ScreenHeading("选题筛选", "先满足分类、时效与指标条件,再进行候选排序")
|
||||
Section(title = "内容分类", help = "可多选,不限于社会类;未选择任何类别时不产生合格候选") {
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
CrossPlatformConfig.CATEGORY_CATALOGUE.forEach { category ->
|
||||
val selected = category in draft.categories
|
||||
FilterChip(selected = selected, onClick = {
|
||||
draft = draft.copy(categories = if (selected) draft.categories - category else draft.categories + category)
|
||||
}, label = { Text(category) })
|
||||
}
|
||||
}
|
||||
FieldHelp("分类选择与图文 / 视频形式分开设置,素材许可、事实核验与账号条件仍需通过。")
|
||||
}
|
||||
Section(title = "发布时间") {
|
||||
ValidatedNumberField("距离发布时间不超过", maxAge, "小时", 1..72, { maxAge = it })
|
||||
FieldHelp("发布时间不可读或超限时跳过,不以首次发现时间替代。")
|
||||
}
|
||||
Section(title = "可选指标门槛") {
|
||||
ToggleRow("点赞数限制", "启用后,点赞数未知的候选不放行", draft.likesGateEnabled) { draft = draft.copy(likesGateEnabled = it) }
|
||||
ValidatedNumberField("作品点赞至少", likes, "赞", 0..1_000_000_000, { likes = it })
|
||||
ToggleRow("作者粉丝数限制", "启用后,粉丝数未知的候选不放行", draft.fansGateEnabled) { draft = draft.copy(fansGateEnabled = it) }
|
||||
ValidatedNumberField("作者粉丝不超过", fans, "人", 0..1_000_000_000, { fans = it })
|
||||
}
|
||||
Section(title = "优选与去重") {
|
||||
Text("按来源与指标口径比较热度;增长需要两次真实快照。同一事件在图文与视频之间共用去重记录。", style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
Button(onClick = {
|
||||
onConfigChange(config.copy(crossPlatform = config.crossPlatform.copy(
|
||||
categories = draft.categories, maxAgeHours = maxAge.toInt(),
|
||||
likesGateEnabled = draft.likesGateEnabled, likesMin = likes.toInt(),
|
||||
fansGateEnabled = draft.fansGateEnabled, fansMax = fans.toInt(),
|
||||
)))
|
||||
onToast("筛选设置已提交保存")
|
||||
}, enabled = valid, modifier = Modifier.fillMaxWidth()) { Text("保存筛选条件") }
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun CrossAutomationScreen(config: AppConfig, onConfigChange: (AppConfig) -> Unit, onNavigate: (String) -> Unit, onToast: (String) -> Unit) {
|
||||
var draft by rememberConfigDraft(config.crossPlatform)
|
||||
val fieldsSaver = remember {
|
||||
mapSaver(
|
||||
save = { values: androidx.compose.runtime.snapshots.SnapshotStateMap<String, String> -> values.toMap() },
|
||||
restore = { values -> values.map { (key, value) -> key to (value as String) }.toMutableStateMap() },
|
||||
)
|
||||
}
|
||||
val fields = rememberSaveable(config.crossPlatform, saver = fieldsSaver) { mutableStateMapOf(
|
||||
"article" to config.crossPlatform.articleDailyLimit.toString(), "video" to config.crossPlatform.videoDailyLimit.toString(),
|
||||
"gap" to config.crossPlatform.publishGapMinutes.toString(), "queue" to config.crossPlatform.readyQueueLimit.toString(),
|
||||
"size" to config.crossPlatform.videoMaxMiB.toString(), "min" to config.crossPlatform.videoMinSeconds.toString(),
|
||||
"max" to config.crossPlatform.videoMaxSeconds.toString(),
|
||||
) }
|
||||
val ranges = mapOf("article" to 0..28, "video" to 0..28, "gap" to 60..1440, "queue" to 1..10, "size" to 1..500, "min" to 20..4000, "max" to 20..4000)
|
||||
val durationsValid = fields.getValue("min").toIntOrNull()?.let { min -> fields.getValue("max").toIntOrNull()?.let { max -> min <= max } } == true
|
||||
val valid = fields.all { (key, value) -> validNumber(value, ranges.getValue(key)) } && durationsValid
|
||||
ScreenColumn {
|
||||
ScreenHeading("自动化设置", "内容形式、运行方式与发布额度")
|
||||
StatusBanner("当前仅实现本地设置与任务框架。来源采集和新发布器待验收,不会执行真实跨平台投稿。", StatusLevel.WARN)
|
||||
Section(title = "运行方式") {
|
||||
ToggleRow("启用跨平台模块", "保存启用偏好,实际执行仍受来源和发布能力门控", draft.enabled) { draft = draft.copy(enabled = it) }
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
FilterChip(selected = draft.mode == CrossPlatformConfig.MODE_DRY_RUN, onClick = { draft = draft.copy(mode = CrossPlatformConfig.MODE_DRY_RUN) }, label = { Text("草稿模式") })
|
||||
FilterChip(selected = draft.mode == CrossPlatformConfig.MODE_AUTO, onClick = {}, enabled = false, label = { Text("自动发布 · 待验收") })
|
||||
}
|
||||
FieldHelp("本版保存本页时使用草稿模式,正式自动提交暂未开放。既有视频的草稿 / 正式设置仍在首页独立保留。")
|
||||
}
|
||||
Section(title = "作品形式") {
|
||||
ToggleRow("图文文章", "事实整理、独立分析与有权使用的配图", draft.articleEnabled) { draft = draft.copy(articleEnabled = it) }
|
||||
ToggleRow("跨平台视频", "本人或已获得许可的素材", draft.videoEnabled) { draft = draft.copy(videoEnabled = it) }
|
||||
}
|
||||
Section(title = "发布额度", help = "新内容与既有视频共用账户总额度,不会在既有额度之外额外增加投稿量") {
|
||||
Text("既有每日总上限:${if (config.segment.enabled) config.segment.dailyTotal else minOf(config.toutiao.publishTotal, config.toutiao.completionLimit)} 篇 / 条", style = MaterialTheme.typography.bodyMedium)
|
||||
ValidatedNumberField("新图文每天最多", fields.getValue("article"), "篇", ranges.getValue("article"), { fields["article"] = it })
|
||||
ValidatedNumberField("新视频每天最多", fields.getValue("video"), "条", ranges.getValue("video"), { fields["video"] = it })
|
||||
ValidatedNumberField("新链路发布间隔", fields.getValue("gap"), "分钟", ranges.getValue("gap"), { fields["gap"] = it })
|
||||
ValidatedNumberField("READY 队列上限", fields.getValue("queue"), "项", ranges.getValue("queue"), { fields["queue"] = it })
|
||||
SettingsLink("调整账户总量与时段", "保留既有视频额度及每日重置设置", { onNavigate(Routes.COLLECT) })
|
||||
}
|
||||
Section(title = "视频边界") {
|
||||
ValidatedNumberField("视频文件大小上限", fields.getValue("size"), "MiB", ranges.getValue("size"), { fields["size"] = it })
|
||||
ValidatedNumberField("视频最短时长", fields.getValue("min"), "秒", ranges.getValue("min"), { fields["min"] = it })
|
||||
ValidatedNumberField("视频最长时长", fields.getValue("max"), "秒", ranges.getValue("max"), { fields["max"] = it })
|
||||
if (!durationsValid) Text("最短时长不能大于最长时长", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
|
||||
FieldHelp("首版范围为可校验的兼容 MP4;来源媒体获取和许可仍需独立验收。")
|
||||
}
|
||||
SettingsLink("来源 App 管理", "查看安装版本与适配情况", { onNavigate(Routes.CROSS_SOURCES) })
|
||||
SettingsLink("内容分类与选题筛选", "修改方向、时效和指标门槛", { onNavigate(Routes.CROSS_FILTERS) })
|
||||
Button(onClick = {
|
||||
onConfigChange(config.copy(crossPlatform = config.crossPlatform.copy(
|
||||
enabled = draft.enabled, articleEnabled = draft.articleEnabled, videoEnabled = draft.videoEnabled,
|
||||
mode = CrossPlatformConfig.MODE_DRY_RUN,
|
||||
articleDailyLimit = fields.getValue("article").toInt(), videoDailyLimit = fields.getValue("video").toInt(),
|
||||
publishGapMinutes = fields.getValue("gap").toInt(), readyQueueLimit = fields.getValue("queue").toInt(),
|
||||
videoMaxMiB = fields.getValue("size").toInt(), videoMinSeconds = fields.getValue("min").toInt(), videoMaxSeconds = fields.getValue("max").toInt(),
|
||||
)))
|
||||
onToast("自动化设置已提交保存,运行模式为草稿")
|
||||
}, enabled = valid, modifier = Modifier.fillMaxWidth()) { Text("保存自动化设置") }
|
||||
}
|
||||
}
|
||||
|
||||
private fun validNumber(value: String, range: IntRange): Boolean = value.toIntOrNull()?.let { it in range } == true
|
||||
|
||||
@Composable
|
||||
private fun ValidatedNumberField(label: String, value: String, unit: String, range: IntRange, onChange: (String) -> Unit) {
|
||||
val valid = validNumber(value, range)
|
||||
OutlinedTextField(
|
||||
value = value, onValueChange = onChange, label = { Text("$label($unit)") },
|
||||
supportingText = { Text(if (valid) "范围 ${range.first}~${range.last}" else "请输入 ${range.first}~${range.last} 之间的整数") },
|
||||
isError = !valid, singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
shape = RoundedCornerShape(12.dp), modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
|
||||
private val unknownStates = setOf(CrossTaskState.SUBMIT_INTENT, CrossTaskState.RESULT_UNKNOWN)
|
||||
private val topicStates = setOf(CrossTaskState.DISCOVERED, CrossTaskState.FILTERED)
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun TopicsScreen(config: AppConfig, tasks: List<CrossPublishTask>, loaded: Boolean, loadError: String?, onNavigate: (String) -> Unit) {
|
||||
var source by rememberSaveable { mutableStateOf("all") }
|
||||
var kind by rememberSaveable { mutableStateOf("all") }
|
||||
var selected by remember { mutableStateOf<CrossPublishTask?>(null) }
|
||||
val candidates = tasks.filter { it.state in topicStates && (source == "all" || it.sourcePlatform == source) && (kind == "all" || it.contentKind.name == kind) }
|
||||
ScreenColumn {
|
||||
ScreenHeading("发现热点", "按选择的内容分类积累可回溯的候选")
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
TextButton({ onNavigate(Routes.CROSS_SOURCES) }) { Text("管理来源") }
|
||||
TextButton({ onNavigate(Routes.CROSS_FILTERS) }) { Text("选题筛选") }
|
||||
}
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(7.dp)) {
|
||||
FilterChip(selected = source == "all", onClick = { source = "all" }, label = { Text("全部来源") })
|
||||
SourceRegistry.definitions.forEach { item -> FilterChip(selected = source == item.id, onClick = { source = item.id }, label = { Text(item.label) }) }
|
||||
}
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(7.dp)) {
|
||||
listOf("all" to "全部形式", "ARTICLE" to "图文", "VIDEO" to "视频").forEach { (id, label) ->
|
||||
FilterChip(selected = kind == id, onClick = { kind = id }, label = { Text(label) })
|
||||
}
|
||||
}
|
||||
Text("分类:${config.crossPlatform.categories.joinToString("、").ifBlank { "未选择" }} · ${config.crossPlatform.maxAgeHours} 小时内", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
when {
|
||||
loadError != null -> StatusBanner("本地任务读取失败:$loadError", StatusLevel.BAD)
|
||||
!loaded -> EmptyPanel("正在读取本地候选", "请稍候")
|
||||
candidates.isEmpty() -> EmptyPanel("暂时没有热点候选", "来源适配通过后,这里将显示真实采集结果。可以先保存分类、作品形式和指标条件。")
|
||||
else -> candidates.forEach { TaskCard(it, { selected = it }) }
|
||||
}
|
||||
FieldHelp("本页读取真实本地记录,不填充演示热榜或虚构热度。当前来源均待真机适配。")
|
||||
}
|
||||
selected?.let { prior -> TaskPreview(tasks.firstOrNull { it.id == prior.id } ?: prior) { selected = null } }
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun CrossTasksScreen(tasks: List<CrossPublishTask>, loaded: Boolean, loadError: String?, onNavigate: (String) -> Unit) {
|
||||
var tab by rememberSaveable { mutableStateOf("pending") }
|
||||
var selected by remember { mutableStateOf<CrossPublishTask?>(null) }
|
||||
fun matches(task: CrossPublishTask, group: String): Boolean = when (group) {
|
||||
"submitted" -> task.state == CrossTaskState.SUBMITTED
|
||||
"draft" -> task.state == CrossTaskState.DRAFT_SAVED
|
||||
"unknown" -> task.state in unknownStates
|
||||
else -> task.state !in unknownStates && task.state !in setOf(CrossTaskState.SUBMITTED, CrossTaskState.DRAFT_SAVED)
|
||||
}
|
||||
ScreenColumn {
|
||||
ScreenHeading("创作任务", "成品准备、草稿和投稿结果分别记录")
|
||||
TextButton({ onNavigate(Routes.CROSS_AUTOMATION) }) { Icon(Icons.Filled.Settings, contentDescription = null); Text(" 发布设置") }
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(7.dp)) {
|
||||
listOf("pending" to "待处理", "draft" to "草稿", "submitted" to "已提交", "unknown" to "待核对").forEach { (id, label) ->
|
||||
FilterChip(selected = tab == id, onClick = { tab = id }, label = { Text("$label ${tasks.count { matches(it, id) }}") })
|
||||
}
|
||||
}
|
||||
if (tab == "unknown") StatusBanner("先核对作品管理中的提交结果;结果不明时保留素材和额度,不提供重复提交操作。", StatusLevel.WARN)
|
||||
if (tab == "submitted") FieldHelp("已提交表示提交回执已核对,不代表作品已审核公开。")
|
||||
val visible = tasks.filter { matches(it, tab) }
|
||||
when {
|
||||
loadError != null -> StatusBanner("本地任务读取失败:$loadError", StatusLevel.BAD)
|
||||
!loaded -> EmptyPanel("正在读取任务", "请稍候")
|
||||
visible.isEmpty() -> EmptyPanel("此状态下暂无任务", "真实成品和提交记录将在这里保留。当前不会生成模拟任务,也不会触发跨平台发布。")
|
||||
else -> visible.forEach { TaskCard(it, { selected = it }) }
|
||||
}
|
||||
}
|
||||
selected?.let { prior -> TaskPreview(tasks.firstOrNull { it.id == prior.id } ?: prior) { selected = null } }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EmptyPanel(title: String, description: String) {
|
||||
Surface(color = MaterialTheme.colorScheme.surface, shape = RoundedCornerShape(20.dp)) {
|
||||
Column(Modifier.fillMaxWidth().padding(22.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text(title, style = MaterialTheme.typography.titleMedium)
|
||||
Text(description, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TaskCard(task: CrossPublishTask, onPreview: () -> Unit) {
|
||||
Surface(shape = RoundedCornerShape(18.dp), color = MaterialTheme.colorScheme.surface, onClick = onPreview) {
|
||||
Column(Modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Icon(if (task.contentKind == CrossContentKind.VIDEO) Icons.Filled.VideoLibrary else Icons.Filled.Article, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
|
||||
Text(task.contentKind.displayName, style = MaterialTheme.typography.labelLarge)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(task.state.displayName, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
Text(task.title, style = MaterialTheme.typography.titleMedium)
|
||||
Text("${SourceRegistry.find(task.sourcePlatform)?.label ?: task.sourcePlatform} · ${formatTime(task.updatedAtMs)}", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
if (task.reason.isNotBlank()) Text(task.reason, style = MaterialTheme.typography.bodySmall)
|
||||
Text("查看内容与来源记录", style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun formatTime(value: Long): String = SimpleDateFormat("MM-dd HH:mm", Locale.CHINA).format(Date(value))
|
||||
|
||||
@Composable
|
||||
private fun TaskPreview(task: CrossPublishTask, onDismiss: () -> Unit) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(if (task.contentKind == CrossContentKind.ARTICLE) "图文内容" else "视频任务") },
|
||||
text = {
|
||||
SelectionContainer {
|
||||
Column(Modifier.heightIn(max = 520.dp).verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text(task.title, style = MaterialTheme.typography.titleMedium)
|
||||
Text("状态:${task.state.displayName}", style = MaterialTheme.typography.bodyMedium)
|
||||
if (task.state == CrossTaskState.SUBMITTED) Text("已提交不等于审核公开。", style = MaterialTheme.typography.bodySmall)
|
||||
if (task.bodyText.isNotBlank()) Text(task.bodyText, style = MaterialTheme.typography.bodyMedium)
|
||||
if (task.mediaPath.isNotBlank()) Text("素材文件:${File(task.mediaPath).name}", style = MaterialTheme.typography.bodyMedium)
|
||||
if (task.sourceUrl.isNotBlank()) Text("来源链接\n${task.sourceUrl}", style = MaterialTheme.typography.bodySmall)
|
||||
Text("许可记录:${task.rightsRef.ifBlank { "尚未记录" }}", style = MaterialTheme.typography.bodySmall)
|
||||
if (task.evidenceJson.isNotBlank()) Text("事实依据\n${task.evidenceJson}", style = MaterialTheme.typography.bodySmall)
|
||||
if (task.receiptRef.isNotBlank()) Text("回执:${task.receiptRef}", style = MaterialTheme.typography.bodySmall)
|
||||
if (task.reason.isNotBlank()) Text(task.reason, style = MaterialTheme.typography.bodySmall)
|
||||
Text("本页仅查看本地记录,不执行发布、重试或回执认定。", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onDismiss) { Text("关闭") } },
|
||||
)
|
||||
}
|
||||
@@ -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 {
|
||||
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', '|')}")
|
||||
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))
|
||||
}
|
||||
return extractCreditScore(text)
|
||||
}
|
||||
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"
|
||||
|
||||
@@ -91,7 +91,8 @@ class ScreenCapturer(private val service: AccessibilityService) {
|
||||
} else {
|
||||
RunLogger.w(TAG, "截屏回调成功但位图转换失败(wrapHardwareBuffer/copy)")
|
||||
}
|
||||
if (cont.isActive) cont.resume(bmp)
|
||||
if (cont.isActive) cont.resume(bmp, onCancellation = { _, value, _ -> value?.recycle() })
|
||||
else bmp?.recycle()
|
||||
}
|
||||
|
||||
override fun onFailure(errorCode: Int) {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.haorui.app.automation.selection
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class DraftReceiptPolicyTest {
|
||||
private fun confirms(lines: List<String>, actualTitle: String? = "测试视频", actualDeclaration: String? = "内容无需标注",
|
||||
elapsed: Long = 1500) =
|
||||
DraftReceiptPolicy.confirms("测试视频", actualTitle, "内容无需标注", actualDeclaration, lines, elapsed)
|
||||
|
||||
@Test fun acceptsTheObservedReceiptForTheCurrentTitleAndDeclaration() {
|
||||
assertTrue(confirms(listOf("保存草稿成功")))
|
||||
}
|
||||
|
||||
@Test fun buttonsSharePanelsAndTimeoutAreNeverReceipts() {
|
||||
listOf("存草稿", "草稿", "发布成功", "分享至", "未能保存草稿成功", "保存草稿失败")
|
||||
.forEach { assertFalse(it, confirms(listOf(it))) }
|
||||
assertFalse(confirms(emptyList(), elapsed = 8000))
|
||||
}
|
||||
|
||||
@Test fun rejectsOtherEditorsDeclarationsAndStaleCallbacks() {
|
||||
assertFalse(confirms(listOf("保存草稿成功"), actualTitle = "另一个标题"))
|
||||
assertFalse(confirms(listOf("保存草稿成功"), actualTitle = null))
|
||||
assertFalse(confirms(listOf("保存草稿成功"), actualDeclaration = "内容为转载"))
|
||||
assertFalse(confirms(listOf("保存草稿成功"), elapsed = -1))
|
||||
assertFalse(confirms(listOf("保存草稿成功"), elapsed = 8001))
|
||||
}
|
||||
|
||||
@Test fun acceptsOcrSpacingWithoutAcceptingAQuotedLongSentence() {
|
||||
assertTrue(confirms(listOf("保存 草稿 成功")))
|
||||
assertTrue(confirms(listOf("✓ 保存草稿成功")))
|
||||
assertTrue(confirms(listOf("O 保存草稿成功")))
|
||||
assertTrue(confirms(listOf("0保存草稿成功")))
|
||||
assertFalse(confirms(listOf("出现保存草稿成功后返回")))
|
||||
assertFalse(confirms(listOf("保存草稿成功后返回")))
|
||||
}
|
||||
|
||||
@Test fun acceptsReceiptMergedWithNeighbouringPageTextWhenNotChinesePreceded() {
|
||||
// 2026-11-14 真机实测三种行合并形态:⊙ 图标被 OCR 误读为 0 / O / 。,均为非汉字承接。
|
||||
assertTrue(confirms(listOf("0保存草稿成功")))
|
||||
assertTrue(confirms(listOf("宁兴·城O保存草稿成功鄞州万达广场小")))
|
||||
assertTrue(confirms(listOf("城市广场。保存草稿成功达广场IMAX店")))
|
||||
// 短语由汉字承接(否定句或纯噪声),不能当回执。
|
||||
assertFalse(confirms(listOf("宁兴·城保存草稿成功鄞州万达广场小")))
|
||||
assertFalse(confirms(listOf("宁兴·城能保存草稿成功鄞州万达广场小")))
|
||||
assertFalse(confirms(listOf("未能保存草稿成功")))
|
||||
}
|
||||
|
||||
@Test fun emptyDeclarationSummaryOnlyConfirmsAnExplicitNoAnnotationChoice() {
|
||||
assertEquals("内容无需标注", DraftReceiptPolicy.declarationReadback("内容无需标注", true, false, null))
|
||||
assertNull(DraftReceiptPolicy.declarationReadback("内容无需标注", false, false, null))
|
||||
assertNull(DraftReceiptPolicy.declarationReadback("内容无需标注", true, true, null))
|
||||
assertNull(DraftReceiptPolicy.declarationReadback("内容为转载", true, false, null))
|
||||
assertEquals("内容为转载", DraftReceiptPolicy.declarationReadback("内容为转载", true, false, "内容为转载"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package com.haorui.app.crossplatform
|
||||
|
||||
import com.haorui.app.crossplatform.model.CrossPlatformConfig
|
||||
import com.haorui.app.crossplatform.model.CrossPlatformConfigCodec
|
||||
import com.haorui.app.data.model.AppConfig
|
||||
import kotlinx.serialization.json.Json
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class CrossPlatformConfigTest {
|
||||
private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }
|
||||
|
||||
@Test fun oldStoredJsonKeepsLegacySettingsAndNewModuleDisabled() {
|
||||
val old = """{"toutiao":{"category":"三农","autoPublish":false,"likeMin":88},"ai":{"deepseekKey":"test-only-placeholder"},"collectMode":"BAIDU"}"""
|
||||
val config = json.decodeFromString(AppConfig.serializer(), old)
|
||||
assertEquals("三农", config.toutiao.category)
|
||||
assertFalse(config.toutiao.autoPublish)
|
||||
assertEquals(88, config.toutiao.likeMin)
|
||||
assertEquals("test-only-placeholder", config.ai.deepseekKey)
|
||||
assertEquals("BAIDU", config.collectMode)
|
||||
assertFalse(config.crossPlatform.enabled)
|
||||
assertEquals(CrossPlatformConfig.MODE_DRY_RUN, config.crossPlatform.mode)
|
||||
}
|
||||
|
||||
@Test fun unknownStoredModeFallsBackToDraftWithoutDiscardingLegacyValues() {
|
||||
val raw = """{"toutiao":{"category":"视频","autoPublish":false},"crossPlatform":{"enabled":true,"mode":"UNKNOWN_FUTURE_MODE"}}"""
|
||||
val config = json.decodeFromString(AppConfig.serializer(), raw)
|
||||
val normalized = config.copy(crossPlatform = config.crossPlatform.normalized())
|
||||
assertEquals("视频", normalized.toutiao.category)
|
||||
assertFalse(normalized.toutiao.autoPublish)
|
||||
assertEquals(CrossPlatformConfig.MODE_DRY_RUN, normalized.crossPlatform.mode)
|
||||
}
|
||||
|
||||
@Test fun flatRoundTripPreservesEveryNewSettingAndNeverUsesLegacyKeys() {
|
||||
val expected = CrossPlatformConfig(
|
||||
enabled = true, mode = CrossPlatformConfig.MODE_AUTO,
|
||||
zhihuEnabled = true, xiaohongshuEnabled = true, weiboEnabled = true, douyinEnabled = true,
|
||||
articleEnabled = false, videoEnabled = true, scanIntervalMinutes = 17,
|
||||
maxAgeHours = 12, articleDailyLimit = 0, videoDailyLimit = 3,
|
||||
publishGapMinutes = 120, readyQueueLimit = 7, videoMaxMiB = 200,
|
||||
videoMinSeconds = 30, videoMaxSeconds = 1200,
|
||||
likesGateEnabled = true, likesMin = 333, fansGateEnabled = true, fansMax = 7000,
|
||||
categories = listOf("职场", "教育"),
|
||||
)
|
||||
val flat = CrossPlatformConfigCodec.toFlatMap(expected)
|
||||
assertTrue(flat.keys.all { it.startsWith("cross_platform_") })
|
||||
assertFalse(flat.containsKey("auto_publish"))
|
||||
assertEquals(expected, CrossPlatformConfigCodec.fromFlatMap(flat + mapOf("auto_publish" to "false")))
|
||||
}
|
||||
|
||||
@Test fun legacyFlatPresetDoesNotEnableSourcesOrInferNewPublishMode() {
|
||||
val config = CrossPlatformConfigCodec.fromFlatMap(mapOf("auto_publish" to "true", "publish_total" to "28"))
|
||||
assertFalse(config.enabled)
|
||||
assertFalse(config.sourceEnabled("zhihu"))
|
||||
assertEquals(CrossPlatformConfig.MODE_DRY_RUN, config.mode)
|
||||
}
|
||||
|
||||
@Test fun malformedImportCannotEnableModuleOrChooseUnknownAutomaticMode() {
|
||||
val config = CrossPlatformConfigCodec.fromFlatMap(mapOf(
|
||||
"cross_platform_enabled" to "TRUE",
|
||||
"cross_platform_mode" to "publish-now",
|
||||
"cross_platform_zhihu_enabled" to "yes",
|
||||
"cross_platform_ready_queue_limit" to "-4",
|
||||
"cross_platform_max_age_hours" to "0",
|
||||
"cross_platform_publish_gap_minutes" to "-1",
|
||||
))
|
||||
assertFalse(config.enabled)
|
||||
assertFalse(config.zhihuEnabled)
|
||||
assertEquals(CrossPlatformConfig.MODE_DRY_RUN, config.mode)
|
||||
assertEquals(1, config.readyQueueLimit)
|
||||
assertEquals(1, config.maxAgeHours)
|
||||
assertEquals(60, config.publishGapMinutes)
|
||||
}
|
||||
|
||||
@Test fun invertedDurationAndOutOfRangeValuesAreConstrainedBeforeUse() {
|
||||
val config = CrossPlatformConfig(
|
||||
videoMinSeconds = 1000, videoMaxSeconds = 40, videoMaxMiB = Int.MAX_VALUE,
|
||||
articleDailyLimit = -3, videoDailyLimit = 100, readyQueueLimit = 999,
|
||||
scanIntervalMinutes = 0, maxAgeHours = 1000, likesMin = -1, fansMax = -4,
|
||||
).normalized()
|
||||
assertEquals(40, config.videoMinSeconds)
|
||||
assertEquals(40, config.videoMaxSeconds)
|
||||
assertEquals(500, config.videoMaxMiB)
|
||||
assertEquals(0, config.articleDailyLimit)
|
||||
assertEquals(28, config.videoDailyLimit)
|
||||
assertEquals(10, config.readyQueueLimit)
|
||||
assertEquals(5, config.scanIntervalMinutes)
|
||||
assertEquals(72, config.maxAgeHours)
|
||||
assertEquals(0, config.likesMin)
|
||||
assertEquals(0, config.fansMax)
|
||||
}
|
||||
|
||||
@Test fun malformedNumericGateDoesNotSilentlyWeakenAutomaticSelection() {
|
||||
val config = CrossPlatformConfigCodec.fromFlatMap(mapOf(
|
||||
"cross_platform_enabled" to "true", "cross_platform_mode" to "AUTO",
|
||||
"cross_platform_zhihu_enabled" to "true", "cross_platform_likes_gate_enabled" to "true",
|
||||
"cross_platform_likes_min" to "999999999999999999999999999999",
|
||||
))
|
||||
assertFalse(config.enabled)
|
||||
assertEquals(CrossPlatformConfig.MODE_DRY_RUN, config.mode)
|
||||
assertTrue(config.likesGateEnabled)
|
||||
}
|
||||
|
||||
@Test fun categoriesAreRestrictedAndExplicitEmptySelectionStaysEmpty() {
|
||||
assertEquals(listOf("教育"), CrossPlatformConfig(categories = listOf("未识别类别", " 教育 ", "教育", "广告")).normalized().categories)
|
||||
val empty = CrossPlatformConfig(categories = emptyList())
|
||||
assertTrue(CrossPlatformConfigCodec.fromFlatMap(CrossPlatformConfigCodec.toFlatMap(empty)).categories.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun expandedCatalogueDoesNotAutoSelectNewCategoriesForExistingSettings() {
|
||||
val originalSelection = listOf("民生生活", "社会现象", "职场", "教育")
|
||||
val oldJson = """{"crossPlatform":{"enabled":false,"maxAgeHours":12}}"""
|
||||
val fromJson = json.decodeFromString(AppConfig.serializer(), oldJson).crossPlatform.normalized()
|
||||
assertEquals(originalSelection, CrossPlatformConfig().categories)
|
||||
assertEquals(originalSelection, fromJson.categories)
|
||||
assertEquals(originalSelection, CrossPlatformConfigCodec.fromFlatMap(mapOf("cross_platform_max_age_hours" to "12")).categories)
|
||||
assertTrue(CrossPlatformConfig.CATEGORY_CATALOGUE.size > originalSelection.size)
|
||||
assertFalse(fromJson.categories.contains("科技数码"))
|
||||
}
|
||||
|
||||
@Test fun newTopicMultiSelectionSurvivesStorageWithoutChangingPublicationForms() {
|
||||
val expected = CrossPlatformConfig(
|
||||
categories = listOf("科技数码", "生活", "宠物", "体育"),
|
||||
articleEnabled = false, videoEnabled = true,
|
||||
)
|
||||
val fromJson = json.decodeFromString(CrossPlatformConfig.serializer(),
|
||||
json.encodeToString(CrossPlatformConfig.serializer(), expected)).normalized()
|
||||
val fromFlat = CrossPlatformConfigCodec.fromFlatMap(CrossPlatformConfigCodec.toFlatMap(expected))
|
||||
assertEquals(expected, fromJson)
|
||||
assertEquals(expected, fromFlat)
|
||||
assertFalse(fromFlat.articleEnabled)
|
||||
assertTrue(fromFlat.videoEnabled)
|
||||
assertEquals(listOf("汽车", "文化历史"), CrossPlatformConfig(categories = listOf(" 汽车 ", "文化历史", "汽车")).normalized().categories)
|
||||
}
|
||||
|
||||
@Test fun normalizedStoredConfigurationRoundTripsWithoutChangingLegacyMode() {
|
||||
val expected = AppConfig().copy(crossPlatform = CrossPlatformConfig(enabled = true, mode = "auto").normalized())
|
||||
val decoded = json.decodeFromString(AppConfig.serializer(), json.encodeToString(AppConfig.serializer(), expected))
|
||||
assertEquals(expected, decoded)
|
||||
assertEquals(CrossPlatformConfig.MODE_AUTO, decoded.crossPlatform.mode)
|
||||
assertEquals(AppConfig().toutiao.autoPublish, decoded.toutiao.autoPublish)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package com.haorui.app.crossplatform
|
||||
|
||||
import com.haorui.app.crossplatform.model.LegacyBudgetState
|
||||
import com.haorui.app.crossplatform.model.CrossPlatformConfig
|
||||
import com.haorui.app.data.model.ResetConfig
|
||||
import com.haorui.app.data.model.SegmentConfig
|
||||
import com.haorui.app.data.model.ToutiaoConfig
|
||||
import com.haorui.app.scheduler.QuotaManager
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import java.time.Clock
|
||||
import java.time.Instant
|
||||
import java.time.ZoneId
|
||||
import java.time.ZonedDateTime
|
||||
|
||||
class QuotaManagerSnapshotTest {
|
||||
private class MutableClock(time: String) : Clock() {
|
||||
var current = ZonedDateTime.parse(time).toInstant()
|
||||
override fun getZone(): ZoneId = ZoneId.of("Asia/Shanghai")
|
||||
override fun withZone(zone: ZoneId): Clock = Clock.fixed(current, zone)
|
||||
override fun instant(): Instant = current
|
||||
fun at(time: String) { current = ZonedDateTime.parse(time).toInstant() }
|
||||
}
|
||||
|
||||
private fun manager(clock: Clock, segment: SegmentConfig = SegmentConfig(), reset: ResetConfig = ResetConfig(),
|
||||
toutiao: ToutiaoConfig = ToutiaoConfig()) = QuotaManager(segment, reset, toutiao, clock).apply {
|
||||
initDaily(0); armResetChain()
|
||||
}
|
||||
|
||||
@Test fun snapshotCannotRunBeforeLegacyStateHasBeenRestored() {
|
||||
val clock = MutableClock("2026-11-13T10:00:00+08:00")
|
||||
val quota = QuotaManager(SegmentConfig(), ResetConfig(), ToutiaoConfig(), clock)
|
||||
assertThrows(IllegalStateException::class.java) { quota.accountSnapshot() }
|
||||
}
|
||||
|
||||
@Test fun standaloneSnapshotUsesSmallerExistingLimitAndAllRestoredSegments() {
|
||||
val clock = MutableClock("2026-11-13T19:00:00+08:00")
|
||||
val quota = manager(clock, toutiao = ToutiaoConfig(publishTotal = 28, completionLimit = 7))
|
||||
quota.initDaily(6)
|
||||
quota.restoreState("1,2,3,0|120")
|
||||
val snapshot = quota.accountSnapshot()
|
||||
assertEquals(7, snapshot.totalLimit)
|
||||
assertEquals(6, snapshot.legacyUsed)
|
||||
assertEquals(listOf(1, 2, 3, 0), snapshot.segmentCounts)
|
||||
assertEquals("2026-11-13:2", snapshot.windowKey)
|
||||
assertNull(snapshot.windowLimit)
|
||||
assertEquals(clock.millis() + 120_000, snapshot.restUntilMs)
|
||||
}
|
||||
|
||||
@Test fun midnightSnapshotResetsExactlyOnceAndExpiresAtTheOldBoundary() {
|
||||
val clock = MutableClock("2026-11-13T23:59:59+08:00")
|
||||
val quota = manager(clock)
|
||||
quota.initDaily(3)
|
||||
var resets = 0
|
||||
quota.onDailyReset = { resets++ }
|
||||
assertEquals(clock.millis() + 1000, quota.accountSnapshot().validUntilMs)
|
||||
clock.at("2026-11-14T00:00:00+08:00")
|
||||
assertEquals("2026-11-14", quota.accountSnapshot().dayKey)
|
||||
assertEquals(0, quota.accountSnapshot().legacyUsed)
|
||||
assertEquals(1, resets)
|
||||
}
|
||||
|
||||
@Test fun defaultSegmentDayEndsAtSixAndWindowExpiresAtTheNextSixHourBoundary() {
|
||||
val clock = MutableClock("2026-11-14T05:59:59+08:00")
|
||||
val quota = manager(clock, SegmentConfig(enabled = true, quota4 = 3))
|
||||
quota.initDaily(2)
|
||||
quota.restoreState("0,0,0,2|0")
|
||||
val before = quota.accountSnapshot()
|
||||
assertEquals("2026-11-13", before.dayKey)
|
||||
assertEquals("2026-11-13:3", before.windowKey)
|
||||
assertEquals(3, before.windowLimit)
|
||||
assertEquals(2, before.legacyWindowUsed)
|
||||
assertEquals(clock.millis() + 1000, before.validUntilMs)
|
||||
clock.at("2026-11-14T06:00:00+08:00")
|
||||
val after = quota.accountSnapshot()
|
||||
assertEquals("2026-11-14:0", after.windowKey)
|
||||
assertEquals(0, after.legacyUsed)
|
||||
assertEquals(clock.millis() + 6 * 3_600_000, after.validUntilMs)
|
||||
}
|
||||
|
||||
@Test fun customResetKeepsTheSameSegmentBudgetWhenItOccursTwiceInOneQuotaDay() {
|
||||
val clock = MutableClock("2026-11-13T14:31:00+08:00")
|
||||
val quota = manager(clock, SegmentConfig(enabled = true), ResetConfig(hour = 14, minute = 30))
|
||||
quota.initDaily(1)
|
||||
quota.restoreState("0,1,0,0|0")
|
||||
val initial = quota.accountSnapshot()
|
||||
clock.at("2026-11-14T12:00:00+08:00")
|
||||
val repeated = quota.accountSnapshot()
|
||||
assertEquals(initial.windowKey, repeated.windowKey)
|
||||
assertEquals(1, repeated.legacyWindowUsed)
|
||||
assertEquals(ZonedDateTime.parse("2026-11-14T14:30:00+08:00").toInstant().toEpochMilli(), repeated.validUntilMs)
|
||||
clock.at("2026-11-14T14:30:00+08:00")
|
||||
assertEquals("2026-11-14", quota.accountSnapshot().dayKey)
|
||||
assertEquals(0, quota.accountSnapshot().legacyUsed)
|
||||
}
|
||||
|
||||
@Test fun repeatedDatabaseProjectionCannotAddCountsTwiceOrLoseOtherWindowsOrRest() {
|
||||
val clock = MutableClock("2026-11-13T19:00:00+08:00")
|
||||
val quota = manager(clock, SegmentConfig(enabled = true))
|
||||
quota.initDaily(1)
|
||||
val state = LegacyBudgetState("2026-11-13", 4, mapOf("2026-11-13:0" to 2, "2026-11-13:1" to 1, "2026-11-13:2" to 1), clock.millis() + 60_000)
|
||||
quota.mergeSharedLegacyState(state)
|
||||
quota.mergeSharedLegacyState(state)
|
||||
quota.mergeSharedLegacyState(state.copy(used = 2, windows = emptyMap(), restUntilMs = 0))
|
||||
assertEquals(4, quota.accountSnapshot().legacyUsed)
|
||||
assertEquals(listOf(2, 1, 1, 0), quota.accountSnapshot().segmentCounts)
|
||||
assertEquals(state.restUntilMs, quota.accountSnapshot().restUntilMs)
|
||||
assertFalse(quota.canPublish())
|
||||
// 跨配额日的计数不投影到今天,已持久化的未来休息截止仍须保留。
|
||||
quota.mergeSharedLegacyState(state.copy(dayKey = "2026-11-12", used = 100))
|
||||
assertEquals(4, quota.accountSnapshot().legacyUsed)
|
||||
}
|
||||
|
||||
@Test fun newContentCapsAndGapAreDerivedWithoutAddingToExistingTotal() {
|
||||
val clock = MutableClock("2026-11-13T19:00:00+08:00")
|
||||
val quota = manager(clock, toutiao = ToutiaoConfig(publishTotal = 3, completionLimit = 2, restMin = 60, restMax = 60))
|
||||
quota.initDaily(1)
|
||||
val budget = quota.submissionBudget(CrossPlatformConfig(articleDailyLimit = 2, videoDailyLimit = 2, publishGapMinutes = 120))
|
||||
assertEquals(2, budget.totalLimit)
|
||||
assertEquals(1, budget.legacySubmittedCount)
|
||||
assertEquals(2, budget.articleLimit)
|
||||
assertEquals(2, budget.videoLimit)
|
||||
assertEquals(7_200_000, budget.minGapMs)
|
||||
assertEquals(clock.millis() + 60_000, quota.sharedRestUntil())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.haorui.app.crossplatform
|
||||
|
||||
import com.haorui.app.crossplatform.model.CrossPlatformConfig
|
||||
import com.haorui.app.crossplatform.source.SourceCapability
|
||||
import com.haorui.app.crossplatform.source.SourceRegistry
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class SourceRegistryTest {
|
||||
private val requested = CrossPlatformConfig(
|
||||
enabled = true, mode = CrossPlatformConfig.MODE_AUTO,
|
||||
zhihuEnabled = true, xiaohongshuEnabled = true, weiboEnabled = true, douyinEnabled = true,
|
||||
)
|
||||
|
||||
@Test fun selectingEverySourceDoesNotInventVerifiedCapabilities() {
|
||||
assertEquals(4, SourceRegistry.definitions.size)
|
||||
SourceRegistry.definitions.forEach { source ->
|
||||
assertFalse(source.verified)
|
||||
SourceCapability.entries.forEach { capability ->
|
||||
assertFalse(SourceRegistry.executionStatus(source.id, "99.99", requested, capability).canExecute)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun moduleAndPerSourceSwitchesBothGateExecution() {
|
||||
assertEquals("跨平台模块未启用", SourceRegistry.executionStatus("zhihu", "1", requested.copy(enabled = false)).reason)
|
||||
assertEquals("来源未启用", SourceRegistry.executionStatus("zhihu", "1", requested.copy(zhihuEnabled = false)).reason)
|
||||
}
|
||||
|
||||
@Test fun absentOrUnreadableVersionDoesNotPassInstallationCheck() {
|
||||
assertFalse(SourceRegistry.executionStatus("xiaohongshu", null, requested).canExecute)
|
||||
assertTrue(SourceRegistry.executionStatus("xiaohongshu", " ", requested).reason.contains("未安装"))
|
||||
}
|
||||
|
||||
@Test fun unknownSourceCannotBorrowAnotherSourcesSelectionOrCapability() {
|
||||
assertNull(SourceRegistry.find("unexpected"))
|
||||
assertFalse(requested.sourceEnabled("unexpected"))
|
||||
assertEquals("未知来源", SourceRegistry.executionStatus("unexpected", "1", requested).reason)
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.haorui.app.crossplatform.account
|
||||
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class AccountClipboardRequestsTest {
|
||||
@Test fun staleCompletionCannotReachANewRequest() = runBlocking {
|
||||
val requests = AccountClipboardRequests()
|
||||
val old = requests.begin(requests.newOwner(), AccountClipboardRequests.Operation.READ, "old")
|
||||
requests.claim()
|
||||
val current = requests.begin(requests.newOwner(), AccountClipboardRequests.Operation.READ, "current")
|
||||
assertNull(old.result.await())
|
||||
assertFalse(requests.complete(old, AccountClipboardRequests.Result("stale", 1)))
|
||||
assertFalse(current.result.isCompleted)
|
||||
assertTrue(requests.complete(current, AccountClipboardRequests.Result("current", 2)))
|
||||
assertEquals("current", current.result.await()!!.text)
|
||||
}
|
||||
@Test fun cancelledOwnerCannotReadOrChangeTheForegroundLater() = runBlocking {
|
||||
val requests = AccountClipboardRequests()
|
||||
val owner = requests.newOwner()
|
||||
val request = requests.begin(owner, AccountClipboardRequests.Operation.PREPARE, "nonce")
|
||||
assertSame(request, requests.claim())
|
||||
requests.cancel(owner)
|
||||
assertNull(request.result.await())
|
||||
assertFalse(requests.isCurrent(request))
|
||||
assertFalse(requests.complete(request, AccountClipboardRequests.Result("nonce", 1)))
|
||||
assertFalse(requests.hasPending())
|
||||
}
|
||||
@Test fun oldCancellationCannotCancelANewOwnerAndUiCanClaimOnlyOnce() {
|
||||
val requests = AccountClipboardRequests()
|
||||
val old = requests.newOwner()
|
||||
val current = requests.begin(requests.newOwner(), AccountClipboardRequests.Operation.READ, "nonce")
|
||||
requests.cancel(old)
|
||||
assertSame(current, requests.claim())
|
||||
assertNull(requests.claim())
|
||||
assertTrue(requests.isCurrent(current))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.haorui.app.crossplatform.account
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class ToutiaoAccountIdentityTest {
|
||||
private val profile = "https://profile.zjurl.cn/rogue/ugc/profile/"
|
||||
@Test fun identityUsesUserIdAndIgnoresDisplayNameAndShareTracking() {
|
||||
val first = ToutiaoAccountIdentity.keyFromProfileLink("$profile?user_id=123456789&name=old&share_id=one")!!
|
||||
val renamed = ToutiaoAccountIdentity.keyFromProfileLink("$profile?name=new&share_id=two&user_id=123456789")!!
|
||||
assertEquals(first, renamed)
|
||||
assertTrue(first.matches(Regex("tt:[a-f0-9]{64}")))
|
||||
assertFalse(first.contains("123456789"))
|
||||
assertNotEquals(first, ToutiaoAccountIdentity.keyFromProfileLink("$profile?user_id=987654321&name=old"))
|
||||
}
|
||||
@Test fun unknownHostOtherPagesNicknamesAndAmbiguousIdsCannotBecomeAccounts() {
|
||||
for (url in listOf("$profile?name=same", "$profile?user_id=123456&user_id=654321", "$profile?user_id=-123456", "$profile?user_id=123x56",
|
||||
"http://profile.zjurl.cn/rogue/ugc/profile?user_id=123456", "https://profile.zjurl.cn.evil.test/rogue/ugc/profile?user_id=123456",
|
||||
"https://[email protected]/rogue/ugc/profile?user_id=123456", "https://profile.zjurl.cn:444/rogue/ugc/profile?user_id=123456",
|
||||
"https://profile.zjurl.cn/rogue/ugc/article?user_id=123456", "$profile?user_id=123456#fragment", "$profile?user_id=123456 $profile?user_id=123456")) {
|
||||
assertNull(url, ToutiaoAccountIdentity.keyFromProfileLink(url))
|
||||
}
|
||||
}
|
||||
@Test fun clipboardMustActuallyChangeAfterAnAcknowledgedPrepare() {
|
||||
val nonce = "nonce"
|
||||
val arm = AccountClipboardRequests.Result(nonce, 100)
|
||||
assertTrue(ToutiaoAccountIdentity.copiedAfterArm(arm, AccountClipboardRequests.Result("$profile?user_id=123456", 101), nonce))
|
||||
assertFalse(ToutiaoAccountIdentity.copiedAfterArm(arm, AccountClipboardRequests.Result("$profile?user_id=123456", 99), nonce))
|
||||
assertFalse(ToutiaoAccountIdentity.copiedAfterArm(arm, AccountClipboardRequests.Result(nonce, 101), nonce))
|
||||
assertFalse(ToutiaoAccountIdentity.copiedAfterArm(arm.copy(text = "not-armed"), AccountClipboardRequests.Result("url", 101), nonce))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package com.haorui.app.crossplatform.model
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class CrossTaskPolicyTest {
|
||||
private val now = 1_800_000_000_000L
|
||||
private fun article() = CrossPublishTask(
|
||||
id = "task-1", accountKey = "account-a", eventId = "event-1", contentKind = CrossContentKind.ARTICLE,
|
||||
title = "社区生活观察", sourcePlatform = "zhihu", sourceUrl = "https://www.zhihu.com/question/1",
|
||||
state = CrossTaskState.EDITING, bodyText = "已整理的文章正文", evidenceJson = "{\"source\":\"verified\"}",
|
||||
payloadHash = "a".repeat(64), publishedAtMs = now - 1000, expiresAtMs = now + 1000, runGeneration = 7,
|
||||
)
|
||||
private fun budget(total: Int = 4, legacy: Int = 0, articles: Int = 2, videos: Int = 2) = CrossSubmissionBudget("2026-11-13", total, legacy, articles, videos)
|
||||
private fun entry(kind: CrossContentKind, state: CrossReservationState, day: String = "2026-11-13") = CrossQuotaEntry(day, kind, state)
|
||||
|
||||
@Test fun cannotBypassSubmissionJournalWithOrdinaryStateTransitions() {
|
||||
for (from in CrossTaskState.entries) {
|
||||
for (to in listOf(CrossTaskState.SUBMIT_INTENT, CrossTaskState.SUBMITTED, CrossTaskState.DRAFT_SAVED, CrossTaskState.RESULT_UNKNOWN)) {
|
||||
assertFalse("$from -> $to", CrossTaskPolicy.canTransition(from, to))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun submittedAndUnknownTasksCannotReturnToTheQueue() {
|
||||
for (from in listOf(CrossTaskState.SUBMITTED, CrossTaskState.RESULT_UNKNOWN, CrossTaskState.DRAFT_SAVED)) {
|
||||
for (to in CrossTaskState.entries) assertFalse(CrossTaskPolicy.canTransition(from, to))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun discoveryCannotSkipFilteringOrPreparation() {
|
||||
assertTrue(CrossTaskPolicy.canTransition(CrossTaskState.DISCOVERED, CrossTaskState.FILTERED))
|
||||
assertFalse(CrossTaskPolicy.canTransition(CrossTaskState.DISCOVERED, CrossTaskState.READY))
|
||||
assertTrue(CrossTaskPolicy.canTransition(CrossTaskState.PREPARED, CrossTaskState.READY))
|
||||
assertFalse(CrossTaskPolicy.canTransition(CrossTaskState.READY, CrossTaskState.EDITING))
|
||||
}
|
||||
|
||||
@Test fun submissionRequiresBothActiveRunAndMatchingTaskGeneration() {
|
||||
val task = article()
|
||||
assertTrue(CrossTaskPolicy.canBeginSubmission(task, 7, 7, true, now))
|
||||
assertFalse(CrossTaskPolicy.canBeginSubmission(task, 7, 7, false, now))
|
||||
assertFalse(CrossTaskPolicy.canBeginSubmission(task, 6, 7, true, now))
|
||||
assertFalse(CrossTaskPolicy.canBeginSubmission(task.copy(runGeneration = 6), 7, 7, true, now))
|
||||
assertFalse(CrossTaskPolicy.canBeginSubmission(task.copy(state = CrossTaskState.SUBMIT_INTENT), 7, 7, true, now))
|
||||
}
|
||||
|
||||
@Test fun expiredOrUnfingerprintedPayloadCannotStartSubmission() {
|
||||
assertNotNull(CrossTaskPolicy.preparationRejection(article().copy(expiresAtMs = now), now))
|
||||
assertNotNull(CrossTaskPolicy.preparationRejection(article().copy(payloadHash = "x".repeat(64)), now))
|
||||
assertNotNull(CrossTaskPolicy.preparationRejection(article().copy(payloadHash = "a".repeat(63)), now))
|
||||
assertNull(CrossTaskPolicy.preparationRejection(article(), now))
|
||||
}
|
||||
|
||||
@Test fun articleNeedsTextAndEvidenceVideoNeedsFileAndRights() {
|
||||
assertNotNull(CrossTaskPolicy.preparationRejection(article().copy(bodyText = ""), now))
|
||||
assertNotNull(CrossTaskPolicy.preparationRejection(article().copy(evidenceJson = ""), now))
|
||||
val video = article().copy(contentKind = CrossContentKind.VIDEO, bodyText = "", mediaPath = "/private/video.mp4", rightsRef = "author-permission-1")
|
||||
assertNull(CrossTaskPolicy.preparationRejection(video, now))
|
||||
assertNotNull(CrossTaskPolicy.preparationRejection(video.copy(mediaPath = ""), now))
|
||||
assertNotNull(CrossTaskPolicy.preparationRejection(video.copy(rightsRef = ""), now))
|
||||
}
|
||||
|
||||
@Test fun restartNeverTreatsSubmittingAsUnsubmitted() {
|
||||
assertEquals(CrossTaskState.RESULT_UNKNOWN, CrossTaskPolicy.recoverState(CrossTaskState.SUBMIT_INTENT))
|
||||
assertEquals(CrossTaskState.PAUSED, CrossTaskPolicy.recoverState(CrossTaskState.EDITING))
|
||||
assertEquals(CrossTaskState.RESULT_UNKNOWN, CrossTaskPolicy.recoverState(CrossTaskState.RESULT_UNKNOWN))
|
||||
assertEquals(CrossTaskState.SUBMITTED, CrossTaskPolicy.recoverState(CrossTaskState.SUBMITTED))
|
||||
}
|
||||
|
||||
@Test fun legacyUsageReducesSharedTotalInsteadOfAddingNewCapacity() {
|
||||
assertNotNull(CrossTaskPolicy.budgetRejection(budget(total = 4, legacy = 4), CrossContentKind.ARTICLE, emptyList()))
|
||||
assertNull(CrossTaskPolicy.budgetRejection(budget(total = 4, legacy = 3), CrossContentKind.ARTICLE, emptyList()))
|
||||
val held = listOf(entry(CrossContentKind.VIDEO, CrossReservationState.RESERVED))
|
||||
assertNotNull(CrossTaskPolicy.budgetRejection(budget(total = 4, legacy = 3), CrossContentKind.ARTICLE, held))
|
||||
}
|
||||
|
||||
@Test fun priorDayUnknownReservationContinuesToOccupyCapacity() {
|
||||
val held = listOf(entry(CrossContentKind.ARTICLE, CrossReservationState.RESERVED, "2026-11-12"))
|
||||
assertNotNull(CrossTaskPolicy.budgetRejection(budget(total = 1), CrossContentKind.VIDEO, held))
|
||||
assertNotNull(CrossTaskPolicy.budgetRejection(budget(articles = 1), CrossContentKind.ARTICLE, held))
|
||||
}
|
||||
|
||||
@Test fun settledPreviousDayAndExplicitlyReleasedReservationsDoNotConsumeToday() {
|
||||
val entries = listOf(
|
||||
entry(CrossContentKind.ARTICLE, CrossReservationState.SETTLED, "2026-11-12"),
|
||||
entry(CrossContentKind.ARTICLE, CrossReservationState.RELEASED),
|
||||
)
|
||||
assertNull(CrossTaskPolicy.budgetRejection(budget(total = 1, articles = 1), CrossContentKind.ARTICLE, entries))
|
||||
}
|
||||
|
||||
@Test fun articleAndVideoCapsAreIndependentUnderSharedAccountTotal() {
|
||||
val entries = listOf(entry(CrossContentKind.ARTICLE, CrossReservationState.SETTLED), entry(CrossContentKind.ARTICLE, CrossReservationState.RESERVED))
|
||||
assertNotNull(CrossTaskPolicy.budgetRejection(budget(), CrossContentKind.ARTICLE, entries))
|
||||
assertNull(CrossTaskPolicy.budgetRejection(budget(), CrossContentKind.VIDEO, entries))
|
||||
assertNotNull(CrossTaskPolicy.budgetRejection(budget(videos = 0), CrossContentKind.VIDEO, entries))
|
||||
}
|
||||
|
||||
@Test fun invalidBudgetCannotSilentlyIncreaseLimits() {
|
||||
for (make in listOf<() -> CrossSubmissionBudget>({ budget(total = -1) }, { budget(legacy = -1) }, { budget(articles = -1) }, { budget(videos = -1) })) {
|
||||
assertThrows(IllegalArgumentException::class.java) { make() }
|
||||
}
|
||||
assertNotNull(CrossTaskPolicy.budgetRejection(budget(total = 0), CrossContentKind.ARTICLE, emptyList()))
|
||||
}
|
||||
|
||||
@Test fun missingFutureOrUnlimitedDatesCannotEnterPublishing() {
|
||||
assertNotNull(CrossTaskPolicy.preparationRejection(article().copy(publishedAtMs = null), now))
|
||||
assertNotNull(CrossTaskPolicy.preparationRejection(article().copy(publishedAtMs = now + 1), now))
|
||||
assertNotNull(CrossTaskPolicy.preparationRejection(article().copy(expiresAtMs = Long.MAX_VALUE), now))
|
||||
assertNotNull(CrossTaskPolicy.preparationRejection(article().copy(expiresAtMs = 0), now))
|
||||
assertNull(CrossTaskPolicy.preparationRejection(article().copy(publishedAtMs = now), now))
|
||||
}
|
||||
|
||||
private fun snapshot() = AccountQuotaSnapshot(now, now + 60_000, "2026-11-13", 4, 0, "2026-11-13:2", 2, 0, listOf(0, 0, 0, 0), 0)
|
||||
|
||||
@Test fun staleFutureOrExpiredQuotaSnapshotsCannotAuthorizeSubmission() {
|
||||
val b = budget().copy(quotaSnapshot = snapshot())
|
||||
assertNull(CrossTaskPolicy.budgetRejection(b, CrossContentKind.ARTICLE, emptyList(), now))
|
||||
for (time in listOf(now - 1, now + 5_001, now + 60_000)) {
|
||||
assertNotNull(CrossTaskPolicy.budgetRejection(b, CrossContentKind.ARTICLE, emptyList(), time))
|
||||
}
|
||||
assertNotNull(CrossTaskPolicy.budgetRejection(b.copy(dayKey = "2026-11-14"), CrossContentKind.ARTICLE, emptyList(), now))
|
||||
}
|
||||
|
||||
@Test fun sharedWindowIncludesLegacyBaselineAndUnknownReservationsFromAnyDay() {
|
||||
val b = budget().copy(quotaSnapshot = snapshot().copy(legacyWindowUsed = 1))
|
||||
val unknown = entry(CrossContentKind.VIDEO, CrossReservationState.RESERVED, "2026-11-12").copy(legacy = true, windowKey = "2026-11-12:0")
|
||||
assertNotNull(CrossTaskPolicy.budgetRejection(b, CrossContentKind.ARTICLE, listOf(unknown), now))
|
||||
assertNotNull(CrossTaskPolicy.budgetRejection(b, null, listOf(unknown), now))
|
||||
val otherWindow = entry(CrossContentKind.ARTICLE, CrossReservationState.SETTLED).copy(windowKey = "2026-11-13:1")
|
||||
assertNull(CrossTaskPolicy.budgetRejection(b, CrossContentKind.VIDEO, listOf(otherWindow), now))
|
||||
}
|
||||
|
||||
@Test fun settledLegacyEntriesAreCountedOnceThroughBaselineAndDoNotUseNewVideoCap() {
|
||||
val settled = entry(CrossContentKind.VIDEO, CrossReservationState.SETTLED).copy(legacy = true)
|
||||
assertNull(CrossTaskPolicy.budgetRejection(budget(total = 2, legacy = 1, videos = 1), CrossContentKind.VIDEO, listOf(settled), now))
|
||||
assertNotNull(CrossTaskPolicy.budgetRejection(budget(total = 1, legacy = 1), null, listOf(settled), now))
|
||||
}
|
||||
|
||||
@Test fun accountRestAppliesToAllFormalSubmissionsButNewGapOnlyAppliesToNewKinds() {
|
||||
val b = budget().copy(quotaSnapshot = snapshot(), minGapMs = 3_600_000)
|
||||
val recent = entry(CrossContentKind.VIDEO, CrossReservationState.SETTLED).copy(legacy = true, settledAtMs = now - 1000)
|
||||
assertNotNull(CrossTaskPolicy.budgetRejection(b, CrossContentKind.ARTICLE, listOf(recent), now))
|
||||
assertNull(CrossTaskPolicy.budgetRejection(b, null, listOf(recent), now))
|
||||
assertNotNull(CrossTaskPolicy.budgetRejection(b, null, listOf(recent.copy(restUntilMs = now + 1)), now))
|
||||
assertNotNull(CrossTaskPolicy.budgetRejection(b.copy(quotaSnapshot = snapshot().copy(restUntilMs = now + 1)), null, emptyList(), now))
|
||||
}
|
||||
|
||||
@Test fun callerCannotRaiseSnapshotTotalOrLowerObservedLegacyUsage() {
|
||||
val b = budget(total = 100).copy(quotaSnapshot = snapshot().copy(totalLimit = 1, legacyUsed = 1))
|
||||
assertNotNull(CrossTaskPolicy.budgetRejection(b, CrossContentKind.ARTICLE, emptyList(), now))
|
||||
assertNotNull(CrossTaskPolicy.budgetRejection(b, null, emptyList(), now))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package com.haorui.app.crossplatform.publish
|
||||
|
||||
import com.haorui.app.crossplatform.model.*
|
||||
import kotlinx.coroutines.*
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class LegacyPublishSessionTest {
|
||||
private val time = 1_800_000_000_000L
|
||||
private val hash = "b".repeat(64)
|
||||
private fun snapshot() = AccountQuotaSnapshot(time, time + 60_000, "2026-11-14", 5, 0, "2026-11-14:0", null, 0, listOf(0,0,0,0), 0)
|
||||
private class Journal : LegacyPublishSession.Journal {
|
||||
var bound = true
|
||||
var reservedId: String? = null
|
||||
var claimed = false
|
||||
var released = false
|
||||
var unknown = false
|
||||
var settled = 0
|
||||
var reserveHook: suspend () -> Unit = {}
|
||||
var claimHook: suspend () -> Unit = {}
|
||||
var releaseFails = false
|
||||
override suspend fun bind(account: String, generation: Long, snapshot: AccountQuotaSnapshot) = bound
|
||||
override suspend fun reserve(id: String, account: String, generation: Long, path: String, hash: String, budget: CrossSubmissionBudget): Boolean {
|
||||
reservedId = id; reserveHook(); return true
|
||||
}
|
||||
override suspend fun claim(id: String, generation: Long, budget: CrossSubmissionBudget): Boolean { claimed = true; claimHook(); return true }
|
||||
override suspend fun unknown(id: String) { assertEquals(reservedId, id); unknown = true }
|
||||
override suspend fun releaseUnclicked(id: String, generation: Long): Boolean {
|
||||
assertEquals(reservedId, id)
|
||||
if (releaseFails) error("database unavailable")
|
||||
return (!claimed).also { if (it) released = true }
|
||||
}
|
||||
override suspend fun settle(id: String, receiptRef: String, snapshot: AccountQuotaSnapshot, restUntilMs: Long, period: SubmissionBudgetPeriod): LegacyBudgetState {
|
||||
if (settled == 0) settled++
|
||||
return LegacyBudgetState(period.dayKey, settled, mapOf(period.windowKey to settled), restUntilMs)
|
||||
}
|
||||
}
|
||||
private fun session(journal: Journal, current: () -> Boolean = { true }, account: VerifiedAccount? = VerifiedAccount("tt:" + "a".repeat(64), "显示名", time, "operation"), now: () -> Long = { time }) =
|
||||
LegacyPublishSession(7, "/test.mp4", hash, journal, { account }, { CrossSubmissionBudget(snapshot().dayKey, 5, 0, 2, 2, snapshot()) }, current, now)
|
||||
|
||||
@Test fun unknownOrChangedAccountCannotReachTheJournalOrClick() = runBlocking {
|
||||
val journal = Journal()
|
||||
val unknown = session(journal, account = null)
|
||||
assertFalse(unknown.prepare())
|
||||
assertFalse(unknown.dispatch(hash, { true }) { error("must not click") })
|
||||
assertNull(journal.reservedId)
|
||||
journal.bound = false
|
||||
assertFalse(session(journal).prepare())
|
||||
assertNull(journal.reservedId)
|
||||
}
|
||||
|
||||
@Test fun changedPayloadOrExpiredIdentityCannotReserve() = runBlocking {
|
||||
val journal = Journal()
|
||||
var now = time
|
||||
val session = session(journal, now = { now })
|
||||
assertTrue(session.prepare())
|
||||
now += 120_001
|
||||
assertFalse(session.dispatch(hash, { true }) { error("must not click") })
|
||||
assertNull(journal.reservedId)
|
||||
val changed = session(journal)
|
||||
assertTrue(changed.prepare())
|
||||
assertFalse(changed.dispatch("c".repeat(64), { true }) { error("must not click") })
|
||||
assertNull(journal.reservedId)
|
||||
}
|
||||
|
||||
@Test fun stopOrIdentityChangeAfterReservationReleasesOnlyAnUnclaimedClick() = runBlocking {
|
||||
for (identityChange in listOf(false, true)) {
|
||||
val journal = Journal()
|
||||
var current = true
|
||||
var identity = true
|
||||
val session = session(journal, current = { current })
|
||||
assertTrue(session.prepare())
|
||||
journal.reserveHook = { if (identityChange) identity = false else current = false }
|
||||
assertFalse(session.dispatch(hash, { identity }) { error("must not click") })
|
||||
assertTrue(journal.released)
|
||||
assertFalse(journal.claimed)
|
||||
assertEquals(LegacyPublishSession.State.NOT_SUBMITTED, session.state)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun cancellationAfterIntentCommitStillFindsTheKnownAttemptId() = runBlocking {
|
||||
val journal = Journal()
|
||||
val session = session(journal)
|
||||
assertTrue(session.prepare())
|
||||
journal.reserveHook = { throw CancellationException("cancel after commit") }
|
||||
var cancelled = false
|
||||
try { session.dispatch(hash, { true }) { error("must not click") } } catch (_: CancellationException) { cancelled = true }
|
||||
assertTrue(cancelled)
|
||||
assertEquals(session.attemptId, journal.reservedId)
|
||||
assertTrue(journal.released)
|
||||
}
|
||||
|
||||
@Test fun cancellationAfterClickClaimCommitCannotReleaseQuota() = runBlocking {
|
||||
val journal = Journal()
|
||||
val session = session(journal)
|
||||
assertTrue(session.prepare())
|
||||
journal.claimHook = { throw CancellationException("cancel after claim commit") }
|
||||
try { session.dispatch(hash, { true }) { error("must not click") }; fail() } catch (_: CancellationException) { }
|
||||
assertFalse(journal.released)
|
||||
assertTrue(journal.unknown)
|
||||
assertTrue(session.retainsMedia)
|
||||
assertEquals(LegacyPublishSession.State.UNKNOWN, session.state)
|
||||
}
|
||||
|
||||
@Test fun stopAfterClaimKeepsQuotaAndNeverDispatches() = runBlocking {
|
||||
val journal = Journal()
|
||||
var current = true
|
||||
val session = session(journal, current = { current })
|
||||
assertTrue(session.prepare())
|
||||
journal.claimHook = { current = false }
|
||||
assertFalse(session.dispatch(hash, { true }) { error("must not click") })
|
||||
assertTrue(journal.unknown)
|
||||
assertFalse(journal.released)
|
||||
}
|
||||
|
||||
@Test fun uncertainClickIsNeverRetriedAndMediaIsRetained() = runBlocking {
|
||||
val journal = Journal()
|
||||
val session = session(journal)
|
||||
assertTrue(session.prepare())
|
||||
var clicks = 0
|
||||
assertFalse(session.dispatch(hash, { true }) { clicks++; false })
|
||||
assertFalse(session.dispatch(hash, { true }) { clicks++; true })
|
||||
assertEquals(1, clicks)
|
||||
assertTrue(journal.unknown)
|
||||
assertTrue(session.retainsMedia)
|
||||
}
|
||||
|
||||
@Test fun concurrentDispatchesProduceOnlyOneClick() = runBlocking {
|
||||
val journal = Journal()
|
||||
val session = session(journal)
|
||||
assertTrue(session.prepare())
|
||||
var clicks = 0
|
||||
val results = (1..3).map { async(Dispatchers.Default) { session.dispatch(hash, { true }) { clicks++; delay(10); true } } }.awaitAll()
|
||||
assertEquals(1, results.count { it })
|
||||
assertEquals(1, clicks)
|
||||
}
|
||||
|
||||
@Test fun explicitReceiptIsIdempotentAndOnlyThenAllowsCleanup() = runBlocking {
|
||||
val journal = Journal()
|
||||
val session = session(journal)
|
||||
assertTrue(session.prepare())
|
||||
assertTrue(session.dispatch(hash, { true }) { true })
|
||||
assertTrue(session.retainsMedia)
|
||||
session.markUnknown("等待作品核对")
|
||||
assertEquals(1, session.confirm("verified-work-id", snapshot(), time + 60_000, snapshot().period)!!.used)
|
||||
assertEquals(1, session.confirm("verified-work-id", snapshot(), time + 60_000, snapshot().period)!!.used)
|
||||
assertFalse(session.retainsMedia)
|
||||
}
|
||||
|
||||
@Test fun cleanupFailureCannotTurnCancellationIntoSuccessOrAllowMediaDeletion() = runBlocking {
|
||||
val journal = Journal().apply { reserveHook = { throw CancellationException("cancel") }; releaseFails = true }
|
||||
val session = session(journal)
|
||||
assertTrue(session.prepare())
|
||||
try { session.dispatch(hash, { true }) { error("must not click") }; fail() } catch (_: CancellationException) { }
|
||||
assertTrue(session.retainsMedia)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.haorui.app.crossplatform.schedule
|
||||
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.flow.first
|
||||
import org.junit.After
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class CrossRunLifecycleTest {
|
||||
private data class Call(val start: Boolean, val result: CompletableDeferred<Long> = CompletableDeferred())
|
||||
private class Persistence : CrossRunPersistence {
|
||||
val calls = Channel<Call>(Channel.UNLIMITED)
|
||||
private suspend fun persist(start: Boolean): Long {
|
||||
val call = Call(start)
|
||||
calls.send(call)
|
||||
return call.result.await()
|
||||
}
|
||||
override suspend fun beginRun() = persist(true)
|
||||
override suspend fun pauseRun() = persist(false)
|
||||
suspend fun next(start: Boolean): Call = withTimeout(5_000) {
|
||||
calls.receive().also { assertEquals(start, it.start) }
|
||||
}
|
||||
}
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
private val persistence = Persistence()
|
||||
private val lifecycle = CrossRunLifecycle(persistence, scope)
|
||||
@After fun tearDown() { scope.cancel() }
|
||||
|
||||
private suspend fun session(): CrossRunLifecycle.Session = lifecycle.openSession().also {
|
||||
persistence.next(false).result.complete(1)
|
||||
withTimeout(5_000) { lifecycle.state.first { !it.pending } }
|
||||
}
|
||||
|
||||
private suspend fun running(): CrossRunLifecycle.Session = session().also {
|
||||
it.configure(true)
|
||||
it.start()
|
||||
persistence.next(true).result.complete(2)
|
||||
awaitGeneration(2)
|
||||
}
|
||||
|
||||
private suspend fun awaitGeneration(generation: Long) = withTimeout(5_000) {
|
||||
lifecycle.state.first { it.generation == generation }
|
||||
}
|
||||
|
||||
@Test fun moduleAndExplicitRunIntentAreBothRequired() = runBlocking {
|
||||
val session = session()
|
||||
session.start()
|
||||
assertNull(session.currentGeneration())
|
||||
assertTrue(persistence.calls.tryReceive().isFailure)
|
||||
session.configure(true)
|
||||
val start = persistence.next(true)
|
||||
assertNull(session.currentGeneration())
|
||||
start.result.complete(7)
|
||||
awaitGeneration(7)
|
||||
assertEquals(7L, session.currentGeneration())
|
||||
session.start()
|
||||
session.configure(true)
|
||||
assertTrue(persistence.calls.tryReceive().isFailure)
|
||||
assertEquals(7L, session.currentGeneration())
|
||||
}
|
||||
|
||||
@Test fun enablingAloneDoesNotStartTheRun() = runBlocking {
|
||||
val session = session()
|
||||
session.configure(true)
|
||||
assertNull(session.currentGeneration())
|
||||
assertTrue(persistence.calls.tryReceive().isFailure)
|
||||
}
|
||||
|
||||
@Test fun stopAndRestartDuringSlowStartOnlyExposeTheLastPersistedGeneration() = runBlocking {
|
||||
val session = session()
|
||||
session.configure(true)
|
||||
session.start()
|
||||
val firstStart = persistence.next(true)
|
||||
session.stop()
|
||||
session.start()
|
||||
assertNull(session.currentGeneration())
|
||||
firstStart.result.complete(2)
|
||||
val stop = persistence.next(false)
|
||||
assertNull(session.currentGeneration())
|
||||
stop.result.complete(3)
|
||||
val restart = persistence.next(true)
|
||||
assertNull(session.currentGeneration())
|
||||
restart.result.complete(4)
|
||||
awaitGeneration(4)
|
||||
assertEquals(4L, session.currentGeneration())
|
||||
}
|
||||
|
||||
@Test fun disablingRevokesImmediatelyAndStoppedIntentDoesNotReturnOnEnable() = runBlocking {
|
||||
val session = running()
|
||||
session.configure(false)
|
||||
assertNull(session.currentGeneration())
|
||||
val stop = persistence.next(false)
|
||||
session.stop()
|
||||
session.configure(true)
|
||||
stop.result.complete(3)
|
||||
withTimeout(5_000) { lifecycle.state.first { !it.pending } }
|
||||
assertNull(session.currentGeneration())
|
||||
assertTrue(persistence.calls.tryReceive().isFailure)
|
||||
}
|
||||
|
||||
@Test fun reEnablingDuringAnExplicitRunAllocatesANewGeneration() = runBlocking {
|
||||
val session = running()
|
||||
session.configure(false)
|
||||
session.configure(true)
|
||||
persistence.next(false).result.complete(3)
|
||||
persistence.next(true).result.complete(4)
|
||||
awaitGeneration(4)
|
||||
assertEquals(4L, session.currentGeneration())
|
||||
}
|
||||
|
||||
@Test fun staleServiceCannotStopOrReconfigureTheNewServiceSession() = runBlocking<Unit> {
|
||||
val old = running()
|
||||
val current = lifecycle.openSession()
|
||||
assertNull(old.currentGeneration())
|
||||
persistence.next(false).result.complete(3)
|
||||
current.configure(true)
|
||||
current.start()
|
||||
persistence.next(true).result.complete(4)
|
||||
awaitGeneration(4)
|
||||
old.configure(false)
|
||||
old.start()
|
||||
old.stop()
|
||||
old.close()
|
||||
assertEquals(4L, current.currentGeneration())
|
||||
assertTrue(persistence.calls.tryReceive().isFailure)
|
||||
current.close()
|
||||
assertNull(current.currentGeneration())
|
||||
persistence.next(false).result.complete(5)
|
||||
withTimeout(5_000) { lifecycle.state.first { !it.pending } }
|
||||
}
|
||||
|
||||
@Test fun persistenceFailureBlocksAdmissionAndExplicitStartCanRetry() = runBlocking {
|
||||
val session = session()
|
||||
session.configure(true)
|
||||
session.start()
|
||||
persistence.next(true).result.completeExceptionally(IllegalStateException("private diagnostic"))
|
||||
val failed = withTimeout(5_000) { lifecycle.state.first { it.error != null } }
|
||||
assertNull(session.currentGeneration())
|
||||
assertFalse(failed.error!!.contains("private diagnostic"))
|
||||
session.start()
|
||||
persistence.next(true).result.complete(3)
|
||||
awaitGeneration(3)
|
||||
assertEquals(3L, session.currentGeneration())
|
||||
}
|
||||
|
||||
@Test fun failedStopNeverRestoresThePreviousPermit() = runBlocking {
|
||||
val session = running()
|
||||
session.stop()
|
||||
assertNull(session.currentGeneration())
|
||||
persistence.next(false).result.completeExceptionally(IllegalStateException())
|
||||
withTimeout(5_000) { lifecycle.state.first { it.error != null } }
|
||||
assertNull(session.currentGeneration())
|
||||
session.stop()
|
||||
persistence.next(false).result.complete(3)
|
||||
withTimeout(5_000) { lifecycle.state.first { !it.pending && it.error == null } }
|
||||
assertNull(session.currentGeneration())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.haorui.app.crossplatform.schedule
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
class ForegroundCoordinatorTest {
|
||||
private fun ready() = ForegroundCoordinator().apply { configure(true); beginRun() }
|
||||
|
||||
@Test fun sourceCannotPreemptInFlightStepOrUnsafeBoundary() {
|
||||
val c = ready()
|
||||
val old = c.tryEnterLegacy("COLLECT")!!
|
||||
assertNull(c.tryEnterSource("zhihu") { true })
|
||||
c.release(old)
|
||||
assertNull(c.tryEnterSource("zhihu") { false })
|
||||
assertNotNull(c.tryEnterSource("zhihu") { true })
|
||||
}
|
||||
|
||||
@Test fun allLegacyDriversYieldForWholeSourceSession() {
|
||||
val c = ready()
|
||||
val source = c.tryEnterSource("xhs") { true }!!
|
||||
listOf("COLLECT", "PUBLISH", "INTERACT", "REST", "CREDIT", "RECOVERY").forEach {
|
||||
assertNull(c.tryEnterLegacy(it))
|
||||
}
|
||||
assertTrue(c.hasSourceOwner())
|
||||
assertTrue(c.release(source))
|
||||
assertNotNull(c.tryEnterLegacy("PUBLISH"))
|
||||
}
|
||||
|
||||
@Test fun stopInvalidatesButDoesNotReleaseInFlightOperation() {
|
||||
val c = ready()
|
||||
val source = c.tryEnterSource("zhihu") { true }!!
|
||||
c.stop()
|
||||
assertFalse(c.isCurrent(source))
|
||||
c.beginRun()
|
||||
assertNull(c.tryEnterLegacy("COLLECT"))
|
||||
assertNull(c.tryEnterSource("xhs") { true })
|
||||
assertTrue(c.release(source))
|
||||
val next = c.tryEnterSource("xhs") { true }!!
|
||||
assertFalse(c.release(source))
|
||||
assertTrue(c.isCurrent(next))
|
||||
}
|
||||
|
||||
@Test fun disablingDoesNotDropSourceLeaseBeforeItsFinally() {
|
||||
val c = ready()
|
||||
val source = c.tryEnterSource("zhihu") { true }!!
|
||||
c.configure(false)
|
||||
assertFalse(c.isCurrent(source))
|
||||
assertNull(c.tryEnterLegacy("COLLECT"))
|
||||
c.release(source)
|
||||
assertNotNull(c.tryEnterLegacy("COLLECT"))
|
||||
assertNull(c.tryEnterSource("xhs") { true })
|
||||
}
|
||||
|
||||
@Test fun disabledModePreservesLegacyAdmissionAndTracksAllInFlightSteps() {
|
||||
val c = ForegroundCoordinator()
|
||||
val a = c.tryEnterLegacy("COLLECT")!!
|
||||
val b = c.tryEnterLegacy("REST")!!
|
||||
c.configure(true)
|
||||
c.beginRun()
|
||||
c.release(a)
|
||||
assertNull(c.tryEnterSource("zhihu") { true })
|
||||
c.release(b)
|
||||
assertNotNull(c.tryEnterSource("zhihu") { true })
|
||||
}
|
||||
|
||||
@Test fun concurrentAdmissionsHaveOnlyOneWinner() {
|
||||
val c = ready()
|
||||
val pool = Executors.newFixedThreadPool(8)
|
||||
val barrier = CountDownLatch(1)
|
||||
try {
|
||||
val results = (1..24).map { i -> pool.submit<ForegroundCoordinator.Ticket?> {
|
||||
barrier.await()
|
||||
c.tryEnterSource("source-$i") { true }
|
||||
} }
|
||||
barrier.countDown()
|
||||
assertEquals(1, results.count { it.get() != null })
|
||||
} finally { pool.shutdownNow() }
|
||||
}
|
||||
|
||||
@Test fun copiedOrForeignTicketCannotReleaseCurrentOwner() {
|
||||
val a = ready()
|
||||
val b = ready()
|
||||
val active = a.tryEnterSource("zhihu") { true }!!
|
||||
val foreign = b.tryEnterSource("zhihu") { true }!!
|
||||
assertFalse(a.release(active.copy()))
|
||||
assertFalse(a.release(foreign))
|
||||
assertTrue(a.isCurrent(active))
|
||||
}
|
||||
@Test fun accountCheckExcludesLegacyStepsEvenWithTheNewModuleDisabled() {
|
||||
val c = ForegroundCoordinator()
|
||||
val account = c.tryEnterExclusive("ACCOUNT")!!
|
||||
assertNull(c.tryEnterLegacy("COLLECT"))
|
||||
assertNull(c.tryEnterExclusive("ACCOUNT"))
|
||||
c.stop()
|
||||
assertFalse(c.isCurrent(account))
|
||||
assertNull(c.tryEnterLegacy("PUBLISH"))
|
||||
c.release(account)
|
||||
assertNotNull(c.tryEnterLegacy("PUBLISH"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.haorui.app.ocr
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class CreditScoreParserTest {
|
||||
private fun line(text: String, left: Int, top: Int, right: Int, bottom: Int) =
|
||||
CreditScoreParser.Line(text, CreditScoreParser.Area(left, top, right, bottom))
|
||||
private fun page(score: String = "100分") = listOf(
|
||||
line("账号处罚中心", 350, 146, 726, 204),
|
||||
line("测试账户", 185, 343, 830, 390),
|
||||
line("信用分", 65, 470, 180, 510),
|
||||
line("账号状态", 540, 470, 700, 510),
|
||||
line(score, 125, 547, 260, 595),
|
||||
line("正常", 600, 547, 700, 595),
|
||||
line("处罚记录", 75, 850, 315, 900),
|
||||
)
|
||||
private fun read(lines: List<CreditScoreParser.Line>) = CreditScoreParser.extract(lines, 1080, 2408)
|
||||
|
||||
@Test fun readsTheActualPenaltyPageDespiteItsTitleAndHistoryLabels() {
|
||||
assertEquals(100, read(page()))
|
||||
assertEquals(80, read(page("80分") + line("已扣20分", 80, 1000, 340, 1060)))
|
||||
}
|
||||
|
||||
@Test fun preservesLowScoresAndExactGateBoundaries() {
|
||||
listOf(0, 1, 59, 60, 99, 100).forEach { assertEquals(it, read(page("${it}分"))) }
|
||||
}
|
||||
|
||||
@Test fun requiresTheObservedPageAndBothCardLabels() {
|
||||
listOf("账号处罚中心", "信用分", "账号状态").forEach { missing ->
|
||||
assertNull(missing, read(page().filterNot { it.text == missing }))
|
||||
}
|
||||
assertNull(read(page().map { if (it.text == "账号处罚中心") it.copy(text = "视频详情") else it }))
|
||||
assertNull(read(page() + line("信用分", 65, 540, 180, 580)))
|
||||
}
|
||||
|
||||
@Test fun ignoresClockVideoDurationAndNumbersOutsideTheCreditColumn() {
|
||||
val noisy = page() + listOf(
|
||||
line("09:42", 45, 45, 180, 100),
|
||||
line("00:20/01:00", 50, 650, 360, 700),
|
||||
line("80分", 600, 547, 740, 595),
|
||||
line("20分", 125, 1050, 260, 1100),
|
||||
)
|
||||
assertEquals(100, read(noisy))
|
||||
assertNull(read(noisy.filterNot { it.text == "100分" }))
|
||||
}
|
||||
|
||||
@Test fun neverTreatsDeductionsOrLongSentencesAsTheCurrentScore() {
|
||||
listOf("已扣20分", "扣分20", "-20分", "+20分", "信用分扣除20分", "视频播放100分钟", "09:42")
|
||||
.forEach { assertNull(it, read(page(it))) }
|
||||
}
|
||||
|
||||
@Test fun rejectsConflictingOrOutOfRangeValuesInTheCard() {
|
||||
assertNull(read(page() + line("80分", 125, 602, 260, 645)))
|
||||
listOf("101分", "999分").forEach { assertNull(read(page(it))) }
|
||||
assertNull(read(page() + line("101分", 125, 602, 260, 645)))
|
||||
}
|
||||
|
||||
@Test fun handlesOcrDigitVariantsAndAnInlineLabelWithoutReadingOtherColumns() {
|
||||
listOf("100 分", "1OO分", "1oo 分", "100").forEach { assertEquals(it, 100, read(page(it))) }
|
||||
val inline = page().filterNot { it.text == "信用分" || it.text == "100分" } +
|
||||
line("信用分:80分", 65, 470, 300, 510)
|
||||
assertEquals(80, read(inline))
|
||||
}
|
||||
|
||||
@Test fun scalesWithScreenSizeAndDoesNotDependOnOcrReadingOrder() {
|
||||
listOf(0.5, 1.0, 2.0).forEach { scale ->
|
||||
val scaled = page().reversed().map { line ->
|
||||
val b = line.bounds
|
||||
line.copy(bounds = CreditScoreParser.Area((b.left * scale).toInt(), (b.top * scale).toInt(),
|
||||
(b.right * scale).toInt(), (b.bottom * scale).toInt()))
|
||||
}
|
||||
assertEquals(100, CreditScoreParser.extract(scaled, (1080 * scale).toInt(), (2408 * scale).toInt()))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun rejectsMissingOrInvalidScoreGeometry() {
|
||||
val missing = page().filterNot { it.text == "100分" }
|
||||
listOf(CreditScoreParser.Area(0, 0, 0, 0), CreditScoreParser.Area(-10, 547, 260, 595),
|
||||
CreditScoreParser.Area(125, 547, 1260, 595), CreditScoreParser.Area(125, 1000, 260, 1050))
|
||||
.forEach { assertNull(read(missing + CreditScoreParser.Line("100分", it))) }
|
||||
assertNull(CreditScoreParser.extract(page(), 0, 2408))
|
||||
}
|
||||
|
||||
@Test fun optionalRegionRestrictsTheScoreWhileKeepingFullPageValidation() {
|
||||
assertEquals(100, CreditScoreParser.extract(page(), 1080, 2408, CreditScoreParser.Area(70, 520, 450, 650)))
|
||||
assertNull(CreditScoreParser.extract(page(), 1080, 2408, CreditScoreParser.Area(550, 520, 950, 650)))
|
||||
assertNull(CreditScoreParser.extract(page(), 1080, 2408, CreditScoreParser.Area(-1, 520, 450, 650)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.haorui.app.pipeline
|
||||
|
||||
import java.io.File
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
|
||||
class PendingDraftStoreTest {
|
||||
@get:Rule val temporary = TemporaryFolder()
|
||||
private fun media() = temporary.newFile("测试素材.mp4").apply { writeText("owned test fixture") }
|
||||
|
||||
@Test fun committedIntentSurvivesReopeningWithoutReleasingMedia() {
|
||||
val file = media()
|
||||
val directory = File(temporary.root, "pending")
|
||||
val attempt = PendingDraftStore(directory).begin(file.path, "当前标题", "内容无需标注")
|
||||
val reopened = PendingDraftStore(directory)
|
||||
assertEquals(setOf(file.canonicalPath), reopened.protectedPaths())
|
||||
assertEquals(attempt, reopened.attempts().single())
|
||||
assertTrue(file.exists())
|
||||
}
|
||||
|
||||
@Test fun refusesASecondIntentForTheSameUnconfirmedFile() {
|
||||
val file = media()
|
||||
val store = PendingDraftStore(temporary.newFolder("pending"))
|
||||
store.begin(file.path, "标题一", "内容无需标注")
|
||||
assertThrows(IllegalStateException::class.java) { store.begin(file.path, "标题二", "内容无需标注") }
|
||||
assertEquals(1, store.attempts().size)
|
||||
}
|
||||
|
||||
@Test fun onlyTheExactConfirmedAttemptReleasesItsProtection() {
|
||||
val file = media()
|
||||
val store = PendingDraftStore(temporary.newFolder("pending"))
|
||||
val attempt = store.begin(file.path, "当前标题", "内容无需标注")
|
||||
assertFalse(store.confirm("unknown-attempt"))
|
||||
assertEquals(setOf(file.canonicalPath), store.protectedPaths())
|
||||
assertTrue(store.confirm(attempt.id))
|
||||
assertTrue(store.protectedPaths().isEmpty())
|
||||
assertTrue(file.exists())
|
||||
}
|
||||
|
||||
@Test fun refusesDispatchWhenTheJournalCannotBeWritten() {
|
||||
val file = media()
|
||||
val unusableDirectory = temporary.newFile("not-a-directory")
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
PendingDraftStore(unusableDirectory).begin(file.path, "当前标题", "内容无需标注")
|
||||
}
|
||||
assertTrue(file.exists())
|
||||
}
|
||||
|
||||
@Test fun corruptJournalFailsClosedInsteadOfReturningAnEmptyProtectionSet() {
|
||||
val directory = temporary.newFolder("pending")
|
||||
File(directory, "broken.json").writeText("partial journal")
|
||||
assertThrows(Exception::class.java) { PendingDraftStore(directory).protectedPaths() }
|
||||
}
|
||||
}
|
||||
+18
-4
@@ -7,11 +7,13 @@
|
||||
| 日期或范围 | 结果 |
|
||||
|---|---|
|
||||
| 2026-10-29、10-30 原视频链路 | 留存记录显示真机跑通过采集、解析、下载、草稿/发布与互斥;不等于新功能已验收 |
|
||||
| 2026-11-14 JVM | 88 项全通过,新增旧提交会话 10 项、账号策略 3 项、剪贴板请求 3 项、独占票据 1 项;原视频筛选 16 项仍通过 |
|
||||
| 2026-11-14 JVM | 107 项全通过;本轮在前轮 88 项基础上新增信用分 10 项、草稿回执 4 项、草稿意图持久化 5 项。原视频筛选 16 项仍通过 |
|
||||
| 2026-11-14 M1 真机 SQLite | 19 项通过,新增意图/点击许可提交后丢失返回值的真实库取消测试;使用隔离库,未知额度与媒体跨重启保留 |
|
||||
| 2026-11-13 M1 基础 UI | 五 tab、空任务、18 分类、作品形式独立保存、跨页不覆盖、旋转及进程重启保留配置通过 |
|
||||
| 2026-11-14 账号核验 UI | 真机两次自身名片解码、返回复查、首页导航、按钮触发及成功状态回读通过;中途停止显示取消并保持浩瑞前台,残留分享弹层后直接重试再次通过。记录 `.tmp/account-ui/` |
|
||||
| 截至 2026-11-14 作者往返与热度优选真机 | 用户已开启浩瑞无障碍;原视频真实采集、指标、作者往返与草稿整链路本轮仍未执行 |
|
||||
| 2026-11-14 信用分与启动停止 | 修复整页“处罚”关键词误拒绝后,实际读到 100 分;启动时两次一致,检查途中停止后未拉起调度器。保留旧 UNREADABLE 兼容语义,不计为 M6 完整账号健康通过 |
|
||||
| 2026-11-14 作者往返与热度优选 | 点赞 0 候选拒绝、作者主页粉丝读取与返回、合格链接、5 条优选及优胜者解析/模型改写/下载已有真机记录;粉丝/时间门槛单独收紧待补 |
|
||||
| 2026-11-14 旧草稿 | 旧代码在声明弹层未关闭时将 8 秒超时误报为成功,不计验收通过。手动选择实际选项后观察到明确“保存草稿成功”。新增声明与回执保护代码已构建,因 ADB 掉线尚未装机复测,草稿箱回读和待核对处置仍待补 |
|
||||
| 纯手机四来源、图文发布、跨平台视频 | 配置与本地框架已接入,实际采集及新发布器待实现,未执行真实来源或发布测试 |
|
||||
|
||||
## 一 设备准备
|
||||
@@ -44,6 +46,18 @@ $adbPath = 'D:\env\android-sdk\platform-tools\adb.exe'
|
||||
& $adbPath shell am broadcast -a com.haorui.app.ACTION_TEST_CREDIT
|
||||
```
|
||||
|
||||
自有素材草稿回归走广播(debug APK;activity intent 在 vivo 真机投递不可靠,勿用 am start 传 cmd):
|
||||
|
||||
```powershell
|
||||
# 只接受下载目录中的 haorui-draft-regression.mp4(scripts/create-draft-fixture.ps1 生成后 push);
|
||||
# 强制草稿与单车道,不启动采集、互动或正式发布;成功路径会删除本地夹具并自动核销待核对记录。
|
||||
& $adbPath shell am broadcast -a com.haorui.app.ACTION_TEST_DRAFT --es fixturePath /storage/emulated/0/Android/data/com.haorui.app/files/videos/videos/haorui-draft-regression.mp4
|
||||
# 不支持声明(如“内容为原创”)应在 PREPARE 暂停并保留素材,不写待核对
|
||||
& $adbPath shell am broadcast -a com.haorui.app.ACTION_TEST_DRAFT_INVALID --es fixturePath /storage/emulated/0/Android/data/com.haorui.app/files/videos/videos/haorui-draft-regression.mp4
|
||||
```
|
||||
|
||||
⚠️ 点击红线(2026-11-14 事故):PAUSED/中断会把头条发布编辑器留在前台,右下红色「发布」按钮恰在常用导航坐标 (972,2159)。任何 `input tap` 前必须先 `uiautomator dump`/screencap 核对当前界面,用节点 bounds 求中心;测试收尾先 `input keyevent KEYCODE_HOME` 离开编辑器再导航。误发布过的测试内容立即从作品管理删除。
|
||||
|
||||
仅在需要专项互动测试时发送 ACTION_TEST_INTERACT,它会执行实际互动,不属于只读探测。正式模式使用 ACTION_SET_PUBLISH,不能在普通回归步骤中默认执行。
|
||||
|
||||
vivo 重装后若节点根持续为空,先在系统设置关闭再开启浩瑞无障碍。不要用 force-stop 作为恢复办法;ADB 重置所有无障碍服务会影响其他应用,不作为默认操作。
|
||||
@@ -95,9 +109,9 @@ powershell -File scripts\regress-stats.ps1 .tmp\regression.txt
|
||||
|
||||
## 五 记录格式
|
||||
|
||||
本轮记录(2026-11-14):`561baee` 之上的未提交工作树;vivo V1981A / Android 12,头条 18.3.0。应用及测试 APK 已安装;运行隔离库与账号读取验收。用户已手动开启浩瑞无障碍,instrumentation 后仅重绑该已启用服务,原打卡助手服务保持原值。旧视频草稿、新模块关闭,没有启动真实采集、互动或发布,没有执行手动清空缓存/去重。跨日首启曾触发旧信用分检查并读取失败,该旧门控不计为新增健康检查通过。
|
||||
本轮记录(2026-11-14):基线 main `db850a7`,本轮改动未提交;vivo V1981A / Android 12,头条 18.3.0。信用分修复 APK 已安装并验证,新增草稿保护 APK 因 ADB 掉线待安装。前轮 19 项隔离 SQLite 和账号读取记录保留,本轮未改库模式。浩瑞及原打卡助手的启用状态保留,未授予新无障碍权限。旧视频保持草稿,新模块关闭;本轮执行真实候选采集、一次模型标题改写及下载,没有执行互动或公开发布,没有手动清空缓存/去重。
|
||||
|
||||
结果:JVM `88 / 0 失败 / 0 错误`,SQLite `19 / 0 失败`。全套构建日志 `.tmp/account-qr-build.log`,最终导航修复、APK 离线构建与 JVM 复查 `.tmp/account-navigation-build.log`,SQLite `.tmp/account-session-sqlite.log`。新增覆盖预占提交后取消、点击许可提交后取消、旧回调不归还后续前台、重复派发只点一次、同名不同账号与不合格 URL 拒绝。最终账号运行日志 `.tmp/budget-evidence/account-final-runtime.log` 记录 09:28:55 停止、09:29:18 重试核验通过;取消及成功回读截图在 `.tmp/account-ui/`,发布计数为 0。前轮基础 UI 在 `.tmp/continuation-ui/`。旧流程指标/作者往返与整机停止、不同账号及页面样本、混合正式发布/M6 强回执和所有新来源端到端仍未验收。
|
||||
结果:JVM `107 / 0 失败 / 0 错误`;前轮 SQLite `19 / 0 失败`。本轮构建日志 `.tmp/m0-regression/credit-fix-build.log`、`draft-fix-build.log`,最终复查 `.tmp/m0-regression/draft-final-build.log`;M0 实际运行日志、声明弹层误报证据和手动保存的明确提示均在 `.tmp/m0-regression/`。旧处理计数出现 1,不能将此解释为公开发布 1 条。新草稿路径需使用自有素材验证明确回执、停止和待核对保护;未知结果不得重新点击或删除 `files/pending-drafts/` 对应素材。旧草稿箱持久化核对、粉丝/时间阈值、恢复链、不同账号、M6 强回执及所有新来源端到端仍未验收。前轮账号与基础 UI 记录分别位于 `.tmp/account-ui/`、`.tmp/continuation-ui/`。
|
||||
|
||||
仅保留最近一轮有效结果:日期、提交版本/工作树、设备与 App 版本、运行模式、用例结果、日志位置、失败原因及未验收项。历史逐秒日志不追加到文档。
|
||||
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
# 浩瑞开发计划
|
||||
|
||||
更新:2026-11-14。基线:main 的 561baee;M1 与接续开发仍位于未提交工作树。本文维护实施顺序、交付物与验收门槛;详细规则见[纯手机设计](跨平台自动发布设计.md),实际完成情况见[开发进度](开发进度.md)。
|
||||
更新:2026-11-14。当前基线:main 的 db850a7,前轮 M1 已由用户提交;本轮信用分与草稿修复位于未提交工作树。本文维护实施顺序、交付物与验收门槛;详细规则见[纯手机设计](跨平台自动发布设计.md),实际完成情况见[开发进度](开发进度.md)。
|
||||
|
||||
## 目标与当前起点
|
||||
|
||||
@@ -70,6 +70,6 @@ M4 与 M5 在 M1~M3 通过后可分别推进,最终在 M6 联合验收。微
|
||||
|
||||
## 下一步执行
|
||||
|
||||
1. 补 M0 的旧采集、指标、作者往返与停止恢复草稿回归,记录无障碍启用状态和首批来源版本。
|
||||
1. 继续 M0 草稿修复版真机验收:信用分、指标拒绝、作者往返及优选后的解析/改写/下载已有本轮记录;旧草稿超时误报成功已修复但尚未装机复测。先验证声明回读、明确草稿回执和未知素材保护,再补粉丝/时间阈值与恢复链。当前 ADB 连接断开。
|
||||
2. 完成 M1 的不同账号/异常页面、旧流程草稿、在途服务重连与前台切换验收。本轮单账号名片读取、首页导航、中途停止和带残留弹层重试已通过。复用已有账号读取器、LegacyPublishSession 和共享事务,不重复搭计数器;提交前后实际账号、成品关联与强回执由 M6 完成,混合正式入口继续暂停。88 项 JVM、19 项隔离 SQLite 回归不能替代剩余整机验收。
|
||||
3. 通过上述门槛后推进 M2 知乎详情、真实时间、原链接及返回路径,再做小红书;来源保持独立能力门控。实际完成情况持续写入开发进度,不提前把设计或模拟状态写成已实现。
|
||||
|
||||
+17
-10
@@ -1,6 +1,6 @@
|
||||
# 项目状态与开发入口
|
||||
|
||||
更新:2026-11-14。本轮接入 M1 账号读取器、只读核验入口及旧发布器共享提交会话,88 项 JVM、19 项隔离 SQLite 测试通过。API 30+ 自身名片二维码读取、首页导航、中途停止及残留弹层后的重试已通过真机验证。M1 尚未整体验收,M0 旧流程待回归,M2 目前仅取证;混合正式发布继续等待 M6 的健康与作品回执核对。
|
||||
更新:2026-11-14。本轮继续 M0 回归,修复信用分因“处罚中心”标题而被整页否决的问题,真机已读到 100 分并完成启动二次确认及检查途中停止。草稿保护版已完成真机复测:OCR 回执判定经三种行合并形态实测收敛为“非汉字承接”规则,testDraft 全链路(有效声明→回读→单次保存→明确回执→草稿箱持久化)与 testDraftInvalid(不支持声明暂停)均通过,未知结果保护有三次真机证据。109 项 JVM 测试通过;19 项 SQLite 为前轮有效结果。复测期间发生一起误公开发布事故(导航盲点坐标误触「发布」),两条测试视频已删除、作品数恢复 24,过程见“本轮验证与交付物”。M0/M1 遗留兼容与异常场景仍待验收,混合正式发布继续等待 M6。
|
||||
|
||||
## 文档导航
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
| 能力 | 状态与证据 |
|
||||
|---|---|
|
||||
| 原头条视频采集、解析、标题改写、下载和发布 | 已实现;2026-10-29、10-30 有历史真机回归记录 |
|
||||
| 既有信用分、配额、休息与恢复 | 原有能力保留;本轮修改了前台入场、停止取消和导航失效检查,尚需整体真机回归 |
|
||||
| 点赞、作者粉丝、发布时间筛选和候选优选 | 代码及原有 16 项策略单测通过;尚未完成本轮真实采集/发布回归 |
|
||||
| 既有信用分、配额、休息与恢复 | 信用分改为核对处罚中心页面、信用分/账号状态标签及分数所在列,拒绝无关数值;真机 100 分、连续两次确认及启动检查途中停止通过。旧 OCR 失败兼容语义保留,完整恢复链仍待验收 |
|
||||
| 点赞、作者粉丝、发布时间筛选和候选优选 | 原 16 项策略单测保留;真机拒绝点赞 0 的候选,完成作者粉丝读取和返回,5 条考察后只将优胜者送入解析、改写及下载。粉丝/时间阈值单独收紧及异常样本仍待补 |
|
||||
| 百度采集 | 有配置和界面,服务未接独立百度采集器,不计为已跑通来源 |
|
||||
| 手机界面 | Compose 已接入首页/热点/任务/互动/我的及来源、筛选、自动化设置;基础五 tab、分类和配置持久化已有真机记录。本轮在无障碍连接页新增“核验头条账号”及真实状态回读;旧功能行为仍需单独回归 |
|
||||
| 分类与作品形式 | 已实现 18 分类多选,不限社会类;图文/视频分别开关。配置持久化、JSON 与扁平导入导出、边界归一化有单测;新功能默认关闭、DRY_RUN |
|
||||
@@ -27,23 +27,28 @@
|
||||
| 统一前台协调 | ForegroundCoordinator 已接入旧步骤、信用分及恢复链;加入停止代际、在途票据和手势取消收尾。纯策略测试通过,来源切换及停止的整机行为待验收 |
|
||||
| 持久化启停 | CrossRunLifecycle 已接入用户启停、模块开关、服务接管/解绑/销毁。停止立即撤回内存许可,事务串行保存;只有最新启动事务完成才公开数据库代际。8 项竞态/故障单测及隔离库接线测试通过;已观察到空闲服务重绑及核验状态失效,旧流程在途重连仍待验收 |
|
||||
| 共享账户额度 | 共享事务与旧快照已实现;本轮新增 LegacyPublishSession,并接入旧 PublishMachine 的准备、指纹、单次点击、取消与未知回执分支。事务已提交而返回值因取消丢失时,按预生成 ID 定位;库中已领取点击许可的预占不释放。M6 强回执未接通,混合正式入口继续关闭;草稿及无共享历史的旧独立模式保留 |
|
||||
| 旧视频草稿 | **新版真机复测通过(2026-11-14 17:31)**:有效声明→回读→单次保存→明确“保存草稿成功”回执→草稿箱持久化(`浩瑞草稿回归 1004aef5`);testDraftInvalid 在 PREPARE 即暂停“不受当前版本支持”;未知结果保护有 14:38/16:11/16:41 三次证据(暂停、素材保留、`files/pending-drafts/` 记录保留,核对后清除)。OCR 回执判定为“非汉字承接”规则(⊙ 图标实测被误读为 0/O/。 并与位置卡片文本同行合并)。待核对处置界面仍未实现(现为人工核对后清理记录);旧配置“内容为原创”仍待用户改选 |
|
||||
| 稳定账号读取 | 18.3.0 自身主页、名片及二维码读取代码已实现,唯一数字 user_id 哈希为账户键;两次独立取证并复核自身资料,昵称和分享追踪字段不作为身份。只读核验不绑定预算,不授予后续运行发布许可 |
|
||||
| 知乎、小红书、微博、抖音采集 | 注册与版本门控已实现,实际采集器尚未实现;知乎/小红书仅取证,所有来源执行能力仍禁用 |
|
||||
| 头条图文与跨平台视频 | 事实补全、自动文章生成、文章编辑器、媒体许可及新发布上下文尚未实现;AUTO 未开放,没有执行真实跨平台发布 |
|
||||
|
||||
## 本轮验证与交付物
|
||||
|
||||
- `:app:testDebugUnitTest`:88 项,0 失败、0 错误(原视频 16、配置 11、来源门控 4、任务策略 18、旧额度快照 7、前台票据 8、运行生命周期 8、账号策略 3、剪贴板请求 3、旧提交会话 10)。新增覆盖同名不同身份、迟到 UI 回调、独占入场、事务返回丢失、停止/取消与不重复点击。
|
||||
- `:app:assembleDebug` 与 `:app:assembleDebugAndroidTest`:构建成功;全套日志 `.tmp/account-qr-build.log`,最终导航修复和 88 项 JVM 离线复查见 `.tmp/account-navigation-build.log`。新增 ZXing core 3.5.3 从官方 Maven 下载到 D:/env,LICENSE/NOTICE 随 APK 分发;Kotlin 改为 Gradle JVM 内编译,避免独立守护进程回落 C 盘。
|
||||
- 应用 APK:`app/build/outputs/apk/debug/app-debug.apk`,2026-11-14 最终导航与二维码版本已覆盖安装,SHA-256 为 `6FDB63295473C130C08ACB950C6C5170C92830C73FC4AD9E93FEAEF5D0AF07FC`;测试 APK 已安装。
|
||||
- `:app:testDebugUnitTest`:107 项,0 失败、0 错误。前轮 88 项之外,本轮新增信用分卡片解析 10 项、草稿回执 4 项、持久化草稿意图 5 项,覆盖无关数字、低分、冲突值、过期/错标题回执、写入失败、重启保护与重复意图拒绝。
|
||||
- `:app:assembleDebug`:本轮构建成功,日志 `.tmp/m0-regression/credit-fix-build.log`、`draft-fix-build.log`;最终复查记录 `.tmp/m0-regression/draft-final-build.log`。前轮测试 APK 构建及 19 项 SQLite 记录仍有效,本轮未改 SQLite 模式或重跑该组。
|
||||
- 应用 APK:`app/build/outputs/apk/debug/app-debug.apk`,最终 SHA-256 为 `311D0E6BCC42A049739AE859A6E993F4547196CD5D3CE2B61F3CFEA1CDE08D61`(含 OCR“非汉字承接”规则与草稿回归广播入口;装机后已完成 17:31 真机复测)。此前 10:26/15:02 等中间构建哈希不再有效,以本行为准。
|
||||
- 真机 SQLite:输出 `SQLite tests: 19, failures: 0`,记录 `.tmp/account-session-sqlite.log`。本轮新增在真实库中模拟预占提交后及点击许可提交后的协程取消:前者按同一 ID 明确释放未点击预占,后者跨重启继续保留 UNKNOWN、额度和素材。使用独立缓存测试库。
|
||||
- 前轮基础 UI 验收仍有效,记录在 `.tmp/continuation-ui/`,没有重复执行整套验收。本轮账号链接/名片取证、运行诊断和新增入口结果保存于 `.tmp/budget-evidence/`。
|
||||
- 真机已完成两次独立名片解码及返回复查,调试入口与“无障碍连接→核验头条账号”按钮均返回成功,界面回读当前显示名。从头条首页进入自身资料页通过;修复启动后过早判断分享弹层已关闭的问题。最终核验途中于 09:28:55 停止,界面显示“账号核验已取消”,无迟到成功或跳页;从按钮重试后于 09:29:18 再次核验通过。日志 `.tmp/budget-evidence/account-final-runtime.log`,截图 `.tmp/account-ui/account-ui-stopped.png`、`account-ui-retried.png`;当天发布计数仍为 0。
|
||||
- `uiautomator dump` 与 instrumentation 可能触发服务重连,临时核验状态会失效;自动化运行中使用文件日志和 `screencap` 观察,避免调试工具自身中断会话。此行为不能当成身份缓存恢复或授权依据。
|
||||
- 本轮 M0 记录在 `.tmp/m0-regression/`:`credit-baseline.log`/`credit-baseline.png` 为原信用分误拒绝;`credit-fixed-runtime.log` 为 100 分读数,`credit-stop-runtime.log` 为导航途中停止,`legacy-flow-runtime.log` 为二次确认及旧采集链路。`draft-after.png/xml` 证明旧发布器误报后仍停在声明弹层;手动关闭六层弹层、选择“内容为转载”并保存后,`draft-saved-manual.png` 记录真实“保存草稿成功”提示。未点击正式发布。旧流程处理计数出现 1,该值对应本轮测试处理,不能解释为公开发布 1 条。
|
||||
|
||||
本轮手机:vivo V1981A / Android 12,头条 18.3.0。自身主页复制链接和名片二维码均已留存,观察到 `profile.zjurl.cn/rogue/ugc/profile` 的数字 `user_id`;原始身份及分享追踪值不写入文档和日志。知乎 11.15.0、小红书 9.54.0、抖音 39.8.0,微博未安装;其来源能力与前轮相同,尚未放行。
|
||||
|
||||
本轮用户已手动开启浩瑞无障碍;原 `com.example.clockin` 服务保留。隔离 instrumentation 结束后系统曾将浩瑞列为断开/崩溃服务,仅重新绑定已启用的浩瑞,并核对原启用列表完整恢复。未代用户登录、修改资料、发送分享、点赞、评论、关注或发布;旧视频保持草稿,新模块关闭。自身资料页及名片仅供只读取证。
|
||||
本轮用户已手动开启浩瑞无障碍;原 `com.example.clockin` 服务保留。隔离 instrumentation 结束后系统曾将浩瑞列为断开/崩溃服务,仅重新绑定已启用的浩瑞,并核对原启用列表完整恢复。未代用户登录、修改资料、发送分享、点赞、评论、关注或公开发布;旧视频保持草稿,新模块关闭。M0 回归执行了采集、一次模型标题改写及下载,并手动核实了一条测试草稿;当前配置“内容为原创”需改选当前版本支持的声明,代码不自动替换用户声明。
|
||||
|
||||
- **草稿保护版真机复测(17:2x–17:31,第 5 轮 APK)**:`ACTION_TEST_DRAFT` 广播触发,`浩瑞草稿回归 1004aef5` 全链路通过——标题回读一致、声明“内容无需标注”回读通过、单次点击存草稿、`草稿回执候选:城市广场。保存草稿成功达广场IMAX店` 被“非汉字承接”规则认出,`收到明确的保存草稿成功提示`→`草稿保存已确认`→待核对记录自动核销→本地素材按设计删除;草稿箱核对 `1004aef5` 在列(证据 `.tmp/m0-regression/draft-box-1004aef5-proof.png`,日志 `testdraft-run4.log`)。16:02 的 testDraftInvalid 在 PREPARE 暂停“作品声明「内容为原创」不受当前版本支持”,未写待核对、未动素材。装机复测最初两轮(14:38 见 `0保存草稿成功`、16:11 见 `宁兴·城O保存草稿成功鄞州万达广场小`)先后暴露“前缀容错不足”“整行匹配过严”两类 OCR 差异,`DraftReceiptPolicy` 由此收敛为现行规则,109 项 JVM 测试通过(含三种合并形态用例)。
|
||||
- **⚠️ 误公开发布事故(已处置)**:PAUSED 会把头条发布编辑器留在前台,红色「发布」按钮恰在 (972,2159);我在草稿箱导航时使用硬编码坐标未先核对屏幕,两次盲点分别把 `063f1df0`、`a12c4807` 误发为公开作品(16:25 有“发布成功,分享给朋友一起看”弹层与作品列表 `063f1df0·2展现0播放` 为证)。用户已手动删除两条,作品数 25→24、列表无浩瑞条目(17:2x 核对),当日公开发布基线恢复为 0。教训:**任何 adb 点击前必须 dump/截图核对当前界面并用节点 bounds 求坐标**;测试收尾先 HOME 离开编辑器再导航。另记:本机 vivo 每次 ADB 装机可能把浩瑞无障碍踢出启用列表(15:52 一次、force-stop 一次被踢,16:25/16:39/17:30 未被踢),恢复需手动开“浩瑞自动发布”;activity intent 投递在本机极不可靠(多次“delivered”仍丢包),**调试命令一律用广播入口**。
|
||||
|
||||
## 固定决策
|
||||
|
||||
@@ -58,9 +63,9 @@
|
||||
|
||||
## 下一对话继续入口
|
||||
|
||||
1. 工作目录仍为 `D:/headlineScript`,本地 `HEAD` 保持 main 的 `561baee`;M1 首批代码及本次接续修改均未提交。远端 `origin/main` 上轮(11-13)核对为同一提交,本轮未拉取远端。继续前先看 `git log -1`、`git status`,按需核对远端,保留未提交修改,勿 reset、clean 或重复创建已有模块。
|
||||
1. 工作目录仍为 `D:/headlineScript`。本轮开始时用户已将前轮 M1 工作提交为 main 的 `db850a7`,工作树干净;本轮信用分与草稿修复尚未提交,未拉取远端。继续前先看 `git log -1`、`git status`,保留未提交修改,勿 reset、clean 或重复创建已有模块。
|
||||
2. 基础 UI 已验收,最新 APK 已装机;记录见本文验证结果与回归清单。后续仅在界面有改动或出现新问题时重做相关场景,不用点击旧视频正式启动来替代 UI 检查。
|
||||
3. 补 M0 的旧采集与启停回归,特别是指标限制、作者主页往返、停止时信用分导航/手势收尾及恢复链。本轮跨日首启的旧信用分检查未从浩瑞首页读到分数,后续头条导航失败并按旧规则放行;需补稳定启动入口与导航回归,不把该结果计为新增健康检查通过。单测及数据库测试不能替代上述行为验收。
|
||||
3. **草稿保护版复测已完成(见“本轮验证与交付物”)**,有效声明→回读→单次保存→明确回执、不支持声明暂停、未知结果保护、草稿箱持久化四项均通过,不必重复。调试入口改用广播(activity intent 在本机不可靠):`adb shell am broadcast -a com.haorui.app.ACTION_TEST_DRAFT --es fixturePath <下载目录>/haorui-draft-regression.mp4`(无效声明用 `ACTION_TEST_DRAFT_INVALID`),仍强制草稿与单车道。成功路径会删除本地夹具,重测前用 `scripts/create-draft-fixture.ps1` 重建并 push 回下载目录。随后补粉丝/时间硬阈值和恢复链回归;M6 账号健康不能只依赖旧信用分兼容门控。**导航红线**:PAUSED 会留下头条编辑器(「发布」按钮在右下),任何 adb 点击前先 dump/截图核屏、用节点 bounds 求坐标,收尾先 HOME。
|
||||
4. 继续 M1 的整机兼容回归与不同账号/异常页面验收;本轮已通过单账号读取、首页导航、停止和残留弹层后重试,不必无改动重复这些场景。复用 `account/ToutiaoAccountReader`、`publish/LegacyPublishSession` 和现有事务,勿另建计数器或用昵称/缓存绑定替代现场身份。当前混合正式入口仍关闭;M6 需要接通健康检查、编辑器最终账号/成品关联和明确作品回执,再开放正式路径。旧共享分支不复用分享面板/草稿超时成功判据。
|
||||
5. 再推进 M2:优先知乎热榜、具体详情身份/真实发布时间、分享原链接与返回路径,再做小红书。知乎回答时间不能当问题时间;小红书混淆资源 ID 不能直接当稳定选择器。未核验字段保留未知,来源版本/能力未通过不得放行。
|
||||
6. 来源稳定后按[开发计划](开发计划.md)推进分类优选、事实补全、图文、视频及新发布协调;整体验收前不开放 AUTO。
|
||||
@@ -80,7 +85,7 @@
|
||||
| automation/HaoRuiAccessibilityService.kt、scheduler/RecoveryChain.kt、ocr/CreditGateRunner.kt、automation/GestureRunner.kt | 本轮改动的真实接线、停止取消与恢复边界,必须补整机回归 |
|
||||
| crossplatform/source/SourceRegistry.kt | 四来源包名及版本/能力门控;目前 verifiedVersions、capabilities 均为空,不能仅因已安装就设为可执行 |
|
||||
|
||||
测试位于 `app/src/test/java/com/haorui/app/crossplatform/`、`app/src/androidTest/java/com/haorui/app/crossplatform/`。最终构建与 JVM 日志 `.tmp/account-navigation-build.log`,JVM 结果为 `app/build/test-results/testDebugUnitTest/`,真机库结果为 `.tmp/account-session-sqlite.log`。测试库与正式任务库隔离,不把测试记录导入真实队列。
|
||||
测试位于 `app/src/test/java/com/haorui/app/` 和 `app/src/androidTest/java/com/haorui/app/crossplatform/`。本轮最终构建与 JVM 日志 `.tmp/m0-regression/draft-final-build.log`,JVM 结果为 `app/build/test-results/testDebugUnitTest/`,前轮真机库结果为 `.tmp/account-session-sqlite.log`。测试库与正式任务库隔离,不把测试记录导入真实队列。
|
||||
|
||||
构建命令(PowerShell;有新增代码时再运行,不必因换对话重复所有检查):
|
||||
|
||||
@@ -95,6 +100,8 @@ gradle --offline :app:testDebugUnitTest :app:assembleDebug :app:assembleDebugAnd
|
||||
|
||||
| 日期 | 事项 | 验证范围 |
|
||||
|---|---|---|
|
||||
| 2026-11-14 | 草稿保护版装机复测:OCR 回执“非汉字承接”规则、广播调试入口、误公开发布事故处置 | testDraft/testDraftInvalid 真机通过、草稿箱持久化、109 项 JVM 通过;误发布的两条测试视频已删除并复核,M0/M1 遗留场景仍待验收 |
|
||||
| 2026-11-14 | M0 信用分卡片解析、旧采集回归、声明回读和草稿明确回执、点击前日志与未知素材保护 | 107 项 JVM 通过;信用分及旧采集至下载已真机验证,新草稿修复版因 ADB 离线待安装,M0 未整体验收 |
|
||||
| 2026-11-14 | 接入账号读取、只读入口、旧发布器共享提交会话与取消故障恢复,手动缓存清理保护未知素材;新增本机名片二维码读取 | 88 项 JVM、19 项真机 SQLite 全通过,最终 APK 已安装;实际账号与新增 UI 验收结果见本文,混合正式发布继续等待 M6 |
|
||||
| 2026-11-13 | M1 共享额度事务、旧额度快照与幂等恢复、v1→v2 保留升级、未知文件保护及混合正式入口暂停保护 | 71 项 JVM、17 项真机 SQLite 全通过,最终应用及测试 APK 已安装;稳定账号核验与旧发布器日志调用仍待接通 |
|
||||
| 2026-11-13 | 接通服务启停、模块开关与任务库运行代际;旧任务暂停、队列与素材代际检查、服务接管及调度器启停同步 | 59 项 JVM 与 9 项真机 SQLite 测试通过;基础 UI、跨页保存、旋转及进程重启通过;已安装新版 APK,真实服务重连和旧链路仍待验收 |
|
||||
|
||||
@@ -76,12 +76,16 @@ AndroidManifest.xml 管理组件、权限及包可见性;res/xml/file_paths.xm
|
||||
|
||||
- 发布器使用 video/mp4 的 ACTION_SEND 和 FileProvider URI,不是通用图文发布器。
|
||||
- 标题写入后回读;声明与封面按当前配置处理。每次只受理一条任务,忙时保留已准备成品,不能重跑整个下载管线。
|
||||
- 声明必须属于当前 `AppConfig.DECLARATIONS`。不支持的旧配置暂停并提示重新选择,不自动替换声明;弹层仅打开一次,选择后要求弹层消失且 `id/jm2` 回读一致,未通过不发送提交动作。
|
||||
- 草稿点击前由 `PendingDraftStore` 写入 `files/pending-drafts/`,记录尝试、路径、标题及声明。先排除旧提示,再仅派发一次保存;`DraftReceiptPolicy` 要求本次 8 秒窗口内的明确“保存草稿成功”,截图前后核对当前编辑器标题及声明。按钮“存草稿”、分享面板和超时均不算回执。
|
||||
- 草稿结果未知或点击中断时保留文件并暂停;下载缓存及失败删除路径均检查持久化保护,损坏日志使清理停止。重启后存在待核对草稿时拒绝自动运行,处置界面与草稿箱自动核对尚未实现。明确确认后的草稿沿用旧处理额度与休息语义,日志区分“草稿保存已确认”和正式“发布成功”。
|
||||
- QuotaManager 的非分时段日限额为 min(publishTotal, completionLimit),分时段使用对应配置;两种模式均检查休息。
|
||||
- 配额快照包含时段计数、剩余休息与最近重置点;启动恢复完成后才武装每日重置,日期使用 todayKey 的同一语义。
|
||||
- FrontStageGuard 是纯读状态表;ForegroundCoordinator 负责原子入场与票据归还。新功能关闭时保留旧步骤的入场方式,启用后每次只允许一个前台操作,来源仅在完整安全边界入场。
|
||||
- 用户停止应清除启动意愿,恢复链不能复活主动停止的任务;协程取消异常必须重抛。
|
||||
- 节点等待、网络与 OCR 都要有超时和有限重试。跨线程状态使用合适的同步;节点副本按现有 API 生命周期管理。
|
||||
- OCR 截图先隐藏悬浮窗,结束后在 finally 恢复。剪贴板读取应保持前台与候选代际匹配。
|
||||
- 信用分不再解析整页任意数字:`CreditScoreParser` 核对上方“账号处罚中心”、信用分及账号状态两列,只解析信用分标签下方的完整 0~100 分数。处罚标题和历史扣分不否决整页;未知、冲突、位置不符返回空,日志不再输出账户页 OCR 全文。原旧门控 UNREADABLE 兼容行为保留,M6 另行验收。
|
||||
- 文件日志不可阻塞状态机;诊断优先看应用文件日志与心跳,不仅依赖 logcat。
|
||||
|
||||
## 本地任务运行生命周期
|
||||
|
||||
@@ -60,6 +60,10 @@ Lynx 页面可能持续更新,uiautomator dump 失败不能直接证明页面
|
||||
|
||||
草稿没有提示、页面消失或分享面板出现,不足以证明新任务已正式发布。视频简介、署名、多项声明和文章编辑器需要新增真机取证。
|
||||
|
||||
2026-11-14 旧视频回归补充:声明选项为 `com.ss.android.article.news:id/fci`,当前配置“内容为原创”不在实际选项中;选择后的摘要为 `id/jm2`。“内容无需标注”会清空摘要,必须确认该选项已点击且弹层已消失才接受空摘要。标题输入键盘可能遮挡下方选项,选择声明及提交前通过可见输入法窗口判断并收起键盘。重复打开会叠加六层声明弹层,背景仍暴露标题与存草稿按钮,不能用背景节点判断可提交。手动选择“内容为转载”并点击存草稿,观察到短暂的“保存草稿成功”提示,页面仍留在编辑器;该提示未出现在常规节点树中,新增代码使用截图 OCR 及当前标题/声明核对,最终自动化结果见回归清单。
|
||||
|
||||
信用分页面已观察到“账号处罚中心”、左侧“信用分 / 100分”和右侧“账号状态 / 正常”。整页含“处罚”不应直接否决当前信用分;新增解析按页面和卡片位置判断,10 项相关 JVM 测试及本机 100 分读取已通过。
|
||||
|
||||
## 新来源适配记录要求
|
||||
|
||||
### 2026-11-14 头条账户页与名片取证
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
param([string]$EncoderPath = 'D:\env\ffmpeg-tools\ffmpeg.exe')
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
. (Join-Path $PSScriptRoot 'env.ps1')
|
||||
if (-not (Test-Path -LiteralPath $EncoderPath -PathType Leaf)) {
|
||||
throw 'FFmpeg is required in D:\env for this development-only fixture.'
|
||||
}
|
||||
$fixtureDirectory = Join-Path (Split-Path -Parent $PSScriptRoot) '.tmp\m0-regression'
|
||||
New-Item -ItemType Directory -Path $fixtureDirectory -Force | Out-Null
|
||||
$fixturePath = Join-Path $fixtureDirectory 'haorui-draft-regression.mp4'
|
||||
& $EncoderPath -nostdin -y -hide_banner -loglevel error -f lavfi -i 'testsrc2=size=640x360:rate=25' `
|
||||
-f lavfi -i 'anullsrc=r=44100:cl=stereo' -t 22 -c:v libx264 -preset veryfast -crf 30 `
|
||||
-pix_fmt yuv420p -c:a aac -b:a 64k -shortest -movflags +faststart $fixturePath
|
||||
if ($LASTEXITCODE -ne 0) { throw "Draft fixture generation failed: $LASTEXITCODE" }
|
||||
Get-Item -LiteralPath $fixturePath | Select-Object FullName, Length
|
||||
Reference in New Issue
Block a user