Compare commits

...
3 Commits
18 changed files with 1514 additions and 4 deletions
@@ -18,7 +18,11 @@ class StoreInstrumentation : Instrumentation() {
finish(Activity.RESULT_OK, Bundle().apply { putString("stream", "\n${AccountClipboardProbe.read(this@StoreInstrumentation)}\n") })
return
}
val result = JUnitCore.runClasses(StoreTransactionTest::class.java)
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 })
})
@@ -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("协议"))
}
}
@@ -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() }
}
}
@@ -435,6 +435,8 @@ class HaoRuiAccessibilityService : AccessibilityService() {
// 回归测试:发布模式切换(草稿/正式)
addAction("com.haorui.app.ACTION_SET_DRAFT")
addAction("com.haorui.app.ACTION_SET_PUBLISH")
// M5 跨平台视频草稿车道端到端(debug APK:管线→桥→旧发布器→草稿箱)
addAction("com.haorui.app.ACTION_TEST_CROSS_VIDEO")
}
@Suppress("UnspecifiedRegisterReceiverFlag")
registerReceiver(cmdReceiver, filter)
@@ -678,6 +680,11 @@ class HaoRuiAccessibilityService : AccessibilityService() {
val accepted = startArticleMachineVerify(title, body)
RunLogger.i(TAG, "文章验证受理=$accepted(广播 ACTION_TEST_ARTICLE title=$title bodyLen=${body.length})")
}
// M5 跨平台视频草稿车道端到端:夹具经管线(导入→校验→许可→桥)→旧发布器
"com.haorui.app.ACTION_TEST_CROSS_VIDEO" -> {
val accepted = startCrossVideoDraftSandbox()
RunLogger.i(TAG, "跨平台视频草稿沙盒受理=$accepted(广播 ACTION_TEST_CROSS_VIDEO)")
}
// 回归测试发布模式切换(草稿/正式;autoPublish 无 UI 开关,走广播)
"com.haorui.app.ACTION_SET_DRAFT" -> setAutoPublish(false)
"com.haorui.app.ACTION_SET_PUBLISH" -> setAutoPublish(true)
@@ -764,6 +771,74 @@ class HaoRuiAccessibilityService : AccessibilityService() {
accepted
}
/**
* M5 跨平台视频草稿车道端到端(仅调试 APK):自有测试视频经**完整管线**
* (SourceMediaProvider 导入→VideoFileValidator 校验→许可→CrossVideoPipeline 加工)
* → VideoTaskBridge 桥接 → 旧 PublishMachine 草稿车道 → 草稿箱核对。
*
* 与 [startDraftSandbox] 的区别:素材走新链路加工(校验/许可/署名编排全跑),
* 标题与递交来自管线成品而非直接 submit——M5 最终验收门槛。
*
* 素材来源:App 外部私有目录 `m5-fixture.mp4`(adb push,分区存储下无需权限;
* MediaStore 生产导入待授权后单独验收)。门控同草稿沙盒:debug-only、
* 调度器空闲、草稿模式、新模块总开关不校验(沙盒独立于正式入口)。
*/
fun startCrossVideoDraftSandbox(): Boolean = synchronized(stepLifecycleLock) {
if (applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE == 0 ||
!::scheduler.isInitialized || scheduler.isRunning || publisher.isWorking || interactor.isWorking ||
frontGuard.creditNavigating || !foregroundCoordinator.isIdle() || latestConfig.toutiao.autoPublish ||
runCatching { videoDownloader.hasPendingDrafts() }.getOrDefault(true)) return@synchronized false
val fixture = java.io.File(getExternalFilesDir(null), "m5-fixture.mp4")
if (!fixture.exists() || fixture.length() <= 0) {
RunLogger.w(TAG, "M5 草稿沙盒:夹具缺失(adb push 到 ${fixture.absolutePath})")
return@synchronized false
}
val logs = mutableListOf<String>()
try {
// ── 完整管线 ──────────────────────────────────────
val provider = com.haorui.app.crossplatform.media.SourceMediaProvider(this) { msg ->
RunLogger.i(TAG, "M5-Provider: $msg"); logs.add(msg)
}
val imported = provider.importFrom(android.net.Uri.fromFile(fixture), "haorui-m5-e2e")
if (imported !is com.haorui.app.crossplatform.media.SourceMediaProvider.Result.Imported) {
RunLogger.w(TAG, "M5 草稿沙盒:导入失败 ${(imported as com.haorui.app.crossplatform.media.SourceMediaProvider.Result.Rejected).reason}")
return@synchronized false
}
// 许可:测试夹具登记为自有素材(沙盒专用,不进生产许可库)
val licenseStore = com.haorui.app.crossplatform.media.MediaLicenseStore()
licenseStore.registerOwn("sandbox-account", "M5 草稿沙盒自有素材")
val pipeline = com.haorui.app.crossplatform.media.CrossVideoPipeline(licenseStore) { msg ->
RunLogger.i(TAG, "M5-Pipeline: $msg"); logs.add(msg)
}
val title = "浩瑞跨平台视频草稿 ${java.util.UUID.randomUUID().toString().take(8)}"
val outcome = pipeline.prepare(
imported.localPath, "sandbox-account", null,
title, null, System.currentTimeMillis(),
)
val prepared = outcome.prepared
if (prepared == null) {
RunLogger.w(TAG, "M5 草稿沙盒:管线拒绝 ${outcome.reason}")
return@synchronized false
}
// ── 桥接 → 旧发布器(草稿车道)─────────────────────
// 声明经 declarationOverride 透传(绕开旧配置"内容为原创"——M0 已知问题)
val bridge = com.haorui.app.crossplatform.media.VideoTaskBridge({ t, uri, auto, decl ->
publisher.submit(t, uri, autoPublish = auto, declaration = decl)
}) { msg -> RunLogger.i(TAG, "M5-Bridge: $msg") }
val bridged = bridge.bridge(prepared, declarationOverride = "内容无需标注")
if (bridged !is com.haorui.app.crossplatform.media.VideoTaskBridge.Result.Submitted) {
RunLogger.w(TAG, "M5 草稿沙盒:桥接拒绝 ${(bridged as com.haorui.app.crossplatform.media.VideoTaskBridge.Result.Rejected).reason}")
return@synchronized false
}
scheduler.startLaneOnly(LaneScheduler.Lane.PUBLISH)
RunLogger.i(TAG, "M5 草稿沙盒受理:标题「$title」素材=${prepared.localPath} sha=${prepared.sha256.take(12)}…")
true
} catch (t: Throwable) {
RunLogger.e(TAG, "M5 草稿沙盒异常: ${t.javaClass.simpleName}:${t.message}", t)
false
}
}
/**
* 仅调试 APK 的知乎单候选采集沙盒(端到端真机验收)。
* 只读采集、不发布、不启动调度器——WATCHDOG(恢复链)不运行,
@@ -617,8 +617,14 @@ class PublishMachine(
if (!declarationVerified || !draftEditorMatches(fresh)) { pauseForReview("草稿标题或声明已变化,未发送"); return }
val button = NodeLocator.byId(fresh, ToutiaoSelectors.ID_PUB_DRAFT) ?: return
try {
val id = try { videoDownloader?.beginDraft(mediaUri, title, declaration) }
catch (failure: Exception) { log("草稿意图保存失败:${failure.javaClass.simpleName}"); null }
// 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()
@@ -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,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,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,101 @@
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()
}
/**
* 领取并执行一个 READY 任务(单次调用处理单任务;调度节奏由调用方控制)。
* 流程:门控 → claimNextReady(事务领取,EDITING)→ beginSubmission(点击前落库)
* → 执行 → 归账。
*/
suspend fun dispatchOnce(accountKey: String, generation: Long, executor: Executor): Outcome {
// ① 门控(额度静默门 + 信用分实时读)
when (val decision = gate.check()) {
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)
}
}
}
}
@@ -46,11 +46,27 @@ class VideoDownloader(private val context: Context) {
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()
@@ -59,6 +75,11 @@ class VideoDownloader(private val context: Context) {
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。
+5
View File
@@ -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,256 @@
package com.haorui.app.crossplatform.media
import org.junit.Assert.*
import org.junit.Test
import java.io.File
/**
* M5 媒体层验收:许可匹配(自有/授权/有效期/署名)、简介署名策略、
* 校验器纯文件部分(魔数/大小/缺失)与 JSON 往返。
*/
class MediaLicenseTest {
private val now = 1_763_100_000_000L
// ── 许可库 ────────────────────────────────────────────────
@Test fun ownLicenseMatchesByAccountKeyAndIsIdempotent() {
val store = MediaLicenseStore()
val first = store.registerOwn("account-A", "本人素材")
val second = store.registerOwn("account-A") // 幂等
assertEquals(first.id, second.id)
val match = store.match("account-A", "evil.example.com", now)
assertNotNull(match)
assertFalse(match!!.needsAttribution)
}
@Test fun grantedLicenseRequiresHostAndValidityWindow() {
val store = MediaLicenseStore()
store.registerGranted(
subject = "video.example.com",
requiresAttribution = true,
validFromMs = now - 86_400_000L,
validUntilMs = now + 86_400_000L,
)
// 域名+有效期内:命中且要求署名
val hit = store.match("other-account", "video.example.com", now)
assertNotNull(hit)
assertTrue(hit!!.needsAttribution)
// 有效期外:不命中
assertNull(store.match("other-account", "video.example.com", now + 7 * 86_400_000L))
// 域名不同:不命中
assertNull(store.match("other-account", "other.example.com", now))
// 来源未知:不命中(仅自有可匹配)
assertNull(store.match("other-account", null, now))
}
@Test fun matchPrefersOwnOverGrantedAndLatestWindow() {
val store = MediaLicenseStore()
store.registerOwn("account-A")
store.registerGranted("host1", requiresAttribution = true, validFromMs = 0, validUntilMs = now + 1000)
// 自有优先:即便来源域名有授权
val m = store.match("account-A", "host1", now)
assertEquals(MediaLicenseStore.Kind.OWN, m!!.license.kind)
// 多条授权取有效期最晚
val store2 = MediaLicenseStore()
store2.registerGranted("host2", requiresAttribution = false, validFromMs = 0, validUntilMs = now + 1000)
store2.registerGranted("host2", requiresAttribution = false, validFromMs = 0, validUntilMs = now + 999_000)
assertEquals(now + 999_000, store2.match("x", "host2", now)!!.license.validUntilMs)
}
// ── JSON 往返 ─────────────────────────────────────────────
@Test fun serializeDeserializeRoundTrip() {
val store = MediaLicenseStore()
store.registerOwn("account-A", "备注甲")
store.registerGranted("video.example.com", requiresAttribution = true, validFromMs = 100, validUntilMs = 200, note = "备注乙")
val json = store.serialize()
val restored = MediaLicenseStore().deserialize(json)
assertEquals(2, restored.size)
val own = restored.first { it.kind == MediaLicenseStore.Kind.OWN }
assertEquals("account-A", own.subject)
assertEquals("备注甲", own.note)
val granted = restored.first { it.kind == MediaLicenseStore.Kind.GRANTED }
assertTrue(granted.requiresAttribution)
assertEquals(200L, granted.validUntilMs)
}
@Test fun deserializeSkipsCorruptedEntries() {
val store = MediaLicenseStore()
val bad = """[{"id":"x","kind":"UNKNOWN"},{"id":"y","kind":"OWN","subject":"acc"}]"""
val restored = store.deserialize(bad)
assertEquals(1, restored.size)
assertEquals("acc", restored[0].subject)
// 完全坏 JSON:空表,不抛
assertTrue(store.deserialize("不是JSON").isEmpty())
}
// ── 简介署名 ──────────────────────────────────────────────
@Test fun captionOwnAddsNothingAndGrantedAppendsCredit() {
// 自有:不加署名段
val own = MediaLicenseStore.Match(
MediaLicenseStore.MediaLicense("o1", MediaLicenseStore.Kind.OWN, "acc"),
needsAttribution = false,
)
assertEquals("测试简介", VideoCaptionPolicy.build("测试简介", own, null))
// 授权+署名信息齐全:末段追加
val granted = MediaLicenseStore.Match(
MediaLicenseStore.MediaLicense("g1", MediaLicenseStore.Kind.GRANTED, "video.example.com", requiresAttribution = true),
needsAttribution = true,
)
val attr = VideoCaptionPolicy.Attribution("示例视频站", "原作者甲")
val caption = VideoCaptionPolicy.build("看一个视频", granted, attr)!!
assertTrue(caption.startsWith("看一个视频"))
assertTrue(caption.contains("内容转载自示例视频站"))
assertTrue(caption.contains("原作者甲"))
assertTrue(caption.contains("已获授权"))
}
@Test fun captionSkipsWhenAttributionMissingOrNoLicense() {
val granted = MediaLicenseStore.Match(
MediaLicenseStore.MediaLicense("g1", MediaLicenseStore.Kind.GRANTED, "h", requiresAttribution = true),
needsAttribution = true,
)
// 需署名但信息缺失 → 跳过(null),不静默放行
assertNull(VideoCaptionPolicy.build("简介", granted, null))
assertNull(VideoCaptionPolicy.build("简介", granted, VideoCaptionPolicy.Attribution("", "甲")))
assertNull(VideoCaptionPolicy.build("简介", granted, VideoCaptionPolicy.Attribution("站", "")))
// 无许可 → 兜底拒绝
assertNull(VideoCaptionPolicy.build("简介", null, null))
}
// ── 校验器(纯文件部分;媒体轨道探测需真机)────────────────
@Test fun validatorRejectsMissingEmptyAndOversized() {
assertFalse(VideoFileValidator.validate("/nonexistent/file.mp4").ok)
val empty = File.createTempFile("empty", ".mp4").apply { deleteOnExit() }
assertFalse(VideoFileValidator.validate(empty.absolutePath).ok)
val tmp = File.createTempFile("notmp4", ".bin").apply { deleteOnExit() }
tmp.writeBytes(ByteArray(16))
val report = VideoFileValidator.validate(tmp.absolutePath)
assertFalse(report.ok)
assertTrue(report.reason.contains("MP4"))
}
@Test fun sha256IsStableAndHexEncoded() {
val tmp = File.createTempFile("sha", ".bin").apply { deleteOnExit() }
tmp.writeBytes("浩瑞视频校验测试内容".toByteArray(Charsets.UTF_8))
val h1 = VideoFileValidator.sha256(tmp)
val h2 = VideoFileValidator.sha256(tmp)
assertEquals(h1, h2)
assertEquals(64, h1.length)
assertTrue(h1.all { it in "0123456789abcdef" })
}
// ── CrossVideoPipeline 编排(校验器拒绝路径+许可+署名)──────
@Test fun pipelineRejectsInvalidFileBeforeLicenseCheck() {
val logs = mutableListOf<String>()
val pipeline = CrossVideoPipeline(MediaLicenseStore()) { logs.add(it) }
val outcome = pipeline.prepare("/nonexistent/video.mp4", "acc", null, "简介", null, now)
assertNull(outcome.prepared)
assertTrue(outcome.reason.contains("视频校验未通过"))
// 校验失败先于许可判断(日志可证)
assertTrue(logs.any { it.contains("视频校验拒绝") })
assertFalse(logs.any { it.contains("许可缺失") })
}
@Test fun pipelineRejectsMissingLicenseEvenForValidFileShape() {
// 媒体轨道探测在 JVM 不可跑——用许可缺失路径验证编排顺序(文件存在但非 MP4 同样先被校验拦);
// 真机文件级通过场景由 instrumentation 覆盖。
val pipeline = CrossVideoPipeline(MediaLicenseStore())
val tmp = File.createTempFile("notmp4", ".bin").apply { deleteOnExit() }
tmp.writeBytes(ByteArray(16))
val outcome = pipeline.prepare(tmp.absolutePath, "acc", "host.example.com", "简介", null, now)
assertNull(outcome.prepared)
assertTrue(outcome.reason.contains("视频校验未通过") || outcome.reason.contains("许可缺失"))
}
@Test fun pipelinePreparesOwnVideoWithoutAttribution() {
// 自有许可 + 合法文件:真机媒体探测在 JVM 不可跑,此处仅验证许可/署名编排语义——
// 用"校验必败"文件确认拒绝原因排序正确后,成功路径由真机验收覆盖。
// (本用例钉住的是:自有许可匹配 → needsAttribution=false → 简介不加署名段)
val store = MediaLicenseStore()
store.registerOwn("acc-own")
val match = store.match("acc-own", null, now)!!
assertFalse(match.needsAttribution)
assertEquals("纯简介", VideoCaptionPolicy.build("纯简介", match, null))
}
// ── VideoTaskBridge 桥接(署名前置/SHA 复核/草稿车道硬编码)──
private fun prepared(
path: String,
sha: String,
needsAttribution: Boolean = false,
caption: String = "测试简介第一行",
) = CrossVideoPipeline.PreparedVideo(
localPath = path, sha256 = sha, durationMs = 30_000, sizeBytes = 1024,
rightsRef = "own-x", caption = caption, needsAttribution = needsAttribution,
)
@Test fun bridgeRejectsAttributionWhenPageCannotSet() {
var submitted = 0
val bridge = VideoTaskBridge({ _, _, _, _ -> submitted++; true })
val file = File.createTempFile("attr", ".mp4").apply { deleteOnExit() }
file.writeBytes(ByteArray(32))
val result = bridge.bridge(
prepared(file.absolutePath, VideoFileValidator.sha256(file), needsAttribution = true),
publishPageSupportsAttribution = false,
)
assertTrue(result is VideoTaskBridge.Result.Rejected)
assertTrue((result as VideoTaskBridge.Result.Rejected).reason.contains("署名"))
assertEquals(0, submitted) // 未递交
}
@Test fun bridgeRejectsMissingOrSwappedFileByShaCheck() {
var submitted = 0
val bridge = VideoTaskBridge({ _, _, _, _ -> submitted++; true })
// 文件丢失
val missing = bridge.bridge(prepared("/nonexistent/x.mp4", "ab".repeat(32)))
assertTrue(missing is VideoTaskBridge.Result.Rejected)
assertTrue((missing as VideoTaskBridge.Result.Rejected).reason.contains("丢失"))
// 内容被换(SHA 不符)
val file = File.createTempFile("swap", ".mp4").apply { deleteOnExit() }
file.writeBytes(ByteArray(32))
val swapped = bridge.bridge(prepared(file.absolutePath, "cd".repeat(32)))
assertTrue(swapped is VideoTaskBridge.Result.Rejected)
assertTrue((swapped as VideoTaskBridge.Result.Rejected).reason.contains("身份不符"))
assertEquals(0, submitted)
}
@Test fun bridgeSubmitsDraftLaneWithFirstLineAsTitle() {
var capturedTitle = ""
var capturedAutoPublish: Boolean? = null
var capturedDeclaration: String? = "sentinel"
val file = File.createTempFile("bridge-ok", ".mp4").apply { deleteOnExit() }
file.writeBytes(ByteArray(32))
val bridge = VideoTaskBridge({ t, _, auto, decl -> capturedTitle = t; capturedAutoPublish = auto; capturedDeclaration = decl; true })
val result = bridge.bridge(prepared(file.absolutePath, VideoFileValidator.sha256(file)))
assertTrue(result is VideoTaskBridge.Result.Submitted)
assertEquals("测试简介第一行", capturedTitle)
// 草稿车道硬编码:autoPublish 恒 false(新链路首版 DRY_RUN);声明默认透传 null
assertEquals(false, capturedAutoPublish)
assertNull(capturedDeclaration)
}
@Test fun bridgePassesDeclarationOverrideThrough() {
// 沙盒场景:显式声明覆盖透传到发布器(绕开旧配置"内容为原创")
var capturedDeclaration: String? = null
val file = File.createTempFile("bridge-decl", ".mp4").apply { deleteOnExit() }
file.writeBytes(ByteArray(32))
val bridge = VideoTaskBridge({ _, _, _, decl -> capturedDeclaration = decl; true })
bridge.bridge(prepared(file.absolutePath, VideoFileValidator.sha256(file)), declarationOverride = "内容无需标注")
assertEquals("内容无需标注", capturedDeclaration)
}
@Test fun bridgeReportsPublisherRejection() {
val file = File.createTempFile("rej", ".mp4").apply { deleteOnExit() }
file.writeBytes(ByteArray(32))
val bridge = VideoTaskBridge({ _, _, _, _ -> false })
val result = bridge.bridge(prepared(file.absolutePath, VideoFileValidator.sha256(file)))
assertTrue(result is VideoTaskBridge.Result.Rejected)
assertTrue((result as VideoTaskBridge.Result.Rejected).reason.contains("发布器拒绝"))
}
}
@@ -0,0 +1,56 @@
package com.haorui.app.crossplatform.publish
import com.haorui.app.ocr.CreditGateRunner
import org.junit.Assert.*
import org.junit.Test
/**
* 账号发布门控验收:额度静默门先于信用读、新链路 fail-closed 语义
* (UNREADABLE=HOLD 跳过,与旧链路 fail-open 相反)、BLOCKED=SUSPEND 当日暂停、
* 全过=ALLOW。quota=null(额度门下线场景)不阻塞信用检查。
*/
class AccountPublishGateTest {
private class FakeQuota(var allow: Boolean = true) {
fun canPublish(): Boolean = allow
}
@Test fun allowWhenQuotaOpenAndCreditPass() {
val logs = mutableListOf<String>()
val gate = AccountPublishGate(null, 90, { CreditGateRunner.Verdict.PASS }) { logs.add(it) }
val decision = kotlinx.coroutines.runBlocking { gate.check() }
assertEquals(AccountPublishGate.Decision.Allow, decision)
}
@Test fun holdWhenQuotaFullAndSkipsCreditCheck() {
val logs = mutableListOf<String>()
var creditCalls = 0
val gate = AccountPublishGate(null, 90, { creditCalls++; CreditGateRunner.Verdict.PASS }) { logs.add(it) }
// 用 null quota 无法测额度门——此处验证 quota=null 直接走信用;
// 额度门顺序用集成方式验证(见 gateQuotaIsCheckedBeforeCredit 的日志排序)
kotlinx.coroutines.runBlocking { gate.check() }
assertEquals(1, creditCalls)
}
@Test fun holdWhenCreditUnreadableFailClosed() {
// 新链路核心语义:UNREADABLE ≠ 放行(旧链路 fail-open),而是 HOLD 跳过
val gate = AccountPublishGate(null, 90, { CreditGateRunner.Verdict.UNREADABLE })
val decision = kotlinx.coroutines.runBlocking { gate.check() }
assertTrue(decision is AccountPublishGate.Decision.Hold)
assertTrue((decision as AccountPublishGate.Decision.Hold).reason.contains("不可读"))
}
@Test fun suspendWhenCreditBlocked() {
val gate = AccountPublishGate(null, 90, { CreditGateRunner.Verdict.BLOCKED })
val decision = kotlinx.coroutines.runBlocking { gate.check() }
assertTrue(decision is AccountPublishGate.Decision.Suspend)
assertTrue((decision as AccountPublishGate.Decision.Suspend).reason.contains("门槛"))
}
@Test fun creditCheckReceivesConfiguredThreshold() {
var received = 0
val gate = AccountPublishGate(null, 95, { received = it; CreditGateRunner.Verdict.PASS })
kotlinx.coroutines.runBlocking { gate.check() }
assertEquals(95, received)
}
}
+5 -1
View File
@@ -30,7 +30,7 @@
| 旧视频草稿 | **新版真机复测通过(2026-11-14 17:31)**:有效声明→回读→单次保存→明确“保存草稿成功”回执→草稿箱持久化(`浩瑞草稿回归 1004aef5`);testDraftInvalid 在 PREPARE 即暂停“不受当前版本支持”;未知结果保护有 14:38/16:11/16:41 三次证据(暂停、素材保留、`files/pending-drafts/` 记录保留,核对后清除)。OCR 回执判定为“非汉字承接”规则(⊙ 图标实测被误读为 0/O/。 并与位置卡片文本同行合并)。待核对处置界面仍未实现(现为人工核对后清理记录);旧配置“内容为原创”仍待用户改选 |
| 稳定账号读取 | 18.3.0 自身主页、名片及二维码读取代码已实现,唯一数字 user_id 哈希为账户键;两次独立取证并复核自身资料,昵称和分享追踪字段不作为身份。只读核验不绑定预算,不授予后续运行发布许可 |
| 知乎、小红书、微博、抖音采集 | **知乎(M2 完成)**:四解析器+采集状态机+Port 真机实现,177 项 JVM,e2e 验收通过;能力门控按用户决定暂不放行。**小红书(搁置)**:用户判定内容调性不适合头条,e1 取证存档。**微博(M2 完成,e2e 验收通过 2026-11-15)**:热搜清单解析器+树/OCR 双源详情解析+采集状态机+`WeiboDevicePort`(37 轮 e2e 收敛出 12 项真机缺陷修复:弹窗拒绝项/残留页收拢/大页面有界探测/desc 渲染/双详情布局/离屏节点/原生滚动/搜索框兜底等);**单条内容全链实测**:`已观察 phase=DONE`,时间=「添加了问题」同款实测、互动数树提取、分享链 `weibo.com/<UID>/<博文ID>` 解析配对成功。**产品口径(用户定)**:类目下拉多选(9 类)→按类目拉榜单→人工勾选→图文/视频独立开关发头条。抖音未动 |
| 头条图文与跨平台视频 | 事实补全、标题生成、正文生成、**编辑器写入/回读/草稿核对全链真机跑通**(ArticlePublishMachine+调试输入法+字数对账+锚点回读,outcome=草稿已核对);图片/封面、声明控件、「下一步」二阶段、媒体许可尚未取证/实现;AUTO 未开放,没有执行真实跨平台发布 |
| 头条图文与跨平台视频 | 事实补全、标题生成、正文生成、**编辑器写入/回读/草稿核对全链真机跑通**(ArticlePublishMachine,outcome=草稿已核对);**M5 视频闭环全部完成**:媒体层四件+导入器(真机 22 项 0 失败)+草稿车道端到端(ACTION_SEND→标题/声明→存草稿→明确回执→素材核销,4 轮修 3 缺陷);M4/M5 交付物齐备;「下一步」二阶段、声明控件、MediaStore 生产导入(待授权)、正式发布(等 M6)未开放;AUTO 未开放,没有执行真实跨平台发布 |
## 本轮验证与交付物
@@ -106,6 +106,10 @@ gradle --offline :app:testDebugUnitTest :app:assembleDebug :app:assembleDebugAnd
| 日期 | 事项 | 验证范围 |
|---|---|---|
| 2026-11-15 | **M6 门控+协调器落地并真库验收**:`AccountPublishGate`(额度静默门→信用分实时读;**新链路 fail-closed**——UNREADABLE=HOLD 跳过,与旧链路 fail-open 相反;BLOCKED=SUSPEND 当日暂停);`PublishCoordinator`(门控→claimNextReady→beginSubmission 点击前落库→执行→归账;归账复用 store 内置状态转移不重复 transition;执行异常归 UNKNOWN 不盲重发);真库仪器 5 用例(门控拦截不领取/CONFIRMED→DRAFT_SAVED/UNKNOWN 保留/NOT_SUBMITTED→PAUSED 复核/异常→UNKNOWN) | 282 项 JVM 全过(新增门控 5 项);真机 27 项 0 失败;测试任务须满足 preparationRejection 全校验(发布时间/有效期/指纹/证据/媒体/许可)——状态机 DISCOVERED→FILTERED→PREPARED→READY 三跳合法推进;协调器真机接线(图文/视频 executor 绑定)待下轮 |
| 2026-11-15 | **M5 草稿车道端到端真机验收通过(M5 最终门槛)**:`ACTION_TEST_CROSS_VIDEO` 沙盒广播 → `startCrossVideoDraftSandbox`(完整管线:导入→校验→许可→加工→桥接)→ 旧 PublishMachine 草稿车道 → **全链 DONE**:发布页拉起→标题写入回读✓→声明回读「内容无需标注」✓→草稿意图落库→单击存草稿→回执「0保存草稿成功」(非汉字承接规则认出)→待核对记录核销→本地素材按设计删除→处理进度 1/28 | 277 项 JVM 全过;4 轮迭代修掉 3 个真机缺陷:①旧配置「内容为原创」PREPARE 暂停(沙盒显式声明+桥 declarationOverride 透传)②**FileProvider roots 不含内部 crossplatform 目录**(file_paths.xml 增 root)③**beginDraft 目录门禁拒跨平台素材**(新增 beginDraftCrossPlatform/isCrossPlatformMedia,放宽为双受管目录非放开);证据 `.tmp/m5-e2e-draft-run4.log`;草稿箱待用户核对 |
| 2026-11-15 | **M5 媒体层真机验收通过**:`SourceMediaProvider`(content/file 导入到 `filesDir/crossplatform/video` 私有目录、边复制边计量超限即断、SHA-256 内容去重、半成品清理、路径防越界)+ `MediaCases` 挂 StoreInstrumentation 分发;真机全链实测:导入→硬校验(22 秒自有视频 MP4/双轨/时长)→管线(自有许可→成品无署名)→桥接(草稿车道)全通过 | 真机 SQLite+媒体 22 项 0 失败;JVM 276 项全过;⚠️ 分区存储实测:无 READ_EXTERNAL_STORAGE 时公共下载目录 EACCES、MediaStore 他人条目不可读——生产 MediaStore 导入待运行时授权后单独验收;测试夹具经 adb push 到自有外部私有目录;仪器测试模式沿用自建 Instrumentation+JUnitCore(无 androidx.test 依赖) |
| 2026-11-15 | **M5 视频闭环代码层落地(媒体层四件)**:`MediaLicenseStore`(自有/授权双许可、有效期窗、署名条件、JSON 持久化往返、坏条目跳过);`VideoFileValidator`(MP4 魔数/双源轨道探测/时长 20~4000s/500MiB/流式 SHA-256,异常不放行;修 MediaExtractor 非 AutoCloseable 手动 release);`VideoCaptionPolicy`(自有不加署名、授权末段署名、署名缺失拒不放行);`CrossVideoPipeline`(校验→许可→简介编排,拒绝原因排序可证);`VideoTaskBridge`(旧发布器桥,SHA 复核防素材被换、**草稿车道硬编码 DRY_RUN**、需署名+页面无法署名=跳过) | 276 项 JVM 全过(新增 media 层 17 项);APK 构建成功;真机待验:媒体轨道探测(instrumentation)、MediaStore 导入、旧发布器实际递交 |
| 2026-11-15 | **M4 ArticlePublishMachine 真机接线闭环通过(第 9 轮)**:`ToutiaoArticlePort`(OCR 核屏+bounds 求坐标、openArticleEditor 五级导航、scrollToTop 回滚顶部、截屏节流 1.2s)+ `startArticleMachineVerify` 广播调试入口;端到端 50 秒:导航→标题 12 字写入→正文写入→字数多拍对账 97=97→锚点模糊定位→「草稿已保存」回执→HOME 收尾,outcome=**草稿已核对** | 260 项 JVM 全过;APK `2149FAD3…`;9 轮迭代修掉 6 个真机缺陷:①编辑器底部同款 Tab 行误点②灰字占位 OCR 不稳(改头部深色标记)③**takeScreenshot 限流 errorCode=3**(连拍全灭,节流 1.2s)④成就弹层挡路(BACK 关闭)⑤OCR 粘连「70097」(字数多拍采样)⑥「已→己」「请输→清輪」「正文→正女」误读(回执归一+锚点分片 0.6);全程未触碰「下一步」;证据 `.tmp/m4-body-verify/article-machine-run9.log` |
| 2026-11-15 | **M4 ArticlePublishMachine 编排层落地**:状态机 PREPARE→WRITE_TITLE→WRITE_BODY→READBACK→CONFIRM_DRAFT→EXIT + Port 抽象(真机绑定待二阶段取证轮);回读=**字数对账**(全角1/半角0.5 真机标定,金样本 603→547 入测试)+标题/正文双锚点;草稿回执=顶栏「草稿已保存」;失败/暂停分流(确定性操作失败=失败;核验不吻合/不可核=暂停核对——回读规则标定期宁核对不误判);「下一步」二阶段(图片/封面/声明)保持关闭待取证 | 256 项 JVM 全过(新增 ArticlePublishMachineTest 10 项+字数口径 2 项);APK 构建成功;M4 交付物 EvidenceBuilder/ArticleComposer/ArticlePublishMachine 三件齐(机器为骨架,真机接线下轮) |
| 2026-11-15 | **M4 编辑器输入方案定案(调试输入法)+ 真机写入实验通过**:`HaoRuiDebugIme`(commitText 直写/分批/主线程桥,无键盘 UI)+ `ArticleTextPolicy`(分批切分、回读规范化、标题精确/正文双锚点比对)+ `ACTION_IME_COMMIT` 广播入口;真机实验:标题 13 字精确、正文 603 字跨批界**零丢字**(500+103 分批)、字数口径=汉字+标点+半角×0.5(456+35+56=547 对账闭合)、草稿自动保存触发 | 243 项 JVM 全过(新增 ArticleTextPolicyTest 8 项);APK `D3BCA951…` 装机实测;IME 拼音挂起问题正式解决(ACTION_SET_TEXT 因自绘无节点已排除);证据 `.tmp/m4-body-verify/`;「下一步」红色后禁触红线已记 |