feat:
1.完成头条账号二维码核验,修复首页导航及停止后重试。 2.补齐共享提交会话、取消恢复和未知素材保护。 3.88 项 JVM、19 项 SQLite 测试通过;真机账号核验、停止、重试通过。
This commit is contained in:
@@ -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]
|
||||||
@@ -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("关闭") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -91,7 +91,8 @@ class ScreenCapturer(private val service: AccessibilityService) {
|
|||||||
} else {
|
} else {
|
||||||
RunLogger.w(TAG, "截屏回调成功但位图转换失败(wrapHardwareBuffer/copy)")
|
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) {
|
override fun onFailure(errorCode: Int) {
|
||||||
|
|||||||
@@ -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"))
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user