Compare commits
49
Commits
b5ac4ca4d4
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cb861b5aaf | ||
|
|
df2c44d199 | ||
|
|
8844c9b63a | ||
|
|
020873fc40 | ||
|
|
e6ef534f7b | ||
|
|
7eaccb6696 | ||
|
|
26271c3690 | ||
|
|
f61d65c526 | ||
|
|
a2359b9dd2 | ||
|
|
8bea19d334 | ||
|
|
ebbed5ed82 | ||
|
|
8963fa5c6d | ||
|
|
d55d41f610 | ||
|
|
a2de5d2275 | ||
|
|
4ac4b7dd78 | ||
|
|
eb6f8e2398 | ||
|
|
455c20fb93 | ||
|
|
b23b53d417 | ||
|
|
6a59ae5e99 | ||
|
|
ff69bfb82c | ||
|
|
f68536009d | ||
|
|
32acd3fa4b | ||
|
|
528675d3b5 | ||
|
|
9a078a24d1 | ||
|
|
39913c6453 | ||
|
|
0306ff8bf7 | ||
|
|
c147f8e805 | ||
|
|
bcca999646 | ||
|
|
966ecd9196 | ||
|
|
682856c961 | ||
|
|
856951f296 | ||
|
|
95b7666270 | ||
|
|
4d87bbd0fb | ||
|
|
70f47cc25d | ||
|
|
294a80716a | ||
|
|
d42a1ad05f | ||
|
|
70367207c5 | ||
|
|
82bcb49b70 | ||
|
|
4cc0b3a9da | ||
|
|
1a7390568d | ||
|
|
b6fa23a3f2 | ||
|
|
282a5b4407 | ||
|
|
6b34421f5e | ||
|
|
4dc5ae7235 | ||
|
|
e3b4bf8dd7 | ||
|
|
62c1720b70 | ||
|
|
cc0f621c53 | ||
|
|
1dae7453be | ||
|
|
db850a78c8 |
@@ -0,0 +1,39 @@
|
||||
package com.haorui.app.crossplatform
|
||||
|
||||
import android.app.Instrumentation
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import com.haorui.app.MainActivity
|
||||
import java.net.URI
|
||||
import java.security.MessageDigest
|
||||
|
||||
/** 仅测试 APK:读取刚复制的头条主页链接形态,不授权账号或操作发布。 */
|
||||
internal object AccountClipboardProbe {
|
||||
fun read(instrumentation: Instrumentation): String = with(instrumentation) {
|
||||
val activity = startActivitySync(Intent(targetContext, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
waitForIdleSync()
|
||||
val deadline = System.nanoTime() + 5_000_000_000L
|
||||
while (!activity.hasWindowFocus() && System.nanoTime() < deadline) Thread.sleep(50)
|
||||
Thread.sleep(900)
|
||||
var raw = ""
|
||||
var metadata = ""
|
||||
runOnMainSync {
|
||||
val manager = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
val clip = manager.primaryClip
|
||||
raw = clip?.takeIf { it.itemCount == 1 }?.getItemAt(0)?.coerceToText(activity)?.toString().orEmpty()
|
||||
metadata = "focus=${activity.hasWindowFocus()}, items=${clip?.itemCount}, length=${raw.length}"
|
||||
}
|
||||
val candidate = Regex("https?://[^\\s]+", RegexOption.IGNORE_CASE).find(raw)?.value ?: return "No profile link ($metadata)"
|
||||
val uri = URI(candidate)
|
||||
val parts = uri.path.split('/').filter { it.isNotBlank() }
|
||||
val shape = parts.joinToString("/") { if (it.length > 16 || it.all(Char::isDigit)) "<id:${it.length}>" else it }
|
||||
val query = uri.rawQuery.orEmpty().split('&').filter { it.isNotBlank() }.joinToString(",") { part ->
|
||||
val p = part.split('=', limit = 2)
|
||||
"${p[0]}:${p.getOrElse(1) { "" }.length}:${p.getOrElse(1) { "" }.all(Char::isDigit)}"
|
||||
}
|
||||
if (uri.host !in setOf("www.toutiao.com", "m.toutiao.com", "toutiao.com")) return "Profile host: ${uri.scheme}://${uri.host}/$shape; query shape=$query"
|
||||
val digest = MessageDigest.getInstance("SHA-256").digest(uri.path.toByteArray()).joinToString("") { "%02x".format(it) }
|
||||
"Profile link: ${uri.scheme}://${uri.host}/$shape; pathSha256=$digest"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
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,
|
||||
com.haorui.app.crossplatform.media.MediaCases::class.java,
|
||||
com.haorui.app.crossplatform.publish.PublishCoordinatorCases::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,443 @@
|
||||
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)
|
||||
}
|
||||
|
||||
@Test fun deleteTaskRemovesLedgerAttemptsAssetsAndTaskRow() = runBlocking {
|
||||
val generation = store.beginRun()
|
||||
val attempt = intent("gone", generation)
|
||||
val asset = CrossAsset("media", "gone", 1, "/deletable.mp4", "b".repeat(64), 42, "test-rights")
|
||||
assertTrue(store.saveAsset(asset, generation))
|
||||
assertEquals(1L, store.budgetUsage("test-account", "2026-11-13").totalUsed)
|
||||
val deleted = store.deleteTask("gone")!!
|
||||
assertEquals("gone", deleted.task.id)
|
||||
assertEquals(setOf("/deletable.mp4"), deleted.mediaPaths.toSet())
|
||||
assertNull(store.find("gone"))
|
||||
assertTrue(store.attempts("gone").isEmpty())
|
||||
assertTrue(store.assets("gone").isEmpty())
|
||||
// 台账随任务删除:额度占用清零,等同释放。
|
||||
assertEquals(0L, store.budgetUsage("test-account", "2026-11-13").totalUsed)
|
||||
assertNull(store.deleteTask("gone"))
|
||||
val db = database()
|
||||
assertEquals(0, db.rawQuery("SELECT COUNT(*) FROM quota_ledger", null).use { it.moveToFirst(); it.getInt(0) })
|
||||
assertEquals(0, db.rawQuery("SELECT COUNT(*) FROM attempts", null).use { it.moveToFirst(); it.getInt(0) })
|
||||
assertEquals(0, db.rawQuery("SELECT COUNT(*) FROM assets", null).use { it.moveToFirst(); it.getInt(0) })
|
||||
assertEquals(0, db.rawQuery("SELECT COUNT(*) FROM tasks", null).use { it.moveToFirst(); it.getInt(0) })
|
||||
}
|
||||
|
||||
@Test fun deletingTerminalTaskAlsoReleasesItsLedger() = runBlocking {
|
||||
val generation = store.beginRun()
|
||||
val attempt = intent("done", generation)
|
||||
assertTrue(store.claimSubmissionClick(attempt.id, generation, budget()))
|
||||
assertTrue(store.recordReceipt(attempt.id, "verified-receipt", snapshot().period))
|
||||
assertEquals(CrossTaskState.SUBMITTED, store.find("done")!!.state)
|
||||
assertEquals(1L, store.budgetUsage("test-account", "2026-11-13").totalUsed)
|
||||
store.deleteTask("done")
|
||||
assertNull(store.find("done"))
|
||||
assertEquals(0L, 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"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.haorui.app.crossplatform.media
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Assume
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* M5 媒体层真机验收用例(挂 StoreInstrumentation 的 JUnitCore 分发):
|
||||
* JVM 跑不了的 Android 媒体框架路径——SourceMediaProvider 导入、
|
||||
* VideoFileValidator 轨道/时长探测、管线成功路径。
|
||||
* 入口:`adb shell am instrument -w com.haorui.app.test/com.haorui.app.crossplatform.StoreInstrumentation`
|
||||
* 测试素材:/sdcard/Download/haorui-draft-regression.mp4(create-draft-fixture.ps1 产出后 push;
|
||||
* 缺失时 Assume 跳过,不影响其余用例)。
|
||||
*/
|
||||
class MediaCases {
|
||||
|
||||
private val context: Context get() = com.haorui.app.crossplatform.StoreInstrumentation.appContext
|
||||
|
||||
private fun fixtureFile(): File {
|
||||
val fixture = File("/sdcard/Download/haorui-draft-regression.mp4")
|
||||
Assume.assumeTrue("测试夹具不在 /sdcard/Download(push 后重跑)", fixture.exists() && fixture.length() > 0)
|
||||
return fixture
|
||||
}
|
||||
|
||||
private fun fixtureUri(): Uri {
|
||||
// 夹具由 adb push 到 App 自有外部私有目录(分区存储下 App 读公共下载目录 EACCES、
|
||||
// MediaStore 他人条目同样无权——自有外部私有目录无需权限,导入管线语义等价);
|
||||
// push 命令:adb push .tmp/m0-regression/haorui-draft-regression.mp4 \
|
||||
// /sdcard/Android/data/com.haorui.app/files/m5-fixture.mp4
|
||||
val staged = File(context.getExternalFilesDir(null), "m5-fixture.mp4")
|
||||
Assume.assumeTrue(
|
||||
"夹具未 push 到外部私有目录(见类注释 push 命令)",
|
||||
staged.exists() && staged.length() > 0,
|
||||
)
|
||||
return Uri.fromFile(staged)
|
||||
}
|
||||
|
||||
@Test fun importThenValidateOwnVideo() {
|
||||
val provider = SourceMediaProvider(context)
|
||||
val result = provider.importFrom(fixtureUri(), "haorui-m5-test")
|
||||
assertTrue("导入应成功: $result", result is SourceMediaProvider.Result.Imported)
|
||||
val imported = result as SourceMediaProvider.Result.Imported
|
||||
// 落盘在私有目录内
|
||||
assertTrue(provider.isManagedPath(imported.localPath))
|
||||
assertTrue(imported.sizeBytes > 0)
|
||||
assertEquals(64, imported.sha256.length)
|
||||
// 内容去重
|
||||
assertTrue(provider.isDuplicate(imported.sha256))
|
||||
// 硬校验(真机媒体框架):22 秒自有视频应通过
|
||||
val report = VideoFileValidator.validate(imported.localPath)
|
||||
assertTrue("校验应通过: ${report.reason}", report.ok)
|
||||
assertTrue(report.durationMs in 20_000..4_000_000)
|
||||
// 管线成功路径:自有许可 → 成品(无署名段)
|
||||
val store = MediaLicenseStore()
|
||||
store.registerOwn("test-account")
|
||||
val pipeline = CrossVideoPipeline(store)
|
||||
val outcome = pipeline.prepare(
|
||||
imported.localPath, "test-account", null,
|
||||
"M5 真机验收简介第一行", null, System.currentTimeMillis(),
|
||||
)
|
||||
assertNotNull("管线应通过: ${outcome.reason}", outcome.prepared)
|
||||
assertEquals("M5 真机验收简介第一行", outcome.prepared!!.caption)
|
||||
assertFalse(outcome.prepared.needsAttribution)
|
||||
// 桥接(假发布器):草稿车道递交成功
|
||||
var submittedAuto: Boolean? = null
|
||||
val bridge = VideoTaskBridge({ _, _, auto, _ -> submittedAuto = auto; true })
|
||||
val bridged = bridge.bridge(outcome.prepared)
|
||||
assertTrue(bridged is VideoTaskBridge.Result.Submitted)
|
||||
assertEquals(false, submittedAuto)
|
||||
// 收尾:清理测试导入文件
|
||||
File(imported.localPath).delete()
|
||||
}
|
||||
|
||||
@Test fun validateRejectsCorruptedFile() {
|
||||
// 损坏文件:媒体解析失败 → 不放行
|
||||
val bad = File(context.filesDir, "crossplatform/video/corrupt-test.mp4")
|
||||
bad.parentFile?.mkdirs()
|
||||
bad.writeBytes(ByteArray(64) { 'f'.code.toByte() })
|
||||
try {
|
||||
val report = VideoFileValidator.validate(bad.absolutePath)
|
||||
assertFalse("损坏文件应拒绝", report.ok)
|
||||
} finally {
|
||||
bad.delete()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun importRejectsUnsupportedScheme() {
|
||||
val provider = SourceMediaProvider(context)
|
||||
val result = provider.importFrom(Uri.parse("https://example.com/video.mp4"))
|
||||
assertTrue(result is SourceMediaProvider.Result.Rejected)
|
||||
assertTrue((result as SourceMediaProvider.Result.Rejected).reason.contains("协议"))
|
||||
}
|
||||
}
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
package com.haorui.app.crossplatform.publish
|
||||
|
||||
import com.haorui.app.crossplatform.data.CrossPublishTaskStore
|
||||
import com.haorui.app.crossplatform.model.CrossContentKind
|
||||
import com.haorui.app.crossplatform.model.CrossPublishTask
|
||||
import com.haorui.app.crossplatform.model.CrossTaskState
|
||||
import com.haorui.app.ocr.CreditGateRunner
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.cancel
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
* 发布协调器真库验收(挂 StoreInstrumentation 分发;隔离临时库,不碰真实任务库):
|
||||
* 门控拦截不领取、领取→落库→执行→归账顺序、三种执行结果的库内终态、
|
||||
* 执行异常归 UNKNOWN(不盲重发)。JVM 侧语义已由门控单测覆盖。
|
||||
*/
|
||||
class PublishCoordinatorCases {
|
||||
|
||||
/** 隔离库(StoreTransactionTest 同款:反射构造 + 临时目录 + scope/helper 清理)。 */
|
||||
private fun isolatedStore(): Pair<CrossPublishTaskStore, File> {
|
||||
val dir = File(com.haorui.app.crossplatform.StoreInstrumentation.appContext.cacheDir, "coord-${UUID.randomUUID()}").apply { mkdirs() }
|
||||
val isolated = object : android.content.ContextWrapper(com.haorui.app.crossplatform.StoreInstrumentation.appContext) {
|
||||
override fun getApplicationContext(): android.content.ContextWrapper = this
|
||||
override fun getDatabasePath(name: String) = File(dir, name)
|
||||
}
|
||||
val store = CrossPublishTaskStore::class.java
|
||||
.getDeclaredConstructor(android.content.Context::class.java).apply { isAccessible = true }
|
||||
.newInstance(isolated)
|
||||
return store to dir
|
||||
}
|
||||
|
||||
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 android.database.sqlite.SQLiteOpenHelper).close()
|
||||
}
|
||||
|
||||
private val task = CrossPublishTask(
|
||||
id = "ct1", accountKey = "acc", eventId = "e1", contentKind = CrossContentKind.VIDEO,
|
||||
title = "协调器验收任务", sourcePlatform = "weibo", sourceUrl = "https://weibo.com/x",
|
||||
)
|
||||
|
||||
/** 入队并沿状态机合法路径推到 READY。
|
||||
* ⚠️ transition 到 PREPARED/READY 有 preparationRejection 硬校验(发布时间/有效期/
|
||||
* 指纹/证据/媒体/许可)——测试任务必须像真任务;runGeneration 必须与 beginRun 代际一致。 */
|
||||
private suspend fun enqueueReady(store: CrossPublishTaskStore, generation: Long) {
|
||||
val now = System.currentTimeMillis()
|
||||
val valid = task.copy(
|
||||
runGeneration = generation,
|
||||
publishedAtMs = now - 3_600_000L, // 1 小时前发布(有效且非未来)
|
||||
expiresAtMs = now + 86_400_000L, // 24 小时后过期
|
||||
payloadHash = "ab".repeat(32), // 64 位十六进制指纹
|
||||
evidenceJson = """{"titleSeed":"协调器验收","sourceText":"测试事实依据文本,长度满足回溯要求。"}""",
|
||||
mediaPath = "/data/media/ct1.mp4",
|
||||
rightsRef = "own-test",
|
||||
bodyText = "视频任务无正文要求,占位满足非空校验。",
|
||||
)
|
||||
store.enqueue(valid)
|
||||
store.transition(valid.id, CrossTaskState.DISCOVERED, CrossTaskState.FILTERED, generation, "协调器验收·筛选")
|
||||
store.transition(valid.id, CrossTaskState.FILTERED, CrossTaskState.PREPARED, generation, "协调器验收·准备")
|
||||
store.transition(valid.id, CrossTaskState.PREPARED, CrossTaskState.READY, generation, "协调器验收·就绪")
|
||||
}
|
||||
|
||||
@Test fun gateHoldSkipsClaiming() {
|
||||
val (store, dir) = isolatedStore()
|
||||
try {
|
||||
val generation = kotlinx.coroutines.runBlocking { store.beginRun() }
|
||||
kotlinx.coroutines.runBlocking { enqueueReady(store, generation) }
|
||||
val gate = AccountPublishGate(null, 90, { CreditGateRunner.Verdict.UNREADABLE })
|
||||
val coordinator = PublishCoordinator(store, gate)
|
||||
var executed = false
|
||||
val outcome = kotlinx.coroutines.runBlocking {
|
||||
coordinator.dispatchOnce("acc", generation) {
|
||||
executed = true
|
||||
PublishCoordinator.ExecutionResult.Confirmed("不应执行")
|
||||
}
|
||||
}
|
||||
assertTrue(outcome is PublishCoordinator.Outcome.Idle)
|
||||
assertFalse(executed)
|
||||
// 任务未被领取(仍 READY)
|
||||
assertEquals(CrossTaskState.READY, kotlinx.coroutines.runBlocking { store.find(task.id) }!!.state)
|
||||
} finally { closeStore(store); dir.deleteRecursively() }
|
||||
}
|
||||
|
||||
@Test fun confirmedFlowReachesDraftSaved() {
|
||||
val (store, dir) = isolatedStore()
|
||||
try {
|
||||
val generation = kotlinx.coroutines.runBlocking { store.beginRun() }
|
||||
kotlinx.coroutines.runBlocking { enqueueReady(store, generation) }
|
||||
val gate = AccountPublishGate(null, 90, { CreditGateRunner.Verdict.PASS })
|
||||
val coordinator = PublishCoordinator(store, gate)
|
||||
val outcome = kotlinx.coroutines.runBlocking {
|
||||
coordinator.dispatchOnce("acc", generation) {
|
||||
PublishCoordinator.ExecutionResult.Confirmed("草稿回执明确 9f625776")
|
||||
}
|
||||
}
|
||||
assertTrue(outcome is PublishCoordinator.Outcome.Dispatched)
|
||||
val result = (outcome as PublishCoordinator.Outcome.Dispatched).result
|
||||
assertTrue(result is PublishCoordinator.ExecutionResult.Confirmed)
|
||||
// 库内终态:任务 DRAFT_SAVED、attempt CONFIRMED
|
||||
assertEquals(CrossTaskState.DRAFT_SAVED, kotlinx.coroutines.runBlocking { store.find(task.id) }!!.state)
|
||||
val attempts = kotlinx.coroutines.runBlocking { store.attempts(task.id) }
|
||||
assertEquals(1, attempts.size)
|
||||
assertEquals(com.haorui.app.crossplatform.model.CrossAttemptState.CONFIRMED, attempts[0].state)
|
||||
} finally { closeStore(store); dir.deleteRecursively() }
|
||||
}
|
||||
|
||||
@Test fun unknownFlowPreservesForReview() {
|
||||
val (store, dir) = isolatedStore()
|
||||
try {
|
||||
val generation = kotlinx.coroutines.runBlocking { store.beginRun() }
|
||||
kotlinx.coroutines.runBlocking { enqueueReady(store, generation) }
|
||||
val coordinator = PublishCoordinator(store, AccountPublishGate(null, 90, { CreditGateRunner.Verdict.PASS }))
|
||||
val outcome = kotlinx.coroutines.runBlocking {
|
||||
coordinator.dispatchOnce("acc", generation) {
|
||||
PublishCoordinator.ExecutionResult.Unknown("回执超时待核对")
|
||||
}
|
||||
}
|
||||
assertTrue(outcome is PublishCoordinator.Outcome.Dispatched)
|
||||
assertEquals(CrossTaskState.RESULT_UNKNOWN, kotlinx.coroutines.runBlocking { store.find(task.id) }!!.state)
|
||||
val attempts = kotlinx.coroutines.runBlocking { store.attempts(task.id) }
|
||||
assertEquals(com.haorui.app.crossplatform.model.CrossAttemptState.UNKNOWN, attempts[0].state)
|
||||
} finally { closeStore(store); dir.deleteRecursively() }
|
||||
}
|
||||
|
||||
@Test fun notSubmittedFlowPausesForReview() {
|
||||
// store 语义(CrossPublishTaskStore.confirmNotSubmitted):明确未提交 → PAUSED
|
||||
//("已核对未提交,需重新检查页面和成品"——保守复核后 resumeTask 重入,非直接 SKIPPED)
|
||||
val (store, dir) = isolatedStore()
|
||||
try {
|
||||
val generation = kotlinx.coroutines.runBlocking { store.beginRun() }
|
||||
kotlinx.coroutines.runBlocking { enqueueReady(store, generation) }
|
||||
val coordinator = PublishCoordinator(store, AccountPublishGate(null, 90, { CreditGateRunner.Verdict.PASS }))
|
||||
val outcome = kotlinx.coroutines.runBlocking {
|
||||
coordinator.dispatchOnce("acc", generation) {
|
||||
PublishCoordinator.ExecutionResult.NotSubmitted("执行方明确未提交")
|
||||
}
|
||||
}
|
||||
assertTrue(outcome is PublishCoordinator.Outcome.Dispatched)
|
||||
assertEquals(CrossTaskState.PAUSED, kotlinx.coroutines.runBlocking { store.find(task.id) }!!.state)
|
||||
} finally { closeStore(store); dir.deleteRecursively() }
|
||||
}
|
||||
|
||||
@Test fun executorExceptionBecomesUnknown() {
|
||||
val (store, dir) = isolatedStore()
|
||||
try {
|
||||
val generation = kotlinx.coroutines.runBlocking { store.beginRun() }
|
||||
kotlinx.coroutines.runBlocking { enqueueReady(store, generation) }
|
||||
val coordinator = PublishCoordinator(store, AccountPublishGate(null, 90, { CreditGateRunner.Verdict.PASS }))
|
||||
val outcome = kotlinx.coroutines.runBlocking {
|
||||
coordinator.dispatchOnce("acc", generation) { throw IllegalStateException("机器崩溃") }
|
||||
}
|
||||
assertTrue(outcome is PublishCoordinator.Outcome.Dispatched)
|
||||
assertEquals(CrossTaskState.RESULT_UNKNOWN, kotlinx.coroutines.runBlocking { store.find(task.id) }!!.state)
|
||||
} finally { closeStore(store); dir.deleteRecursively() }
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,8 @@
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||
<!-- MediaProjection 独立截屏通道(抖音防缓存绕行,2026-11-17) -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
|
||||
<!-- Android 13+ 通知运行时权限(仅影响通知可见性,不影响前台化生效) -->
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
|
||||
@@ -61,12 +63,30 @@
|
||||
<service
|
||||
android:name=".automation.KeepAliveService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="dataSync|specialUse">
|
||||
android:foregroundServiceType="dataSync|specialUse|mediaProjection">
|
||||
<property
|
||||
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
||||
android:value="Accessibility automation keep-alive: prevents the process from being frozen by Android Cached App Freezer while driving the target app in background." />
|
||||
</service>
|
||||
|
||||
<!--
|
||||
调试输入法(M4,2026-11-15):文章编辑器标题/正文为自绘(无 EditText 节点),
|
||||
ACTION_SET_TEXT 不可用——focus + 本输入法 commitText 直写(绕开拼音 IME 挂起丢字)。
|
||||
仅调试/自动化使用:adb shell ime enable/set 切换,用毕恢复原输入法。
|
||||
-->
|
||||
<service
|
||||
android:name=".automation.ime.HaoRuiDebugIme"
|
||||
android:exported="true"
|
||||
android:label="浩瑞调试输入法"
|
||||
android:permission="android.permission.BIND_INPUT_METHOD">
|
||||
<intent-filter>
|
||||
<action android:name="android.view.InputMethod" />
|
||||
</intent-filter>
|
||||
<meta-data
|
||||
android:name="android.view.im"
|
||||
android:resource="@xml/method" />
|
||||
</service>
|
||||
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.fileprovider"
|
||||
|
||||
+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]
|
||||
@@ -27,6 +27,31 @@ import kotlinx.coroutines.launch
|
||||
*/
|
||||
class MainActivity : ComponentActivity() {
|
||||
|
||||
/** MediaProjection 授权弹窗回调(抖音独立截屏通道,2026-11-17):结果直接交给 ProjectionHolder */
|
||||
private val projectionLauncher =
|
||||
registerForActivityResult(androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult()) { result ->
|
||||
val data = result.data
|
||||
if (result.resultCode == android.app.Activity.RESULT_OK && data != null) {
|
||||
val ok = com.haorui.app.ocr.ProjectionHolder.createProjection(applicationContext, result.resultCode, data)
|
||||
com.haorui.app.automation.RunLogger.i(
|
||||
"UI",
|
||||
"MediaProjection 授权回调:用户同意,创建投影 ok=$ok",
|
||||
)
|
||||
com.haorui.app.automation.RunState.projectionReady = ok
|
||||
} else {
|
||||
com.haorui.app.automation.RunLogger.w("UI", "MediaProjection 授权回调:用户拒绝或数据为空")
|
||||
com.haorui.app.automation.RunState.projectionReady = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 发起屏幕采集授权(由 UI 页调用) */
|
||||
fun requestProjection() {
|
||||
val manager = getSystemService(android.content.Context.MEDIA_PROJECTION_SERVICE)
|
||||
as android.media.projection.MediaProjectionManager
|
||||
runCatching { projectionLauncher.launch(manager.createScreenCaptureIntent()) }
|
||||
.onFailure { com.haorui.app.automation.RunLogger.w("UI", "发起投影授权失败: ${it.message}") }
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge()
|
||||
super.onCreate(savedInstanceState)
|
||||
@@ -150,6 +175,11 @@ class MainActivity : ComponentActivity() {
|
||||
val accepted = com.haorui.app.automation.HaoRuiAccessibilityService.instance?.verifyAccountSandbox() == true
|
||||
com.haorui.app.automation.RunLogger.i("UI", "账号只读核验受理=$accepted")
|
||||
}
|
||||
"testDraft", "testDraftInvalid" -> if (applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE != 0) {
|
||||
val accepted = com.haorui.app.automation.HaoRuiAccessibilityService.instance?.startDraftSandbox(
|
||||
intent.getStringExtra("fixturePath").orEmpty(), intent.getStringExtra("cmd") == "testDraftInvalid") == true
|
||||
com.haorui.app.automation.RunLogger.i("UI", "自有素材草稿回归受理=$accepted")
|
||||
}
|
||||
// ── 装机调试命令(adb 触发,验证 F1/F2 用)─────────
|
||||
"testCredit" -> {
|
||||
val svc = com.haorui.app.automation.HaoRuiAccessibilityService.instance
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -89,16 +89,21 @@ class KeepAliveService : Service() {
|
||||
this,
|
||||
NOTIFICATION_ID,
|
||||
notification,
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE,
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE or
|
||||
// 投影活跃期间必须带 mediaProjection 类型(MediaProjection 要求宿主前台服务含此类型),
|
||||
// 未授权投影时带该类型合法(类型只是声明,无需运行时校验)
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION,
|
||||
)
|
||||
// API 29~33:必须用 dataSync。specialUse 是 API 34 才引入的常量,
|
||||
// 在旧机型上是未知类型位,vivo 等厂商的省电策略会因此不认这个前台服务,
|
||||
// 导致进程照样被 Cached App Freezer 冻结(2026-10-29 真机实测踩过)。
|
||||
// mediaProjection 类型叠加(API 29+ 常量):投影活跃期间系统校验宿主服务类型。
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> ServiceCompat.startForeground(
|
||||
this,
|
||||
NOTIFICATION_ID,
|
||||
notification,
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC,
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC or
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION,
|
||||
)
|
||||
// API 28 及以下:两参重载即可
|
||||
else -> startForeground(NOTIFICATION_ID, notification)
|
||||
|
||||
@@ -22,4 +22,8 @@ object RunState {
|
||||
/** 最近一次识别到的信用分(同 CreditGateRunner.lastScore;null = 未读到) */
|
||||
@Volatile
|
||||
var creditScore: Int? = null
|
||||
|
||||
/** MediaProjection 投影是否就绪(抖音独立截屏通道;授权后为 true,投影停止/进程重启后为 false) */
|
||||
@Volatile
|
||||
var projectionReady: Boolean = false
|
||||
}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.haorui.app.automation.ime
|
||||
|
||||
import android.inputmethodservice.InputMethodService
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.View
|
||||
import android.widget.TextView
|
||||
import com.haorui.app.crossplatform.publish.ArticleTextPolicy
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
/**
|
||||
* 浩瑞调试输入法(M4,2026-11-15):文章编辑器自绘控件无 EditText 节点,
|
||||
* ACTION_SET_TEXT 不可用 → focus + 本输入法 [android.view.inputmethod.InputConnection.commitText]
|
||||
* 直写通道。commitText 无拼音组合过程,绕开 adb 输入/拼音 IME 的挂起丢字问题。
|
||||
*
|
||||
* 设计要点:
|
||||
* - **无键盘 UI**:[onCreateInputView] 只显示提示条,不提供按键——这是自动化直写通道,
|
||||
* 手动打字请切回原输入法(`adb shell ime set <原IME>`);
|
||||
* - **进程内桥**:与无障碍服务同进程,[commit] 直取实例;InputConnection 有线程亲和性,
|
||||
* 统一抛主 Looper 执行,调用方有界等待(防 IME 线程卡死拖垮自动化);
|
||||
* - **分批提交**:超长正文按 [ArticleTextPolicy.commitBatches] 切批(单次 commitText 过长
|
||||
* 可能被编辑器截断),批间 flush;
|
||||
* - 调试入口:广播 `com.haorui.app.ACTION_IME_COMMIT --es text <文本>`(由无障碍服务转接)。
|
||||
*
|
||||
* 使用约束:仅调试/自动化使用;切换命令
|
||||
* `adb shell ime enable com.haorui.app/.automation.ime.HaoRuiDebugIme`、
|
||||
* `adb shell ime set com.haorui.app/.automation.ime.HaoRuiDebugIme`,用毕恢复原输入法。
|
||||
*/
|
||||
class HaoRuiDebugIme : InputMethodService() {
|
||||
|
||||
companion object {
|
||||
private const val COMMIT_TIMEOUT_SEC = 5L
|
||||
|
||||
@Volatile
|
||||
private var instance: HaoRuiDebugIme? = null
|
||||
|
||||
/** 输入法是否已被系统创建(不代表正持有输入焦点)。 */
|
||||
fun isServiceReady(): Boolean = instance != null
|
||||
|
||||
/**
|
||||
* 向当前焦点控件提交文本(分批)。
|
||||
* @return true=已向 InputConnection 提交;false=输入法未启用/未获焦点/提交线程超时。
|
||||
*/
|
||||
fun commit(text: String): Boolean {
|
||||
val ime = instance ?: return false
|
||||
val done = CountDownLatch(1)
|
||||
val ok = AtomicBoolean(false)
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
ok.set(ime.commitAll(text))
|
||||
done.countDown()
|
||||
}
|
||||
runCatching { done.await(COMMIT_TIMEOUT_SEC, TimeUnit.SECONDS) }
|
||||
return ok.get()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
instance = this
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
if (instance === this) instance = null
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
/** 无键盘 UI:仅提示条(自动化直写通道,不提供按键)。 */
|
||||
override fun onCreateInputView(): View = TextView(this).apply {
|
||||
text = "浩瑞调试输入法(直写通道,无键盘)"
|
||||
textSize = 12f
|
||||
setPadding(24, 12, 24, 12)
|
||||
}
|
||||
|
||||
/** 主 Looper 上执行:InputConnection 非线程安全。 */
|
||||
private fun commitAll(text: String): Boolean {
|
||||
val ic = currentInputConnection ?: return false
|
||||
for (batch in ArticleTextPolicy.commitBatches(text)) {
|
||||
ic.commitText(batch, 1)
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import com.haorui.app.automation.selection.DraftReceiptPolicy
|
||||
|
||||
/**
|
||||
* 视频发布状态机。
|
||||
@@ -43,6 +44,15 @@ class PublishMachine(
|
||||
/** 运行期注入真实配置(服务层配置流调用) */
|
||||
fun updateConfig(cfg: ToutiaoConfig) {
|
||||
this.toutiaoConfig = cfg
|
||||
if (phase == Phase.PAUSED && draftAttemptId == null && declaration != cfg.workDeclaration &&
|
||||
cfg.workDeclaration in com.haorui.app.data.model.AppConfig.DECLARATIONS) {
|
||||
declaration = cfg.workDeclaration
|
||||
declarationOpened = false
|
||||
declarationSelected = false
|
||||
declarationVerified = false
|
||||
declarationOptionRetry = 0
|
||||
go(Phase.PREPARE)
|
||||
}
|
||||
}
|
||||
|
||||
enum class Phase {
|
||||
@@ -64,6 +74,8 @@ class PublishMachine(
|
||||
DONE,
|
||||
/** 失败清理 */
|
||||
FAILED,
|
||||
/** 保留任务和素材,等待核对或修正不支持的声明。 */
|
||||
PAUSED,
|
||||
}
|
||||
|
||||
// ── 任务数据 ──────────────────────────────────────────────
|
||||
@@ -89,6 +101,10 @@ class PublishMachine(
|
||||
|
||||
/** 声明选项查找重试(对照原 500ms 轮询直到选项出现) */
|
||||
private var declarationOptionRetry = 0
|
||||
private var declarationOpened = false
|
||||
private var declarationSelected = false
|
||||
private var declarationVerified = false
|
||||
private var draftAttemptId: String? = null
|
||||
|
||||
/**
|
||||
* 提交一个发布任务。
|
||||
@@ -123,6 +139,10 @@ class PublishMachine(
|
||||
this.nullRootStreak = 0
|
||||
this.titleFocused = false
|
||||
this.declarationOptionRetry = 0
|
||||
this.declarationOpened = false
|
||||
this.declarationSelected = false
|
||||
this.declarationVerified = false
|
||||
this.draftAttemptId = null
|
||||
go(Phase.PREPARE)
|
||||
log("提交发布任务:${title.take(24)}…")
|
||||
return true
|
||||
@@ -193,9 +213,14 @@ class PublishMachine(
|
||||
Phase.WAIT_RECEIPT -> doWaitReceipt()
|
||||
Phase.DONE -> doDone()
|
||||
Phase.FAILED -> doFailed()
|
||||
Phase.PAUSED -> Unit
|
||||
}
|
||||
} catch (cancelled: kotlinx.coroutines.CancellationException) {
|
||||
withContext(NonCancellable) { runCatching { sharedSession?.markUnknown("发布步骤已取消,等待作品核对") } }
|
||||
if (draftAttemptId != null) {
|
||||
go(Phase.PAUSED)
|
||||
TaskStatusBus.status("草稿提交已中断,结果待核对,素材已保留")
|
||||
}
|
||||
throw cancelled
|
||||
} finally {
|
||||
busy.set(false)
|
||||
@@ -206,6 +231,10 @@ class PublishMachine(
|
||||
|
||||
private suspend fun doPrepare() {
|
||||
if (pauseForSharedAccount()) return
|
||||
if (declaration !in com.haorui.app.data.model.AppConfig.DECLARATIONS) {
|
||||
pauseForReview("作品声明「$declaration」不受当前版本支持,请在采集设置重新选择")
|
||||
return
|
||||
}
|
||||
if (title.isBlank() || mediaUri.isBlank()) {
|
||||
log("标题或素材为空,任务作废")
|
||||
go(Phase.FAILED)
|
||||
@@ -367,6 +396,8 @@ class PublishMachine(
|
||||
|
||||
val ok = svc.gestures.setText(titleBox, title)
|
||||
runCatching { titleBox.recycle() }
|
||||
|
||||
|
||||
if (!ok) {
|
||||
log("标题写入失败,重试 $titleRetry/3")
|
||||
titleRetry++
|
||||
@@ -488,124 +519,202 @@ class PublishMachine(
|
||||
log("退出子页面达最大层数,可能未回到发布页")
|
||||
}
|
||||
|
||||
/** 作品声明 */
|
||||
/** 只打开一次声明弹层;选项消失且编辑器回读一致后才能提交。 */
|
||||
private suspend fun doSetDeclaration() {
|
||||
if (!declarationOpened && dismissKeyboardIfVisible()) return
|
||||
val root = rootOrNull() ?: return
|
||||
val decl = NodeLocator.byText(root, ToutiaoSelectors.TXT_DECLARATION)
|
||||
if (decl == null) {
|
||||
// 对照原 C1:「未找到作品声明入口;未发布」—— 不带声明发布会合规风险
|
||||
log("未找到作品声明入口;未发布(对照原 C1)")
|
||||
TaskStatusBus.status("未找到作品声明入口;未发布")
|
||||
go(Phase.FAILED)
|
||||
return
|
||||
}
|
||||
svc.gestures.tapNode(decl)
|
||||
runCatching { decl.recycle() }
|
||||
TaskStatusBus.status("已打开作品声明,准备选择:$declaration")
|
||||
delay(700)
|
||||
|
||||
// 对照原:轮询等声明选项出现(u1(f0)),未出现 500ms 重试
|
||||
val opt = NodeLocator.byText(svc.root(), declaration)
|
||||
if (opt == null) {
|
||||
declarationOptionRetry++
|
||||
if (declarationOptionRetry < DECLARATION_OPTION_RETRY_LIMIT) {
|
||||
log("作品声明选项未出现,等待 $declarationOptionRetry/$DECLARATION_OPTION_RETRY_LIMIT")
|
||||
delay(500)
|
||||
try {
|
||||
if (declarationOpened && !declarationSheetOpen(root) && declarationReadback(root) == declaration) {
|
||||
declarationVerified = true
|
||||
log("作品声明回读通过:$declaration")
|
||||
go(Phase.CONFIRM)
|
||||
return
|
||||
}
|
||||
log("未找到作品声明选项「$declaration」(对照原等待超时仍进入下一步,由回读兜底)")
|
||||
declarationOptionRetry = 0
|
||||
go(Phase.CONFIRM)
|
||||
if (!declarationOpened) {
|
||||
val entry = NodeLocator.byText(root, ToutiaoSelectors.TXT_DECLARATION)
|
||||
if (entry == null) { pauseForReview("未找到作品声明入口,任务已暂停"); return }
|
||||
val opened = try { svc.gestures.tapNodeOnce(entry) } finally { entry.recycle() }
|
||||
if (!opened) { pauseForReview("作品声明入口点击结果不明,任务已暂停"); return }
|
||||
declarationOpened = true
|
||||
delay(500)
|
||||
}
|
||||
} finally { root.recycle() }
|
||||
val sheet = rootOrNull() ?: return
|
||||
val options = sheet.findAccessibilityNodeInfosByViewId("${com.haorui.app.automation.Targets.TOUTIAO_PKG}:id/fci").orEmpty()
|
||||
try {
|
||||
val option = options.firstOrNull { it.isVisibleToUser && it.text?.toString() == declaration }
|
||||
if (option != null && svc.gestures.tapNodeOnce(option)) declarationSelected = true
|
||||
if (++declarationOptionRetry >= DECLARATION_OPTION_RETRY_LIMIT) {
|
||||
pauseForReview("作品声明未能完成回读,任务已暂停,素材保留")
|
||||
}
|
||||
} finally { options.forEach { it.recycle() }; sheet.recycle() }
|
||||
}
|
||||
|
||||
private fun declarationReadback(root: AccessibilityNodeInfo): String? {
|
||||
val node = NodeLocator.byId(root, "${com.haorui.app.automation.Targets.TOUTIAO_PKG}:id/jm2")
|
||||
val summary = try { node?.text?.toString() } finally { node?.recycle() }
|
||||
return DraftReceiptPolicy.declarationReadback(declaration, declarationSelected, declarationSheetOpen(root), summary)
|
||||
}
|
||||
|
||||
private suspend fun dismissKeyboardIfVisible(): Boolean {
|
||||
if (svc.currentPackage() != com.haorui.app.automation.Targets.TOUTIAO_PKG) return false
|
||||
val visible = svc.windows.any { window ->
|
||||
window.type == android.view.accessibility.AccessibilityWindowInfo.TYPE_INPUT_METHOD &&
|
||||
!android.graphics.Rect().also(window::getBoundsInScreen).isEmpty
|
||||
}
|
||||
if (!visible) return false
|
||||
svc.gestures.back()
|
||||
delay(300)
|
||||
log("已收起标题输入键盘,等待编辑器布局稳定")
|
||||
return true
|
||||
}
|
||||
|
||||
private fun declarationSheetOpen(root: AccessibilityNodeInfo): Boolean {
|
||||
val nodes = root.findAccessibilityNodeInfosByViewId("${com.haorui.app.automation.Targets.TOUTIAO_PKG}:id/fci").orEmpty()
|
||||
return try { nodes.any { it.isVisibleToUser && it.text?.toString() == "取消" } } finally { nodes.forEach { it.recycle() } }
|
||||
}
|
||||
|
||||
private fun pauseForReview(reason: String) {
|
||||
log(reason)
|
||||
TaskStatusBus.status(reason)
|
||||
go(Phase.PAUSED)
|
||||
svc.stopAutomation()
|
||||
}
|
||||
|
||||
private fun draftEditorMatches(root: AccessibilityNodeInfo): Boolean {
|
||||
if (root.packageName?.toString() != com.haorui.app.automation.Targets.TOUTIAO_PKG || declarationSheetOpen(root)) return false
|
||||
val node = NodeLocator.byId(root, ToutiaoSelectors.ID_PUB_TITLE) ?: return false
|
||||
val matches = try { node.text?.toString() == title } finally { node.recycle() }
|
||||
return matches && declarationReadback(root) == declaration
|
||||
}
|
||||
|
||||
private suspend fun draftReceiptLines(): List<String> {
|
||||
com.haorui.app.overlay.MonitorOverlay.setHidden(true)
|
||||
return try {
|
||||
delay(200)
|
||||
val bitmap = com.haorui.app.ocr.ScreenCapturer(svc).capture() ?: return emptyList()
|
||||
try {
|
||||
val lines = com.haorui.app.ocr.OcrProcessor.recognize(bitmap).flatMap { it.lines }.filter { line ->
|
||||
val box = line.boundingBox
|
||||
box != null && box.centerY() > bitmap.height * 0.35 && box.centerY() < bitmap.height * 0.85 &&
|
||||
box.centerX() > bitmap.width * 0.2 && box.centerX() < bitmap.width * 0.8
|
||||
}.map { it.text }
|
||||
kotlinx.coroutines.currentCoroutineContext().ensureActive()
|
||||
lines.filter { it.contains("保存") && it.contains("草稿") }.forEach { log("草稿回执候选:${it.take(40)}") }
|
||||
lines
|
||||
} finally { bitmap.recycle() }
|
||||
} finally { com.haorui.app.overlay.MonitorOverlay.setHidden(false) }
|
||||
}
|
||||
|
||||
private suspend fun dispatchDraft() {
|
||||
if (draftAttemptId != null) { pauseForReview("草稿已有提交意图,禁止重复点击,等待核对"); return }
|
||||
if (DraftReceiptPolicy.hasSuccess(draftReceiptLines())) {
|
||||
if (++confirmRetry > CONFIRM_MAX_RETRY) pauseForReview("旧草稿提示尚未消失,未发送新草稿")
|
||||
return
|
||||
}
|
||||
declarationOptionRetry = 0
|
||||
val tapped = svc.gestures.tapNode(opt)
|
||||
runCatching { opt.recycle() }
|
||||
if (tapped) {
|
||||
TaskStatusBus.status("已选择作品声明:$declaration;等待回读")
|
||||
log("作品声明已设为「$declaration」")
|
||||
} else {
|
||||
log("作品声明选项 tap 失败,重试一次")
|
||||
val opt2 = NodeLocator.byText(svc.root(), declaration)
|
||||
if (opt2 != null) {
|
||||
svc.gestures.tapNode(opt2)
|
||||
runCatching { opt2.recycle() }
|
||||
TaskStatusBus.status("已选择作品声明:$declaration;等待回读")
|
||||
}
|
||||
}
|
||||
go(Phase.CONFIRM)
|
||||
val fresh = rootOrNull() ?: return
|
||||
try {
|
||||
if (!declarationVerified || !draftEditorMatches(fresh)) { pauseForReview("草稿标题或声明已变化,未发送"); return }
|
||||
val button = NodeLocator.byId(fresh, ToutiaoSelectors.ID_PUB_DRAFT) ?: return
|
||||
try {
|
||||
// M5:跨平台素材(crossplatform/video 目录)用放宽版登记——待核对保护语义一致
|
||||
val id = try {
|
||||
if (videoDownloader?.isCrossPlatformMedia(mediaUri) == true) {
|
||||
videoDownloader.beginDraftCrossPlatform(mediaUri, title, declaration)
|
||||
} else {
|
||||
videoDownloader?.beginDraft(mediaUri, title, declaration)
|
||||
}
|
||||
} catch (failure: Exception) { log("草稿意图保存失败:${failure.javaClass.simpleName}"); null }
|
||||
if (id == null) { pauseForReview("草稿意图无法保存,未点击存草稿"); return }
|
||||
draftAttemptId = id
|
||||
receiptWaitStartMs = SystemClock.elapsedRealtime()
|
||||
kotlinx.coroutines.currentCoroutineContext().ensureActive()
|
||||
if (!svc.gestures.tapNodeOnce(button)) { pauseForReview("草稿点击结果不明,素材保留,等待核对"); return }
|
||||
go(Phase.WAIT_RECEIPT)
|
||||
TaskStatusBus.status("草稿动作已发送,等待当前编辑器的保存成功提示")
|
||||
} finally { button.recycle() }
|
||||
} finally { fresh.recycle() }
|
||||
}
|
||||
|
||||
/** 点发布 / 存草稿 */
|
||||
private suspend fun doConfirm() {
|
||||
if (pauseForSharedAccount()) return
|
||||
if (dismissKeyboardIfVisible()) return
|
||||
val root = rootOrNull() ?: return
|
||||
eligibilityCheck?.invoke()?.let { reason ->
|
||||
log("点击发布前筛选拒绝:$reason")
|
||||
TaskStatusBus.status("发布前复查跳过:$reason")
|
||||
go(Phase.FAILED)
|
||||
return
|
||||
}
|
||||
|
||||
// 兜底:若此刻不在发布页(可能被子页面/异步跳转带走),先退回
|
||||
val titleBox = NodeLocator.byId(root, ToutiaoSelectors.ID_PUB_TITLE)
|
||||
if (titleBox == null) {
|
||||
log("当前不在发布页,尝试退回")
|
||||
ensureBackToPublisher()
|
||||
return
|
||||
}
|
||||
runCatching { titleBox.recycle() }
|
||||
|
||||
val btnId = if (autoPublish) ToutiaoSelectors.ID_PUB_PUBLISH else ToutiaoSelectors.ID_PUB_DRAFT
|
||||
val btn = NodeLocator.byId(root, btnId)
|
||||
?: NodeLocator.byText(root, if (autoPublish) "发布" else "存草稿")
|
||||
|
||||
if (btn == null) {
|
||||
confirmRetry++
|
||||
// 需要真实结构才能校正选择器
|
||||
if (confirmRetry == 1) {
|
||||
log("CONFIRM 节点树诊断 →\n${NodeLocator.dumpTree(root, maxDepth = 12, maxNodes = 150)}")
|
||||
}
|
||||
// ⚠️ 加重试上限:原先无限 delay(800) 重试,真机实测空转 24 次,
|
||||
// 既不放弃也不上报,白白占住状态机。
|
||||
if (confirmRetry > CONFIRM_MAX_RETRY) {
|
||||
log("未找到${if (autoPublish) "发布" else "存草稿"}按钮,重试 $confirmRetry 次后放弃")
|
||||
try {
|
||||
eligibilityCheck?.invoke()?.let { reason ->
|
||||
log("点击发布前筛选拒绝:$reason")
|
||||
TaskStatusBus.status("发布前复查跳过:$reason")
|
||||
go(Phase.FAILED)
|
||||
return
|
||||
}
|
||||
log("未找到${if (autoPublish) "发布" else "存草稿"}按钮,重试 $confirmRetry/$CONFIRM_MAX_RETRY")
|
||||
delay(800)
|
||||
return
|
||||
}
|
||||
val context = sharedSession
|
||||
val tapped = if (context != null) {
|
||||
val titleNode = NodeLocator.byId(root, ToutiaoSelectors.ID_PUB_TITLE)
|
||||
val exactTitle = titleNode?.text?.toString() == title
|
||||
titleNode?.recycle()
|
||||
context.dispatch(payloadFingerprint(), { exactTitle && svc.currentCrossRunGeneration() == context.generation }) {
|
||||
svc.gestures.tapNodeOnce(btn)
|
||||
|
||||
// 兜底:若此刻不在发布页(可能被子页面/异步跳转带走),先退回
|
||||
val titleBox = NodeLocator.byId(root, ToutiaoSelectors.ID_PUB_TITLE)
|
||||
if (titleBox == null) {
|
||||
log("当前不在发布页,尝试退回")
|
||||
ensureBackToPublisher()
|
||||
return
|
||||
}
|
||||
} else svc.gestures.tapNode(btn)
|
||||
runCatching { btn.recycle() }
|
||||
if (context != null && !tapped) {
|
||||
TaskStatusBus.status(context.reason)
|
||||
go(Phase.FAILED)
|
||||
return
|
||||
}
|
||||
// ⚠️ 二轮审计:tap 失败不能进 WAIT_RECEIPT 干等 30 分钟超时
|
||||
if (!tapped) {
|
||||
log("发布按钮 tap 失败,重试")
|
||||
confirmRetry++
|
||||
if (confirmRetry > CONFIRM_MAX_RETRY) {
|
||||
go(Phase.FAILED)
|
||||
} else {
|
||||
runCatching { titleBox.recycle() }
|
||||
|
||||
if (!declarationVerified || declarationSheetOpen(root) || declarationReadback(root) != declaration) {
|
||||
pauseForReview("作品声明未通过回读,未发送提交动作")
|
||||
return
|
||||
}
|
||||
if (!autoPublish) { dispatchDraft(); return }
|
||||
|
||||
val btnId = if (autoPublish) ToutiaoSelectors.ID_PUB_PUBLISH else ToutiaoSelectors.ID_PUB_DRAFT
|
||||
val btn = NodeLocator.byId(root, btnId)
|
||||
?: NodeLocator.byText(root, if (autoPublish) "发布" else "存草稿")
|
||||
|
||||
if (btn == null) {
|
||||
confirmRetry++
|
||||
// 需要真实结构才能校正选择器
|
||||
if (confirmRetry == 1) {
|
||||
log("CONFIRM 节点树诊断 →\n${NodeLocator.dumpTree(root, maxDepth = 12, maxNodes = 150)}")
|
||||
}
|
||||
// ⚠️ 加重试上限:原先无限 delay(800) 重试,真机实测空转 24 次,
|
||||
// 既不放弃也不上报,白白占住状态机。
|
||||
if (confirmRetry > CONFIRM_MAX_RETRY) {
|
||||
log("未找到${if (autoPublish) "发布" else "存草稿"}按钮,重试 $confirmRetry 次后放弃")
|
||||
go(Phase.FAILED)
|
||||
return
|
||||
}
|
||||
log("未找到${if (autoPublish) "发布" else "存草稿"}按钮,重试 $confirmRetry/$CONFIRM_MAX_RETRY")
|
||||
delay(800)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
receiptWaitStartMs = SystemClock.elapsedRealtime()
|
||||
TaskStatusBus.status("发布动作已发送,等待头条成功回执;确认后才删除素材")
|
||||
go(Phase.WAIT_RECEIPT)
|
||||
val context = sharedSession
|
||||
val tapped = if (context != null) {
|
||||
val titleNode = NodeLocator.byId(root, ToutiaoSelectors.ID_PUB_TITLE)
|
||||
val exactTitle = titleNode?.text?.toString() == title
|
||||
titleNode?.recycle()
|
||||
context.dispatch(payloadFingerprint(), { exactTitle && svc.currentCrossRunGeneration() == context.generation }) {
|
||||
svc.gestures.tapNodeOnce(btn)
|
||||
}
|
||||
} else svc.gestures.tapNode(btn)
|
||||
runCatching { btn.recycle() }
|
||||
if (context != null && !tapped) {
|
||||
TaskStatusBus.status(context.reason)
|
||||
go(Phase.FAILED)
|
||||
return
|
||||
}
|
||||
// ⚠️ 二轮审计:tap 失败不能进 WAIT_RECEIPT 干等 30 分钟超时
|
||||
if (!tapped) {
|
||||
log("发布按钮 tap 失败,重试")
|
||||
confirmRetry++
|
||||
if (confirmRetry > CONFIRM_MAX_RETRY) {
|
||||
go(Phase.FAILED)
|
||||
} else {
|
||||
delay(800)
|
||||
}
|
||||
return
|
||||
}
|
||||
receiptWaitStartMs = SystemClock.elapsedRealtime()
|
||||
TaskStatusBus.status("发布动作已发送,等待头条成功回执;确认后才删除素材")
|
||||
go(Phase.WAIT_RECEIPT)
|
||||
} finally { root.recycle() }
|
||||
}
|
||||
|
||||
private fun pauseForSharedAccount(): Boolean {
|
||||
@@ -617,6 +726,25 @@ class PublishMachine(
|
||||
|
||||
/** 等回执(发布成功 / 发布失败 / 已发布)—— 未确认回执不计数 */
|
||||
private suspend fun doWaitReceipt() {
|
||||
if (!autoPublish) {
|
||||
val root = rootOrNull() ?: return
|
||||
val matches = try { draftEditorMatches(root) } finally { root.recycle() }
|
||||
val lines = if (matches) draftReceiptLines() else emptyList()
|
||||
val fresh = rootOrNull() ?: return
|
||||
val confirmed = try {
|
||||
val titleNode = NodeLocator.byId(fresh, ToutiaoSelectors.ID_PUB_TITLE)
|
||||
val actualTitle = try { titleNode?.text?.toString() } finally { titleNode?.recycle() }
|
||||
matches && draftEditorMatches(fresh) && DraftReceiptPolicy.confirms(title, actualTitle,
|
||||
declaration, declarationReadback(fresh), lines, SystemClock.elapsedRealtime() - receiptWaitStartMs)
|
||||
} finally { fresh.recycle() }
|
||||
if (confirmed) {
|
||||
log("当前标题和声明匹配,收到明确的保存草稿成功提示")
|
||||
go(Phase.DONE)
|
||||
} else if (SystemClock.elapsedRealtime() - receiptWaitStartMs > DRAFT_RECEIPT_TIMEOUT_MS) {
|
||||
pauseForReview("草稿未收到明确保存回执,结果待核对,素材已保留")
|
||||
}
|
||||
return
|
||||
}
|
||||
sharedSession?.let { context ->
|
||||
// M6 作品核对器尚未接通。共享尝试不能进入旧的分享面板/超时成功判定。
|
||||
context.markUnknown("发布动作已派发,等待明确作品回执")
|
||||
@@ -634,7 +762,6 @@ class PublishMachine(
|
||||
// 「发布成功」单条即成功;
|
||||
// 「已发布」必须**同时**看到标题节点(防 feed 里"已发布"字样误判)。
|
||||
val publishOk = NodeLocator.byTextContains(root, ToutiaoSelectors.TXT_PUBLISH_OK)
|
||||
?: if (!autoPublish) NodeLocator.byTextContains(root, "草稿") else null
|
||||
// 兜底:发布成功后头条会自动弹「分享至」面板(引导分享),可作成功信号
|
||||
?: NodeLocator.byTextContains(root, ToutiaoSelectors.TXT_SHARE_TO)
|
||||
if (publishOk != null) {
|
||||
@@ -664,13 +791,6 @@ class PublishMachine(
|
||||
}
|
||||
|
||||
val waited = SystemClock.elapsedRealtime() - receiptWaitStartMs
|
||||
// ⚠️ 草稿模式:存草稿通常**没有成功提示**,不宜按 30 分钟等回执。
|
||||
// 短时间内没检测到失败提示即视为成功,避免状态机长期卡死。
|
||||
if (!autoPublish && waited > DRAFT_RECEIPT_TIMEOUT_MS) {
|
||||
log("草稿模式:${waited / 1000}s 未见失败提示,视为保存成功")
|
||||
go(Phase.DONE)
|
||||
return
|
||||
}
|
||||
|
||||
// 超时判定(原 publish_timeout 默认 30 分钟)
|
||||
if (waited > RECEIPT_TIMEOUT_MS) {
|
||||
@@ -706,6 +826,10 @@ class PublishMachine(
|
||||
svc.stopAutomation()
|
||||
return
|
||||
}
|
||||
if (!autoPublish && (draftAttemptId == null || videoDownloader?.confirmDraft(draftAttemptId!!) != true)) {
|
||||
pauseForReview("草稿回执日志未能确认,素材继续保留")
|
||||
return
|
||||
}
|
||||
// 对照原 m2():BACK 退出发布页 → 删除本地素材 → 进度计数 → 启动休息
|
||||
log("收到成功回执,开始收尾(删素材 + 计数 + 休息)")
|
||||
svc.gestures.back() // performGlobalAction(BACK) 退出发布页
|
||||
@@ -721,13 +845,15 @@ class PublishMachine(
|
||||
}
|
||||
quotaManager?.recordPublish()
|
||||
// 对照原 m2() 的两行输出:过程日志 + 监控窗"进度 X/Y"
|
||||
log("发布成功;" + (if (deleted) "本地素材已删除" else "本地素材记录已清理"))
|
||||
TaskStatusBus.status("发布成功,已清理本地素材;进度 ${quotaManager?.dailyProgress ?: "0/0"}")
|
||||
val outcome = if (autoPublish) "发布成功" else "草稿保存已确认"
|
||||
log("$outcome;" + (if (deleted) "本地素材已删除" else "本地素材记录已清理"))
|
||||
TaskStatusBus.status("$outcome,已清理本地素材;处理进度 ${quotaManager?.dailyProgress ?: "0/0"}")
|
||||
// 启动休息倒计时 + 休息浏览(对照原 X2("发布完成"))
|
||||
restBrowse?.startRest("发布完成")
|
||||
restBrowse?.startRest(if (autoPublish) "发布完成" else "草稿已保存")
|
||||
title = ""
|
||||
mediaUri = ""
|
||||
eligibilityCheck = null
|
||||
draftAttemptId = null
|
||||
reset()
|
||||
}
|
||||
|
||||
@@ -802,7 +928,7 @@ class PublishMachine(
|
||||
/** 发布页自动重开上限(对照原 f1289n0 ≤2) */
|
||||
private const val PUBLISH_REOPEN_LIMIT = 2
|
||||
|
||||
/** 草稿模式回执等待上限:存草稿通常无成功提示,短等即判成功 */
|
||||
/** 草稿回执等待上限:超时进入待核对,不能视为保存成功 */
|
||||
private const val DRAFT_RECEIPT_TIMEOUT_MS = 8L * 1000L
|
||||
|
||||
/** 声明选项等待重试上限(对照原 500ms 轮询) */
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.haorui.app.automation.selection
|
||||
|
||||
/** 已观察到的 18.3.0 草稿回执;“存草稿”按钮、分享弹层和超时都不是成功。 */
|
||||
object DraftReceiptPolicy {
|
||||
const val SUCCESS = "保存草稿成功"
|
||||
private const val MARKERS = "✓✔√☑✅○〇◎●0oOQC©"
|
||||
private val cleanReceipt = Regex("[$MARKERS]?保存草稿成功[!!。]?")
|
||||
|
||||
/**
|
||||
* 真机实测:回执是“⊙ 图标 + 保存草稿成功”胶囊,OCR 会把它与同屏位置卡片文本合并成一行,
|
||||
* 且 ⊙ 图标被误读为 0/O/。 等非汉字字符(“0保存草稿成功”“宁兴·城O保存草稿成功鄞州万达广场小”
|
||||
* “城市广场。保存草稿成功达广场IMAX店”)。判定:
|
||||
* 1. 整行即回执签名(含空格与图标误读容错);
|
||||
* 2. 或行内“保存草稿成功”紧邻的前一字符不是汉字——否定句(“未能…”“出现…后返回”)以汉字承接,仍被拒绝。
|
||||
*/
|
||||
fun hasSuccess(lines: List<String>): Boolean = lines.any { raw ->
|
||||
val line = raw.filterNot(Char::isWhitespace)
|
||||
if (cleanReceipt.matches(line)) return@any true
|
||||
val index = line.indexOf(SUCCESS)
|
||||
index > 0 && line[index - 1].code !in 0x4E00..0x9FFF
|
||||
}
|
||||
|
||||
fun declarationReadback(expected: String, selected: Boolean, sheetOpen: Boolean, summary: String?): String? {
|
||||
if (!selected || sheetOpen) return null
|
||||
return summary?.takeIf { it.isNotBlank() } ?: expected.takeIf { it == "内容无需标注" }
|
||||
}
|
||||
|
||||
fun confirms(expectedTitle: String, actualTitle: String?, expectedDeclaration: String, actualDeclaration: String?,
|
||||
receiptLines: List<String>, elapsedMs: Long): Boolean =
|
||||
expectedTitle.isNotBlank() && actualTitle == expectedTitle && actualDeclaration == expectedDeclaration &&
|
||||
elapsedMs in 0..8_000 && hasSuccess(receiptLines)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.haorui.app.crossplatform.account
|
||||
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
|
||||
/** 账号读取专用请求,不与旧采集剪贴板队列共用;超时回调不能交给下一次核验。 */
|
||||
class AccountClipboardRequests {
|
||||
enum class Operation { PREPARE, READ }
|
||||
data class Result(val text: String, val timestampMs: Long)
|
||||
class Request internal constructor(val owner: Long, val id: Long, val operation: Operation, val nonce: String) {
|
||||
val result = CompletableDeferred<Result?>()
|
||||
internal var claimed = false
|
||||
}
|
||||
private var sequence = 0L
|
||||
private var ownerSequence = 0L
|
||||
private var pending: Request? = null
|
||||
|
||||
@Synchronized fun newOwner(): Long = ++ownerSequence
|
||||
@Synchronized fun hasPending(): Boolean = pending != null
|
||||
|
||||
@Synchronized fun begin(owner: Long, operation: Operation, nonce: String): Request {
|
||||
require(owner > 0 && nonce.isNotBlank())
|
||||
pending?.result?.complete(null)
|
||||
return Request(owner, ++sequence, operation, nonce).also { pending = it }
|
||||
}
|
||||
|
||||
@Synchronized fun claim(): Request? = pending?.takeIf { !it.claimed }?.also { it.claimed = true }
|
||||
|
||||
@Synchronized fun isCurrent(request: Request): Boolean = pending === request && !request.result.isCompleted
|
||||
|
||||
@Synchronized fun complete(request: Request, result: Result?): Boolean {
|
||||
if (!isCurrent(request)) return false
|
||||
pending = null
|
||||
request.result.complete(result)
|
||||
return true
|
||||
}
|
||||
|
||||
@Synchronized fun cancel(owner: Long) {
|
||||
if (pending?.owner != owner) return
|
||||
pending?.result?.complete(null)
|
||||
pending = null
|
||||
}
|
||||
|
||||
companion object { val shared = AccountClipboardRequests() }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.haorui.app.crossplatform.account
|
||||
|
||||
import com.google.zxing.BinaryBitmap
|
||||
import com.google.zxing.DecodeHintType
|
||||
import com.google.zxing.RGBLuminanceSource
|
||||
import com.google.zxing.common.HybridBinarizer
|
||||
import com.google.zxing.qrcode.QRCodeReader
|
||||
|
||||
/** 只解码本机名片截图裁剪的像素,不打开二维码链接。 */
|
||||
object ProfileQrDecoder {
|
||||
fun decode(width: Int, height: Int, pixels: IntArray): String? {
|
||||
if (width < 32 || height < 32 || width.toLong() * height != pixels.size.toLong() || pixels.size > 16_777_216) return null
|
||||
return runCatching {
|
||||
QRCodeReader().decode(BinaryBitmap(HybridBinarizer(RGBLuminanceSource(width, height, pixels))),
|
||||
mapOf(DecodeHintType.TRY_HARDER to true)).text.takeIf { it.length <= 8192 }
|
||||
}.getOrNull()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.haorui.app.crossplatform.account
|
||||
|
||||
import java.net.URI
|
||||
import java.net.URLDecoder
|
||||
import java.security.MessageDigest
|
||||
|
||||
/** 仅处理已从自身主页复制的 18.3.0 链接;链接解析本身不构成账号核验。 */
|
||||
object ToutiaoAccountIdentity {
|
||||
fun keyFromProfileLink(text: String): String? = runCatching {
|
||||
if (text.length > 8192) return null
|
||||
val links = Regex("https?://[^\\s\"<>]+", RegexOption.IGNORE_CASE).findAll(text).toList()
|
||||
if (links.size != 1) return null
|
||||
val uri = URI(links.single().value)
|
||||
if (uri.scheme != "https" || uri.host != "profile.zjurl.cn" || uri.userInfo != null || uri.port != -1 ||
|
||||
uri.fragment != null || uri.rawPath?.trimEnd('/') != "/rogue/ugc/profile") return null
|
||||
val pairs = uri.rawQuery?.split('&')?.map { part ->
|
||||
val pieces = part.split('=', limit = 2)
|
||||
URLDecoder.decode(pieces[0], "UTF-8") to URLDecoder.decode(pieces.getOrElse(1) { "" }, "UTF-8")
|
||||
} ?: return null
|
||||
val ids = pairs.filter { it.first == "user_id" }
|
||||
if (ids.size != 1) return null
|
||||
val id = ids.single().second.takeIf { it.matches(Regex("[1-9][0-9]{4,23}")) } ?: return null
|
||||
"tt:" + MessageDigest.getInstance("SHA-256").digest("toutiao:user:$id".toByteArray(Charsets.UTF_8)).joinToString("") { "%02x".format(it) }
|
||||
}.getOrNull()
|
||||
|
||||
fun copiedAfterArm(armed: AccountClipboardRequests.Result, copied: AccountClipboardRequests.Result, nonce: String): Boolean =
|
||||
armed.text == nonce && armed.timestampMs > 0 && copied.text != nonce && copied.timestampMs > armed.timestampMs
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
package com.haorui.app.crossplatform.account
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.content.Intent
|
||||
import android.graphics.Rect
|
||||
import android.os.Build
|
||||
import android.view.accessibility.AccessibilityNodeInfo
|
||||
import com.haorui.app.MainActivity
|
||||
import com.haorui.app.automation.HaoRuiAccessibilityService
|
||||
import com.haorui.app.automation.NodeLocator
|
||||
import com.haorui.app.automation.Targets
|
||||
import com.haorui.app.crossplatform.publish.VerifiedAccount
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import java.util.UUID
|
||||
|
||||
/** 每次核验使用两次独立名片/链接取证,始终检查自身资料指纹;不复用旧核验或昵称作为身份。 */
|
||||
class ToutiaoAccountReader(private val service: HaoRuiAccessibilityService, private val isCurrent: () -> Boolean) {
|
||||
private val requests = AccountClipboardRequests.shared
|
||||
private val owner = requests.newOwner()
|
||||
var failure: String = "账号读取尚未完成"
|
||||
private set
|
||||
|
||||
suspend fun verify(): VerifiedAccount? {
|
||||
if (!Targets.isToutiaoCompatible(service)) { failure = "头条版本尚未适配"; return null }
|
||||
return try {
|
||||
withTimeoutOrNull(60_000) {
|
||||
checkCurrent()
|
||||
service.startActivity(Intent().setComponent(ComponentName(Targets.TOUTIAO_PKG, "com.ss.android.article.news.activity.MainActivity"))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
|
||||
if (!awaitHomeNavigation()) {
|
||||
logNavigationFailure()
|
||||
return@withTimeoutOrNull reject("未能打开头条主页")
|
||||
}
|
||||
if (ownName() == null && !tapMine()) return@withTimeoutOrNull reject("未能进入自己的资料页")
|
||||
if (!await { ownName() != null }) return@withTimeoutOrNull reject("未能核对自身资料入口")
|
||||
val name = ownName() ?: return@withTimeoutOrNull null
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) return@withTimeoutOrNull verifyCards(name)
|
||||
var key: String? = null
|
||||
repeat(2) {
|
||||
val nonce = "haorui-account:${UUID.randomUUID()}"
|
||||
val armed = exchange(AccountClipboardRequests.Operation.PREPARE, nonce) ?: return@withTimeoutOrNull reject("前台剪贴板准备失败")
|
||||
if (armed.text != nonce || !await { ownName() == name }) return@withTimeoutOrNull reject("准备后账号页面已变化")
|
||||
if (!tapId("hs2") || !await { nodeExists(text = "分享至") }) return@withTimeoutOrNull reject("自身主页分享入口不可用")
|
||||
var found = nodeExists(text = "复制链接")
|
||||
repeat(3) {
|
||||
if (!found) {
|
||||
if (!scrollShareRow()) return@withTimeoutOrNull reject("主页复制链接入口不可用")
|
||||
delay(400)
|
||||
found = nodeExists(text = "复制链接")
|
||||
}
|
||||
}
|
||||
if (!found || !tapText("复制链接") || !await { ownName() == name }) return@withTimeoutOrNull reject("复制后账号页面已变化")
|
||||
// 主页链接可能异步写入;在头条仍持有前台时等待并复核。
|
||||
delay(2_500)
|
||||
checkCurrent()
|
||||
if (ownName() != name) return@withTimeoutOrNull reject("复制完成前账号页面已变化")
|
||||
val copied = exchange(AccountClipboardRequests.Operation.READ, nonce) ?: return@withTimeoutOrNull reject("前台账号链接读取失败")
|
||||
if (!await { ownName() == name } || !ToutiaoAccountIdentity.copiedAfterArm(armed, copied, nonce)) return@withTimeoutOrNull reject("账号链接未更新或页面已变化")
|
||||
val currentKey = ToutiaoAccountIdentity.keyFromProfileLink(copied.text) ?: return@withTimeoutOrNull reject("账号链接格式尚未核验")
|
||||
if (key != null && key != currentKey) return@withTimeoutOrNull reject("两次核验的账号不一致")
|
||||
key = currentKey
|
||||
}
|
||||
checkCurrent()
|
||||
VerifiedAccount(key!!, name, System.currentTimeMillis(), UUID.randomUUID().toString())
|
||||
}.also { if (it == null && failure == "账号读取尚未完成") failure = "账号核验超时" }
|
||||
} finally { requests.cancel(owner) }
|
||||
}
|
||||
|
||||
private fun reject(reason: String): VerifiedAccount? {
|
||||
failure = reason
|
||||
val window = service.root()
|
||||
val pkg = try { window?.packageName?.toString() } finally { window?.recycle() }
|
||||
com.haorui.app.automation.RunLogger.i("AccountRead", "reason=$reason package=$pkg")
|
||||
return null
|
||||
}
|
||||
|
||||
private suspend fun closeShares(): Boolean {
|
||||
repeat(2) {
|
||||
checkCurrent()
|
||||
if (!nodeExists("分享至")) return true
|
||||
val card = nodeExists("扫码关注我 获取更多信息")
|
||||
service.gestures.back()
|
||||
// 先等弹层确实消失或名片退回普通分享页,再决定是否需要第二次返回。
|
||||
if (!await { !nodeExists("分享至") || (card && !nodeExists("扫码关注我 获取更多信息")) }) return false
|
||||
}
|
||||
return !nodeExists("分享至")
|
||||
}
|
||||
|
||||
private suspend fun verifyCards(name: String): VerifiedAccount? {
|
||||
var key: String? = null
|
||||
repeat(2) {
|
||||
if (ownName() != name || !tapId("hs2") || !await { nodeExists("分享至") }) return reject("自身主页分享入口不可用")
|
||||
var found = nodeExists("名片分享")
|
||||
repeat(3) {
|
||||
if (!found) {
|
||||
if (!scrollShareRow()) return reject("名片分享入口不可用")
|
||||
delay(400)
|
||||
found = nodeExists("名片分享")
|
||||
}
|
||||
}
|
||||
if (!found || !tapText("名片分享") || !await { cardQrBounds(name) != null }) return reject("自身名片信息未能核对")
|
||||
var currentKey: String? = null
|
||||
repeat(3) {
|
||||
if (currentKey == null) {
|
||||
checkCurrent()
|
||||
delay(450)
|
||||
val bounds = cardQrBounds(name) ?: return reject("名片页面已变化")
|
||||
com.haorui.app.overlay.MonitorOverlay.setHidden(true)
|
||||
val bitmap = try { com.haorui.app.ocr.ScreenCapturer(service).capture() }
|
||||
finally { com.haorui.app.overlay.MonitorOverlay.setHidden(false) }
|
||||
if (bitmap != null) try {
|
||||
checkCurrent()
|
||||
if (cardQrBounds(name) != bounds || bounds.left < 0 || bounds.top < 0 || bounds.right > bitmap.width || bounds.bottom > bitmap.height) return reject("名片截图与页面不一致")
|
||||
currentKey = withContext(Dispatchers.Default) {
|
||||
val pixels = IntArray(bounds.width() * bounds.height())
|
||||
bitmap.getPixels(pixels, 0, bounds.width(), bounds.left, bounds.top, bounds.width(), bounds.height())
|
||||
ProfileQrDecoder.decode(bounds.width(), bounds.height(), pixels)?.let(ToutiaoAccountIdentity::keyFromProfileLink)
|
||||
}
|
||||
} finally { bitmap.recycle() }
|
||||
}
|
||||
}
|
||||
if (currentKey == null) return reject("名片二维码身份无法核验")
|
||||
if (key != null && key != currentKey) return reject("两次核验的账号不一致")
|
||||
key = currentKey
|
||||
if (!closeShares()) return reject("名片弹层未能关闭")
|
||||
if (!await { ownName() == name }) return reject("名片返回后账号页面已变化")
|
||||
}
|
||||
checkCurrent()
|
||||
return VerifiedAccount(key!!, name, System.currentTimeMillis(), UUID.randomUUID().toString())
|
||||
}
|
||||
|
||||
private fun cardQrBounds(name: String): Rect? {
|
||||
val root = root() ?: return null
|
||||
return try {
|
||||
val frame = NodeLocator.byId(root, id("kr")) ?: return null
|
||||
try {
|
||||
val sameName = findText(frame, name)?.also { it.recycle() } != null
|
||||
val caption = findText(frame, "扫码关注我 获取更多信息")?.also { it.recycle() } != null
|
||||
if (!sameName || !caption) return null
|
||||
val bounds = Rect().also(frame::getBoundsInScreen)
|
||||
// 18.3.0 名片的二维码位于下半部;排除上方头像及其可能包含的二维码。
|
||||
if (bounds.width() <= 0 || bounds.height() < 128) null else Rect(bounds.left, bounds.centerY(), bounds.right, bounds.bottom)
|
||||
} finally { frame.recycle() }
|
||||
} finally { root.recycle() }
|
||||
}
|
||||
private fun checkCurrent() { if (!isCurrent()) throw CancellationException("账号核验运行已失效") }
|
||||
private suspend fun await(predicate: () -> Boolean): Boolean {
|
||||
repeat(25) { checkCurrent(); if (predicate()) return true; delay(200) }
|
||||
return false
|
||||
}
|
||||
private fun root(): AccessibilityNodeInfo? {
|
||||
checkCurrent()
|
||||
val root = service.root() ?: return null
|
||||
if (root.packageName?.toString() == Targets.TOUTIAO_PKG) return root
|
||||
root.recycle(); return null
|
||||
}
|
||||
private fun ownName(): String? {
|
||||
val root = root() ?: return null
|
||||
return try {
|
||||
// 弹层打开时头条仍暴露背景资料节点;必须先关闭分享/名片弹层。
|
||||
findText(root, "分享至")?.let { it.recycle(); return null }
|
||||
val edit = NodeLocator.byId(root, id("hno")) ?: return null
|
||||
val own = edit.contentDescription?.toString() == "编辑资料"
|
||||
edit.recycle()
|
||||
if (!own) return null
|
||||
val node = NodeLocator.byId(root, id("hqt")) ?: return null
|
||||
node.text?.toString()?.trim()?.takeIf { it.isNotBlank() }.also { node.recycle() }
|
||||
} finally { root.recycle() }
|
||||
}
|
||||
private fun nodeExists(text: String): Boolean {
|
||||
val root = root() ?: return false
|
||||
return try { findText(root, text)?.also { it.recycle() } != null } finally { root.recycle() }
|
||||
}
|
||||
private fun findText(root: AccessibilityNodeInfo, text: String): AccessibilityNodeInfo? {
|
||||
val nodes = root.findAccessibilityNodeInfosByText(text).orEmpty()
|
||||
var selected: AccessibilityNodeInfo? = null
|
||||
nodes.forEach { node -> if (selected == null && (node.text?.toString() == text || node.contentDescription?.toString() == text)) selected = node else node.recycle() }
|
||||
return selected ?: NodeLocator.byText(root, text) ?: NodeLocator.byDesc(root, text)
|
||||
}
|
||||
|
||||
private fun mineNode(root: AccessibilityNodeInfo): AccessibilityNodeInfo? {
|
||||
findText(root, "我的")?.let { return it }
|
||||
val indexed = root.findAccessibilityNodeInfosByViewId(id("llm")).orEmpty()
|
||||
val nodes = if (indexed.isNotEmpty()) indexed else NodeLocator.all(root, com.haorui.app.automation.Selector.ResId(id("llm")), limit = 8)
|
||||
return try {
|
||||
val screen = Rect().also(root::getBoundsInScreen)
|
||||
val candidates = nodes.map { it to Rect().also(it::getBoundsInScreen) }.filter { (node, rect) ->
|
||||
node.isEnabled && node.isClickable && !rect.isEmpty && rect.top > screen.top + screen.height() * 3 / 4
|
||||
}.sortedBy { it.second.left }
|
||||
// 18.3.0 底栏为首页/视频/赚钱/商城/我的。仅接受覆盖整行的五个相邻项。
|
||||
val aligned = candidates.size == 5 && candidates.first().second.left <= screen.left + screen.width() / 20 &&
|
||||
candidates.last().second.right >= screen.right - screen.width() / 20 &&
|
||||
candidates.all { kotlin.math.abs(it.second.centerY() - candidates.first().second.centerY()) <= 12 } &&
|
||||
candidates.zipWithNext().all { (left, right) -> right.second.left >= left.second.right - 2 }
|
||||
if (aligned) AccessibilityNodeInfo.obtain(candidates.last().first) else null
|
||||
} finally { nodes.forEach { it.recycle() } }
|
||||
}
|
||||
|
||||
private fun homeNavigationReady(): Boolean {
|
||||
val root = root() ?: return false
|
||||
return try {
|
||||
findText(root, "分享至")?.let { it.recycle(); return false }
|
||||
mineNode(root)?.also { it.recycle() } != null
|
||||
} finally { root.recycle() }
|
||||
}
|
||||
|
||||
private suspend fun awaitHomeNavigation(): Boolean {
|
||||
repeat(25) {
|
||||
checkCurrent()
|
||||
// startActivity 返回时可能仍在浩瑞;弹层清理必须等头条实际恢复后执行。
|
||||
if (nodeExists("分享至") && !closeShares()) return false
|
||||
if (ownName() != null || homeNavigationReady()) return true
|
||||
delay(200)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun logNavigationFailure() {
|
||||
val root = root() ?: return
|
||||
try {
|
||||
val bounds = Rect().also(root::getBoundsInScreen)
|
||||
val nodes = root.findAccessibilityNodeInfosByViewId(id("llm")).orEmpty()
|
||||
try {
|
||||
val items = nodes.joinToString(";") { node ->
|
||||
val rect = Rect().also(node::getBoundsInScreen)
|
||||
"${rect.flattenToString()},visible=${node.isVisibleToUser},clickable=${node.isClickable},enabled=${node.isEnabled}"
|
||||
}
|
||||
com.haorui.app.automation.RunLogger.i("AccountRead", "navigation root=${root.className} bounds=${bounds.flattenToString()} footer=${nodes.size} items=$items")
|
||||
} finally { nodes.forEach { it.recycle() } }
|
||||
} finally { root.recycle() }
|
||||
}
|
||||
|
||||
private suspend fun tapMine(): Boolean {
|
||||
val root = root() ?: return false
|
||||
val node = try { mineNode(root) } finally { root.recycle() } ?: return false
|
||||
return try {
|
||||
checkCurrent()
|
||||
val parent = NodeLocator.clickableAncestor(node)
|
||||
try { service.gestures.tapNodeOnce(parent ?: node) } finally { parent?.recycle() }
|
||||
} finally { node.recycle() }
|
||||
}
|
||||
private suspend fun tapText(text: String): Boolean {
|
||||
val root = root() ?: return false
|
||||
val node = try { findText(root, text) } finally { root.recycle() } ?: return false
|
||||
return try {
|
||||
checkCurrent()
|
||||
if (text in setOf("复制链接", "名片分享")) {
|
||||
val parent = NodeLocator.clickableAncestor(node)
|
||||
try { service.gestures.tapNodeOnce(parent ?: node) } finally { parent?.recycle() }
|
||||
} else service.gestures.tapNode(node)
|
||||
} finally { node.recycle() }
|
||||
}
|
||||
private suspend fun tapId(value: String): Boolean {
|
||||
val root = root() ?: return false
|
||||
val node = try { NodeLocator.byId(root, id(value)) } finally { root.recycle() } ?: return false
|
||||
return try { checkCurrent(); service.gestures.tapNode(node) } finally { node.recycle() }
|
||||
}
|
||||
private fun scrollShareRow(): Boolean {
|
||||
val root = root() ?: return false
|
||||
return try {
|
||||
val row = NodeLocator.byId(root, id("onk")) ?: return false
|
||||
try { checkCurrent(); row.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD) } finally { row.recycle() }
|
||||
} finally { root.recycle() }
|
||||
}
|
||||
private suspend fun exchange(operation: AccountClipboardRequests.Operation, nonce: String): AccountClipboardRequests.Result? {
|
||||
checkCurrent()
|
||||
val request = requests.begin(owner, operation, nonce)
|
||||
return try {
|
||||
service.startActivity(Intent(service, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP))
|
||||
withTimeoutOrNull(8_000) { request.result.await() }
|
||||
} finally { requests.cancel(owner) }
|
||||
}
|
||||
private fun id(value: String) = "${Targets.TOUTIAO_PKG}:id/$value"
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
package com.haorui.app.crossplatform.compose
|
||||
|
||||
import com.haorui.app.data.model.AiConfig
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.json.Json
|
||||
import java.io.BufferedReader
|
||||
import java.io.InputStreamReader
|
||||
import java.io.OutputStreamWriter
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
/**
|
||||
* 图文正文生成器(M4,2026-11-15):事实包 → 提纲 → 正文 + 核验。
|
||||
*
|
||||
* 设计口径(跨平台自动发布设计 §图文生成):
|
||||
* 流程为 事实包 → 提纲 → 正文 → 3 个标题候选 → 自动核验 → 配图。
|
||||
* 正文初始目标 800~1500 字,按信息量调整,不能凑字数;口语化分段,给出分析依据,
|
||||
* 结尾可提出一个与正文有关的问题(提示词要求,不作硬核验)。
|
||||
*
|
||||
* 核验三关(不合格最多修一次,仍不合格即跳过——“最多修一次,不合格即跳过”):
|
||||
* ①长度关:800~1500 字(按码点;与编辑器/设计目标一致,不合格带原因修一次);
|
||||
* ②分段关:口语化分段,正文至少 2 个非空段落;
|
||||
* ③数字一致关:正文中的数字串(≥2 位)必须出现在来源全文——不编造统计(与标题同规则)。
|
||||
*
|
||||
* 提纲解析失败不阻塞(降级为模型自拟结构,日志记录);正文生成失败返回 null 交由任务跳过。
|
||||
* HTTP 栈与 [ArticleComposer]/[com.haorui.app.pipeline.AiRewriteService] 同构(OpenAI 兼容
|
||||
* chat/completions)。日志经 [logger] 注入(默认 no-op)——保持纯 JVM 可测。
|
||||
*/
|
||||
class ArticleBodyComposer(
|
||||
private val config: AiConfig,
|
||||
private val logger: (String) -> Unit = {},
|
||||
) {
|
||||
|
||||
companion object {
|
||||
private const val CONNECT_TIMEOUT_MS = 20_000
|
||||
private const val READ_TIMEOUT_MS = 120_000
|
||||
|
||||
/** 正文长度窗口(设计:初始目标 800~1500 字)。 */
|
||||
const val BODY_MIN = 800
|
||||
const val BODY_MAX = 1500
|
||||
|
||||
/** 正文生成给模型看的来源全文上限(正文材料比标题更多,6000 字内一并喂给模型)。 */
|
||||
private const val SOURCE_TAKE = 6000
|
||||
|
||||
private const val OUTLINE_PROMPT =
|
||||
"你是中文新媒体编辑。请根据来源文章全文列出正文写作提纲:3~6 个要点,每个要点一句话," +
|
||||
"覆盖事件经过、关键事实与分析角度。只返回 JSON 数组(字符串),不要解释。"
|
||||
|
||||
private const val BODY_PROMPT =
|
||||
"你是中文新媒体编辑。请根据提纲和来源文章全文写一篇今日头条风格的图文正文。" +
|
||||
"要求:①800~1500 字,按信息量调整,不要凑字数;②口语化分段,段落短,给出分析依据;" +
|
||||
"③不编造事实、数字、引用——文中出现的数字、时间、人名必须能在来源全文中找到;" +
|
||||
"④结尾提出一个与正文有关的问题;⑤只返回正文文本,不要标题、不要 markdown 标记。"
|
||||
}
|
||||
|
||||
private val json = Json { ignoreUnknownKeys = true; isLenient = true }
|
||||
|
||||
/** 正文结果:提纲要点(可能为空=模型自拟结构)+ 正文全文。 */
|
||||
data class BodyResult(
|
||||
val outline: List<String>,
|
||||
val body: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* 生成正文(提纲→正文→核验,最多修一次)。
|
||||
* @return null=模型失败或核验仍不合格(任务应跳过,原因进 [failureReason])。
|
||||
*/
|
||||
var failureReason: String = ""
|
||||
private set
|
||||
|
||||
suspend fun composeBody(evidence: EvidenceBuilder.Evidence): BodyResult? =
|
||||
withContext(Dispatchers.IO) {
|
||||
failureReason = ""
|
||||
val apiKey = when (config.provider) {
|
||||
"deepseek" -> config.deepseekKey
|
||||
"qwen_plus" -> config.qwenKey
|
||||
else -> ""
|
||||
}
|
||||
if (apiKey.isBlank()) {
|
||||
failureReason = "模型 Key 未配置,无法生成正文"
|
||||
logger(failureReason)
|
||||
return@withContext null
|
||||
}
|
||||
// 提纲(失败降级:模型自拟结构,不阻塞正文)
|
||||
val outline = generateOutline(evidence, apiKey)
|
||||
if (outline.isEmpty()) {
|
||||
logger("提纲未取得,降级为模型自拟结构")
|
||||
} else {
|
||||
logger("提纲 ${outline.size} 要点")
|
||||
}
|
||||
// 初稿 + 修稿一次(“最多修一次,不合格即跳过”)
|
||||
var revisionHint = ""
|
||||
for (attempt in 1..2) {
|
||||
try {
|
||||
val raw = callModel(apiKey, buildBodyPrompt(evidence, outline, revisionHint)) ?: continue
|
||||
val body = cleanBody(raw)
|
||||
val reason = verifyBody(body, evidence)
|
||||
if (reason == null) {
|
||||
logger("正文生成成功(第${attempt}稿):${body.codePointCount(0, body.length)} 字,提纲 ${outline.size} 要点")
|
||||
return@withContext BodyResult(outline, body)
|
||||
}
|
||||
logger("正文不合格(第${attempt}稿):$reason")
|
||||
revisionHint = "(上一稿问题:$reason。请修正后重新输出整篇正文)"
|
||||
} catch (e: kotlin.coroutines.cancellation.CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
logger("正文生成失败(第${attempt}稿): ${e.javaClass.simpleName}:${e.message}")
|
||||
}
|
||||
}
|
||||
failureReason = "正文生成初稿+修稿仍不合格"
|
||||
null
|
||||
}
|
||||
|
||||
/** 提纲生成:失败返回空表(不阻塞正文)。 */
|
||||
private suspend fun generateOutline(evidence: EvidenceBuilder.Evidence, apiKey: String): List<String> {
|
||||
val userPrompt = buildString {
|
||||
append("来源标题:").append(evidence.titleSeed).append('\n')
|
||||
append("来源全文:\n").append(evidence.sourceText.take(SOURCE_TAKE))
|
||||
}
|
||||
return try {
|
||||
val raw = callModel(apiKey, userPrompt, OUTLINE_PROMPT) ?: return emptyList()
|
||||
val outline = parseOutline(raw)
|
||||
if (outline.isEmpty()) logger("提纲解析为空,原文前 80 字:${raw.take(80)}")
|
||||
outline
|
||||
} catch (e: kotlin.coroutines.cancellation.CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
logger("提纲生成失败: ${e.javaClass.simpleName}:${e.message}")
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildBodyPrompt(
|
||||
evidence: EvidenceBuilder.Evidence,
|
||||
outline: List<String>,
|
||||
revisionHint: String,
|
||||
): String = buildString {
|
||||
append("来源标题:").append(evidence.titleSeed).append('\n')
|
||||
append("来源全文:\n").append(evidence.sourceText.take(SOURCE_TAKE)).append('\n')
|
||||
if (outline.isNotEmpty()) {
|
||||
append("写作提纲:\n")
|
||||
outline.forEachIndexed { i, point -> append("${i + 1}. ").append(point).append('\n') }
|
||||
}
|
||||
if (revisionHint.isNotEmpty()) append(revisionHint)
|
||||
}
|
||||
|
||||
/** 清理模型输出:去代码围栏、"正文:"类前导标签与首尾空白。 */
|
||||
internal fun cleanBody(raw: String): String {
|
||||
var text = raw.trim()
|
||||
text = text.removePrefix("```text").removePrefix("```").removeSuffix("```").trim()
|
||||
text = text.removePrefix("正文:").removePrefix("正文:").trim()
|
||||
return text
|
||||
}
|
||||
|
||||
/** 解析提纲 JSON 数组(容忍 ```json 包裹与尾注;与标题候选解析同规则)。 */
|
||||
internal fun parseOutline(raw: String): List<String> {
|
||||
val cleaned = raw.replace("```json", "").replace("```", "").trim()
|
||||
val start = cleaned.indexOf('[')
|
||||
val end = cleaned.lastIndexOf(']')
|
||||
if (start < 0 || end <= start) return emptyList()
|
||||
return try {
|
||||
json.decodeFromString<List<String>>(cleaned.substring(start, end + 1))
|
||||
.map { it.trim() }.filter { it.isNotEmpty() }
|
||||
} catch (e: Exception) {
|
||||
logger("提纲 JSON 解析失败: ${e.message}")
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 正文核验三关,返回拒绝原因;合格返回 null。
|
||||
* ①长度关:$BODY_MIN..$BODY_MAX 字(按码点);②分段关:至少 2 个非空段落;
|
||||
* ③数字一致关:≥2 位数字串必须在来源全文中找到——不编造统计。
|
||||
*/
|
||||
internal fun verifyBody(body: String, evidence: EvidenceBuilder.Evidence): String? {
|
||||
if (body.isBlank()) return "为空"
|
||||
val cp = body.codePointCount(0, body.length)
|
||||
if (cp < BODY_MIN) return "不足 $BODY_MIN 字(实际 $cp)"
|
||||
if (cp > BODY_MAX) return "超过 $BODY_MAX 字(实际 $cp)"
|
||||
if (body.lineSequence().count { it.isNotBlank() } < 2) return "未分段(口语化分段要求)"
|
||||
Regex("\\d+(?:\\.\\d+)?").findAll(body).forEach { match ->
|
||||
val number = match.value
|
||||
if (number.length >= 2 && !evidence.sourceText.contains(number)) {
|
||||
return "数字 $number 不在来源全文中(疑似编造)"
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// ── HTTP(与 ArticleComposer/AiRewriteService 同构)────────
|
||||
|
||||
/** 通用模型调用(提纲/正文共用;systemPrompt 可覆盖默认正文提示词)。 */
|
||||
private fun callModel(apiKey: String, userPrompt: String, systemPrompt: String = BODY_PROMPT): String? {
|
||||
val endpoint = when (config.provider) {
|
||||
"deepseek" -> "https://api.deepseek.com/chat/completions"
|
||||
"qwen_plus" -> config.qwenEndpoint
|
||||
else -> "https://api.deepseek.com/chat/completions"
|
||||
}
|
||||
val model = when (config.provider) {
|
||||
"deepseek" -> config.deepseekModel.ifBlank { "deepseek-chat" }
|
||||
"qwen_plus" -> "qwen-plus"
|
||||
else -> "deepseek-chat"
|
||||
}
|
||||
val body = """{"model":${jsonString(model)},""" +
|
||||
""""messages":[{"role":"system","content":${jsonString(systemPrompt)}},""" +
|
||||
"""{"role":"user","content":${jsonString(userPrompt)}}],"stream": false}"""
|
||||
val response = httpPost(endpoint, apiKey, body)
|
||||
return parseChatResponse(response)
|
||||
}
|
||||
|
||||
private fun parseChatResponse(response: String): String? = try {
|
||||
val resp = json.decodeFromString<ChatResponseDto>(response)
|
||||
resp.choices?.firstOrNull()?.message?.content?.trim()?.takeIf { it.isNotEmpty() }
|
||||
} catch (e: Exception) {
|
||||
logger("响应解析失败: ${e.javaClass.simpleName}:${e.message}")
|
||||
null
|
||||
}
|
||||
|
||||
private fun httpPost(endpoint: String, apiKey: String, body: String): String {
|
||||
val conn = URL(endpoint).openConnection() as HttpURLConnection
|
||||
try {
|
||||
conn.requestMethod = "POST"
|
||||
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8")
|
||||
conn.setRequestProperty("Authorization", "Bearer $apiKey")
|
||||
conn.connectTimeout = CONNECT_TIMEOUT_MS
|
||||
conn.readTimeout = READ_TIMEOUT_MS
|
||||
conn.doOutput = true
|
||||
OutputStreamWriter(conn.outputStream, Charsets.UTF_8).use { it.write(body) }
|
||||
val code = conn.responseCode
|
||||
if (code in 500..599) throw RuntimeException("网络不可用 HTTP $code")
|
||||
if (code == 204) throw RuntimeException("接口返回空结果")
|
||||
if (code !in 200..299) {
|
||||
val err = conn.errorStream?.let { s ->
|
||||
BufferedReader(InputStreamReader(s, Charsets.UTF_8)).use { it.readText() }
|
||||
} ?: ""
|
||||
throw RuntimeException("接口 HTTP $code: ${err.take(200)}")
|
||||
}
|
||||
return BufferedReader(InputStreamReader(conn.inputStream, Charsets.UTF_8)).use { it.readText() }
|
||||
} finally {
|
||||
conn.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
private fun jsonString(s: String): String = buildString {
|
||||
append('"')
|
||||
for (ch in s) {
|
||||
when (ch) {
|
||||
'"' -> append("\\\"")
|
||||
'\\' -> append("\\\\")
|
||||
'\n' -> append("\\n")
|
||||
'\r' -> append("\\r")
|
||||
'\t' -> append("\\t")
|
||||
else -> if (ch < ' ') append("\\u%04x".format(ch.code)) else append(ch)
|
||||
}
|
||||
}
|
||||
append('"')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
package com.haorui.app.crossplatform.compose
|
||||
|
||||
import com.haorui.app.data.model.AiConfig
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import java.io.BufferedReader
|
||||
import java.io.InputStreamReader
|
||||
import java.io.OutputStreamWriter
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
/**
|
||||
* 图文创作器(M4,2026-11-15):事实包 → 标题候选 + 核验。
|
||||
*
|
||||
* 标题逻辑(用户 2026-11-15 口径:转发文章 → 全文塞给模型生成有吸引力的标题):
|
||||
* - 事实包(含来源全文)交给 deepseek/qwen(配置决定);
|
||||
* - 要求产出 3 个标题候选:有吸引力、与事实一致、2~30 字(编辑器页面自带约束);
|
||||
* - 三关核验:①非空/单行/长度 ②吸引性启发(非原文复读)③数字一致性(标题中的数字
|
||||
* 必须出现在来源全文——不编造统计);
|
||||
* - 生成失败或全部候选不合格 → 返回 null 交由任务跳过(设计:"最多修一次,不合格即跳过")。
|
||||
*
|
||||
* 正文生成(提纲→正文)后续迭代接入;本版先打通标题链(M4 最小可验闭环)。
|
||||
* HTTP 栈与 [com.haorui.app.pipeline.AiRewriteService] 同构(OpenAI 兼容 chat/completions)。
|
||||
* 日志经 [logger] 注入(默认 no-op)——保持纯 JVM 可测。
|
||||
*/
|
||||
class ArticleComposer(
|
||||
private val config: AiConfig,
|
||||
private val logger: (String) -> Unit = {},
|
||||
) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "HaoRui-Composer"
|
||||
private const val CONNECT_TIMEOUT_MS = 20_000
|
||||
private const val READ_TIMEOUT_MS = 90_000
|
||||
private const val MAX_RETRIES = 2
|
||||
|
||||
/** 编辑器页面自带约束(2026-11-15 取证:"请输入标题(2~30个字)")。 */
|
||||
const val TITLE_MIN = 2
|
||||
const val TITLE_MAX = 30
|
||||
|
||||
private const val TITLE_PROMPT =
|
||||
"你是中文标题编辑。用户给你一篇来源文章的全文,请基于其内容写 3 个候选标题。" +
|
||||
"要求:①有吸引力、具体,但不虚构紧迫性、不夸大范围、不编造统计或引用;" +
|
||||
"②标题中出现的数字、时间、人名等必须能在原文中找到;" +
|
||||
"③每个标题 2~30 个汉字;④只返回 JSON 数组(3 个字符串),不要引号解释或换行说明。"
|
||||
}
|
||||
|
||||
private val json = Json { ignoreUnknownKeys = true; isLenient = true }
|
||||
|
||||
/** 标题候选 + 核验结果。 */
|
||||
data class TitleResult(
|
||||
val candidates: List<String>,
|
||||
val selected: String,
|
||||
val rejectedReasons: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* 生成标题候选并核验。
|
||||
* @return null=模型失败或全部候选不合格(任务应跳过,原因进 [failureReason])。
|
||||
*/
|
||||
var failureReason: String = ""
|
||||
private set
|
||||
|
||||
suspend fun composeTitles(evidence: EvidenceBuilder.Evidence): TitleResult? =
|
||||
withContext(Dispatchers.IO) {
|
||||
failureReason = ""
|
||||
val apiKey = when (config.provider) {
|
||||
"deepseek" -> config.deepseekKey
|
||||
"qwen_plus" -> config.qwenKey
|
||||
else -> ""
|
||||
}
|
||||
if (apiKey.isBlank()) {
|
||||
failureReason = "模型 Key 未配置,无法生成标题"
|
||||
logger(failureReason)
|
||||
return@withContext null
|
||||
}
|
||||
val userPrompt = buildString {
|
||||
append("来源标题:").append(evidence.titleSeed).append('\n')
|
||||
append("来源全文:\n").append(evidence.sourceText.take(3000))
|
||||
}
|
||||
val endpoint = when (config.provider) {
|
||||
"deepseek" -> "https://api.deepseek.com/chat/completions"
|
||||
"qwen_plus" -> config.qwenEndpoint
|
||||
else -> "https://api.deepseek.com/chat/completions"
|
||||
}
|
||||
val model = when (config.provider) {
|
||||
"deepseek" -> config.deepseekModel.ifBlank { "deepseek-chat" }
|
||||
"qwen_plus" -> "qwen-plus"
|
||||
else -> "deepseek-chat"
|
||||
}
|
||||
val body = """{"model":${jsonString(model)},""" +
|
||||
""""messages":[{"role":"system","content":${jsonString(TITLE_PROMPT)}},""" +
|
||||
"""{"role":"user","content":${jsonString(userPrompt)}}],"stream": false}"""
|
||||
|
||||
for (attempt in 0..MAX_RETRIES) {
|
||||
try {
|
||||
val response = httpPost(endpoint, apiKey, body)
|
||||
val raw = parseChatResponse(response) ?: continue
|
||||
val candidates = parseCandidates(raw)
|
||||
val verified = verify(candidates, evidence)
|
||||
if (verified != null) {
|
||||
logger("标题生成成功(第${attempt + 1}次):选中「${verified.selected}」" +
|
||||
"(候选 ${candidates.size},淘汰原因 ${verified.rejectedReasons.size})")
|
||||
return@withContext verified
|
||||
}
|
||||
logger("候选全部不合格(第${attempt + 1}次):${verified?.rejectedReasons ?: "解析失败"}")
|
||||
} catch (e: kotlin.coroutines.cancellation.CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
logger("标题生成失败(第${attempt + 1}次): ${e.javaClass.simpleName}:${e.message}")
|
||||
}
|
||||
}
|
||||
failureReason = "标题生成重试 ${MAX_RETRIES + 1} 次仍无合格候选"
|
||||
null
|
||||
}
|
||||
|
||||
/** 解析模型返回的 JSON 数组(容忍 ```json 包裹与尾注)。 */
|
||||
internal fun parseCandidates(raw: String): List<String> {
|
||||
val cleaned = raw.replace("```json", "").replace("```", "").trim()
|
||||
val start = cleaned.indexOf('[')
|
||||
val end = cleaned.lastIndexOf(']')
|
||||
if (start < 0 || end <= start) return emptyList()
|
||||
return try {
|
||||
json.decodeFromString<List<String>>(cleaned.substring(start, end + 1))
|
||||
} catch (e: Exception) {
|
||||
logger("候选 JSON 解析失败: ${e.message}")
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 三关核验,返回首个全过的候选;全不合格返回 null(原因清单供日志/任务记录)。
|
||||
* ①格式关:非空、单行、$TITLE_MIN..$TITLE_MAX 字(按码点);
|
||||
* ②非复读关:不得与来源标题完全相同(否则没有生成价值);
|
||||
* ③数字一致关:标题中的每个数字必须能在来源全文找到——不编造统计。
|
||||
*/
|
||||
internal fun verify(candidates: List<String>, evidence: EvidenceBuilder.Evidence): TitleResult? {
|
||||
val rejected = mutableListOf<String>()
|
||||
for (candidate in candidates.map { it.trim() }) {
|
||||
val reason = verifyOne(candidate, evidence) ?: return TitleResult(
|
||||
candidates = candidates,
|
||||
selected = candidate,
|
||||
rejectedReasons = rejected,
|
||||
)
|
||||
rejected.add("$candidate:$reason")
|
||||
}
|
||||
failureReason = if (rejected.isEmpty()) "模型未返回候选" else rejected.joinToString(";")
|
||||
return null
|
||||
}
|
||||
|
||||
internal fun verifyOne(candidate: String, evidence: EvidenceBuilder.Evidence): String? {
|
||||
if (candidate.isEmpty()) return "为空"
|
||||
if (candidate.contains('\n') || candidate.contains('\r')) return "含换行"
|
||||
val cp = candidate.codePointCount(0, candidate.length)
|
||||
if (cp < TITLE_MIN) return "不足 $TITLE_MIN 字"
|
||||
if (cp > TITLE_MAX) return "超过 $TITLE_MAX 字"
|
||||
if (candidate == evidence.titleSeed.trim()) return "与来源标题完全相同(无生成价值)"
|
||||
// 数字一致关:标题中的数字串(≥2 位才核验,避免“3人”类量词误伤——量词数字也须可定位,
|
||||
// 但允许出现在原文的更大数字内,如标题“5万”匹配原文“5.2万”放宽为包含关系)
|
||||
Regex("\\d+(?:\\.\\d+)?").findAll(candidate).forEach { match ->
|
||||
val number = match.value
|
||||
if (number.length >= 2 && !evidence.sourceText.contains(number)) {
|
||||
return "数字 $number 不在来源全文中(疑似编造)"
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// ── HTTP(与 AiRewriteService 同构)────────────────────────
|
||||
|
||||
private fun parseChatResponse(response: String): String? = try {
|
||||
val resp = json.decodeFromString<ChatResponseDto>(response)
|
||||
resp.choices?.firstOrNull()?.message?.content?.trim()?.takeIf { it.isNotEmpty() }
|
||||
} catch (e: Exception) {
|
||||
logger("响应解析失败: ${e.javaClass.simpleName}:${e.message}")
|
||||
null
|
||||
}
|
||||
|
||||
private fun httpPost(endpoint: String, apiKey: String, body: String): String =
|
||||
composerHttpPost(endpoint, apiKey, body, CONNECT_TIMEOUT_MS, READ_TIMEOUT_MS)
|
||||
|
||||
private fun jsonString(s: String): String = composerJsonString(s)
|
||||
}
|
||||
|
||||
/** 共享 HTTP POST(chat/completions 同构调用共用;VideoTitleComposer 亦复用)。 */
|
||||
internal fun composerHttpPost(
|
||||
endpoint: String,
|
||||
apiKey: String,
|
||||
body: String,
|
||||
connectTimeoutMs: Int,
|
||||
readTimeoutMs: Int,
|
||||
): String {
|
||||
val conn = URL(endpoint).openConnection() as HttpURLConnection
|
||||
try {
|
||||
conn.requestMethod = "POST"
|
||||
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8")
|
||||
conn.setRequestProperty("Authorization", "Bearer $apiKey")
|
||||
conn.connectTimeout = connectTimeoutMs
|
||||
conn.readTimeout = readTimeoutMs
|
||||
conn.doOutput = true
|
||||
OutputStreamWriter(conn.outputStream, Charsets.UTF_8).use { it.write(body) }
|
||||
val code = conn.responseCode
|
||||
if (code in 500..599) throw RuntimeException("网络不可用 HTTP $code")
|
||||
if (code == 204) throw RuntimeException("接口返回空结果")
|
||||
if (code !in 200..299) {
|
||||
val err = conn.errorStream?.let { s ->
|
||||
BufferedReader(InputStreamReader(s, Charsets.UTF_8)).use { it.readText() }
|
||||
} ?: ""
|
||||
throw RuntimeException("接口 HTTP $code: ${err.take(200)}")
|
||||
}
|
||||
return BufferedReader(InputStreamReader(conn.inputStream, Charsets.UTF_8)).use { it.readText() }
|
||||
} finally {
|
||||
conn.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
/** 共享 JSON 字符串转义(composerHttpPost 同级工具)。 */
|
||||
internal fun composerJsonString(s: String): String = buildString {
|
||||
append('"')
|
||||
for (ch in s) {
|
||||
when (ch) {
|
||||
'"' -> append("\\\"")
|
||||
'\\' -> append("\\\\")
|
||||
'\n' -> append("\\n")
|
||||
'\r' -> append("\\r")
|
||||
'\t' -> append("\\t")
|
||||
else -> if (ch < ' ') append("\\u%04x".format(ch.code)) else append(ch)
|
||||
}
|
||||
}
|
||||
append('"')
|
||||
}
|
||||
|
||||
// 响应 DTO(internal:与 ArticleBodyComposer 共用同构 chat/completions 响应模型;
|
||||
// 同包 private 顶层同名类会 Redeclaration,故不各持一份)
|
||||
@Serializable
|
||||
internal data class ChatResponseDto(val choices: List<ChatChoiceDto>? = null)
|
||||
|
||||
@Serializable
|
||||
internal data class ChatChoiceDto(val message: ChatMessageDto? = null)
|
||||
|
||||
@Serializable
|
||||
internal data class ChatMessageDto(val content: String? = null)
|
||||
@@ -0,0 +1,183 @@
|
||||
package com.haorui.app.crossplatform.compose
|
||||
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
/**
|
||||
* 音频转写器(阿里云百炼 dashscope,2026-11-18 官方文档取证口径)。
|
||||
*
|
||||
* 用途:抖音视频「保存本地」后提取音轨,转写为文本供 AI 生成标题。
|
||||
*
|
||||
* 模型选择(官方文档 qwen-audio-3.1-asr-flash):
|
||||
* - 短音频同步识别:≤5 分钟、≤2GB,支持 mp4/m4a/aac/mp3/wav 等 16 种格式;
|
||||
* 端点 POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
|
||||
* - 请求体:input.messages[].content[] = {type: "input_audio", input_audio: {data: <URL或Base64 Data URI>}};
|
||||
* parameters.format 与实际文件格式一致;
|
||||
* - 响应:output.text = 累计完整转写文本;
|
||||
* - 认证:Authorization: Bearer <DASHSCOPE_API_KEY>(复用现有 qwen 配置的 Key)。
|
||||
*
|
||||
* 设计口径:
|
||||
* - 抖音热点视频时长普遍 <5 分钟,同步接口够用;超长视频返回 null 由调用方降级
|
||||
* (不接 filetrans 异步轮询——多一个状态机多一类故障面,首版不引入);
|
||||
* - 音频以 Base64 Data URI 直传(手机本地文件没有公网 URL,filetrans 路线本身不可用);
|
||||
* - JSON 手拼(jsonString 转义)+ 响应手动提取字段——与 ArticleComposer 同型,
|
||||
* 不引 org.json(JVM 单测 stub not mocked)也不新增 kotlinx DTO(请求体结构单一)。
|
||||
*/
|
||||
object AsrTranscriber {
|
||||
/** 官方文档:短音频 ≤5 分钟、≤2GB。格式白名单为官方 16 种中与音轨输出相关的子集。 */
|
||||
const val MAX_DURATION_MS = 5 * 60 * 1000L
|
||||
const val MAX_BYTES = 2L * 1024 * 1024 * 1024
|
||||
internal val SUPPORTED_FORMATS = setOf("mp4", "m4a", "aac", "mp3", "wav", "ogg", "opus", "flac")
|
||||
|
||||
private const val DEFAULT_WORKSPACE_ENDPOINT_SUFFIX =
|
||||
".cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation"
|
||||
internal const val MODEL = "qwen-audio-3.1-asr-flash"
|
||||
|
||||
/** 转写结果。text 为完整转写文本;失败时 text=null 且 failureReason 说明原因。 */
|
||||
data class Transcription(val text: String?, val failureReason: String = "")
|
||||
|
||||
/**
|
||||
* 转写音频文件。
|
||||
* @param audioBytes 音频文件字节(调用方先做时长/大小预检)
|
||||
* @param format 文件格式(mp4/m4a/…,白名单内)
|
||||
* @param apiKey dashscope API Key(复用 qwen 配置)
|
||||
* @param workspaceId 百炼 WorkspaceId(空则回退 dashscope 主域兼容端点)
|
||||
*/
|
||||
fun transcribe(
|
||||
audioBytes: ByteArray,
|
||||
format: String,
|
||||
apiKey: String,
|
||||
workspaceId: String = "",
|
||||
): Transcription {
|
||||
if (format.lowercase() !in SUPPORTED_FORMATS) {
|
||||
return Transcription(null, "音频格式 $format 不在转写支持范围")
|
||||
}
|
||||
if (audioBytes.size > MAX_BYTES) {
|
||||
return Transcription(null, "音频超过 2GB 上限")
|
||||
}
|
||||
if (apiKey.isBlank()) {
|
||||
return Transcription(null, "模型 Key 未配置,无法转写音频")
|
||||
}
|
||||
val endpoint = if (workspaceId.isBlank()) {
|
||||
"https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation"
|
||||
} else {
|
||||
"https://$workspaceId$DEFAULT_WORKSPACE_ENDPOINT_SUFFIX"
|
||||
}
|
||||
val body = buildRequestBody(audioBytes, format)
|
||||
return try {
|
||||
val response = httpPostJson(endpoint, apiKey, body)
|
||||
parseResponse(response)
|
||||
} catch (e: Exception) {
|
||||
Transcription(null, "转写请求失败:${e.message ?: e.javaClass.simpleName}")
|
||||
}
|
||||
}
|
||||
|
||||
/** 组装官方 multimodal-generation 请求体;音频 Base64 Data URI 直传。 */
|
||||
internal fun buildRequestBody(audioBytes: ByteArray, format: String): String {
|
||||
val b64 = java.util.Base64.getEncoder().encodeToString(audioBytes)
|
||||
val dataUri = "data:audio/${format.lowercase()};base64,$b64"
|
||||
return buildString {
|
||||
append("{\"model\":").append(jsonString(MODEL))
|
||||
append(",\"input\":{\"messages\":[{\"role\":\"user\",\"content\":[")
|
||||
append("{\"type\":\"input_audio\",\"input_audio\":{\"data\":")
|
||||
append(jsonString(dataUri))
|
||||
append("}}]}")
|
||||
append(",\"parameters\":{\"format\":").append(jsonString(format.lowercase()))
|
||||
append("}}")
|
||||
}
|
||||
}
|
||||
|
||||
/** 解析官方响应:output.text 为累计完整文本;业务错误如实带回。 */
|
||||
internal fun parseResponse(responseJson: String): Transcription {
|
||||
// 轻量字段提取(不做完整 JSON 解析——响应结构由官方文档钉死,两层字段):
|
||||
// 成功形态 {"output":{"text":"..."},...};错误形态 {"code":"...","message":"..."}
|
||||
val text = extractStringField(responseJson, "\"text\"")
|
||||
return when {
|
||||
text != null && text.isNotBlank() -> Transcription(text)
|
||||
text != null -> Transcription(null, "转写结果为空(音频可能无人声)")
|
||||
else -> {
|
||||
val message = extractStringField(responseJson, "\"message\"")
|
||||
?: extractStringField(responseJson, "\"code\"")
|
||||
Transcription(null, "转写被拒绝:${message ?: "响应缺少 output.text(形态未取证)"}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 提取顶层嵌套字段字符串值(转义还原);找不到返回 null。仅覆盖文档取证的两层形态。 */
|
||||
internal fun extractStringField(json: String, key: String): String? {
|
||||
val keyIdx = json.indexOf(key)
|
||||
if (keyIdx < 0) return null
|
||||
val colon = json.indexOf(':', keyIdx + key.length)
|
||||
if (colon < 0) return null
|
||||
var i = colon + 1
|
||||
while (i < json.length && json[i].isWhitespace()) i++
|
||||
if (i >= json.length || json[i] != '"') return null
|
||||
i++
|
||||
val sb = StringBuilder()
|
||||
while (i < json.length) {
|
||||
val c = json[i]
|
||||
when {
|
||||
c == '\\' && i + 1 < json.length -> {
|
||||
when (val n = json[i + 1]) {
|
||||
'"' -> sb.append('"')
|
||||
'\\' -> sb.append('\\')
|
||||
'/' -> sb.append('/')
|
||||
'n' -> sb.append('\n')
|
||||
't' -> sb.append('\t')
|
||||
'r' -> sb.append('\r')
|
||||
'b' -> sb.append('\b')
|
||||
'f' -> sb.append('')
|
||||
'u' -> {
|
||||
if (i + 5 < json.length) {
|
||||
sb.append(json.substring(i + 2, i + 6).toInt(16).toChar())
|
||||
i += 4
|
||||
}
|
||||
}
|
||||
else -> sb.append(n)
|
||||
}
|
||||
i += 2
|
||||
}
|
||||
c == '"' -> return sb.toString()
|
||||
else -> { sb.append(c); i++ }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** JSON 字符串转义(与 ArticleComposer.jsonString 同型)。 */
|
||||
internal fun jsonString(s: String): String = buildString {
|
||||
append('"')
|
||||
for (ch in s) {
|
||||
when (ch) {
|
||||
'"' -> append("\\\"")
|
||||
'\\' -> append("\\\\")
|
||||
'\n' -> append("\\n")
|
||||
'\r' -> append("\\r")
|
||||
'\t' -> append("\\t")
|
||||
else -> if (ch < ' ') append("\\u%04x".format(ch.code)) else append(ch)
|
||||
}
|
||||
}
|
||||
append('"')
|
||||
}
|
||||
|
||||
private fun httpPostJson(endpoint: String, apiKey: String, body: String): String {
|
||||
val conn = URL(endpoint).openConnection() as HttpURLConnection
|
||||
try {
|
||||
conn.requestMethod = "POST"
|
||||
conn.connectTimeout = 15_000
|
||||
conn.readTimeout = 120_000
|
||||
conn.doOutput = true
|
||||
conn.setRequestProperty("Authorization", "Bearer $apiKey")
|
||||
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8")
|
||||
conn.setRequestProperty("X-DashScope-SSE", "disable")
|
||||
conn.outputStream.use { it.write(body.toByteArray(Charsets.UTF_8)) }
|
||||
val code = conn.responseCode
|
||||
val stream = if (code in 200..299) conn.inputStream else conn.errorStream
|
||||
val text = stream?.bufferedReader(Charsets.UTF_8)?.readText() ?: ""
|
||||
if (code !in 200..299) throw IllegalStateException("HTTP $code: ${text.take(200)}")
|
||||
return text
|
||||
} finally {
|
||||
conn.disconnect()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.haorui.app.crossplatform.compose
|
||||
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* 事实包构建器(M4,2026-11-15 定案,真机取证后修订路线顺序)。
|
||||
*
|
||||
* 真机取证(2026-11-15 v1 轮)三条通路实测:
|
||||
* 1. 裸 HTTP 拉 m.weibo.cn → **Sina Visitor System 游客墙**(无正文,电脑/手机同);
|
||||
* 2. 手机浏览器打开分享链 → 正文完整渲染**但 WebView 无 DOM 节点**(同头条自绘);
|
||||
* 3. OCR 读渲染页面 → 可行(正文已在屏上,Port 的 readPostOcrLines 管线现成)。
|
||||
* 因此:**OCR 全文提取为主路线**,分享链 HTTP 分支降级为实验性(访客墙放行时才有用)。
|
||||
*
|
||||
* 统一入口:OCR 全文提取(主)→ 分享链展开(实验,失败不阻塞)→ 两路都失败保留
|
||||
* DISCOVERED 并记录原因,不硬生成——“来源事实必须可回溯、不可回溯不进生产”。
|
||||
*
|
||||
* 事实包口径(跨平台自动发布设计):
|
||||
* - titleSeed:来源话题标题(任务 title,标题生成的参考);
|
||||
* - sourceText:来源正文全文(OCR 拼接或分享链 DOM);
|
||||
* - sourceRoute:正文取得路线(ocr / share_link),核验与排障依据;
|
||||
* - 关键数字/时间/对象在 ArticleComposer 的标题核验阶段从 [sourceText] 定位,
|
||||
* 本层不做语义抽取(模型层职责),只保证全文可回溯。
|
||||
*
|
||||
* 日志经 [logger] 注入(默认 no-op)——compose 层保持纯 JVM 可测,不直接依赖 RunLogger。
|
||||
*/
|
||||
class EvidenceBuilder(
|
||||
private val fetcher: ArticleFetcher = DEFAULT_FETCHER,
|
||||
private val logger: (String) -> Unit = {},
|
||||
) {
|
||||
/** 正文取得路线抽象(测试可注入假实现)。 */
|
||||
fun interface ArticleFetcher {
|
||||
/** 返回正文全文;失败返回 null。 */
|
||||
suspend fun fetch(sourceUrl: String, postId: String?): String?
|
||||
}
|
||||
/** 默认实现:微博分享链展开。 */
|
||||
companion object {
|
||||
val DEFAULT_FETCHER = ArticleFetcher { sourceUrl, postId ->
|
||||
val id = postId
|
||||
?: sourceUrl.substringAfter("weibo.com/", "").substringBefore('?')
|
||||
.takeIf { it.contains('/') }?.substringAfter('/')
|
||||
if (id.isNullOrBlank()) null else WeiboArticleFetcher.fetch(id)
|
||||
}
|
||||
}
|
||||
|
||||
/** 事实包。 */
|
||||
data class Evidence(
|
||||
val titleSeed: String,
|
||||
val sourceText: String,
|
||||
val sourceRoute: String,
|
||||
val fetchedAtMs: Long,
|
||||
)
|
||||
|
||||
/**
|
||||
* 构建事实包。
|
||||
* @param ocrLines OCR 兜底的全文行(Port 已采集的行;空=无兜底材料)。
|
||||
* @return null=两路都失败(原因写入 [failureReason])。
|
||||
*/
|
||||
var failureReason: String = ""
|
||||
private set
|
||||
|
||||
suspend fun build(
|
||||
titleSeed: String,
|
||||
sourceUrl: String,
|
||||
ocrLines: List<String>,
|
||||
nowMs: Long,
|
||||
): Evidence? = withContext(Dispatchers.IO) {
|
||||
failureReason = ""
|
||||
// 主路线:OCR 全文提取(真机取证:浏览器 WebView 无 DOM 节点,正文只能 OCR 读屏)
|
||||
val viaOcr = OcrArticleExtractor.extract(ocrLines)
|
||||
if (!viaOcr.isNullOrBlank()) {
|
||||
logger("事实包走 OCR 提取:${viaOcr.length} 字")
|
||||
return@withContext Evidence(titleSeed, viaOcr, "ocr", nowMs)
|
||||
}
|
||||
// 实验路线:分享链展开(裸 HTTP 会被 Sina Visitor System 拦截,仅在访客墙放行时有用)
|
||||
val viaLink = runCatching { fetcher.fetch(sourceUrl, null) }.getOrNull()
|
||||
if (!viaLink.isNullOrBlank() && viaLink.length >= 20) {
|
||||
logger("OCR 未取得,分享链展开兜底成功:${viaLink.length} 字")
|
||||
return@withContext Evidence(titleSeed, viaLink, "share_link", nowMs)
|
||||
}
|
||||
failureReason = buildString {
|
||||
append("正文不可得(OCR 提取")
|
||||
if (ocrLines.isEmpty()) append("无输入材料") else append("过短")
|
||||
append(";分享链展开被访客墙拦截或结构未命中)")
|
||||
}
|
||||
logger("事实包构建失败:$failureReason")
|
||||
null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.haorui.app.crossplatform.compose
|
||||
|
||||
/**
|
||||
* OCR 全文提取兜底(M4 EvidenceBuilder,2026-11-15 定案)。
|
||||
*
|
||||
* 输入:博文详情页逐屏 OCR 文本行(已按滑动顺序拼接)。
|
||||
* 提取规则按已核验的噪声形态(e1/e3 取证):
|
||||
* - 作者行(含时间 token/IP 属地/置顶/已编辑)整行剔除;
|
||||
* - 互动行(转发 N/评论 N/赞 N/热文指数/大家都在搜)剔除;
|
||||
* - 页面框架行(分享/问智搜/写回答/和当前N人一起讨论等)剔除;
|
||||
* - 其余行按序拼接为正文,过短(<20 字)视为提取失败。
|
||||
* 纯 JVM 逻辑,与 Port/OCR 引擎解耦,便于样本回归。
|
||||
*/
|
||||
object OcrArticleExtractor {
|
||||
/** 整行剔除模式(全匹配)。 */
|
||||
private val DROP_LINE_PATTERNS = listOf(
|
||||
Regex("""^(?:转发|评论|赞)\s*\d+.*$"""),
|
||||
Regex("""^.*\d{2}-\d{2}-\d{2}\s+\d{1,2}:\d{2}.*$"""), // 作者行(含时间 token)
|
||||
Regex("""^(?:置顶|已编辑|热文|热文指数.*|大家都在搜.*|关注|已关注|超话.*|.*级)$"""),
|
||||
Regex("""^(?:分享|问智搜|讨论|写回答|邀请回答|和当前\d+人一起讨论|.*人正在讨论|全屏|拍同款.*|跟拍同款视频|参与话题.*|展开|收起|全文|视频.*|直播.*|\d+/\d+)$"""),
|
||||
Regex("""^(?:点赞|评论|收藏|情感博主|颜值博主|搞笑幽默博主|娱乐博主|漫画家.*|.*博主)$"""),
|
||||
Regex("""^#{1,2}[^#]{1,30}#{1,2}$"""), // 独立话题行
|
||||
// 纯表情/标点行:JVM 正则无 \p{Emoji} 属性(ICU 扩展,Android 有而 JVM 无),
|
||||
// 改用 emoji 常用区段(U+1F300–U+1FAFF、U+2600–U+27BF)+ 标点 + 空白
|
||||
Regex("""^[\x{1F300}-\x{1FAFF}\x{2600}-\x{27BF}\p{Punct}\s]+$"""),
|
||||
)
|
||||
|
||||
/** 从 OCR 行序列提取正文;失败返回 null。
|
||||
* 逐屏拼接的重复行去重(半屏滑动会跨屏重复出现同行),保持首现顺序。 */
|
||||
fun extract(lines: List<String>): String? {
|
||||
val seen = HashSet<String>()
|
||||
val kept = lines.map { it.trim() }
|
||||
.filter { it.isNotEmpty() }
|
||||
.filterNot { line -> DROP_LINE_PATTERNS.any { it.matches(line) } }
|
||||
.filter { line -> seen.add(line) } // 首现保留,重复剔除
|
||||
val text = kept.joinToString("\n").trim()
|
||||
return text.takeIf { it.length >= 20 }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.haorui.app.crossplatform.compose
|
||||
|
||||
/**
|
||||
* AI 视频标题生成器(2026-11-19):转录文本(或 OCR 降级)→ 3 标题候选 → 三关核验。
|
||||
*
|
||||
* 与 ArticleComposer(图文标题链)同型:双 provider、三关核验、失败原因可证。
|
||||
* 差异点:
|
||||
* - 证据源是「音频转录文本」优先,OCR 详情文本降级(用户决策:接 ASR,音频转文字给 AI);
|
||||
* - 视频标题不带正文创作,只做标题候选(正文=视频本身);
|
||||
* - 核验口径复用:长度 2~30、非复读、数字一致不编造。
|
||||
*/
|
||||
object VideoTitleComposer {
|
||||
|
||||
/** 视频标题的证据源。转录文本优先;双源皆空则任务跳过(不凭空生成)。 */
|
||||
data class VideoEvidence(
|
||||
val transcriptText: String,
|
||||
val hotListTitle: String = "",
|
||||
val ocrDetailText: String = "",
|
||||
)
|
||||
|
||||
data class TitleResult(
|
||||
val selected: String,
|
||||
val rejectedReasons: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
const val TITLE_PROMPT =
|
||||
"你是短视频标题编辑。根据给定材料写 3 个今日头条视频标题候选。" +
|
||||
"要求:8~28 字,具体、有信息量、与材料事实一致;" +
|
||||
"不虚构数字/人名/地点;不复读原热榜标题;" +
|
||||
"只输出 JSON 数组字符串,如 [\"标题1\",\"标题2\",\"标题3\"]。"
|
||||
|
||||
var failureReason: String = ""
|
||||
private set
|
||||
|
||||
/**
|
||||
* 标题证据组装工厂(编排层便捷入口):按「转录优先」口径填三字段。
|
||||
* 纯函数不触依赖;DouyinVideoChain 等编排层用它把 Outcome 转成证据。
|
||||
*/
|
||||
fun buildEvidence(
|
||||
transcriptText: String,
|
||||
hotListTitle: String,
|
||||
ocrDetailText: String,
|
||||
): VideoEvidence = VideoEvidence(
|
||||
transcriptText = transcriptText,
|
||||
hotListTitle = hotListTitle,
|
||||
ocrDetailText = ocrDetailText,
|
||||
)
|
||||
|
||||
/** 生成标题候选并核验;null=模型失败或全不合格(调用方降级/跳过)。 */
|
||||
suspend fun composeTitles(
|
||||
evidence: VideoEvidence,
|
||||
configProvider: () -> Triple<String, String, String>, // (provider, apiKey, endpoint)
|
||||
logger: (String) -> Unit = {},
|
||||
): TitleResult? {
|
||||
failureReason = ""
|
||||
val materials = buildMaterials(evidence)
|
||||
if (materials == null) {
|
||||
failureReason = "转录与 OCR 文本皆空,无法生成视频标题"
|
||||
logger(failureReason)
|
||||
return null
|
||||
}
|
||||
val (provider, apiKey, endpoint) = configProvider()
|
||||
if (apiKey.isBlank()) {
|
||||
failureReason = "模型 Key 未配置,无法生成视频标题"
|
||||
logger(failureReason)
|
||||
return null
|
||||
}
|
||||
val model = if (provider == "qwen_plus") "qwen-plus" else "deepseek-chat"
|
||||
val body = """{"model":${composerJsonString(model)},""" +
|
||||
""""messages":[{"role":"system","content":${composerJsonString(TITLE_PROMPT)}},""" +
|
||||
"""{"role":"user","content":${composerJsonString(buildUserPrompt(evidence))}}],"stream": false}"""
|
||||
return try {
|
||||
val raw = composerHttpPost(endpoint, apiKey, body, 15_000, 120_000)
|
||||
val candidates = parseCandidates(raw)
|
||||
verify(candidates, evidence)?.also { logger("视频标题生成成功:${it.selected}") }
|
||||
?: run {
|
||||
failureReason = "候选全部不合格:${rejectedReasons.joinToString(";")}"
|
||||
logger(failureReason)
|
||||
null
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
failureReason = "视频标题生成异常:${e.message ?: e.javaClass.simpleName}"
|
||||
logger(failureReason)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
internal var rejectedReasons: List<String> = emptyList()
|
||||
|
||||
/** 组装用户提示词:转录优先,转录为空降级 OCR;热榜标题始终带上(供 AI 参考)。 */
|
||||
internal fun buildUserPrompt(evidence: VideoEvidence): String = buildString {
|
||||
if (evidence.transcriptText.isNotBlank()) {
|
||||
append("视频语音转录:\n").append(evidence.transcriptText.take(2000)).append('\n')
|
||||
} else if (evidence.ocrDetailText.isNotBlank()) {
|
||||
append("视频页面文字:\n").append(evidence.ocrDetailText.take(2000)).append('\n')
|
||||
}
|
||||
if (evidence.hotListTitle.isNotBlank()) {
|
||||
append("热榜词条:").append(evidence.hotListTitle)
|
||||
}
|
||||
}
|
||||
|
||||
/** 双源皆空返回 null(不生成)。 */
|
||||
internal fun buildMaterials(evidence: VideoEvidence): String? {
|
||||
return when {
|
||||
evidence.transcriptText.isNotBlank() -> evidence.transcriptText
|
||||
evidence.ocrDetailText.isNotBlank() -> evidence.ocrDetailText
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
/** 解析 AI 返回的 JSON 数组候选(容错:trim/非字符串跳过)。 */
|
||||
internal fun parseCandidates(raw: String): List<String> {
|
||||
val trimmed = raw.trim()
|
||||
if (!trimmed.startsWith("[")) return emptyList()
|
||||
return listOf<String>().let {
|
||||
// 手动解析数组字符串(与 ArticleComposer.parseCandidates 同口径,不引 JSON 库)
|
||||
val inner = trimmed.removePrefix("[").removeSuffix("]")
|
||||
Regex("\"((?:[^\"\\\\]|\\\\.)*)\"").findAll(inner).mapNotNull { m ->
|
||||
val s = m.groupValues[1]
|
||||
.replace("\\\"", "\"")
|
||||
.replace("\\\\", "\\")
|
||||
.trim()
|
||||
s.takeIf { it.isNotEmpty() }
|
||||
}.toList()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 三关核验(与图文标题同口径):
|
||||
* 1) 长度 2~30 字;2) 非复读热榜标题;3) 数字一致(标题数字必须出现在证据材料中)。
|
||||
* 选中首个合格候选;全部不合格返回 null(rejectedReasons 留存)。
|
||||
*/
|
||||
internal fun verify(candidates: List<String>, evidence: VideoEvidence): TitleResult? {
|
||||
val reasons = mutableListOf<String>()
|
||||
val materials = buildMaterials(evidence).orEmpty()
|
||||
for (candidate in candidates) {
|
||||
val c = candidate.trim()
|
||||
if (c.length < 2 || c.length > 30) {
|
||||
reasons.add("「$c」长度${c.length}越界")
|
||||
continue
|
||||
}
|
||||
if (evidence.hotListTitle.isNotBlank() &&
|
||||
c.replace(" ", "") == evidence.hotListTitle.replace(" ", "")
|
||||
) {
|
||||
reasons.add("「$c」复读热榜标题")
|
||||
continue
|
||||
}
|
||||
// 数字一致关:标题中的数字串必须能在材料中找到(防编造统计/数量)
|
||||
val numbers = Regex("\\d+").findAll(c).map { it.value }.toList()
|
||||
val fabricated = numbers.firstOrNull { n -> !materials.contains(n) }
|
||||
if (fabricated != null) {
|
||||
reasons.add("「$c」数字 $fabricated 材料中不存在")
|
||||
continue
|
||||
}
|
||||
return TitleResult(selected = c, rejectedReasons = reasons.toList())
|
||||
}
|
||||
rejectedReasons = reasons
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.haorui.app.crossplatform.compose
|
||||
|
||||
import com.haorui.app.automation.RunLogger
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.BufferedReader
|
||||
import java.io.InputStreamReader
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
/**
|
||||
* 微博分享链正文展开器(M4 EvidenceBuilder 主路线,2026-11-15 定案)。
|
||||
*
|
||||
* `https://weibo.com/<UID>/<博文ID>` → 移动版网页 `m.weibo.cn/status/<博文ID>` →
|
||||
* 网页版正文为标准 HTML(无需登录的公开博文)。纯网络层实现(HttpURLConnection,与
|
||||
* AiRewriteService 同栈),不起 WebView、不建电脑后台服务——符合纯手机架构纪律。
|
||||
*
|
||||
* 正文提取按已核验的移动版页面结构(text 节点:wbpro-layer-text / detail-wb-text 等
|
||||
* class 家族);结构不符时返回 null 交由 OCR 兜底——不猜、不硬解。
|
||||
* 未登录可见性受限的博文(博主设置仅粉丝可见等)返回 null 并记录原因。
|
||||
*/
|
||||
object WeiboArticleFetcher {
|
||||
private const val TAG = "HaoRui-Evidence"
|
||||
private const val CONNECT_TIMEOUT_MS = 15_000
|
||||
private const val READ_TIMEOUT_MS = 20_000
|
||||
|
||||
/** 移动版正文容器的 class 特征(取证口径,多个候选按出现序取首个非空)。 */
|
||||
private val CONTENT_CLASS_PATTERNS = listOf(
|
||||
Regex("""class="[^"]*\b(?:wbpro-layer-text|detail-wb-text|weibo-text)\b[^"]*"[^>]*>(.*?)</(?:div|p)>""",
|
||||
RegexOption.DOT_MATCHES_ALL),
|
||||
Regex("""<div[^>]*class="[^"]*(?:wbpro-layer-text|detail-wb-text|weibo-text)[^"]*"[^>]*>([\s\S]*?)</div>"""),
|
||||
)
|
||||
|
||||
/** 展开博文正文;失败/不可见返回 null(日志说明原因),不抛异常。 */
|
||||
suspend fun fetch(postId: String): String? = withContext(Dispatchers.IO) {
|
||||
val url = "https://m.weibo.cn/status/$postId"
|
||||
try {
|
||||
val conn = URL(url).openConnection() as HttpURLConnection
|
||||
try {
|
||||
conn.requestMethod = "GET"
|
||||
// 移动版 UA(桌面 UA 会被 302 到登录墙)
|
||||
conn.setRequestProperty("User-Agent",
|
||||
"Mozilla/5.0 (Linux; Android 12; V1981A) AppleWebKit/537.36 (KHTML, like Gecko) " +
|
||||
"Chrome/120.0.0.0 Mobile Safari/537.36")
|
||||
conn.setRequestProperty("Accept", "text/html,application/xhtml+xml")
|
||||
conn.connectTimeout = CONNECT_TIMEOUT_MS
|
||||
conn.readTimeout = READ_TIMEOUT_MS
|
||||
val code = conn.responseCode
|
||||
if (code !in 200..299) {
|
||||
RunLogger.w(TAG, "分享链展开 HTTP $code(postId=$postId)")
|
||||
return@withContext null
|
||||
}
|
||||
val html = BufferedReader(InputStreamReader(conn.inputStream, Charsets.UTF_8)).use { it.readText() }
|
||||
extractContent(html) ?: run {
|
||||
RunLogger.w(TAG, "分享链展开成功但正文结构未命中(postId=$postId,len=${html.length})")
|
||||
null
|
||||
}
|
||||
} finally {
|
||||
conn.disconnect()
|
||||
}
|
||||
} catch (e: kotlin.coroutines.cancellation.CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
RunLogger.w(TAG, "分享链展开异常: ${e.javaClass.simpleName}:${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/** 从移动版 HTML 提取正文纯文本;结构不符返回 null。 */
|
||||
internal fun extractContent(html: String): String? {
|
||||
for (pattern in CONTENT_CLASS_PATTERNS) {
|
||||
val match = pattern.find(html) ?: continue
|
||||
val text = stripTags(match.groupValues[1]).trim()
|
||||
if (text.length >= 20) return text // 过短的命中视为误配(导航/按钮文案)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** HTML 转纯文本:去标签、解常见实体、合并空白(块级标签统一产出换行)。 */
|
||||
internal fun stripTags(htmlFragment: String): String = htmlFragment
|
||||
.replace(Regex("<br\\s*/?>"), "\n")
|
||||
.replace(Regex("</p>"), "\n")
|
||||
.replace(Regex("<p[^>]*>"), "\n")
|
||||
.replace(Regex("<div[^>]*>"), "\n")
|
||||
.replace(Regex("</div>"), "\n")
|
||||
.replace(Regex("<[^>]+>"), "")
|
||||
.replace(" ", " ")
|
||||
.replace("&", "&")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
.replace(""", "\"")
|
||||
.replace("'", "'")
|
||||
.replace(Regex("[ \\t]+"), " ")
|
||||
.replace(Regex("\\n{3,}"), "\n\n")
|
||||
.trim()
|
||||
}
|
||||
@@ -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,459 @@
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除任务及其全部关联记录(额度台账、提交尝试、素材记录,按外键依赖顺序)。
|
||||
* 任何状态都可删;UNKNOWN/待核对任务删除即放弃核对保护并释放其占用的额度,调用方 UI 必须先二次确认。
|
||||
* 事件表不连带删(同事件可能被图文/视频共用)。返回被删任务与素材文件路径(含资产记录),
|
||||
* 媒体文件由调用方在事务外自行处置(需再核对本机保护清单,避免误删旧链路 UNKNOWN 提交引用的素材)。
|
||||
*/
|
||||
suspend fun deleteTask(id: String): DeletedTask? = write { db ->
|
||||
val t = task(db, id) ?: return@write null
|
||||
val assetPaths = db.query("assets", null, "task_id=?", arrayOf(id), null, null, null).use { c ->
|
||||
buildList { while (c.moveToNext()) add(c.s("local_path")) }
|
||||
}
|
||||
db.execSQL("DELETE FROM quota_ledger WHERE attempt_id IN (SELECT id FROM attempts WHERE task_id=?)", arrayOf(id))
|
||||
db.execSQL("DELETE FROM attempts WHERE task_id=?", arrayOf(id))
|
||||
db.execSQL("DELETE FROM assets WHERE task_id=?", arrayOf(id))
|
||||
db.execSQL("DELETE FROM tasks WHERE id=?", arrayOf(id))
|
||||
DeletedTask(t, (assetPaths + t.mediaPath).filter { it.isNotBlank() }.distinct())
|
||||
}
|
||||
|
||||
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。
|
||||
* ⚠️ 2026-11-17 真机实锤:归 PAUSED 且 resume_state=NULL 造成孤儿 PAUSED——
|
||||
* 重采撞幂等键时 resumeTask 恒 false、三跳全拒,任务永远卡死。
|
||||
* 「明确未提交」是确定性结论(未进编辑器/写入失败/桥拒绝,页面无成品残留),
|
||||
* 按「不会自动回到 READY」的设计意图归终态 SKIPPED(可在任务页手动删除)。 */
|
||||
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.SKIPPED, "已核对未提交:${evidenceRef.take(40)}")
|
||||
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)) } }
|
||||
}
|
||||
|
||||
/** 全部 RESULT_UNKNOWN 任务的 id(草稿核对器遍历用;M6 恢复场景)。 */
|
||||
suspend fun unknownTaskIds(): List<String> = read { db ->
|
||||
db.query("tasks", arrayOf("id"), "state='RESULT_UNKNOWN'", null, null, null, "updated_at").use { c ->
|
||||
buildList { while (c.moveToNext()) add(c.getString(0)) }
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
/** 删除任务的结果:被删任务快照 + 事务外待处置的素材文件路径(调用方自行核对保护清单后处置) */
|
||||
data class DeletedTask(val task: CrossPublishTask, val mediaPaths: List<String>)
|
||||
|
||||
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,128 @@
|
||||
package com.haorui.app.crossplatform.media
|
||||
|
||||
import android.media.MediaExtractor
|
||||
import android.media.MediaFormat
|
||||
import com.haorui.app.crossplatform.compose.AsrTranscriber
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
|
||||
/**
|
||||
* 音轨提取器(2026-11-19):MP4 → 独立音频文件(m4a),供 ASR 转写。
|
||||
*
|
||||
* 输入是「保存本地」落盘的相册视频(见 douyin-save-local-file-shape 记忆:
|
||||
* DCIM/Camera/share_*.mp4,H.264+AAC 双轨)。提取音轨(不解码重编码——
|
||||
* 直接搬运 AAC 压缩帧),输出 MP4 容器裸流(.m4a,dashscope 官方支持格式)。
|
||||
*
|
||||
* 设计口径:
|
||||
* - 只搬轨道不转码:MediaExtractor.selectTrack 音轨 → writeSampleData 到
|
||||
* MediaMuxer,零解码,速度≈IO 速度,输出质量无损;
|
||||
* - ASR 上限 5 分钟(AsrTranscriber.MAX_DURATION_MS):超限直接拒绝不提取,
|
||||
* 调用方降级 OCR 文案路线;
|
||||
* - 输出文件由调用方管理生命周期(转写完即删,与素材按设计删除的口径一致);
|
||||
* - MediaExtractor/MediaMuxer 手动 try/finally 释放(非 AutoCloseable,
|
||||
* VideoFileValidator 同款教训)。
|
||||
*/
|
||||
object AudioTrackExtractor {
|
||||
|
||||
/** 提取失败原因(调用方记入任务未知/跳过)。 */
|
||||
data class Report(
|
||||
val ok: Boolean,
|
||||
val reason: String = "",
|
||||
val outputPath: String = "",
|
||||
val durationMs: Long = 0,
|
||||
val sizeBytes: Long = 0,
|
||||
)
|
||||
|
||||
/**
|
||||
* 从视频文件提取音轨到指定输出路径(.m4a)。
|
||||
* @param inputPath 已落盘视频(须存在且可读)
|
||||
* @param outputPath 输出音频文件路径(调用方保证父目录存在;已存在则覆盖)
|
||||
*/
|
||||
fun extract(inputPath: String, outputPath: String): Report {
|
||||
val input = File(inputPath)
|
||||
if (!input.exists() || !input.isFile) return Report(false, "输入文件不存在: $inputPath")
|
||||
if (input.length() <= 0) return Report(false, "输入文件为空")
|
||||
|
||||
// 时长预检:超 ASR 上限不提取(省一次无谓 IO)
|
||||
val durationMs = probeDurationMs(input)
|
||||
?: return Report(false, "时长探测失败(MediaMetadataRetriever 解析异常)")
|
||||
if (durationMs <= 0) return Report(false, "时长非法: ${durationMs}ms")
|
||||
if (durationMs > AsrTranscriber.MAX_DURATION_MS) {
|
||||
return Report(false, "时长 ${durationMs / 1000}s 超过 ASR 上限 5 分钟")
|
||||
}
|
||||
|
||||
var extractor: MediaExtractor? = null
|
||||
var muxer: android.media.MediaMuxer? = null
|
||||
try {
|
||||
extractor = MediaExtractor()
|
||||
extractor.setDataSource(input.absolutePath)
|
||||
|
||||
var audioTrackIndex = -1
|
||||
var audioFormat: MediaFormat? = null
|
||||
for (i in 0 until extractor.trackCount) {
|
||||
val format = extractor.getTrackFormat(i)
|
||||
val mime = format.getString(MediaFormat.KEY_MIME).orEmpty()
|
||||
if (mime.startsWith("audio/")) {
|
||||
audioTrackIndex = i
|
||||
audioFormat = format
|
||||
break
|
||||
}
|
||||
}
|
||||
if (audioTrackIndex < 0 || audioFormat == null) {
|
||||
return Report(false, "无音轨(视频可能为静音素材)")
|
||||
}
|
||||
|
||||
extractor.selectTrack(audioTrackIndex)
|
||||
muxer = android.media.MediaMuxer(
|
||||
outputPath,
|
||||
android.media.MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4,
|
||||
)
|
||||
val muxTrack = muxer.addTrack(audioFormat)
|
||||
muxer.start()
|
||||
|
||||
val buffer = java.nio.ByteBuffer.allocate(512 * 1024)
|
||||
val info = android.media.MediaCodec.BufferInfo()
|
||||
var written = 0
|
||||
while (true) {
|
||||
info.offset = 0
|
||||
info.size = extractor.readSampleData(buffer, 0)
|
||||
if (info.size < 0) break
|
||||
info.presentationTimeUs = extractor.sampleTime
|
||||
info.flags = extractor.sampleFlags
|
||||
muxer.writeSampleData(muxTrack, buffer, info)
|
||||
written += info.size
|
||||
extractor.advance()
|
||||
}
|
||||
if (written == 0) return Report(false, "音轨零样本(提取结果为空)")
|
||||
val outSize = File(outputPath).length()
|
||||
if (outSize <= 0) return Report(false, "输出文件为空")
|
||||
return Report(
|
||||
ok = true,
|
||||
outputPath = outputPath,
|
||||
durationMs = durationMs,
|
||||
sizeBytes = outSize,
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
return Report(false, "音轨提取异常:${e.message ?: e.javaClass.simpleName}")
|
||||
} finally {
|
||||
runCatching { muxer?.stop() }
|
||||
runCatching { muxer?.release() }
|
||||
runCatching { extractor?.release() }
|
||||
}
|
||||
}
|
||||
|
||||
/** 探测时长(MediaMetadataRetriever,VideoFileValidator 同款口径);失败返回 null。 */
|
||||
private fun probeDurationMs(file: File): Long? {
|
||||
var retriever: android.media.MediaMetadataRetriever? = null
|
||||
return try {
|
||||
retriever = android.media.MediaMetadataRetriever()
|
||||
retriever.setDataSource(file.absolutePath)
|
||||
retriever.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION)
|
||||
?.toLongOrNull()
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
} finally {
|
||||
runCatching { retriever?.release() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.haorui.app.crossplatform.media
|
||||
|
||||
/**
|
||||
* 跨平台视频加工管线(M5,2026-11-15):文件 → 校验 → 许可 → 简介 → 成品。
|
||||
*
|
||||
* 设计口径(跨平台自动发布设计 §视频转载):
|
||||
* 链路为 筛选 -> 许可核验 -> 媒体获取 -> 文件及内容检查 -> 标题简介与署名 -> 去重 -> 发布。
|
||||
* 本类覆盖「许可核验→文件检查→简介署名」三段(筛选在 TopicPolicy、发布在 VideoTaskBridge)。
|
||||
*
|
||||
* 失败语义(固定决策 6):
|
||||
* - 校验失败/无许可 → 拒绝(reason 明确,任务 SKIPPED);
|
||||
* - 需署名但署名缺失 → 拒绝(不放行不合规转载);
|
||||
* - 校验通过 → 产出 [PreparedVideo](sha256/时长/简介齐备,供任务落库与发布桥接)。
|
||||
*
|
||||
* 纯编排(校验器/许可库经构造注入),JVM 可测。
|
||||
*/
|
||||
class CrossVideoPipeline(
|
||||
private val licenseStore: MediaLicenseStore,
|
||||
private val logger: (String) -> Unit = {},
|
||||
) {
|
||||
|
||||
/** 加工成品。 */
|
||||
data class PreparedVideo(
|
||||
val localPath: String,
|
||||
val sha256: String,
|
||||
val durationMs: Long,
|
||||
val sizeBytes: Long,
|
||||
val rightsRef: String,
|
||||
val caption: String,
|
||||
/** 需署名(发布页无法署名时任务在发布前跳过)。 */
|
||||
val needsAttribution: Boolean,
|
||||
)
|
||||
|
||||
/** 加工结果:rejected=true 时 reason 给出跳过原因。 */
|
||||
data class Outcome(
|
||||
val prepared: PreparedVideo?,
|
||||
val reason: String = "",
|
||||
) {
|
||||
companion object {
|
||||
fun reject(reason: String) = Outcome(null, reason)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加工已落盘的视频文件。
|
||||
* @param ownerKey 素材归属账号 key(自有判定)。
|
||||
* @param sourceHost 来源域名(授权判定;null=未知来源)。
|
||||
* @param baseCaption 业务简介(标题外描述)。
|
||||
* @param attribution 署名信息(授权要求署名时必填)。
|
||||
* @param nowMs 当前时刻(授权有效期)。
|
||||
*/
|
||||
fun prepare(
|
||||
localPath: String,
|
||||
ownerKey: String,
|
||||
sourceHost: String?,
|
||||
baseCaption: String,
|
||||
attribution: VideoCaptionPolicy.Attribution?,
|
||||
nowMs: Long,
|
||||
): Outcome {
|
||||
// ① 文件硬校验(异常不放行)
|
||||
val report = VideoFileValidator.validate(localPath)
|
||||
if (!report.ok) {
|
||||
logger("视频校验拒绝:${report.reason}")
|
||||
return Outcome.reject("视频校验未通过:${report.reason}")
|
||||
}
|
||||
// ② 许可匹配(能下载 ≠ 能转发)
|
||||
val match = licenseStore.match(ownerKey, sourceHost, nowMs)
|
||||
if (match == null) {
|
||||
logger("许可缺失:owner=$ownerKey host=$sourceHost")
|
||||
return Outcome.reject("素材许可缺失(owner=$ownerKey,source=${sourceHost ?: "未知"})")
|
||||
}
|
||||
// ③ 简介署名(需署名但信息缺失 → 拒绝)
|
||||
val caption = VideoCaptionPolicy.build(baseCaption, match, attribution)
|
||||
if (caption == null) {
|
||||
logger("署名信息缺失,任务拒绝")
|
||||
return Outcome.reject("需署名转载但署名信息缺失")
|
||||
}
|
||||
val prepared = PreparedVideo(
|
||||
localPath = localPath,
|
||||
sha256 = report.sha256,
|
||||
durationMs = report.durationMs,
|
||||
sizeBytes = report.sizeBytes,
|
||||
rightsRef = match.license.id,
|
||||
caption = caption,
|
||||
needsAttribution = match.needsAttribution,
|
||||
)
|
||||
logger("视频加工完成:sha=${prepared.sha256.take(12)}… 时长=${prepared.durationMs / 1000}s 许可=${prepared.rightsRef}")
|
||||
return Outcome(prepared)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.haorui.app.crossplatform.media
|
||||
|
||||
import android.content.ContentUris
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.provider.MediaStore
|
||||
|
||||
/**
|
||||
* 抖音「保存本地」相册定位器(2026-11-19,douyin-save-local-file-shape 取证口径)。
|
||||
*
|
||||
* 职责:在 MediaStore 中定位抖音刚保存的视频条目,交给 [SourceMediaProvider] 导入。
|
||||
* 只做**查询**(把 MediaStore 行转成 content URI + 候选清单),不做搬运——
|
||||
* 搬运/去重/校验仍是 SourceMediaProvider 与 VideoFileValidator 的职责。
|
||||
*
|
||||
* 定位双条件(取证实锤):
|
||||
* 1. 时间窗:`date_modified >= savedSinceMs`(保存动作发生时刻)——排除用户历史视频;
|
||||
* 2. 命名前缀:`_display_name LIKE 'share_%.mp4'`——抖音保存命名
|
||||
* `share_<32位MD5><13位毫秒时间戳>.mp4`(DCIM/Camera);
|
||||
* 相册可能残留用户更早的 share_* 文件,只靠前缀会误取——时间窗是硬条件。
|
||||
*/
|
||||
class DouyinSavedVideoLocator(private val context: Context) {
|
||||
|
||||
/** 候选条目(按 date_modified 降序——最新优先)。 */
|
||||
data class Candidate(
|
||||
val uri: Uri,
|
||||
val displayName: String,
|
||||
val sizeBytes: Long,
|
||||
val dateModifiedSec: Long,
|
||||
val durationMs: Long,
|
||||
val relativePath: String?,
|
||||
)
|
||||
|
||||
/**
|
||||
* 查询保存时间窗之后的 share_*.mp4 候选。
|
||||
* @param savedSinceMs 保存动作开始时刻(epoch ms;与 date_modified 秒比较时取 floor)
|
||||
* @return 候选列表(可能为空=未找到;调用方提示用户/降级)。
|
||||
*/
|
||||
fun findSavedVideos(savedSinceMs: Long): List<Candidate> {
|
||||
val savedSinceSec = savedSinceMs / 1000
|
||||
val projection = arrayOf(
|
||||
MediaStore.Video.Media._ID,
|
||||
MediaStore.Video.Media.DISPLAY_NAME,
|
||||
MediaStore.Video.Media.SIZE,
|
||||
MediaStore.Video.Media.DATE_MODIFIED,
|
||||
MediaStore.Video.Media.DURATION,
|
||||
MediaStore.Video.Media.RELATIVE_PATH,
|
||||
)
|
||||
val selection = "${MediaStore.Video.Media.DISPLAY_NAME} LIKE ? AND " +
|
||||
"${MediaStore.Video.Media.DATE_MODIFIED} >= ?"
|
||||
val selectionArgs = arrayOf("share_%.mp4", savedSinceSec.toString())
|
||||
val sortOrder = "${MediaStore.Video.Media.DATE_MODIFIED} DESC"
|
||||
val out = mutableListOf<Candidate>()
|
||||
try {
|
||||
context.contentResolver.query(
|
||||
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
|
||||
projection, selection, selectionArgs, sortOrder,
|
||||
)?.use { cursor ->
|
||||
while (cursor.moveToNext()) {
|
||||
val id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID))
|
||||
val name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME)) ?: ""
|
||||
val size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE))
|
||||
val dateSec = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_MODIFIED))
|
||||
val durationMs = try {
|
||||
cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION))
|
||||
} catch (e: Exception) {
|
||||
0L // DURATION 个别机型可能缺列,0=未知(VideoFileValidator 会再校验)
|
||||
}
|
||||
val relPath = try {
|
||||
cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.RELATIVE_PATH))
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
out += Candidate(
|
||||
uri = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id),
|
||||
displayName = name,
|
||||
sizeBytes = size,
|
||||
dateModifiedSec = dateSec,
|
||||
durationMs = durationMs,
|
||||
relativePath = relPath,
|
||||
)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
// 查询失败(权限拒绝等)返回空——调用方按「未找到」处理,不假装成功
|
||||
return emptyList()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 首个候选的 content URI(时间窗内最新一条);无候选返回 null。 */
|
||||
fun firstSavedUri(savedSinceMs: Long): Uri? = findSavedVideos(savedSinceMs).firstOrNull()?.uri
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.haorui.app.crossplatform.media
|
||||
|
||||
import com.haorui.app.crossplatform.compose.AsrTranscriber
|
||||
import com.haorui.app.crossplatform.compose.VideoTitleComposer
|
||||
|
||||
/**
|
||||
* 抖音视频链编排器(2026-11-19):保存本地产物 → ASR 标题素材。
|
||||
*
|
||||
* 串联五段(各段职责独立,失败即短路并给出可归因原因):
|
||||
* 相册定位(DouyinSavedVideoLocator)→ 私有目录导入(SourceMediaProvider)
|
||||
* → 文件硬校验(VideoFileValidator)→ 音轨提取(AudioTrackExtractor)
|
||||
* → ASR 转写(AsrTranscriber)→ 视频标题素材(VideoTitleComposer.VideoEvidence)
|
||||
*
|
||||
* 设计口径:
|
||||
* - 任何一段失败返回 Failed,reason 归因到段名——任务侧按未知/跳过处理,不硬重试;
|
||||
* - 转写失败降级:ASR 失败仍返回 success(transcriptText 空 + failureReason 记录),
|
||||
* 标题链可走 OCR 降级路线(VideoTitleComposer 内置降级)——音频是增益不是硬依赖;
|
||||
* - 音频临时文件转写后即删(素材生命周期与草稿核对口径一致);
|
||||
* - 视频 SHA-256 返回给调用方(幂等键/去重联动)。
|
||||
*/
|
||||
class DouyinVideoChain(
|
||||
private val mediaProvider: SourceMediaProvider,
|
||||
private val locator: DouyinSavedVideoLocator,
|
||||
private val logger: (String) -> Unit = {},
|
||||
) {
|
||||
|
||||
/** 编排结果。 */
|
||||
data class Outcome(
|
||||
val ok: Boolean,
|
||||
val stage: String = "",
|
||||
val reason: String = "",
|
||||
val videoPath: String = "",
|
||||
val videoSha256: String = "",
|
||||
val audioPath: String = "",
|
||||
val transcriptText: String = "",
|
||||
val transcriptFailure: String = "",
|
||||
)
|
||||
|
||||
/**
|
||||
* 从「保存本地」产物跑完整链到标题素材。
|
||||
* @param savedSinceMs 保存动作开始时刻(epoch ms,定位时间窗起点)
|
||||
* @param asrApiKey dashscope Key(复用 qwen 配置;空=跳过转写走 OCR 降级)
|
||||
*/
|
||||
fun run(
|
||||
savedSinceMs: Long,
|
||||
hotListTitle: String,
|
||||
ocrDetailText: String,
|
||||
asrApiKey: String,
|
||||
asrWorkspaceId: String = "",
|
||||
): Outcome {
|
||||
// 1) 相册定位
|
||||
val candidate = locator.findSavedVideos(savedSinceMs).firstOrNull()
|
||||
?: return Outcome(false, stage = "LOCATE", reason = "时间窗内未找到 share_*.mp4(保存未发生或权限拒绝)")
|
||||
logger("视频链 LOCATE:${candidate.displayName} ${candidate.sizeBytes / 1024}KB")
|
||||
|
||||
// 2) 私有目录导入(搬运+SHA-256+去重)
|
||||
val imported = when (val r = mediaProvider.importFrom(candidate.uri, "douyin-saved")) {
|
||||
is SourceMediaProvider.Result.Imported -> r
|
||||
is SourceMediaProvider.Result.Rejected -> return Outcome(false, stage = "IMPORT", reason = r.reason)
|
||||
}
|
||||
logger("视频链 IMPORT:sha=${imported.sha256.take(12)}…")
|
||||
|
||||
// 3) 文件硬校验(MP4/双轨/时长窗口)
|
||||
val check = VideoFileValidator.validate(imported.localPath)
|
||||
if (!check.ok) {
|
||||
return Outcome(false, stage = "VALIDATE", reason = check.reason, videoPath = imported.localPath)
|
||||
}
|
||||
|
||||
// 4) 音轨提取
|
||||
val audioPath = imported.localPath.removeSuffix(".mp4") + ".m4a"
|
||||
val audio = AudioTrackExtractor.extract(imported.localPath, audioPath)
|
||||
if (!audio.ok) {
|
||||
return Outcome(
|
||||
false, stage = "AUDIO", reason = audio.reason,
|
||||
videoPath = imported.localPath, videoSha256 = imported.sha256,
|
||||
)
|
||||
}
|
||||
logger("视频链 AUDIO:${audio.sizeBytes / 1024}KB ${audio.durationMs}ms")
|
||||
|
||||
// 5) ASR 转写(失败降级不短路——标题链有 OCR 兜底)
|
||||
var transcript = ""
|
||||
var transcriptFailure = ""
|
||||
if (asrApiKey.isNotBlank()) {
|
||||
val bytes = try {
|
||||
java.io.File(audioPath).readBytes()
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
if (bytes == null) {
|
||||
transcriptFailure = "音频文件读取失败"
|
||||
} else {
|
||||
val result = AsrTranscriber.transcribe(bytes, "m4a", asrApiKey, asrWorkspaceId)
|
||||
if (result.text != null) {
|
||||
transcript = result.text
|
||||
logger("视频链 ASR:转写 ${result.text.length} 字")
|
||||
} else {
|
||||
transcriptFailure = result.failureReason
|
||||
logger("视频链 ASR 失败(降级 OCR 路线):${result.failureReason}")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
transcriptFailure = "ASR Key 未配置(走 OCR 降级)"
|
||||
}
|
||||
|
||||
// 音频临时文件转写后即删(无论成败——素材生命周期口径)
|
||||
runCatching { java.io.File(audioPath).delete() }
|
||||
|
||||
// 6) 标题素材组装(VideoTitleComposer 消费)
|
||||
return Outcome(
|
||||
ok = true,
|
||||
stage = "DONE",
|
||||
videoPath = imported.localPath,
|
||||
videoSha256 = imported.sha256,
|
||||
audioPath = "",
|
||||
transcriptText = transcript,
|
||||
transcriptFailure = transcriptFailure,
|
||||
).also {
|
||||
logger("视频链 DONE:视频 ${imported.localPath};转录 ${transcript.length} 字" +
|
||||
(if (transcriptFailure.isNotBlank()) ";转录降级[$transcriptFailure]" else ""))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package com.haorui.app.crossplatform.media
|
||||
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* 素材许可库(M5,2026-11-15):自有或获许可视频的唯一判定入口。
|
||||
*
|
||||
* 设计口径(跨平台自动发布设计 §视频转载):
|
||||
* - 许可按**自有账号或批量授权**初始化,系统按作品、目的平台、有效期及署名条件匹配;
|
||||
* - 「读取/保存权限」与「跨平台发布许可」分别判断——能下载 ≠ 能转发;
|
||||
* - 没有匹配许可的视频一律不放行(固定决策 7:视频以自有或获得许可的转载为目标)。
|
||||
*
|
||||
* 首版实现:内存库 + JSON 持久化(filesDir/crossplatform/licenses.json);
|
||||
* 许可来源两类:
|
||||
* - OWN(自有):按账号 key 匹配,永不过期;
|
||||
* - GRANTED(授权):按来源域名+署名条件+有效期匹配。
|
||||
*
|
||||
* 纯 JVM 逻辑(持久化经 [store] 注入),可测。
|
||||
*/
|
||||
class MediaLicenseStore(
|
||||
private val store: ((String) -> Unit)? = null,
|
||||
private val load: (() -> List<MediaLicense>)? = null,
|
||||
) {
|
||||
|
||||
/** 许可类型。 */
|
||||
enum class Kind { OWN, GRANTED }
|
||||
|
||||
/** 单条许可记录。 */
|
||||
data class MediaLicense(
|
||||
val id: String,
|
||||
val kind: Kind,
|
||||
/** OWN:账号 key;GRANTED:来源域名。 */
|
||||
val subject: String,
|
||||
/** GRANTED:要求署名。 */
|
||||
val requiresAttribution: Boolean = false,
|
||||
/** GRANTED:有效期起点(ms);0=不限定。 */
|
||||
val validFromMs: Long = 0,
|
||||
/** GRANTED:有效期终点(ms);0=不过期。 */
|
||||
val validUntilMs: Long = 0,
|
||||
val note: String = "",
|
||||
)
|
||||
|
||||
/** 许可匹配结果。 */
|
||||
data class Match(
|
||||
val license: MediaLicense,
|
||||
/** GRANTED 且要求署名时为 true——发布页无法署名时任务跳过(设计口径)。 */
|
||||
val needsAttribution: Boolean,
|
||||
)
|
||||
|
||||
private val licenses = mutableListOf<MediaLicense>().apply {
|
||||
load?.let { addAll(it()) }
|
||||
}
|
||||
|
||||
/** 登记自有素材许可(按账号 key;幂等——同 subject 重复登记返回已有项)。 */
|
||||
fun registerOwn(subject: String, note: String = ""): MediaLicense {
|
||||
findOwn(subject)?.let { return it }
|
||||
val license = MediaLicense(
|
||||
id = "own-${subject.hashCode().toString(16)}",
|
||||
kind = Kind.OWN,
|
||||
subject = subject,
|
||||
note = note,
|
||||
)
|
||||
licenses += license
|
||||
persist()
|
||||
return license
|
||||
}
|
||||
|
||||
/** 登记授权许可(按来源域名+署名条件+有效期)。 */
|
||||
fun registerGranted(
|
||||
subject: String,
|
||||
requiresAttribution: Boolean,
|
||||
validFromMs: Long,
|
||||
validUntilMs: Long,
|
||||
note: String = "",
|
||||
): MediaLicense {
|
||||
val license = MediaLicense(
|
||||
id = "granted-${subject.hashCode().toString(16)}-${validUntilMs.toString(16)}",
|
||||
kind = Kind.GRANTED,
|
||||
subject = subject,
|
||||
requiresAttribution = requiresAttribution,
|
||||
validFromMs = validFromMs,
|
||||
validUntilMs = validUntilMs,
|
||||
note = note,
|
||||
)
|
||||
licenses += license
|
||||
persist()
|
||||
return license
|
||||
}
|
||||
|
||||
/**
|
||||
* 按作品匹配许可。
|
||||
* @param ownerKey 素材归属账号 key(自有判定)。
|
||||
* @param sourceHost 来源域名(授权判定;null=无法判断来源,仅自有可匹配)。
|
||||
* @param nowMs 当前时刻(授权有效期判定)。
|
||||
*/
|
||||
fun match(ownerKey: String, sourceHost: String?, nowMs: Long): Match? {
|
||||
findOwn(ownerKey)?.let { return Match(it, needsAttribution = false) }
|
||||
if (sourceHost != null) {
|
||||
val granted = licenses.filter {
|
||||
it.kind == Kind.GRANTED && it.subject == sourceHost &&
|
||||
(it.validFromMs == 0L || nowMs >= it.validFromMs) &&
|
||||
(it.validUntilMs == 0L || nowMs <= it.validUntilMs)
|
||||
}.maxByOrNull { it.validUntilMs }
|
||||
if (granted != null) return Match(granted, needsAttribution = granted.requiresAttribution)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun findOwn(subject: String): MediaLicense? =
|
||||
licenses.firstOrNull { it.kind == Kind.OWN && it.subject == subject }
|
||||
|
||||
private fun persist() {
|
||||
store?.invoke(serialize())
|
||||
}
|
||||
|
||||
/** JSON 序列化(手写转义,纯 JVM 无 Android 依赖)。 */
|
||||
internal fun serialize(): String = buildString {
|
||||
append("[")
|
||||
licenses.forEachIndexed { i, l ->
|
||||
if (i > 0) append(",")
|
||||
append("""{"id":${jstr(l.id)},"kind":"${l.kind.name}",""")
|
||||
append(""""subject":${jstr(l.subject)},"requiresAttribution":${l.requiresAttribution},""")
|
||||
append(""""validFromMs":${l.validFromMs},"validUntilMs":${l.validUntilMs},"note":${jstr(l.note)}}""")
|
||||
}
|
||||
append("]")
|
||||
}
|
||||
|
||||
/** 从 JSON 反序列化(坏数据跳过该条,不抛异常——许可库坏一条不能拖垮整库)。 */
|
||||
internal fun deserialize(json: String): List<MediaLicense> {
|
||||
val result = mutableListOf<MediaLicense>()
|
||||
val objRegex = Regex("""\{[^{}]*\}""")
|
||||
for (m in objRegex.findAll(json)) {
|
||||
runCatching {
|
||||
val obj = m.value
|
||||
fun field(name: String): String =
|
||||
Regex(""""$name":(?:\"((?:[^\"\\\\]|\\\\.)*)\"|([^,}]+))""")
|
||||
.find(obj)?.groupValues?.let { it[1].ifEmpty { it[2] } } ?: ""
|
||||
val kind = when (field("kind").trim('"')) {
|
||||
"OWN" -> Kind.OWN
|
||||
"GRANTED" -> Kind.GRANTED
|
||||
else -> return@runCatching
|
||||
}
|
||||
result += MediaLicense(
|
||||
id = field("id").trim('"'),
|
||||
kind = kind,
|
||||
subject = field("subject").trim('"'),
|
||||
requiresAttribution = field("requiresAttribution").trim('"') == "true",
|
||||
validFromMs = field("validFromMs").toLongOrNull() ?: 0L,
|
||||
validUntilMs = field("validUntilMs").toLongOrNull() ?: 0L,
|
||||
note = field("note").trim('"'),
|
||||
)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private fun jstr(s: String): String = buildString {
|
||||
append('"')
|
||||
for (ch in s) {
|
||||
when (ch) {
|
||||
'"' -> append("\\\"")
|
||||
'\\' -> append("\\\\")
|
||||
'\n' -> append("\\n")
|
||||
else -> append(ch)
|
||||
}
|
||||
}
|
||||
append('"')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package com.haorui.app.crossplatform.media
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
import java.security.MessageDigest
|
||||
|
||||
/**
|
||||
* 来源媒体导入器(M5,2026-11-15):MediaStore/内容 URI → 应用私有目录成品。
|
||||
*
|
||||
* 设计口径(跨平台自动发布设计 §视频转载):
|
||||
* - 来源素材导入 `filesDir/crossplatform/video`(内部私有;不被旧视频孤儿清理器扫描,
|
||||
* 与外部私有目录 `getExternalFilesDir/videos` 隔离);
|
||||
* - Android 媒体读取许可或 URI 授权在初始化时准备,失效后暂停;
|
||||
* - 导入时执行大小上限(500 MiB,与 VideoFileValidator 一致),边复制边计量——
|
||||
* 超限立即终止并清理半成品,不落脏文件;
|
||||
* - 导入完成即 SHA-256(内容级去重依据),文件校验(MP4/轨道/时长)由
|
||||
* [VideoFileValidator] 在管线里做——本类只管**搬运**,不管**内容合格性**。
|
||||
*
|
||||
* 安全约束:
|
||||
* - 只接受 content:// 或 file://(http/https 拒绝——网络下载属旧下载器职责);
|
||||
* - 导入目标固定在本类私有目录内(防路径注入把文件写到别处)。
|
||||
*/
|
||||
class SourceMediaProvider(
|
||||
private val context: Context,
|
||||
private val logger: (String) -> Unit = {},
|
||||
) {
|
||||
|
||||
companion object {
|
||||
/** 导入大小上限(与校验器一致)。 */
|
||||
const val MAX_SIZE_BYTES = VideoFileValidator.MAX_SIZE_BYTES
|
||||
private const val IMPORT_DIR = "crossplatform/video"
|
||||
private const val COPY_BUFFER = 64 * 1024
|
||||
}
|
||||
|
||||
/** 导入结果。 */
|
||||
sealed class Result {
|
||||
/** 成功:本地路径 + SHA-256 + 大小。 */
|
||||
data class Imported(val localPath: String, val sha256: String, val sizeBytes: Long) : Result()
|
||||
/** 拒绝(来源不支持/超限/IO 失败;半成品已清理)。 */
|
||||
data class Rejected(val reason: String) : Result()
|
||||
}
|
||||
|
||||
private val importDir: File
|
||||
get() = File(context.filesDir, IMPORT_DIR).apply { mkdirs() }
|
||||
|
||||
/** 已导入内容的 SHA-256 集合(内容级去重,防同一视频重复导入)。 */
|
||||
private val knownHashes = LinkedHashSet<String>()
|
||||
|
||||
/**
|
||||
* 从内容 URI 导入视频到私有目录。
|
||||
* @param sourceUri 来源(content:// 由 MediaStore/授权文档提供方;file:// 仅限自有测试)。
|
||||
* @param suggestedName 建议文件名(可空;实际名加时间戳防冲突)。
|
||||
*/
|
||||
fun importFrom(sourceUri: Uri, suggestedName: String? = null): Result {
|
||||
val scheme = sourceUri.scheme?.lowercase()
|
||||
if (scheme != "content" && scheme != "file") {
|
||||
return Result.Rejected("不支持的来源协议: $scheme(仅 content/file)")
|
||||
}
|
||||
// 打开来源流(大小未知来源先探元数据;读不到就流式计量)
|
||||
val resolver = context.contentResolver
|
||||
val sizeHint = try {
|
||||
resolver.openAssetFileDescriptor(sourceUri, "r")?.use { it.length }
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
if (sizeHint != null && sizeHint > MAX_SIZE_BYTES) {
|
||||
return Result.Rejected("来源视频超限 ${sizeHint / 1024 / 1024}MiB > 500MiB")
|
||||
}
|
||||
val input = try {
|
||||
resolver.openInputStream(sourceUri) ?: return Result.Rejected("来源不可读(流为空)")
|
||||
} catch (e: Exception) {
|
||||
return Result.Rejected("来源打开失败: ${e.javaClass.simpleName}")
|
||||
}
|
||||
val targetName = buildString {
|
||||
append(suggestedName?.takeIf { it.isNotBlank() } ?: "video")
|
||||
append('-').append(System.currentTimeMillis())
|
||||
append(".mp4")
|
||||
}
|
||||
// 文件名防注入:只保留安全字符
|
||||
val safeName = targetName.replace(Regex("[^A-Za-z0-9._-]"), "_")
|
||||
val target = File(importDir, safeName)
|
||||
val tmp = File(importDir, "$safeName.tmp")
|
||||
var copied = 0L
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
try {
|
||||
input.use { src ->
|
||||
FileOutputStream(tmp).use { out ->
|
||||
val buffer = ByteArray(COPY_BUFFER)
|
||||
while (true) {
|
||||
val n = src.read(buffer)
|
||||
if (n < 0) break
|
||||
copied += n
|
||||
if (copied > MAX_SIZE_BYTES) {
|
||||
// 边复制边计量:超限立即终止(设计口径:下载期间也执行大小上限)
|
||||
return Result.Rejected("导入超限 >500MiB(已复制 ${copied / 1024 / 1024}MiB,半成品已清理)")
|
||||
}
|
||||
digest.update(buffer, 0, n)
|
||||
out.write(buffer, 0, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (copied <= 0) {
|
||||
return Result.Rejected("来源为空流")
|
||||
}
|
||||
if (!tmp.renameTo(target)) {
|
||||
return Result.Rejected("落盘失败(rename 失败)")
|
||||
}
|
||||
val sha = digest.digest().joinToString("") { "%02x".format(it) }
|
||||
knownHashes.add(sha)
|
||||
logger("视频导入完成:$safeName ${copied / 1024}KB sha=${sha.take(12)}…")
|
||||
return Result.Imported(target.absolutePath, sha, copied)
|
||||
} catch (e: Exception) {
|
||||
// 半成品清理(不留脏文件)
|
||||
runCatching { tmp.delete() }
|
||||
runCatching { target.delete() }
|
||||
return Result.Rejected("导入 IO 异常: ${e.javaClass.simpleName}:${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/** 内容是否已导入过(SHA-256 去重)。 */
|
||||
fun isDuplicate(sha256: String): Boolean = sha256 in knownHashes
|
||||
|
||||
/** 记录外部已见哈希(与任务库/旧下载器去重联动时用)。 */
|
||||
fun registerKnownHash(sha256: String) {
|
||||
knownHashes.add(sha256)
|
||||
}
|
||||
|
||||
/** 私有目录内文件存在性核对(成品路径必须在导入目录内——与旧下载器同款防越界)。 */
|
||||
fun isManagedPath(path: String): Boolean {
|
||||
val f = File(path)
|
||||
return f.isFile && runCatching {
|
||||
f.canonicalFile.parentFile == importDir.canonicalFile
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.haorui.app.crossplatform.media
|
||||
|
||||
/**
|
||||
* 视频简介署名策略(M5,2026-11-15)。
|
||||
*
|
||||
* 设计口径(跨平台自动发布设计 §视频转载):
|
||||
* - 非本人作品按实际情况标注转载,不因改标题或封面就声明原创;
|
||||
* - 需要署名但发布页无法正确填写的任务跳过。
|
||||
*
|
||||
* 简介形态(首版模板):
|
||||
* - 自有:不附加署名段;
|
||||
* - 授权:末段「内容转载自 <来源名>(<署名>),已获授权」——署名缺失/来源缺失时
|
||||
* 返回 null(任务跳过),不静默放行。
|
||||
*/
|
||||
object VideoCaptionPolicy {
|
||||
|
||||
/** 署名素材上下文(许可匹配后构造)。 */
|
||||
data class Attribution(
|
||||
val sourceName: String,
|
||||
val authorName: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* 生成简介。
|
||||
* @param baseCaption 业务简介(标题外的描述文字;可为空)。
|
||||
* @param match 许可匹配结果;null=无许可(上游已拦截,此处兜底拒绝)。
|
||||
* @param attribution 署名信息;needsAttribution=true 时必须非空。
|
||||
* @return null=无法合规生成(任务跳过)。
|
||||
*/
|
||||
fun build(
|
||||
baseCaption: String,
|
||||
match: MediaLicenseStore.Match?,
|
||||
attribution: Attribution?,
|
||||
): String? {
|
||||
if (match == null) return null
|
||||
if (!match.needsAttribution) {
|
||||
return baseCaption.trim().takeIf { it.isNotEmpty() } ?: ""
|
||||
}
|
||||
val attr = attribution?.takeIf {
|
||||
it.sourceName.isNotBlank() && it.authorName.isNotBlank()
|
||||
} ?: return null
|
||||
val base = baseCaption.trim()
|
||||
val credit = "内容转载自${attr.sourceName}(作者:${attr.authorName}),已获授权"
|
||||
return if (base.isEmpty()) credit else "$base\n$credit"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package com.haorui.app.crossplatform.media
|
||||
|
||||
import android.media.MediaExtractor
|
||||
import android.media.MediaMetadataRetriever
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.security.MessageDigest
|
||||
|
||||
/**
|
||||
* 视频文件校验器(M5,2026-11-15):兼容 MP4 硬校验,异常一律不放行。
|
||||
*
|
||||
* 设计口径(跨平台自动发布设计 §视频转载):
|
||||
* - 首版只接收可识别的兼容 MP4,不引入手机端转码工程;
|
||||
* - 校验实际视频轨道、存在的音轨、时长、大小和 SHA-256;下载期间也执行大小上限;
|
||||
* - 解析异常不放行(辅助手段不能代替事实依据)。
|
||||
*
|
||||
* 与旧管线 [com.haorui.app.pipeline.VideoDownloader] 的边界:旧下载器面向 HTTP 流
|
||||
* (下载中校验+内容去重),本校验器面向**已落盘文件**(导入/MediaStore 取回后复核),
|
||||
* 两者校验规则一致但不共享代码路径。
|
||||
*/
|
||||
object VideoFileValidator {
|
||||
|
||||
/** 校验失败原因(供任务跳过/核对记录)。 */
|
||||
data class Report(
|
||||
val ok: Boolean,
|
||||
val reason: String = "",
|
||||
val sha256: String = "",
|
||||
val durationMs: Long = 0,
|
||||
val sizeBytes: Long = 0,
|
||||
)
|
||||
|
||||
/** 文件大小上限:500 MiB(设计口径)。 */
|
||||
const val MAX_SIZE_BYTES = 500L * 1024 * 1024
|
||||
/** 时长窗口:20~4000 秒(设计口径)。 */
|
||||
const val MIN_DURATION_MS = 20_000L
|
||||
const val MAX_DURATION_MS = 4_000_000L
|
||||
|
||||
/** 校验已落盘视频文件(硬校验:MP4 魔数/视频轨/音轨/时长/大小;SHA-256 一并算出)。 */
|
||||
fun validate(path: String): Report {
|
||||
val file = File(path)
|
||||
if (!file.exists() || !file.isFile) return Report(false, "文件不存在: $path")
|
||||
val size = file.length()
|
||||
if (size <= 0) return Report(false, "文件为空")
|
||||
if (size > MAX_SIZE_BYTES) return Report(false, "文件超限 ${size / 1024 / 1024}MiB > 500MiB")
|
||||
if (!isMp4Magic(file)) return Report(false, "非 MP4(ftyp 魔数缺失)")
|
||||
val sha = sha256(file)
|
||||
val meta = probeTracks(file)
|
||||
?: return Report(false, "媒体解析异常(MediaExtractor/MetadataRetriever 失败)", sha, sizeBytes = size)
|
||||
if (!meta.hasVideo) return Report(false, "无视频轨道")
|
||||
if (!meta.hasAudio) return Report(false, "无音轨")
|
||||
if (meta.durationMs < MIN_DURATION_MS) return Report(false, "时长 ${meta.durationMs / 1000}s 不足 20s")
|
||||
if (meta.durationMs > MAX_DURATION_MS) return Report(false, "时长 ${meta.durationMs / 1000}s 超过 4000s")
|
||||
return Report(
|
||||
ok = true,
|
||||
sha256 = sha,
|
||||
durationMs = meta.durationMs,
|
||||
sizeBytes = size,
|
||||
)
|
||||
}
|
||||
|
||||
/** MP4 魔数:offset 4 起 "ftyp"(与旧下载器同规则)。 */
|
||||
private fun isMp4Magic(file: File): Boolean = try {
|
||||
FileInputStream(file).use { input ->
|
||||
val head = ByteArray(8)
|
||||
var read = 0
|
||||
while (read < 8) {
|
||||
val n = input.read(head, read, 8 - read)
|
||||
if (n < 0) break
|
||||
read += n
|
||||
}
|
||||
read >= 8 && head[4] == 'f'.code.toByte() && head[5] == 't'.code.toByte() &&
|
||||
head[6] == 'y'.code.toByte() && head[7] == 'p'.code.toByte()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
false
|
||||
}
|
||||
|
||||
private class TrackMeta(val hasVideo: Boolean, val hasAudio: Boolean, val durationMs: Long)
|
||||
|
||||
/**
|
||||
* 轨道与时长探测(双源交叉:MediaExtractor 数轨道、MetadataRetriever 取时长);
|
||||
* 任一解析失败即返回 null(不放行)。
|
||||
* ⚠️ MediaExtractor/MediaMetadataRetriever 的 release()/close() 非 AutoCloseable 语义,
|
||||
* 不能 use{}——手动 try/finally 释放,防 native 句柄泄漏。
|
||||
*/
|
||||
private fun probeTracks(file: File): TrackMeta? {
|
||||
var hasVideo = false
|
||||
var hasAudio = false
|
||||
var extractor: MediaExtractor? = null
|
||||
try {
|
||||
extractor = MediaExtractor()
|
||||
extractor.setDataSource(file.absolutePath)
|
||||
for (i in 0 until extractor.trackCount) {
|
||||
val format = extractor.getTrackFormat(i)
|
||||
val mime = format.getString(android.media.MediaFormat.KEY_MIME).orEmpty()
|
||||
when {
|
||||
mime.startsWith("video/") -> hasVideo = true
|
||||
mime.startsWith("audio/") -> hasAudio = true
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
return null
|
||||
} finally {
|
||||
runCatching { extractor?.release() }
|
||||
}
|
||||
var retriever: MediaMetadataRetriever? = null
|
||||
val durationMs = try {
|
||||
retriever = MediaMetadataRetriever()
|
||||
retriever.setDataSource(file.absolutePath)
|
||||
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() ?: -1L
|
||||
} catch (e: Exception) {
|
||||
return null
|
||||
} finally {
|
||||
runCatching { retriever?.release() }
|
||||
}
|
||||
if (durationMs < 0) return null
|
||||
return TrackMeta(hasVideo, hasAudio, durationMs)
|
||||
}
|
||||
|
||||
/** 流式 SHA-256(大文件不整载)。 */
|
||||
fun sha256(file: File): String = try {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
FileInputStream(file).use { input ->
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
while (true) {
|
||||
val n = input.read(buffer)
|
||||
if (n < 0) break
|
||||
digest.update(buffer, 0, n)
|
||||
}
|
||||
}
|
||||
digest.digest().joinToString("") { "%02x".format(it) }
|
||||
} catch (e: Exception) {
|
||||
""
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.haorui.app.crossplatform.media
|
||||
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* 视频任务桥(M5,2026-11-15):跨平台成品 → 旧视频发布器(DRAFT 车道)。
|
||||
*
|
||||
* 设计口径(跨平台自动发布设计 §视频转载 + 开发计划 M5):
|
||||
* - **复用同一个 PublishMachine**,通过可选执行上下文区分 LEGACY_VIDEO 和
|
||||
* CROSS_PLATFORM_VIDEO;旧调用默认行为不变;
|
||||
* - 首版新链路默认关闭、DRY_RUN:桥只走**草稿**车道(autoPublish=false),
|
||||
* 正式发布等 M6 强回执;
|
||||
* - 点击前复查:素材文件与成品身份匹配(SHA-256 复核)——文件被删/被换即拒绝;
|
||||
* - 简介/署名:旧发布器无简介输入字段(只有标题/封面/声明),署名信息编码进
|
||||
* 标题外暂不可行——首版把 needsAttribution=true 且编辑器无法署名视为**跳过**
|
||||
* (设计口径「需要署名但发布页无法正确填写的任务跳过」),待编辑器简介控件
|
||||
* 取证后接入。
|
||||
*/
|
||||
class VideoTaskBridge(
|
||||
private val publisher: Publisher,
|
||||
private val logger: (String) -> Unit = {},
|
||||
) {
|
||||
|
||||
/** 旧发布器最小接口(真机绑定 PublishMachine.submit;测试注入假实现)。 */
|
||||
fun interface Publisher {
|
||||
/**
|
||||
* 与 PublishMachine.submit 同语义:false=拒绝(非空闲/门控拦截)。
|
||||
* @param declaration 作品声明(草稿沙盒显式传"内容无需标注"绕开旧配置;null=用发布器默认)。
|
||||
*/
|
||||
fun submit(title: String, mediaUri: String, autoPublish: Boolean, declaration: String?): Boolean
|
||||
}
|
||||
|
||||
/** 桥接结果。 */
|
||||
sealed class Result {
|
||||
/** 已递交给发布器(草稿车道)。 */
|
||||
data class Submitted(val title: String) : Result()
|
||||
/** 拒绝递交(原因明确,任务应 SKIPPED,素材保留)。 */
|
||||
data class Rejected(val reason: String) : Result()
|
||||
}
|
||||
|
||||
/**
|
||||
* 把加工成品递交给旧发布器(仅草稿)。
|
||||
* @param prepared 管线成品(CrossVideoPipeline.prepare 产出)。
|
||||
* @param publishPageSupportsAttribution 发布页是否已取证可署名——首版恒 false。
|
||||
* @param declarationOverride 递交时的作品声明覆盖(null=发布器默认配置)。
|
||||
*/
|
||||
fun bridge(
|
||||
prepared: CrossVideoPipeline.PreparedVideo,
|
||||
publishPageSupportsAttribution: Boolean = false,
|
||||
declarationOverride: String? = null,
|
||||
): Result {
|
||||
// ① 署名前置检查:需署名且发布页无法填写 → 跳过(不静默放行不合规转载)
|
||||
if (prepared.needsAttribution && !publishPageSupportsAttribution) {
|
||||
logger("需署名但发布页暂无法填写,任务跳过(素材保留)")
|
||||
return Result.Rejected("需署名转载但发布页暂无法署名(待简介控件取证)")
|
||||
}
|
||||
// ② 点击前复查:文件仍在且内容身份匹配(SHA-256 复核,防素材被删/被换)
|
||||
val file = File(prepared.localPath)
|
||||
if (!file.exists()) {
|
||||
logger("素材文件已丢失:${prepared.localPath}")
|
||||
return Result.Rejected("素材文件已丢失(SHA-256 无法复核)")
|
||||
}
|
||||
val currentSha = VideoFileValidator.sha256(file)
|
||||
if (currentSha != prepared.sha256) {
|
||||
logger("素材身份不符:当前 ${currentSha.take(12)}…,成品 ${prepared.sha256.take(12)}…")
|
||||
return Result.Rejected("素材文件内容与成品身份不符(SHA-256 复核失败)")
|
||||
}
|
||||
// ③ 递交(草稿车道;autoPublish=false 由本桥硬编码——新链路首版 DRY_RUN)。
|
||||
// 旧发布器只有标题输入;简介/署名段暂以标题行承载(首行),完整简介控件待取证。
|
||||
// 声明经 [declarationOverride] 透传(沙盒显式传值绕开旧配置;默认 null=发布器默认)。
|
||||
val ok = publisher.submit(titleOf(prepared), prepared.localPath, autoPublish = false, declaration = declarationOverride)
|
||||
if (!ok) {
|
||||
return Result.Rejected("发布器拒绝(非空闲或门控拦截)")
|
||||
}
|
||||
logger("视频已递交旧发布器(草稿车道):${prepared.localPath}")
|
||||
return Result.Submitted(titleOf(prepared))
|
||||
}
|
||||
|
||||
private fun titleOf(prepared: CrossVideoPipeline.PreparedVideo): String =
|
||||
prepared.caption.lineSequence().firstOrNull().orEmpty().ifBlank { "浩瑞视频草稿" }
|
||||
}
|
||||
@@ -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,175 @@
|
||||
package com.haorui.app.crossplatform.model
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.builtins.ListSerializer
|
||||
import kotlinx.serialization.builtins.serializer
|
||||
import kotlinx.serialization.encodeToString
|
||||
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,
|
||||
/** 微博热搜类目勾选(WeiboHotCategories.id;空=未选择。旧配置缺字段按空处理保持兼容)。 */
|
||||
val weiboHotCategories: List<String> = emptyList(),
|
||||
/** 微博热搜词条勾选(类目 id → 勾选的词条标题;重启不丢,重启后榜单已刷新——按标题在新榜单中匹配,匹配不到保留待核)。 */
|
||||
val weiboHotTopics: Map<String, List<String>> = emptyMap(),
|
||||
/** 知乎热榜采集卡片区间(榜单展示序,1 起;start≤end 由 normalized 归一)。 */
|
||||
val zhihuCardRangeStart: Int = 1,
|
||||
val zhihuCardRangeEnd: Int = 20,
|
||||
/** 抖音热榜只采前 N 条(1 起)。 */
|
||||
val douyinTopN: Int = 20,
|
||||
/** 抖音标签过滤(热/新/挑战/辟谣;空=不过滤)。 */
|
||||
val douyinLabelFilter: List<String> = emptyList(),
|
||||
) {
|
||||
fun normalized(): CrossPlatformConfig {
|
||||
val maximumDuration = videoMaxSeconds.coerceIn(20, 4000)
|
||||
val cardStart = zhihuCardRangeStart.coerceIn(1, 50)
|
||||
val cardEnd = zhihuCardRangeEnd.coerceIn(cardStart, 50)
|
||||
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(),
|
||||
weiboHotCategories = weiboHotCategories.map { it.trim() }.filter { it in WEIBO_CATEGORY_IDS }.distinct(),
|
||||
weiboHotTopics = weiboHotTopics.entries
|
||||
.filter { it.key.trim() in WEIBO_CATEGORY_IDS }
|
||||
.associate { it.key.trim() to it.value.map { t -> t.trim() }.filter { t -> t.isNotEmpty() }.distinct() },
|
||||
zhihuCardRangeStart = cardStart,
|
||||
zhihuCardRangeEnd = cardEnd,
|
||||
douyinTopN = douyinTopN.coerceIn(1, 50),
|
||||
douyinLabelFilter = douyinLabelFilter.filter { it in DOUYIN_LABELS }.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
|
||||
/** 微博热搜类目合法 id(见 WeiboHotCategories,2026-11-14 e2 实测清单)。 */
|
||||
private val WEIBO_CATEGORY_IDS: Set<String> =
|
||||
com.haorui.app.crossplatform.source.weibo.WeiboHotCategories.ALL.map { it.id }.toSet()
|
||||
/** 抖音标签过滤合法词(见 DouyinHotListParser.LABELS,2026-11-16 e1 实测全集)。 */
|
||||
val DOUYIN_LABELS = listOf("热", "新", "挑战", "辟谣")
|
||||
}
|
||||
}
|
||||
|
||||
/** 与历史扁平预设共同导入导出,新字段均使用独立前缀。 */
|
||||
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("|"),
|
||||
"weibo_hot_categories" to c.weiboHotCategories.joinToString("|"),
|
||||
"weibo_hot_topics" to kotlinx.serialization.json.Json.encodeToString(c.weiboHotTopics),
|
||||
"zhihu_card_range_start" to c.zhihuCardRangeStart.toString(),
|
||||
"zhihu_card_range_end" to c.zhihuCardRangeEnd.toString(),
|
||||
"douyin_top_n" to c.douyinTopN.toString(),
|
||||
"douyin_label_filter" to c.douyinLabelFilter.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,
|
||||
weiboHotCategories = value("weibo_hot_categories")?.split('|')?.filter { it.isNotBlank() }
|
||||
?: d.weiboHotCategories,
|
||||
weiboHotTopics = value("weibo_hot_topics")?.let { raw ->
|
||||
runCatching {
|
||||
kotlinx.serialization.json.Json.decodeFromString<Map<String, List<String>>>(raw)
|
||||
}.getOrDefault(d.weiboHotTopics)
|
||||
} ?: d.weiboHotTopics,
|
||||
zhihuCardRangeStart = i("zhihu_card_range_start", d.zhihuCardRangeStart),
|
||||
zhihuCardRangeEnd = i("zhihu_card_range_end", d.zhihuCardRangeEnd),
|
||||
douyinTopN = i("douyin_top_n", d.douyinTopN),
|
||||
douyinLabelFilter = value("douyin_label_filter")?.split('|')?.filter { it.isNotBlank() }
|
||||
?: d.douyinLabelFilter,
|
||||
).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,67 @@
|
||||
package com.haorui.app.crossplatform.publish
|
||||
|
||||
import com.haorui.app.automation.HaoRuiAccessibilityService
|
||||
import com.haorui.app.ocr.CreditGateRunner
|
||||
import com.haorui.app.scheduler.QuotaManager
|
||||
|
||||
/**
|
||||
* 新链路账号发布门控(M6,2026-11-15)。
|
||||
*
|
||||
* 设计口径(跨平台自动发布设计 §配额与发布条件):
|
||||
* - 出队及点击前复查:账号身份、证据与许可有效期、文件哈希、声明、前台占位、时效与额度;
|
||||
* - **信用分不可读或处罚状态未知时暂停新链路**——与健康检查不能复用过期的旧每日缓存;
|
||||
* - 已确认限制同账号发文时暂停所有发布入口。
|
||||
*
|
||||
* 与旧链路 CreditGateRunner 的语义差异(关键):
|
||||
* - 旧链路 fail-open(UNREADABLE 放行,防 OCR 不稳掐死全天任务);
|
||||
* - **新链路 fail-closed**(UNREADABLE 暂停本次任务,宁跳过不盲发)——
|
||||
* 新链路任务量小(每日各 2),跳过代价低;违规发布代价高(账号处罚)。
|
||||
*
|
||||
* 信用分读取经 [CreditGateRunner.evaluate](forceRefresh=true 不吃当日缓存);
|
||||
* 额度经 [QuotaManager.canPublish](配额满/休息期=静默 HOLD)。
|
||||
* 结论三态:ALLOW 放行 / HOLD 本次跳过(原因明确)/ SUSPEND 当日暂停(进 dayBlocked 语义)。
|
||||
*/
|
||||
class AccountPublishGate(
|
||||
private val quota: QuotaManager?,
|
||||
private val creditThreshold: Int,
|
||||
/** 信用分评估器(真机绑定 CreditGateRunner;测试注入假实现)。 */
|
||||
private val creditCheck: suspend (threshold: Int) -> CreditGateRunner.Verdict,
|
||||
private val logger: (String) -> Unit = {},
|
||||
) {
|
||||
|
||||
/** 门控结论。 */
|
||||
sealed class Decision {
|
||||
/** 全部通过,可发布。 */
|
||||
data object Allow : Decision()
|
||||
/** 本次任务跳过(原因明确;额度/时效类,下个窗口重试)。 */
|
||||
data class Hold(val reason: String) : Decision()
|
||||
/** 当日暂停(账号健康问题;进入 dayBlocked 语义,全部发布入口暂停)。 */
|
||||
data class Suspend(val reason: String) : Decision()
|
||||
}
|
||||
|
||||
/**
|
||||
* 出队复查(任务提交前调用一次;点击前由现有点击许可机制复查)。
|
||||
* 顺序:额度静默门(快,纯内存)→ 信用分实时读(慢,OCR+导航)。
|
||||
*/
|
||||
suspend fun check(): Decision {
|
||||
// ① 额度门(配额满/休息期 = HOLD,不算账号异常)
|
||||
quota?.let {
|
||||
if (!it.canPublish()) {
|
||||
val reason = "额度已满或处于休息期"
|
||||
logger("门控 HOLD:$reason")
|
||||
return Decision.Hold(reason)
|
||||
}
|
||||
}
|
||||
// ② 信用分实时读(不吃缓存;新链路 fail-closed)
|
||||
when (val verdict = creditCheck(creditThreshold)) {
|
||||
CreditGateRunner.Verdict.PASS -> {
|
||||
logger("门控 ALLOW:信用分达标、额度可用")
|
||||
return Decision.Allow
|
||||
}
|
||||
CreditGateRunner.Verdict.BLOCKED ->
|
||||
return Decision.Suspend("信用分低于门槛 $creditThreshold,当日暂停发布")
|
||||
CreditGateRunner.Verdict.UNREADABLE ->
|
||||
return Decision.Hold("信用分不可读(新链路不盲发,任务跳过待下窗重试)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.haorui.app.crossplatform.publish
|
||||
|
||||
import com.haorui.app.crossplatform.compose.ArticleComposer
|
||||
|
||||
/**
|
||||
* 文章发布机(M4 编排层,2026-11-15):标题/正文 → 编辑器写入 → 回读核对 → 草稿确认。
|
||||
*
|
||||
* 原语已真机定案(选择器可用性报告「文章编辑器写入实验」):
|
||||
* - 写入 = focus + 调试输入法 commitText(自绘无 EditText 节点,ACTION_SET_TEXT 不可用);
|
||||
* - 回读 = OCR(顶栏「N字/草稿已保存」字数对账 + 首尾双锚点);
|
||||
* - 草稿 = 编辑器自动保存,回执为顶栏常驻「草稿已保存」(区别于「草稿将自动保存」)。
|
||||
*
|
||||
* 失败语义(对齐 WeiboHotListCollector 与固定决策 6):
|
||||
* - **失败**:确定性操作失败(不在编辑器/焦点/写入失败/标题越出 2~30 约束)——记录原因,安全退出;
|
||||
* - **暂停核对**:核验不可判定或不吻合(字数对不上/锚点缺失/草稿回执未见)——回读规则仍在
|
||||
* 标定期(字数口径单样本、OCR 有噪声),不吻合一律进人工核对,不宣称成功也不误判失败;
|
||||
* - 任何路径都在 finally 走 EXIT 安全退出(不碰「下一步」——发布二阶段未取证,保持关闭)。
|
||||
*
|
||||
* 图片/封面/声明与「下一步」二阶段:待取证后接入(固定决策:不预设未核验能力)。
|
||||
* Port 契约:每个方法是一次页面操作/读取,实现方负责可见性核对,不抛异常(返回 false 表失败)。
|
||||
*/
|
||||
class ArticlePublishMachine(
|
||||
private val port: Port,
|
||||
private val logger: (String) -> Unit = {},
|
||||
) {
|
||||
|
||||
/** 真机驱动接口(编辑器侧;实现绑定调试输入法与 OCR 管线)。 */
|
||||
interface Port {
|
||||
/** 已在文章编辑器(标题占位/取消/草稿箱特征可辨)。 */
|
||||
fun ensureEditorOpen(): Boolean
|
||||
fun focusTitle(): Boolean
|
||||
fun focusBody(): Boolean
|
||||
/** 调试输入法 commitText 直写(分批由 [ArticleTextPolicy.commitBatches] 处理)。 */
|
||||
fun commitText(text: String): Boolean
|
||||
/** 当前屏 OCR 行(含顶栏「N字/…」与「草稿已保存」状态)。 */
|
||||
fun readEditorOcr(): List<String>
|
||||
/** 正文逐屏滚动全文 OCR 行(回读锚点核验用)。 */
|
||||
fun readBodyOcrFull(): List<String>
|
||||
/** 安全退出编辑器(取消/返回;绝不触碰「下一步」)。 */
|
||||
fun exitEditor(): Boolean
|
||||
}
|
||||
|
||||
enum class Phase {
|
||||
PREPARE, WRITE_TITLE, WRITE_BODY, READBACK, CONFIRM_DRAFT, EXIT, DONE, FAILED, PAUSED,
|
||||
}
|
||||
|
||||
/** 结果:outcome ∈ 草稿已核对 / 失败 / 暂停核对。 */
|
||||
data class Result(
|
||||
val outcome: String,
|
||||
val phase: Phase,
|
||||
val reason: String = "",
|
||||
val exitedSafely: Boolean = false,
|
||||
)
|
||||
|
||||
var phase: Phase = Phase.PREPARE
|
||||
private set
|
||||
|
||||
/**
|
||||
* 跑完整链路。
|
||||
* @param title 成品标题(2~30 字,页面自带约束,超界直接失败不落编辑器)。
|
||||
* @param body 成品正文(非空;长度/数字一致性由上游 ArticleBodyComposer 核验)。
|
||||
*/
|
||||
fun run(title: String, body: String): Result {
|
||||
var failure: String? = null
|
||||
var paused: String? = null
|
||||
var failedAt: Phase? = null
|
||||
var exitedSafely = false
|
||||
try {
|
||||
phase = Phase.PREPARE
|
||||
val titleCp = title.codePointCount(0, title.length)
|
||||
if (titleCp < ArticleComposer.TITLE_MIN || titleCp > ArticleComposer.TITLE_MAX) {
|
||||
fail("标题 $titleCp 字不在 ${ArticleComposer.TITLE_MIN}~${ArticleComposer.TITLE_MAX} 约束内")
|
||||
}
|
||||
if (body.isBlank()) fail("正文为空")
|
||||
if (!port.ensureEditorOpen()) fail("未在文章编辑器")
|
||||
|
||||
phase = Phase.WRITE_TITLE
|
||||
if (!port.focusTitle()) fail("标题区未获焦点")
|
||||
if (!port.commitText(title)) fail("标题写入失败")
|
||||
logger("标题已写入($titleCp 字)")
|
||||
|
||||
phase = Phase.WRITE_BODY
|
||||
if (!port.focusBody()) fail("正文区未获焦点")
|
||||
if (!port.commitText(body)) fail("正文写入失败")
|
||||
logger("正文已写入(口径 ${ArticleTextPolicy.toutiaoWordCountUnits(body) / 2} 字)")
|
||||
|
||||
phase = Phase.READBACK
|
||||
// 顶栏字数多拍采样(最多 3 拍):OCR 偶发粘连(2026-11-15 真机「70097」=
|
||||
// 「97字/」与相邻数字行合并)或草稿保存未刷新——取每拍全部「数字字」候选,
|
||||
// 任一候选与正文口径吻合即通过;全部不吻合才进核对。
|
||||
var wordCountOk = false
|
||||
var displayed = -1
|
||||
for (attempt in 1..3) {
|
||||
val topLines = port.readEditorOcr()
|
||||
val topText = ArticleTextPolicy.normalize(topLines.joinToString("\n"))
|
||||
val candidates = WORD_COUNT_REGEX.findAll(topText).mapNotNull {
|
||||
it.groupValues[1].toIntOrNull()
|
||||
}
|
||||
val expected = ArticleTextPolicy.toutiaoWordCountUnits(body) / 2
|
||||
val hit = candidates.firstOrNull {
|
||||
ArticleTextPolicy.wordCountMatches(body, it)
|
||||
}
|
||||
if (hit != null) {
|
||||
displayed = hit
|
||||
wordCountOk = true
|
||||
break
|
||||
}
|
||||
logger("字数采样第${attempt}拍不吻合(候选 ${candidates.toList()},正文口径 $expected)")
|
||||
}
|
||||
if (!wordCountOk) {
|
||||
pause("字数对账不符:正文口径 ${ArticleTextPolicy.toutiaoWordCountUnits(body) / 2},3 拍均未命中")
|
||||
}
|
||||
val bodyOcr = port.readBodyOcrFull()
|
||||
if (!ArticleTextPolicy.titleMatches(title, port.readEditorOcr() + bodyOcr)) {
|
||||
pause("标题回读锚点缺失(OCR 抽样:${bodyOcr.take(3).joinToString(" | ").take(120)})")
|
||||
}
|
||||
if (!ArticleTextPolicy.bodyMatches(body, bodyOcr)) {
|
||||
pause("正文回读锚点缺失(OCR 抽样:${(bodyOcr.firstOrNull().orEmpty() + "…" + bodyOcr.lastOrNull().orEmpty()).take(160)})")
|
||||
}
|
||||
logger("回读核对通过:字数 $displayed、标题/正文锚点可定位")
|
||||
|
||||
phase = Phase.CONFIRM_DRAFT
|
||||
// 回执判定经归一(真机 OCR「已→己」误读,2026-11-15)——见 ArticleTextPolicy.normalizeReceipt
|
||||
val receiptNormalized = ArticleTextPolicy.normalizeReceipt(port.readEditorOcr().joinToString("\n"))
|
||||
if (!receiptNormalized.contains(SAVED_MARK)) {
|
||||
pause("未见「草稿已保存」回执(自动保存可能滞后,结果未知进核对)")
|
||||
}
|
||||
logger("草稿回执确认:$SAVED_MARK")
|
||||
// 图片/封面/声明与「下一步」二阶段未取证——保持关闭,草稿即本链路终点
|
||||
} catch (stop: StopRequest) {
|
||||
failure = stop.message
|
||||
failedAt = phase
|
||||
} catch (hold: PauseRequest) {
|
||||
paused = hold.message
|
||||
failedAt = phase
|
||||
} finally {
|
||||
phase = Phase.EXIT
|
||||
exitedSafely = runCatching { port.exitEditor() }.getOrDefault(false)
|
||||
}
|
||||
val outcome = when {
|
||||
failure != null -> "失败"
|
||||
paused != null -> "暂停核对"
|
||||
else -> "草稿已核对"
|
||||
}
|
||||
return Result(outcome, failedAt ?: Phase.DONE, failure ?: paused.orEmpty(), exitedSafely)
|
||||
}
|
||||
|
||||
private class StopRequest(message: String) : RuntimeException(message)
|
||||
private class PauseRequest(message: String) : RuntimeException(message)
|
||||
|
||||
private fun fail(reason: String): Nothing = throw StopRequest(reason)
|
||||
private fun pause(reason: String): Nothing = throw PauseRequest(reason)
|
||||
|
||||
companion object {
|
||||
/** 顶栏字数形态(实测「547字/草稿已保存」)。 */
|
||||
private val WORD_COUNT_REGEX = Regex("(\\d+)\\s*字")
|
||||
/** 草稿保存回执(顶栏常驻文本;区别于未保存态「草稿将自动保存」)。 */
|
||||
const val SAVED_MARK = "草稿已保存"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package com.haorui.app.crossplatform.publish
|
||||
|
||||
/**
|
||||
* 文章编辑器写入/回读文本策略(M4,2026-11-15)。
|
||||
*
|
||||
* 取证结论(选择器可用性报告「头条文章编辑器取证(M4 第一轮)」):
|
||||
* 标题/正文为自绘控件(无 EditText 节点)→ ACTION_SET_TEXT 不可用,
|
||||
* 输入走 **focus + 调试输入法 commitText**(HaoRuiDebugIme),回读核验走 OCR。
|
||||
*
|
||||
* 职责(纯 JVM,输入法与 OCR 管线解耦):
|
||||
* - [commitBatches]:超长文本分批提交——单次 commitText 过长可能被编辑器截断;
|
||||
* 按码点切批,不切开代理对(emoji 等增补平面字符)。
|
||||
* - [normalize]:回读比对规范化——折叠空白、去零宽/不可见字符(OCR 行合并与编辑器
|
||||
* 自动换行都会改变空白形态,不能按原文空格逐字比对)。
|
||||
* - [titleMatches]:标题回读判定——标题 2~30 字且页面自带长度约束,规范化后在 OCR
|
||||
* 文本中可完整定位即接受(OCR 可能把标题与邻近文本合并成一行,用包含而非整行相等)。
|
||||
* - [bodyMatches]:正文回读判定——首段前 30 字 + 尾段后 30 字双锚点定位,不以整篇
|
||||
* 相等要求(OCR 有误读、编辑器自动换行与原文段落不同);任一锚点不可定位即判不一致。
|
||||
*/
|
||||
object ArticleTextPolicy {
|
||||
|
||||
/** 默认分批大小(字符数):经验值,覆盖编辑器单次 commit 稳定区间。 */
|
||||
const val DEFAULT_BATCH = 500
|
||||
|
||||
/** 回读锚点 bigram 匹配阈值与最小锚点长度。
|
||||
* 2026-11-15 分片方案:30 字锚点切 6 片×5 字,OCR 错 2 片=0.667→0.7 误拒→放宽 0.6。
|
||||
* 2026-11-17 bigram 修订(AI 正文真机):分片方案 OCR 错 1 字即毁整片(5 字全废),
|
||||
* 30 字锚点错 3 字=3 片毁=0.5<0.6 拒绝。改 bigram——错 1 字最多毁 2 组(29 组中 6 组
|
||||
* 损失=0.79),阈值 0.65 留足安全边际(无关文本/段间共用短语 bigram 重合 ≤0.62,
|
||||
* 污染段尾锚点 0.83,真机标定)。 */
|
||||
private const val ANCHOR_LEN = 30
|
||||
private const val ANCHOR_MIN = 6
|
||||
private const val SHARD_LEN = 5 // 仅短锚点退回精确包含的门槛
|
||||
const val FUZZY_HIT_RATE = 0.65
|
||||
|
||||
/** 超长文本分批(按码点切分,不切开代理对)。空文本返回空表。 */
|
||||
fun commitBatches(text: String, batchSize: Int = DEFAULT_BATCH): List<String> {
|
||||
if (text.isEmpty()) return emptyList()
|
||||
val batches = mutableListOf<String>()
|
||||
val sb = StringBuilder()
|
||||
var i = 0
|
||||
while (i < text.length) {
|
||||
val cp = text.codePointAt(i)
|
||||
val size = Character.charCount(cp)
|
||||
if (sb.isNotEmpty() && sb.length + size > batchSize) {
|
||||
batches.add(sb.toString())
|
||||
sb.setLength(0)
|
||||
}
|
||||
sb.appendCodePoint(cp)
|
||||
i += size
|
||||
}
|
||||
if (sb.isNotEmpty()) batches.add(sb.toString())
|
||||
return batches
|
||||
}
|
||||
|
||||
/**
|
||||
* 回读比对规范化:去一切空白与零宽/不可见字符(U+200B~U+200D、U+FEFF)。
|
||||
* 用码点区间书写,避免源码内嵌隐形字符。
|
||||
*/
|
||||
fun normalize(s: String): String = buildString {
|
||||
for (ch in s) {
|
||||
val invisible = ch.code in 0x200B..0x200D || ch.code == 0xFEFF
|
||||
if (!ch.isWhitespace() && !invisible) append(ch)
|
||||
}
|
||||
}
|
||||
|
||||
/** 标题回读:规范化后非空且模糊定位(分片命中率 ≥ [FUZZY_HIT_RATE],容忍 OCR 局部误读)。 */
|
||||
fun titleMatches(expected: String, ocrLines: List<String>): Boolean {
|
||||
val want = normalize(expected)
|
||||
if (want.isEmpty()) return false
|
||||
return fuzzyContains(normalize(ocrLines.joinToString("\n")), want)
|
||||
}
|
||||
|
||||
/**
|
||||
* 正文回读:首段锚点(双候选)+ 尾段后 [ANCHOR_LEN] 字锚点均模糊定位。
|
||||
* 2026-11-15 真机修订:逐字精确包含过脆(OCR 把「请输」误读为「清輪」,错 1 字即缺失),
|
||||
* 改分片命中——锚点切 [SHARD_LEN] 字片,命中率 ≥ [FUZZY_HIT_RATE] 即判定位;
|
||||
* 弱锚点(<6 字)仍拒绝,无关内容 0 命中仍拒绝——不放行假一致。
|
||||
* 2026-11-17 修订(AI 正文 1431 字真机):首锚点双候选——
|
||||
* ① 段首前 30 字(未污染时的快路径);
|
||||
* ② 段尾 30 字(污染容错:OCR 对段首前几字误读率高——「e國e中」式替换只伤段首,
|
||||
* 段尾必然完好;固定跳头窗口赌不中污染长度,真机复算 skip=4/6/8 均 ≤1/6 命中)。
|
||||
* 任一首候选命中即通过,尾锚点不变;两候选都未命中仍拒绝。
|
||||
*/
|
||||
fun bodyMatches(expected: String, ocrLines: List<String>): Boolean {
|
||||
val paragraphs = expected.split('\n').map { normalize(it) }.filter { it.isNotEmpty() }
|
||||
if (paragraphs.isEmpty()) return false
|
||||
val firstPara = paragraphs.first()
|
||||
val last = paragraphs.last().takeLast(ANCHOR_LEN)
|
||||
val firstCandidates = buildList {
|
||||
add(firstPara.take(ANCHOR_LEN))
|
||||
if (firstPara.length > ANCHOR_LEN) add(firstPara.takeLast(ANCHOR_LEN))
|
||||
}.filter { it.length >= ANCHOR_MIN }
|
||||
if (firstCandidates.isEmpty() || last.length < ANCHOR_MIN) return false
|
||||
val joined = normalize(ocrLines.joinToString("\n"))
|
||||
return firstCandidates.any { fuzzyContains(joined, it) } && fuzzyContains(joined, last)
|
||||
}
|
||||
|
||||
/**
|
||||
* 模糊包含(2026-11-17 bigram 修订):needle 的二字组在 haystack 中的命中率 ≥ [FUZZY_HIT_RATE]。
|
||||
*
|
||||
* 原分片方案(5 字片)对 OCR 形近错字过脆:一片中错 1 字即整片毁,30 字锚点错 3 字
|
||||
* =3 片毁=0.5<0.6 拒绝(AI 正文 1199 字真机实锤)。
|
||||
*
|
||||
* bigram 方案:30 字锚点=29 个二字组,OCR 错 1 字最多毁 2 组(相邻 2 个 bigram);
|
||||
* 错 3 字毁 ≤6 组=23/29≈0.79 远超阈值。无关文本 bigram 重合率 <0.3(真机标定),
|
||||
* 0.5 阈值留足安全边际——不放行假一致(无关内容 0 命中仍拒绝)。
|
||||
*/
|
||||
internal fun fuzzyContains(haystack: String, needle: String): Boolean {
|
||||
if (needle.isEmpty()) return true
|
||||
if (haystack.isEmpty()) return false
|
||||
// 短锚点(≤SHARD_LEN)无 bigram 统计力,退回精确包含
|
||||
if (needle.length <= SHARD_LEN) return haystack.contains(needle)
|
||||
val needleBigrams = (0 until needle.length - 1)
|
||||
.map { needle.substring(it, it + 2) }
|
||||
if (needleBigrams.isEmpty()) return haystack.contains(needle)
|
||||
val hits = needleBigrams.count { haystack.contains(it) }
|
||||
return hits.toDouble() / needleBigrams.size >= FUZZY_HIT_RATE
|
||||
}
|
||||
|
||||
/**
|
||||
* 头条编辑器字数口径(2026-11-15 真机标定):**全角=1 字、半角=0.5 字、空白不计**。
|
||||
* 实测对账:456 汉字 + 35 全角标点 + 112 半角字母×0.5 = 547(编辑器顶栏实显 547 字)。
|
||||
* 返回半字单位(全角=2、半角=1),避免小数。
|
||||
* ⚠️ 数字/ASCII 标点按半角计属推断(实测样本未覆盖),比对留 1 半字容差。
|
||||
*/
|
||||
fun toutiaoWordCountUnits(text: String): Int {
|
||||
var units = 0
|
||||
var i = 0
|
||||
while (i < text.length) {
|
||||
val cp = text.codePointAt(i)
|
||||
val size = Character.charCount(cp)
|
||||
if (!Character.isWhitespace(cp)) {
|
||||
units += if (cp >= 0x80) 2 else 1
|
||||
}
|
||||
i += size
|
||||
}
|
||||
return units
|
||||
}
|
||||
|
||||
/** 字数对账:编辑器顶栏显示字数 [displayedCount] 与 [text] 口径吻合(±1 半字容差)。 */
|
||||
fun wordCountMatches(text: String, displayedCount: Int): Boolean {
|
||||
if (displayedCount < 0) return false
|
||||
return Math.abs(toutiaoWordCountUnits(text) - displayedCount * 2) <= 1
|
||||
}
|
||||
|
||||
/**
|
||||
* 草稿回执归一:真机 OCR 实测「已→己」误读(2026-11-15「97字/草稿己保存」)。
|
||||
* 仅回执匹配使用;正文回读保持字面一致性要求,不受本归一影响。
|
||||
*/
|
||||
fun normalizeReceipt(ocrText: String): String = normalize(ocrText).replace("草稿己保存", "草稿已保存")
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package com.haorui.app.crossplatform.publish
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import com.haorui.app.automation.HaoRuiAccessibilityService
|
||||
import com.haorui.app.automation.RunLogger
|
||||
import com.haorui.app.crossplatform.data.CrossPublishTaskStore
|
||||
import com.haorui.app.crossplatform.model.CrossAttemptState
|
||||
import com.haorui.app.crossplatform.model.CrossTaskState
|
||||
import com.haorui.app.ocr.OcrProcessor
|
||||
import com.haorui.app.ocr.ScreenCapturer
|
||||
import com.haorui.app.ocr.OcrTextLine
|
||||
|
||||
/**
|
||||
* 草稿核对器(M6 恢复场景,2026-11-16):UNKNOWN 结果任务 → 草稿箱核对 → 归账。
|
||||
*
|
||||
* 设计口径(跨平台自动发布设计 §手机任务库与防重复):
|
||||
* "崩溃后先核对作品管理。找到当前账号的匹配新作品则补回执;无法确认是否提交时
|
||||
* RESULT_UNKNOWN,不盲目重发,列表暂未出现不能当作确定失败。"
|
||||
*
|
||||
* DRAFT 车道的核对对象=**草稿箱**(正式发布的作品管理核对待 M6 长跑验收后接入)。
|
||||
*
|
||||
* 页面取证(2026-11-16 真机):
|
||||
* - 草稿箱入口:「我的」页底部 Tab「草稿」(与作品/收藏/赞过并列);
|
||||
* - 草稿条目:封面+标题(可能截断)——OCR 按标题匹配;
|
||||
* - 标题匹配用分片模糊(ArticleTextPolicy.fuzzyContains,OCR 单字误读容忍)。
|
||||
*
|
||||
* 归账语义(保守):
|
||||
* - 草稿箱命中标题 → recordReceipt(补回执,额度结算);
|
||||
* - 未命中 → **保留 UNKNOWN**(列表暂未出现≠未提交——草稿箱可能分页/加载中);
|
||||
* - 「我的」页 Tab 用树定位(原生页),条目读用 OCR。
|
||||
*/
|
||||
class DraftReconciler(
|
||||
private val service: HaoRuiAccessibilityService,
|
||||
private val store: CrossPublishTaskStore,
|
||||
private val logger: (String) -> Unit = {},
|
||||
) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "Draft-Reconcile"
|
||||
private const val NAV_TIMEOUT_MS = 60_000L
|
||||
private const val MAX_SCREENS = 6
|
||||
private const val MIN_CAPTURE_INTERVAL_MS = 1_200L
|
||||
}
|
||||
|
||||
/** 核对结果。 */
|
||||
data class Report(
|
||||
val matchedCount: Int,
|
||||
val pendingCount: Int,
|
||||
val reason: String = "",
|
||||
)
|
||||
|
||||
private var lastCaptureAtMs = 0L
|
||||
|
||||
/**
|
||||
* 核对全部 UNKNOWN 任务的草稿箱存在性并归账。
|
||||
* 流程:我的页(launchApp+底部 tab)→ 草稿 Tab → 逐屏 OCR → 标题匹配 → 归账。
|
||||
*/
|
||||
suspend fun reconcileAll(): Report {
|
||||
val unknownTasks = collectUnknownTasks()
|
||||
if (unknownTasks.isEmpty()) {
|
||||
logger("无 UNKNOWN 任务待核对")
|
||||
return Report(0, 0, "无待核对任务")
|
||||
}
|
||||
logger("待核对 UNKNOWN 任务 ${unknownTasks.size} 个")
|
||||
if (!openDraftTab()) {
|
||||
return Report(0, unknownTasks.size, "草稿箱导航失败")
|
||||
}
|
||||
// 逐屏 OCR 收集草稿标题行
|
||||
val lines = mutableListOf<String>()
|
||||
val seen = HashSet<String>()
|
||||
var noNewCount = 0
|
||||
for (screen in 0 until MAX_SCREENS) {
|
||||
val current = screenOcrLines()
|
||||
if (current.isEmpty()) {
|
||||
Thread.sleep(800)
|
||||
continue
|
||||
}
|
||||
var appended = 0
|
||||
current.forEach { if (seen.add(it)) { lines.add(it); appended++ } }
|
||||
if (appended == 0) {
|
||||
noNewCount++
|
||||
if (noNewCount >= 2) break
|
||||
} else {
|
||||
noNewCount = 0
|
||||
}
|
||||
val scrolled = kotlinx.coroutines.runBlocking {
|
||||
service.gestures.swipe(0.5f, 0.70f, 0.5f, 0.30f)
|
||||
}
|
||||
if (!scrolled) break
|
||||
Thread.sleep(1_000)
|
||||
}
|
||||
logger("草稿箱 OCR 共 ${lines.size} 行")
|
||||
// 标题匹配归账
|
||||
var matched = 0
|
||||
var pending = 0
|
||||
val generation = store.currentGeneration()
|
||||
for ((id, title) in unknownTasks) {
|
||||
val hit = ArticleTextPolicy.fuzzyContains(lines.joinToString("\n"), title)
|
||||
if (hit && generation != null) {
|
||||
val attempts = store.attempts(id)
|
||||
val unknown = attempts.firstOrNull { it.state == CrossAttemptState.UNKNOWN }
|
||||
if (unknown != null) {
|
||||
// recordReceipt 内部已把任务转 DRAFT_SAVED(草稿车道终态)——
|
||||
// ⚠️ 不 resume 到 READY(重复发布风险;resumeAfterPageCheck 语义是
|
||||
// PAUSED 任务复核后重入,UNKNOWN+CONFIRMED 不适用)
|
||||
store.recordReceipt(unknown.id, "草稿箱核对命中:$title")
|
||||
logger("任务 $id 补回执(recordReceipt 内部转 DRAFT_SAVED)")
|
||||
} else {
|
||||
logger("任务 $id 草稿命中但无 UNKNOWN attempt(已是终态),跳过")
|
||||
}
|
||||
matched++
|
||||
} else {
|
||||
pending++
|
||||
logger("任务 $id 草稿箱未命中,保留 UNKNOWN(不盲判失败)")
|
||||
}
|
||||
}
|
||||
kotlinx.coroutines.runBlocking { service.gestures.home() }
|
||||
return Report(matched, pending)
|
||||
}
|
||||
|
||||
/** 全部 UNKNOWN 任务的 (id, title)。 */
|
||||
private suspend fun collectUnknownTasks(): List<Pair<String, String>> {
|
||||
val result = mutableListOf<Pair<String, String>>()
|
||||
for (id in store.unknownTaskIds()) {
|
||||
store.find(id)?.let { result.add(id to it.title) }
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/** 导航到「我的」页草稿 Tab(树定位;原生页)。 */
|
||||
private suspend fun openDraftTab(): Boolean {
|
||||
val deadline = android.os.SystemClock.elapsedRealtime() + NAV_TIMEOUT_MS
|
||||
while (android.os.SystemClock.elapsedRealtime() < deadline) {
|
||||
if (service.currentPackage() != "com.ss.android.article.news") {
|
||||
service.launchApp("com.ss.android.article.news")
|
||||
Thread.sleep(1_500)
|
||||
continue
|
||||
}
|
||||
// 已在「我的」页(关注/粉丝特征)→ 点草稿 Tab
|
||||
val root = service.root()
|
||||
val draftTab = try {
|
||||
if (root?.packageName?.toString() == "com.ss.android.article.news") {
|
||||
com.haorui.app.automation.NodeLocator.byText(root, "草稿")
|
||||
} else null
|
||||
} finally { root?.recycle() }
|
||||
if (draftTab != null) {
|
||||
val ok = kotlinx.coroutines.runBlocking { service.gestures.tapNode(draftTab) }
|
||||
runCatching { draftTab.recycle() }
|
||||
if (ok) {
|
||||
logger("已进入草稿 Tab")
|
||||
Thread.sleep(1_500)
|
||||
return true
|
||||
}
|
||||
}
|
||||
// 不在我的页 → 点底栏「我的」(等分第 5 格)
|
||||
val myTab = kotlinx.coroutines.runBlocking {
|
||||
service.gestures.tapAt(972, 2159)
|
||||
}
|
||||
if (!myTab) Thread.sleep(1_000)
|
||||
Thread.sleep(1_500)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** 单屏 OCR(节流防 takeScreenshot 限流)。 */
|
||||
private fun screenOcrLines(): List<String> {
|
||||
val since = android.os.SystemClock.elapsedRealtime() - lastCaptureAtMs
|
||||
if (since < MIN_CAPTURE_INTERVAL_MS) Thread.sleep(MIN_CAPTURE_INTERVAL_MS - since)
|
||||
lastCaptureAtMs = android.os.SystemClock.elapsedRealtime()
|
||||
val bitmap: Bitmap = kotlinx.coroutines.runBlocking {
|
||||
ScreenCapturer(service).capture()
|
||||
} ?: return emptyList()
|
||||
return try {
|
||||
kotlinx.coroutines.runBlocking { OcrProcessor.recognize(bitmap) }
|
||||
.flatMap { it.lines }
|
||||
.map { it.text.trim() }
|
||||
.filter { it.isNotEmpty() }
|
||||
} finally {
|
||||
bitmap.recycle()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,111 @@
|
||||
package com.haorui.app.crossplatform.publish
|
||||
|
||||
import com.haorui.app.crossplatform.data.CrossPublishTaskStore
|
||||
import com.haorui.app.crossplatform.model.CrossPublishTask
|
||||
import com.haorui.app.crossplatform.model.CrossSubmissionMode
|
||||
|
||||
/**
|
||||
* 发布协调器(M6,2026-11-15):READY 任务 → 门控 → 上下文路由 → 提交车道 → 回执归账。
|
||||
*
|
||||
* 设计口径(开发计划 M6 / 跨平台自动发布设计):
|
||||
* - 出队即复查(门控 ALLOW 才领取任务);点击前落库(beginSubmission 先于任何 UI 动作);
|
||||
* - 同次尝试仅点击一次(claimSubmissionClick);未知结果保留素材和额度不盲重发;
|
||||
* - contentKind 只负责路由(ARTICLE→图文机器 / VIDEO→视频桥),同事件去重由
|
||||
* 幂等键 accountKey+eventId+publicationVersion 在任务库层保证;
|
||||
* - 首版仅 DRAFT 车道(正式发布等混合 4 小时长跑验收后开放)。
|
||||
*
|
||||
* 与旧链路的关系:视频走 VideoTaskBridge(旧 PublishMachine 车道),图文走
|
||||
* ArticlePublishMachine(独立机器);协调器只做**领取→复查→登记→递交→归账**编排,
|
||||
* 不直接操作 UI。执行结果按 [Executor] 回调归账(CONFIRMED/UNKNOWN/NOT_SUBMITTED)。
|
||||
*/
|
||||
class PublishCoordinator(
|
||||
private val store: CrossPublishTaskStore,
|
||||
private val gate: AccountPublishGate,
|
||||
private val logger: (String) -> Unit = {},
|
||||
) {
|
||||
|
||||
/**
|
||||
* 执行通道抽象(真机绑定图文机器/视频桥;测试注入假实现)。
|
||||
* @return 提交结果归账类;执行方负责 UI 全程,协调器只记录结果。
|
||||
*/
|
||||
fun interface Executor {
|
||||
/** 执行任务提交;返回归账结论(reason 供日志/任务记录)。 */
|
||||
suspend fun execute(task: CrossPublishTask): ExecutionResult
|
||||
}
|
||||
|
||||
/** 执行结果(与 CrossAttemptState 对齐)。 */
|
||||
sealed class ExecutionResult {
|
||||
/** 明确保存成功(草稿回执确认)。 */
|
||||
data class Confirmed(val receiptRef: String) : ExecutionResult()
|
||||
/** 结果未知(超时/中断/弹层异常)——保留素材与额度,等作品管理核对。 */
|
||||
data class Unknown(val reason: String) : ExecutionResult()
|
||||
/** 明确未提交(门控/准备失败,未点任何提交按钮)——释放预占。 */
|
||||
data class NotSubmitted(val reason: String) : ExecutionResult()
|
||||
}
|
||||
|
||||
/** 领取与执行结果。 */
|
||||
sealed class Outcome {
|
||||
data class Dispatched(val taskId: String, val result: ExecutionResult) : Outcome()
|
||||
/** 无任务/门控拦截(原因明确)。 */
|
||||
data class Idle(val reason: String) : Outcome()
|
||||
}
|
||||
|
||||
/** 门控检查整体预算(信用读含导航,正常 30~90s;超时按 HOLD 处理不阻塞分发)。 */
|
||||
companion object {
|
||||
const val GATE_BUDGET_MS = 180_000L
|
||||
}
|
||||
|
||||
/**
|
||||
* 领取并执行一个 READY 任务(单次调用处理单任务;调度节奏由调用方控制)。
|
||||
* 流程:门控 → claimNextReady(事务领取,EDITING)→ beginSubmission(点击前落库)
|
||||
* → 执行 → 归账。
|
||||
*
|
||||
* ⚠️ 门控包整体预算(M6 卡死防御 2026-11-16):信用读导航存在非挂起阻塞点
|
||||
* (binder/系统 IPC),withTimeoutOrNull 无法打断但至少把分发从无限等待中解放——
|
||||
* 超时归 HOLD("门控超时"),任务留在队列下轮重试。
|
||||
*/
|
||||
suspend fun dispatchOnce(accountKey: String, generation: Long, executor: Executor): Outcome {
|
||||
// ① 门控(额度静默门 + 信用分实时读;180s 预算兜底)
|
||||
val gateDecision = kotlinx.coroutines.withTimeoutOrNull(GATE_BUDGET_MS) { gate.check() }
|
||||
when (val decision = gateDecision ?: AccountPublishGate.Decision.Hold("门控检查超时 ${GATE_BUDGET_MS / 1000}s(导航静默阻塞兜底)")) {
|
||||
is AccountPublishGate.Decision.Hold -> return Outcome.Idle("门控跳过:${decision.reason}")
|
||||
is AccountPublishGate.Decision.Suspend -> return Outcome.Idle("门控暂停:${decision.reason}")
|
||||
AccountPublishGate.Decision.Allow -> {}
|
||||
}
|
||||
// ② 事务领取(READY→EDITING;代际校验在 store 内)
|
||||
val task = store.claimNextReady(generation, accountKey)
|
||||
?: return Outcome.Idle("无 READY 任务")
|
||||
// ③ 点击前落库(SUBMIT_INTENT;首版仅 DRAFT 车道)。
|
||||
// 失败不强行转状态(policy 拒绝时任务保持原状态,下轮 claimNextReady 重试)。
|
||||
val attempt = store.beginSubmission(task.id, generation, CrossSubmissionMode.DRAFT)
|
||||
if (attempt == null) {
|
||||
logger("任务 ${task.id} 提交意图登记失败(policy 拒绝或代际不符),本轮跳过")
|
||||
return Outcome.Idle("提交意图登记失败(任务保持原状态待重试)")
|
||||
}
|
||||
logger("任务 ${task.id} 已落提交意图 attempt=${attempt.id}(DRAFT 车道)")
|
||||
// ④ 执行(图文机器/视频桥按 contentKind 路由——路由由注入的 executor 决定)
|
||||
val result = try {
|
||||
executor.execute(task)
|
||||
} catch (t: Throwable) {
|
||||
logger("任务 ${task.id} 执行异常: ${t.javaClass.simpleName}:${t.message}")
|
||||
ExecutionResult.Unknown("执行异常: ${t.javaClass.simpleName}")
|
||||
}
|
||||
// ⑤ 归账(attempt 归账方法内部已同步转任务状态:
|
||||
// recordReceipt→DRAFT_SAVED / markSubmissionUnknown→RESULT_UNKNOWN /
|
||||
// confirmNotSubmitted→SKIPPED;协调器不重复 transition)
|
||||
return when (result) {
|
||||
is ExecutionResult.Confirmed -> {
|
||||
store.recordReceipt(attempt.id, result.receiptRef)
|
||||
Outcome.Dispatched(task.id, result)
|
||||
}
|
||||
is ExecutionResult.Unknown -> {
|
||||
store.markSubmissionUnknown(attempt.id, result.reason)
|
||||
Outcome.Dispatched(task.id, result)
|
||||
}
|
||||
is ExecutionResult.NotSubmitted -> {
|
||||
store.confirmNotSubmitted(attempt.id, result.reason)
|
||||
Outcome.Dispatched(task.id, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,294 @@
|
||||
package com.haorui.app.crossplatform.publish
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.os.SystemClock
|
||||
import com.haorui.app.automation.HaoRuiAccessibilityService
|
||||
import com.haorui.app.automation.RunLogger
|
||||
import com.haorui.app.automation.ime.HaoRuiDebugIme
|
||||
import com.haorui.app.ocr.OcrProcessor
|
||||
import com.haorui.app.ocr.OcrTextLine
|
||||
import com.haorui.app.ocr.ScreenCapturer
|
||||
|
||||
/**
|
||||
* 头条文章编辑器真机 Port(M4,2026-11-15)。
|
||||
*
|
||||
* 坐标纪律(误点「发布」事故红线):**每步先 OCR 核屏、按 OCR 行 bounds 求坐标再点击**;
|
||||
* 无 bounds 的兜底坐标仅在屏幕状态标记命中后使用(取证记录见选择器可用性报告)。
|
||||
* 全程不触碰「下一步」(发布二阶段)与任何发布按钮;收尾 HOME(编辑器草稿自动保存,
|
||||
* 不受 HOME 影响;下轮 openArticleEditor 总是从 +发布 开新稿)。
|
||||
*
|
||||
* 输入前置:需先 `adb shell ime enable/set` 切换到浩瑞调试输入法(commitText 直写通道);
|
||||
* 未切换时 [commitText] 明确失败并记日志,不静默吞。
|
||||
*/
|
||||
class ToutiaoArticlePort(
|
||||
private val service: HaoRuiAccessibilityService,
|
||||
) : ArticlePublishMachine.Port {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "TT-Article"
|
||||
private const val TOUTIAO_PKG = "com.ss.android.article.news"
|
||||
private const val NAV_TIMEOUT_MS = 60_000L
|
||||
private const val MAX_BODY_SCREENS = 12 // AI 正文 800~1500 字约 8~10 屏,留页底判定余量
|
||||
/** 截屏最小间隔(takeScreenshot 系统频率限制;实测连拍 <1s 即 errorCode=3)。 */
|
||||
private const val MIN_CAPTURE_INTERVAL_MS = 1_200L
|
||||
/** 兜底坐标(2026-11-15 取证+实测;仅在 OCR 定位失败且屏幕标记命中后使用)。 */
|
||||
private const val FALLBACK_TITLE_X = 500
|
||||
private const val FALLBACK_TITLE_Y = 340
|
||||
private const val FALLBACK_BODY_X = 500
|
||||
private const val FALLBACK_BODY_Y = 520
|
||||
/** 编辑器顶栏字数前缀形态(「547字/草稿已保存」)。 */
|
||||
private val WORD_COUNT_PREFIX = Regex("\\d+\\s*字[//]")
|
||||
}
|
||||
|
||||
// ── ArticlePublishMachine.Port ────────────────────────────
|
||||
|
||||
/**
|
||||
* 编辑器状态判定。⚠️ 灰字占位「请输入标题/请输入正文」OCR 命中率低(2026-11-15 真机:
|
||||
* 单拍约三成,连 3 拍全丢)——改以**头部深色标记**为主判据(「草稿将自动保存」/
|
||||
* 「草稿已保存」/「N字/」+「取消」),占位符为辅;重试 6 拍任一命中即认。
|
||||
* 注意:本判定含已写内容的编辑器(草稿已保存态);空稿约束依赖 openArticleEditor
|
||||
* 恒从「+发布」新开稿件保证。
|
||||
*/
|
||||
override fun ensureEditorOpen(): Boolean = (1..6).any { editorMarkers(screen()) }
|
||||
|
||||
override fun focusTitle(): Boolean {
|
||||
val lines = screen()
|
||||
val target = lines.firstOrNull { it.text.contains("请输入标题") || it.text.contains("个字") }
|
||||
return if (target != null && tapCenter(target)) true
|
||||
else tapFallback(FALLBACK_TITLE_X, FALLBACK_TITLE_Y, "标题占位 OCR 未定位,走兜底坐标")
|
||||
}
|
||||
|
||||
override fun focusBody(): Boolean {
|
||||
val lines = screen()
|
||||
val target = lines.firstOrNull { it.text.contains("请输入正文") }
|
||||
return if (target != null && tapCenter(target)) true
|
||||
else tapFallback(FALLBACK_BODY_X, FALLBACK_BODY_Y, "正文占位 OCR 未定位,走兜底坐标")
|
||||
}
|
||||
|
||||
override fun commitText(text: String): Boolean {
|
||||
if (!isDebugImeCurrent()) {
|
||||
log("当前输入法非浩瑞调试输入法,无法直写(请先 adb shell ime set)")
|
||||
return false
|
||||
}
|
||||
return HaoRuiDebugIme.commit(text)
|
||||
}
|
||||
|
||||
override fun readEditorOcr(): List<String> = screen().map { it.text }
|
||||
|
||||
/**
|
||||
* 正文逐屏全文 OCR。⚠️ commit 后光标停在正文末尾——必须**先滚回顶部**再逐屏下扫,
|
||||
* 否则正文开头(回读首锚点)永不进入视野(2026-11-15 真机:字数对账 97=97 通过、
|
||||
* 仅首锚点缺失,即此根因)。半屏上滑+行序去重;连续两屏无新行/滑不动即止。
|
||||
*/
|
||||
override fun readBodyOcrFull(): List<String> {
|
||||
scrollToTop()
|
||||
val all = mutableListOf<String>()
|
||||
val seen = HashSet<String>()
|
||||
var noNewCount = 0
|
||||
for (i in 0 until MAX_BODY_SCREENS) {
|
||||
val lines = screen().map { it.text.trim() }.filter { it.isNotEmpty() }
|
||||
if (lines.isEmpty()) {
|
||||
Thread.sleep(800)
|
||||
continue
|
||||
}
|
||||
var appended = 0
|
||||
lines.forEach { if (seen.add(it)) { all.add(it); appended++ } }
|
||||
if (appended == 0) {
|
||||
noNewCount++
|
||||
if (noNewCount >= 2) {
|
||||
log("回读全文连续两屏无新行,判定到页底")
|
||||
break
|
||||
}
|
||||
} else {
|
||||
noNewCount = 0
|
||||
}
|
||||
val scrolled = kotlinx.coroutines.runBlocking {
|
||||
service.gestures.swipe(0.5f, 0.62f, 0.5f, 0.25f)
|
||||
}
|
||||
if (!scrolled) break
|
||||
Thread.sleep(1_000)
|
||||
}
|
||||
return all
|
||||
}
|
||||
|
||||
/** 滚回正文顶部:反向滑动(指纹下移=内容上移),内容签名稳定即到顶。
|
||||
* ⚠️ 2026-11-17 真机(AI 正文 1431 字):10 次预算不够——8~10 屏文档反向滑
|
||||
* 恰好耗尽,顶未到就下扫 → 首锚点永不入视野 → 回读必失败。预算提到 25;
|
||||
* 且用「连续两次滑动后签名相同」判定(单次相同可能是滚动动画中的采样抖动)。 */
|
||||
private fun scrollToTop(maxSwipes: Int = 25) {
|
||||
var prevSignature = ""
|
||||
var stableCount = 0
|
||||
for (i in 0 until maxSwipes) {
|
||||
val signature = screen().map { it.text.trim() }.joinToString("|")
|
||||
if (signature == prevSignature) {
|
||||
stableCount++
|
||||
if (stableCount >= 2) {
|
||||
log("回读:已滚动到顶部(第 $i 次反向滑,连续 $stableCount 次稳定)")
|
||||
return
|
||||
}
|
||||
} else {
|
||||
stableCount = 0
|
||||
}
|
||||
prevSignature = signature
|
||||
val ok = kotlinx.coroutines.runBlocking {
|
||||
service.gestures.swipe(0.5f, 0.30f, 0.5f, 0.70f)
|
||||
}
|
||||
if (!ok) return
|
||||
Thread.sleep(800)
|
||||
}
|
||||
log("回读:反向滑 $maxSwipes 次未稳定(文档可能超长),按当前顶部继续")
|
||||
}
|
||||
|
||||
/** 安全收尾:HOME 离开编辑器(红线:不点「下一步」/「发布」;草稿自动保存不受影响)。 */
|
||||
override fun exitEditor(): Boolean = kotlinx.coroutines.runBlocking { service.gestures.home() }
|
||||
|
||||
// ── 导航:我的→创作中心→+发布→文章 ───────────────────────
|
||||
|
||||
/**
|
||||
* 打开文章编辑器(新空稿)。循环核屏导航:每步以 OCR 文本+区域约束定位,
|
||||
* 命中才点;未知页面等待重试。
|
||||
* @return true=编辑器空稿就绪(占位「请输入标题」可见)。
|
||||
*/
|
||||
fun openArticleEditor(): Boolean {
|
||||
val deadline = SystemClock.elapsedRealtime() + NAV_TIMEOUT_MS
|
||||
while (SystemClock.elapsedRealtime() < deadline) {
|
||||
if (service.currentPackage() != TOUTIAO_PKG) {
|
||||
service.launchApp(TOUTIAO_PKG)
|
||||
Thread.sleep(1_500)
|
||||
continue
|
||||
}
|
||||
val lines = screen()
|
||||
val height = runCatching { service.gestures.screenHeight }.getOrDefault(2408)
|
||||
// ⓪ 干扰弹层(成就海报/活动页)→ BACK 关闭。
|
||||
// 2026-11-15 真机:发文触发「恭喜你的发文累计阅读量破N」成就弹层挡住创作中心,
|
||||
// 机器不认识导致 58s 轮询超时;BACK 可关该弹层,不动弹层内任何按钮。
|
||||
val popup = lines.firstOrNull {
|
||||
it.text.contains("保存海报并分享") || it.text.contains("编辑后发文") ||
|
||||
it.text.contains("恭喜你的发文") || it.text.contains("累计阅读量破")
|
||||
}
|
||||
if (popup != null) {
|
||||
log("导航:发现成就/活动弹层,BACK 关闭")
|
||||
kotlinx.coroutines.runBlocking { service.gestures.back() }
|
||||
Thread.sleep(1_500); continue
|
||||
}
|
||||
// ⓪′ 信用分门控遗留深层页(处罚中心/全部服务等)→ BACK 收拢回首页。
|
||||
// 2026-11-17 真机两轮实锤:
|
||||
// - 处罚中心 BACK 一跳到「全部服务」(有作品管理锚点但无顶部「发布」,
|
||||
// 判据③不命中)→ 锚点须覆盖门控导航链沿途页面;
|
||||
// - ⚠️ 创作中心页同样含「作品管理/创作工具/收益提现」字样但方向相反
|
||||
// (要点「+发布」不是 BACK)——这些词不能进本判据;判据锚点限定
|
||||
// 处罚中心专属词 + 「全部服务」页专属标题,且无首页底栏。
|
||||
val deepAnchor = lines.any {
|
||||
it.text.contains("处罚记录") || it.text.contains("账号处罚中心") ||
|
||||
it.text.contains("全部服务") || it.text.contains("信用分") ||
|
||||
it.text.contains("治理公告")
|
||||
} && !lines.any { it.text.trim() == "首页" && (it.boundingBox?.top ?: 0) > height * 0.85 } &&
|
||||
// 排除创作中心:有顶部「发布」或「作品管理+数据助手」组合走判据③
|
||||
!lines.any { it.text.contains("发布") && (it.boundingBox?.top ?: Int.MAX_VALUE) < height * 0.12 }
|
||||
if (deepAnchor) {
|
||||
log("导航:信用分门控遗留深层页,BACK 回首页")
|
||||
kotlinx.coroutines.runBlocking { service.gestures.back() }
|
||||
Thread.sleep(1_500); continue
|
||||
}
|
||||
// ① 已在编辑器空稿
|
||||
if (editorMarkers(lines)) return true
|
||||
// ② 发布面板(微头条撰写页)→「文章」Tab(底部)。
|
||||
// ⚠️ 文章编辑器底部有同款「文章/微头条」Tab 行——必须先排除编辑器标记,
|
||||
// 否则会在编辑器里反复点 Tab(2026-11-15 真机缺陷)。
|
||||
val articleTab = lines.firstOrNull {
|
||||
it.text.contains("文章") && (it.boundingBox?.top ?: 0) > height * 0.8
|
||||
}
|
||||
if (articleTab != null && lines.any { it.text.contains("微头条") } && !editorMarkers(lines)) {
|
||||
log("导航:发布面板 →「文章」Tab")
|
||||
tapCenter(articleTab); Thread.sleep(1_500); continue
|
||||
}
|
||||
// ③ 创作中心(作品管理/创作权益特征)→ 右上「+发布」
|
||||
val publish = lines.firstOrNull {
|
||||
it.text.contains("发布") && (it.boundingBox?.top ?: Int.MAX_VALUE) < height * 0.12
|
||||
}
|
||||
if (publish != null && lines.any { it.text.contains("作品管理") || it.text.contains("创作权益") }) {
|
||||
log("导航:创作中心 →「+发布」")
|
||||
tapCenter(publish); Thread.sleep(1_500); continue
|
||||
}
|
||||
// ④ 我的页 →「查看我的创作中心」卡片
|
||||
val creator = lines.firstOrNull { it.text.contains("查看我的创作中心") }
|
||||
if (creator != null) {
|
||||
log("导航:我的 → 创作中心")
|
||||
tapCenter(creator); Thread.sleep(1_500); continue
|
||||
}
|
||||
// ⑤ 头条首页(底栏首页+我的)→「我的」Tab
|
||||
val myTab = lines.firstOrNull {
|
||||
it.text.trim() == "我的" && (it.boundingBox?.top ?: 0) > height * 0.85
|
||||
}
|
||||
val homeTab = lines.any {
|
||||
it.text.trim() == "首页" && (it.boundingBox?.top ?: 0) > height * 0.85
|
||||
}
|
||||
if (myTab != null && homeTab) {
|
||||
log("导航:首页 →「我的」Tab")
|
||||
tapCenter(myTab); Thread.sleep(1_500); continue
|
||||
}
|
||||
Thread.sleep(1_200) // 未知页面(加载中/弹层):核屏等待
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ── 内部工具 ──────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 编辑器标记(多组取或):
|
||||
* ① 头部深色标记(高对比度,OCR 稳):「草稿将自动保存/草稿已保存/数字字/」+「取消」;
|
||||
* ② 灰字占位「请输入标题/请输入正文」(辅助信号)。
|
||||
* 微头条撰写页只有「取消/草稿箱/说点什么」,不会命中本判据。
|
||||
*/
|
||||
private fun editorMarkers(lines: List<OcrTextLine>): Boolean {
|
||||
val texts = lines.map { it.text }
|
||||
val placeholder = texts.any { it.contains("请输入标题") || it.contains("请输入正文") }
|
||||
val header = texts.any {
|
||||
it.contains("草稿将自动保存") || it.contains("草稿已保存") || WORD_COUNT_PREFIX.containsMatchIn(it)
|
||||
} && texts.any { it.contains("取消") }
|
||||
return placeholder || header
|
||||
}
|
||||
|
||||
private var lastCaptureAtMs = 0L
|
||||
|
||||
/**
|
||||
* 单屏 OCR。⚠️ `AccessibilityService.takeScreenshot` 有系统频率限制——过密连拍会
|
||||
* 全部 errorCode=3 被拒(2026-11-15 真机:machine 连拍 6 次全灭→误判"不在编辑器")。
|
||||
* 本函数统一节流到至少 [MIN_CAPTURE_INTERVAL_MS] 一拍,保护全部调用方。
|
||||
*/
|
||||
private fun screen(): List<OcrTextLine> {
|
||||
val since = SystemClock.elapsedRealtime() - lastCaptureAtMs
|
||||
if (since < MIN_CAPTURE_INTERVAL_MS) Thread.sleep(MIN_CAPTURE_INTERVAL_MS - since)
|
||||
lastCaptureAtMs = SystemClock.elapsedRealtime() // 尝试也占限流额度
|
||||
val bitmap: Bitmap = kotlinx.coroutines.runBlocking {
|
||||
ScreenCapturer(service).capture()
|
||||
} ?: return emptyList()
|
||||
return try {
|
||||
kotlinx.coroutines.runBlocking { OcrProcessor.recognize(bitmap) }
|
||||
.flatMap { it.lines }
|
||||
.filter { it.text.isNotBlank() }
|
||||
} finally {
|
||||
bitmap.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
/** 按 OCR 行 bounds 求中心点击(红线:坐标出自核屏内容)。 */
|
||||
private fun tapCenter(line: OcrTextLine): Boolean {
|
||||
val box = line.boundingBox ?: return false
|
||||
val x = (box.left + box.right) / 2
|
||||
val y = (box.top + box.bottom) / 2
|
||||
log("点击「${line.text.take(12)}」@($x,$y)")
|
||||
return kotlinx.coroutines.runBlocking { service.gestures.tapAt(x, y) }
|
||||
}
|
||||
|
||||
private fun tapFallback(x: Int, y: Int, reason: String): Boolean {
|
||||
log(reason)
|
||||
return kotlinx.coroutines.runBlocking { service.gestures.tapAt(x, y) }
|
||||
}
|
||||
|
||||
private fun isDebugImeCurrent(): Boolean =
|
||||
android.provider.Settings.Secure.getString(service.contentResolver, "default_input_method")
|
||||
?.startsWith("com.haorui.app/") == true
|
||||
|
||||
private fun log(msg: String) = RunLogger.i(TAG, msg)
|
||||
}
|
||||
@@ -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,75 @@
|
||||
package com.haorui.app.crossplatform.source
|
||||
|
||||
/**
|
||||
* 来源页面的中立节点树。
|
||||
*
|
||||
* 同一棵树同时服务两个输入端:真机无障碍树(运行时)与 uiautomator XML 页面样本(测试/取证),
|
||||
* 使采集解析器可以在 JVM 上按真实页面样本验收,不必起真机。
|
||||
* 只读属性,不做任何点击决策;坐标兜底必须绑定页面指纹,禁止盲点。
|
||||
*/
|
||||
data class SourceBounds(val left: Int, val top: Int, val right: Int, val bottom: Int) {
|
||||
val centerX: Int get() = (left + right) / 2
|
||||
val centerY: Int get() = (top + bottom) / 2
|
||||
|
||||
companion object {
|
||||
private val PATTERN = Regex("\\[(-?\\d+),(-?\\d+)]\\[(-?\\d+),(-?\\d+)]")
|
||||
|
||||
/** 解析 uiautomator 的 `bounds="[l,t][r,b]"`;格式不符返回 null,不猜测。 */
|
||||
fun parse(raw: String?): SourceBounds? {
|
||||
val text = raw?.trim().orEmpty()
|
||||
val match = PATTERN.matchEntire(text) ?: return null
|
||||
val (left, top, right, bottom) = match.destructured
|
||||
return SourceBounds(left.toInt(), top.toInt(), right.toInt(), bottom.toInt())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class SourceNode(
|
||||
val id: String = "",
|
||||
val text: String = "",
|
||||
val description: String = "",
|
||||
val className: String = "",
|
||||
val clickable: Boolean = false,
|
||||
val bounds: SourceBounds? = null,
|
||||
val children: List<SourceNode> = emptyList(),
|
||||
) {
|
||||
/** 先序遍历(含自身)。 */
|
||||
fun selfAndDescendants(): List<SourceNode> = buildList {
|
||||
add(this@SourceNode)
|
||||
children.forEach { addAll(it.selfAndDescendants()) }
|
||||
}
|
||||
|
||||
fun findAll(predicate: (SourceNode) -> Boolean): List<SourceNode> =
|
||||
selfAndDescendants().filter(predicate)
|
||||
|
||||
/** 精确匹配完整 resource-id 的第一个节点(不做后缀模糊,避免 ranking_no 误吞 ranking_no_img)。 */
|
||||
fun firstById(resourceId: String): SourceNode? =
|
||||
selfAndDescendants().firstOrNull { it.id == resourceId }
|
||||
|
||||
fun allById(resourceId: String): List<SourceNode> =
|
||||
selfAndDescendants().filter { it.id == resourceId }
|
||||
|
||||
/**
|
||||
* 把散落在不同子树的字段聚成“卡片/条目”:返回子树同时包含全部指定 id 的**最深**节点。
|
||||
* 用于热榜卡片(trend_layout 组)、回答条目(shortContainerTemplateView 组)等成组解析,
|
||||
* 防止字段与邻近条目串组(同名标题不同内容、迟到节点混入等场景)。
|
||||
*/
|
||||
fun deepestGroupsContaining(vararg ids: String): List<SourceNode> {
|
||||
val wanted = ids.toSet()
|
||||
val groups = mutableListOf<SourceNode>()
|
||||
|
||||
fun subtreeHas(node: SourceNode, id: String): Boolean =
|
||||
node.selfAndDescendants().any { it.id == id }
|
||||
|
||||
fun walk(node: SourceNode) {
|
||||
val qualifies = wanted.all { subtreeHas(node, it) }
|
||||
if (qualifies && node.children.none { child -> wanted.all { subtreeHas(child, it) } }) {
|
||||
groups += node
|
||||
return
|
||||
}
|
||||
node.children.forEach(::walk)
|
||||
}
|
||||
walk(this)
|
||||
return groups
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.haorui.app.crossplatform.source
|
||||
|
||||
import android.graphics.Rect
|
||||
import android.view.accessibility.AccessibilityNodeInfo
|
||||
|
||||
/**
|
||||
* 真机无障碍节点树 → 中立 [SourceNode] 树。
|
||||
*
|
||||
* 与 [SourceNodeXml](uiautomator 样本)产出同一棵树,采集解析器即可
|
||||
* “样本在 JVM 验收、真机同一套解析”。只读转换:不缓存节点、不做点击决策,
|
||||
* 调用方用完即可让原 AccessibilityNodeInfo 回收。
|
||||
*/
|
||||
object SourceNodeAccessibility {
|
||||
/** 转换整棵树;[maxDepth] 防异常深层嵌套,超出的子树截断为空。 */
|
||||
fun from(node: AccessibilityNodeInfo, depth: Int = 0, maxDepth: Int = 40): SourceNode {
|
||||
val rect = Rect()
|
||||
node.getBoundsInScreen(rect)
|
||||
val children = if (depth >= maxDepth) emptyList() else buildList {
|
||||
for (i in 0 until node.childCount) {
|
||||
val child = node.getChild(i) ?: continue
|
||||
try {
|
||||
add(from(child, depth + 1, maxDepth))
|
||||
} finally {
|
||||
runCatching { child.recycle() }
|
||||
}
|
||||
}
|
||||
}
|
||||
return SourceNode(
|
||||
id = node.viewIdResourceName.orEmpty(),
|
||||
text = node.text?.toString().orEmpty(),
|
||||
description = node.contentDescription?.toString().orEmpty(),
|
||||
className = node.className?.toString().orEmpty(),
|
||||
clickable = node.isClickable,
|
||||
bounds = SourceBounds(rect.left, rect.top, rect.right, rect.bottom),
|
||||
children = children,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.haorui.app.crossplatform.source
|
||||
|
||||
import java.io.StringReader
|
||||
import javax.xml.parsers.DocumentBuilderFactory
|
||||
import org.xml.sax.InputSource
|
||||
|
||||
/**
|
||||
* uiautomator dump XML → [SourceNode]。
|
||||
*
|
||||
* 仅服务于页面样本(测试/取证留存的 dump),属性映射固定为
|
||||
* resource-id / text / content-desc / class / clickable / bounds;
|
||||
* 解析失败抛 [IllegalArgumentException],不静默返回空树,避免样本损坏被当作“页面无节点”。
|
||||
*/
|
||||
object SourceNodeXml {
|
||||
fun parse(xml: String): SourceNode {
|
||||
val factory = DocumentBuilderFactory.newInstance()
|
||||
// 禁用 DTD/外部实体,样本是本地数据,不需要实体解析,同时避免 XXE。
|
||||
runCatching { factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) }
|
||||
runCatching { factory.setFeature("http://xml.org/sax/features/external-general-entities", false) }
|
||||
runCatching { factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false) }
|
||||
val document = try {
|
||||
factory.newDocumentBuilder().parse(InputSource(StringReader(xml)))
|
||||
} catch (error: Exception) {
|
||||
throw IllegalArgumentException("页面样本 XML 解析失败:${error.javaClass.simpleName}", error)
|
||||
}
|
||||
val roots = document.getElementsByTagName("node")
|
||||
if (roots.length == 0) throw IllegalArgumentException("页面样本 XML 中没有 node 节点")
|
||||
// dump 的根 node 就是整棵屏幕树;若出现多个顶层 node,包一层虚拟根统一返回。
|
||||
val parsed = mutableListOf<SourceNode>()
|
||||
for (index in 0 until roots.length) {
|
||||
val element = roots.item(index) as? org.w3c.dom.Element ?: continue
|
||||
if (element.parentNode?.nodeName == "node") continue
|
||||
parsed += fromElement(element)
|
||||
}
|
||||
return when (parsed.size) {
|
||||
1 -> parsed.single()
|
||||
else -> SourceNode(children = parsed)
|
||||
}
|
||||
}
|
||||
|
||||
/** 供真机适配复用:把任意具名属性的节点转换为 [SourceNode](属性缺失即空值,不推断)。 */
|
||||
fun fromElement(element: org.w3c.dom.Element): SourceNode {
|
||||
fun attr(name: String): String = element.getAttribute(name).orEmpty()
|
||||
val children = mutableListOf<SourceNode>()
|
||||
val childNodes = element.childNodes
|
||||
for (index in 0 until childNodes.length) {
|
||||
val child = childNodes.item(index)
|
||||
if (child is org.w3c.dom.Element && child.nodeName == "node") children += fromElement(child)
|
||||
}
|
||||
return SourceNode(
|
||||
id = attr("resource-id"),
|
||||
text = attr("text"),
|
||||
description = attr("content-desc"),
|
||||
className = attr("class"),
|
||||
clickable = attr("clickable") == "true",
|
||||
bounds = SourceBounds.parse(attr("bounds")),
|
||||
children = children,
|
||||
)
|
||||
}
|
||||
|
||||
/** 便捷入口:从字节数组样本加载(取证文件读入后调用)。 */
|
||||
fun parse(bytes: ByteArray): SourceNode = parse(String(bytes, Charsets.UTF_8))
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
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"),
|
||||
// 抖音(2026-11-17 验收):MediaProjection 数据源+OCR 解析+单条详情采集全链通过
|
||||
// 能力:HOT_LIST(热榜解析 4~6 条)+ DETAIL(详情观察 outcome=已观察 phase=DONE)
|
||||
// SHARE_LINK/MEDIA_IMPORT 未取证,不列入
|
||||
SourceDefinition(
|
||||
id = "douyin", label = "抖音", packageName = "com.ss.android.ugc.aweme",
|
||||
verifiedVersions = setOf("39.8.0"),
|
||||
capabilities = setOf(SourceCapability.HOT_LIST, SourceCapability.DETAIL),
|
||||
),
|
||||
)
|
||||
|
||||
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,71 @@
|
||||
package com.haorui.app.crossplatform.source.douyin
|
||||
|
||||
/**
|
||||
* 抖音详情页解析结果(2026-11-16 e1 取证口径)。
|
||||
*
|
||||
* 详情页 = 搜索结果页(词条自动填入搜索框):
|
||||
* 热榜 TOP10 横条(5630.1万人在看)+ 综合/视频/图文/用户/直播/商品 Tab + 内容卡。
|
||||
* 作者/正文/相对时间「3天前」在自绘区(e1 截图实证)——OCR 行为唯一输入源,
|
||||
* 树内字段(互动数等)形态尚未 e2 核验,核验前一律 null。
|
||||
*/
|
||||
data class DouyinDetail(
|
||||
val author: String? = null,
|
||||
val content: String? = null,
|
||||
val publishedAtText: String? = null,
|
||||
val publishedAtMs: Long? = null,
|
||||
val unknownReason: String = "",
|
||||
)
|
||||
|
||||
/** 单条抖音观察结果(采集机输出)。 */
|
||||
data class DouyinPostObservation(
|
||||
val hotEntry: DouyinHotEntry? = null,
|
||||
val author: String? = null,
|
||||
val content: String? = null,
|
||||
val publishedAtText: String? = null,
|
||||
val publishedAtMs: Long? = null,
|
||||
val sourceUrl: String? = null,
|
||||
val fetchedAtMs: Long = 0,
|
||||
val runGeneration: Long = 0,
|
||||
val unknowns: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* 抖音详情解析器(骨架:只落已核验口径,未核验字段显式留 null)。
|
||||
*
|
||||
* 时间白名单(e1 实测「3天前」相对时间形态):相对时间折算绝对时刻;
|
||||
* 「昨天」「X小时前」「X分钟前」为常见形态一并支持;绝对日期形态(如「11-15」)未取证,不认。
|
||||
* 作者行启发式(OCR 行首「@昵称」)未核验——暂不启用,作者恒 null 待 e2 取证。
|
||||
*/
|
||||
object DouyinDetailParser {
|
||||
private val RELATIVE_PATTERNS = listOf(
|
||||
Regex("^(\\d+)分钟前$") to 60_000L,
|
||||
Regex("^(\\d+)小时前$") to 3_600_000L,
|
||||
Regex("^(\\d+)天前$") to 86_400_000L,
|
||||
)
|
||||
|
||||
fun parse(tree: com.haorui.app.crossplatform.source.SourceNode, ocrLines: List<String>, nowMs: Long): DouyinDetail {
|
||||
// 树内字段形态未核验(e2 待做):不从树读任何字段,全部留 null。
|
||||
val published = parseRelativeTime(ocrLines, nowMs)
|
||||
return DouyinDetail(
|
||||
author = null,
|
||||
content = null,
|
||||
publishedAtText = published?.first,
|
||||
publishedAtMs = published?.second,
|
||||
unknownReason = if (published == null) "详情 OCR 未读到已核验时间形态" else "",
|
||||
)
|
||||
}
|
||||
|
||||
/** OCR 行内取第一个命中白名单的相对时间;形态未核验不认。 */
|
||||
internal fun parseRelativeTime(ocrLines: List<String>, nowMs: Long): Pair<String, Long>? {
|
||||
ocrLines.forEach { raw ->
|
||||
val line = raw.trim()
|
||||
RELATIVE_PATTERNS.forEach { (pattern, unitMs) ->
|
||||
val match = pattern.matchEntire(line) ?: return@forEach
|
||||
val value = match.groupValues[1].toIntOrNull() ?: return@forEach
|
||||
if (value < 0 || value > 365) return@forEach
|
||||
return line to (nowMs - value * unitMs)
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,730 @@
|
||||
package com.haorui.app.crossplatform.source.douyin
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.os.SystemClock
|
||||
import android.view.accessibility.AccessibilityNodeInfo
|
||||
import com.haorui.app.automation.HaoRuiAccessibilityService
|
||||
import com.haorui.app.automation.NodeLocator
|
||||
import com.haorui.app.automation.RunLogger
|
||||
import com.haorui.app.crossplatform.source.SourceBounds
|
||||
import com.haorui.app.crossplatform.source.SourceNode
|
||||
import com.haorui.app.crossplatform.source.SourceNodeAccessibility
|
||||
|
||||
/**
|
||||
* 抖音采集真机驱动([DouyinHotListCollector.Port] 实现,2026-11-16 e1 取证口径)。
|
||||
*
|
||||
* 入口链锚点(e1 dump 实证):
|
||||
* - 首页右上「搜索」按钮:content-desc="搜索"、clickable、x>900、y<300;
|
||||
* - 搜索页「抖音热榜」Tab:content-desc 以“抖音热榜”开头(选中态带“已选中”后缀),
|
||||
* **页内切换不换 Activity**(e1 实证:focus 恒为 SearchResultActivity);
|
||||
* - 热榜列表自绘渲染(XML 树无词条文本)→ OCR 行解析;
|
||||
* - 词条点按按解析行 bounds 定位(e1 教训:屏上估算行位偏移一行,禁止盲估)。
|
||||
*
|
||||
* 详情页分享面板动作(2026-11-18 用户决策修订):「分享链接」「保存本地」两个
|
||||
* 只读复制/落盘动作已放行(saveLocalFromSharePanel/copyShareLink);「投稿」与
|
||||
* 外发动作(私信/微信/QQ/转发到日常/帮上热门等)仍为红线,Port 不提供触发方法。
|
||||
*/
|
||||
internal class DouyinDevicePort(
|
||||
private val service: HaoRuiAccessibilityService,
|
||||
) : DouyinHotListCollector.Port {
|
||||
private companion object {
|
||||
const val TAG = "Douyin-Port"
|
||||
const val DOUYIN_PKG = "com.ss.android.ugc.aweme"
|
||||
const val WAIT_STEP_MS = 400L
|
||||
/** 榜单 Tab 行 y 区间(e1 实测 [299,1118][531,1190] 一带;键盘/弹层遮挡时此区间无匹配)。 */
|
||||
const val TAB_Y_MIN = 900
|
||||
const val TAB_Y_MAX = 1500
|
||||
}
|
||||
|
||||
// ── 基础工具(与知乎/微博 Port 同型) ─────────────────────
|
||||
|
||||
private fun log(message: String) = RunLogger.i(TAG, message)
|
||||
|
||||
private fun tree(): SourceNode? = service.root()?.let { SourceNodeAccessibility.from(it) }
|
||||
|
||||
private fun waitTree(timeoutMs: Long, until: (SourceNode) -> Boolean): Boolean {
|
||||
val deadline = SystemClock.elapsedRealtime() + timeoutMs
|
||||
while (SystemClock.elapsedRealtime() < deadline) {
|
||||
val t = tree()
|
||||
if (t != null && until(t)) return true
|
||||
Thread.sleep(WAIT_STEP_MS)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** 活树有界遍历找节点(供坐标点击;抖音热榜 Tab 为不可点击 ViewGroup,需按 bounds 手势点)。 */
|
||||
private fun liveFind(
|
||||
root: AccessibilityNodeInfo?,
|
||||
budget: Int = 3_000,
|
||||
predicate: (AccessibilityNodeInfo, android.graphics.Rect) -> Boolean,
|
||||
): android.graphics.Rect? {
|
||||
if (root == null) return null
|
||||
var visited = 0
|
||||
val rect = android.graphics.Rect()
|
||||
fun walk(node: AccessibilityNodeInfo): android.graphics.Rect? {
|
||||
if (visited++ > budget) return null
|
||||
runCatching { node.getBoundsInScreen(rect) }
|
||||
if (predicate(node, rect)) return android.graphics.Rect(rect)
|
||||
for (i in 0 until node.childCount) {
|
||||
val child = node.getChild(i) ?: continue
|
||||
val found = try { walk(child) } finally { runCatching { child.recycle() } }
|
||||
if (found != null) return found
|
||||
}
|
||||
return null
|
||||
}
|
||||
return walk(root)
|
||||
}
|
||||
|
||||
/**
|
||||
* 单屏截屏(MediaProjection 优先,回退 takeScreenshot)。
|
||||
* ⚠️ r27 实锤:投影就绪时**不回退 takeScreenShot**——runBlocking+Dispatchers.Main
|
||||
* 在前台协程中会死锁(主线程被 runBlocking 堵住,withContext(Main) 截屏永远排队不上)。
|
||||
* 投影就绪但无帧时返回 null,由调用方处理(不走 runBlocking)。
|
||||
*/
|
||||
private fun captureScreen(): Bitmap? {
|
||||
val projFrame = com.haorui.app.ocr.ProjectionCapturer.capture()
|
||||
if (projFrame != null) {
|
||||
log("截屏走投影通道 ${projFrame.width}x${projFrame.height}")
|
||||
return projFrame
|
||||
}
|
||||
// 投影未就绪才走 takeScreenshot(runBlocking 在后台线程安全)
|
||||
if (com.haorui.app.ocr.ProjectionHolder.isReady) {
|
||||
log("投影已就绪但无帧(frameCount 可能为 0),返回 null 不走 runBlocking")
|
||||
return null
|
||||
}
|
||||
log("投影未就绪,走 takeScreenshot")
|
||||
return kotlinx.coroutines.runBlocking {
|
||||
com.haorui.app.ocr.ScreenCapturer(service).capture()
|
||||
}
|
||||
}
|
||||
|
||||
private fun ocrCurrentScreen(): List<String> {
|
||||
val bitmap: Bitmap = captureScreen() ?: return emptyList()
|
||||
return try {
|
||||
val blocks = try {
|
||||
kotlinx.coroutines.runBlocking {
|
||||
kotlinx.coroutines.withTimeout(8_000) {
|
||||
com.haorui.app.ocr.OcrProcessor.recognize(bitmap)
|
||||
}
|
||||
}
|
||||
} catch (_: Exception) { emptyList() }
|
||||
blocks.flatMap { it.lines }.map { it.text.trim() }.filter { it.isNotEmpty() }
|
||||
} finally {
|
||||
bitmap.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
/** OCR 行轮询等待:until 命中即返回 true(有上限)。超时打印末轮采样辅助诊断。 */
|
||||
private fun waitOcr(timeoutMs: Long, until: (List<String>) -> Boolean, tagForDebug: String = ""): Boolean {
|
||||
val deadline = SystemClock.elapsedRealtime() + timeoutMs
|
||||
var lastLines: List<String> = emptyList()
|
||||
while (SystemClock.elapsedRealtime() < deadline) {
|
||||
val lines = ocrCurrentScreen()
|
||||
lastLines = lines
|
||||
if (lines.isNotEmpty() && until(lines)) return true
|
||||
Thread.sleep(1_000) // OCR 有成本,轮询间隔放宽
|
||||
}
|
||||
if (tagForDebug.isNotEmpty()) {
|
||||
log("OCR 判据超时[$tagForDebug] 末轮 ${lastLines.size} 行采样: ${lastLines.take(8)}")
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** OCR 定位含指定文本的行,返回该行 bounds(截屏坐标系);找不到返回 null。 */
|
||||
private fun ocrFindLine(fragment: String): android.graphics.Rect? =
|
||||
ocrFindLineWithBounds(fragment)?.second
|
||||
|
||||
/** OCR 定位含指定文本的行,返回(行文本, 行 bounds);找不到返回 null。 */
|
||||
private fun ocrFindLineWithBounds(fragment: String): Pair<String, android.graphics.Rect>? {
|
||||
val bitmap: Bitmap = captureScreen() ?: return null
|
||||
return try {
|
||||
val blocks = kotlinx.coroutines.runBlocking { com.haorui.app.ocr.OcrProcessor.recognize(bitmap) }
|
||||
blocks.asSequence()
|
||||
.flatMap { it.lines.asSequence() }
|
||||
.mapNotNull { line -> line.boundingBox?.let { rect -> line to rect } }
|
||||
.firstOrNull { (line, _) -> line.text.replace(" ", "").contains(fragment) }
|
||||
?.let { (line, rect) -> line.text to rect }
|
||||
} finally {
|
||||
bitmap.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
// ── Port 实现 ────────────────────────────────────────────
|
||||
|
||||
override fun ensureAppForeground(): Boolean {
|
||||
val deadline = SystemClock.elapsedRealtime() + 25_000
|
||||
var backs = 0
|
||||
var launches = 0
|
||||
while (SystemClock.elapsedRealtime() < deadline) {
|
||||
// ⚠️ 包名判断兜底:抖音 Splash 常驻壳/沉浸视频页下 root().packageName 可能为 null
|
||||
// (首跑实锤:launchApp 成功后 currentPackage() 仍判非抖音 → 死循环拉起)。
|
||||
// 策略:只拉起一次,之后改用「树内有底栏 Tab」判定就绪——树读得到就是前台可操作。
|
||||
val pkg = service.currentPackage()
|
||||
if (pkg != DOUYIN_PKG) {
|
||||
if (launches >= 1) {
|
||||
// 已拉起过仍读不到包名:用树就绪判据直接验证(Splash 壳下的视频页是常态)
|
||||
val readyByTree = tree()?.let { t ->
|
||||
val flat = t.selfAndDescendants()
|
||||
flat.any { n -> n.text == "首页" && (n.bounds?.top ?: 0) > 2_000 } &&
|
||||
flat.any { n -> n.text == "我" && (n.bounds?.top ?: 0) > 2_000 }
|
||||
} == true
|
||||
if (readyByTree) {
|
||||
log("包名不可读但树就绪(Splash 壳),按前台处理")
|
||||
return true
|
||||
}
|
||||
Thread.sleep(WAIT_STEP_MS)
|
||||
continue
|
||||
}
|
||||
launches++
|
||||
service.launchApp(DOUYIN_PKG)
|
||||
Thread.sleep(1_500)
|
||||
continue
|
||||
}
|
||||
val root = service.root()
|
||||
if (root == null) {
|
||||
Thread.sleep(WAIT_STEP_MS)
|
||||
continue
|
||||
}
|
||||
// 开屏广告/弹窗:只点「跳过」,不点广告本体(知乎同款口径)
|
||||
val skip = NodeLocator.byTextContains(root, "跳过")
|
||||
if (skip != null) {
|
||||
runCatching { kotlinx.coroutines.runBlocking { service.gestures.tapNode(skip) } }
|
||||
.onSuccess { log("开屏广告跳过") }
|
||||
runCatching { skip.recycle() }
|
||||
Thread.sleep(1_000)
|
||||
continue
|
||||
}
|
||||
// 就绪判据:底栏「首页」+「我」同在屏(y>2000,e1 实测底栏 y≈2175)
|
||||
val ready = tree()?.let { t ->
|
||||
val flat = t.selfAndDescendants()
|
||||
flat.any { n -> n.text == "首页" && (n.bounds?.top ?: 0) > 2_000 } &&
|
||||
flat.any { n -> n.text == "我" && (n.bounds?.top ?: 0) > 2_000 }
|
||||
} == true
|
||||
if (ready) return true
|
||||
// 过渡态残留:有界 BACK 收拢
|
||||
if (backs < 3) {
|
||||
backs++
|
||||
service.gestures.back()
|
||||
log("残留页面收拢:第 $backs 次返回")
|
||||
Thread.sleep(1_000)
|
||||
continue
|
||||
}
|
||||
Thread.sleep(WAIT_STEP_MS)
|
||||
}
|
||||
log("进入抖音前台失败")
|
||||
return false
|
||||
}
|
||||
|
||||
override fun openSearch(): Boolean {
|
||||
// 右上「搜索」:desc="搜索"、clickable、x>900、y<300(e1 dump 实证 [924,108][1080,240])。
|
||||
// 搜索钮本身在首页树可达(desc 形态);就绪判据走 OCR(搜索页内容树不可达,r4 实证)。
|
||||
// ⚠️ r12 实锤:上次采集残留的词条详情页会让点搜索钮直接跳详情——先 OCR 检测
|
||||
// 详情页特征(热榜TOP/万人在看),命中则 BACK 回搜索主页再继续。
|
||||
val deadline = SystemClock.elapsedRealtime() + 15_000
|
||||
var logged = false
|
||||
var backs = 0
|
||||
while (SystemClock.elapsedRealtime() < deadline) {
|
||||
// 详情残留排除:BACK 收拢(有上限)
|
||||
val onDetail = runCatching { ocrCurrentScreen() }.getOrDefault(emptyList()).any {
|
||||
it.replace(" ", "").contains("热榜TOP") || it.contains("万人在看")
|
||||
}
|
||||
if (onDetail && backs < 3) {
|
||||
backs++
|
||||
service.gestures.back()
|
||||
log("检测到词条详情残留,BACK $backs 次收拢")
|
||||
Thread.sleep(1_000)
|
||||
continue
|
||||
}
|
||||
val root = service.root()
|
||||
val rect = root?.let {
|
||||
liveFind(it, budget = 2_000) { node, r ->
|
||||
node.contentDescription?.toString() == "搜索" &&
|
||||
node.isClickable && r.left > 900 && r.top < 300
|
||||
}
|
||||
}
|
||||
if (rect != null) {
|
||||
if (!logged) { log("定位到搜索钮 bounds=$rect"); logged = true }
|
||||
// r27 实锤:runBlocking+tapAt 在前台协程可能死锁——加超时兜底
|
||||
val ok = try {
|
||||
kotlinx.coroutines.runBlocking {
|
||||
kotlinx.coroutines.withTimeout(5_000) {
|
||||
service.gestures.tapAt(rect.centerX(), rect.centerY(), retry = true)
|
||||
}
|
||||
}
|
||||
} catch (_: Exception) { false }
|
||||
if (ok) {
|
||||
// 就绪判据走 OCR:搜索页特有锚点「猜你想看」在屏,且**详情页特征不在屏**。
|
||||
// ⚠️ r33 实锤:搜索按钮点击后可能停留在「上热门」页(Tab 行=「上热门话題榜|宁波榜|直播榜」)——
|
||||
// 必须等「猜你想看」出现(搜索页 Tab 行锚点)才算进入搜索页。
|
||||
val entered = waitOcr(12_000, until = { lines ->
|
||||
val hasSearchAnchor = lines.any { line ->
|
||||
val clean = line.replace(" ", "")
|
||||
clean.contains("猜你想看") || clean.contains("语音搜索") || clean.contains("展开更多历史")
|
||||
}
|
||||
val onDetail = lines.any { it.replace(" ", "").contains("热榜TOP") || it.contains("万人在看") }
|
||||
hasSearchAnchor && !onDetail
|
||||
}, tagForDebug = "search-page")
|
||||
if (entered) return true
|
||||
}
|
||||
} else if (!logged) {
|
||||
log("搜索钮未定位(树${if (root == null) "空" else "有"},抖音可能未落首页)")
|
||||
}
|
||||
Thread.sleep(WAIT_STEP_MS)
|
||||
}
|
||||
log("搜索入口未打开")
|
||||
return false
|
||||
}
|
||||
|
||||
override fun openHotListTab(): Boolean {
|
||||
// 「抖音热榜」Tab:树不可达(r4 实证),按 OCR 行 bounds 定位点击;
|
||||
// 选中态判据 = 热榜列表行出现(「排名+标题+热度」形态,见 DouyinHotListParser)。
|
||||
// ⚠️ r9 实锤:OCR 把 Tab 行识别为「猜你想看 抖音热榜」(行只含前两词),
|
||||
// 「抖音热榜」词中心≈行宽 76%(e1 校准 x=404/行宽 530)。
|
||||
// ⚠️ r10 实锤:BACK 收键盘可能连搜索页一起退出(OCR 找不到 Tab 行)——
|
||||
// 此时返回 false 让采集机归 OPEN_HOT_TAB 失败;改为**不主动 BACK**,
|
||||
// 先直接尝试找 Tab 行(r9 已证浮层下的 Tab 行 OCR 仍可读可点),
|
||||
// 只有连续找不到才 BACK 一次重试。
|
||||
val deadline = SystemClock.elapsedRealtime() + 60_000
|
||||
// ⚠️ r30 实锤:Tab 行 y 位置随搜索词/广告横幅动态变化(e1 校准 y=1154 不可靠)。
|
||||
// 修法:OCR 动态定位 Tab 行,按行 bounds 中心点击;找不到则点顶部空白区重试。
|
||||
// ⚠️ r32:OCR 对「抖音热榜」可能误读为「抖音热板」「抖音热様」等——用「热榜」宽松匹配。
|
||||
kotlinx.coroutines.runBlocking {
|
||||
service.gestures.tapAt(540, 80, retry = false)
|
||||
}
|
||||
Thread.sleep(1_500)
|
||||
log("进入热榜 Tab 前点顶部空白区关浮层")
|
||||
var attempt = 0
|
||||
while (SystemClock.elapsedRealtime() < deadline && attempt < 5) {
|
||||
// 宽松匹配:「热榜」比「抖音热榜」更抗 OCR 误读
|
||||
val line = ocrFindLineWithBounds("热榜")
|
||||
if (line == null) {
|
||||
// 诊断:打印含"榜"的行(定位 OCR 读到了什么)
|
||||
val sample = ocrCurrentScreen().filter { it.contains("榜") }.take(3)
|
||||
log("Tab 行不可读,含「榜」行采样: $sample")
|
||||
Thread.sleep(2_000)
|
||||
continue
|
||||
}
|
||||
val (text, rect) = line
|
||||
// 按 OCR 行 bounds 中心点击(行含「猜你想看 抖音热榜」两词,中心偏右命中「抖音热榜」)
|
||||
val x = rect.left + (rect.width() * 0.7).toInt()
|
||||
val y = rect.centerY()
|
||||
log("点热榜 Tab:attempt=$attempt x=$x y=$y 行文本=${text.take(30)} 行bounds=$rect")
|
||||
val ok = try {
|
||||
kotlinx.coroutines.runBlocking {
|
||||
kotlinx.coroutines.withTimeout(5_000) {
|
||||
service.gestures.tapAt(x, y, retry = true)
|
||||
}
|
||||
}
|
||||
} catch (_: Exception) { false }
|
||||
if (ok) {
|
||||
attempt++
|
||||
log("Tab 点击已发(信任直行),静默 12 秒后推进")
|
||||
Thread.sleep(12_000)
|
||||
return true
|
||||
}
|
||||
Thread.sleep(WAIT_STEP_MS)
|
||||
}
|
||||
log("「抖音热榜」Tab 未切换成功")
|
||||
return false
|
||||
}
|
||||
|
||||
override fun readHotListOcrLines(): List<String> {
|
||||
// 榜单渲染稳定后采集。
|
||||
// 【帧追赶·Tab 点触版】r22 实证:滚动(半屏×5)推不动缓存(49 行全旧帧),
|
||||
// r21 微手势同样无效;r20 唯一命中的刷新源是 **Tab 点击事件本身**。
|
||||
// 策略:第 0 屏直读(Tab 点击刚推过一帧)→ 后续每轮**轻点 Tab 坐标**
|
||||
// (点击已选中的 Tab 无副作用,不切页不滚动)→ 静默 → 直读收新行。
|
||||
// 直到解析 ≥8 条或连续 2 轮无新行或 5 轮用尽。
|
||||
val collected = linkedSetOf<String>()
|
||||
var bestParsed = 0
|
||||
val maxRounds = 5
|
||||
val targetParsed = 8
|
||||
// 第 0 屏:不动作直接读(信任直行的静默刚过,帧最新)
|
||||
run {
|
||||
val lines = ocrCurrentScreen()
|
||||
collected.addAll(lines)
|
||||
val merged = com.haorui.app.crossplatform.source.douyin.DouyinHotListParser.mergeAdjacentLines(collected.toList())
|
||||
val parsed = com.haorui.app.crossplatform.source.douyin.DouyinHotListParser.parse(collected.toList())
|
||||
bestParsed = maxOf(bestParsed, parsed.size)
|
||||
log("帧追赶第 0 屏(直读):${lines.size} 行,合并后 ${merged.size} 行,解析 ${bestParsed} 条")
|
||||
// 诊断:打印合并后含数字的行(定位解析失败原因)
|
||||
val digitLines = merged.filter { it.any { c -> c.isDigit() } }
|
||||
log("合并后含数字行(${digitLines.size} 条): ${digitLines.take(10).joinToString(" | ")}")
|
||||
}
|
||||
var noFreshRounds = 0
|
||||
for (round in 1..maxRounds) {
|
||||
if (bestParsed >= targetParsed || noFreshRounds >= 2) break
|
||||
// 轻点「抖音热榜」Tab:e1 dump 校准的**绝对坐标** (404,1154)。
|
||||
// ⚠️ r23 实锤:OCR 行内比例定位不稳定(行内容每次解读不同),比例点过界
|
||||
// 会切回「猜你想看」页——改绝对坐标主攻;且只点一次成功后不再补点。
|
||||
kotlinx.coroutines.runBlocking {
|
||||
service.gestures.tapAt(404, 1154, retry = false)
|
||||
}
|
||||
Thread.sleep(4_000) // 点击事件传播+快照刷新窗口
|
||||
val lines = ocrCurrentScreen()
|
||||
val fresh = lines.count { collected.add(it) }
|
||||
bestParsed = maxOf(bestParsed, DouyinHotListParser.parse(collected.toList()).size)
|
||||
log("帧追赶第 $round 轮(点 Tab 后):本屏 ${lines.size} 行(新 $fresh),累计 ${collected.size},解析 ${bestParsed} 条")
|
||||
if (fresh == 0) noFreshRounds++ else noFreshRounds = 0
|
||||
}
|
||||
log("帧追赶完成:累计 ${collected.size} 行,最优解析 $bestParsed 条")
|
||||
return collected.toList()
|
||||
}
|
||||
|
||||
override fun openEntry(index: Int): Boolean {
|
||||
// ⚠️ r31 实锤:collectOne 和 openEntry 读不同帧导致 entry 不一致——
|
||||
// collectOne 挑的 entry[0] 到 openEntry 时序号变了。
|
||||
// 修法:openEntry 自己重读解析,按**标题碎片**匹配 OCR 行块(不依赖 index)。
|
||||
// ⚠️ 2026-11-17 真机:帧追赶末轮截屏后立即再拍命中 takeScreenshot 限流
|
||||
// (errorCode=3)→ 重读解析 0 条直接失败。先退避再拍,空解析重试一次。
|
||||
val parsed: List<com.haorui.app.crossplatform.source.douyin.DouyinHotEntry> = buildList {
|
||||
for (attempt in 1..2) {
|
||||
Thread.sleep(1_300) // 截屏限流退避(系统配额约 1s+)
|
||||
val lines = ocrCurrentScreen()
|
||||
val p = DouyinHotListParser.parse(lines)
|
||||
if (p.isNotEmpty()) {
|
||||
addAll(p); break
|
||||
}
|
||||
log("openEntry 重读解析 0 条(第 $attempt 次)")
|
||||
}
|
||||
}
|
||||
if (parsed.isEmpty()) {
|
||||
log("openEntry 重读两次均 0 条,放弃")
|
||||
return false
|
||||
}
|
||||
// 优先用 index 对应的 entry,找不到则用第 0 条
|
||||
val entry = parsed.getOrNull(index) ?: parsed[0]
|
||||
val titleFragment = entry.title.take(8)
|
||||
val bitmap: Bitmap? = captureScreen()
|
||||
val target = bitmap?.let { bmp ->
|
||||
try {
|
||||
val blocks = kotlinx.coroutines.runBlocking { com.haorui.app.ocr.OcrProcessor.recognize(bmp) }
|
||||
blocks.asSequence()
|
||||
.flatMap { it.lines.asSequence() }
|
||||
.mapNotNull { line -> line.boundingBox?.let { rect -> line to rect } }
|
||||
.firstOrNull { (line, _) -> line.text.replace(" ", "").contains(titleFragment) }
|
||||
?.second
|
||||
} finally {
|
||||
bmp.recycle()
|
||||
}
|
||||
}
|
||||
if (target == null || target.width() <= 0) {
|
||||
log("词条「${entry.title.take(12)}」OCR 行块定位失败")
|
||||
return false
|
||||
}
|
||||
val ok = kotlinx.coroutines.runBlocking {
|
||||
service.gestures.tapAt(target.centerX(), target.centerY(), retry = false)
|
||||
}
|
||||
if (!ok) return false
|
||||
// 就绪判据走 OCR:热榜 TOP10 横条出现(详情页=搜索结果页顶部横条,e1 实证「热榜 TOP10 5630.1万人在看」)
|
||||
val entered = waitOcr(8_000, until = { lines ->
|
||||
lines.any { it.replace(" ", "").contains("热榜TOP") || it.contains("万人在看") }
|
||||
}, tagForDebug = "entry-detail")
|
||||
if (!entered) {
|
||||
log("词条详情未打开(热榜 TOP 横条未出现)")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
override fun readDetailOcrLines(): List<String> {
|
||||
Thread.sleep(800) // 详情渲染稳定
|
||||
return ocrCurrentScreen()
|
||||
}
|
||||
|
||||
/**
|
||||
* 详情页逐屏全文 OCR(AI 创作链材料,2026-11-17):半屏上滑+行序去重,最多 [maxScreens] 屏。
|
||||
* 仿微博 readPostOcrFullText;滑动幅度 0.72→0.34(抖音详情=搜索结果页,卡片密集防跨卡)。
|
||||
* 调用时机:必须在详情页仍在前台时(collectOne 的 onDetail 钩子)——EXIT 后读到的是榜单。
|
||||
*/
|
||||
fun readDetailOcrFullText(maxScreens: Int = 4): List<String> {
|
||||
val allLines = mutableListOf<String>()
|
||||
val seen = HashSet<String>()
|
||||
var noNewCount = 0
|
||||
for (screen in 0 until maxScreens) {
|
||||
val lines = ocrCurrentScreen()
|
||||
if (lines.isEmpty()) {
|
||||
log("详情全文 OCR 第 $screen 屏识别失败,继续尝试")
|
||||
Thread.sleep(1_000)
|
||||
continue
|
||||
}
|
||||
var appended = 0
|
||||
lines.forEach { line ->
|
||||
val text = line.trim()
|
||||
if (text.isNotEmpty() && seen.add(text)) {
|
||||
allLines.add(text)
|
||||
appended++
|
||||
}
|
||||
}
|
||||
log("详情全文 OCR 第 $screen 屏:识别 ${lines.size} 行,新增 $appended 行")
|
||||
// 页底判定:连续两屏无新行(微博同款口径)
|
||||
if (appended == 0) {
|
||||
noNewCount++
|
||||
if (noNewCount >= 2) {
|
||||
log("详情全文 OCR 连续两屏无新行,判定到页底")
|
||||
break
|
||||
}
|
||||
} else {
|
||||
noNewCount = 0
|
||||
}
|
||||
val scrolled = kotlinx.coroutines.runBlocking {
|
||||
service.gestures.swipe(0.5f, 0.72f, 0.5f, 0.34f)
|
||||
}
|
||||
if (!scrolled) {
|
||||
log("详情全文 OCR 第 $screen 屏滑动失败,终止")
|
||||
break
|
||||
}
|
||||
Thread.sleep(1_200)
|
||||
}
|
||||
return allLines
|
||||
}
|
||||
|
||||
override fun readDetailTree(): SourceNode = tree() ?: SourceNode()
|
||||
|
||||
override fun backToHotList(): Boolean {
|
||||
// 详情→热榜:一次 BACK(详情=搜索结果页内的词条视图)。
|
||||
// 判据走 OCR:「抖音热榜」Tab 行回到屏上(树不可达,r4 实证)。
|
||||
val deadline = SystemClock.elapsedRealtime() + 10_000
|
||||
var backs = 0
|
||||
while (SystemClock.elapsedRealtime() < deadline && backs < 4) {
|
||||
if (service.currentPackage() != DOUYIN_PKG && service.currentPackage() != null) return false
|
||||
val backOnList = runCatching { ocrFindLine("抖音热榜") }.getOrNull() != null
|
||||
if (backOnList) return true
|
||||
service.gestures.back()
|
||||
backs++
|
||||
Thread.sleep(1_000)
|
||||
}
|
||||
// 收尾不强求回热榜:BACK 兜底收拢弹层后让出前台(采集机 finally 口径)
|
||||
runCatching { service.gestures.back() }
|
||||
log("退出导航:BACK $backs 次后收尾")
|
||||
return false
|
||||
}
|
||||
|
||||
// ── 视频链扩展(2026-11-19 e2e 第一轮重取证:全屏页树通道) ─────────────
|
||||
|
||||
/**
|
||||
* 热榜词条详情页(搜索结果页双列视频卡片流,HotSpotDetail 前一跳)→ 点首个视频卡
|
||||
* 进入全屏播放页(HotSpotDetailActivity)。
|
||||
*
|
||||
* ⚠️ 2026-11-19 e2e 第一轮实锤:热榜词条「详情页」是卡片流**没有右栏分享图标**
|
||||
* (树 dump 右侧 x>900 仅「单双列切换图标」);分享按钮在全屏播放页右栏
|
||||
* (content-desc="分享<N>,按钮")——必须先进全屏页。
|
||||
* 视频卡锚点:树 content-desc="视频,按钮"(e2e-03 dump 实证,clickable=true)。
|
||||
*/
|
||||
fun openFullscreenFromEntry(): Boolean {
|
||||
val root = tree() ?: run { log("全屏页:树不可读"); return false }
|
||||
// 找第一个「视频,按钮」卡片(左列 = bounds.x 较小者)
|
||||
var target: SourceNode? = null
|
||||
for (node in root.selfAndDescendants()) {
|
||||
val desc = node.description.orEmpty()
|
||||
if (desc.startsWith("视频") && desc.contains("按钮")) {
|
||||
val b = node.bounds
|
||||
if (b != null && (b.right - b.left) > 200 && (b.bottom - b.top) > 300) { target = node; break }
|
||||
}
|
||||
}
|
||||
if (target == null || target.bounds == null) {
|
||||
log("全屏页:未找到视频卡锚点(页面形态变化或未进卡片流)")
|
||||
return false
|
||||
}
|
||||
val rect = target.bounds!!
|
||||
val ok = runCatching {
|
||||
kotlinx.coroutines.runBlocking { service.gestures.tapAt(rect.centerX, rect.centerY, retry = true) }
|
||||
}.getOrDefault(false)
|
||||
if (!ok) { log("全屏页:视频卡点击失败"); return false }
|
||||
// 就绪判据(树通道):「分享<N>,按钮」content-desc 出现
|
||||
val entered = waitTree(10_000) { t ->
|
||||
t.selfAndDescendants().any { it.description.orEmpty().startsWith("分享") && it.description.orEmpty().contains("按钮") }
|
||||
}
|
||||
if (!entered) log("全屏页:分享锚点未出现(可能进了图文或加载慢)")
|
||||
return entered
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开全屏播放页分享面板:点右栏分享箭头。
|
||||
* ⚠️ 红线修订(用户 2026-11-18 决策):「分享链接」「保存本地」两个只读动作已放行;
|
||||
* 外发动作(私信/微信/QQ/帮上热门/转发到日常等)仍是红线。
|
||||
* 锚点(2026-11-19 全屏页树 dump 实证):content-desc="分享3694,按钮"
|
||||
* bounds=[900,1757][1080,1958]——树通道,不再走 OCR/比例坐标
|
||||
* (比例坐标在 e2e 第一轮实锤失败:readDetailOcrFullText 滚屏后按钮位漂移)。
|
||||
* 就绪判据(树):text="分享给" 面板标题节点出现。
|
||||
*/
|
||||
private fun openSharePanel(): Boolean {
|
||||
val root = tree() ?: run { log("分享面板:树不可读"); return false }
|
||||
val shareNode = root.selfAndDescendants().firstOrNull {
|
||||
val d = it.description.orEmpty()
|
||||
d.startsWith("分享") && d.contains("按钮")
|
||||
}
|
||||
val rect = shareNode?.bounds
|
||||
if (rect == null || (rect.right - rect.left) <= 0) {
|
||||
log("分享面板:树内未找到分享按钮锚点")
|
||||
return false
|
||||
}
|
||||
val tapped = runCatching {
|
||||
kotlinx.coroutines.runBlocking { service.gestures.tapAt(rect.centerX, rect.centerY, retry = true) }
|
||||
}.getOrDefault(false)
|
||||
if (!tapped) { log("分享面板:点击分享按钮失败"); return false }
|
||||
val ready = waitTree(8_000) { t ->
|
||||
t.selfAndDescendants().any { it.text == "分享给" }
|
||||
}
|
||||
if (!ready) log("分享面板:树内未出现「分享给」判据")
|
||||
return ready
|
||||
}
|
||||
|
||||
/** 面板功能行按钮查找:text 精确匹配(树通道),带重试轮询(横滑动画/树刷新有延迟)。 */
|
||||
private fun findPanelButton(label: String): com.haorui.app.crossplatform.source.SourceBounds? {
|
||||
// 横滑动画≈0.5s+树刷新延迟:2 次重试间隔 1s(e2e 第三轮实锤单次查询会扑空)
|
||||
for (attempt in 1..2) {
|
||||
val root = tree()
|
||||
if (root == null) { Thread.sleep(1_000); continue }
|
||||
// 按钮布局(2026-11-19 panel2/panel3 dump 实证):text 标签 y≈2147,
|
||||
// clickable 容器(ViewGroup)同 x 区间、底边=标签底边([285,1971][472,2182])。
|
||||
val labelNode = root.selfAndDescendants().firstOrNull { it.text == label && it.bounds != null }
|
||||
if (labelNode != null) {
|
||||
val labelRect = labelNode.bounds!!
|
||||
// 找与标签 x 区间重叠、底边≥标签底的可点击容器;找不到容器时点标签本体(text 节点也可能可点)
|
||||
val container = root.selfAndDescendants().firstOrNull { n ->
|
||||
val b = n.bounds ?: return@firstOrNull false
|
||||
b.left <= labelRect.right && b.right >= labelRect.left &&
|
||||
b.bottom >= labelRect.bottom && (b.bottom - b.top) >= (labelRect.bottom - labelRect.top)
|
||||
}
|
||||
return container?.bounds ?: labelRect
|
||||
}
|
||||
if (attempt == 1) {
|
||||
// 未找到:dump 当屏 text 采样辅助诊断(面板页码/形态变化可见)
|
||||
val sample = root.selfAndDescendants().mapNotNull { it.text.takeIf { t -> t.isNotBlank() } }
|
||||
.take(12).joinToString("|")
|
||||
log("面板按钮[$label]第 $attempt 次未找到,当屏 text 采样: $sample")
|
||||
}
|
||||
Thread.sleep(1_000)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 分享面板功能行翻页(R5/R6 实锤链):
|
||||
* - 手势横滑(adb input swipe 同参)真机验证可行,GestureRunner 派发待验证;
|
||||
* - 原生滚动 ACTION_SCROLL_FORWARD 返回 true 但滚错容器(好友列表),**不可信**;
|
||||
* - 第二页按钮不在第一页树里(R6 取证证伪离屏预渲染)。
|
||||
* 策略:手势横滑 → **翻页验证闭环**(树 text 集出现新按钮=成功);未翻页重试一次;
|
||||
* 全部失败才退原生滚动(知道它不可信,仅兜底记录)。
|
||||
*/
|
||||
private fun swipePanelRowForward(): Boolean {
|
||||
fun panelTexts(): Set<String> =
|
||||
tree()?.selfAndDescendants()?.mapNotNull { it.text.takeIf { t -> t.isNotBlank() } }?.toSet() ?: emptySet()
|
||||
|
||||
val before = panelTexts()
|
||||
for (attempt in 1..2) {
|
||||
val swiped = runCatching {
|
||||
kotlinx.coroutines.runBlocking { service.gestures.swipe(0.833f, 0.868f, 0.185f, 0.868f) }
|
||||
}.getOrDefault(false)
|
||||
Thread.sleep(1_200)
|
||||
val after = panelTexts()
|
||||
val changed = before.isNotEmpty() && after.isNotEmpty() && (after - before).isNotEmpty()
|
||||
if (swiped && changed) {
|
||||
log("面板功能行:手势翻页成功(第 $attempt 次,新增按钮=${(after - before).take(3)})")
|
||||
return true
|
||||
}
|
||||
log("面板功能行:手势第 $attempt 次 派发=$swiped 页面变化=$changed")
|
||||
}
|
||||
// 兜底:原生滚动(R5 实锤滚错容器,返回值不可信,仅当最后的尝试)
|
||||
val root = service.root()
|
||||
if (root != null) {
|
||||
var visited = 0
|
||||
val rect = android.graphics.Rect()
|
||||
fun walk(node: android.view.accessibility.AccessibilityNodeInfo): android.view.accessibility.AccessibilityNodeInfo? {
|
||||
if (visited++ > 4_000) return null
|
||||
runCatching { node.getBoundsInScreen(rect) }
|
||||
if (node.isScrollable && rect.top > 1_400) return android.view.accessibility.AccessibilityNodeInfo.obtain(node)
|
||||
for (i in 0 until node.childCount) {
|
||||
val child = node.getChild(i) ?: continue
|
||||
val found = try { walk(child) } finally { runCatching { child.recycle() } }
|
||||
if (found != null) return found
|
||||
}
|
||||
return null
|
||||
}
|
||||
val target = walk(root)
|
||||
if (target != null) {
|
||||
val ok = try {
|
||||
runCatching { target.performAction(android.view.accessibility.AccessibilityNodeInfo.ACTION_SCROLL_FORWARD) }.getOrDefault(false)
|
||||
} finally {
|
||||
runCatching { target.recycle() }
|
||||
}
|
||||
Thread.sleep(1_200)
|
||||
val after = panelTexts()
|
||||
if ((after - before).isNotEmpty()) {
|
||||
log("面板功能行:原生滚动翻页成功")
|
||||
return true
|
||||
}
|
||||
log("面板功能行:原生滚动 performAction=$ok 但页面未变(滚错容器实锤)")
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
override fun saveLocalFromSharePanel(): DouyinHotListCollector.SaveLocalOutcome {
|
||||
if (!openSharePanel()) return DouyinHotListCollector.SaveLocalOutcome.FAILED
|
||||
// 功能行翻页找「保存本地」(p0-06/v1-05/e2e panel2/panel3 实证在第二页)
|
||||
swipePanelRowForward()
|
||||
Thread.sleep(1_200)
|
||||
val rect = findPanelButton("保存本地")
|
||||
if (rect == null) {
|
||||
log("保存本地:树内未找到按钮(可能灰置或面板形态变化)")
|
||||
// 灰置与找不到无法区分时保守按灰置处理——宁降级不盲点
|
||||
return DouyinHotListCollector.SaveLocalOutcome.SAVE_DISABLED
|
||||
}
|
||||
val tapped = runCatching {
|
||||
kotlinx.coroutines.runBlocking { service.gestures.tapAt(rect.centerX, rect.top + ((rect.bottom - rect.top) * 2 / 3), retry = true) }
|
||||
}.getOrDefault(false)
|
||||
if (!tapped) return DouyinHotListCollector.SaveLocalOutcome.FAILED
|
||||
// 回执判据(v1-06 实证):「已保存」横幅。树通道优先(横幅为 text 节点),OCR 兜底。
|
||||
val receipt = waitTree(15_000) { t ->
|
||||
t.selfAndDescendants().any { it.text.replace(" ", "").contains("已保存") }
|
||||
} || waitOcr(6_000, { lines ->
|
||||
lines.any { it.replace(" ", "").contains("已保存") }
|
||||
}, "保存回执")
|
||||
return if (receipt) {
|
||||
log("保存本地:回执确认(已保存横幅)")
|
||||
DouyinHotListCollector.SaveLocalOutcome.SAVED
|
||||
} else {
|
||||
log("保存本地:未读到「已保存」回执(可能弹下载中或失败)")
|
||||
DouyinHotListCollector.SaveLocalOutcome.FAILED
|
||||
}
|
||||
}
|
||||
|
||||
override fun copyShareLink(): Boolean {
|
||||
if (!openSharePanel()) return false
|
||||
// 「分享链接」第一页屏边半露(e2e panel dump 实证 [1042,2147]),轻滑半格入视野
|
||||
val swiped = runCatching {
|
||||
kotlinx.coroutines.runBlocking { service.gestures.swipe(0.694f, 0.868f, 0.324f, 0.868f) }
|
||||
}.getOrDefault(false)
|
||||
if (!swiped) log("分享链接:功能行轻滑失败(可能已入视野)")
|
||||
Thread.sleep(1_200)
|
||||
val rect = findPanelButton("分享链接")
|
||||
if (rect == null) {
|
||||
log("分享链接:树内未找到按钮")
|
||||
return false
|
||||
}
|
||||
val tapped = runCatching {
|
||||
kotlinx.coroutines.runBlocking { service.gestures.tapAt(rect.centerX, rect.top + ((rect.bottom - rect.top) * 2 / 3), retry = true) }
|
||||
}.getOrDefault(false)
|
||||
if (!tapped) return false
|
||||
// 回执判据(p0-09 实证):「链接已复制」toast。toast 不一定进树——OCR 兜底为主。
|
||||
val receipt = waitOcr(10_000, { lines ->
|
||||
lines.any { it.replace(" ", "").contains("链接已复制") }
|
||||
}, "复制回执")
|
||||
// 复制后面板仍在(外发推荐面板),关闭再返回(外发按钮为红线,只关不点)
|
||||
dismissSharePanel()
|
||||
return receipt
|
||||
}
|
||||
|
||||
override fun dismissSharePanel(): Boolean {
|
||||
// 关闭面板:BACK(面板是弹层,BACK 等效关闭——e2e 第一轮 BACK 兜底实锤有效)
|
||||
runCatching { service.gestures.back() }
|
||||
Thread.sleep(1_200)
|
||||
val closed = waitTree(5_000) { t ->
|
||||
t.selfAndDescendants().none { it.text == "分享给" }
|
||||
}
|
||||
log("分享面板:BACK 关闭 ${if (closed) "成功" else "未确认"}")
|
||||
return closed
|
||||
}
|
||||
}
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
package com.haorui.app.crossplatform.source.douyin
|
||||
|
||||
import com.haorui.app.crossplatform.source.SourceNode
|
||||
|
||||
/**
|
||||
* 抖音热榜采集状态机(骨架,2026-11-16 e1 取证口径)。
|
||||
*
|
||||
* 入口链(e1 实测):
|
||||
* 首页右上「搜索」按钮 → 搜索页(SearchResultActivity)→「抖音热榜」Tab(**页内切换不换 Activity**,
|
||||
* content-desc 带“已选中”状态可读)→ 热榜列表(自绘渲染,OCR 主路线)→ 点词条 → 详情(同为搜索结果页)。
|
||||
*
|
||||
* 约束(继承微博/知乎经验 + e1 教训):
|
||||
* - 一次候选完成才让出前台,失败都走 EXIT 安全退出;
|
||||
* - 缺失字段保留未知(进 unknowns),不从行序、图标或无关文本推断;
|
||||
* - 词条点按必须按解析结果的行 bounds 定位(e1 教训:屏上估算行位偏移一行);
|
||||
* - 详情页「投稿」按钮与「分享」按钮是外发动作红线,未取证前一律不可点击。
|
||||
*
|
||||
* 真机驱动通过 [Port] 接入;未完成真机适配前不注册任何能力,入口由 SourceRegistry 门控拦截。
|
||||
*/
|
||||
class DouyinHotListCollector(
|
||||
private val port: Port,
|
||||
private val nowMs: () -> Long = System::currentTimeMillis,
|
||||
) {
|
||||
/** 真机驱动接口:每个方法都是一次页面操作,实现方负责可见性核对,禁止盲点。 */
|
||||
interface Port {
|
||||
fun ensureAppForeground(): Boolean
|
||||
/** 首页右上搜索按钮进入搜索页。 */
|
||||
fun openSearch(): Boolean
|
||||
/** 点「抖音热榜」Tab(页内切换);须核对“已选中”状态后才返回 true。 */
|
||||
fun openHotListTab(): Boolean
|
||||
/** 逐屏滚动采集热榜 OCR 文本行(含半屏上滑与行序去重,参照微博 readPostOcrFullText)。 */
|
||||
fun readHotListOcrLines(): List<String>
|
||||
/** 按解析出的条目行 bounds 点词条进详情;实现方必须先核对节点可见性。 */
|
||||
fun openEntry(index: Int): Boolean
|
||||
/** 详情页 OCR 文本行(作者/正文/相对时间在自绘区)。 */
|
||||
fun readDetailOcrLines(): List<String>
|
||||
/** 详情页可读节点树(互动数等树内字段,形态待 e2 核验)。 */
|
||||
fun readDetailTree(): SourceNode
|
||||
/** 安全退出:详情→热榜→(必要时)离开抖音前台收尾。 */
|
||||
fun backToHotList(): Boolean
|
||||
|
||||
// ── 视频链扩展(2026-11-18 P0 取证口径;灰置分支见 DouyinDevicePort) ──
|
||||
|
||||
/**
|
||||
* 详情页分享面板「保存本地」(用户决策:带水印官方下载)。
|
||||
* 成功=系统落盘完成且 UI 回执(「已保存,请去相册查看」横幅)可见;
|
||||
* 作者禁下载(按钮灰置)返回 SAVE_DISABLED 分支,调用方降级。
|
||||
*/
|
||||
fun saveLocalFromSharePanel(): SaveLocalOutcome
|
||||
|
||||
/**
|
||||
* 详情页分享面板「分享链接」复制口令(用于溯源/幂等键)。
|
||||
* 返回「已复制」判定结果;口令本体经剪贴板取证兜底(搜索框粘贴)读取。
|
||||
*/
|
||||
fun copyShareLink(): Boolean
|
||||
|
||||
/** 关闭分享面板(X 按钮或 BACK),恢复详情页可导航状态。 */
|
||||
fun dismissSharePanel(): Boolean
|
||||
}
|
||||
|
||||
/** 「保存本地」结果分支。 */
|
||||
enum class SaveLocalOutcome {
|
||||
/** 已保存且回执可见。 */
|
||||
SAVED,
|
||||
/** 作者禁下载(按钮灰置/不可点)。 */
|
||||
SAVE_DISABLED,
|
||||
/** 面板未出现或操作超时。 */
|
||||
FAILED,
|
||||
}
|
||||
|
||||
enum class Phase {
|
||||
OPEN_APP, OPEN_SEARCH, OPEN_HOT_TAB, READ_LIST,
|
||||
OPEN_ENTRY, READ_DETAIL, SAVE_OBSERVATION, EXIT, DONE, FAILED,
|
||||
}
|
||||
|
||||
/** 热榜清单结果:entries 为当屏快照(用户勾选/确认的数据源)。 */
|
||||
data class ListResult(
|
||||
val outcome: String,
|
||||
val phase: Phase,
|
||||
val entries: List<DouyinHotEntry> = emptyList(),
|
||||
val reason: String = "",
|
||||
val exitedSafely: Boolean = false,
|
||||
)
|
||||
|
||||
/** 单条内容采集结果;失败相位即 [phase],观察到的未知字段进 unknowns。 */
|
||||
data class Result(
|
||||
val outcome: String,
|
||||
val phase: Phase,
|
||||
val observation: DouyinPostObservation? = null,
|
||||
val reason: String = "",
|
||||
val exitedSafely: Boolean = false,
|
||||
)
|
||||
|
||||
/** 运行代际:停止/重启后递增,迟到的观察不得混入新代际。 */
|
||||
var runGeneration: Long = 0
|
||||
|
||||
var phase: Phase = Phase.OPEN_APP
|
||||
private set
|
||||
|
||||
/** 拉取抖音热榜词条清单(OPEN_APP→…→READ_LIST→EXIT)。 */
|
||||
fun collectHotList(): ListResult {
|
||||
var entries: List<DouyinHotEntry> = emptyList()
|
||||
var failure: String? = null
|
||||
var failedAt: Phase? = null
|
||||
var exitedSafely = false
|
||||
try {
|
||||
phase = Phase.OPEN_APP
|
||||
if (!port.ensureAppForeground()) fail("抖音未能进入前台")
|
||||
phase = Phase.OPEN_SEARCH
|
||||
if (!port.openSearch()) fail("搜索入口未打开")
|
||||
phase = Phase.OPEN_HOT_TAB
|
||||
if (!port.openHotListTab()) fail("「抖音热榜」Tab 未切换成功")
|
||||
phase = Phase.READ_LIST
|
||||
entries = DouyinHotListParser.parse(port.readHotListOcrLines())
|
||||
if (entries.isEmpty()) fail("热榜清单为空或 OCR 未读到合格行")
|
||||
} catch (stop: StopRequest) {
|
||||
failure = stop.message
|
||||
failedAt = phase
|
||||
} finally {
|
||||
phase = Phase.EXIT
|
||||
exitedSafely = runCatching { port.backToHotList() }.getOrDefault(false)
|
||||
}
|
||||
return ListResult(
|
||||
outcome = if (failure == null) "已取得" else "失败",
|
||||
phase = failedAt ?: Phase.DONE,
|
||||
entries = entries,
|
||||
reason = failure.orEmpty(),
|
||||
exitedSafely = exitedSafely,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 采集热榜第 [entryIndex] 条词条的详情观察。
|
||||
* 详情页时间多为相对时间(「3天前」),唯一合法来源是详情 OCR 行;解析不出保留 null。
|
||||
*
|
||||
* @param onDetail 详情页仍在前台时回调(SAVE_OBSERVATION 之后、EXIT 之前),供调用方取全文材料。
|
||||
* 回调异常吞掉,不影响采集结果。
|
||||
*/
|
||||
fun collectOne(entryIndex: Int, onDetail: (() -> Unit)? = null): Result {
|
||||
var observation: DouyinPostObservation? = null
|
||||
var failure: String? = null
|
||||
var failedAt: Phase? = null
|
||||
var exitedSafely = false
|
||||
try {
|
||||
phase = Phase.OPEN_APP
|
||||
if (!port.ensureAppForeground()) fail("抖音未能进入前台")
|
||||
phase = Phase.OPEN_SEARCH
|
||||
if (!port.openSearch()) fail("搜索入口未打开")
|
||||
phase = Phase.OPEN_HOT_TAB
|
||||
if (!port.openHotListTab()) fail("「抖音热榜」Tab 未切换成功")
|
||||
phase = Phase.READ_LIST
|
||||
val entries = DouyinHotListParser.parse(port.readHotListOcrLines())
|
||||
val entry = entries.getOrNull(entryIndex) ?: fail("热榜第 $entryIndex 条不存在")
|
||||
|
||||
phase = Phase.OPEN_ENTRY
|
||||
if (!port.openEntry(entryIndex)) fail("词条「${entry.title.take(12)}」未打开")
|
||||
phase = Phase.READ_DETAIL
|
||||
// 先读 OCR 行再读树:详情页自绘内容以 OCR 为主,读取顺序固定(与相位记录一致)
|
||||
val detailOcrLines = port.readDetailOcrLines()
|
||||
val detail = DouyinDetailParser.parse(port.readDetailTree(), detailOcrLines, nowMs())
|
||||
|
||||
phase = Phase.SAVE_OBSERVATION
|
||||
observation = DouyinPostObservation(
|
||||
hotEntry = entry,
|
||||
author = detail.author,
|
||||
content = detail.content,
|
||||
publishedAtText = detail.publishedAtText,
|
||||
publishedAtMs = detail.publishedAtMs,
|
||||
fetchedAtMs = nowMs(),
|
||||
runGeneration = runGeneration,
|
||||
unknowns = buildUnknowns(entry, detail),
|
||||
)
|
||||
// 详情页仍在前台:回调调用方取全文材料(异常吞掉——采集结果不受附属动作影响)
|
||||
runCatching { onDetail?.invoke() }
|
||||
} catch (stop: StopRequest) {
|
||||
failure = stop.message
|
||||
failedAt = phase
|
||||
} finally {
|
||||
phase = Phase.EXIT
|
||||
exitedSafely = runCatching { port.backToHotList() }.getOrDefault(false)
|
||||
}
|
||||
return Result(
|
||||
outcome = if (observation != null) "已观察" else "失败",
|
||||
phase = failedAt ?: Phase.DONE,
|
||||
observation = observation,
|
||||
reason = failure.orEmpty(),
|
||||
exitedSafely = exitedSafely,
|
||||
)
|
||||
}
|
||||
|
||||
private class StopRequest(message: String) : RuntimeException(message)
|
||||
|
||||
private fun fail(reason: String): Nothing = throw StopRequest(reason)
|
||||
|
||||
/** 未知口径清单:把“没读到什么”显式记录,供筛选阶段按“缺值不伪造”处置。 */
|
||||
private fun buildUnknowns(entry: DouyinHotEntry, detail: DouyinDetail): List<String> {
|
||||
val unknowns = mutableListOf<String>()
|
||||
if (entry.rank == null) unknowns += "排名未知(置顶行或 OCR 未读到独立排名)"
|
||||
if (entry.heatValue == null) unknowns += "热度数值未知(原文=${entry.heatRaw ?: "缺失"})"
|
||||
if (entry.label == null) unknowns += "标签未知(OCR 未读到独立标签词)"
|
||||
if (detail.publishedAtMs == null) unknowns += "发布时间未知:${detail.unknownReason}"
|
||||
if (detail.author == null) unknowns += "作者未知(详情 OCR 未读到)"
|
||||
if (detail.content == null) unknowns += "正文未知(详情 OCR 未读到)"
|
||||
return unknowns
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package com.haorui.app.crossplatform.source.douyin
|
||||
|
||||
/**
|
||||
* 抖音热榜解析器(com.ss.android.ugc.aweme,2026-11-16 e1 取证形态)。
|
||||
*
|
||||
* 输入是 OCR 文本行(热榜列表自绘渲染,XML 树无词条文本——与微博排名/标签图片化同理,
|
||||
* 但抖音连标题都只在 OCR 里)。
|
||||
*
|
||||
* 行形态(e1 实测):
|
||||
* `1 习近平将同普京特朗普会晤 1165.9万`
|
||||
* `2 第一视角记录APEC瞬间 热 1165.7万`
|
||||
* `12 茉茉手势舞 挑战 918.4万`
|
||||
* `习近平主席这样推介中国深圳`(置顶行:无排名、无热度)
|
||||
*
|
||||
* 解析口径:
|
||||
* - 标题 = 行内去掉行首排名、行尾热度、独立标签词后的剩余文本;为空则整行拒绝(不伪造条目);
|
||||
* - 排名 = 行首 1~2 位独立数字(跟空格分隔);置顶行无排名 → null,不按行序推断;
|
||||
* - 标签 = 行中的独立词 热/新/挑战/辟谣(前后有空白分隔才认,标题内嵌“热”字不算);
|
||||
* OCR 把标签与标题粘连(如「第一视角记录APEC瞬间热」无空格)时不剥离 → 标题保持原样、label=null;
|
||||
* - 热度 = 行尾「数值+万」(1165.9万 → 11659000);纯「数值」不带万不认(可能是页码等噪音);
|
||||
* 正常榜单行必有排名徽章(e1 实测):无排名的行一律拒绝(置顶行/官宣行/搜索历史/OCR 混入的
|
||||
* 非榜单内容);有排名无热度保留条目并标 heatMissing。
|
||||
*/
|
||||
object DouyinHotListParser {
|
||||
const val PACKAGE = "com.ss.android.ugc.aweme"
|
||||
|
||||
/** e1 实测标签词全集;未核验的新标签词不剥离,留在标题里待取证后补充。 */
|
||||
internal val LABELS = setOf("热", "新", "挑战", "辟谣")
|
||||
|
||||
private val RANK_PREFIX = Regex("^(\\d{1,2})\\s*(.+)$")
|
||||
private val HEAT_SUFFIX = Regex("[\\s]*([\\d]+(?:\\.[\\d]+)?)万\\s*$")
|
||||
|
||||
/** 解析 OCR 文本行为热榜条目;无条目返回空表,噪音行静默跳过。 */
|
||||
fun parse(ocrLines: List<String>): List<DouyinHotEntry> {
|
||||
val merged = mergeAdjacentLines(ocrLines)
|
||||
return merged.mapIndexedNotNull { index, line -> parseLine(line, index) }
|
||||
}
|
||||
|
||||
/**
|
||||
* OCR 行合并预处理:热榜一行「排名+标题+热度」常被 OCR 拆成 2~3 行
|
||||
* (排名/标题/热度各一行),单独每行都匹配不到 RANK_PREFIX+标题+热度 → 全被拒。
|
||||
* 合并规则(保守,只合并确定性的拆行形态):
|
||||
* 1) 纯排名行(`^\d{1,2}$`)+ 纯标题行(无排名无热度)→ 拼成「排名 标题」;
|
||||
* 2) 上一步结果 + 纯热度行(`^\d+(\.\d+)?万$`)→ 拼成「排名 标题 热度」;
|
||||
* 3) 纯热度行紧跟已有条目行(含排名)→ 追加到该行末尾。
|
||||
* 不确定的行原样保留(交给 parseLine 按原有规则判定)。
|
||||
*/
|
||||
internal fun mergeAdjacentLines(ocrLines: List<String>): List<String> {
|
||||
val result = mutableListOf<String>()
|
||||
var i = 0
|
||||
while (i < ocrLines.size) {
|
||||
val line = ocrLines[i].trim()
|
||||
if (line.isEmpty()) { i++; continue }
|
||||
|
||||
// 纯排名行(1~2 位数字)
|
||||
if (RANK_ONLY.matches(line)) {
|
||||
val titleCandidate = ocrLines.getOrNull(i + 1)?.trim().orEmpty()
|
||||
if (titleCandidate.isNotEmpty() && !RANK_ONLY.matches(titleCandidate) && !HEAT_ONLY.matches(titleCandidate)) {
|
||||
var merged = "$line $titleCandidate"
|
||||
var next = i + 2
|
||||
// 紧跟纯热度行则追加
|
||||
val heatCandidate = ocrLines.getOrNull(next)?.trim().orEmpty()
|
||||
if (HEAT_ONLY.matches(heatCandidate)) {
|
||||
merged = "$merged $heatCandidate"
|
||||
next++
|
||||
}
|
||||
result += merged
|
||||
i = next
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// 纯热度行紧跟已有条目行(含排名)→ 追加到上一行
|
||||
if (HEAT_ONLY.matches(line) && result.isNotEmpty() && RANK_PREFIX.matches(result.last())) {
|
||||
result[result.size - 1] = result.last() + " " + line
|
||||
i++
|
||||
continue
|
||||
}
|
||||
|
||||
result += line
|
||||
i++
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private val RANK_ONLY = Regex("^\\d{1,2}$")
|
||||
private val HEAT_ONLY = Regex("^\\d+(?:\\.\\d+)?万$")
|
||||
|
||||
internal fun parseLine(rawLine: String, order: Int): DouyinHotEntry? {
|
||||
var line = rawLine.trim()
|
||||
if (line.isEmpty()) return null
|
||||
|
||||
// 0) 清洗排名前非数字前缀(OCR 常把 "|"、"。" 等混入排名前)
|
||||
line = line.trimStart('|', '。', '·', '、', ' ', ' ')
|
||||
|
||||
var rest = line
|
||||
// 1) 行首排名:1~2 位数字 + 可选空白。置顶/官宣行无排名。
|
||||
// 标题首字符必须非数字(防「2026年APEC…」误匹配排名「2」)。
|
||||
// 标题首字符不能是「:」(防时间戳「16:06」误匹配排名「16」)。
|
||||
val rank = RANK_PREFIX.matchEntire(rest)?.let { m ->
|
||||
val titlePart = m.groupValues[2]
|
||||
if (titlePart.isEmpty() || titlePart[0].isDigit() || titlePart[0] == ':') null
|
||||
else {
|
||||
rest = titlePart
|
||||
m.groupValues[1].toIntOrNull()?.takeIf { it in 1..99 }
|
||||
}
|
||||
}
|
||||
|
||||
// 2) 行尾热度:「数值+万」。纯数值不带万不认。
|
||||
var heatRaw: String? = null
|
||||
var heatValue: Long? = null
|
||||
HEAT_SUFFIX.find(rest)?.let { m ->
|
||||
heatRaw = m.groupValues[1] + "万"
|
||||
rest = rest.removeRange(m.range)
|
||||
}
|
||||
heatValue = parseHeat(heatRaw)
|
||||
|
||||
// 3) 独立标签词:按空白分词后整词匹配;不剥离粘连词。
|
||||
val words = rest.split(Regex("\\s+")).filter { it.isNotEmpty() }
|
||||
var label: String? = null
|
||||
val titleWords = words.filter { word ->
|
||||
if (label == null && word in LABELS) { label = word; false } else true
|
||||
}
|
||||
val title = titleWords.joinToString(" ").trim()
|
||||
// 标题最短 2 字符(防单字符噪音如「G」);标题中残留热度样式文本清理
|
||||
val cleanedTitle = title.replace(Regex("\\d+(?:\\.\\d+)?万"), "").trim()
|
||||
// 拒绝纯数字/小数点标题(OCR 噪音如「32.9」「.9」「100」)
|
||||
if (cleanedTitle.length < 2 || cleanedTitle.all { it.isDigit() || it == '.' || it == ',' }) return null
|
||||
|
||||
// 无排名:正常榜单行必有排名徽章(e1 实测);置顶行/官宣行/搜索历史等均无排名 → 拒绝。
|
||||
// 有热度无排名的行同样视为噪音(OCR 混入的非榜单内容),宁缺不滥。
|
||||
if (rank == null) return null
|
||||
|
||||
return DouyinHotEntry(
|
||||
title = cleanedTitle,
|
||||
heatRaw = heatRaw,
|
||||
heatValue = heatValue,
|
||||
rank = rank,
|
||||
label = label,
|
||||
order = order,
|
||||
heatMissing = heatValue == null,
|
||||
)
|
||||
}
|
||||
|
||||
/** 「1165.9万」→ 11659000;非法形态返回 null。 */
|
||||
internal fun parseHeat(raw: String?): Long? {
|
||||
if (raw.isNullOrBlank()) return null
|
||||
val text = raw.trim()
|
||||
if (!text.endsWith("万")) return null
|
||||
val number = text.removeSuffix("万").toDoubleOrNull() ?: return null
|
||||
if (number < 0) return null
|
||||
return (number * 10_000).toLong()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.haorui.app.crossplatform.source.douyin
|
||||
|
||||
/**
|
||||
* 抖音采集解析结果模型(2026-11-16 e1 取证口径)。
|
||||
*
|
||||
* 口径约束(缺值不伪造):解析不到的字段一律保留 null,
|
||||
* 不从行序、图标或无关文本推断补齐。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 抖音热榜条目(e1 实测形态:排名徽章 + 标题 + 热/新/挑战/辟谣彩色标签 + 热度值「1165.9万」)。
|
||||
*
|
||||
* 热榜列表为自绘渲染(XML 树无词条文本),OCR 文本行为唯一输入源:
|
||||
* - [rank] 只认行首 1~2 位独立数字;置顶/官宣行无排名 → null;
|
||||
* - [label] 只认 OCR 读出的独立标签词(热/新/挑战/辟谣);OCR 粘连时保留 null 不强行剥离;
|
||||
* - [heatValue] 只认「数值+万」形态(1165.9万 → 11659000);无热度行不构成条目(OCR 无结构,
|
||||
* 无法区分置顶行与搜索历史/Tab 名等噪音,宁缺不滥);
|
||||
* - [order] 仅为展示序(行序),不是排名。
|
||||
*/
|
||||
data class DouyinHotEntry(
|
||||
val title: String,
|
||||
val heatRaw: String? = null,
|
||||
val heatValue: Long? = null,
|
||||
val rank: Int? = null,
|
||||
val label: String? = null,
|
||||
val order: Int = 0,
|
||||
val heatMissing: Boolean = true,
|
||||
)
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.haorui.app.crossplatform.source.douyin
|
||||
|
||||
/**
|
||||
* 抖音分享链接解析器(2026-11-18 真机取证+开发机验证)。
|
||||
*
|
||||
* 三种输入形态(均为真机/真实样本取证):
|
||||
* 1. 完整口令文本:`8.74 复制打开抖音,看看【天音的作品】透明高跟鞋试穿 # 透明高跟鞋 # 凉鞋 https://v.douyin.com/xOwNvhohtEk/ [email protected] caN:/ :9pm 05/17`
|
||||
* 2. 裸短链:`https://v.douyin.com/xOwNvhohtEk/`
|
||||
* 3. 已展开的分享页 URL(302 目标):`https://www.iesdouyin.com/share/video/7703029017754223097/?region=CN&mid=...`
|
||||
*
|
||||
* 解析口径:
|
||||
* - 口令文本中先按 URL 正则提取短链;口令其余部分(前缀数字/尾缀乱码时间戳)为抖音防钓鱼
|
||||
* 显示变形,不参与解析(真机取证:搜索框显示 `v@f.oq reB:/ 05/22 :4pm` 实为短链的混淆显示);
|
||||
* - 短链域名白名单:v.douyin.com / v.douyin.co(历史形态);其他域名一律拒绝(防钓鱼/防串源);
|
||||
* - 已展开 URL 路径形态:`/share/video/<19位item_id>` 或 `/video/<19位item_id>`(PC 页重定向形态);
|
||||
* - 追踪参数(share_sign/u_code/did/iid/utm_* 等)一律不保留——与知乎/微博分享链同口径;
|
||||
* - 无法提取 item_id 时返回 null(调用方按"分享链不可解析"处理,不伪造身份)。
|
||||
*/
|
||||
object DouyinShareLinkParser {
|
||||
/** 短链域名白名单(2026-11-18 实测 v.douyin.com;v.douyin.co 为历史兼容形态)。 */
|
||||
internal val SHORT_HOSTS = setOf("v.douyin.com", "v.douyin.co")
|
||||
|
||||
private val URL_IN_TEXT = Regex("https?://[A-Za-z0-9.-]+(?:/[A-Za-z0-9._~/-]*)?")
|
||||
|
||||
/** 已展开分享页/PC 页路径:/share/video/<id>/ 或 /video/<id>/(尾部可有路径与 query)。 */
|
||||
private val EXPANDED_PATH = Regex("^/(?:share/)?video/(\\d{15,25})(?:[/?]|$)")
|
||||
|
||||
/** 从任意分享文本(口令/裸链/已展开链接)中提取短链或 item_id 原始候选。 */
|
||||
fun extractCandidates(text: String): List<String> {
|
||||
return URL_IN_TEXT.findAll(text).map { it.value }.toList()
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析结果。
|
||||
* @property shortLink 短链(若输入含短链);已展开输入时为 null
|
||||
* @property itemId 19 位视频身份(已展开输入直接提取;短链输入需调用方 302 展开后二次调用)
|
||||
*/
|
||||
data class Parsed(
|
||||
val shortLink: String?,
|
||||
val itemId: String?,
|
||||
)
|
||||
|
||||
/**
|
||||
* 解析分享文本。规则:
|
||||
* - 输入含已展开 URL(iesdouyin.com/douyin.com 域 + /share/video/<id> 路径)→ 直接返回 itemId;
|
||||
* - 输入含白名单短链 → 返回 shortLink(itemId 为 null,等 302 展开);
|
||||
* - 均不满足 → null(不可解析)。
|
||||
*/
|
||||
fun parse(text: String): Parsed? {
|
||||
val urls = extractCandidates(text)
|
||||
if (urls.isEmpty()) return null
|
||||
|
||||
// 优先找已展开形态(item_id 直接可得)
|
||||
for (url in urls) {
|
||||
val expanded = parseExpanded(url)
|
||||
if (expanded != null) return Parsed(shortLink = null, itemId = expanded)
|
||||
}
|
||||
// 其次找白名单短链
|
||||
for (url in urls) {
|
||||
val host = runCatching { java.net.URI(url).host?.lowercase() }.getOrNull()
|
||||
if (host in SHORT_HOSTS) {
|
||||
return Parsed(shortLink = url, itemId = null)
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** 解析已展开的分享页 URL,提取 item_id;非目标域名或路径不匹配返回 null。 */
|
||||
fun parseExpanded(url: String): String? {
|
||||
val uri = runCatching { java.net.URI(url) }.getOrNull() ?: return null
|
||||
val host = uri.host?.lowercase() ?: return null
|
||||
val hostOk = host == "www.iesdouyin.com" || host == "iesdouyin.com" ||
|
||||
host == "www.douyin.com" || host == "douyin.com" || host == "m.douyin.com"
|
||||
if (!hostOk) return null
|
||||
val path = uri.path ?: return null
|
||||
return EXPANDED_PATH.matchEntire(path)?.groupValues?.getOrNull(1)
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 302 Location 响应头,提取 item_id(短链展开第二步)。
|
||||
* 输入为 Location 头完整值(可含 query);形态不符返回 null。
|
||||
*/
|
||||
fun parseRedirectLocation(location: String): String? {
|
||||
val trimmed = location.trim()
|
||||
if (trimmed.isEmpty()) return null
|
||||
// Location 可能是相对路径或完整 URL;统一补 scheme 后走 parseExpanded
|
||||
val url = if (trimmed.startsWith("http")) trimmed else "https://www.iesdouyin.com$trimmed"
|
||||
return parseExpanded(url)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,683 @@
|
||||
package com.haorui.app.crossplatform.source.weibo
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.os.SystemClock
|
||||
import android.view.accessibility.AccessibilityNodeInfo
|
||||
import com.haorui.app.automation.ClipboardBridge
|
||||
import com.haorui.app.automation.HaoRuiAccessibilityService
|
||||
import com.haorui.app.automation.NodeLocator
|
||||
import com.haorui.app.automation.RunLogger
|
||||
import com.haorui.app.crossplatform.source.SourceNode
|
||||
import com.haorui.app.crossplatform.source.SourceNodeAccessibility
|
||||
|
||||
/**
|
||||
* 微博采集真机驱动([WeiboHotListCollector.Port] 实现,2026-11-14 e2/e3 取证口径)。
|
||||
*
|
||||
* 锚点依据选择器可用性报告:底部“发现”、发现页“更多热搜”、榜单 Tab 文本、
|
||||
* 话题页 `contentTextView`(自绘正文)/`mblogHeadtitle`、详情顶栏右上无名「⋯」
|
||||
* ([954,135][1044,225] 区 ImageView,点后以面板标题“分享”核验)、
|
||||
* 分享面板第 3 行横滑区“复制链接”、“取消”关闭。
|
||||
*
|
||||
* 详情页作者/发布时间为自绘文本:readPostOcrLines 用应用自身 OCR 管线取行文本。
|
||||
* 复制链接读取:剪贴板快速路径(本机受限)+ 微博搜索框 ACTION_PASTE 兜底——全程不切 App。
|
||||
*/
|
||||
internal class WeiboDevicePort(
|
||||
private val service: HaoRuiAccessibilityService,
|
||||
) : WeiboHotListCollector.Port {
|
||||
private companion object {
|
||||
const val TAG = "Weibo-Port"
|
||||
const val WEIBO_PKG = "com.sina.weibo"
|
||||
const val WAIT_STEP_MS = 400L
|
||||
}
|
||||
|
||||
// ── 基础工具 ─────────────────────────────────────────────
|
||||
|
||||
private fun log(message: String) = RunLogger.i(TAG, message)
|
||||
|
||||
private fun tree(): SourceNode? = service.root()?.let { SourceNodeAccessibility.from(it) }
|
||||
|
||||
private fun waitTree(timeoutMs: Long, until: (SourceNode) -> Boolean): Boolean {
|
||||
val deadline = SystemClock.elapsedRealtime() + timeoutMs
|
||||
while (SystemClock.elapsedRealtime() < deadline) {
|
||||
val t = tree()
|
||||
if (t != null && until(t)) return true
|
||||
Thread.sleep(WAIT_STEP_MS)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun tapText(text: String, timeoutMs: Long = 4_000L): Boolean {
|
||||
val deadline = SystemClock.elapsedRealtime() + timeoutMs
|
||||
while (SystemClock.elapsedRealtime() < deadline) {
|
||||
val node = NodeLocator.byText(service.root(), text) ?: NodeLocator.byDesc(service.root(), text)
|
||||
if (node != null) {
|
||||
try {
|
||||
if (kotlinx.coroutines.runBlocking { service.gestures.tapNode(node) }) return true
|
||||
} finally {
|
||||
runCatching { node.recycle() }
|
||||
}
|
||||
}
|
||||
Thread.sleep(WAIT_STEP_MS)
|
||||
}
|
||||
log("未找到可点击目标「$text」")
|
||||
return false
|
||||
}
|
||||
|
||||
private fun findInTree(root: SourceNode, predicate: (SourceNode) -> Boolean): SourceNode? =
|
||||
root.selfAndDescendants().firstOrNull(predicate)
|
||||
|
||||
/** 节点可读标签:text 优先、desc 兜底(微博图标+文字按钮多走 desc 渲染,e25 实测)。 */
|
||||
private fun labelOf(node: SourceNode): String =
|
||||
node.text.trim().takeIf { it.isNotEmpty() } ?: node.description.trim()
|
||||
|
||||
private fun liveFindByClass(root: AccessibilityNodeInfo?, suffix: String): AccessibilityNodeInfo? {
|
||||
if (root == null) return null
|
||||
if (root.className?.toString()?.endsWith(suffix) == true) return root
|
||||
for (i in 0 until root.childCount) {
|
||||
val child = root.getChild(i) ?: continue
|
||||
val found = liveFindByClass(child, suffix)
|
||||
if (found != null) {
|
||||
if (found !== child) runCatching { child.recycle() }
|
||||
return found
|
||||
}
|
||||
runCatching { child.recycle() }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** 收集活树中全部匹配 resource-id 的节点(供无文本控件按序定位)。 */
|
||||
private fun allById(root: AccessibilityNodeInfo?, id: String): List<AccessibilityNodeInfo> {
|
||||
val result = mutableListOf<AccessibilityNodeInfo>()
|
||||
fun walk(node: AccessibilityNodeInfo) {
|
||||
if (node.viewIdResourceName == id) result.add(AccessibilityNodeInfo.obtain(node))
|
||||
for (i in 0 until node.childCount) {
|
||||
val child = node.getChild(i) ?: continue
|
||||
try {
|
||||
walk(child)
|
||||
} finally {
|
||||
runCatching { child.recycle() }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (root != null) walk(root)
|
||||
return result
|
||||
}
|
||||
|
||||
// ── Port 实现 ────────────────────────────────────────────
|
||||
|
||||
/** 前台就绪探测:单次有界遍历同时找 拒绝项/底栏首页/底栏发现(大页面逐目标遍历会吃光预算,e7 实测)。
|
||||
* 底栏节点按区域过滤(y≥1800),避免正文里的“首页”字样误判误点(e8 实测)。 */
|
||||
private class ForegroundProbe {
|
||||
var refuse: AccessibilityNodeInfo? = null
|
||||
var homeNode: AccessibilityNodeInfo? = null
|
||||
var discover = false
|
||||
val ready: Boolean get() = homeNode != null && discover
|
||||
val done: Boolean get() = ready || refuse != null
|
||||
}
|
||||
|
||||
private fun probeForeground(root: AccessibilityNodeInfo, budget: Int = 2_000): ForegroundProbe {
|
||||
val probe = ForegroundProbe()
|
||||
var visited = 0
|
||||
val rect = android.graphics.Rect()
|
||||
fun walk(node: AccessibilityNodeInfo) {
|
||||
if (probe.done || visited++ > budget) return
|
||||
// 底栏 Tab 可能走 content-desc 渲染(微博样本无 text=首页 节点,e10 实测):text 与 desc 都认
|
||||
val label = node.text?.toString()?.takeIf { it.isNotEmpty() }
|
||||
?: node.contentDescription?.toString()?.takeIf { it.isNotEmpty() }
|
||||
when (label) {
|
||||
"不了,谢谢" -> if (probe.refuse == null) probe.refuse = AccessibilityNodeInfo.obtain(node)
|
||||
"首页" -> if (probe.homeNode == null) {
|
||||
runCatching { node.getBoundsInScreen(rect) }
|
||||
if (rect.top >= 1800) probe.homeNode = AccessibilityNodeInfo.obtain(node)
|
||||
}
|
||||
"发现" -> {
|
||||
runCatching { node.getBoundsInScreen(rect) }
|
||||
if (rect.top >= 1800) probe.discover = true
|
||||
}
|
||||
}
|
||||
for (i in 0 until node.childCount) {
|
||||
if (probe.done) return
|
||||
val child = node.getChild(i) ?: continue
|
||||
try {
|
||||
walk(child)
|
||||
} finally {
|
||||
runCatching { child.recycle() }
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(root)
|
||||
return probe
|
||||
}
|
||||
|
||||
/** 活树有界查找 resource-id(榜单页就绪判定用;避免 SourceNode 全树转换的高开销)。 */
|
||||
private fun liveHasId(root: AccessibilityNodeInfo, id: String, budget: Int = 2_000): Boolean {
|
||||
var visited = 0
|
||||
fun walk(node: AccessibilityNodeInfo): Boolean {
|
||||
if (visited++ > budget) return false
|
||||
if (node.viewIdResourceName == id) return true
|
||||
for (i in 0 until node.childCount) {
|
||||
val child = node.getChild(i) ?: continue
|
||||
val found = try {
|
||||
walk(child)
|
||||
} finally {
|
||||
runCatching { child.recycle() }
|
||||
}
|
||||
if (found) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
return walk(root)
|
||||
}
|
||||
|
||||
override fun ensureAppForeground(): Boolean {
|
||||
val deadline = SystemClock.elapsedRealtime() + 30_000
|
||||
var backs = 0
|
||||
while (SystemClock.elapsedRealtime() < deadline) {
|
||||
// 掉出 App(BACK 过头/被切走):立即重拉,不干等
|
||||
if (service.currentPackage() != WEIBO_PKG) {
|
||||
service.launchApp(WEIBO_PKG)
|
||||
Thread.sleep(1_000)
|
||||
continue
|
||||
}
|
||||
val root = service.root()
|
||||
if (root == null) {
|
||||
Thread.sleep(WAIT_STEP_MS)
|
||||
continue
|
||||
}
|
||||
val probe = probeForeground(root)
|
||||
val refuse = probe.refuse
|
||||
val homeNode = probe.homeNode
|
||||
try {
|
||||
if (refuse != null) {
|
||||
// 评分/营销弹窗:只点拒绝项(e2 实测“不了,谢谢”),不点好评/吐槽
|
||||
runCatching { kotlinx.coroutines.runBlocking { service.gestures.tapNode(refuse) } }
|
||||
Thread.sleep(WAIT_STEP_MS)
|
||||
continue
|
||||
}
|
||||
// 就绪=底栏主 Tab(首页+发现同在)**或已在热搜榜**(search_item_text 锚点;
|
||||
// 榜单页无底栏,e20 实测把它当残留收拢会搅乱页面)
|
||||
if (probe.ready) return true
|
||||
if (liveHasId(root, "com.sina.weibo:id/search_item_text")) return true
|
||||
if (homeNode != null) {
|
||||
// 有底栏“首页”但缺“发现”(过渡态):点底栏首页直达
|
||||
runCatching { kotlinx.coroutines.runBlocking { service.gestures.tapNode(homeNode) } }
|
||||
Thread.sleep(1_000)
|
||||
continue
|
||||
}
|
||||
} finally {
|
||||
runCatching { refuse?.recycle() }
|
||||
runCatching { homeNode?.recycle() }
|
||||
}
|
||||
// 无底栏=子页/弹层残留:BACK 收拢(有上限;每轮留 1s 页面过渡)
|
||||
if (backs < 4) {
|
||||
backs++
|
||||
val ok = service.gestures.back()
|
||||
log("残留页面收拢:第 $backs 次返回(dispatch=$ok)")
|
||||
Thread.sleep(1_000)
|
||||
continue
|
||||
}
|
||||
Thread.sleep(WAIT_STEP_MS)
|
||||
}
|
||||
log("进入前台失败;页面采样=${tree()?.selfAndDescendants()?.map { it.text }?.filter { it.isNotBlank() }?.take(6)}")
|
||||
return false
|
||||
}
|
||||
|
||||
private fun tapTextContains(fragment: String, timeoutMs: Long = 4_000L): Boolean {
|
||||
val deadline = SystemClock.elapsedRealtime() + timeoutMs
|
||||
while (SystemClock.elapsedRealtime() < deadline) {
|
||||
val root = service.root()
|
||||
val node = NodeLocator.byTextContains(root, fragment) ?: NodeLocator.byDescContains(root, fragment)
|
||||
if (node != null) {
|
||||
try {
|
||||
if (kotlinx.coroutines.runBlocking { service.gestures.tapNode(node) }) return true
|
||||
} finally {
|
||||
runCatching { node.recycle() }
|
||||
}
|
||||
}
|
||||
Thread.sleep(WAIT_STEP_MS)
|
||||
}
|
||||
log("未找到可点击目标(包含)「$fragment」")
|
||||
return false
|
||||
}
|
||||
|
||||
/** 底栏 Tab 点击:活树有界遍历,只认屏幕底部区(y≥1800)的 text/desc——正文里的同名词条不能点(e12 实测误点跑偏)。 */
|
||||
private fun tapBottomNav(text: String, timeoutMs: Long = 4_000L): Boolean {
|
||||
val deadline = SystemClock.elapsedRealtime() + timeoutMs
|
||||
val rect = android.graphics.Rect()
|
||||
while (SystemClock.elapsedRealtime() < deadline) {
|
||||
val root = service.root()
|
||||
if (root != null) {
|
||||
var target: AccessibilityNodeInfo? = null
|
||||
var visited = 0
|
||||
fun walk(node: AccessibilityNodeInfo) {
|
||||
if (target != null || visited++ > 2_000) return
|
||||
val label = node.text?.toString()?.takeIf { it.isNotEmpty() }
|
||||
?: node.contentDescription?.toString()?.takeIf { it.isNotEmpty() }
|
||||
if (label == text) {
|
||||
runCatching { node.getBoundsInScreen(rect) }
|
||||
if (rect.top >= 1800) {
|
||||
target = AccessibilityNodeInfo.obtain(node)
|
||||
return
|
||||
}
|
||||
}
|
||||
for (i in 0 until node.childCount) {
|
||||
if (target != null) return
|
||||
val child = node.getChild(i) ?: continue
|
||||
try {
|
||||
walk(child)
|
||||
} finally {
|
||||
runCatching { child.recycle() }
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(root)
|
||||
val found = target
|
||||
if (found != null) {
|
||||
try {
|
||||
runCatching { found.getBoundsInScreen(rect) }
|
||||
val ok = kotlinx.coroutines.runBlocking {
|
||||
service.gestures.tapAt(rect.centerX(), rect.centerY(), retry = false)
|
||||
}
|
||||
if (ok) return true
|
||||
} finally {
|
||||
runCatching { found.recycle() }
|
||||
}
|
||||
}
|
||||
}
|
||||
Thread.sleep(WAIT_STEP_MS)
|
||||
}
|
||||
log("未找到底栏目标「$text」")
|
||||
return false
|
||||
}
|
||||
|
||||
override fun openHotSearch(): Boolean {
|
||||
// 幂等入口:已在热搜榜(search_item_text Tab 行)直接过——e20 实测清单阶段后
|
||||
// 第二阶段重复走发现页会在页面状态差异下点击失效
|
||||
if (waitTree(1_500) { t -> t.findAll { it.id == "com.sina.weibo:id/search_item_text" }.isNotEmpty() }) return true
|
||||
// 首页底部“发现”(底栏锚点,禁用无过滤的文本点击)→ 发现页“更多热搜”→
|
||||
// 热搜榜(就绪标志=search_item_text Tab 行锚点;“我的”tab 提示语是“热搜雷达”、
|
||||
// “热搜”tab 是“实时热点”,不按提示语判)
|
||||
if (!tapBottomNav("发现")) {
|
||||
log("OPEN_HOT_SEARCH 失败子步:底栏“发现”未点到")
|
||||
return false
|
||||
}
|
||||
if (!waitTree(8_000) { t ->
|
||||
t.findAll {
|
||||
it.text.contains("更多热搜") || it.description.contains("更多热搜")
|
||||
}.isNotEmpty()
|
||||
}
|
||||
) {
|
||||
log("OPEN_HOT_SEARCH 失败子步:发现页“更多热搜”未出现")
|
||||
return false
|
||||
}
|
||||
// “更多热搜”入口(e4 dump 核验):热搜预览块是一个大 View(clickable,desc=全部词条拼接
|
||||
// 且以“更多热搜”结尾,bounds [0,389][1080,935]),按钮无独立节点——
|
||||
// 核验块特征后点块内右下“更多热搜”文字位置(相对坐标:块宽 68%、底-72px,与实测点 (732,863) 吻合)。
|
||||
// e19 实测同码在不同页面状态下偶发不跳转:每次重新取块并点击、验证跳转,最多 3 轮。
|
||||
repeat(3) { attempt ->
|
||||
var blockBounds: com.haorui.app.crossplatform.source.SourceBounds? = null
|
||||
val deadlineInner = SystemClock.elapsedRealtime() + 5_000
|
||||
while (blockBounds == null && SystemClock.elapsedRealtime() < deadlineInner) {
|
||||
blockBounds = tree()?.selfAndDescendants()?.firstOrNull { n ->
|
||||
n.clickable && n.description.trim().endsWith("更多热搜")
|
||||
}?.bounds
|
||||
if (blockBounds == null) Thread.sleep(WAIT_STEP_MS)
|
||||
}
|
||||
val b = blockBounds
|
||||
if (b != null && kotlinx.coroutines.runBlocking {
|
||||
service.gestures.tapAt(b.left + (b.right - b.left) * 68 / 100, b.bottom - 72, retry = false)
|
||||
}
|
||||
) {
|
||||
log("更多热搜入口点击(第 ${attempt + 1} 轮,块 bounds=$b)")
|
||||
if (waitTree(6_000) { t -> t.findAll { it.id == "com.sina.weibo:id/search_item_text" }.isNotEmpty() }) return true
|
||||
} else {
|
||||
log("更多热搜入口未找到或点击未派发(第 ${attempt + 1} 轮)")
|
||||
}
|
||||
}
|
||||
log("OPEN_HOT_SEARCH 失败子步:三轮点击后热搜榜 Tab 行锚点未出现;采样=${tree()?.selfAndDescendants()?.map { it.text }?.filter { it.isNotBlank() }?.take(6)}")
|
||||
return false
|
||||
}
|
||||
|
||||
override fun switchCategory(tabLabel: String): Boolean {
|
||||
// Tab 文本锚点;点击后以“解析器读得出榜单行”为就绪条件(未加载完不算)
|
||||
if (!tapText(tabLabel)) return false
|
||||
return waitTree(8_000) { t -> WeiboHotSearchParser.parse(t).isNotEmpty() }
|
||||
}
|
||||
|
||||
override fun readListTree(): SourceNode = tree() ?: SourceNode()
|
||||
|
||||
override fun openTopic(index: Int): Boolean {
|
||||
val entries = WeiboHotSearchParser.parse(readListTree())
|
||||
val title = entries.getOrNull(index)?.title ?: return false
|
||||
val deadline = SystemClock.elapsedRealtime() + 4_000
|
||||
var tapped = false
|
||||
while (!tapped && SystemClock.elapsedRealtime() < deadline) {
|
||||
val node = NodeLocator.byText(service.root(), title)
|
||||
if (node != null) {
|
||||
try {
|
||||
tapped = kotlinx.coroutines.runBlocking { service.gestures.tapNode(node) }
|
||||
} finally {
|
||||
runCatching { node.recycle() }
|
||||
}
|
||||
}
|
||||
if (!tapped) Thread.sleep(WAIT_STEP_MS)
|
||||
}
|
||||
if (!tapped) return false
|
||||
return waitTree(6_000) { t -> t.findAll { it.text.contains("阅读量") || it.text.contains("讨论量") }.isNotEmpty() }
|
||||
}
|
||||
|
||||
override fun readTopicTree(): SourceNode = tree() ?: SourceNode()
|
||||
|
||||
override fun openPost(index: Int): Boolean {
|
||||
// 话题页博文卡正文为自绘 View(contentTextView,text 空):按 id 收集取第 index 个
|
||||
val deadline = SystemClock.elapsedRealtime() + 4_000
|
||||
var tapped = false
|
||||
while (!tapped && SystemClock.elapsedRealtime() < deadline) {
|
||||
val nodes = allById(service.root(), "com.sina.weibo:id/contentTextView")
|
||||
val target = nodes.getOrNull(index)
|
||||
if (target != null) {
|
||||
try {
|
||||
tapped = kotlinx.coroutines.runBlocking { service.gestures.tapNode(target) }
|
||||
} finally {
|
||||
nodes.forEach { runCatching { it.recycle() } }
|
||||
}
|
||||
}
|
||||
if (!tapped) Thread.sleep(WAIT_STEP_MS)
|
||||
}
|
||||
if (!tapped) return false
|
||||
// 详情页就绪:顶栏右上组(听/⋯ 所在容器,e3 核验 id)
|
||||
return waitTree(6_000) { t ->
|
||||
t.findAll { it.id == "com.sina.weibo:id/detail_activity_header_right_group" }.isNotEmpty()
|
||||
}
|
||||
}
|
||||
|
||||
override fun readPostTree(): SourceNode = tree() ?: SourceNode()
|
||||
|
||||
/** 详情页作者/发布时间为自绘:走应用自身 OCR 管线取行文本(与草稿回执同管线)。 */
|
||||
override fun readPostOcrLines(): List<String> = ocrCurrentScreen()
|
||||
|
||||
/**
|
||||
* 详情页正文全文:**逐屏 OCR + 半屏上滑 + 行序去重拼接**(M4 事实包主路线)。
|
||||
* 终止条件:①连续两屏无新行(页底;覆盖"内容完全相同"与"时间戳微变"两种形态)
|
||||
* ②达到屏数上限 ③OCR 连续失败 ④滑动失败(已到底或系统未确认,宁少勿错拼)。
|
||||
* 每屏之间留足渲染时间。注:循环用 for+break——repeat 的 return@repeat 只跳过单轮,
|
||||
* 不能终止循环(2026-11-15 自检发现,勿改回 repeat)。
|
||||
*/
|
||||
fun readPostOcrFullText(maxScreens: Int = 8): List<String> {
|
||||
val allLines = mutableListOf<String>()
|
||||
val seen = HashSet<String>()
|
||||
var noNewCount = 0
|
||||
for (screen in 0 until maxScreens) {
|
||||
val lines = ocrCurrentScreen()
|
||||
if (lines.isEmpty()) {
|
||||
log("全文 OCR 第 $screen 屏识别失败,继续尝试")
|
||||
Thread.sleep(1_000)
|
||||
continue
|
||||
}
|
||||
// 行序去重拼接:跨屏/同屏重叠行只保留首现(半屏滑动必然重叠)
|
||||
var appended = 0
|
||||
lines.forEach { line ->
|
||||
val text = line.trim()
|
||||
if (text.isNotEmpty() && seen.add(text)) {
|
||||
allLines.add(text)
|
||||
appended++
|
||||
}
|
||||
}
|
||||
log("全文 OCR 第 $screen 屏:识别 ${lines.size} 行,新增 $appended 行")
|
||||
// 页底判定:连续两屏没有新行(签名稳定或时间戳微变均归此类)即终止
|
||||
if (appended == 0) {
|
||||
noNewCount++
|
||||
if (noNewCount >= 2) {
|
||||
log("全文 OCR 连续两屏无新行,判定到达页底")
|
||||
break
|
||||
}
|
||||
} else {
|
||||
noNewCount = 0
|
||||
}
|
||||
// 半屏上滑(详情页滚动;失败=到底或系统未确认,终止)
|
||||
val scrolled = kotlinx.coroutines.runBlocking {
|
||||
service.gestures.swipe(0.5f, 0.72f, 0.5f, 0.30f)
|
||||
}
|
||||
if (!scrolled) {
|
||||
log("全文 OCR 第 $screen 屏滑动失败,终止")
|
||||
break
|
||||
}
|
||||
Thread.sleep(1_200) // 渲染稳定
|
||||
}
|
||||
return allLines
|
||||
}
|
||||
|
||||
/** 单屏截屏+OCR(readPostOcrLines 与全文采集共用)。 */
|
||||
private fun ocrCurrentScreen(): List<String> {
|
||||
val bitmap: Bitmap = kotlinx.coroutines.runBlocking {
|
||||
com.haorui.app.ocr.ScreenCapturer(service).capture()
|
||||
} ?: return emptyList()
|
||||
return try {
|
||||
val blocks = kotlinx.coroutines.runBlocking { com.haorui.app.ocr.OcrProcessor.recognize(bitmap) }
|
||||
blocks.flatMap { it.lines }.map { it.text.trim() }.filter { it.isNotEmpty() }
|
||||
} finally {
|
||||
bitmap.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 定位底部“分享”按钮的**可点击祖先** bounds。
|
||||
* e4-03 dump 实锤:按钮文字节点 text="分享" 但 **bounds=[0,0][0,0]**(文字坐标为空,实节点是父容器——
|
||||
* 与头条底栏“我的”同坑);因此找到标签后回退到链路上最近的可点击祖先再点击。
|
||||
*/
|
||||
private fun liveFindShareAnchor(root: AccessibilityNodeInfo, budget: Int = 8_000): android.graphics.Rect? {
|
||||
var visited = 0
|
||||
val rect = android.graphics.Rect()
|
||||
fun walk(node: AccessibilityNodeInfo, clickableAncestor: android.graphics.Rect?): android.graphics.Rect? {
|
||||
if (visited++ > budget) return null
|
||||
runCatching { node.getBoundsInScreen(rect) }
|
||||
val selfClickable = node.isClickable && rect.width() > 0
|
||||
val anchor = if (selfClickable) android.graphics.Rect(rect) else clickableAncestor
|
||||
val label = node.text?.toString()?.replace('\u00A0', ' ')?.trim()?.takeIf { it.isNotEmpty() }
|
||||
?: node.contentDescription?.toString()?.replace('\u00A0', ' ')?.trim().orEmpty()
|
||||
// e30:标签可能带不换行空格等隐形字符,contains 容错;y>1900 祖先约束排除顶栏同名
|
||||
if (label.contains("分享") && anchor != null && anchor.top > 1900) return anchor
|
||||
for (i in 0 until node.childCount) {
|
||||
val child = node.getChild(i) ?: continue
|
||||
val found = try {
|
||||
walk(child, anchor)
|
||||
} finally {
|
||||
runCatching { child.recycle() }
|
||||
}
|
||||
if (found != null) return found
|
||||
}
|
||||
return null
|
||||
}
|
||||
return walk(root, null)
|
||||
}
|
||||
|
||||
/** 右上图标(layout B 分享箭头 / layout A 「⋯」):clickable、x>850、y∈40..280;
|
||||
* 排除“关注/回关/已关注”与“听”(带文字标签的功能钮),其余(无标签或标签含“分享”)均可点。 */
|
||||
private fun liveFindTopRightIcon(root: AccessibilityNodeInfo, budget: Int = 2_000): android.graphics.Rect? {
|
||||
var visited = 0
|
||||
val rect = android.graphics.Rect()
|
||||
fun walk(node: AccessibilityNodeInfo): android.graphics.Rect? {
|
||||
if (visited++ > budget) return null
|
||||
runCatching { node.getBoundsInScreen(rect) }
|
||||
val label = node.text?.toString()?.replace('\u00A0', ' ')?.trim()?.takeIf { it.isNotEmpty() }
|
||||
?: node.contentDescription?.toString()?.replace('\u00A0', ' ')?.trim().orEmpty()
|
||||
if (node.isClickable && rect.width() > 0 && rect.left > 850 && rect.top in 40..280 &&
|
||||
!label.contains("关注") && !label.contains("听")
|
||||
) return android.graphics.Rect(rect)
|
||||
for (i in 0 until node.childCount) {
|
||||
val child = node.getChild(i) ?: continue
|
||||
val found = try {
|
||||
walk(child)
|
||||
} finally {
|
||||
runCatching { child.recycle() }
|
||||
}
|
||||
if (found != null) return found
|
||||
}
|
||||
return null
|
||||
}
|
||||
return walk(root)
|
||||
}
|
||||
|
||||
override fun openShareMenu(): Boolean {
|
||||
// 双布局锚点(e1/e3/e4 取证):layout A 置顶详情=底栏“分享”(文字节点坐标空→点可点击祖先);
|
||||
// layout B 普通详情=右上无名图标(分享箭头/⋯)。面板就绪标志=“取消”(面板独有)。
|
||||
repeat(2) { attempt ->
|
||||
val root = service.root()
|
||||
val bottom = root?.let { liveFindShareAnchor(it) }
|
||||
val topRight = root?.let { liveFindTopRightIcon(it) }
|
||||
val anchor = bottom ?: topRight
|
||||
log("分享入口定位(第 ${attempt + 1} 轮):底栏祖先=$bottom 右上图标=$topRight")
|
||||
if (anchor != null && kotlinx.coroutines.runBlocking {
|
||||
service.gestures.tapAt(anchor.centerX(), anchor.centerY(), retry = false)
|
||||
} && waitTree(4_000) { t -> t.findAll { labelOf(it) == "取消" }.isNotEmpty() }
|
||||
) return true
|
||||
}
|
||||
log("openShareMenu 失败:两布局锚点点击后面板均未弹出")
|
||||
return false
|
||||
}
|
||||
|
||||
/** 面板横滑行的原生滚动:找下部可滚容器执行 ACTION_SCROLL_FORWARD(手势横滑易被面板误判为拖拽关闭,e35)。 */
|
||||
private fun liveScrollPanelRow(): Boolean {
|
||||
val root = service.root() ?: return false
|
||||
var visited = 0
|
||||
val rect = android.graphics.Rect()
|
||||
fun walk(node: AccessibilityNodeInfo): AccessibilityNodeInfo? {
|
||||
if (visited++ > 4_000) return null
|
||||
runCatching { node.getBoundsInScreen(rect) }
|
||||
if (node.isScrollable && rect.top > 1400) return AccessibilityNodeInfo.obtain(node)
|
||||
for (i in 0 until node.childCount) {
|
||||
val child = node.getChild(i) ?: continue
|
||||
val found = try {
|
||||
walk(child)
|
||||
} finally {
|
||||
runCatching { child.recycle() }
|
||||
}
|
||||
if (found != null) return found
|
||||
}
|
||||
return null
|
||||
}
|
||||
val target = walk(root) ?: return false
|
||||
return try {
|
||||
runCatching { target.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD) }.getOrDefault(false)
|
||||
} finally {
|
||||
runCatching { target.recycle() }
|
||||
}
|
||||
}
|
||||
|
||||
override fun copyShareLink(): String? {
|
||||
// 复制链接在面板第 3 行横滑区(e3-08 取证):找不到就滚动该行;
|
||||
// 优先无障碍原生滚动(ACTION_SCROLL_FORWARD),失败退化为横滑手势
|
||||
var copied = false
|
||||
val deadline = SystemClock.elapsedRealtime() + 20_000
|
||||
while (!copied && SystemClock.elapsedRealtime() < deadline) {
|
||||
// 面板节点在树深处,NodeLocator 深遍历找不到(e31/e32);离屏节点坐标退化在屏外(e33 实测
|
||||
// bounds=[1080,*][1080,*] 零宽=横滑区未滚动位置)——只点**在屏可见**节点,找不到则横滑重试
|
||||
val target = tree()?.selfAndDescendants()?.firstOrNull { n ->
|
||||
val b = n.bounds
|
||||
(n.text.contains("复制链接") || n.description.contains("复制链接")) &&
|
||||
b != null && b.right > b.left && b.left >= 0 && b.right <= 1080 && b.top > 1500
|
||||
}
|
||||
val b = target?.bounds
|
||||
if (b != null && kotlinx.coroutines.runBlocking {
|
||||
service.gestures.tapAt(b.centerX, b.centerY, retry = false)
|
||||
}
|
||||
) {
|
||||
copied = true
|
||||
log("复制链接点击:bounds=$b")
|
||||
}
|
||||
if (!copied) {
|
||||
val scrolled = liveScrollPanelRow()
|
||||
log("面板行滚动重试:ACTION_SCROLL_FORWARD=$scrolled")
|
||||
if (!scrolled) {
|
||||
kotlinx.coroutines.runBlocking { service.gestures.swipe(0.85f, 0.78f, 0.25f, 0.78f) }
|
||||
}
|
||||
Thread.sleep(1_200) // 滚动后留足渲染与树更新时间
|
||||
}
|
||||
}
|
||||
if (!copied) {
|
||||
log("复制链接未找到(面板横滑重试后仍无)")
|
||||
return null
|
||||
}
|
||||
Thread.sleep(800)
|
||||
val quick = runCatching {
|
||||
ClipboardBridge.readFromClipboard(service) { log("剪贴板诊断: $it") }
|
||||
}.getOrNull()
|
||||
if (!quick.isNullOrBlank() && quick.contains("weibo")) return quick.trim()
|
||||
log("剪贴板不可读,走搜索框粘贴取证")
|
||||
return readLinkViaSearchBox()
|
||||
}
|
||||
|
||||
/** 本机兜底:微博搜索框 ACTION_PASTE → 读文本 → 清空 → 返回(与知乎同管线,不切 App)。 */
|
||||
private fun readLinkViaSearchBox(): String? {
|
||||
repeat(3) {
|
||||
if (tree()?.findAll { it.text.contains("更多热搜") }?.isNotEmpty() == true) return@repeat
|
||||
service.gestures.back()
|
||||
}
|
||||
// 发现页搜索入口:搜索框(占位文本“大家正在搜:…”/“猜你想搜”)——按钮文本实测为“搜索,”带尾标点
|
||||
// (e1-03 dump),exact 匹配不稳;点框体进搜索页(手动取证同款路径,y<400 区域约束)
|
||||
val searchBox = run {
|
||||
val deadlineInner = SystemClock.elapsedRealtime() + 4_000
|
||||
var node: SourceNode? = null
|
||||
while (node == null && SystemClock.elapsedRealtime() < deadlineInner) {
|
||||
node = tree()?.selfAndDescendants()?.firstOrNull { n ->
|
||||
(n.text.contains("大家正在搜") || n.text.contains("猜你想搜")) &&
|
||||
n.bounds != null && n.bounds!!.right > n.bounds!!.left && n.bounds!!.top < 400
|
||||
}
|
||||
if (node == null) Thread.sleep(WAIT_STEP_MS)
|
||||
}
|
||||
node
|
||||
}
|
||||
val searchBounds = searchBox?.bounds
|
||||
if (searchBounds == null || !kotlinx.coroutines.runBlocking {
|
||||
service.gestures.tapAt(searchBounds.centerX, searchBounds.centerY, retry = false)
|
||||
}
|
||||
) {
|
||||
log("搜索框未定位(readLinkViaSearchBox)")
|
||||
return null
|
||||
}
|
||||
if (!waitTree(5_000) { t -> findInTree(t) { n -> n.className.endsWith("EditText") } != null }) return null
|
||||
val pasted = run {
|
||||
val liveInput = liveFindByClass(service.root(), "EditText") ?: return@run false
|
||||
try {
|
||||
runCatching { liveInput.performAction(AccessibilityNodeInfo.ACTION_PASTE) }.getOrDefault(false)
|
||||
} finally {
|
||||
runCatching { liveInput.recycle() }
|
||||
}
|
||||
}
|
||||
if (!pasted) {
|
||||
log("搜索框 ACTION_PASTE 未被接受")
|
||||
return null
|
||||
}
|
||||
Thread.sleep(500)
|
||||
val link = tree()?.let { t -> findInTree(t) { n -> n.className.endsWith("EditText") } }?.text?.trim().orEmpty()
|
||||
val clearInput = liveFindByClass(service.root(), "EditText")
|
||||
if (clearInput != null) {
|
||||
try {
|
||||
kotlinx.coroutines.runBlocking { service.gestures.setText(clearInput, "") }
|
||||
} finally {
|
||||
runCatching { clearInput.recycle() }
|
||||
}
|
||||
}
|
||||
service.gestures.back()
|
||||
return link.takeIf { it.contains("weibo") }
|
||||
}
|
||||
|
||||
override fun leaveShareMenu(): Boolean {
|
||||
// 面板在场标志=“取消”按钮(面板独有;底栏也有“分享”文本,不能用它判面板开合)
|
||||
if (waitTree(1_200) { t -> t.findAll { labelOf(it) == "取消" }.isEmpty() }) return true
|
||||
if (tapText("取消", timeoutMs = 2_000)) {
|
||||
return waitTree(3_000) { t -> t.findAll { labelOf(it) == "取消" }.isEmpty() }
|
||||
}
|
||||
service.gestures.back()
|
||||
return waitTree(3_000) { t -> t.findAll { labelOf(it) == "取消" }.isEmpty() }
|
||||
}
|
||||
|
||||
override fun backToHotList(): Boolean {
|
||||
// 最多三次返回:详情 → 话题 → 热搜榜(就绪=search_item_text Tab 行锚点)
|
||||
repeat(3) {
|
||||
if (waitTree(1_500) { t -> t.findAll { it.id == "com.sina.weibo:id/search_item_text" }.isNotEmpty() }) return true
|
||||
service.gestures.back()
|
||||
}
|
||||
return waitTree(3_000) { t -> t.findAll { it.id == "com.sina.weibo:id/search_item_text" }.isNotEmpty() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package com.haorui.app.crossplatform.source.weibo
|
||||
|
||||
import com.haorui.app.crossplatform.source.SourceNode
|
||||
|
||||
/**
|
||||
* 微博单类目采集状态机(骨架,2026-11-14 e2 取证口径)。
|
||||
*
|
||||
* 产品口径(用户定):用户在热点候选页下拉勾选类目 → 按类目切微博热搜 Tab 拉榜单
|
||||
* → 词条清单展示/确认 → 采该话题代表性博文 → 图文/视频生成 → 发头条。
|
||||
*
|
||||
* 约束(跨平台自动发布设计 + 知乎经验):
|
||||
* - 一次候选完成才让出前台,失败都走 EXIT 安全退出;
|
||||
* - 缺失字段保留未知(进 unknowns),不从行序、图标或无关文本推断;
|
||||
* - 排名/热新爆标签为图片渲染,rank/label 恒未知;
|
||||
* - 分享链接必须与当前候选配对后才作身份,未核验形态拒绝。
|
||||
*
|
||||
* 真机驱动通过 [Port] 接入;未完成真机适配前不注册任何能力,入口由 SourceRegistry 门控拦截。
|
||||
*/
|
||||
class WeiboHotListCollector(
|
||||
private val port: Port,
|
||||
private val nowMs: () -> Long = System::currentTimeMillis,
|
||||
) {
|
||||
/** 真机驱动接口:每个方法都是一次页面操作,实现方负责可见性核对,禁止盲点。 */
|
||||
interface Port {
|
||||
fun ensureAppForeground(): Boolean
|
||||
fun openHotSearch(): Boolean
|
||||
fun switchCategory(tabLabel: String): Boolean
|
||||
fun readListTree(): SourceNode
|
||||
fun openTopic(index: Int): Boolean
|
||||
fun readTopicTree(): SourceNode
|
||||
fun openPost(index: Int): Boolean
|
||||
fun readPostTree(): SourceNode
|
||||
/** 详情页自绘区域的 OCR 文本行(作者/发布时间只在 OCR 行里,e3 实测)。 */
|
||||
fun readPostOcrLines(): List<String>
|
||||
fun openShareMenu(): Boolean
|
||||
fun copyShareLink(): String?
|
||||
fun leaveShareMenu(): Boolean
|
||||
fun backToHotList(): Boolean
|
||||
}
|
||||
|
||||
enum class Phase {
|
||||
OPEN_APP, OPEN_HOT_SEARCH, SWITCH_CATEGORY, READ_LIST,
|
||||
OPEN_TOPIC, READ_TOPIC, OPEN_POST, READ_POST, COPY_SHARE_LINK,
|
||||
SAVE_OBSERVATION, EXIT, DONE, FAILED,
|
||||
}
|
||||
|
||||
/** 类目词条清单结果:entries 为该类目榜单快照(用户勾选/确认的数据源)。 */
|
||||
data class ListResult(
|
||||
val outcome: String,
|
||||
val phase: Phase,
|
||||
val entries: List<WeiboHotEntry> = emptyList(),
|
||||
val reason: String = "",
|
||||
val exitedSafely: Boolean = false,
|
||||
)
|
||||
|
||||
/** 单条内容采集结果;失败相位即 [phase],观察到的未知字段进 unknowns。 */
|
||||
data class Result(
|
||||
val outcome: String,
|
||||
val phase: Phase,
|
||||
val observation: WeiboPostObservation? = null,
|
||||
val reason: String = "",
|
||||
val exitedSafely: Boolean = false,
|
||||
)
|
||||
|
||||
/** 运行代际:停止/重启后递增,迟到的观察不得混入新代际。 */
|
||||
var runGeneration: Long = 0
|
||||
|
||||
var phase: Phase = Phase.OPEN_APP
|
||||
private set
|
||||
|
||||
/** 拉取 [category] 的榜单词条清单(OPEN_APP→…→READ_LIST→EXIT)。 */
|
||||
fun collectCategoryEntries(category: WeiboHotCategory): ListResult {
|
||||
var entries: List<WeiboHotEntry> = emptyList()
|
||||
var failure: String? = null
|
||||
var failedAt: Phase? = null
|
||||
var exitedSafely = false
|
||||
try {
|
||||
phase = Phase.OPEN_APP
|
||||
if (!port.ensureAppForeground()) fail("微博未能进入前台")
|
||||
phase = Phase.OPEN_HOT_SEARCH
|
||||
if (!port.openHotSearch()) fail("热搜榜入口未打开")
|
||||
phase = Phase.SWITCH_CATEGORY
|
||||
if (!port.switchCategory(category.tabLabel)) fail("类目「${category.tabLabel}」未切换成功")
|
||||
phase = Phase.READ_LIST
|
||||
entries = WeiboHotSearchParser.parse(port.readListTree())
|
||||
if (entries.isEmpty()) fail("类目「${category.tabLabel}」榜单为空或结构未核验")
|
||||
} catch (stop: StopRequest) {
|
||||
failure = stop.message
|
||||
failedAt = phase
|
||||
} finally {
|
||||
phase = Phase.EXIT
|
||||
exitedSafely = runCatching { port.backToHotList() }.getOrDefault(false)
|
||||
}
|
||||
return ListResult(
|
||||
outcome = if (failure == null) "已取得" else "失败",
|
||||
phase = failedAt ?: Phase.DONE,
|
||||
entries = entries,
|
||||
reason = failure.orEmpty(),
|
||||
exitedSafely = exitedSafely,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 采集类目榜单第 [entryIndex] 条话题的第 [postIndex] 条代表性博文。
|
||||
* 话题页无发布时间时保留未知;分享链接经 [ZhihuShareLinkParser] 之外的独立核验(待 URL 形态取证后接入)。
|
||||
*
|
||||
* @param onDetail 详情页仍在前台时回调(SAVE_OBSERVATION 之后、EXIT 之前)。
|
||||
* 供调用方取详情页材料(如逐屏全文 OCR)——⚠️ EXIT 会返回榜单,退出后再读屏读到的是榜单
|
||||
* 不是帖子(2026-11-15 真机取证教训:composeVerify 曾因此把榜单当来源正文)。
|
||||
* 回调异常吞掉,不影响采集结果(调用方自行记录失败)。
|
||||
*/
|
||||
fun collectOne(
|
||||
category: WeiboHotCategory,
|
||||
entryIndex: Int,
|
||||
postIndex: Int = 0,
|
||||
onDetail: (() -> Unit)? = null,
|
||||
): Result {
|
||||
var observation: WeiboPostObservation? = null
|
||||
var failure: String? = null
|
||||
var failedAt: Phase? = null
|
||||
var exitedSafely = false
|
||||
try {
|
||||
phase = Phase.OPEN_APP
|
||||
if (!port.ensureAppForeground()) fail("微博未能进入前台")
|
||||
phase = Phase.OPEN_HOT_SEARCH
|
||||
if (!port.openHotSearch()) fail("热搜榜入口未打开")
|
||||
phase = Phase.SWITCH_CATEGORY
|
||||
if (!port.switchCategory(category.tabLabel)) fail("类目「${category.tabLabel}」未切换成功")
|
||||
phase = Phase.READ_LIST
|
||||
val entries = WeiboHotSearchParser.parse(port.readListTree())
|
||||
val entry = entries.getOrNull(entryIndex) ?: fail("类目「${category.tabLabel}」第 $entryIndex 条不存在")
|
||||
|
||||
phase = Phase.OPEN_TOPIC
|
||||
if (!port.openTopic(entryIndex)) fail("话题「${entry.title.take(12)}」未打开")
|
||||
phase = Phase.READ_TOPIC
|
||||
val topic = port.readTopicTree()
|
||||
|
||||
phase = Phase.OPEN_POST
|
||||
if (!port.openPost(postIndex)) fail("第 $postIndex 条博文未打开")
|
||||
phase = Phase.READ_POST
|
||||
val post = WeiboPostParser.parse(port.readPostTree(), port.readPostOcrLines(), nowMs())
|
||||
|
||||
phase = Phase.COPY_SHARE_LINK
|
||||
val linkText = runCatching { port.openShareMenu() }.getOrDefault(false)
|
||||
.let { opened -> if (opened) port.copyShareLink() else null }
|
||||
runCatching { port.leaveShareMenu() }
|
||||
val shareLink = WeiboShareLinkParser.parse(linkText)
|
||||
|
||||
phase = Phase.SAVE_OBSERVATION
|
||||
observation = WeiboPostObservation(
|
||||
category = category,
|
||||
hotEntry = entry,
|
||||
author = post.author,
|
||||
content = post.content,
|
||||
publishedAtText = post.publishedAtText,
|
||||
publishedAtMs = post.publishedAtMs,
|
||||
repostCount = post.repostCount,
|
||||
commentCount = post.commentCount,
|
||||
likeCount = post.likeCount,
|
||||
sourceUrl = shareLink.canonicalUrl,
|
||||
fetchedAtMs = nowMs(),
|
||||
runGeneration = runGeneration,
|
||||
unknowns = buildUnknowns(entry, post, shareLink, topic),
|
||||
)
|
||||
// 详情页仍在前台:回调调用方取全文材料(异常吞掉——采集结果不受 OCR 等附属动作影响)
|
||||
runCatching { onDetail?.invoke() }
|
||||
} catch (stop: StopRequest) {
|
||||
failure = stop.message
|
||||
failedAt = phase
|
||||
} finally {
|
||||
phase = Phase.EXIT
|
||||
val leftShare = runCatching { port.leaveShareMenu() }.getOrDefault(true)
|
||||
val backed = runCatching { port.backToHotList() }.getOrDefault(false)
|
||||
exitedSafely = leftShare && backed
|
||||
}
|
||||
return Result(
|
||||
outcome = if (observation != null) "已观察" else "失败",
|
||||
phase = failedAt ?: Phase.DONE,
|
||||
observation = observation,
|
||||
reason = failure.orEmpty(),
|
||||
exitedSafely = exitedSafely,
|
||||
)
|
||||
}
|
||||
|
||||
private class StopRequest(message: String) : RuntimeException(message)
|
||||
|
||||
private fun fail(reason: String): Nothing = throw StopRequest(reason)
|
||||
|
||||
/** 未知口径清单:把“没读到什么”显式记录,供筛选阶段按“缺值不伪造”处置。 */
|
||||
private fun buildUnknowns(
|
||||
entry: WeiboHotEntry,
|
||||
post: WeiboPostDetail,
|
||||
shareLink: WeiboShareLinkResult,
|
||||
topic: SourceNode,
|
||||
): List<String> {
|
||||
val unknowns = mutableListOf<String>()
|
||||
if (entry.rank == null) unknowns += "排名未知(排名为图片渲染)"
|
||||
if (entry.heatValue == null) unknowns += "热度数值未知(原文=${entry.heatRaw ?: "缺失"})"
|
||||
if (post.publishedAtMs == null) unknowns += "发布时间未知:${post.unknownReason}"
|
||||
if (!shareLink.accepted) unknowns += "分享链接未核验:${shareLink.reason}"
|
||||
if (topic.selfAndDescendants().none { it.text.isNotBlank() }) unknowns += "话题页无可读文本"
|
||||
return unknowns
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.haorui.app.crossplatform.source.weibo
|
||||
|
||||
import com.haorui.app.crossplatform.source.SourceNode
|
||||
|
||||
/**
|
||||
* 微博热搜榜解析器(com.sina.weibo,2026-11-14 e1 取证结构)。
|
||||
*
|
||||
* 榜单行结构(嵌套实测,⚠️ id 命名沿用 coupon 控件但实际是热搜行):
|
||||
* 行容器(无 id、clickable)→ iv_coupon_icon(排名图片) + rl_coupon_des
|
||||
* → tv_coupon_des(词条标题) + [tv_coupon_des_extr(热度数值)] + [iv_highlight_icon(标签图片)]
|
||||
*
|
||||
* 关键口径:
|
||||
* - 排名数字与热/新/爆标签都是**图片渲染**,节点树读不到:rank/label 保留 null,不按行序推断
|
||||
* (置顶行与“•”推广行会穿插,行序 ≠ 排名);
|
||||
* - 热度只认纯数值文本(实测 1398201 形态);“17:52登顶”“最近…”等非数值口径保留原文、数值为 null;
|
||||
* - 无热度数值的行(置顶/官宣/上新位)标记 heatMissing,不删除、不伪造热度——
|
||||
* 用户勾选模式下由人决定是否采集。
|
||||
*/
|
||||
object WeiboHotSearchParser {
|
||||
const val PACKAGE = "com.sina.weibo"
|
||||
|
||||
internal fun res(name: String) = "$PACKAGE:id/$name"
|
||||
|
||||
private val HEAT_PATTERN = Regex("^(\\d{1,3}(?:,\\d{3})+|\\d+)$")
|
||||
|
||||
fun parse(root: SourceNode): List<WeiboHotEntry> {
|
||||
// 成组锚点用双 id:rl_coupon_des + tv_coupon_des。
|
||||
// ⚠️ 单 id(tv_coupon_des)会让 deepestGroupsContaining 把标题节点自身当组(自包含),
|
||||
// 组内读不到兄弟的热度节点;双 id 使组落在 rl_coupon_des(含标题与热度)。
|
||||
val rows = root.deepestGroupsContaining(res("rl_coupon_des"), res("tv_coupon_des"))
|
||||
return rows.mapIndexedNotNull { index, row -> parseRow(row, index) }
|
||||
}
|
||||
|
||||
private fun parseRow(row: SourceNode, index: Int): WeiboHotEntry? {
|
||||
val title = row.firstById(res("tv_coupon_des"))?.text?.trim().orEmpty()
|
||||
if (title.isEmpty()) return null // 缺词条的行不是候选:跳过,不伪造身份
|
||||
val heatRaw = row.firstById(res("tv_coupon_des_extr"))?.text?.trim()?.takeIf { it.isNotEmpty() }
|
||||
val heat = parseHeat(heatRaw)
|
||||
return WeiboHotEntry(
|
||||
title = title,
|
||||
heatRaw = heatRaw,
|
||||
heatValue = heat,
|
||||
rank = null, // 排名为图片渲染,保留未知
|
||||
label = null, // 标签为图片渲染,保留未知
|
||||
order = index,
|
||||
heatMissing = heat == null,
|
||||
)
|
||||
}
|
||||
|
||||
/** “1398201”→1398201;“1,398,201”→1398201;“17:52登顶”等非纯数值保留未知。 */
|
||||
internal fun parseHeat(raw: String?): Long? {
|
||||
if (raw.isNullOrBlank()) return null
|
||||
val match = HEAT_PATTERN.matchEntire(raw.trim()) ?: return null
|
||||
return match.groupValues[1].replace(",", "").toLongOrNull()?.takeIf { it >= 0 }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.haorui.app.crossplatform.source.weibo
|
||||
|
||||
/**
|
||||
* 微博采集解析结果模型。
|
||||
*
|
||||
* 口径约束(缺值不伪造):解析不到的字段一律保留 null,
|
||||
* 不从行序、图标或无关文本推断补齐。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 微博热搜条目(2026-11-14 e1 取证形态)。
|
||||
* 排名数字与热/新/爆标签均为图片渲染(iv_coupon_icon / iv_highlight_icon),节点树不可读:
|
||||
* [rank]、[label] 保留 null(未知),不按行序推断——置顶行与推广行会穿插在榜单中。
|
||||
* [order] 仅为展示序(页面从上到下),不是排名。
|
||||
*/
|
||||
data class WeiboHotEntry(
|
||||
val title: String,
|
||||
val heatRaw: String? = null,
|
||||
val heatValue: Long? = null,
|
||||
val rank: Int? = null,
|
||||
val label: String? = null,
|
||||
val order: Int = 0,
|
||||
/** 无热度数值的行(置顶/推广/官宣位)嫌疑标记;不删除,交由筛选阶段与用户勾选处置。 */
|
||||
val heatMissing: Boolean = true,
|
||||
)
|
||||
|
||||
/**
|
||||
* 微博热搜类目(2026-11-14 e2 实测 Tab 清单,横滑全量枚举)。
|
||||
* 末位「更多」为类目行入口按钮,不作类目;未核验的类目不入清单。
|
||||
* [tabLabel] 为微博 Tab 显示文本(采集时按键名定位),[id] 为内部稳定键。
|
||||
*/
|
||||
data class WeiboHotCategory(val id: String, val tabLabel: String)
|
||||
|
||||
object WeiboHotCategories {
|
||||
val ALL: List<WeiboHotCategory> = listOf(
|
||||
WeiboHotCategory("mine", "我的"),
|
||||
WeiboHotCategory("hot", "热搜"),
|
||||
WeiboHotCategory("ent", "文娱"),
|
||||
WeiboHotCategory("society", "社会"),
|
||||
WeiboHotCategory("sports", "体育"),
|
||||
WeiboHotCategory("acg", "ACG"),
|
||||
WeiboHotCategory("local", "同城"),
|
||||
WeiboHotCategory("tech", "科技"),
|
||||
WeiboHotCategory("life", "生活"),
|
||||
)
|
||||
|
||||
fun byIds(ids: Collection<String>): List<WeiboHotCategory> = ALL.filter { it.id in ids }
|
||||
}
|
||||
|
||||
/**
|
||||
* 单条微博博文观察结果(2026-11-14 e1 取证形态)。
|
||||
* 发布时间唯一合法来源是博文详情的时间文本(实测 `26-11-14 17:43` 两位年份形态);
|
||||
* 缺失或解析不出保留 null,不用“4小时前”类相对时间之外的页面位置回填。
|
||||
*/
|
||||
data class WeiboPostObservation(
|
||||
val category: WeiboHotCategory? = null,
|
||||
val hotEntry: WeiboHotEntry? = null,
|
||||
val author: String? = null,
|
||||
val content: String? = null,
|
||||
val publishedAtText: String? = null,
|
||||
val publishedAtMs: Long? = null,
|
||||
val repostCount: Long? = null,
|
||||
val commentCount: Long? = null,
|
||||
val likeCount: Long? = null,
|
||||
val sourceUrl: String? = null,
|
||||
val fetchedAtMs: Long = 0,
|
||||
val runGeneration: Long = 0,
|
||||
val unknowns: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* 博文详情解析结果。
|
||||
* [publishedAtText] 只认已核验时间形态(`26-11-14 17:43` 两位年份等);
|
||||
* 作者/正文/互动数的节点结构尚未 dump 核验(e1 仅截图),在核验前保留 null 并记录原因——不猜测布局。
|
||||
*/
|
||||
data class WeiboPostDetail(
|
||||
val author: String? = null,
|
||||
val content: String? = null,
|
||||
val publishedAtText: String? = null,
|
||||
val publishedAtMs: Long? = null,
|
||||
val repostCount: Long? = null,
|
||||
val commentCount: Long? = null,
|
||||
val likeCount: Long? = null,
|
||||
val unknownReason: String = "",
|
||||
)
|
||||
|
||||
/** 分享链接解析结果。accepted=false 时 [reason] 说明拒绝原因。 */
|
||||
data class WeiboShareLinkResult(
|
||||
val accepted: Boolean,
|
||||
val userId: String? = null,
|
||||
val postId: String? = null,
|
||||
val canonicalUrl: String? = null,
|
||||
val reason: String = "",
|
||||
)
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.haorui.app.crossplatform.source.weibo
|
||||
|
||||
import com.haorui.app.crossplatform.source.SourceNode
|
||||
|
||||
/**
|
||||
* 微博博文详情解析器(2026-11-14 e3 取证:树+OCR 双源)。
|
||||
*
|
||||
* 详情页作者行/正文为**自绘文本**,节点树读不到(e3 dump 实测 text 为空):
|
||||
* 发布时间只能从 OCR 文本行按已核验形态提取(`26-11-14 20:49` 两位年份等,见 [WeiboTimeParser]);
|
||||
* 互动数在节点树中(实测“转发 105/评论 366/赞 2904”文本形态)。
|
||||
* 正文/作者在 OCR 行语义定型前保留 null 并记录原因——不按截图臆造布局,不拼凑无关行。
|
||||
*/
|
||||
object WeiboPostParser {
|
||||
/**
|
||||
* 时间形 token(行内查找):`26-11-14 20:49` 两位年份 / 完整年份 / 相对时间。
|
||||
* OCR 行合并实测存在(作者行整行如“头条新闻 置顶 26-11-14 20:49 头条… 已编辑”),
|
||||
* 故按 token 匹配而非整行;两位年份形在微博页面上特异性高,误配风险由调用方时间窗复核兜底。
|
||||
*/
|
||||
private val TIME_TOKEN = Regex("(?<!\\d)(?:\\d{2}|\\d{4})-\\d{1,2}-\\d{1,2}\\s+\\d{1,2}:\\d{2}(?::\\d{2})?(?!\\d)")
|
||||
private val RELATIVE_TOKEN = Regex("(?<![\\d\\u4e00-\\u9fff])\\d+\\s*(?:分钟|小时|天)前(?![\\d\\u4e00-\\u9fff])|(?<![\\d\\u4e00-\\u9fff])刚刚(?![\\u4e00-\\u9fff])")
|
||||
private val REPOST = Regex("^转发\\s*(\\d+(?:,\\d{3})*)$")
|
||||
private val COMMENT = Regex("^评论\\s*(\\d+(?:,\\d{3})*)$")
|
||||
private val LIKE = Regex("^赞\\s*(\\d+(?:,\\d{3})*)$")
|
||||
|
||||
fun parse(root: SourceNode, ocrLines: List<String>, nowMs: Long): WeiboPostDetail {
|
||||
val treeTexts = root.selfAndDescendants().map { it.text.trim() }.filter { it.isNotEmpty() }
|
||||
val timeText = findTimeToken(ocrLines)
|
||||
return WeiboPostDetail(
|
||||
author = null,
|
||||
content = null,
|
||||
publishedAtText = timeText,
|
||||
publishedAtMs = timeText?.let { WeiboTimeParser.parse(it, nowMs) },
|
||||
repostCount = firstCount(treeTexts, REPOST),
|
||||
commentCount = firstCount(treeTexts, COMMENT),
|
||||
likeCount = firstCount(treeTexts, LIKE),
|
||||
unknownReason = if (timeText == null) {
|
||||
"OCR 文本行中无已核验发布时间形态;作者/正文待 OCR 语义定型,保留未知"
|
||||
} else {
|
||||
"作者/正文待 OCR 语义定型,保留未知"
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/** 按行序找第一个时间形 token:绝对时间优先于相对时间(同一屏内相对时间常见于卡片,绝对时间更可信)。 */
|
||||
private fun findTimeToken(lines: List<String>): String? {
|
||||
lines.forEach { line ->
|
||||
TIME_TOKEN.find(line)?.let { return it.value.trim() }
|
||||
}
|
||||
lines.forEach { line ->
|
||||
RELATIVE_TOKEN.find(line)?.let { return it.value.trim() }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun firstCount(texts: List<String>, pattern: Regex): Long? =
|
||||
texts.firstNotNullOfOrNull { text ->
|
||||
pattern.matchEntire(text)?.groupValues?.get(1)?.replace(",", "")?.toLongOrNull()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.haorui.app.crossplatform.source.weibo
|
||||
|
||||
/**
|
||||
* 微博分享链接解析(2026-11-14 e3 取证:复制链接实测形态)。
|
||||
*
|
||||
* 实测:`https://weibo.com/<用户UID>/<博文ID>`——完整标准域名、**无查询串无追踪参数**,
|
||||
* 路径直接携带稳定身份(如 https://weibo.com/1618051664/5365257549909249)。
|
||||
* 只接受该形态;非微博域名、缺段、带端口/伪装域一律拒绝——“未核验的形态不进入生产配置”。
|
||||
* 查询串若未来版本出现,按追踪参数整体剥离后再验路径。
|
||||
*/
|
||||
object WeiboShareLinkParser {
|
||||
private val POST_URL = Regex("^https?://(?:www\\.|m\\.)?weibo\\.com/(\\d{4,})/(\\d{4,})/?$")
|
||||
|
||||
fun parse(
|
||||
raw: String?,
|
||||
expectedUserId: String? = null,
|
||||
expectedPostId: String? = null,
|
||||
): WeiboShareLinkResult {
|
||||
val text = raw?.trim().orEmpty()
|
||||
if (text.isEmpty()) return WeiboShareLinkResult(false, reason = "链接为空")
|
||||
val pathOnly = text.substringBefore('#').substringBefore('?').trimEnd('/')
|
||||
val match = POST_URL.matchEntire(pathOnly)
|
||||
?: return WeiboShareLinkResult(false, reason = "未核验的微博链接形态或非微博域名")
|
||||
val userId = match.groupValues[1]
|
||||
val postId = match.groupValues[2]
|
||||
if (expectedUserId != null && expectedUserId != userId) {
|
||||
return WeiboShareLinkResult(false, reason = "链接与候选不匹配:期望用户 $expectedUserId,实际 $userId")
|
||||
}
|
||||
if (expectedPostId != null && expectedPostId != postId) {
|
||||
return WeiboShareLinkResult(false, reason = "链接与候选不匹配:期望博文 $expectedPostId,实际 $postId")
|
||||
}
|
||||
return WeiboShareLinkResult(
|
||||
accepted = true,
|
||||
userId = userId,
|
||||
postId = postId,
|
||||
canonicalUrl = "https://weibo.com/$userId/$postId",
|
||||
reason = "可执行",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.haorui.app.crossplatform.source.weibo
|
||||
|
||||
import java.util.Calendar
|
||||
|
||||
/**
|
||||
* 微博页面时间文本解析(保守白名单)。
|
||||
*
|
||||
* 已核验形态(2026-11-14 e1 博文详情实测):`26-11-14 17:43`(**两位年份** + 月日时分);
|
||||
* 卡片级相对时间(“4小时前”“昨天 12:47”)与完整年份形态一并收录。
|
||||
* 识别不了的形态一律返回 null,不猜测。
|
||||
*/
|
||||
object WeiboTimeParser {
|
||||
/** 两位年份形态:26-11-14 17:43(20xx 年)。 */
|
||||
private val SHORT_YEAR_TIME = Regex("^(\\d{2})-(\\d{1,2})-(\\d{1,2})\\s+(\\d{1,2}):(\\d{2})$")
|
||||
private val FULL_TIME = Regex("^(\\d{4})-(\\d{1,2})-(\\d{1,2})\\s+(\\d{1,2}):(\\d{2})(?::(\\d{2}))?$")
|
||||
private val RELATIVE = Regex("^(\\d+)\\s*(分钟|小时|天)前$")
|
||||
|
||||
fun parse(text: String, nowMs: Long): Long? {
|
||||
val trimmed = text.trim()
|
||||
if (trimmed.isEmpty()) return null
|
||||
if (trimmed == "刚刚") return nowMs
|
||||
RELATIVE.matchEntire(trimmed)?.let { match ->
|
||||
val unitMs = when (match.groupValues[2]) {
|
||||
"分钟" -> 60_000L
|
||||
"小时" -> 3_600_000L
|
||||
else -> 86_400_000L
|
||||
}
|
||||
return runCatching {
|
||||
Math.subtractExact(nowMs, Math.multiplyExact(match.groupValues[1].toLong(), unitMs))
|
||||
}.getOrNull()
|
||||
}
|
||||
SHORT_YEAR_TIME.matchEntire(trimmed)?.let { match ->
|
||||
val g = match.groupValues
|
||||
return at(2000 + g[1].toInt(), g[2].toInt(), g[3].toInt(), g[4].toInt(), g[5].toInt(), 0)
|
||||
}
|
||||
FULL_TIME.matchEntire(trimmed)?.let { match ->
|
||||
val g = match.groupValues
|
||||
return at(g[1].toInt(), g[2].toInt(), g[3].toInt(), g[4].toInt(), g[5].toInt(), g[6].toIntOrNull() ?: 0)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun at(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int): Long? {
|
||||
if (month !in 1..12 || day !in 1..31 || hour !in 0..23 || minute !in 0..59 || second !in 0..59) return null
|
||||
return Calendar.getInstance().apply {
|
||||
clear()
|
||||
set(year, month - 1, day, hour, minute, second)
|
||||
}.timeInMillis
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.haorui.app.crossplatform.source.zhihu
|
||||
|
||||
import com.haorui.app.crossplatform.source.SourceNode
|
||||
|
||||
/**
|
||||
* 知乎问题详情页解析器(com.zhihu.android 11.15.0 取证结构)。
|
||||
*
|
||||
* 详情页结构(2026-11-14 真机树纠正):
|
||||
* - 问题头部为无子节点 WebView:节点树不携带问题标题与问题发布时间;
|
||||
* - 回答卡为**无 id 容器** → shortContainerTemplateView(avatar/username,作者行)
|
||||
* 与 answerContentView(tvAnswerExcerpt)、metricView(tvVoteComment)、tvTime 为兄弟节点;
|
||||
* (2026-11-13 报告曾按裸文本顺序把这些字段记为 shortContainerTemplateView 的子节点,
|
||||
* e2e 实测丢字段后纠正——成组锚点取“同时含作者行与正文的最深容器”。)
|
||||
*
|
||||
* 铁律:`tvTime` 是**回答**时间。问题发布时间(publishedAt)在没有经核验来源前保持 null,
|
||||
* 任何情况下不得用回答时间回填——“知乎回答时间不能当问题时间”。
|
||||
*/
|
||||
object ZhihuDetailParser {
|
||||
internal fun res(name: String) = "${ZhihuHotListParser.PACKAGE}:id/$name"
|
||||
|
||||
private val FINGERPRINT_IDS = listOf(
|
||||
"recycler", "shortContainerTemplateView", "username",
|
||||
"tvVoteComment", "tvTime", "tvAllCount", "write_answer",
|
||||
)
|
||||
|
||||
private val COUNT_PATTERNS = mapOf(
|
||||
"agree" to Regex("(\\d+(?:\\.\\d+)?)\\s*(万|亿)?赞同"),
|
||||
"favorite" to Regex("(\\d+(?:\\.\\d+)?)\\s*(万|亿)?收藏"),
|
||||
"comment" to Regex("(\\d+(?:\\.\\d+)?)\\s*(万|亿)?评论"),
|
||||
)
|
||||
|
||||
fun parse(root: SourceNode, nowMs: Long = System.currentTimeMillis()): ZhihuDetailObservation {
|
||||
val answers = root.deepestGroupsContaining(res("shortContainerTemplateView"), res("answerContentView"))
|
||||
.map { parseAnswer(it, nowMs) }
|
||||
return ZhihuDetailObservation(
|
||||
questionTitle = null,
|
||||
questionPublishedAtMs = null,
|
||||
questionPublishedAtUnknownReason =
|
||||
"问题头部为无子节点 WebView,节点树不携带问题标题与发布时间;tvTime 为回答时间,禁止回填",
|
||||
totalAnswerText = root.firstById(res("tvAllCount"))?.text?.trim()?.takeIf { it.isNotEmpty() },
|
||||
answers = answers,
|
||||
hasShareEntry = root.findAll { it.text == "分享" || it.description == "分享" }.isNotEmpty(),
|
||||
hasWriteAnswer = root.firstById(res("write_answer")) != null,
|
||||
pageFingerprint = fingerprint(root),
|
||||
)
|
||||
}
|
||||
|
||||
private fun parseAnswer(group: SourceNode, nowMs: Long): ZhihuAnswerEntry {
|
||||
val timeText = group.firstById(res("tvTime"))?.text?.trim()?.takeIf { it.isNotEmpty() }
|
||||
return ZhihuAnswerEntry(
|
||||
author = group.firstById(res("username"))?.text?.trim()?.takeIf { it.isNotEmpty() },
|
||||
excerpt = group.firstById(res("tvAnswerExcerpt"))?.text?.trim()?.takeIf { it.isNotEmpty() },
|
||||
agreeCount = parseCount(group, "agree"),
|
||||
favoriteCount = parseCount(group, "favorite"),
|
||||
commentCount = parseCount(group, "comment"),
|
||||
answerTimeText = timeText,
|
||||
answerTimeAtMs = timeText?.let { ZhihuTimeParser.parse(it, nowMs) },
|
||||
)
|
||||
}
|
||||
|
||||
/** “195 赞同 · 19 收藏 · 60 评论”按段解析;缺段或读不出的段为 null,不从其他行补。 */
|
||||
private fun parseCount(group: SourceNode, key: String): Long? {
|
||||
val text = group.firstById(res("tvVoteComment"))?.text?.trim().orEmpty()
|
||||
if (text.isEmpty()) return null
|
||||
val match = COUNT_PATTERNS.getValue(key).find(text) ?: return null
|
||||
val base = match.groupValues[1].toDoubleOrNull() ?: return null
|
||||
return when (match.groupValues[2]) {
|
||||
"万" -> base * 10_000
|
||||
"亿" -> base * 100_000_000
|
||||
else -> base
|
||||
}.toLong()
|
||||
}
|
||||
|
||||
private fun fingerprint(root: SourceNode): String =
|
||||
FINGERPRINT_IDS.filter { root.firstById(res(it)) != null }.joinToString("+")
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
package com.haorui.app.crossplatform.source.zhihu
|
||||
|
||||
import android.os.SystemClock
|
||||
import android.view.accessibility.AccessibilityNodeInfo
|
||||
import com.haorui.app.automation.ClipboardBridge
|
||||
import com.haorui.app.automation.HaoRuiAccessibilityService
|
||||
import com.haorui.app.automation.NodeLocator
|
||||
import com.haorui.app.automation.RunLogger
|
||||
import com.haorui.app.crossplatform.source.SourceNode
|
||||
import com.haorui.app.crossplatform.source.SourceNodeAccessibility
|
||||
|
||||
/**
|
||||
* 知乎采集真机驱动([ZhihuHotListCollector.Port] 实现,2026-11-14 e3 取证口径)。
|
||||
*
|
||||
* 每个操作先在节点树核对目标再点击(禁止盲点);等待用有上限轮询。
|
||||
* 锚点依据选择器可用性报告 e2/e3:Tab“热榜”、详情 desc“搜索/分享”、
|
||||
* 分享面板“复制链接”/“问题日志”/`id/shareClose`、问题日志“问题编辑日志”。
|
||||
*
|
||||
* 复制链接读取:先走前台剪贴板快速路径(本机实测受限),
|
||||
* 失败则搜索框粘贴取证(e3 实测可用)——全程留在知乎 App 内,
|
||||
* 不违反“一条候选完成才让出前台、不中途切换 App”。
|
||||
*/
|
||||
internal class ZhihuDevicePort(
|
||||
private val service: HaoRuiAccessibilityService,
|
||||
) : ZhihuHotListCollector.Port {
|
||||
private companion object {
|
||||
const val TAG = "Zhihu-Port"
|
||||
const val ZHIHU_PKG = "com.zhihu.android"
|
||||
const val WAIT_STEP_MS = 400L
|
||||
}
|
||||
|
||||
// ── 基础工具 ─────────────────────────────────────────────
|
||||
|
||||
private fun log(message: String) = RunLogger.i(TAG, message)
|
||||
|
||||
private fun tree(): SourceNode? = service.root()?.let { SourceNodeAccessibility.from(it) }
|
||||
|
||||
/** 有上限轮询等待页面状态;root 瞬时为空不算失败。 */
|
||||
private fun waitTree(timeoutMs: Long, until: (SourceNode) -> Boolean): Boolean {
|
||||
val deadline = SystemClock.elapsedRealtime() + timeoutMs
|
||||
while (SystemClock.elapsedRealtime() < deadline) {
|
||||
val t = tree()
|
||||
if (t != null && until(t)) return true
|
||||
Thread.sleep(WAIT_STEP_MS)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** 按文本/描述定位并点击(带重试窗口);返回是否点击成功。 */
|
||||
private fun tapText(text: String, timeoutMs: Long = 4_000L): Boolean {
|
||||
val deadline = SystemClock.elapsedRealtime() + timeoutMs
|
||||
while (SystemClock.elapsedRealtime() < deadline) {
|
||||
val root = service.root()
|
||||
val node = NodeLocator.byText(root, text) ?: NodeLocator.byDesc(root, text)
|
||||
if (node != null) {
|
||||
try {
|
||||
if (kotlinx.coroutines.runBlocking { service.gestures.tapNode(node) }) return true
|
||||
} finally {
|
||||
runCatching { node.recycle() }
|
||||
}
|
||||
}
|
||||
Thread.sleep(WAIT_STEP_MS)
|
||||
}
|
||||
log("未找到可点击目标「$text」")
|
||||
return false
|
||||
}
|
||||
|
||||
/** 活节点按类名后缀查找(输入框清空等需要 ACTION_SET_TEXT 的场景)。 */
|
||||
private fun liveByClass(root: AccessibilityNodeInfo?, suffix: String): AccessibilityNodeInfo? {
|
||||
if (root == null) return null
|
||||
if (root.className?.toString()?.endsWith(suffix) == true) return root
|
||||
for (i in 0 until root.childCount) {
|
||||
val child = root.getChild(i) ?: continue
|
||||
val found = liveByClass(child, suffix)
|
||||
if (found != null) {
|
||||
if (found !== child) runCatching { child.recycle() }
|
||||
return found
|
||||
}
|
||||
runCatching { child.recycle() }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun findByClass(root: SourceNode, simpleName: String): SourceNode? =
|
||||
root.selfAndDescendants().firstOrNull { it.className.endsWith(simpleName) }
|
||||
|
||||
// ── Port 实现 ────────────────────────────────────────────
|
||||
|
||||
override fun ensureAppForeground(): Boolean {
|
||||
service.launchApp(ZHIHU_PKG)
|
||||
val deadline = SystemClock.elapsedRealtime() + 25_000
|
||||
var sawApp = false
|
||||
while (SystemClock.elapsedRealtime() < deadline) {
|
||||
if (service.currentPackage() == ZHIHU_PKG) {
|
||||
sawApp = true
|
||||
// 开屏广告倒计时会自跳过;“跳过”按钮出现即点(只点跳过,不点广告本体)。
|
||||
val skip = NodeLocator.byTextContains(service.root(), "跳过")
|
||||
if (skip != null) {
|
||||
runCatching {
|
||||
kotlinx.coroutines.runBlocking { service.gestures.tapNode(skip) }
|
||||
}
|
||||
runCatching { skip.recycle() }
|
||||
Thread.sleep(WAIT_STEP_MS)
|
||||
continue
|
||||
}
|
||||
if (tree()?.findAll { it.text == "热榜" }?.isNotEmpty() == true) return true
|
||||
}
|
||||
Thread.sleep(WAIT_STEP_MS)
|
||||
}
|
||||
log("进入前台失败(见到 App=$sawApp);页面采样=${tree()?.selfAndDescendants()?.map { it.text }?.filter { it.isNotBlank() }?.take(6)}")
|
||||
return false
|
||||
}
|
||||
|
||||
override fun openHotList(): Boolean {
|
||||
// 已在热榜(解析器读得出卡片)则不点 Tab:重复点会触发刷新反而延长加载
|
||||
if (waitTree(1_500) { t -> ZhihuHotListParser.parse(t).isNotEmpty() }) return true
|
||||
if (!tapText("热榜")) return false
|
||||
val ready = waitTree(12_000) { t -> ZhihuHotListParser.parse(t).isNotEmpty() }
|
||||
if (!ready) {
|
||||
val t = tree()
|
||||
val nodes = t?.selfAndDescendants().orEmpty()
|
||||
log(
|
||||
"热榜未就绪:trend_layout=${nodes.count { n -> n.id.endsWith(":id/trend_layout") }} " +
|
||||
"title=${nodes.count { n -> n.id.endsWith(":id/title") }} " +
|
||||
"采样=${nodes.map { it.text }.filter { it.isNotBlank() }.take(8)}",
|
||||
)
|
||||
}
|
||||
return ready
|
||||
}
|
||||
|
||||
override fun readListTree(): SourceNode = tree() ?: SourceNode()
|
||||
|
||||
override fun openCard(index: Int): Boolean {
|
||||
val entries = ZhihuHotListParser.parse(readListTree())
|
||||
val title = entries.getOrNull(index)?.title ?: return false
|
||||
// 按完整标题定位卡片标题节点:与解析结果绑定,跳过无标题卡不串位
|
||||
val deadline = SystemClock.elapsedRealtime() + 4_000
|
||||
var tapped = false
|
||||
while (!tapped && SystemClock.elapsedRealtime() < deadline) {
|
||||
val node = NodeLocator.byText(service.root(), title)
|
||||
if (node != null) {
|
||||
try {
|
||||
tapped = kotlinx.coroutines.runBlocking { service.gestures.tapNode(node) }
|
||||
} finally {
|
||||
runCatching { node.recycle() }
|
||||
}
|
||||
}
|
||||
if (!tapped) Thread.sleep(WAIT_STEP_MS)
|
||||
}
|
||||
if (!tapped) return false
|
||||
return waitTree(6_000) { t ->
|
||||
t.findAll { it.text == "邀请回答" || it.text == "关注问题" || it.text == "写回答" }.isNotEmpty()
|
||||
}
|
||||
}
|
||||
|
||||
override fun readDetailTree(): SourceNode = tree() ?: SourceNode()
|
||||
|
||||
override fun openShareMenu(): Boolean {
|
||||
// 详情页右上 ⋮ 的 content-desc 为“分享”(e2 取证);面板标题“分享问题”为就绪标志
|
||||
if (!tapText("分享")) return false
|
||||
return waitTree(5_000) { t -> t.findAll { it.text == "分享问题" }.isNotEmpty() }
|
||||
}
|
||||
|
||||
override fun copyShareLink(): String? {
|
||||
if (!tapText("复制链接")) return null
|
||||
Thread.sleep(800) // 等 toast 与剪贴板写入(面板会自动关闭)
|
||||
// 快速路径:剪贴板读取(本机受限,保留兼容其他设备)
|
||||
val quick = runCatching {
|
||||
ClipboardBridge.readFromClipboard(service) { log("剪贴板诊断: $it") }
|
||||
}.getOrNull()
|
||||
if (!quick.isNullOrBlank() && quick.contains("zhihu.")) return quick.trim()
|
||||
log("剪贴板不可读,走搜索框粘贴取证")
|
||||
return readLinkViaSearchBox()
|
||||
}
|
||||
|
||||
/**
|
||||
* 本机兜底:知乎搜索框 ACTION_PASTE → 读输入框文本 → 清空 → 返回详情。
|
||||
* e3 实测路径(当时用长按菜单粘贴);此处直接对输入框派发系统粘贴动作,
|
||||
* 不依赖长按菜单的文字匹配。全程留在知乎 App 内,不违反前台独占约束。
|
||||
*/
|
||||
private fun readLinkViaSearchBox(): String? {
|
||||
if (!tapText("搜索")) return null
|
||||
if (!waitTree(5_000) { t -> findByClass(t, "EditText") != null }) return null
|
||||
val pasted = run {
|
||||
val liveInput = liveByClass(service.root(), "EditText") ?: return@run false
|
||||
try {
|
||||
runCatching { liveInput.performAction(AccessibilityNodeInfo.ACTION_PASTE) }.getOrDefault(false)
|
||||
} finally {
|
||||
runCatching { liveInput.recycle() }
|
||||
}
|
||||
}
|
||||
if (!pasted) {
|
||||
log("搜索框 ACTION_PASTE 未被接受")
|
||||
return null
|
||||
}
|
||||
Thread.sleep(500)
|
||||
val link = tree()?.let { findByClass(it, "EditText") }?.text?.trim().orEmpty()
|
||||
// 清空输入框,不留痕
|
||||
val clearInput = liveByClass(service.root(), "EditText")
|
||||
if (clearInput != null) {
|
||||
try {
|
||||
kotlinx.coroutines.runBlocking { service.gestures.setText(clearInput, "") }
|
||||
} finally {
|
||||
runCatching { clearInput.recycle() }
|
||||
}
|
||||
}
|
||||
service.gestures.back() // 离开搜索页回详情(验证回到详情,最多再补一次返回)
|
||||
if (!waitTree(4_000) { t -> t.findAll { it.text == "邀请回答" || it.text == "关注问题" || it.text == "写回答" }.isNotEmpty() }) {
|
||||
service.gestures.back()
|
||||
waitTree(4_000) { t -> t.findAll { it.text == "邀请回答" || it.text == "关注问题" || it.text == "写回答" }.isNotEmpty() }
|
||||
}
|
||||
return link.takeIf { it.contains("zhihu.") }
|
||||
}
|
||||
|
||||
override fun openQuestionLog(): Boolean {
|
||||
// 复制链接后面板已自动关闭;且可能刚从搜索页返回——先校准到详情页再开面板
|
||||
if (waitTree(1_500) { t -> t.findAll { it.text == "分享问题" }.isNotEmpty() }) {
|
||||
// 面板恰好开着,直接走下面的入口定位
|
||||
} else {
|
||||
if (!waitTree(1_500) { t -> t.findAll { it.text == "邀请回答" || it.text == "关注问题" }.isNotEmpty() }) {
|
||||
service.gestures.back()
|
||||
waitTree(3_000) { t -> t.findAll { it.text == "邀请回答" || it.text == "关注问题" }.isNotEmpty() }
|
||||
}
|
||||
if (!openShareMenu()) return false
|
||||
}
|
||||
if (!tapText("问题日志")) return false
|
||||
return waitTree(6_000) { t -> t.findAll { it.text.contains("问题编辑日志") || it.text.contains("添加了问题") }.isNotEmpty() }
|
||||
}
|
||||
|
||||
override fun readQuestionLogTree(): SourceNode = tree() ?: SourceNode()
|
||||
|
||||
override fun leaveQuestionLog(): Boolean {
|
||||
if (!service.gestures.back()) return false
|
||||
return waitTree(5_000) { t ->
|
||||
t.findAll { it.text == "邀请回答" || it.text == "关注问题" || it.text == "写回答" }.isNotEmpty()
|
||||
}
|
||||
}
|
||||
|
||||
override fun leaveShareMenu(): Boolean {
|
||||
// 面板可能已自动关闭:关闭键不在即视为已离开
|
||||
if (waitTree(1_500) { t -> t.findAll { it.text == "分享问题" }.isEmpty() }) return true
|
||||
val root = service.root()
|
||||
val close = NodeLocator.byId(root, "$ZHIHU_PKG:id/shareClose")
|
||||
if (close != null) {
|
||||
try {
|
||||
if (kotlinx.coroutines.runBlocking { service.gestures.tapNode(close) }) {
|
||||
return waitTree(3_000) { t -> t.findAll { it.text == "分享问题" }.isEmpty() }
|
||||
}
|
||||
} finally {
|
||||
runCatching { close.recycle() }
|
||||
}
|
||||
}
|
||||
service.gestures.back()
|
||||
return waitTree(3_000) { t -> t.findAll { it.text == "分享问题" }.isEmpty() }
|
||||
}
|
||||
|
||||
override fun backToFeed(): Boolean {
|
||||
// 最多三次返回:详情 → 热榜
|
||||
repeat(3) {
|
||||
if (waitTree(1_500) { t ->
|
||||
t.findAll { it.id.endsWith(":id/trend_layout") }.isNotEmpty() &&
|
||||
t.findAll { it.text == "邀请回答" }.isEmpty()
|
||||
}
|
||||
) return true
|
||||
service.gestures.back()
|
||||
}
|
||||
return waitTree(3_000) { t -> t.findAll { it.id.endsWith(":id/trend_layout") }.isNotEmpty() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package com.haorui.app.crossplatform.source.zhihu
|
||||
|
||||
import com.haorui.app.crossplatform.source.SourceNode
|
||||
|
||||
/**
|
||||
* 知乎单候选采集状态机(骨架)。
|
||||
*
|
||||
* 设计稿状态:OPEN_APP -> OPEN_FEED -> READ_LIST -> OPEN_DETAIL
|
||||
* -> READ_DETAIL -> COPY_SOURCE_LINK -> READ_QUESTION_LOG -> SAVE_OBSERVATION -> EXIT
|
||||
*
|
||||
* 约束(跨平台自动发布设计):
|
||||
* - 一条候选完成才让出前台,不在分享面板或正文编辑中途切换 App;
|
||||
* - 任何失败都走 EXIT 安全退出,回到已知可恢复页面;
|
||||
* - 缺失字段保留未知(进 unknowns),不从标题/回答时间/旧剪贴板推断;
|
||||
* - 分享链接必须与当前候选配对(已知 question id 时校验),不匹配即拒绝该候选。
|
||||
*
|
||||
* 真机驱动通过 [Port] 接入(无障碍节点读取、点击、返回);
|
||||
* 未完成真机适配前不注册任何能力,采集入口由 SourceRegistry 门控拦截。
|
||||
*/
|
||||
class ZhihuHotListCollector(
|
||||
private val port: Port,
|
||||
private val nowMs: () -> Long = System::currentTimeMillis,
|
||||
) {
|
||||
/** 真机驱动接口:每个方法都是一次页面操作,实现方负责可见性核对,禁止盲点。 */
|
||||
interface Port {
|
||||
fun ensureAppForeground(): Boolean
|
||||
fun openHotList(): Boolean
|
||||
fun readListTree(): SourceNode
|
||||
fun openCard(index: Int): Boolean
|
||||
fun readDetailTree(): SourceNode
|
||||
fun openShareMenu(): Boolean
|
||||
fun copyShareLink(): String?
|
||||
/** 从分享面板打开问题日志页(2026-11-14 取证:面板底行左一)。 */
|
||||
fun openQuestionLog(): Boolean
|
||||
fun readQuestionLogTree(): SourceNode
|
||||
/** 从问题日志页返回详情/可恢复页面;失败不阻断 EXIT 收尾。 */
|
||||
fun leaveQuestionLog(): Boolean
|
||||
fun leaveShareMenu(): Boolean
|
||||
fun backToFeed(): Boolean
|
||||
}
|
||||
|
||||
enum class Phase {
|
||||
OPEN_APP, OPEN_FEED, READ_LIST, OPEN_DETAIL,
|
||||
READ_DETAIL, COPY_SOURCE_LINK, READ_QUESTION_LOG, SAVE_OBSERVATION, EXIT, DONE, FAILED,
|
||||
}
|
||||
|
||||
/** 单候选采集结果;失败相位即 [phase],观察到的未知字段进 [unknowns]。 */
|
||||
data class Result(
|
||||
val outcome: String,
|
||||
val phase: Phase,
|
||||
val observation: ZhihuCandidateObservation? = null,
|
||||
val reason: String = "",
|
||||
val exitedSafely: Boolean = false,
|
||||
)
|
||||
|
||||
/** 运行代际:停止/重启后递增,迟到的观察不得混入新代际。 */
|
||||
var runGeneration: Long = 0
|
||||
|
||||
var phase: Phase = Phase.OPEN_APP
|
||||
private set
|
||||
|
||||
/**
|
||||
* 采集第 [cardIndex] 张热榜卡片(下标来自 READ_LIST 的解析结果)。
|
||||
* [expectedQuestionId]:该候选此前已知的问题 id(首见观察/去重表),已知则校验分享链接配对。
|
||||
* 全程独占前台;无论成败最后都执行 EXIT。
|
||||
*/
|
||||
fun collectOne(cardIndex: Int, expectedQuestionId: String? = null): Result {
|
||||
var observation: ZhihuCandidateObservation? = null
|
||||
var failure: String? = null
|
||||
var failedAt: Phase? = null
|
||||
var exitedSafely = false
|
||||
try {
|
||||
phase = Phase.OPEN_APP
|
||||
if (!port.ensureAppForeground()) fail("来源 App 未能进入前台")
|
||||
|
||||
phase = Phase.OPEN_FEED
|
||||
if (!port.openHotList()) fail("热榜入口未打开")
|
||||
|
||||
phase = Phase.READ_LIST
|
||||
val entries = ZhihuHotListParser.parse(port.readListTree())
|
||||
val entry = entries.getOrNull(cardIndex) ?: fail("热榜第 $cardIndex 张卡片不存在或缺标题")
|
||||
|
||||
phase = Phase.OPEN_DETAIL
|
||||
if (!port.openCard(cardIndex)) fail("未能打开第 $cardIndex 张卡片详情")
|
||||
|
||||
phase = Phase.READ_DETAIL
|
||||
val detail = ZhihuDetailParser.parse(port.readDetailTree(), nowMs())
|
||||
|
||||
phase = Phase.COPY_SOURCE_LINK
|
||||
if (!port.openShareMenu()) fail("分享菜单未打开")
|
||||
val linkText = port.copyShareLink() ?: fail("复制链接未取得")
|
||||
val link = ZhihuShareLinkParser.parse(linkText, expectedQuestionId = expectedQuestionId)
|
||||
if (!link.accepted) fail("分享链接未通过核验:${link.reason}")
|
||||
|
||||
// 问题日志:真实发布时间的唯一合法来源(2026-11-14 取证)。
|
||||
// 打不开/读不到不作失败——发布时间保留未知进 unknowns,由筛选阶段按“仍不明则跳过”处置。
|
||||
phase = Phase.READ_QUESTION_LOG
|
||||
val questionLog: ZhihuQuestionLogObservation? = try {
|
||||
if (port.openQuestionLog()) ZhihuQuestionLogParser.parse(port.readQuestionLogTree(), nowMs()) else null
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
} finally {
|
||||
runCatching { port.leaveQuestionLog() }
|
||||
}
|
||||
|
||||
phase = Phase.SAVE_OBSERVATION
|
||||
observation = ZhihuCandidateObservation(
|
||||
hotEntry = entry,
|
||||
detail = detail,
|
||||
shareLink = link,
|
||||
questionId = link.questionId,
|
||||
sourceUrl = link.canonicalUrl,
|
||||
publishedAtMs = questionLog?.questionCreatedAtMs,
|
||||
questionLog = questionLog,
|
||||
fetchedAtMs = nowMs(),
|
||||
runGeneration = runGeneration,
|
||||
pageFingerprint = detail.pageFingerprint,
|
||||
unknowns = buildUnknowns(entry, detail, questionLog),
|
||||
)
|
||||
} catch (stop: StopRequest) {
|
||||
failure = stop.message
|
||||
failedAt = phase
|
||||
} finally {
|
||||
phase = Phase.EXIT
|
||||
// 收尾两步各自尽力:分享面板关不掉也要继续回到已知可恢复页面。
|
||||
val leftShare = runCatching { port.leaveShareMenu() }.getOrDefault(false)
|
||||
val backedToFeed = runCatching { port.backToFeed() }.getOrDefault(false)
|
||||
exitedSafely = leftShare && backedToFeed
|
||||
}
|
||||
return Result(
|
||||
outcome = if (observation != null) "已观察" else "失败",
|
||||
phase = failedAt ?: Phase.DONE,
|
||||
observation = observation,
|
||||
reason = failure.orEmpty(),
|
||||
exitedSafely = exitedSafely,
|
||||
)
|
||||
}
|
||||
|
||||
private class StopRequest(message: String) : RuntimeException(message)
|
||||
|
||||
private fun fail(reason: String): Nothing = throw StopRequest(reason)
|
||||
|
||||
/** 未知口径清单:把“没读到什么”显式记录,供筛选阶段按“缺值不伪造”处置。 */
|
||||
private fun buildUnknowns(
|
||||
entry: ZhihuHotEntry,
|
||||
detail: ZhihuDetailObservation,
|
||||
questionLog: ZhihuQuestionLogObservation?,
|
||||
): List<String> {
|
||||
val unknowns = mutableListOf<String>()
|
||||
if (entry.rank == null) unknowns += "排名未知(前三名为图片或缺排名节点)"
|
||||
if (entry.heatValue == null) unknowns += "热度数值未知(原文=${entry.heatRaw ?: "缺失"})"
|
||||
if (questionLog?.questionCreatedAtMs == null) {
|
||||
unknowns += "问题发布时间未知:${questionLog?.unknownReason ?: "问题日志页未打开"};${detail.questionPublishedAtUnknownReason}"
|
||||
}
|
||||
if (detail.questionTitle == null) unknowns += "问题标题未从节点树取得(WebView 无子节点,待 OCR 补全)"
|
||||
return unknowns
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.haorui.app.crossplatform.source.zhihu
|
||||
|
||||
import com.haorui.app.crossplatform.source.SourceNode
|
||||
|
||||
/**
|
||||
* 知乎热榜页解析器(com.zhihu.android 11.15.0 取证结构)。
|
||||
*
|
||||
* 真实卡片结构(2026-11-14 真机树纠正):
|
||||
* 卡片容器 → trend_layout(position_container → ranking_no | ranking_no_img) + title_layout(title + metrics_text)
|
||||
* **排名徽标 trend_layout 与 title_layout 是兄弟节点**,不是父子;
|
||||
* (2026-11-13 报告曾按裸文本顺序误记为 trend_layout → title_layout,e2e 实测解析 0 卡后纠正。)
|
||||
*
|
||||
* 关键口径:
|
||||
* - `id/title` 被顶部 Tab(关注/推荐/热榜/故事)与卡片标题共用,标题只取 title_layout 内的;
|
||||
* - 排名前三是图片(ranking_no_img,无文本),只认 ranking_no 文本,缺失保留未知;
|
||||
* - 热度原文/数值/口径词分开保存,解析不出数值不伪造;
|
||||
* - 成组锚点是“同时含 trend_layout 与 title_layout 的最深容器”,广告行等缺徽标/缺标题行不入组。
|
||||
*/
|
||||
object ZhihuHotListParser {
|
||||
const val PACKAGE = "com.zhihu.android"
|
||||
|
||||
internal fun res(name: String) = "$PACKAGE:id/$name"
|
||||
|
||||
private val HEAT_PATTERN = Regex("^(\\d+(?:\\.\\d+)?)\\s*(万|亿)?热度$")
|
||||
|
||||
fun parse(root: SourceNode): List<ZhihuHotEntry> =
|
||||
root.deepestGroupsContaining(res("trend_layout"), res("title_layout")).mapNotNull(::parseCard)
|
||||
|
||||
private fun parseCard(card: SourceNode): ZhihuHotEntry? {
|
||||
val titleLayout = card.firstById(res("title_layout")) ?: return null
|
||||
val title = titleLayout.firstById(res("title"))?.text?.trim().orEmpty()
|
||||
if (title.isEmpty()) return null // 缺标题的卡片不是候选:跳过,不伪造身份
|
||||
val heatRaw = titleLayout.firstById(res("metrics_text"))?.text?.trim()?.takeIf { it.isNotEmpty() }
|
||||
val rank = card.firstById(res("ranking_no"))?.text?.trim()?.toIntOrNull()?.takeIf { it in 1..999 }
|
||||
val heat = parseHeat(heatRaw)
|
||||
return ZhihuHotEntry(
|
||||
title = title,
|
||||
heatRaw = heatRaw,
|
||||
heatValue = heat.first,
|
||||
heatMetric = heat.second,
|
||||
rank = rank,
|
||||
)
|
||||
}
|
||||
|
||||
/** “1044 万热度”→(10_440_000, “热度”);数值/单位异常时保留原文,数值与口径为 null。 */
|
||||
internal fun parseHeat(raw: String?): Pair<Long?, String?> {
|
||||
if (raw.isNullOrBlank()) return null to null
|
||||
val match = HEAT_PATTERN.matchEntire(raw.trim()) ?: return null to null
|
||||
val (number, unit) = match.destructured
|
||||
val base = number.toDoubleOrNull() ?: return null to null
|
||||
val value = when (unit) {
|
||||
"万" -> base * 10_000
|
||||
"亿" -> base * 100_000_000
|
||||
else -> base
|
||||
}
|
||||
return value.toLong() to "热度"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.haorui.app.crossplatform.source.zhihu
|
||||
|
||||
/**
|
||||
* 知乎采集解析结果模型。
|
||||
*
|
||||
* 口径约束(缺值不伪造):解析不到的字段一律保留 null,
|
||||
* 不从标题、评论、回答时间或其他无关位置推断补齐。
|
||||
*/
|
||||
|
||||
/** 热榜条目。热度三口径分开保存:原文、归一数值、口径词。 */
|
||||
data class ZhihuHotEntry(
|
||||
val title: String,
|
||||
val heatRaw: String? = null,
|
||||
val heatValue: Long? = null,
|
||||
val heatMetric: String? = null,
|
||||
/** 排名;前三名以图片呈现不可读时保留 null(未知),不按列表顺序推断。 */
|
||||
val rank: Int? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* 回答条目。
|
||||
* [answerTimeText]/[answerTimeAtMs] 是**回答**时间(tvTime),
|
||||
* 任何调用方不得把它写入问题发布时间字段——见 [ZhihuDetailObservation.questionPublishedAtMs]。
|
||||
*/
|
||||
data class ZhihuAnswerEntry(
|
||||
val author: String? = null,
|
||||
val excerpt: String? = null,
|
||||
val agreeCount: Long? = null,
|
||||
val favoriteCount: Long? = null,
|
||||
val commentCount: Long? = null,
|
||||
val answerTimeText: String? = null,
|
||||
val answerTimeAtMs: Long? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* 问题详情观察结果。
|
||||
* 知乎 11.15.0 问题头部为无子节点 WebView:问题标题与问题发布时间在节点树中不可读,
|
||||
* 显式保留 null 并记录原因,等待经核验的补全来源(控件区域 OCR、分享链等)后再填。
|
||||
*/
|
||||
data class ZhihuDetailObservation(
|
||||
val questionTitle: String? = null,
|
||||
val questionPublishedAtMs: Long? = null,
|
||||
val questionPublishedAtUnknownReason: String = "",
|
||||
val totalAnswerText: String? = null,
|
||||
val answers: List<ZhihuAnswerEntry> = emptyList(),
|
||||
val hasShareEntry: Boolean = false,
|
||||
val hasWriteAnswer: Boolean = false,
|
||||
/** 页面指纹:关键结构节点组合,用于防切页/串素材;不是内容哈希。 */
|
||||
val pageFingerprint: String = "",
|
||||
)
|
||||
|
||||
/** 分享链接解析结果。accepted=false 时 [reason] 说明拒绝原因。 */
|
||||
data class ZhihuShareLinkResult(
|
||||
val accepted: Boolean,
|
||||
val questionId: String? = null,
|
||||
val answerId: String? = null,
|
||||
val canonicalUrl: String? = null,
|
||||
val reason: String = "",
|
||||
)
|
||||
|
||||
/** 问题日志条目(2026-11-14 e3 取证形态:`logitem-<记录ID>` 容器内含操作、#记录ID 文本与时间戳,顺序不固定)。 */
|
||||
data class ZhihuQuestionLogEntry(
|
||||
val recordId: String? = null,
|
||||
val action: String? = null,
|
||||
val timeText: String? = null,
|
||||
val timeAtMs: Long? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* 问题日志观察结果。
|
||||
* 问题真实发布时间的唯一合法来源是「添加了问题」条目时间(2026-11-14 真机核验);
|
||||
* 缺失、重复或读不出时保留 null 并给原因,不用编辑时间、“最近活动”或回答时间回填。
|
||||
*/
|
||||
data class ZhihuQuestionLogObservation(
|
||||
val questionCreatedAtMs: Long? = null,
|
||||
val questionCreatedTimeText: String? = null,
|
||||
val entries: List<ZhihuQuestionLogEntry> = emptyList(),
|
||||
val unknownReason: String = "",
|
||||
val pageFingerprint: String = "",
|
||||
)
|
||||
|
||||
/**
|
||||
* 单候选观察结果(热榜卡片 + 详情 + 原链接)。
|
||||
* [unknowns] 显式列出未取得字段;筛选阶段按“缺值不伪造”处置,不得用首见时间顶替发布时间。
|
||||
*/
|
||||
data class ZhihuCandidateObservation(
|
||||
val hotEntry: ZhihuHotEntry,
|
||||
val detail: ZhihuDetailObservation,
|
||||
val shareLink: ZhihuShareLinkResult,
|
||||
val questionId: String?,
|
||||
val sourceUrl: String?,
|
||||
/** 问题真实发布时间;唯一合法来源是 [questionLog] 的「添加了问题」条目,回答/编辑/首见时间不得回填。 */
|
||||
val publishedAtMs: Long? = null,
|
||||
val questionLog: ZhihuQuestionLogObservation? = null,
|
||||
val fetchedAtMs: Long,
|
||||
val runGeneration: Long,
|
||||
val pageFingerprint: String,
|
||||
val unknowns: List<String> = emptyList(),
|
||||
)
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.haorui.app.crossplatform.source.zhihu
|
||||
|
||||
import com.haorui.app.crossplatform.source.SourceNode
|
||||
|
||||
/**
|
||||
* 知乎问题日志页解析器(com.zhihu.android 11.15.0,2026-11-14 e3 真机取证)。
|
||||
*
|
||||
* 页面为 WebView 渲染,绝大多数节点无 resource-id,但每个日志条目有结构性锚点
|
||||
* `logitem-<记录ID>`(撤销按钮为 `revert-<记录ID>`)。条目子树内含操作文本、
|
||||
* `#记录ID` 文本与时间戳,顺序不固定(实测两种顺序都出现过)。
|
||||
*
|
||||
* 问题真实发布时间 = 操作为「添加了问题」的条目时间(e3 取证核验);
|
||||
* 时间戳只接受实测形态 `YYYY-MM-DD HH:MM:SS`。缺失、重复或读不出时保留 null 并给原因,
|
||||
* 不用编辑时间、“最近活动于 09:58” 或回答时间回填。
|
||||
*/
|
||||
object ZhihuQuestionLogParser {
|
||||
private val LOG_ITEM_ID = Regex("logitem-(\\d+)")
|
||||
/** 实测时间形态(问题日志各条目统一为完整日期时间)。 */
|
||||
private val TIME_SHAPE = Regex("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$")
|
||||
private val ACTIONS = listOf(
|
||||
"添加了问题", "编辑了补充说明", "编辑了问题",
|
||||
"添加了话题", "移除了话题", "锁定问题编辑", "取消锁定问题编辑", "撤销",
|
||||
)
|
||||
|
||||
fun parse(root: SourceNode, nowMs: Long = System.currentTimeMillis()): ZhihuQuestionLogObservation {
|
||||
val items = root.selfAndDescendants().filter { LOG_ITEM_ID.matches(it.id) }
|
||||
if (items.isEmpty()) {
|
||||
return ZhihuQuestionLogObservation(
|
||||
unknownReason = "页面无 logitem 条目锚点,未核验结构,发布时间保留未知",
|
||||
pageFingerprint = fingerprint(root),
|
||||
)
|
||||
}
|
||||
val entries = items.map { item ->
|
||||
val texts = item.selfAndDescendants().map { it.text.trim() }.filter { it.isNotEmpty() }
|
||||
val timeText = texts.firstOrNull { TIME_SHAPE.matches(it) }
|
||||
ZhihuQuestionLogEntry(
|
||||
recordId = LOG_ITEM_ID.matchEntire(item.id)?.groupValues?.get(1),
|
||||
action = texts.firstOrNull { text -> ACTIONS.any { text == it } },
|
||||
timeText = timeText,
|
||||
timeAtMs = timeText?.let { ZhihuTimeParser.parse(it, nowMs) },
|
||||
)
|
||||
}
|
||||
val creations = entries.filter { it.action == "添加了问题" }
|
||||
val created = creations.singleOrNull()
|
||||
return ZhihuQuestionLogObservation(
|
||||
questionCreatedAtMs = created?.timeAtMs,
|
||||
questionCreatedTimeText = created?.timeText,
|
||||
entries = entries,
|
||||
unknownReason = when {
|
||||
creations.isEmpty() -> "未找到「添加了问题」条目,发布时间保留未知"
|
||||
creations.size > 1 -> "「添加了问题」条目不唯一,发布时间保留未知"
|
||||
created?.timeAtMs == null -> "「添加了问题」条目缺少实测形态时间戳,发布时间保留未知"
|
||||
else -> ""
|
||||
},
|
||||
pageFingerprint = fingerprint(root),
|
||||
)
|
||||
}
|
||||
|
||||
/** 页面指纹:条目锚点数量 + 页脚标识,防切页/串页面;不是内容哈希。 */
|
||||
private fun fingerprint(root: SourceNode): String {
|
||||
val items = root.selfAndDescendants().count { LOG_ITEM_ID.matches(it.id) }
|
||||
val footer = root.findAll { it.text.trim() == "查看问题日志" }.isNotEmpty()
|
||||
return "logitems=$items;footer=$footer"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.haorui.app.crossplatform.source.zhihu
|
||||
|
||||
/**
|
||||
* 知乎分享链接解析与配对校验。
|
||||
*
|
||||
* 2026-11-13 取证未核验到分享面板实物(留存 dump 为桌面页),当前只接受已知 Web 形态:
|
||||
* https?://(www.)?zhihu.com/question/<id>[/answer/<id>]
|
||||
* 路径携带稳定身份(question/answer id),查询串按追踪类参数整体剥离(日志隐藏令牌)。
|
||||
* 未核验形态、非知乎域名、带端口/伪装域名一律拒绝并给原因——“未经验证的形态不进入生产配置”。
|
||||
*/
|
||||
object ZhihuShareLinkParser {
|
||||
private val QUESTION_URL = Regex("^https?://(?:www\\.)?zhihu\\.com/question/(\\d{4,})(?:/answer/(\\d{4,}))?/?$")
|
||||
|
||||
fun parse(
|
||||
raw: String?,
|
||||
expectedQuestionId: String? = null,
|
||||
expectedAnswerId: String? = null,
|
||||
): ZhihuShareLinkResult {
|
||||
val text = raw?.trim().orEmpty()
|
||||
if (text.isEmpty()) return ZhihuShareLinkResult(false, reason = "链接为空")
|
||||
// 剥离 #fragment 与 ?query(分享追踪类参数),路径中的 question/answer id 才是稳定身份。
|
||||
val pathOnly = text.substringBefore('#').substringBefore('?').trimEnd('/')
|
||||
val match = QUESTION_URL.matchEntire(pathOnly)
|
||||
?: return ZhihuShareLinkResult(false, reason = "未核验的知乎链接形态或非知乎域名")
|
||||
val questionId = match.groupValues[1]
|
||||
val answerId = match.groupValues[2].takeIf { it.isNotEmpty() }
|
||||
if (expectedQuestionId != null && expectedQuestionId != questionId) {
|
||||
return ZhihuShareLinkResult(false, questionId = questionId, answerId = answerId,
|
||||
reason = "链接与候选不匹配:期望问题 $expectedQuestionId,实际 $questionId")
|
||||
}
|
||||
if (expectedAnswerId != null && expectedAnswerId != answerId) {
|
||||
return ZhihuShareLinkResult(false, questionId = questionId, answerId = answerId,
|
||||
reason = "链接与候选不匹配:期望回答 $expectedAnswerId,实际 ${answerId ?: "无"}")
|
||||
}
|
||||
return ZhihuShareLinkResult(
|
||||
accepted = true,
|
||||
questionId = questionId,
|
||||
answerId = answerId,
|
||||
canonicalUrl = "https://www.zhihu.com/question/$questionId" + (answerId?.let { "/answer/$it" } ?: ""),
|
||||
reason = "可执行",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.haorui.app.crossplatform.source.zhihu
|
||||
|
||||
import java.util.Calendar
|
||||
|
||||
/**
|
||||
* 知乎页面时间文本解析(保守白名单)。
|
||||
*
|
||||
* 仅用于**回答时间**(tvTime)等条目级时间;问题发布时间必须来自经核验的来源,
|
||||
* 不在本解析器职责内。识别不了的形态一律返回 null,不猜测。
|
||||
*/
|
||||
object ZhihuTimeParser {
|
||||
private val MINUTES_AGO = Regex("^(\\d+)\\s*分钟前$")
|
||||
private val HOURS_AGO = Regex("^(\\d+)\\s*小时前$")
|
||||
private val DAYS_AGO = Regex("^(\\d+)\\s*天前$")
|
||||
private val DAY_TIME = Regex("^(今天|昨天|前天)\\s+(\\d{1,2}):(\\d{2})$")
|
||||
private val FULL_TIME = Regex("^(\\d{4})-(\\d{1,2})-(\\d{1,2})(?:\\s+(\\d{1,2}):(\\d{2})(?::(\\d{2}))?)?$")
|
||||
private val MONTH_DAY = Regex("^(\\d{1,2})-(\\d{1,2})(?:\\s+(\\d{1,2}):(\\d{2}))?$")
|
||||
|
||||
fun parse(text: String, nowMs: Long): Long? {
|
||||
val trimmed = text.trim()
|
||||
if (trimmed.isEmpty()) return null
|
||||
MINUTES_AGO.matchEntire(trimmed)?.let { return nowMs - it.groupValues[1].toLong() * 60_000L }
|
||||
HOURS_AGO.matchEntire(trimmed)?.let { return nowMs - it.groupValues[1].toLong() * 3_600_000L }
|
||||
DAYS_AGO.matchEntire(trimmed)?.let { return nowMs - it.groupValues[1].toLong() * 86_400_000L }
|
||||
if (trimmed == "刚刚") return nowMs
|
||||
DAY_TIME.matchEntire(trimmed)?.let { match ->
|
||||
val offset = when (match.groupValues[1]) {
|
||||
"今天" -> 0
|
||||
"昨天" -> -1
|
||||
"前天" -> -2
|
||||
else -> return null
|
||||
}
|
||||
return dayAt(nowMs, offset, match.groupValues[2].toInt(), match.groupValues[3].toInt())
|
||||
}
|
||||
FULL_TIME.matchEntire(trimmed)?.let { match ->
|
||||
return calendarAt(
|
||||
year = match.groupValues[1].toInt(),
|
||||
month = match.groupValues[2].toInt(),
|
||||
day = match.groupValues[3].toInt(),
|
||||
hour = match.groupValues[4].toIntOrNull() ?: 0,
|
||||
minute = match.groupValues[5].toIntOrNull() ?: 0,
|
||||
second = match.groupValues[6].toIntOrNull() ?: 0,
|
||||
)
|
||||
}
|
||||
MONTH_DAY.matchEntire(trimmed)?.let { match ->
|
||||
val year = Calendar.getInstance().apply { timeInMillis = nowMs }.get(Calendar.YEAR)
|
||||
return calendarAt(
|
||||
year = year,
|
||||
month = match.groupValues[1].toInt(),
|
||||
day = match.groupValues[2].toInt(),
|
||||
hour = match.groupValues[3].toIntOrNull() ?: 0,
|
||||
minute = match.groupValues[4].toIntOrNull() ?: 0,
|
||||
second = 0,
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun dayAt(nowMs: Long, dayOffset: Int, hour: Int, minute: Int): Long =
|
||||
Calendar.getInstance().apply {
|
||||
timeInMillis = nowMs
|
||||
add(Calendar.DAY_OF_YEAR, dayOffset)
|
||||
set(Calendar.HOUR_OF_DAY, hour)
|
||||
set(Calendar.MINUTE, minute)
|
||||
set(Calendar.SECOND, 0)
|
||||
set(Calendar.MILLISECOND, 0)
|
||||
}.timeInMillis
|
||||
|
||||
private fun calendarAt(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int): Long? {
|
||||
if (month !in 1..12 || day !in 1..31 || hour !in 0..23 || minute !in 0..59 || second !in 0..59) return null
|
||||
return Calendar.getInstance().apply {
|
||||
clear()
|
||||
set(year, month - 1, day, hour, minute, second)
|
||||
}.timeInMillis
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,754 @@
|
||||
package com.haorui.app.crossplatform.ui
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
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.Delete
|
||||
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.collectAsState
|
||||
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.MultiSelectDropdownField
|
||||
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) {
|
||||
// 品牌 Hero:渐变主卡 + 指标行;文案克制,一眼看清工作台状态
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(24.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
color = com.haorui.app.ui.theme.BrandPurple,
|
||||
) {
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 22.dp, vertical = 24.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||
Text("浩瑞", style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold, color = androidx.compose.ui.graphics.Color.White)
|
||||
Text("热点 → 创作 → 发布,手机上的内容工作台", style = MaterialTheme.typography.bodyMedium, color = androidx.compose.ui.graphics.Color.White.copy(alpha = .85f))
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(20.dp)) {
|
||||
HeroMetric(if (loaded) tasks.size.toString() else "—", "本地任务")
|
||||
HeroMetric(if (loaded) tasks.count { it.state in unknownStates }.toString() else "—", "待核对")
|
||||
HeroMetric(SourceRegistry.definitions.count { config.crossPlatform.sourceEnabled(it.id) }.toString(), "启用来源")
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
TextButton({ onNavigate(Routes.TASKS) }, Modifier.weight(1f)) { Text("创作任务") }
|
||||
TextButton({ onNavigate(Routes.CROSS_AUTOMATION) }, Modifier.weight(1f)) { Text("自动化设置") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun HeroMetric(value: String, label: String) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(value, style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.SemiBold, color = androidx.compose.ui.graphics.Color.White)
|
||||
Text(label, style = MaterialTheme.typography.bodySmall, color = androidx.compose.ui.graphics.Color.White.copy(alpha = .75f))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun CrossSettingsEntries(onNavigate: (String) -> Unit) {
|
||||
// 来源 App 管理入口已并入首页「管理来源」;此处不再放任何链接。
|
||||
Section(title = "通用配置", help = "自动化与采集设置的调整入口") {
|
||||
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.filter { it.id != "xiaohongshu" }.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)
|
||||
"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("保存来源设置") }
|
||||
}
|
||||
}
|
||||
|
||||
/** 带范围归一化的数字输入:编辑中文本自由变化,归一化成功后回写配置 */
|
||||
@Composable
|
||||
private fun OutlinedNumberField(label: String, value: String, range: IntRange, onText: (String) -> Unit, onCommit: (Int) -> Unit) {
|
||||
val parsed = value.toIntOrNull()
|
||||
OutlinedTextField(
|
||||
value = value,
|
||||
onValueChange = { raw ->
|
||||
onText(raw)
|
||||
raw.toIntOrNull()?.let { if (it in range) onCommit(it.coerceIn(range.first, range.last)) }
|
||||
},
|
||||
label = { Text(label) },
|
||||
supportingText = { Text(if (parsed != null && parsed in range) "范围 ${range.first}~${range.last}" else "请输入 ${range.first}~${range.last} 之间的整数") },
|
||||
isError = parsed == null || parsed !in range,
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
|
||||
@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) })
|
||||
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 TopicSourceSection(config: AppConfig, tasks: List<CrossPublishTask>, loaded: Boolean, loadError: String?,
|
||||
onConfigChange: (AppConfig) -> Unit, onNavigate: (String) -> Unit) {
|
||||
var source by rememberSaveable { mutableStateOf("weibo") }
|
||||
var kind by rememberSaveable { mutableStateOf("all") }
|
||||
var selected by remember { mutableStateOf<CrossPublishTask?>(null) }
|
||||
val candidates = tasks.filter { it.state in topicStates && it.sourcePlatform == source && (kind == "all" || it.contentKind.name == kind) }
|
||||
Section(title = "热点选题", help = "选来源 → 配置该来源的选题条件 → 勾选词条采集") {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
TextButton({ onNavigate(Routes.CROSS_SOURCES) }) { Text("管理来源") }
|
||||
}
|
||||
// ── 来源切换:决定下方显示哪个来源的专属筛选(小红书已搁置,不提供) ────
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(7.dp)) {
|
||||
listOf("zhihu", "weibo", "douyin").forEach { id ->
|
||||
val def = SourceRegistry.find(id) ?: return@forEach
|
||||
FilterChip(selected = source == id, onClick = { source = id }, label = { Text(def.label) })
|
||||
}
|
||||
}
|
||||
// ── 来源专属筛选:不同来源的选题维度不同 ────
|
||||
when (source) {
|
||||
"zhihu" -> ZhihuSourceFilter(config, onConfigChange)
|
||||
"weibo" -> WeiboSourceFilter(config, onConfigChange)
|
||||
"douyin" -> DouyinSourceFilter(config, onConfigChange)
|
||||
}
|
||||
// ── 作品形式过滤 + 候选列表 ────
|
||||
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) })
|
||||
}
|
||||
}
|
||||
when {
|
||||
loadError != null -> StatusBanner("本地任务读取失败:$loadError", StatusLevel.BAD)
|
||||
!loaded -> EmptyPanel("正在读取本地候选", "请稍候")
|
||||
candidates.isEmpty() -> EmptyPanel("此来源暂无热点候选", "采集落库后,这里将显示真实候选记录。")
|
||||
else -> candidates.forEach { TaskCard(it, { selected = it }) }
|
||||
}
|
||||
}
|
||||
selected?.let { prior -> TaskPreview(tasks.firstOrNull { it.id == prior.id } ?: prior) { selected = null } }
|
||||
}
|
||||
|
||||
/** 知乎来源专属筛选:热榜卡片范围(按榜单序号区间采集)。 */
|
||||
@Composable
|
||||
private fun ZhihuSourceFilter(config: AppConfig, onConfigChange: (AppConfig) -> Unit) {
|
||||
var rangeStart by rememberSaveable(config.crossPlatform.zhihuCardRangeStart) { mutableStateOf(config.crossPlatform.zhihuCardRangeStart.toString()) }
|
||||
var rangeEnd by rememberSaveable(config.crossPlatform.zhihuCardRangeEnd) { mutableStateOf(config.crossPlatform.zhihuCardRangeEnd.toString()) }
|
||||
Section(title = "知乎热榜范围", help = "采集热榜第 N~M 条卡片;卡片序号按榜单展示序(1 起)") {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
OutlinedNumberField("起始条(1~50)", rangeStart, 1..50, { rangeStart = it }) {
|
||||
onConfigChange(config.copy(crossPlatform = config.crossPlatform.copy(zhihuCardRangeStart = it)))
|
||||
}
|
||||
OutlinedNumberField("结束条(起始~50)", rangeEnd, 1..50, { rangeEnd = it }) {
|
||||
onConfigChange(config.copy(crossPlatform = config.crossPlatform.copy(zhihuCardRangeEnd = it)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 抖音来源专属筛选:榜单前 N 条 + 标签过滤(OCR 可读标签:热/新/挑战/辟谣)。 */
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun DouyinSourceFilter(config: AppConfig, onConfigChange: (AppConfig) -> Unit) {
|
||||
var topN by rememberSaveable(config.crossPlatform.douyinTopN) { mutableStateOf(config.crossPlatform.douyinTopN.toString()) }
|
||||
val selectedLabels = config.crossPlatform.douyinLabelFilter.toSet()
|
||||
Section(title = "抖音热榜范围", help = "采集榜单前 N 条;标签过滤为空表示不过滤(全部标签都采)") {
|
||||
OutlinedNumberField("只采前(1~50)条", topN, 1..50, { topN = it }) {
|
||||
onConfigChange(config.copy(crossPlatform = config.crossPlatform.copy(douyinTopN = it)))
|
||||
}
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
listOf("热", "新", "挑战", "辟谣").forEach { label ->
|
||||
FilterChip(selected = label in selectedLabels, onClick = {
|
||||
val next = if (label in selectedLabels) selectedLabels - label else selectedLabels + label
|
||||
// 保持稳定顺序(热/新/挑战/辟谣)
|
||||
onConfigChange(config.copy(crossPlatform = config.crossPlatform.copy(
|
||||
douyinLabelFilter = listOf("热", "新", "挑战", "辟谣").filter { it in next },
|
||||
)))
|
||||
}, label = { Text(label) })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 微博来源专属筛选:热搜类目多选 + 词条勾选器(选什么采什么)。 */
|
||||
@Composable
|
||||
private fun WeiboSourceFilter(config: AppConfig, onConfigChange: (AppConfig) -> Unit) {
|
||||
// 微博热搜类目:下拉多选(全部实测类目),选择持久化到配置;所选类目决定去微博热搜拉哪些榜单
|
||||
val selectedCategoryIds: Set<String> = config.crossPlatform.weiboHotCategories.toSet()
|
||||
Section(title = "微博热搜类目", tag = "下拉可选",
|
||||
help = "在微博热搜的类目 Tab 中选择要采集的类型;选中后按类目拉取对应榜单,未核验类目不列入") {
|
||||
MultiSelectDropdownField(
|
||||
label = "热搜类型(可多选)",
|
||||
selectedIds = selectedCategoryIds,
|
||||
options = com.haorui.app.crossplatform.source.weibo.WeiboHotCategories.ALL.map { it.id to it.tabLabel },
|
||||
onToggle = { id ->
|
||||
val next = if (id in selectedCategoryIds) selectedCategoryIds - id else selectedCategoryIds + id
|
||||
onConfigChange(config.copy(crossPlatform = config.crossPlatform.copy(
|
||||
weiboHotCategories = com.haorui.app.crossplatform.source.weibo.WeiboHotCategories.ALL
|
||||
.map { it.id }.filter { it in next },
|
||||
)))
|
||||
},
|
||||
onClear = {
|
||||
onConfigChange(config.copy(crossPlatform = config.crossPlatform.copy(weiboHotCategories = emptyList())))
|
||||
},
|
||||
placeholder = "未选择类目",
|
||||
)
|
||||
Text(
|
||||
text = if (selectedCategoryIds.isEmpty()) "尚未选择热搜类型;选择后这里将按类目展示可采集的热搜词条"
|
||||
else "已选 ${selectedCategoryIds.size} 个类型:" +
|
||||
com.haorui.app.crossplatform.source.weibo.WeiboHotCategories.byIds(selectedCategoryIds)
|
||||
.joinToString("、") { it.tabLabel },
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
// 微博热搜词条清单:按已选类目拉取真机榜单 → 勾选词条 → 持久化到配置(勾选后系统按所选词条采集)
|
||||
WeiboHotTopicPicker(config, onConfigChange)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 微博热搜词条勾选器(用户口径:用户选什么,系统采什么发什么)。
|
||||
* 数据流:服务直读——「拉取榜单」触发 `startWeiboTopicCollect(id, emptyList())`(仅清单模式),
|
||||
* `weiboCollectState.entries` 上屏后**点词条即勾选**(持久化到配置);「开始采集」把勾选交给
|
||||
* `startWeiboTopicCollect(id, topics)` 执行全链并落任务库。
|
||||
*/
|
||||
@Composable
|
||||
private fun WeiboHotTopicPicker(config: AppConfig, onConfigChange: (AppConfig) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
var expandedCategory by remember { mutableStateOf<String?>(null) }
|
||||
var newTopicDraft by remember { mutableStateOf("") }
|
||||
val topics = config.crossPlatform.weiboHotTopics
|
||||
val categories = com.haorui.app.crossplatform.source.weibo.WeiboHotCategories.ALL
|
||||
val selectedCategoryIds: Set<String> = config.crossPlatform.weiboHotCategories.toSet()
|
||||
// 服务采集状态直读(清单/进度/结果)
|
||||
val service = com.haorui.app.automation.HaoRuiAccessibilityService.instance
|
||||
val collectState by service?.weiboCollectState?.collectAsState()
|
||||
?: remember { mutableStateOf(com.haorui.app.automation.HaoRuiAccessibilityService.WeiboCollectUiState()) }
|
||||
Section(title = "微博热搜词条勾选", tag = "选什么采什么",
|
||||
help = "拉取榜单后点词条即勾选;「开始采集」按勾选逐条采集并落任务库") {
|
||||
if (selectedCategoryIds.isEmpty()) {
|
||||
FieldHelp("请先在上方「微博热搜类目」选择至少一个类型")
|
||||
} else {
|
||||
categories.filter { it.id in selectedCategoryIds }.forEach { category ->
|
||||
val checked = topics[category.id].orEmpty()
|
||||
// 类目折叠行:点击展开该类目的词条勾选明细
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp)
|
||||
.clickable { expandedCategory = if (expandedCategory == category.id) null else category.id },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(Icons.Filled.ChevronRight, contentDescription = null,
|
||||
modifier = Modifier.padding(end = 6.dp))
|
||||
Text(
|
||||
text = "${category.tabLabel}(已勾选 ${checked.size} 条)",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = if (checked.isNotEmpty()) FontWeight.SemiBold else FontWeight.Normal,
|
||||
)
|
||||
}
|
||||
if (expandedCategory == category.id) {
|
||||
// 拉到的榜单词条(点词条即勾选/取消勾选;已勾选的高亮)
|
||||
val liveEntries = if (collectState.categoryLabel == category.tabLabel) collectState.entries else emptyList()
|
||||
if (liveEntries.isNotEmpty()) {
|
||||
FieldHelp("最新榜单 ${liveEntries.size} 条(点词条即勾选)")
|
||||
liveEntries.forEach { (title, heat) ->
|
||||
val isChecked = title in checked
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(start = 20.dp)
|
||||
.clickable {
|
||||
val next = if (isChecked) checked - title else checked + title
|
||||
onConfigChange(config.copy(crossPlatform = config.crossPlatform.copy(
|
||||
weiboHotTopics = (topics - category.id) +
|
||||
if (next.isEmpty()) emptyMap() else mapOf(category.id to next),
|
||||
)))
|
||||
},
|
||||
) {
|
||||
Text(
|
||||
text = if (isChecked) "✓ $title" else title,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = if (isChecked) MaterialTheme.colorScheme.primary
|
||||
else MaterialTheme.colorScheme.onSurface,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
text = heat ?: "热度未知",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
checked.filter { it !in liveEntries.map { e -> e.first } }.forEach { title ->
|
||||
Row(verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(start = 20.dp)) {
|
||||
Text("✓ $title", style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.primary, modifier = Modifier.weight(1f))
|
||||
TextButton(onClick = {
|
||||
val next = checked - title
|
||||
onConfigChange(config.copy(crossPlatform = config.crossPlatform.copy(
|
||||
weiboHotTopics = (topics - category.id) + if (next.isEmpty()) emptyMap()
|
||||
else mapOf(category.id to next),
|
||||
)))
|
||||
}) { Text("移除") }
|
||||
}
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(start = 20.dp, top = 4.dp)) {
|
||||
OutlinedTextField(
|
||||
value = newTopicDraft,
|
||||
onValueChange = { newTopicDraft = it },
|
||||
placeholder = { Text("手动输入词条标题") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Button(
|
||||
onClick = {
|
||||
val title = newTopicDraft.trim()
|
||||
if (title.isNotEmpty()) {
|
||||
onConfigChange(config.copy(crossPlatform = config.crossPlatform.copy(
|
||||
weiboHotTopics = topics + mapOf(category.id to (checked + title).distinct()),
|
||||
)))
|
||||
newTopicDraft = ""
|
||||
}
|
||||
},
|
||||
modifier = Modifier.padding(start = 8.dp),
|
||||
) { Text("添加") }
|
||||
}
|
||||
Button(
|
||||
onClick = {
|
||||
com.haorui.app.automation.HaoRuiAccessibilityService.instance
|
||||
?.startWeiboTopicCollect(category.id, checked)
|
||||
},
|
||||
enabled = checked.isNotEmpty() && !collectState.running,
|
||||
modifier = Modifier.padding(start = 20.dp, top = 6.dp),
|
||||
) { Text(if (collectState.running) "采集中…" else "开始采集(${checked.size} 条)") }
|
||||
}
|
||||
}
|
||||
TextButton(onClick = {
|
||||
// 拉取最新榜单(服务直读:collectOnlyList 清单模式)——完成后 weiboCollectState.entries 上屏
|
||||
selectedCategoryIds.forEach { id ->
|
||||
com.haorui.app.automation.HaoRuiAccessibilityService.instance
|
||||
?.startWeiboTopicCollect(id, emptyList())
|
||||
}
|
||||
}) { Text("拉取所选类目的最新榜单") }
|
||||
if (collectState.running) {
|
||||
Text(
|
||||
text = "采集中:${collectState.categoryLabel}(榜单 ${collectState.entries.size} 条,已落库 ${collectState.collected.size} 条)",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
} else if (collectState.done) {
|
||||
val summary = buildString {
|
||||
if (collectState.collected.isNotEmpty()) {
|
||||
append("已落库 ${collectState.collected.size} 条:")
|
||||
append(collectState.collected.joinToString("、") { it.first.take(12) })
|
||||
}
|
||||
if (collectState.reason.isNotEmpty()) {
|
||||
if (isNotEmpty()) append(";")
|
||||
append(collectState.reason)
|
||||
}
|
||||
}
|
||||
if (summary.isNotEmpty()) {
|
||||
Text(
|
||||
text = summary,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = if (collectState.collected.isEmpty()) MaterialTheme.colorScheme.error
|
||||
else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
FieldHelp("采集为只读观察并落本地任务库(同链接幂等),不发布内容;图文/视频生成由后续阶段处理。")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun CrossTasksScreen(tasks: List<CrossPublishTask>, loaded: Boolean, loadError: String?,
|
||||
onDeleteTask: (String) -> Unit, onNavigate: (String) -> Unit) {
|
||||
var tab by rememberSaveable { mutableStateOf("pending") }
|
||||
var selected by remember { mutableStateOf<CrossPublishTask?>(null) }
|
||||
// 待删除任务(弹出二次确认框);UNKNOWN/待核对任务删除即放弃核对保护,高危文案明示
|
||||
var pendingDelete 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)
|
||||
}
|
||||
val dangerous = pendingDelete != null && pendingDelete!!.state in unknownStates
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(7.dp), modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.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,
|
||||
modifier = Modifier.padding(horizontal = 16.dp))
|
||||
if (tab == "submitted") FieldHelp("已提交表示提交回执已核对,不代表作品已审核公开。")
|
||||
when {
|
||||
loadError != null -> StatusBanner("本地任务读取失败:$loadError", StatusLevel.BAD,
|
||||
modifier = Modifier.padding(horizontal = 16.dp))
|
||||
!loaded -> Column(Modifier.fillMaxSize().padding(22.dp)) { EmptyPanel("正在读取任务", "请稍候") }
|
||||
tasks.filter { matches(it, tab) }.isEmpty() -> Column(Modifier.fillMaxSize().padding(22.dp)) {
|
||||
EmptyPanel("此状态下暂无任务", "真实成品和提交记录将在这里保留。当前不会生成模拟任务,也不会触发跨平台发布。")
|
||||
}
|
||||
else ->
|
||||
// 数据量大时全量组合会卡顿:改用 LazyColumn 按需组合列表项
|
||||
androidx.compose.foundation.lazy.LazyColumn(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
val visible = tasks.filter { matches(it, tab) }
|
||||
items(visible.size, key = { visible[it].id }) { index ->
|
||||
val task = visible[index]
|
||||
TaskCardWithDelete(task, onPreview = { selected = task }, onDelete = { pendingDelete = task })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
selected?.let { prior -> TaskPreview(tasks.firstOrNull { it.id == prior.id } ?: prior) { selected = null } }
|
||||
pendingDelete?.let { task ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { pendingDelete = null },
|
||||
title = { Text(if (dangerous) "删除结果待核对的任务?" else "删除该任务?") },
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text("「${task.title.take(24)}」", style = MaterialTheme.typography.titleSmall)
|
||||
if (dangerous) {
|
||||
Text("该任务提交结果不明:删除将永久放弃核对保护,其占用的发布额度与点击许可一并释放(等于当作没发过)。",
|
||||
color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium)
|
||||
Text("如果这条任务可能已在头条实际存草稿或发布,删除后系统不会再追踪它。",
|
||||
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
} else {
|
||||
Text("任务记录、提交尝试、额度台账与素材记录将一并删除;关联的本地素材文件同时清理(受保护素材除外)。",
|
||||
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
onDeleteTask(task.id)
|
||||
pendingDelete = null
|
||||
}) { Text("确认删除", color = MaterialTheme.colorScheme.error) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { pendingDelete = null }) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TaskCardWithDelete(task: CrossPublishTask, onPreview: () -> Unit, onDelete: () -> Unit) {
|
||||
Surface(shape = RoundedCornerShape(18.dp), color = MaterialTheme.colorScheme.surface) {
|
||||
Column(Modifier.fillMaxWidth().padding(start = 16.dp, top = 16.dp, bottom = 16.dp, end = 10.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)
|
||||
Icon(
|
||||
Icons.Filled.Delete,
|
||||
contentDescription = "删除任务",
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(start = 4.dp).clickable { onDelete() },
|
||||
)
|
||||
}
|
||||
Text(task.title, style = MaterialTheme.typography.titleMedium, modifier = Modifier.clickable { onPreview() })
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.clickable { onPreview() }) {
|
||||
Text("${SourceRegistry.find(task.sourcePlatform)?.label ?: task.sourcePlatform} · ${formatTime(task.updatedAtMs)}", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f))
|
||||
Text("查看详情", style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@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("关闭") } },
|
||||
)
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import com.haorui.app.automation.RunLogger
|
||||
import com.haorui.app.automation.Targets
|
||||
import com.haorui.app.automation.ToutiaoSelectors
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
|
||||
/**
|
||||
* 浩瑞 · 信用分门控执行器(P5-1)
|
||||
@@ -28,6 +29,15 @@ import kotlinx.coroutines.delay
|
||||
*/
|
||||
object CreditGateRunner {
|
||||
|
||||
// ── M6 导航超时防御(2026-11-16)──────────────────────
|
||||
// 真机实Run(M6 分发沙盒第 3 轮):CreditGateRunner 在创作中心页停摆 24 分钟
|
||||
// 无日志——树定位/OCR 某处静默阻塞且无整体预算。旧链路 fail-open 下卡住只是
|
||||
// 慢,新链路 fail-closed 下会**无限阻塞分发**,必须兜底。
|
||||
/** 单跳定位预算(tapTarget 3 次重试 × 树+OCR;takeScreenshot 5s 上限为基准)。 */
|
||||
private const val TAP_BUDGET_MS = 30_000L
|
||||
/** 一次完整读取(含导航四跳+OCR+二次确认)整体预算。 */
|
||||
private const val READ_BUDGET_MS = 120_000L
|
||||
|
||||
private const val TAG = "HaoRui-CreditGate"
|
||||
|
||||
// ── 导航链目标文案(真机实测)────────────────────────────
|
||||
@@ -117,12 +127,19 @@ object CreditGateRunner {
|
||||
cachedScore = -1
|
||||
Verdict.UNREADABLE
|
||||
} else {
|
||||
// 对照原 l0:首次读到后等 1600ms 二次确认(同值才落库)
|
||||
// 对照原 l0:首次读到后等 1600ms 二次确认(同值才落库)。
|
||||
// ⚠️ 二次读禁导航(2026-11-16 第 12 轮实锤):人在处罚中心深层页无底栏,
|
||||
// 重新导航必然失败→null→误判"不一致"。二次读=原地 OCR 快路径重试。
|
||||
lastRawScore = score
|
||||
lastRawStable = 1
|
||||
RunLogger.i(TAG, "已读取信用分 $score 分,等待二次确认")
|
||||
RunLogger.i(TAG, "已读取信用分 $score 分,等待二次确认(原地重读)")
|
||||
delay(1600)
|
||||
val again = readScoreWithNav(service, region)
|
||||
var again: Int? = null
|
||||
for (attempt in 1..3) {
|
||||
again = readScoreInPlace(service, region)
|
||||
if (again != null) break
|
||||
delay(1200)
|
||||
}
|
||||
if (again != score) {
|
||||
RunLogger.w(TAG, "信用分二次读取不一致($score vs $again),按 fail-open 放行")
|
||||
cachedScoreDate = today
|
||||
@@ -168,6 +185,16 @@ object CreditGateRunner {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 原地读(二次确认专用):不导航、不领前台票据(外层已持有会话上下文),
|
||||
* 仅 overlay 包壳+截屏 OCR——人在处罚中心时从当前屏直接再读。
|
||||
*/
|
||||
private suspend fun readScoreInPlace(service: HaoRuiAccessibilityService, region: Rect?): Int? =
|
||||
withOverlayHidden {
|
||||
val capturer = ScreenCapturer(service)
|
||||
CreditScoreReader.readFromScreen(capturer, region)
|
||||
}
|
||||
|
||||
// ── 导航 + 读取(P5-1 核心)──────────────────────────────
|
||||
|
||||
/**
|
||||
@@ -179,24 +206,39 @@ object CreditGateRunner {
|
||||
service: HaoRuiAccessibilityService,
|
||||
region: Rect?,
|
||||
): Int? {
|
||||
if (!service.checkVersionGate()) return null
|
||||
val ticket = service.tryEnterCreditForeground() ?: return null
|
||||
service.frontGuard.creditNavigating = true
|
||||
try {
|
||||
return withOverlayHidden {
|
||||
if (!service.foregroundCoordinator.isCurrent(ticket)) return@withOverlayHidden null
|
||||
val capturer = ScreenCapturer(service)
|
||||
// 快路径:当前屏已是信用分页(重复检查/误入时省导航)
|
||||
var score = CreditScoreReader.readFromScreen(capturer, region)
|
||||
if (score == null) {
|
||||
RunLogger.i(TAG, "当前屏未识别到信用分,导航至信用分页(我的→创作中心→全部服务→处罚中心)")
|
||||
if (navigateToCreditPage(service, ticket)) {
|
||||
score = CreditScoreReader.readFromScreen(capturer, region)
|
||||
} else {
|
||||
RunLogger.w(TAG, "信用分页导航失败(页面改版或定位失败),按 fail-open 放行")
|
||||
// M6 整体预算:导航链任一处静默阻塞时 120s 强制超时 → null(UNREADABLE)。
|
||||
// 旧链路 fail-open 语义不变;新链路经 Gate 把 UNREADABLE 转 HOLD,不阻塞分发。
|
||||
// ⚠️ 超时与正常失败都返回 null——用时间戳区分日志语义(不误报超时)。
|
||||
val readStart = android.os.SystemClock.elapsedRealtime()
|
||||
val score = withTimeoutOrNull(READ_BUDGET_MS) {
|
||||
withOverlayHidden {
|
||||
if (!service.foregroundCoordinator.isCurrent(ticket)) return@withOverlayHidden null
|
||||
val capturer = ScreenCapturer(service)
|
||||
// 快路径:当前屏已是信用分页(重复检查/误入时省导航)
|
||||
var s = if (service.currentPackage() == Targets.TOUTIAO_PKG) CreditScoreReader.readFromScreen(capturer, region) else null
|
||||
if (!service.foregroundCoordinator.isCurrent(ticket)) return@withOverlayHidden null
|
||||
if (s == null) {
|
||||
RunLogger.i(TAG, "当前屏未识别到信用分,导航至信用分页(我的→创作中心→全部服务→处罚中心)")
|
||||
if (navigateToCreditPage(service, ticket)) {
|
||||
s = CreditScoreReader.readFromScreen(capturer, region)
|
||||
} else {
|
||||
RunLogger.w(TAG, "信用分页导航失败(页面改版或定位失败),按 fail-open 放行")
|
||||
}
|
||||
}
|
||||
if (service.foregroundCoordinator.isCurrent(ticket) && service.currentPackage() == Targets.TOUTIAO_PKG) s else null
|
||||
}
|
||||
score
|
||||
}
|
||||
if (score == null) {
|
||||
val elapsed = android.os.SystemClock.elapsedRealtime() - readStart
|
||||
if (elapsed >= READ_BUDGET_MS) {
|
||||
RunLogger.w(TAG, "信用分读取整体预算 ${READ_BUDGET_MS / 1000}s 超时(导航静默阻塞兜底)")
|
||||
}
|
||||
}
|
||||
return score
|
||||
} finally {
|
||||
service.frontGuard.creditNavigating = false
|
||||
service.foregroundCoordinator.release(ticket)
|
||||
@@ -218,17 +260,81 @@ object CreditGateRunner {
|
||||
service.launchApp(Targets.TOUTIAO_PKG)
|
||||
delay(2500)
|
||||
}
|
||||
if (!tapTarget(service, ticket, ToutiaoSelectors.TXT_ME, backOnFail = true, preferBottom = true)) return false
|
||||
delay(1500)
|
||||
if (!tapTarget(service, ticket, TXT_CREATION_CENTER)) return false
|
||||
delay(1500)
|
||||
if (!tapTarget(service, ticket, TXT_ALL_SERVICES)) return false
|
||||
delay(1500)
|
||||
if (!tapTarget(service, ticket, TXT_PENALTY_CENTER)) return false
|
||||
// M6(2026-11-16 第 8/9 轮实锤):残留的**视频发布编辑器**(M5/沙盒遗留)会拦截
|
||||
// launchApp——CLEAR_TOP 也回不到主页,底栏「我的」不存在 → 导航必败。
|
||||
// 对策:检测编辑器特征先退出。「是否保存草稿」弹窗不吃系统 BACK——
|
||||
// 点「不保存」(安全侧按钮):残留编辑器是自动化自己制造的重复现场,
|
||||
// 已存草稿早前已确认保存(回执 DONE),不保存只丢弃重复残留。
|
||||
for (attempt in 1..5) {
|
||||
val editor = screenHas(service, "编辑封面") || screenHas(service, "作品声明") ||
|
||||
screenHas(service, "存草稿") || screenHas(service, "是否保存草稿")
|
||||
if (!editor) break
|
||||
val discardDialog = screenHas(service, "是否保存草稿")
|
||||
if (discardDialog) {
|
||||
RunLogger.i(TAG, "「是否保存草稿」弹窗(第 $attempt 次):点「不保存」丢弃残留(安全侧按钮)")
|
||||
tapByOcr(service, ticket, "不保存")
|
||||
} else {
|
||||
RunLogger.i(TAG, "检测到发布编辑器残留(第 $attempt 次),BACK 退出")
|
||||
service.gestures.back()
|
||||
}
|
||||
delay(1500)
|
||||
}
|
||||
// M6 卡死防御:看屏定跳——每跳先 OCR 核屏,目标页特征已在屏就跳过
|
||||
//(残留页/重复导航场景)。⚠️ 「我的」跳必须保留:launchApp CLEAR_TOP 会把头条
|
||||
// 重置到信息流(残留页假设不成立时),没有它导航到不了创作中心。
|
||||
val hops: List<Pair<String, suspend () -> Boolean>> = listOf(
|
||||
"我的" to { tapTarget(service, ticket, ToutiaoSelectors.TXT_ME, backOnFail = true, preferBottom = true) },
|
||||
"创作中心" to { tapTarget(service, ticket, TXT_CREATION_CENTER) },
|
||||
"全部服务" to { tapTarget(service, ticket, TXT_ALL_SERVICES) },
|
||||
"处罚中心" to { tapTarget(service, ticket, TXT_PENALTY_CENTER) },
|
||||
)
|
||||
for ((label, tap) in hops) {
|
||||
// 跳前核屏(挂起安全的 OCR 管线):仅页面级跳有 marker,特征已在屏跳过点击
|
||||
val marker = markerFor(label)
|
||||
if (marker != null && screenHas(service, marker)) {
|
||||
RunLogger.i(TAG, "跳「$label」:页面特征已在屏,跳过")
|
||||
continue
|
||||
}
|
||||
val ok = withTimeoutOrNull(TAP_BUDGET_MS) { tap() } ?: run {
|
||||
RunLogger.w(TAG, "跳「$label」预算 ${TAP_BUDGET_MS / 1000}s 超时(非挂起阻塞兜底)")
|
||||
false
|
||||
}
|
||||
if (!ok) {
|
||||
RunLogger.w(TAG, "导航中断在跳「$label」(页面改版或定位失败)")
|
||||
return false
|
||||
}
|
||||
RunLogger.i(TAG, "导航跳「$label」完成")
|
||||
delay(1500)
|
||||
}
|
||||
delay(2000) // 等信用分页渲染(Lynx)
|
||||
return true
|
||||
}
|
||||
|
||||
/** 各跳的"已在目标页"特征(看屏定跳用)。
|
||||
* ⚠️ 只对**页面级**跳(我的/创作中心)启用——按钮级跳(全部服务/处罚中心)的
|
||||
* 按钮名在上一页也可见,marker 误判会导致"没点进去却以为到了"(2026-11-16
|
||||
* 第 11 轮实锤)。按钮级跳恒执行点击,定位失败由重试机制兜底。 */
|
||||
private fun markerFor(label: String): String? = when (label) {
|
||||
// 已在创作中心内页(创作权益/作品管理)或更深 → 我的 tab 无需再点
|
||||
"我的" -> "创作权益"
|
||||
// 创作中心内页特征(标题下方小字;比卡片名"创作中心"稳定——卡片名只在"我的"页)
|
||||
"创作中心" -> "创作权益"
|
||||
// 按钮级跳:无 marker(恒执行点击)
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** 屏幕特征核对(OCR 管线;树查询存在非挂起 binder 阻塞风险——M6 卡死实锤,不用)。 */
|
||||
private suspend fun screenHas(service: HaoRuiAccessibilityService, text: String): Boolean {
|
||||
val capturer = ScreenCapturer(service)
|
||||
val bitmap = capturer.capture() ?: return false
|
||||
val blocks = try {
|
||||
OcrProcessor.recognize(bitmap)
|
||||
} finally {
|
||||
runCatching { bitmap.recycle() }
|
||||
}
|
||||
return blocks.any { block -> block.text.contains(text) || block.lines.any { it.text.trim().contains(text) } }
|
||||
}
|
||||
|
||||
/**
|
||||
* 点击目标文本:树定位优先(原生页),OCR boundingBox 兜底(Lynx 页),重试 ≤3。
|
||||
* @param backOnFail 失败重试前先 back(首跳用:详情页退回后底部 tab 才可见)
|
||||
@@ -255,9 +361,11 @@ object CreditGateRunner {
|
||||
}
|
||||
// ① 树定位(原生页有 text/desc 节点)
|
||||
val root = service.root()
|
||||
val node = root?.let {
|
||||
NodeLocator.byText(it, label) ?: NodeLocator.byTextContains(it, label)
|
||||
}
|
||||
val node = try {
|
||||
root?.takeIf { it.packageName?.toString() == Targets.TOUTIAO_PKG }?.let {
|
||||
NodeLocator.byText(it, label) ?: NodeLocator.byTextContains(it, label)
|
||||
}
|
||||
} finally { root?.recycle() }
|
||||
if (node != null) {
|
||||
if (!service.foregroundCoordinator.isCurrent(ticket)) {
|
||||
node.recycle()
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.haorui.app.ocr
|
||||
|
||||
/** 18.3.0 处罚中心的信用分卡片;仅接收已核对页面和列位置中的完整分数字样。 */
|
||||
object CreditScoreParser {
|
||||
data class Area(val left: Int, val top: Int, val right: Int, val bottom: Int) {
|
||||
val centerX get() = left / 2.0 + right / 2.0
|
||||
val centerY get() = top / 2.0 + bottom / 2.0
|
||||
fun valid(width: Int, height: Int) = left >= 0 && top >= 0 && right > left && bottom > top && right <= width && bottom <= height
|
||||
fun contains(other: Area) = other.left >= left && other.top >= top && other.right <= right && other.bottom <= bottom
|
||||
}
|
||||
data class Line(val text: String, val bounds: Area)
|
||||
|
||||
private val labelPattern = Regex("信用(?:分|评分)(?:[::]?([0-9Oo]{1,3})分?)?")
|
||||
private val valuePattern = Regex("([0-9Oo]{1,3})分?")
|
||||
|
||||
fun extract(lines: List<Line>, width: Int, height: Int, scoreRegion: Area? = null): Int? {
|
||||
if (width <= 0 || height <= 0 || scoreRegion != null && !scoreRegion.valid(width, height)) return null
|
||||
val visible = lines.filter { it.bounds.valid(width, height) }.map { it.copy(text = normalize(it.text)) }
|
||||
val title = visible.singleOrNull { it.text == "账号处罚中心" && it.bounds.centerY < height * 0.15 } ?: return null
|
||||
val label = visible.singleOrNull {
|
||||
labelPattern.matches(it.text) && it.bounds.top > title.bounds.bottom && it.bounds.bottom < height * 0.45
|
||||
} ?: return null
|
||||
val status = visible.singleOrNull {
|
||||
it.text == "账号状态" && it.bounds.left > label.bounds.right &&
|
||||
kotlin.math.abs(it.bounds.centerY - label.bounds.centerY) < height * 0.035
|
||||
} ?: return null
|
||||
|
||||
val candidates = visible.filter { line ->
|
||||
line.bounds.centerX >= label.bounds.left - width * 0.03 && line.bounds.right < status.bounds.left &&
|
||||
line.bounds.centerY >= label.bounds.centerY && line.bounds.bottom <= label.bounds.bottom + height * 0.06 &&
|
||||
(scoreRegion == null || scoreRegion.contains(line.bounds))
|
||||
}
|
||||
val values = mutableSetOf<Int>()
|
||||
for (line in candidates) {
|
||||
val match = if (line == label) labelPattern.matchEntire(line.text) else valuePattern.matchEntire(line.text)
|
||||
val raw = match?.groupValues?.get(1)?.takeIf { it.isNotEmpty() } ?: continue
|
||||
val value = raw.replace('O', '0').replace('o', '0').toIntOrNull() ?: return null
|
||||
if (value !in 0..100) return null
|
||||
values += value
|
||||
}
|
||||
return values.singleOrNull()
|
||||
}
|
||||
|
||||
private fun normalize(text: String): String = buildString {
|
||||
for (char in text) {
|
||||
if (char.isWhitespace() || Character.isSpaceChar(char)) continue
|
||||
append(if (char in '0'..'9') (char.code - 0xFEE0).toChar() else char)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,145 +1,31 @@
|
||||
package com.haorui.app.ocr
|
||||
|
||||
import android.graphics.Rect
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import com.haorui.app.automation.RunLogger
|
||||
|
||||
/**
|
||||
* 信用分 OCR 文本解析。约束分数范围与匹配上下文,避免把播放时长等无关数字当作信用分。
|
||||
*/
|
||||
/** 读取完整页面的 OCR 行与位置;限定信用分卡片,不记录账户页面全文。 */
|
||||
object CreditScoreReader {
|
||||
|
||||
private const val TAG = "HaoRui-Credit"
|
||||
|
||||
/**
|
||||
* 严格正则(对照原 `CreditScoreParser.f308a` + **matches() 整串语义**):
|
||||
* 整个字符串必须是 `信用分 100` / `100分` / `100` 形,不能从长文里 find。
|
||||
* ⚠️ 2026-10-31 长测实测:原 find() + 「前缀/后缀都可选」会把 **时钟「11:59」**
|
||||
* 的 11 当成信用分,误判 BLOCKED 锁死当天任务。对齐原 matches()。
|
||||
*/
|
||||
private val SCORE_WHOLE = Regex(
|
||||
"""(?:(?:信\s*用\s*分(?:\s*数)?|信\s*用\s*评\s*分)\s*[::]?\s*)?([0-9]{1,3})\s*分?""",
|
||||
)
|
||||
|
||||
/** 宽松正则(对照原 `CreditScoreParser.b`):**必须带「分」**,且处理 O/o 混淆 */
|
||||
private val LOOSE_PATTERN = Regex("""(?<![0-9Oo])([0-9Oo]{1,3})\s*分(?![0-9])""")
|
||||
|
||||
/** 信用分有效范围 */
|
||||
const val MIN_CREDIT = 0
|
||||
const val MAX_CREDIT = 100
|
||||
|
||||
/**
|
||||
* 归一化 OCR 文本(对照原 `CreditScoreParser.extractScoreText` + `b()`):
|
||||
* 全角数字/冒号转半角、去空白、O/o→0。
|
||||
*/
|
||||
private fun normalize(raw: String): String {
|
||||
val sb = StringBuilder(raw.length)
|
||||
var lastWasSpace = false
|
||||
for (ch in raw) {
|
||||
if (Character.isWhitespace(ch) || Character.isSpaceChar(ch)) {
|
||||
if (sb.isNotEmpty()) lastWasSpace = true
|
||||
continue
|
||||
}
|
||||
if (lastWasSpace && sb.isNotEmpty()) sb.append(' ')
|
||||
lastWasSpace = false
|
||||
// 全角数字 0-9 → 半角
|
||||
val c = if (ch in '0'..'9') (ch.code - 0xFEE0).toChar() else ch
|
||||
// 全角冒号/斜杠 → 半角(时长解析用)
|
||||
val c2 = when (c) {
|
||||
':' -> ':'
|
||||
'/' -> '/'
|
||||
else -> c
|
||||
}
|
||||
sb.append(c2)
|
||||
}
|
||||
return sb.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 OCR 文本提取信用分(对照原 `CreditScoreParser.parseScore` / `parseScoreLoose`)。
|
||||
*
|
||||
* 否决链(任一命中返回 null):
|
||||
* 1. 含「扣分/已扣/处罚」
|
||||
* 2. 含负分 `…-N 分…`
|
||||
* 3. 含加分 `…+N 分…`
|
||||
* 4. 多个**不同**数值冲突
|
||||
* 5. 超出 0~100
|
||||
*
|
||||
* 匹配语义(⚠️ 2026-10-31 长测实测必须收紧):
|
||||
* - 严格通道:**整行** matches(原 f308a + matches()),不能从长文 find
|
||||
* - 宽松通道:**必须带「分」**(原 b),否则「11:59」的 11 会误命中
|
||||
*
|
||||
* @param ocrText OCR 识别出的全文
|
||||
* @return 信用分(0~100),未识别/被否决返回 null
|
||||
*/
|
||||
fun extractCreditScore(ocrText: String): Int? {
|
||||
val text = normalize(ocrText)
|
||||
if (text.isEmpty()) return null
|
||||
|
||||
// ── 否决:扣分/处罚/加减分(对照原 parseScore 顶部 if)──
|
||||
val flat = text.replace(" ", "")
|
||||
if (flat.contains("扣分") || flat.contains("已扣") || flat.contains("处罚")) {
|
||||
RunLogger.w(TAG, "OCR 含扣分/处罚字样,否决信用分识别")
|
||||
return null
|
||||
}
|
||||
if (Regex("""[+\+]\s*[0-9Oo]{1,3}\s*分?""").containsMatchIn(flat) ||
|
||||
Regex("""[\--−–—]\s*[0-9Oo]{1,3}\s*分?""").containsMatchIn(flat)
|
||||
) {
|
||||
RunLogger.w(TAG, "OCR 含加减分字样,否决信用分识别")
|
||||
return null
|
||||
}
|
||||
|
||||
// ── 宽松通道:必须带「分」的 token(对照原 parseScoreLoose)──
|
||||
val found = LinkedHashSet<Int>()
|
||||
for (m in LOOSE_PATTERN.findAll(text)) {
|
||||
val v = m.groupValues[1].replace('O', '0').replace('o', '0').toIntOrNull()
|
||||
?: continue
|
||||
if (v in MIN_CREDIT..MAX_CREDIT) found.add(v)
|
||||
}
|
||||
if (found.size > 1) {
|
||||
RunLogger.w(TAG, "OCR 多值冲突 $found,否决信用分识别")
|
||||
return null
|
||||
}
|
||||
if (found.size == 1) {
|
||||
val score = found.first()
|
||||
RunLogger.i(TAG, "识别到信用分: $score(宽松通道)")
|
||||
return score
|
||||
}
|
||||
|
||||
// ── 严格通道:整行 matches(原 f308a + matcher.matches())──
|
||||
// 只在**单行本身就是分数形**时才认,绝不从长文里抠数字
|
||||
for (rawLine in text.split('\n', '|')) {
|
||||
val line = rawLine.trim()
|
||||
if (line.isEmpty()) continue
|
||||
val m = SCORE_WHOLE.matchEntire(line) ?: continue
|
||||
val v = m.groupValues[1].toIntOrNull() ?: continue
|
||||
if (v in MIN_CREDIT..MAX_CREDIT) {
|
||||
RunLogger.i(TAG, "识别到信用分: $v(严格整行)")
|
||||
return v
|
||||
}
|
||||
}
|
||||
RunLogger.w(TAG, "未能从 OCR 文本识别信用分")
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 从截图识别信用分。
|
||||
* @param capturer 截图器
|
||||
* @param region 信用分所在区域(屏幕坐标,null = 全屏搜索)
|
||||
* @return 信用分
|
||||
*/
|
||||
suspend fun readFromScreen(capturer: ScreenCapturer, region: Rect? = null): Int? {
|
||||
val text = capturer.captureAndRecognize(region)
|
||||
// 观测点(装机实测):区分「截屏失败(空文本)」与「截到但正则不中」两种死因
|
||||
if (text.isBlank()) {
|
||||
RunLogger.w(TAG, "OCR 文本为空(截屏失败或无文字内容)")
|
||||
} else {
|
||||
// 校准用:打全文(换行压平),真机正则校准需看完整识别结果
|
||||
RunLogger.i(TAG, "OCR 全文(${text.length} 字)=${text.replace('\n', '|')}")
|
||||
}
|
||||
return extractCreditScore(text)
|
||||
val bitmap = capturer.capture() ?: return null
|
||||
return try {
|
||||
val lines = OcrProcessor.recognize(bitmap).flatMap { block ->
|
||||
block.lines.mapNotNull { line ->
|
||||
val box = line.boundingBox ?: return@mapNotNull null
|
||||
CreditScoreParser.Line(line.text, CreditScoreParser.Area(box.left, box.top, box.right, box.bottom))
|
||||
}
|
||||
}
|
||||
kotlinx.coroutines.currentCoroutineContext().ensureActive()
|
||||
val area = region?.let { CreditScoreParser.Area(it.left, it.top, it.right, it.bottom) }
|
||||
val score = CreditScoreParser.extract(lines, bitmap.width, bitmap.height, area)
|
||||
if (score == null) RunLogger.w(TAG, "未能核对处罚中心信用分卡片(OCR 行数=${lines.size})")
|
||||
else RunLogger.i(TAG, "已核对处罚中心信用分:$score")
|
||||
score
|
||||
} finally { bitmap.recycle() }
|
||||
}
|
||||
}
|
||||
|
||||
object EarningsReader {
|
||||
|
||||
private const val TAG = "HaoRui-Earnings"
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.haorui.app.ocr
|
||||
|
||||
import android.graphics.Bitmap
|
||||
|
||||
/**
|
||||
* MediaProjection 截屏器(抖音专用,2026-11-17 r20~r24 定案的缓存绕行)。
|
||||
*
|
||||
* 与 [ScreenCapturer] 的 capture() 签名对齐:调用方先试本类(实时帧),
|
||||
* 返回 null(未授权/无帧)回退 takeScreenshot(fail-open)。
|
||||
* 头条/微博不受截图缓存影响,继续用 ScreenCapturer——不改动它们的链路。
|
||||
*/
|
||||
object ProjectionCapturer {
|
||||
|
||||
/**
|
||||
* 取当前屏幕实时帧。
|
||||
* @return 投影未就绪/无新帧返回 null(调用方回退无障碍截图)
|
||||
*/
|
||||
fun capture(): Bitmap? {
|
||||
if (!ProjectionHolder.isReady) return null
|
||||
return ProjectionHolder.captureLatest()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package com.haorui.app.ocr
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.PixelFormat
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.hardware.display.VirtualDisplay
|
||||
import android.media.Image
|
||||
import android.media.ImageReader
|
||||
import android.media.projection.MediaProjection
|
||||
import android.media.projection.MediaProjectionManager
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import android.util.DisplayMetrics
|
||||
import android.view.WindowManager
|
||||
import com.haorui.app.automation.RunLogger
|
||||
|
||||
/**
|
||||
* MediaProjection 投影持有者(单例)。
|
||||
*
|
||||
* 背景(2026-11-17 r20~r24 定案):抖音对无障碍 takeScreenshot 通道主动缓存,
|
||||
* 服务内树/截屏在搜索页永远读到旧帧——MediaProjection 走独立 SurfaceFlinger
|
||||
* 通道拿实时帧,完全绕开该防护。
|
||||
*
|
||||
* 生命周期:授权一次(用户在系统弹窗点同意)→ createProjection 持有
|
||||
* VirtualDisplay+ImageReader → 抖音采集期间按需取帧 → stopProjection 释放。
|
||||
* ⚠️ Android 14+ 投影在 App 进程重启后失效(系统回收),需重新授权——
|
||||
* 失效时 capture() 返回 null,调用方回退无障碍截图(fail-open)。
|
||||
*
|
||||
* 授权结果 Intent 由 MainActivity 的系统弹窗回调传入(用户亲手操作)。
|
||||
*/
|
||||
object ProjectionHolder {
|
||||
private const val TAG = "HaoRui-Projection"
|
||||
|
||||
@Volatile private var projection: MediaProjection? = null
|
||||
@Volatile private var virtualDisplay: VirtualDisplay? = null
|
||||
@Volatile private var imageReader: ImageReader? = null
|
||||
@Volatile private var callbackThread: HandlerThread? = null
|
||||
@Volatile private var width = 0
|
||||
@Volatile private var height = 0
|
||||
|
||||
/**
|
||||
* 监听器持有的最新帧(消费式:ImageReader 队列必须被消费才有新帧,
|
||||
* acquireLatestImage 惰性模式在无消费时拿不到帧——r25 实证)。
|
||||
* ⚠️ 回调线程写、capture 读——必须加锁防「回收中的位图被拷贝」竞态(r29 崩溃实证)。
|
||||
*/
|
||||
private val frameLock = Any()
|
||||
private var latestBitmap: Bitmap? = null
|
||||
private var frameCount = 0
|
||||
|
||||
/** 投影是否就绪(可取帧) */
|
||||
val isReady: Boolean
|
||||
get() = imageReader != null && projection != null
|
||||
|
||||
/** 当前投影实例(用于 onStop 回调识别:旧投影的迟到回调不得清掉新投影的状态) */
|
||||
@Volatile private var currentProjection: MediaProjection? = null
|
||||
|
||||
/**
|
||||
* 用系统弹窗授权结果创建投影。
|
||||
* @param resultCode onActivityResult 的 resultCode
|
||||
* @param data onActivityResult 的 data(含授权令牌)
|
||||
* @return 创建是否成功(用户拒绝/令牌无效返回 false)
|
||||
*/
|
||||
fun createProjection(context: Context, resultCode: Int, data: Intent): Boolean {
|
||||
stopProjection() // 先清理旧投影
|
||||
return try {
|
||||
val manager = context.getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
|
||||
val p = manager.getMediaProjection(resultCode, data) ?: return false
|
||||
val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
|
||||
val metrics: DisplayMetrics = DisplayMetrics()
|
||||
@Suppress("DEPRECATION")
|
||||
wm.defaultDisplay.getRealMetrics(metrics)
|
||||
width = metrics.widthPixels
|
||||
height = metrics.heightPixels
|
||||
// 帧回调在独立线程(ImageReader 要求非主线程 Handler)
|
||||
val thread = HandlerThread("haorui-projection").apply { start() }
|
||||
callbackThread = thread
|
||||
val reader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2)
|
||||
// 消费式监听:每来一帧立即转 Bitmap 存 latestBitmap(不消费队列会停摆,r25 实证)
|
||||
reader.setOnImageAvailableListener({
|
||||
val img = try { reader.acquireLatestImage() } catch (_: Exception) { null }
|
||||
if (img != null) {
|
||||
try {
|
||||
convertImage(img)?.let { bmp ->
|
||||
synchronized(frameLock) {
|
||||
latestBitmap?.recycle()
|
||||
latestBitmap = bmp
|
||||
frameCount++
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
RunLogger.w(TAG, "帧转换异常: ${e.javaClass.simpleName}:${e.message}")
|
||||
} finally {
|
||||
runCatching { img.close() }
|
||||
}
|
||||
}
|
||||
}, Handler(thread.looper))
|
||||
val display = p.createVirtualDisplay(
|
||||
"haorui-capture", width, height, metrics.densityDpi,
|
||||
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
|
||||
reader.surface, null, null,
|
||||
)
|
||||
projection = p
|
||||
currentProjection = p
|
||||
virtualDisplay = display
|
||||
imageReader = reader
|
||||
// 投影停止回调:**只认当前投影**——旧投影的迟到 onStop 不得清掉新投影状态
|
||||
//(r26 崩溃实证:旧投影 onStop 排队到新投影创建后执行,把新投影连带清空)
|
||||
p.registerCallback(object : MediaProjection.Callback() {
|
||||
override fun onStop() {
|
||||
if (currentProjection === p) {
|
||||
RunLogger.w(TAG, "MediaProjection 被停止(通知栏/系统回收),清空持有状态")
|
||||
stopProjection()
|
||||
} else {
|
||||
RunLogger.i(TAG, "旧投影 onStop 迟到回调(已换代),忽略")
|
||||
}
|
||||
}
|
||||
}, Handler(thread.looper))
|
||||
RunLogger.i(TAG, "MediaProjection 就绪 ${width}x${height}")
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
RunLogger.w(TAG, "创建投影失败: ${e.javaClass.simpleName}:${e.message}")
|
||||
stopProjection()
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取最新帧位图(监听器持续消费帧存 latestBitmap,capture 直接取现成的)。
|
||||
* @return 无投影/尚无帧返回 null(调用方回退 takeScreenshot)
|
||||
*/
|
||||
fun captureLatest(): Bitmap? {
|
||||
if (imageReader == null) return null
|
||||
synchronized(frameLock) {
|
||||
val bmp = latestBitmap ?: run {
|
||||
RunLogger.w(TAG, "投影尚无帧(frameCount=$frameCount,VirtualDisplay 未渲染或队列未消费)")
|
||||
return null
|
||||
}
|
||||
// 返回副本:latestBitmap 会被下一帧替换回收,调用方持有必须独立
|
||||
val copy = bmp.copy(Bitmap.Config.ARGB_8888, false)
|
||||
if (frameCount % 30 == 0) RunLogger.i(TAG, "投影取帧 #${frameCount} → ${copy.width}x${copy.height}")
|
||||
return copy
|
||||
}
|
||||
}
|
||||
|
||||
/** Image → Bitmap(RGBA_8888 → ARGB_8888,处理行 padding)。img 由调用方 close。 */
|
||||
private fun convertImage(image: Image): Bitmap? {
|
||||
return try {
|
||||
val plane = image.planes[0]
|
||||
val rowStride = plane.rowStride
|
||||
val pixelStride = plane.pixelStride
|
||||
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
|
||||
val buffer = plane.buffer
|
||||
if (rowStride == width * pixelStride) {
|
||||
buffer.rewind()
|
||||
bitmap.copyPixelsFromBuffer(buffer)
|
||||
} else {
|
||||
buffer.rewind()
|
||||
val packed = java.nio.ByteBuffer.allocate(width * height * pixelStride)
|
||||
val rowBytes = ByteArray(width * pixelStride)
|
||||
for (row in 0 until height) {
|
||||
buffer.position(row * rowStride)
|
||||
buffer.get(rowBytes)
|
||||
packed.put(rowBytes)
|
||||
}
|
||||
packed.rewind()
|
||||
bitmap.copyPixelsFromBuffer(packed)
|
||||
}
|
||||
bitmap
|
||||
} catch (e: Exception) {
|
||||
RunLogger.w(TAG, "帧转位图失败: ${e.javaClass.simpleName}:${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/** 释放全部资源(幂等)。 */
|
||||
fun stopProjection() {
|
||||
runCatching { imageReader?.close() }
|
||||
runCatching { virtualDisplay?.release() }
|
||||
runCatching { projection?.stop() }
|
||||
imageReader = null
|
||||
virtualDisplay = null
|
||||
projection = null
|
||||
currentProjection = null
|
||||
latestBitmap?.recycle()
|
||||
latestBitmap = null
|
||||
callbackThread?.quitSafely()
|
||||
callbackThread = null
|
||||
}
|
||||
}
|
||||
@@ -91,7 +91,8 @@ class ScreenCapturer(private val service: AccessibilityService) {
|
||||
} else {
|
||||
RunLogger.w(TAG, "截屏回调成功但位图转换失败(wrapHardwareBuffer/copy)")
|
||||
}
|
||||
if (cont.isActive) cont.resume(bmp)
|
||||
if (cont.isActive) cont.resume(bmp, onCancellation = { _, value, _ -> value?.recycle() })
|
||||
else bmp?.recycle()
|
||||
}
|
||||
|
||||
override fun onFailure(errorCode: Int) {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.haorui.app.pipeline
|
||||
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.util.UUID
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.decodeFromString
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
/** 草稿点击前落盘;未得到当前编辑器的明确回执前,缓存清理和失败分支不得删除素材。 */
|
||||
class PendingDraftStore(private val directory: File) {
|
||||
@Serializable
|
||||
data class Attempt(val id: String, val mediaPath: String, val title: String, val declaration: String, val createdAtMs: Long)
|
||||
|
||||
@Synchronized fun begin(mediaPath: String, title: String, declaration: String): Attempt {
|
||||
require(title.isNotBlank() && declaration.isNotBlank())
|
||||
val path = File(mediaPath).canonicalPath
|
||||
require(File(path).isFile)
|
||||
check(attempts().none { it.mediaPath == path }) { "该素材已有待核对草稿" }
|
||||
check(directory.isDirectory || directory.mkdirs())
|
||||
val attempt = Attempt(UUID.randomUUID().toString(), path, title, declaration, System.currentTimeMillis())
|
||||
val temporary = File(directory, "${attempt.id}.tmp")
|
||||
try {
|
||||
FileOutputStream(temporary).use { output ->
|
||||
output.write(Json.encodeToString(attempt).toByteArray(Charsets.UTF_8))
|
||||
output.fd.sync()
|
||||
}
|
||||
check(temporary.renameTo(File(directory, "${attempt.id}.json"))) { "草稿日志保存失败" }
|
||||
} finally { temporary.delete() }
|
||||
return attempt
|
||||
}
|
||||
|
||||
@Synchronized fun attempts(): List<Attempt> {
|
||||
if (!directory.exists()) return emptyList()
|
||||
val files = checkNotNull(directory.listFiles()) { "草稿日志不可读" }
|
||||
return files.filter { it.extension == "json" }.map { file ->
|
||||
Json.decodeFromString<Attempt>(file.readText()).also { check(file.name == "${it.id}.json") }
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized fun protectedPaths(): Set<String> = attempts().map { it.mediaPath }.toSet()
|
||||
|
||||
@Synchronized fun confirm(id: String): Boolean {
|
||||
val attempt = attempts().singleOrNull { it.id == id } ?: return false
|
||||
return File(directory, "${attempt.id}.json").delete()
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,42 @@ class VideoDownloader(private val context: Context) {
|
||||
/** 视频存储目录 */
|
||||
private val videoDir: File = File(context.getExternalFilesDir("videos") ?: context.filesDir, "videos").apply { mkdirs() }
|
||||
|
||||
private val pendingDrafts = PendingDraftStore(File(context.filesDir, "pending-drafts"))
|
||||
|
||||
/** 跨平台素材导入目录(M5 SourceMediaProvider 落盘处;与 videoDir 同受待核对保护)。 */
|
||||
private val crossVideoDir: File = File(context.filesDir, "crossplatform/video")
|
||||
|
||||
fun beginDraft(path: String, title: String, declaration: String): String {
|
||||
check(File(path).canonicalFile.parentFile == videoDir.canonicalFile) { "草稿素材不在下载目录" }
|
||||
return pendingDrafts.begin(path, title, declaration).id
|
||||
}
|
||||
|
||||
/**
|
||||
* 跨平台素材的草稿意图登记(M5,2026-11-15):素材在 crossplatform 导入目录也接受。
|
||||
* 与 [beginDraft] 同用 PendingDraftStore(待核对保护语义一致);目录校验放宽为
|
||||
* 旧下载目录**或** crossplatform/video——仍防任意路径注入,非放开。
|
||||
*/
|
||||
fun beginDraftCrossPlatform(path: String, title: String, declaration: String): String {
|
||||
val parent = runCatching { File(path).canonicalFile.parentFile }.getOrNull()
|
||||
check(parent == videoDir.canonicalFile || parent == crossVideoDir.canonicalFile) {
|
||||
"草稿素材不在受管目录(videoDir/crossplatform)"
|
||||
}
|
||||
return pendingDrafts.begin(path, title, declaration).id
|
||||
}
|
||||
|
||||
fun confirmDraft(id: String): Boolean = pendingDrafts.confirm(id)
|
||||
|
||||
fun hasPendingDrafts(): Boolean = pendingDrafts.attempts().isNotEmpty()
|
||||
|
||||
fun isOwnedMedia(path: String): Boolean = runCatching {
|
||||
File(path).isFile && File(path).canonicalFile.parentFile == videoDir.canonicalFile
|
||||
}.getOrDefault(false)
|
||||
|
||||
/** 素材是否为跨平台导入目录(M5;beginDraftCrossPlatform 的路径判定用)。 */
|
||||
fun isCrossPlatformMedia(path: String): Boolean = runCatching {
|
||||
File(path).isFile && File(path).canonicalFile.parentFile == crossVideoDir.canonicalFile
|
||||
}.getOrDefault(false)
|
||||
|
||||
/**
|
||||
* 已下载内容的 SHA-256 集合(内容级去重)。
|
||||
* ⚠️ 并发安全:管线多协程可能并行下载/查重(第一性审计)→ 线程安全 Set。
|
||||
@@ -304,11 +340,12 @@ class VideoDownloader(private val context: Context) {
|
||||
*/
|
||||
@Synchronized
|
||||
fun clearDownloadCache(exclude: Set<String> = emptySet()): Int {
|
||||
val protected = try { exclude + pendingDrafts.protectedPaths() } catch (_: Exception) { return 0 }
|
||||
var n = 0
|
||||
val cutoff = System.currentTimeMillis() - 24 * 60 * 60 * 1000L
|
||||
videoDir.listFiles()?.forEach { f ->
|
||||
if (f.isFile && (f.name.endsWith(".mp4") || f.name.endsWith(".tmp")) &&
|
||||
f.lastModified() < cutoff && f.absolutePath !in exclude
|
||||
f.lastModified() < cutoff && f.canonicalPath !in protected && f.absolutePath !in protected
|
||||
) {
|
||||
if (f.delete()) n++
|
||||
}
|
||||
@@ -371,6 +408,7 @@ class VideoDownloader(private val context: Context) {
|
||||
fun deleteVideo(filePath: String): Boolean {
|
||||
return try {
|
||||
val f = File(filePath)
|
||||
if (f.canonicalPath in pendingDrafts.protectedPaths()) return false
|
||||
if (f.exists()) f.delete() else false
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
|
||||
@@ -285,7 +285,8 @@ class QuotaManager(
|
||||
@Synchronized
|
||||
fun snapshotState(): String {
|
||||
val remainRest = maxOf(0L, (restUntilMs - clock.millis()) / 1000)
|
||||
return segmentCounts.joinToString(",") + "|" + remainRest + "|" + lastResetAtMs
|
||||
// 第 4 段=保存时刻(M6 长跑修复:恢复时按 savedAt 折算绝对截止,防跨重启休息期续命)
|
||||
return segmentCounts.joinToString(",") + "|" + remainRest + "|" + lastResetAtMs + "|" + clock.millis()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -303,14 +304,48 @@ class QuotaManager(
|
||||
for (i in 0..3) {
|
||||
segs.getOrNull(i)?.toIntOrNull()?.let { segmentCounts[i] = maxOf(0, it) }
|
||||
}
|
||||
parts.getOrNull(1)?.toLongOrNull()?.let { remainSec ->
|
||||
if (remainSec > 0) {
|
||||
restUntilMs = clock.millis() + remainSec * 1000L
|
||||
log("休息期已恢复: 剩余 ${remainSec}s")
|
||||
// ⚠️ M6 长跑发现(2026-11-16):快照存"剩余秒数"(相对量),恢复时 now+remainSec
|
||||
// 会把旧进程的休息期**重新从头计时**——昨晚保存的"剩余 537s"今早恢复成
|
||||
// "现在+537s",休息期凭空续命。
|
||||
// 修复(兼容三态):
|
||||
// ① 第 4 段=保存时刻(新格式):按 savedAt 折算绝对截止——now > savedAt+remain
|
||||
// 则已过期丢弃,否则按剩余差额续;
|
||||
// ② 无第 4 段但有第 3 段(旧三段格式):同配额期保守保留(原语义),跨期丢弃;
|
||||
// ③ 两段旧格式:保守保留(既有用例钉住的兼容语义)。
|
||||
val snapResetAt = parts.getOrNull(2)?.toLongOrNull()?.takeIf { it > 0 }
|
||||
val savedAt = parts.getOrNull(3)?.toLongOrNull()?.takeIf { it > 0 }
|
||||
val remainSec = parts.getOrNull(1)?.toLongOrNull() ?: 0L
|
||||
val currentResetPoint = lastResetPointMs(clock.millis())
|
||||
when {
|
||||
// ① 新格式:按保存时刻折算绝对截止
|
||||
savedAt != null -> {
|
||||
val absoluteUntil = savedAt + remainSec * 1000L
|
||||
val now = clock.millis()
|
||||
if (remainSec > 0 && absoluteUntil > now) {
|
||||
restUntilMs = absoluteUntil
|
||||
log("休息期已恢复: 剩余 ${(absoluteUntil - now) / 1000}s(按快照时刻折算)")
|
||||
} else if (remainSec > 0) {
|
||||
log("休息期快照已过期(保存于 ${savedAt},截止 ${absoluteUntil} < now),丢弃")
|
||||
}
|
||||
}
|
||||
// ② 旧三段:同配额期保守保留
|
||||
snapResetAt != null -> {
|
||||
if (remainSec > 0 && kotlin.math.abs(snapResetAt - currentResetPoint) <= 60_000L) {
|
||||
restUntilMs = clock.millis() + remainSec * 1000L
|
||||
log("休息期已恢复: 剩余 ${remainSec}s(同配额期保守恢复)")
|
||||
} else if (remainSec > 0) {
|
||||
log("休息期快照跨配额期,丢弃")
|
||||
}
|
||||
}
|
||||
// ③ 两段旧格式:保守保留(兼容既有快照)
|
||||
else -> {
|
||||
if (remainSec > 0) {
|
||||
restUntilMs = clock.millis() + remainSec * 1000L
|
||||
log("休息期已恢复: 剩余 ${remainSec}s(旧格式保守恢复)")
|
||||
}
|
||||
}
|
||||
}
|
||||
lastResetAtMs = parts.getOrNull(2)?.toLongOrNull()
|
||||
?.takeIf { it > 0 } ?: lastResetPointMs(clock.millis())
|
||||
lastResetAtMs = snapResetAt ?: currentResetPoint
|
||||
}
|
||||
|
||||
// ── 内部逻辑 ──────────────────────────────────────────────
|
||||
|
||||
@@ -28,6 +28,7 @@ import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
@@ -523,6 +524,83 @@ fun DropdownField(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 下拉多选框:点击展开候选列表,逐项勾选/取消。
|
||||
* 用于「微博热搜类目」这类需要从固定清单中多选的字段;已选为空时显示占位提示。
|
||||
*/
|
||||
@Composable
|
||||
fun MultiSelectDropdownField(
|
||||
label: String,
|
||||
selectedIds: Set<String>,
|
||||
options: List<Pair<String, String>>,
|
||||
onToggle: (String) -> Unit,
|
||||
onClear: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
placeholder: String = "未选择",
|
||||
help: String? = null,
|
||||
) {
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
val summary = options.filter { it.first in selectedIds }.joinToString("、") { it.second }.ifBlank { placeholder }
|
||||
Column(modifier = modifier) {
|
||||
Text(
|
||||
text = label,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Box(modifier = Modifier.padding(top = 4.dp)) {
|
||||
OutlinedTextField(
|
||||
value = summary,
|
||||
onValueChange = {},
|
||||
readOnly = true,
|
||||
trailingIcon = {
|
||||
Icon(
|
||||
imageVector = if (expanded) Icons.Filled.KeyboardArrowUp
|
||||
else Icons.Filled.KeyboardArrowDown,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.clickable { expanded = !expanded },
|
||||
)
|
||||
},
|
||||
shape = RoundedCornerShape(10.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.matchParentSize()
|
||||
.clickable { expanded = !expanded }
|
||||
)
|
||||
DropdownMenu(
|
||||
expanded = expanded,
|
||||
onDismissRequest = { expanded = false },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
options.forEach { (id, text) ->
|
||||
DropdownMenuItem(
|
||||
text = {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Checkbox(checked = id in selectedIds, onCheckedChange = { onToggle(id) })
|
||||
Text(text)
|
||||
}
|
||||
},
|
||||
onClick = { onToggle(id) },
|
||||
)
|
||||
}
|
||||
if (options.isNotEmpty()) {
|
||||
HorizontalDivider()
|
||||
DropdownMenuItem(
|
||||
text = { Text("清空选择", color = MaterialTheme.colorScheme.error) },
|
||||
onClick = {
|
||||
onClear()
|
||||
expanded = false
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (help != null) FieldHelp(help)
|
||||
}
|
||||
}
|
||||
|
||||
/** 勾选项 */
|
||||
@Composable
|
||||
fun CheckRow(
|
||||
|
||||
@@ -42,18 +42,13 @@ import com.haorui.app.crossplatform.data.CrossPublishTaskStore
|
||||
import com.haorui.app.crossplatform.ui.CrossAutomationScreen
|
||||
import com.haorui.app.crossplatform.ui.CrossTasksScreen
|
||||
import com.haorui.app.crossplatform.ui.SourcesScreen
|
||||
import com.haorui.app.crossplatform.ui.TopicFiltersScreen
|
||||
import com.haorui.app.crossplatform.ui.TopicsScreen
|
||||
import com.haorui.app.crossplatform.ui.rememberSourceVersions
|
||||
import com.haorui.app.data.model.AppConfig
|
||||
import com.haorui.app.data.model.CollectMode
|
||||
import com.haorui.app.ui.screens.A11yScreen
|
||||
import com.haorui.app.ui.screens.ApiScreen
|
||||
import com.haorui.app.ui.screens.BaiduConfigScreen
|
||||
import com.haorui.app.ui.screens.BrowseScreen
|
||||
import com.haorui.app.ui.screens.CollectScreen
|
||||
import com.haorui.app.ui.screens.HomeScreen
|
||||
import com.haorui.app.ui.screens.InteractScreen
|
||||
import com.haorui.app.ui.screens.LogsScreen
|
||||
import com.haorui.app.ui.screens.MineScreen
|
||||
import com.haorui.app.ui.screens.ToutiaoConfigScreen
|
||||
@@ -63,15 +58,11 @@ import kotlinx.coroutines.launch
|
||||
object Routes {
|
||||
const val HOME = "home"
|
||||
const val COLLECT = "collect"
|
||||
const val TOPICS = "topics"
|
||||
const val TASKS = "tasks"
|
||||
const val CROSS_SOURCES = "cross_sources"
|
||||
const val CROSS_FILTERS = "cross_filters"
|
||||
const val CROSS_AUTOMATION = "cross_automation"
|
||||
const val INTERACT = "interact"
|
||||
const val MINE = "mine"
|
||||
const val TOUTIAO = "toutiao"
|
||||
const val BAIDU = "baidu"
|
||||
const val API = "api"
|
||||
const val BROWSE = "browse"
|
||||
const val LOGS = "logs"
|
||||
@@ -81,15 +72,11 @@ object Routes {
|
||||
val titles = mapOf(
|
||||
HOME to "浩瑞",
|
||||
COLLECT to "采集",
|
||||
TOPICS to "热点",
|
||||
TASKS to "任务",
|
||||
CROSS_SOURCES to "来源 App 管理",
|
||||
CROSS_FILTERS to "选题筛选",
|
||||
CROSS_AUTOMATION to "自动化设置",
|
||||
INTERACT to "互动",
|
||||
MINE to "我的",
|
||||
TOUTIAO to "头条采集设置",
|
||||
BAIDU to "百度采集设置",
|
||||
API to "解析 / 大模型",
|
||||
BROWSE to "定时浏览",
|
||||
LOGS to "任务记录",
|
||||
@@ -100,10 +87,8 @@ object Routes {
|
||||
val subtitles = mapOf(
|
||||
HOME to "今日头条 18.3.0 · 全流程自动采集发布",
|
||||
COLLECT to "选择采集源并进入详细参数",
|
||||
INTERACT to "新粉谢谢关注 / 随机回关 · 每日配额",
|
||||
MINE to "设置入口与本机数据管理",
|
||||
TOUTIAO to "18 项筛选参数 · 类目 / 作品声明",
|
||||
BAIDU to "com.baidu.searchbox · 采集后转头条发布",
|
||||
API to "标题改写供应商 · 解析线路",
|
||||
BROWSE to "发布休息期浏览 · 停留时长随机",
|
||||
LOGS to "运行日志 · 诊断导出",
|
||||
@@ -111,12 +96,11 @@ object Routes {
|
||||
)
|
||||
|
||||
/** 底部 tab */
|
||||
val tabs = listOf(HOME, TOPICS, TASKS, INTERACT, MINE)
|
||||
val tabs = listOf(HOME, TASKS, MINE)
|
||||
|
||||
/** 路由 → 所属 tab(用于返回键回落) */
|
||||
fun tabOf(route: String): String = when (route) {
|
||||
TOUTIAO, BAIDU, COLLECT, API, BROWSE, LOGS, A11Y, CROSS_AUTOMATION -> MINE
|
||||
CROSS_SOURCES, CROSS_FILTERS -> TOPICS
|
||||
TOUTIAO, COLLECT, API, BROWSE, LOGS, A11Y, CROSS_AUTOMATION -> MINE
|
||||
else -> route
|
||||
}
|
||||
}
|
||||
@@ -125,9 +109,7 @@ private data class TabDef(val route: String, val label: String, val icon: ImageV
|
||||
|
||||
private val tabDefs = listOf(
|
||||
TabDef(Routes.HOME, "首页", Icons.Filled.Home),
|
||||
TabDef(Routes.TOPICS, "热点", Icons.Filled.AutoAwesome),
|
||||
TabDef(Routes.TASKS, "任务", Icons.Filled.Assignment),
|
||||
TabDef(Routes.INTERACT, "互动", Icons.Filled.Settings),
|
||||
TabDef(Routes.MINE, "我的", Icons.Filled.Person),
|
||||
)
|
||||
|
||||
@@ -164,6 +146,26 @@ fun HaoRuiApp(config: AppConfig, onConfigChange: (AppConfig) -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 删除跨平台任务(UI 已做二次确认);素材文件在事务外按保护清单核对后删除 */
|
||||
fun deleteCrossTask(id: String) {
|
||||
scope.launch {
|
||||
val deleted = taskStore.deleteTask(id)
|
||||
if (deleted == null) {
|
||||
toast("任务不存在或已删除")
|
||||
return@launch
|
||||
}
|
||||
val protectedPaths = taskStore.protectedSubmissionMediaPaths() + taskStore.protectedLegacyMediaPaths()
|
||||
var removed = 0
|
||||
deleted.mediaPaths.forEach { path ->
|
||||
if (path !in protectedPaths) {
|
||||
runCatching { java.io.File(path).delete() }.onSuccess { if (it) removed++ }
|
||||
}
|
||||
}
|
||||
val skipped = deleted.mediaPaths.size - removed
|
||||
toast("已删除任务「${deleted.task.title.take(12)}」" + if (removed > 0) ",清理素材 $removed 个" + (if (skipped > 0) "(保护清单拦下 $skipped 个)" else "") else "")
|
||||
}
|
||||
}
|
||||
|
||||
/** 启动/停止自动化 —— 真正驱动无障碍服务 */
|
||||
fun setRunning(on: Boolean) {
|
||||
com.haorui.app.automation.RunLogger.i("UI", "setRunning($on) 被调用")
|
||||
@@ -247,20 +249,15 @@ fun HaoRuiApp(config: AppConfig, onConfigChange: (AppConfig) -> Unit) {
|
||||
onConfigChange = onConfigChange,
|
||||
crossTasks = crossTasks,
|
||||
crossTasksLoaded = crossTasksLoaded,
|
||||
crossTasksError = crossTasksError,
|
||||
)
|
||||
}
|
||||
composable(Routes.TOPICS) {
|
||||
TopicsScreen(config, crossTasks, crossTasksLoaded, crossTasksError) { nav.navigate(it) }
|
||||
}
|
||||
composable(Routes.TASKS) {
|
||||
CrossTasksScreen(crossTasks, crossTasksLoaded, crossTasksError) { nav.navigate(it) }
|
||||
CrossTasksScreen(crossTasks, crossTasksLoaded, crossTasksError, ::deleteCrossTask) { nav.navigate(it) }
|
||||
}
|
||||
composable(Routes.CROSS_SOURCES) {
|
||||
SourcesScreen(config, sourceVersions, onConfigChange, ::toast)
|
||||
}
|
||||
composable(Routes.CROSS_FILTERS) {
|
||||
TopicFiltersScreen(config, onConfigChange, ::toast)
|
||||
}
|
||||
composable(Routes.CROSS_AUTOMATION) {
|
||||
CrossAutomationScreen(config, onConfigChange, { nav.navigate(it) }, ::toast)
|
||||
}
|
||||
@@ -273,11 +270,10 @@ fun HaoRuiApp(config: AppConfig, onConfigChange: (AppConfig) -> Unit) {
|
||||
onConfigChange = onConfigChange,
|
||||
)
|
||||
}
|
||||
composable(Routes.INTERACT) {
|
||||
InteractScreen(config, onConfigChange, ::toast)
|
||||
}
|
||||
composable(Routes.MINE) {
|
||||
MineScreen(
|
||||
config = config,
|
||||
onConfigChange = onConfigChange,
|
||||
onNavigate = { nav.navigate(it) },
|
||||
onToast = ::toast,
|
||||
)
|
||||
@@ -285,9 +281,6 @@ fun HaoRuiApp(config: AppConfig, onConfigChange: (AppConfig) -> Unit) {
|
||||
composable(Routes.TOUTIAO) {
|
||||
ToutiaoConfigScreen(config, onConfigChange, ::toast)
|
||||
}
|
||||
composable(Routes.BAIDU) {
|
||||
BaiduConfigScreen(config, onConfigChange, ::toast) { nav.popBackStack() }
|
||||
}
|
||||
composable(Routes.API) {
|
||||
ApiScreen(config, onConfigChange, ::toast)
|
||||
}
|
||||
|
||||
@@ -137,104 +137,21 @@ fun ToutiaoConfigScreen(
|
||||
}
|
||||
|
||||
/**
|
||||
* 百度采集设置 — 11 项数值 + 频道 + 行为
|
||||
* 对照 docs/技术架构与代码说明.md
|
||||
* 互动设置区块(原「互动」tab 内容,2026-11-16 并入「我的」页)——
|
||||
* 新粉互动 / 信用分门控 / 评论辅助,三个 Section 平铺嵌入宿主页。
|
||||
*/
|
||||
@Composable
|
||||
fun BaiduConfigScreen(
|
||||
config: AppConfig,
|
||||
onConfigChange: (AppConfig) -> Unit,
|
||||
onToast: (String) -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
val ctx = androidx.compose.ui.platform.LocalContext.current
|
||||
val b = config.baidu
|
||||
fun upd(v: com.haorui.app.data.model.BaiduConfig) = onConfigChange(config.copy(baidu = v))
|
||||
|
||||
Column(
|
||||
modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState())
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
) {
|
||||
GuideBanner(
|
||||
text = "从百度抓内容,抓到后自动转到头条发布。适合头条选题不足时补充。",
|
||||
step = "i",
|
||||
)
|
||||
|
||||
Section(title = "目标 App") {
|
||||
StatusBanner("com.baidu.searchbox · 采集后转头条发布", StatusLevel.NEUTRAL)
|
||||
HaoRuiButton("检测百度 APP", {
|
||||
val installed = try {
|
||||
ctx.packageManager.getPackageInfo("com.baidu.searchbox", 0); true
|
||||
} catch (_: Exception) { false }
|
||||
val ver = try {
|
||||
ctx.packageManager.getPackageInfo("com.baidu.searchbox", 0).versionName
|
||||
} catch (_: Exception) { null }
|
||||
onToast(if (installed) "百度已安装 · 版本 ${ver ?: "未知"}" else "百度未安装,无法使用百度采集")
|
||||
}, Modifier.fillMaxWidth())
|
||||
}
|
||||
|
||||
Section(title = "数值参数", tag = "11 项") {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
NumberField("每日发布量", b.publishTotal, { upd(b.copy(publishTotal = it)) }, Modifier.weight(1f))
|
||||
NumberField("单轮完成阈值", b.completionLimit, { upd(b.copy(completionLimit = it)) }, Modifier.weight(1f))
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
NumberField("休息秒 · 下限", b.restMin, { upd(b.copy(restMin = it)) }, Modifier.weight(1f))
|
||||
NumberField("休息秒 · 上限", b.restMax, { upd(b.copy(restMax = it)) }, Modifier.weight(1f))
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
NumberField("未找到素材等待 · 下限", b.missRestMin, { upd(b.copy(missRestMin = it)) }, Modifier.weight(1f))
|
||||
NumberField("未找到素材等待 · 上限", b.missRestMax, { upd(b.copy(missRestMax = it)) }, Modifier.weight(1f))
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
NumberField("播放秒 · 下限", b.playMin, { upd(b.copy(playMin = it)) }, Modifier.weight(1f))
|
||||
NumberField("播放秒 · 上限", b.playMax, { upd(b.copy(playMax = it)) }, Modifier.weight(1f))
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
NumberField("视频时长上限", b.videoMax, { upd(b.copy(videoMax = it)) }, Modifier.weight(1f))
|
||||
NumberField("连续滑动次数上限", b.slideLimit, { upd(b.copy(slideLimit = it)) }, Modifier.weight(1f))
|
||||
}
|
||||
NumberField("每发布清缓存个数", b.cacheEvery, { upd(b.copy(cacheEvery = it)) })
|
||||
}
|
||||
|
||||
Section(title = "频道与行为") {
|
||||
CheckRow("热搜频道", b.categoryHot, { upd(b.copy(categoryHot = it)) })
|
||||
CheckRow("推荐频道", b.categoryRecommend, { upd(b.copy(categoryRecommend = it)) })
|
||||
CheckRow("影视频道", b.categoryFilm, { upd(b.copy(categoryFilm = it)) })
|
||||
CheckRow("仅采集视频", b.videoOnly, { }, note = "当前版本固定开启", enabled = false)
|
||||
CheckRow("使用所选大模型改写标题", b.rewriteTitle, { upd(b.copy(rewriteTitle = it)) })
|
||||
CheckRow("下载后转入头条发布流程", b.toToutiao, { upd(b.copy(toToutiao = it)) })
|
||||
ButtonRow {
|
||||
FieldHelp("修改后自动保存到本机")
|
||||
HaoRuiButton("‹ 返回首页", onBack, Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 互动设置 — 新粉互动 / 随机回关 / 信用分门控 / 评论辅助
|
||||
* 对照 docs/技术架构与代码说明.md
|
||||
*/
|
||||
@Composable
|
||||
fun InteractScreen(
|
||||
fun InteractSettingsSections(
|
||||
config: AppConfig,
|
||||
onConfigChange: (AppConfig) -> Unit,
|
||||
onToast: (String) -> Unit,
|
||||
) {
|
||||
val i = config.interact
|
||||
val c = config.credit
|
||||
val ctx = androidx.compose.ui.platform.LocalContext.current
|
||||
fun updI(v: com.haorui.app.data.model.InteractConfig) = onConfigChange(config.copy(interact = v))
|
||||
fun updC(v: com.haorui.app.data.model.CreditConfig) = onConfigChange(config.copy(credit = v))
|
||||
|
||||
Column(
|
||||
modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState())
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
) {
|
||||
Section(title = "每日新粉互动") {
|
||||
Section(title = "每日新粉互动") {
|
||||
CheckRow("每日启动前先执行新粉互动", i.dailyEnabled, { updI(i.copy(dailyEnabled = it)) })
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
NumberField("谢谢关注上限(0–20)", i.fanThanksMax,
|
||||
@@ -304,4 +221,3 @@ fun InteractScreen(
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,9 +32,9 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.haorui.app.data.model.AppConfig
|
||||
import com.haorui.app.data.model.CollectMode
|
||||
import com.haorui.app.crossplatform.model.CrossPublishTask
|
||||
import com.haorui.app.crossplatform.ui.CrossWorkspaceOverview
|
||||
import com.haorui.app.crossplatform.ui.TopicSourceSection
|
||||
import com.haorui.app.ui.components.CheckRow
|
||||
import com.haorui.app.ui.components.NumberField
|
||||
import com.haorui.app.ui.components.DropdownField
|
||||
@@ -46,23 +46,15 @@ import com.haorui.app.ui.components.PrimaryButton
|
||||
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.components.StepHint
|
||||
|
||||
/**
|
||||
* 首页 —— **运行与启动**(唯一启动点)
|
||||
* 首页 —— 工作台总览 + 唯一启动点 + 热点选题
|
||||
*
|
||||
* ## 功能去重原则(2026-10-29 重构)
|
||||
* 每个功能只在一处设置,避免用户困惑「该在哪里改」:
|
||||
* 启动/停止 → **本页**(唯一)
|
||||
* 采集参数 → 「采集」tab
|
||||
* 互动参数 → 「互动」tab
|
||||
* 接口/无障碍/浏览/记录 → 「我的」tab
|
||||
* 本页**不做**其它功能的入口,只在需要时给文字指引。
|
||||
*
|
||||
* 信息层次:
|
||||
* ① 状态大卡(一眼看懂 + 启动/停止)
|
||||
* ② 三步上手引导(跳转到各配置页,不是重复入口)
|
||||
* ③ 高级设置(模式 / 分时段 / 每日重置)
|
||||
* ## 功能布局(2026-11-16 重构)
|
||||
* ① 品牌 Hero(工作台指标 + 视觉焦点)
|
||||
* ② 运行卡(唯一启动/停止入口 + 发布模式 + 限额)
|
||||
* ③ 热点选题(来源切换 → 来源专属筛选 → 词条勾选 → 候选)
|
||||
* ④ 通用筛选(分类/时效/点赞/粉丝,全来源共用)
|
||||
*/
|
||||
@Composable
|
||||
fun HomeScreen(
|
||||
@@ -73,15 +65,15 @@ fun HomeScreen(
|
||||
onConfigChange: (AppConfig) -> Unit,
|
||||
crossTasks: List<CrossPublishTask> = emptyList(),
|
||||
crossTasksLoaded: Boolean = false,
|
||||
crossTasksError: String? = null,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(18.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
) {
|
||||
|
||||
CrossWorkspaceOverview(config, crossTasks, crossTasksLoaded, onNavigate)
|
||||
|
||||
// 唯一的既有视频启动/停止入口。
|
||||
@@ -92,17 +84,8 @@ fun HomeScreen(
|
||||
onConfigChange = onConfigChange,
|
||||
)
|
||||
|
||||
// ── ② 三步上手引导:指向各配置页,不是重复入口 ────
|
||||
StepHint(
|
||||
title = "开始使用前,请先完成这三步",
|
||||
steps = listOf(
|
||||
"在「我的」开启无障碍服务(必需)" to "a11y",
|
||||
"在「我的」进入既有视频采集设置" to "collect",
|
||||
"在「我的」配置大模型 Key(可选)" to "api",
|
||||
),
|
||||
onNavigate = onNavigate,
|
||||
)
|
||||
|
||||
// ── ③ 热点选题(来源切换:知乎/微博/抖音各自专属筛选;小红书已搁置不提供) ────
|
||||
TopicSourceSection(config, crossTasks, crossTasksLoaded, crossTasksError, onConfigChange, onNavigate)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
}
|
||||
@@ -161,19 +144,6 @@ private fun RunStatusCard(
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
// 采集模式:可点击下拉,一步切换
|
||||
DropdownField(
|
||||
label = "采集模式",
|
||||
value = if (config.collectMode == CollectMode.BAIDU.name) "百度采集" else "头条采集",
|
||||
options = listOf("头条采集", "百度采集"),
|
||||
onSelect = { label ->
|
||||
onConfigChange(config.copy(
|
||||
collectMode = if (label == "百度采集") CollectMode.BAIDU.name else CollectMode.TOUTIAO.name
|
||||
))
|
||||
},
|
||||
help = "切换采集来源,抓到后统一发布到头条",
|
||||
)
|
||||
|
||||
// 发布模式:草稿 / 正式(改即生效——配置流实时注入管线,无需重启任务)
|
||||
DropdownField(
|
||||
label = "发布模式",
|
||||
@@ -260,15 +230,12 @@ fun CollectScreen(
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(18.dp),
|
||||
) {
|
||||
// 采集参数(本页唯一入口)
|
||||
// 采集参数(本页唯一入口;百度采集无独立实现已下线)
|
||||
Section(
|
||||
title = "采集参数",
|
||||
help = "筛选要采集的内容类型。不确定就用默认值,先跑一轮看效果再微调",
|
||||
) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
HaoRuiButton("头条采集参数", { onNavigate("toutiao") }, Modifier.weight(1f))
|
||||
HaoRuiButton("百度采集参数", { onNavigate("baidu") }, Modifier.weight(1f))
|
||||
}
|
||||
HaoRuiButton("头条采集参数", { onNavigate("toutiao") }, Modifier.fillMaxWidth())
|
||||
}
|
||||
|
||||
// 分时段发布(从首页迁入)
|
||||
|
||||
@@ -45,9 +45,11 @@ import com.haorui.app.ui.components.StatusBanner
|
||||
import com.haorui.app.ui.components.StatusLevel
|
||||
import com.haorui.app.ui.components.TextRow
|
||||
|
||||
/** 我的 — 设置入口与本机数据管理 */
|
||||
/** 我的 — 设置入口与本机数据管理(互动设置已并入本页) */
|
||||
@Composable
|
||||
fun MineScreen(
|
||||
config: AppConfig,
|
||||
onConfigChange: (AppConfig) -> Unit,
|
||||
onNavigate: (String) -> Unit,
|
||||
onToast: (String) -> Unit,
|
||||
) {
|
||||
@@ -66,8 +68,11 @@ fun MineScreen(
|
||||
) {
|
||||
CrossSettingsEntries(onNavigate)
|
||||
|
||||
// ── 互动设置(原「互动」tab 内容,并入本页通用配置) ────
|
||||
InteractSettingsSections(config, onConfigChange, onToast)
|
||||
|
||||
Section(
|
||||
title = "系统设置",
|
||||
title = "通用配置 · 系统开关",
|
||||
help = "影响任务能否正常运行的关键配置",
|
||||
) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
@@ -105,8 +110,11 @@ fun MineScreen(
|
||||
}
|
||||
}
|
||||
|
||||
// ── 屏幕采集授权(抖音独立截屏通道;绕开无障碍截图缓存) ────
|
||||
ScreenProjectionSection(onToast)
|
||||
|
||||
Section(
|
||||
title = "本机数据",
|
||||
title = "通用配置 · 本机数据",
|
||||
help = "清理本地缓存与去重记录",
|
||||
) {
|
||||
StatusBanner("已发布去重索引:$dedupCount 条", StatusLevel.NEUTRAL)
|
||||
@@ -129,6 +137,38 @@ fun MineScreen(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 屏幕采集授权区块(MediaProjection)。
|
||||
* 抖音搜索页对无障碍截图通道有缓存防护(r13~r24 定案),投影通道拿实时帧绕开;
|
||||
* 授权需用户在系统弹窗亲手点同意,进程重启后投影失效需重新授权。
|
||||
*/
|
||||
@Composable
|
||||
private fun ScreenProjectionSection(onToast: (String) -> Unit) {
|
||||
var ready by remember { mutableStateOf(com.haorui.app.automation.RunState.projectionReady) }
|
||||
val scope = androidx.compose.runtime.rememberCoroutineScope()
|
||||
val activity = androidx.compose.ui.platform.LocalContext.current as? com.haorui.app.MainActivity
|
||||
Section(title = "屏幕采集授权", help = "抖音采集需要;授权后 App 可截取屏幕实时画面") {
|
||||
StatusBanner(
|
||||
text = if (ready) "屏幕采集已授权(投影就绪)"
|
||||
else "未授权——抖音采集将退化为无障碍截图(读不到实时画面)",
|
||||
level = if (ready) StatusLevel.OK else StatusLevel.WARN,
|
||||
)
|
||||
HaoRuiButton(if (ready) "重新授权屏幕采集" else "授权屏幕采集", {
|
||||
if (activity == null) {
|
||||
onToast("授权入口异常(非主窗口),请重启 App 后再试")
|
||||
} else {
|
||||
activity.requestProjection()
|
||||
// 授权结果异步回调(projectionLauncher),按钮状态延迟刷新
|
||||
scope.launch {
|
||||
kotlinx.coroutines.delay(3_000)
|
||||
ready = com.haorui.app.automation.RunState.projectionReady
|
||||
}
|
||||
}
|
||||
}, Modifier.fillMaxWidth())
|
||||
FieldHelp("授权弹窗由系统弹出,请勾选「整个屏幕」后点立即开始;进程重启后需重新授权")
|
||||
}
|
||||
}
|
||||
|
||||
/** 接口 / 大模型 — 供应商切换、密钥、标题字数、解析源 */
|
||||
@Composable
|
||||
fun ApiScreen(
|
||||
|
||||
@@ -13,6 +13,11 @@
|
||||
name="internal_videos"
|
||||
path="videos/" />
|
||||
|
||||
<!-- M5 跨平台视频素材(SourceMediaProvider 导入目录 filesDir/crossplatform/video/) -->
|
||||
<files-path
|
||||
name="crossplatform_video"
|
||||
path="crossplatform/" />
|
||||
|
||||
<!-- 日志导出(LogExporter.generateExportFile → cacheDir/export/) -->
|
||||
<cache-path
|
||||
name="export"
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- 浩瑞调试输入法子类型声明(M4 文章编辑器直写通道;无键盘 UI,仅 commitText) -->
|
||||
<input-method xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<subtype
|
||||
android:label="浩瑞调试输入法"
|
||||
android:imeSubtypeLocale="zh_CN"
|
||||
android:imeSubtypeMode="keyboard" />
|
||||
</input-method>
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.haorui.app.automation.selection
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class DraftReceiptPolicyTest {
|
||||
private fun confirms(lines: List<String>, actualTitle: String? = "测试视频", actualDeclaration: String? = "内容无需标注",
|
||||
elapsed: Long = 1500) =
|
||||
DraftReceiptPolicy.confirms("测试视频", actualTitle, "内容无需标注", actualDeclaration, lines, elapsed)
|
||||
|
||||
@Test fun acceptsTheObservedReceiptForTheCurrentTitleAndDeclaration() {
|
||||
assertTrue(confirms(listOf("保存草稿成功")))
|
||||
}
|
||||
|
||||
@Test fun buttonsSharePanelsAndTimeoutAreNeverReceipts() {
|
||||
listOf("存草稿", "草稿", "发布成功", "分享至", "未能保存草稿成功", "保存草稿失败")
|
||||
.forEach { assertFalse(it, confirms(listOf(it))) }
|
||||
assertFalse(confirms(emptyList(), elapsed = 8000))
|
||||
}
|
||||
|
||||
@Test fun rejectsOtherEditorsDeclarationsAndStaleCallbacks() {
|
||||
assertFalse(confirms(listOf("保存草稿成功"), actualTitle = "另一个标题"))
|
||||
assertFalse(confirms(listOf("保存草稿成功"), actualTitle = null))
|
||||
assertFalse(confirms(listOf("保存草稿成功"), actualDeclaration = "内容为转载"))
|
||||
assertFalse(confirms(listOf("保存草稿成功"), elapsed = -1))
|
||||
assertFalse(confirms(listOf("保存草稿成功"), elapsed = 8001))
|
||||
}
|
||||
|
||||
@Test fun acceptsOcrSpacingWithoutAcceptingAQuotedLongSentence() {
|
||||
assertTrue(confirms(listOf("保存 草稿 成功")))
|
||||
assertTrue(confirms(listOf("✓ 保存草稿成功")))
|
||||
assertTrue(confirms(listOf("O 保存草稿成功")))
|
||||
assertTrue(confirms(listOf("0保存草稿成功")))
|
||||
assertFalse(confirms(listOf("出现保存草稿成功后返回")))
|
||||
assertFalse(confirms(listOf("保存草稿成功后返回")))
|
||||
}
|
||||
|
||||
@Test fun acceptsReceiptMergedWithNeighbouringPageTextWhenNotChinesePreceded() {
|
||||
// 2026-11-14 真机实测三种行合并形态:⊙ 图标被 OCR 误读为 0 / O / 。,均为非汉字承接。
|
||||
assertTrue(confirms(listOf("0保存草稿成功")))
|
||||
assertTrue(confirms(listOf("宁兴·城O保存草稿成功鄞州万达广场小")))
|
||||
assertTrue(confirms(listOf("城市广场。保存草稿成功达广场IMAX店")))
|
||||
// 短语由汉字承接(否定句或纯噪声),不能当回执。
|
||||
assertFalse(confirms(listOf("宁兴·城保存草稿成功鄞州万达广场小")))
|
||||
assertFalse(confirms(listOf("宁兴·城能保存草稿成功鄞州万达广场小")))
|
||||
assertFalse(confirms(listOf("未能保存草稿成功")))
|
||||
}
|
||||
|
||||
@Test fun emptyDeclarationSummaryOnlyConfirmsAnExplicitNoAnnotationChoice() {
|
||||
assertEquals("内容无需标注", DraftReceiptPolicy.declarationReadback("内容无需标注", true, false, null))
|
||||
assertNull(DraftReceiptPolicy.declarationReadback("内容无需标注", false, false, null))
|
||||
assertNull(DraftReceiptPolicy.declarationReadback("内容无需标注", true, true, null))
|
||||
assertNull(DraftReceiptPolicy.declarationReadback("内容为转载", true, false, null))
|
||||
assertEquals("内容为转载", DraftReceiptPolicy.declarationReadback("内容为转载", true, false, "内容为转载"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
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)
|
||||
}
|
||||
|
||||
// ── 微博热搜类目勾选持久化(2026-11-14 用户口径)──────────────
|
||||
|
||||
@Test fun oldJsonWithoutWeiboCategoriesKeepsEmptySelection() {
|
||||
val old = """{"crossPlatform":{"enabled":false,"maxAgeHours":12}}"""
|
||||
val config = json.decodeFromString(AppConfig.serializer(), old).crossPlatform
|
||||
assertTrue(config.weiboHotCategories.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun weiboCategorySelectionSurvivesJsonAndFlatRoundTrip() {
|
||||
val expected = CrossPlatformConfig(weiboHotCategories = listOf("hot", "society", "tech"))
|
||||
val fromJson = json.decodeFromString(CrossPlatformConfig.serializer(),
|
||||
json.encodeToString(CrossPlatformConfig.serializer(), expected)).normalized()
|
||||
val fromFlat = CrossPlatformConfigCodec.fromFlatMap(CrossPlatformConfigCodec.toFlatMap(expected))
|
||||
assertEquals(listOf("hot", "society", "tech"), fromJson.weiboHotCategories)
|
||||
assertEquals(listOf("hot", "society", "tech"), fromFlat.weiboHotCategories)
|
||||
}
|
||||
|
||||
@Test fun weiboCategoryNormalizationDropsUnknownIdsAndDuplicates() {
|
||||
val config = CrossPlatformConfig(weiboHotCategories = listOf(" tech ", "tech", "未核验类目", "hot")).normalized()
|
||||
assertEquals(listOf("tech", "hot"), config.weiboHotCategories)
|
||||
assertTrue(CrossPlatformConfig().weiboHotCategories.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun weiboTopicSelectionSurvivesJsonAndFlatRoundTrip() {
|
||||
val expected = CrossPlatformConfig(
|
||||
weiboHotCategories = listOf("hot", "tech"),
|
||||
weiboHotTopics = mapOf("hot" to listOf("BLG夺冠", "和合共生"), "tech" to listOf("Gemini压谁谁输")),
|
||||
)
|
||||
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)
|
||||
}
|
||||
|
||||
@Test fun weiboTopicNormalizationDropsUnknownCategoryKeysAndBlankTitles() {
|
||||
val config = CrossPlatformConfig(
|
||||
weiboHotTopics = mapOf(
|
||||
"hot" to listOf(" 正常词条 ", "", "正常词条", " "),
|
||||
"未核验类目" to listOf("不该保留"),
|
||||
),
|
||||
).normalized()
|
||||
assertEquals(mapOf("hot" to listOf("正常词条")), config.weiboHotTopics)
|
||||
assertTrue(CrossPlatformConfig().weiboHotTopics.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun malformedWeiboTopicJsonFallsBackToEmptyWithoutDisablingModule() {
|
||||
val config = CrossPlatformConfigCodec.fromFlatMap(mapOf(
|
||||
"cross_platform_enabled" to "true",
|
||||
"cross_platform_weibo_hot_topics" to "{不是JSON",
|
||||
))
|
||||
assertTrue(config.enabled)
|
||||
assertTrue(config.weiboHotTopics.isEmpty())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
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())
|
||||
}
|
||||
|
||||
// ── M6 长跑修复:休息期快照跨重启不得续命 ────────────────
|
||||
|
||||
@Test fun restSnapshotWithSavedAtDiscardsExpiredRestAcrossReboot() {
|
||||
// 新格式(第 4 段=保存时刻):昨晚保存"剩余 537s",今早恢复——按 savedAt 折算
|
||||
// 绝对截止已过期 → 丢弃(真机实锤:旧逻辑会重置 537s 全程重新计时)
|
||||
val clock = MutableClock("2026-11-16T02:04:00+08:00")
|
||||
val quota = manager(clock)
|
||||
quota.initDaily(1)
|
||||
quota.restoreState("0,0,0,0|537|${clock.millis()}|${clock.millis()}")
|
||||
assertEquals(clock.millis() + 537_000, quota.accountSnapshot().restUntilMs)
|
||||
// 跨夜重启(进程死亡 7 小时后)
|
||||
clock.at("2026-11-16T09:10:00+08:00")
|
||||
val quota2 = manager(clock)
|
||||
quota2.initDaily(1)
|
||||
quota2.restoreState("0,0,0,0|537|${ZonedDateTime.parse("2026-11-16T02:04:00+08:00").toInstant().toEpochMilli()}|${ZonedDateTime.parse("2026-11-16T02:04:00+08:00").toInstant().toEpochMilli()}")
|
||||
assertEquals(0, quota2.accountSnapshot().restUntilMs) // 已过期丢弃
|
||||
assertFalse(quota2.snapshotState().contains("537"))
|
||||
}
|
||||
|
||||
@Test fun restSnapshotWithSavedAtKeepsUnexpiredRestWithCorrectRemainder() {
|
||||
// 未过期的休息按 savedAt 折算剩余差额(不是重新从头计时)
|
||||
val savedAt = ZonedDateTime.parse("2026-11-16T09:00:00+08:00").toInstant().toEpochMilli()
|
||||
val clock = MutableClock("2026-11-16T09:05:00+08:00") // 5 分钟后重启
|
||||
val quota = manager(clock)
|
||||
quota.initDaily(1)
|
||||
quota.restoreState("0,0,0,0|537|$savedAt|$savedAt")
|
||||
// 剩余 = 537 - 300 = 237s(按绝对截止折算)
|
||||
assertEquals(savedAt + 537_000, quota.accountSnapshot().restUntilMs)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
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)
|
||||
// 抖音已验收放行(2026-11-17);其余来源仍未验证
|
||||
val verifiedIds = SourceRegistry.definitions.filter { it.verified }.map { it.id }
|
||||
assertEquals(listOf("douyin"), verifiedIds)
|
||||
SourceRegistry.definitions.filter { !it.verified }.forEach { source ->
|
||||
SourceCapability.entries.forEach { capability ->
|
||||
assertFalse(SourceRegistry.executionStatus(source.id, "99.99", requested, capability).canExecute)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun douyinIsVerifiedWithHotListAndDetailCapabilities() {
|
||||
val douyin = SourceRegistry.find("douyin")!!
|
||||
assertTrue(douyin.verified)
|
||||
assertTrue(douyin.verifiedVersions.contains("39.8.0"))
|
||||
assertTrue(douyin.capabilities.contains(SourceCapability.HOT_LIST))
|
||||
assertTrue(douyin.capabilities.contains(SourceCapability.DETAIL))
|
||||
// 未取证能力不列入
|
||||
assertFalse(douyin.capabilities.contains(SourceCapability.SHARE_LINK))
|
||||
assertFalse(douyin.capabilities.contains(SourceCapability.MEDIA_IMPORT))
|
||||
}
|
||||
|
||||
@Test fun douyinExecutesWithVerifiedVersionAndCapability() {
|
||||
assertTrue(SourceRegistry.executionStatus("douyin", "39.8.0", requested, SourceCapability.HOT_LIST).canExecute)
|
||||
assertTrue(SourceRegistry.executionStatus("douyin", "39.8.0", requested, SourceCapability.DETAIL).canExecute)
|
||||
// 未验证版本拒绝
|
||||
assertFalse(SourceRegistry.executionStatus("douyin", "39.7.0", requested, SourceCapability.HOT_LIST).canExecute)
|
||||
// 未验证能力拒绝
|
||||
assertFalse(SourceRegistry.executionStatus("douyin", "39.8.0", requested, SourceCapability.SHARE_LINK).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,130 @@
|
||||
package com.haorui.app.crossplatform.compose
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* M4 正文生成器样本验收:提纲解析、正文核验三关(长度边界/分段/数字一致)、
|
||||
* 输出清理与空 Key 失败路径。
|
||||
* 用例设计遵循测试用例 skill 方法论(边界值、异常场景、P1/P2 分级),
|
||||
* 形态沿用仓库既有 JUnit4 内嵌风格(项目测试统一在 app/src/test)。
|
||||
*/
|
||||
class ArticleBodyComposeTest {
|
||||
|
||||
private val config = com.haorui.app.data.model.AiConfig()
|
||||
private val composer = ArticleBodyComposer(config)
|
||||
|
||||
private val evidence = EvidenceBuilder.Evidence(
|
||||
titleSeed = "国足马来西亚爆发冲突",
|
||||
sourceText = "11月14日讯 2026CFA中国之队邀请赛,中国男足vs马来西亚,比赛第44分钟," +
|
||||
"裁判吹罚犯规后对手故意将球踢中杨希,双方爆发大规模冲突,现场约500名球迷见证。",
|
||||
sourceRoute = "ocr",
|
||||
fetchedAtMs = 1_763_100_000_000L,
|
||||
)
|
||||
|
||||
/** 恰好 cp 个码点、paragraphs 段的无数字正文(长度边界用例共用;段间换行计入总码点)。 */
|
||||
private fun makeBody(cp: Int, paragraphs: Int = 2): String {
|
||||
val fillerTotal = cp - (paragraphs - 1) // 扣除段间换行符的码点
|
||||
val seg = fillerTotal / paragraphs
|
||||
val rem = fillerTotal - seg * paragraphs
|
||||
return (1..paragraphs).joinToString("\n") { i ->
|
||||
"叙".repeat(seg + if (i == 1) rem else 0)
|
||||
}
|
||||
}
|
||||
|
||||
/** 带指定前缀(如数字场景)的正文:总码点恰好 cp、paragraphs 段。 */
|
||||
private fun bodyWith(prefix: String, cp: Int = 850, paragraphs: Int = 2): String {
|
||||
val rest = makeBody(cp - prefix.codePointCount(0, prefix.length), paragraphs)
|
||||
return prefix + rest
|
||||
}
|
||||
|
||||
// ── 提纲解析(P1 正常 / P2 容错 / P3 异常)────────────────
|
||||
|
||||
@Test fun outlineParsesJsonArrayAndDropsBlankPoints() {
|
||||
assertEquals(
|
||||
listOf("事件经过", "关键事实", "分析角度"),
|
||||
composer.parseOutline("""["事件经过","关键事实","分析角度"]"""),
|
||||
)
|
||||
// 空白要点剔除
|
||||
assertEquals(listOf("甲"), composer.parseOutline("""["甲",""," "]"""))
|
||||
}
|
||||
|
||||
@Test fun outlineToleratesCodeFenceAndTrailingNotes() {
|
||||
assertEquals(
|
||||
listOf("要点一", "要点二"),
|
||||
composer.parseOutline("```json\n[\"要点一\",\"要点二\"]\n```"),
|
||||
)
|
||||
assertEquals(listOf("要点"), composer.parseOutline("提纲如下:[\"要点\"] 以上。"))
|
||||
}
|
||||
|
||||
@Test fun outlineRejectsNonJsonAndEmptyInput() {
|
||||
assertTrue(composer.parseOutline("不是JSON").isEmpty())
|
||||
assertTrue(composer.parseOutline("").isEmpty())
|
||||
assertTrue(composer.parseOutline("[]").isEmpty())
|
||||
assertTrue(composer.parseOutline("[\"未闭合").isEmpty()) // 未闭合数组
|
||||
}
|
||||
|
||||
// ── 正文核验①长度关(P1 边界值 799/800/1500/1501)────────
|
||||
|
||||
@Test fun verifyBodyAcceptsExactBoundaryLengths() {
|
||||
assertNull(composer.verifyBody(makeBody(800), evidence)) // 下边界
|
||||
assertNull(composer.verifyBody(makeBody(1500), evidence)) // 上边界
|
||||
}
|
||||
|
||||
@Test fun verifyBodyRejectsBelowMinAndAboveMax() {
|
||||
assertTrue(composer.verifyBody(makeBody(799), evidence)!!.contains("不足 800"))
|
||||
assertTrue(composer.verifyBody(makeBody(1501), evidence)!!.contains("超过 1500"))
|
||||
}
|
||||
|
||||
@Test fun verifyBodyRejectsBlank() {
|
||||
assertTrue(composer.verifyBody("", evidence)!!.contains("为空"))
|
||||
assertTrue(composer.verifyBody(" \n ", evidence)!!.contains("为空"))
|
||||
}
|
||||
|
||||
// ── 正文核验②分段关(P1/P2)────────────────────────────
|
||||
|
||||
@Test fun verifyBodyRejectsSingleBlockWithoutParagraphs() {
|
||||
// 900 字但无换行 → 不符合“口语化分段”
|
||||
assertTrue(composer.verifyBody(makeBody(900, paragraphs = 1), evidence)!!.contains("未分段"))
|
||||
}
|
||||
|
||||
@Test fun verifyBodyAcceptsTwoParagraphs() {
|
||||
assertNull(composer.verifyBody(makeBody(850, paragraphs = 2), evidence))
|
||||
}
|
||||
|
||||
// ── 正文核验③数字一致关(P1 防编造 / P2 量词放宽)────────
|
||||
|
||||
@Test fun verifyBodyRejectsFabricatedNumbers() {
|
||||
val body = bodyWith("冲突持续长达98小时震惊全场。")
|
||||
val reason = composer.verifyBody(body, evidence)
|
||||
assertNotNull(reason)
|
||||
assertTrue(reason!!.contains("98"))
|
||||
assertTrue(reason.contains("编造"))
|
||||
}
|
||||
|
||||
@Test fun verifyBodyAcceptsNumbersFoundInSource() {
|
||||
// 44 / 500 / 2026 均在来源全文中
|
||||
assertNull(composer.verifyBody(bodyWith("第44分钟冲突,现场约500名球迷,2026年赛事。"), evidence))
|
||||
}
|
||||
|
||||
@Test fun verifyBodyIgnoresSingleDigitQuantifiers() {
|
||||
// 单位数(1 位)不核验——量词类数字(“3人”)不误伤
|
||||
assertNull(composer.verifyBody(bodyWith("3人当场倒地,双方一度聚集。"), evidence))
|
||||
}
|
||||
|
||||
// ── 输出清理(P2)与空 Key 失败路径(P1)─────────────────
|
||||
|
||||
@Test fun cleanBodyStripsCodeFenceAndLabel() {
|
||||
val raw = "```text\n正文:这是正文内容。\n```"
|
||||
assertEquals("这是正文内容。", composer.cleanBody(raw))
|
||||
assertEquals("正文内容。", composer.cleanBody("正文:正文内容。"))
|
||||
assertEquals("无标记正文。", composer.cleanBody("无标记正文。"))
|
||||
}
|
||||
|
||||
@Test fun composeBodyFailsFastWithoutApiKey() {
|
||||
// AiConfig() 默认 deepseek 且 Key 为空 → 不发 HTTP,直接失败
|
||||
val result = kotlinx.coroutines.runBlocking { composer.composeBody(evidence) }
|
||||
assertNull(result)
|
||||
assertTrue(composer.failureReason.contains("模型 Key 未配置"))
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user