fix: 修复视频筛选并更新纯手机方案与 UI 原型

接入点赞、粉丝、发布时间硬筛选和候选优选,补充 16 项策略测试。整合开发文档,新增纯手机跨平台设计与离线 UI 原型;新增跨平台运行功能仍待实现。同步 D 盘公共工具链配置。
This commit is contained in:
2026-11-13 15:37:20 +08:00
parent 205cf88c27
commit 02824baf02
23 changed files with 1352 additions and 3465 deletions
+1
View File
@@ -71,4 +71,5 @@ dependencies {
implementation("com.google.mlkit:text-recognition-chinese:16.0.1")
debugImplementation("androidx.compose.ui:ui-tooling")
testImplementation("junit:junit:4.13.2")
}
@@ -192,6 +192,7 @@ class HaoRuiAccessibilityService : AccessibilityService() {
restBrowse.updateConfig(cfg.browse)
pipeline.installAiRewrite(AiRewriteService(cfg.ai))
pipeline.autoPublish = cfg.toutiao.autoPublish
pipeline.updateSelectionConfig(cfg.toutiao)
RunLogger.i(
TAG,
"配置已注入全链路: provider=${cfg.ai.provider}, titleMax=${cfg.ai.titleMax}, " +
@@ -84,6 +84,7 @@ object ToutiaoSelectors {
/** 视频详情页 TikTokActivity(复核 + 交互)—— 主战场 */
const val ID_DETAIL_TITLE = "com.ss.android.article.news:id/nf7" // 🆕 标题全文
const val ID_DETAIL_AUTHOR = "com.ss.android.article.news:id/i7e" // 🆕 作者
const val ID_DETAIL_AVATAR = "com.ss.android.article.news:id/bga" // 作者主页入口
const val ID_DETAIL_TIME = "com.ss.android.article.news:id/jmb" // 🔴 发布时间(替换 o08)
const val ID_LIKE = "com.ss.android.article.news:id/gz1" // 🔴 点赞(替换 epp)
const val ID_LIKE_COUNT = "com.ss.android.article.news:id/e1m" // 🆕 点赞数字
@@ -136,6 +137,8 @@ object ToutiaoSelectors {
const val ID_PUBLISH_ENTRY = "com.ss.android.article.news:id/q4b"
const val ID_FOLLOW_COUNT = "com.ss.android.article.news:id/ho2"
const val ID_FANS_COUNT = "com.ss.android.article.news:id/hnz"
const val ID_PROFILE_NAME = "com.ss.android.article.news:id/hqt"
const val ID_PROFILE_FANS_VALUE = "com.ss.android.article.news:id/hny"
const val ID_LIKED_COUNT = "com.ss.android.article.news:id/hnn"
const val ID_SETTINGS = "com.ss.android.article.news:id/hrf"
const val TXT_CREATION_CENTER = "创作中心"
@@ -13,6 +13,10 @@ import com.haorui.app.automation.Targets
import com.haorui.app.automation.TaskStatusBus
import com.haorui.app.automation.ToutiaoSelectors
import com.haorui.app.automation.scheduler.LaneScheduler
import com.haorui.app.automation.selection.VideoMetrics
import com.haorui.app.automation.selection.VideoMetricsReader
import com.haorui.app.automation.selection.VideoSelectionBatch
import com.haorui.app.automation.selection.VideoSelectionPolicy
import com.haorui.app.data.model.ToutiaoConfig
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
@@ -27,8 +31,8 @@ import java.util.concurrent.atomic.AtomicBoolean
/**
* 浩瑞 · 采集状态机
*
* 对照原产品 `AutomationCycleRunner` case 1 的 4 相位:
* SCAN → OPEN → SHARE → CLIPBOARD
* 在原产品采集链路中加入作者核对和候选比较:
* SCAN → OPEN → AUTHOR → RETURN_DETAIL → OPEN → SHARE → CLIPBOARD
*
* 与原版的差异(都是修正,不是照抄):
* - 相位用命名枚举,不用魔法数字
@@ -65,6 +69,10 @@ class CollectMachine(
SCAN,
/** 打开候选卡片 + 模拟观看 */
OPEN,
/** 进入已核对身份的作者主页读取粉丝 */
AUTHOR,
/** 返回原视频并重新核对标题、作者和指标 */
RETURN_DETAIL,
/** 分享面板找「复制链接」 */
SHARE,
/** 读剪贴板交下游流水线 */
@@ -91,6 +99,16 @@ class CollectMachine(
private var nonVideoStreak = 0 // 连续非视频候选计数(卡怪页面的自愈信号)
private var durationMissStreak = 0 // 连续时长不达标/未识别计数(对照原 f1222G)
private var pauseUntilMs = 0L // 本轮未找到素材的休息截止(对照原 f1293q0/W2)
private val metricsReader = VideoMetricsReader(svc)
private val selectionBatch = VideoSelectionBatch<CollectResult>()
private var batchConfig = toutiaoConfig
private var currentMetrics = VideoMetrics()
private var currentAuthor = ""
private var metricsRetry = 0
private var authorRetry = 0
private var returnRetry = 0
private var authorChecked = false
private var authorRejection: String? = null
/** 已采集 URL 的 SHA-256 指纹(去重,对应原 C7 管线) */
private val seenFingerprints = LinkedHashSet<String>()
@@ -130,6 +148,8 @@ class CollectMachine(
when (phase) {
Phase.SCAN -> doScan()
Phase.OPEN -> doOpen()
Phase.AUTHOR -> doReadAuthor()
Phase.RETURN_DETAIL -> doReturnDetail()
Phase.SHARE -> doShare()
Phase.CLIPBOARD -> doClipboard()
}
@@ -142,6 +162,17 @@ class CollectMachine(
private suspend fun doScan() {
log("SCAN: tick phase=$phase")
val config = toutiaoConfig
if (batchConfig != config) {
selectionBatch.clear()
seenTitles.clear()
if (batchConfig.category != config.category) channelEntered = false
batchConfig = config
}
VideoSelectionPolicy.invalidConfigReason(config)?.let { reason ->
TaskStatusBus.status("采集已等待:$reason")
return
}
// ── 本轮未找到素材的休息期(对照原 W2/f1293q0)──────────
val nowMs = SystemClock.elapsedRealtime()
if (nowMs < pauseUntilMs) {
@@ -291,6 +322,11 @@ class CollectMachine(
}
tab?.let { runCatching { it.recycle() } }
if (selectionBatch.isReady(config, System.currentTimeMillis())) {
dispatchBestCandidate()
return
}
log("进入信息流扫描")
val cards = NodeLocator.all(root, Selector.ResId(ToutiaoSelectors.ID_CARD), limit = 12)
log("找到 ${cards.size} 个卡片节点")
@@ -334,6 +370,13 @@ class CollectMachine(
// 打开前先记入已见(对照原 a0:选中即 add,防止异常中断后重开同卡)
currentCardTitle = cardTitleOf(target)
markTitleSeen(currentCardTitle)
currentMetrics = VideoMetrics()
currentAuthor = ""
metricsRetry = 0
authorRetry = 0
returnRetry = 0
authorChecked = false
authorRejection = null
// ⚠️ 2026-10-30 真机修复:点**标题**而非容器中心 ——
// 中心常落在作者区/内嵌视频上,被带进作者主页(联调实录死循环)。
val titleNode = NodeLocator.byId(target, ToutiaoSelectors.ID_TITLE)
@@ -345,6 +388,7 @@ class CollectMachine(
svc.gestures.tapNode(target)
}
if (ok) {
selectionBatch.recordAttempt(System.currentTimeMillis())
openAtMs = SystemClock.elapsedRealtime()
watchMs = randomWatchMs()
copyRetry = 0
@@ -354,7 +398,7 @@ class CollectMachine(
watchAnnounced = false
openVideoRetry = 0
go(Phase.OPEN)
TaskStatusBus.status("已打开首条初筛候选,等待详情页")
TaskStatusBus.status("正在考察候选 ${selectionBatch.examined}/${if (config.hotSelectionEnabled) config.candidateSampleSize else 1},等待详情页指标")
log("已打开候选卡片,模拟观看 ${watchMs}ms")
} else {
log("tapNode 失败,下一轮重试")
@@ -392,6 +436,7 @@ class CollectMachine(
NodeLocator.recycleAll(cards)
if (slideCount >= slideLimit) {
if (selectionBatch.examined > 0 && dispatchBestCandidate()) return
TaskStatusBus.status("可见卡片扫描结束")
log("连续滑动已达上限 $slideCount,重开头条刷新信息流")
newRound()
@@ -425,7 +470,7 @@ class CollectMachine(
val root = svc.root()
if (root == null) {
log("OPEN: 根节点为空,等待")
retryMetricsOrSkip("详情页暂不可读取")
return
}
@@ -464,15 +509,25 @@ class CollectMachine(
openVideoRetry = 0
nonVideoStreak = 0
// 抓详情页标题(供 AI 改写用,对照原产品 TaskStepRunner:196)
detailTitle = searchWithTimeout(3000L) {
NodeLocator.byId(root, "nf7")?.let { node ->
val t = node.text?.toString() ?: ""
runCatching { node.recycle() }
t
}
} ?: ""
if (detailTitle.isNotBlank()) log("OPEN: 抓到标题: ${detailTitle.take(30)}…")
val detail = metricsReader.readDetail(root, System.currentTimeMillis())
if (detail.title.isBlank() || detail.author.isBlank()) {
retryMetricsOrSkip("未识别到当前视频的标题或作者")
return
}
if (detailTitle.isNotBlank() && (detail.title != detailTitle || detail.author != currentAuthor)) {
TaskStatusBus.status("详情页视频已切换,跳过以防指标与链接错配")
finishCandidate()
return
}
detailTitle = detail.title
currentAuthor = detail.author
currentMetrics = detail.metrics.copy(fans = currentMetrics.fans)
val beforeFans = VideoSelectionPolicy.rejection(currentMetrics, toutiaoConfig, System.currentTimeMillis(), requireFans = false)
if (beforeFans != null) {
if (currentMetrics.likes == null || currentMetrics.publishedAtMs == null) retryMetricsOrSkip(beforeFans)
else rejectCandidate(beforeFans)
return
}
// ── 时长过滤(对照原 v()/GestureTimeoutHandler:video_min..video_max)──
// ⚠️ 文本可解析时长才做硬过滤;解析不到不拦(OCR 初筛留待阶段 5,
@@ -494,6 +549,31 @@ class CollectMachine(
durationMissStreak = 0 // 对照原 v():时长通过则清零连续不达标
}
if (!authorChecked) {
val authorNode = NodeLocator.byId(root, ToutiaoSelectors.ID_DETAIL_AUTHOR)
?: NodeLocator.byId(root, ToutiaoSelectors.ID_DETAIL_AVATAR)
val tapped = try {
authorNode != null && svc.gestures.tapNode(authorNode)
} finally {
runCatching { authorNode?.recycle() }
}
if (!tapped) {
retryMetricsOrSkip("无法打开当前视频作者主页")
return
}
metricsRetry = 0
TaskStatusBus.status("正在读取作者 $currentAuthor 的粉丝数")
go(Phase.AUTHOR)
return
}
val rejection = VideoSelectionPolicy.rejection(currentMetrics, toutiaoConfig, System.currentTimeMillis())
if (rejection != null) {
rejectCandidate(rejection)
return
}
metricsRetry = 0
log("指标硬筛选通过:点赞=${currentMetrics.likes} 粉丝=${currentMetrics.fans} 发布时间=${currentMetrics.publishedAtMs}")
// 节点查找加硬超时:视频详情页节点树极大,Binder IPC 遇 stale 节点可能永久挂起
// ⚠️ 对照原 G():分享按钮先查**全部窗口**(分享面板可能是独立窗口)
val share = searchWithTimeout(5000L) { findShareButton(root) }
@@ -528,6 +608,55 @@ class CollectMachine(
finishCandidate(swipeNext = true, resetChannel = true)
}
private suspend fun retryMetricsOrSkip(reason: String) {
metricsRetry++
if (metricsRetry < METRICS_RETRY_LIMIT) {
TaskStatusBus.status("$reason,等待重读 $metricsRetry/$METRICS_RETRY_LIMIT")
return
}
rejectCandidate("$reason(重试后仍未读取,严格跳过)")
}
private suspend fun rejectCandidate(reason: String) {
log("筛选拒绝:$reason;${detailTitle.ifBlank { currentCardTitle }.take(30)}")
TaskStatusBus.status("筛选跳过:$reason")
finishCandidate()
}
private suspend fun doReadAuthor() {
val root = svc.root()
val fans = if (root != null) metricsReader.readAuthorFans(root, currentAuthor) else null
if (fans == null && ++authorRetry < AUTHOR_RETRY_LIMIT) {
TaskStatusBus.status("等待作者主页粉丝数 $authorRetry/$AUTHOR_RETRY_LIMIT;未读取时不会放行")
return
}
currentMetrics = currentMetrics.copy(fans = fans)
authorChecked = true
authorRejection = VideoSelectionPolicy.rejection(currentMetrics, toutiaoConfig, System.currentTimeMillis())
log("作者粉丝核对:author=$currentAuthor fans=$fans 结论=${authorRejection ?: "通过"}")
svc.gestures.back()
go(Phase.RETURN_DETAIL)
}
private suspend fun doReturnDetail() {
val root = svc.root()
val titleNode = NodeLocator.byId(root, ToutiaoSelectors.ID_DETAIL_TITLE)
val title = try {
runCatching { titleNode?.takeIf { it.isVisibleToUser && NodeLocator.hasValidBounds(it) }?.text?.toString() }.getOrNull()
} finally { runCatching { titleNode?.recycle() } }
if (title == detailTitle) {
val rejection = authorRejection
if (rejection != null) rejectCandidate(rejection)
else go(Phase.OPEN) // 再读点赞、时间及作者,防主页往返期间视频已切换。
return
}
if (++returnRetry >= AUTHOR_RETRY_LIMIT) {
log("未能返回原视频,放弃候选并回首页,禁止复制其他视频链接")
TaskStatusBus.status("未返回原视频,已跳过候选并重新定位频道")
finishCandidate(goHome = true, resetChannel = true)
}
}
// ── 相位:分享面板找「复制链接」 ──────────────────────────
private suspend fun doShare() {
@@ -789,8 +918,8 @@ class CollectMachine(
}
log("取到链接:${url.take(48)}")
TaskStatusBus.status("已读取新复制链接,正在后台处理")
handoff(url)
TaskStatusBus.status("已读取合格候选链接,加入热度比较")
addCandidate(url)
// ⚠️ 2026-10-31 根治「循环播一个视频」:成功收尾必须**退回详情页**再开新一轮。
// 原实现只 newRound(),人留在 TikTok 详情页(短视频自动循环播放),
// SCAN 又把详情页误判成信息流 → 表象即「一直在一个视频上循环播放」。
@@ -828,16 +957,40 @@ class CollectMachine(
return bytes.joinToString("") { "%02x".format(it) }
}
private fun handoff(url: String) {
private fun addCandidate(url: String) {
if (batchConfig != toutiaoConfig) {
log("考察期间配置已修改,本候选不进入旧批次")
return
}
VideoSelectionPolicy.rejection(currentMetrics, toutiaoConfig, System.currentTimeMillis())?.let {
log("复制链接前再次筛选未通过:$it")
return
}
val result = CollectResult(
url = url,
title = detailTitle,
fingerprint = sha256(url),
source = CollectSource.TOUTIAO_FEED,
collectedAtMs = System.currentTimeMillis(),
selectionMetrics = currentMetrics,
selectionCategory = toutiaoConfig.category,
)
log("已交接下游流水线: ${result.summary()}")
onCollected?.invoke(result)
selectionBatch.offer(result, currentMetrics)
log("合格候选入池: ${result.summary()} score=${VideoSelectionPolicy.score(currentMetrics, System.currentTimeMillis())}")
}
private fun dispatchBestCandidate(): Boolean {
val examined = selectionBatch.examined
val best = selectionBatch.takeBest(toutiaoConfig, System.currentTimeMillis())
if (best == null) {
TaskStatusBus.status("本轮考察 $examined 条,无符合全部筛选条件的视频,继续寻找")
log("热度比较结束:考察=$examined,无合格候选;未提交发布")
return false
}
log("热度优选:考察=$examined score=${VideoSelectionPolicy.score(best.metrics, System.currentTimeMillis())} ${best.value.summary()}")
TaskStatusBus.status("已从 $examined 条候选中选出最优合格视频,转入后台处理")
onCollected?.invoke(best.value)
return true
}
/** 采集完成回调(由阶段 3 管线注册) */
@@ -1034,6 +1187,10 @@ class CollectMachine(
}
currentCardTitle = ""
detailTitle = ""
currentAuthor = ""
currentMetrics = VideoMetrics()
authorChecked = false
authorRejection = null
newRound()
}
@@ -1105,6 +1262,8 @@ class CollectMachine(
private fun randomWatchMs(): Long = com.haorui.app.util.randomIn(toutiaoConfig.playMin.toLong(), toutiaoConfig.playMax.toLong()) * 1000L
companion object {
private const val METRICS_RETRY_LIMIT = 3
private const val AUTHOR_RETRY_LIMIT = 5
/** 分享面板图标行横滑上限(对照原 f1284l ≤6) */
private const val SCROLL_LIMIT = 6
@@ -1167,6 +1326,10 @@ data class CollectResult(
val source: CollectSource,
/** 采集时间戳(毫秒) */
val collectedAtMs: Long,
/** 筛选时实读指标,供入队、出队再次检查时间和当前配置。 */
val selectionMetrics: VideoMetrics? = null,
val selectionCategory: String? = null,
) {
fun summary(): String = "[${source.name}] ${title.take(20)}… ${url.take(48)}… fp=${fingerprint.take(8)}"
fun summary(): String = "[${source.name}] ${title.take(20)}… ${url.take(48)}… fp=${fingerprint.take(8)}" +
(selectionMetrics?.let { " likes=${it.likes} fans=${it.fans} publishedAt=${it.publishedAtMs}" } ?: "")
}
@@ -78,6 +78,7 @@ class PublishMachine(
private var title: String = ""
private var mediaUri: String = ""
private var autoPublish: Boolean = true
private var eligibilityCheck: (() -> String?)? = null
private var declaration: String = ToutiaoSelectors.TXT_DECLARATION_DEFAULT
private var titleRetry = 0
@@ -105,7 +106,8 @@ class PublishMachine(
* @return true=已受理;false=发布机忙(调用方应暂存重试)
*/
@Synchronized
fun submit(title: String, mediaUri: String, autoPublish: Boolean = true, declaration: String? = null): Boolean {
fun submit(title: String, mediaUri: String, autoPublish: Boolean = true, declaration: String? = null,
eligibilityCheck: (() -> String?)? = null): Boolean {
if (phase != Phase.IDLE) {
log("发布机非空闲(phase=$phase),拒绝新任务")
return false
@@ -113,6 +115,7 @@ class PublishMachine(
this.title = title
this.mediaUri = mediaUri
this.autoPublish = autoPublish
this.eligibilityCheck = eligibilityCheck
this.declaration = declaration ?: toutiaoConfig.workDeclaration
this.titleRetry = 0
this.coverFramesTried = 0
@@ -527,6 +530,12 @@ class PublishMachine(
/** 点发布 / 存草稿 */
private suspend fun doConfirm() {
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)
@@ -674,6 +683,7 @@ class PublishMachine(
restBrowse?.startRest("发布完成")
title = ""
mediaUri = ""
eligibilityCheck = null
reset()
}
@@ -696,6 +706,7 @@ class PublishMachine(
}
title = ""
mediaUri = ""
eligibilityCheck = null
// 对照原 n2():失败收尾同样 `X2("发布失败")` 进休息,再接下一条
TaskStatusBus.status("发布失败,已清理本轮素材,进入休息后继续下一条")
restBrowse?.startRest("发布失败")
@@ -0,0 +1,86 @@
package com.haorui.app.automation.selection
import android.graphics.Rect
import android.view.accessibility.AccessibilityNodeInfo
import com.haorui.app.automation.HaoRuiAccessibilityService
import com.haorui.app.automation.NodeLocator
import com.haorui.app.automation.ToutiaoSelectors
import com.haorui.app.ocr.ScreenCapturer
import com.haorui.app.overlay.MonitorOverlay
import kotlinx.coroutines.delay
import kotlinx.coroutines.withTimeoutOrNull
/** 只读取当前视频控件和已核对身份的作者主页,避免将评论点赞、自己粉丝或画面文字当作指标。 */
class VideoMetricsReader(private val service: HaoRuiAccessibilityService) {
private val capturer = ScreenCapturer(service)
data class Detail(val title: String, val author: String, val metrics: VideoMetrics)
suspend fun readDetail(root: AccessibilityNodeInfo, nowMs: Long): Detail {
val title = textOf(root, ToutiaoSelectors.ID_DETAIL_TITLE).firstOrNull().orEmpty()
val author = textOf(root, ToutiaoSelectors.ID_DETAIL_AUTHOR).firstOrNull().orEmpty()
var likes = (textOf(root, ToutiaoSelectors.ID_LIKE_COUNT) + textOf(root, ToutiaoSelectors.ID_LIKE))
.firstNotNullOfOrNull { VideoMetricParser.parseCount(it) }
var publishedAt = textOf(root, ToutiaoSelectors.ID_DETAIL_TIME)
.firstNotNullOfOrNull { VideoMetricParser.parsePublishedAt(it, nowMs) }
if (likes == null) {
likes = recognizeControl(root, ToutiaoSelectors.ID_LIKE_COUNT)
?.let { VideoMetricParser.parseCount(it) }
}
if (publishedAt == null) {
publishedAt = recognizeControl(root, ToutiaoSelectors.ID_DETAIL_TIME)
?.let { VideoMetricParser.parsePublishedAt(it, nowMs) }
}
return Detail(title, author, VideoMetrics(likes = likes, publishedAtMs = publishedAt))
}
fun isExpectedAuthor(root: AccessibilityNodeInfo, expectedAuthor: String): Boolean {
if (expectedAuthor.isBlank()) return false
val names = textOf(root, ToutiaoSelectors.ID_PROFILE_NAME)
return names.any { VideoMetricParser.authorMatches(expectedAuthor, it) }
}
suspend fun readAuthorFans(root: AccessibilityNodeInfo, expectedAuthor: String): Long? {
if (!isExpectedAuthor(root, expectedAuthor)) return null
// hnz 是“粉丝”标签,hny 才是数值;不可读取“关注”或“获赞”的相邻数字。
if (textOf(root, ToutiaoSelectors.ID_FANS_COUNT).none { it.trim() == "粉丝" }) return null
return textOf(root, ToutiaoSelectors.ID_PROFILE_FANS_VALUE)
.firstNotNullOfOrNull { VideoMetricParser.parseCount(it) }
?: recognizeControl(root, ToutiaoSelectors.ID_PROFILE_FANS_VALUE)?.let { VideoMetricParser.parseCount(it) }
}
private fun textOf(root: AccessibilityNodeInfo, id: String): List<String> {
val node = NodeLocator.byId(root, id) ?: return emptyList()
return try {
runCatching {
if (!node.isVisibleToUser || !NodeLocator.hasValidBounds(node)) emptyList()
else listOfNotNull(node.text?.toString(), node.contentDescription?.toString()).filter { it.isNotBlank() }
}.getOrDefault(emptyList())
} finally {
runCatching { node.recycle() }
}
}
/** OCR 只裁剪已定位的指标控件,禁止对整幅视频画面猜数字;旧系统或无控件时保持未知。 */
private suspend fun recognizeControl(root: AccessibilityNodeInfo, id: String): String? {
if (!capturer.isCaptureSupported) return null
val node = NodeLocator.byId(root, id) ?: return null
val bounds = Rect()
val visible = try {
runCatching {
node.getBoundsInScreen(bounds)
node.isVisibleToUser && !bounds.isEmpty
}.getOrDefault(false)
} finally {
runCatching { node.recycle() }
}
if (!visible) return null
MonitorOverlay.setHidden(true)
return try {
delay(150)
withTimeoutOrNull(6_000L) { capturer.captureAndRecognize(bounds) }?.trim()?.takeIf { it.isNotEmpty() }
} finally {
MonitorOverlay.setHidden(false)
}
}
}
@@ -0,0 +1,185 @@
package com.haorui.app.automation.selection
import com.haorui.app.data.model.ToutiaoConfig
import java.math.BigDecimal
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.ZoneId
import kotlin.math.ln1p
/** 只保存读到的数据;缺失值保持 null,不能当成 0 或“刚刚发布”。 */
data class VideoMetrics(
val likes: Long? = null,
val fans: Long? = null,
val publishedAtMs: Long? = null,
)
/** 页面数字和发布时间解析,不依赖 Android,便于用录屏节点文本回归。 */
object VideoMetricParser {
private const val NUMBER = "(?:[0-9]+(?:,[0-9]{3})*(?:\\.[0-9]+)?)\\s*(?:亿|万|千|[kKmMwW])?"
private val count = Regex("^($NUMBER)(?:次|人)?$")
private val labelledCount = Regex("^(?:点赞|获赞|粉丝|赞)[\\s::,,]*($NUMBER)(?:次|人)?$|^($NUMBER)\\s*(?:次点赞|个赞|赞|粉丝)$")
fun parseCount(raw: String?): Long? {
if (raw.isNullOrBlank()) return null
val text = normalize(raw).trim()
val token = count.matchEntire(text)?.groupValues?.get(1)
?: labelledCount.matchEntire(text)?.groupValues?.drop(1)?.firstOrNull { it.isNotEmpty() }
?: return null
val compact = token.replace(Regex("[\\s,]"), "")
val multiplier = when (compact.last()) {
'亿' -> 100_000_000L
'万', 'w', 'W' -> 10_000L
'千', 'k', 'K' -> 1_000L
'm', 'M' -> 1_000_000L
else -> 1L
}
val numeric = if (compact.last().isLetter() || compact.last() in "万亿") compact.dropLast(1) else compact
return runCatching { BigDecimal(numeric).multiply(BigDecimal.valueOf(multiplier)).longValueExact() }
.getOrNull()?.takeIf { it >= 0 }
}
fun parsePublishedAt(raw: String?, nowMs: Long, zone: ZoneId = ZoneId.systemDefault()): Long? {
if (raw.isNullOrBlank()) return null
val text = normalize(raw).trim()
val now = java.time.Instant.ofEpochMilli(nowMs).atZone(zone)
if (Regex("^(?:发布于\\s*)?刚刚(?:发布)?$").matches(text)) return nowMs
Regex("(?:^|发布于\\s*)([0-9]+)\\s*(秒|分钟|小时|天)前(?:发布)?$").find(text)?.let { match ->
val amount = match.groupValues[1].toLongOrNull() ?: return null
val unitMs = when (match.groupValues[2]) {
"秒" -> 1_000L
"分钟" -> 60_000L
"小时" -> 3_600_000L
else -> 86_400_000L
}
return runCatching { Math.subtractExact(nowMs, Math.multiplyExact(amount, unitMs)) }.getOrNull()
}
Regex("(?:^|发布于\\s*)(今天|昨天|前天)(?:\\s*([0-9]{1,2}):([0-9]{2}))?(?:发布)?$").find(text)?.let { match ->
val days = when (match.groupValues[1]) { "昨天" -> 1L; "前天" -> 2L; else -> 0L }
return runCatching {
val time = if (match.groupValues[2].isEmpty()) LocalTime.MIDNIGHT
else LocalTime.of(match.groupValues[2].toInt(), match.groupValues[3].toInt())
now.toLocalDate().minusDays(days).atTime(time).atZone(zone).toInstant().toEpochMilli()
}.getOrNull()
}
// 只对发布时间控件调用;绝不从标题或评论里猜测日期。
Regex("(?<![0-9])([0-9]{4})[-/.年]([0-9]{1,2})[-/.月]([0-9]{1,2})日?(?:[ T\\s]*([0-9]{1,2})[:时]([0-9]{1,2})(?:[:分]([0-9]{1,2}))?分?秒?)?").find(text)?.let { match ->
return dateTime(match.groupValues[1].toInt(), match, 2, zone)
}
// 无年份的日期取最近一次出现,正确处理一月看到十二月的作品。
Regex("(?<![0-9])([0-9]{1,2})[-/.月]([0-9]{1,2})日?(?:\\s*([0-9]{1,2}):([0-9]{2}))?(?![0-9])").find(text)?.let { match ->
val date = runCatching { LocalDate.of(now.year, match.groupValues[1].toInt(), match.groupValues[2].toInt()) }.getOrNull() ?: return null
val time = runCatching { if (match.groupValues[3].isEmpty()) LocalTime.MIDNIGHT else LocalTime.of(match.groupValues[3].toInt(), match.groupValues[4].toInt()) }.getOrNull() ?: return null
var value = date.atTime(time)
if (value.isAfter(now.toLocalDateTime())) value = value.minusYears(1)
return value.atZone(zone).toInstant().toEpochMilli()
}
return null
}
private fun dateTime(year: Int, match: MatchResult, offset: Int, zone: ZoneId): Long? = runCatching {
val groups = match.groupValues
LocalDateTime.of(year, groups[offset].toInt(), groups[offset + 1].toInt(),
groups[offset + 2].toIntOrNull() ?: 0, groups[offset + 3].toIntOrNull() ?: 0,
groups[offset + 4].toIntOrNull() ?: 0).atZone(zone).toInstant().toEpochMilli()
}.getOrNull()
private fun normalize(raw: String): String = buildString {
raw.forEach { ch -> append(when (ch) {
in '0'..'9' -> '0' + (ch - '0')
':' -> ':'
',' -> ','
'.' -> '.'
' ', '\u00a0', '\u202f' -> ' '
else -> ch
}) }
}
fun authorMatches(expected: String, actual: String): Boolean {
fun author(value: String) = value.trim().removePrefix("@").replace(Regex("\\s+"), "")
val name = author(expected)
return name.isNotEmpty() && name == author(actual)
}
}
object VideoSelectionPolicy {
const val MAX_BATCH_SIZE = 20
const val BATCH_TIMEOUT_MS = 120_000L
fun invalidConfigReason(config: ToutiaoConfig): String? = when {
config.likeMin < 0 || config.likeMax < config.likeMin -> "点赞数范围无效,请设置 0 ≤ 下限 ≤ 上限"
config.fansMin < 0 || config.fansMax < config.fansMin -> "粉丝数范围无效,请设置 0 ≤ 下限 ≤ 上限"
config.ageHours < 1 -> "发布时间限制必须至少为 1 小时"
config.hotSelectionEnabled && config.candidateSampleSize !in 1..MAX_BATCH_SIZE -> "候选比较数必须在 1~$MAX_BATCH_SIZE 之间"
else -> null
}
fun rejection(metrics: VideoMetrics, config: ToutiaoConfig, nowMs: Long, requireFans: Boolean = true): String? {
invalidConfigReason(config)?.let { return it }
val likes = metrics.likes ?: return "未识别到点赞数"
if (likes !in config.likeMin.toLong()..config.likeMax.toLong()) return "点赞 $likes 不在 ${config.likeMin}~${config.likeMax}"
val published = metrics.publishedAtMs ?: return "未识别到发布时间"
if (published > nowMs) return "发布时间晚于当前时间"
if (nowMs - published > config.ageHours.toLong() * 3_600_000L) return "发布时间超过 ${config.ageHours} 小时"
if (requireFans) {
val fans = metrics.fans ?: return "未识别到作者粉丝数"
if (fans !in config.fansMin.toLong()..config.fansMax.toLong()) return "作者粉丝 $fans 不在 ${config.fansMin}~${config.fansMax}"
}
return null
}
fun candidateRejection(title: String, category: String?, metrics: VideoMetrics?, config: ToutiaoConfig, nowMs: Long): String? {
invalidConfigReason(config)?.let { return it }
if (category != config.category) return "采集频道已变更"
if (config.keywords.split('-', ',', ',', '\n').any { it.isNotBlank() && title.contains(it.trim()) }) return "命中当前排除关键词"
return rejection(metrics ?: return "缺少采集筛选指标", config, nowMs)
}
/** 快照估计:平均每小时点赞 65% + 相对粉丝表现 25% + 新鲜度 10%。 */
fun score(metrics: VideoMetrics, nowMs: Long): Double {
val likes = (metrics.likes ?: 0).coerceAtLeast(0).toDouble()
val fans = (metrics.fans ?: 0).coerceAtLeast(100).toDouble()
val ageHours = ((nowMs - (metrics.publishedAtMs ?: nowMs)).coerceAtLeast(0) / 3_600_000.0)
// 至少按一小时计算,避免刚发布几秒的作品被速度指标无限放大。
return 0.65 * ln1p(likes / ageHours.coerceAtLeast(1.0)) +
0.25 * ln1p(1000.0 * likes / fans) + 0.10 / (1.0 + ageHours / 24.0)
}
}
/** 一批考察 N 条,保存已通过硬筛选且已取到链接的候选;超时或翻页到上限也可结束。 */
class VideoSelectionBatch<T> {
data class Candidate<T>(val value: T, val metrics: VideoMetrics)
private val candidates = mutableListOf<Candidate<T>>()
var examined: Int = 0
private set
private var startedAtMs: Long? = null
fun recordAttempt(nowMs: Long) {
if (startedAtMs == null) startedAtMs = nowMs
examined++
}
fun offer(value: T, metrics: VideoMetrics) {
candidates.add(Candidate(value, metrics))
}
fun isReady(config: ToutiaoConfig, nowMs: Long): Boolean = examined > 0 &&
(examined >= (if (config.hotSelectionEnabled) config.candidateSampleSize else 1) ||
nowMs - (startedAtMs ?: nowMs) >= VideoSelectionPolicy.BATCH_TIMEOUT_MS)
fun takeBest(config: ToutiaoConfig, nowMs: Long): Candidate<T>? {
// 配置改变、比较期间过期时重新硬筛选,不能凭旧结论发布。
val best = candidates.filter { VideoSelectionPolicy.rejection(it.metrics, config, nowMs) == null }
.maxWithOrNull(compareBy<Candidate<T>> { VideoSelectionPolicy.score(it.metrics, nowMs) }
.thenBy { it.metrics.publishedAtMs }.thenBy { it.metrics.likes })
clear()
return best
}
fun clear() {
candidates.clear()
examined = 0
startedAtMs = null
}
}
@@ -113,6 +113,8 @@ class ConfigRepository(private val context: Context) {
"random_cover" to c.toutiao.randomCover.toString(),
"video_only" to c.toutiao.videoOnly.toString(),
"auto_publish" to c.toutiao.autoPublish.toString(),
"hot_selection_enabled" to c.toutiao.hotSelectionEnabled.toString(),
"candidate_sample_size" to c.toutiao.candidateSampleSize.toString(),
"publish_total" to c.toutiao.publishTotal.toString(),
"completion_limit" to c.toutiao.completionLimit.toString(),
"rest_min" to c.toutiao.restMin.toString(),
@@ -205,6 +207,8 @@ class ConfigRepository(private val context: Context) {
randomCover = b("random_cover", d.toutiao.randomCover),
videoOnly = b("video_only", d.toutiao.videoOnly),
autoPublish = b("auto_publish", d.toutiao.autoPublish),
hotSelectionEnabled = b("hot_selection_enabled", d.toutiao.hotSelectionEnabled),
candidateSampleSize = i("candidate_sample_size", d.toutiao.candidateSampleSize),
publishTotal = i("publish_total", d.toutiao.publishTotal),
completionLimit = i("completion_limit", d.toutiao.completionLimit),
restMin = i("rest_min", d.toutiao.restMin),
@@ -20,6 +20,8 @@ data class ToutiaoConfig(
// 发布模式:true=正式发布(点「发布」),false=草稿(点「存草稿」,回归验证用)。
// 2026-10-30 P4:原实现硬编码 true 导致失去草稿验证手段;配置化后默认 true(行为不变)。
val autoPublish: Boolean = true,
val hotSelectionEnabled: Boolean = true,
val candidateSampleSize: Int = 5,
// 18 项数值参数
val publishTotal: Int = 28,
val completionLimit: Int = 28,
@@ -3,7 +3,10 @@ package com.haorui.app.pipeline
import com.haorui.app.automation.RunLogger
import com.haorui.app.automation.TaskStatusBus
import com.haorui.app.automation.machine.CollectResult
import com.haorui.app.automation.machine.CollectSource
import com.haorui.app.automation.machine.PublishMachine
import com.haorui.app.automation.selection.VideoSelectionPolicy
import com.haorui.app.data.model.ToutiaoConfig
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
@@ -121,6 +124,13 @@ class ContentPipeline(
@Volatile
var autoPublish: Boolean = true
@Volatile
private var selectionConfig = ToutiaoConfig()
fun updateSelectionConfig(config: ToutiaoConfig) {
selectionConfig = config
}
/**
* 处理一条采集结果。
* 由 CollectMachine.onCollected 回调触发,异步执行不阻塞采集。
@@ -129,6 +139,11 @@ class ContentPipeline(
scope.launch {
var inFlightVid: String? = null
try {
selectionRejection(result)?.let { reason ->
log("采集结果复查拒绝:$reason")
TaskStatusBus.status("候选复查跳过:$reason")
return@launch
}
log("处理采集结果: ${result.summary()}")
TaskStatusBus.status("已转入后台:解析、改标题和下载")
@@ -256,6 +271,13 @@ class ContentPipeline(
* 多半是内容问题,重发也失败,跳过更稳)。
*/
private fun submitOrQueue(task: PreparedTask) {
selectionRejection(task.result)?.let { reason ->
log("发布前筛选拒绝:$reason;已清理候选素材")
TaskStatusBus.status("发布前复查跳过:$reason")
if (task.videoId.isNotBlank()) inFlightVideoIds.remove(task.videoId)
videoDownloader?.deleteVideo(task.mediaUri)
return
}
// ⚠️ 2026-10-31 长测 P0 修复:配额硬限必须在**提交前**拦截,
// 对照原 `x2()`:配额耗尽不发布。否则 28/28 后仍超发。
if (!canPublish()) {
@@ -269,6 +291,7 @@ class ContentPipeline(
title = task.title,
mediaUri = task.mediaUri,
autoPublish = autoPublish,
eligibilityCheck = { selectionRejection(task.result) },
)
if (accepted) {
TaskStatusBus.status("素材已准备,正在打开头条发布页")
@@ -291,6 +314,13 @@ class ContentPipeline(
pending.addLast(task)
}
private fun selectionRejection(result: CollectResult): String? {
if (result.selectionMetrics == null && result.source != CollectSource.TOUTIAO_FEED) return null
val config = selectionConfig
return VideoSelectionPolicy.candidateRejection(result.title, result.selectionCategory,
result.selectionMetrics, config, System.currentTimeMillis())
}
/** 消化暂存队列(发布机空闲时由 PUBLISH 车道调用)——直接提交产物,不重跑管线 */
fun processPending() {
if (!publisher.isIdle || !canSubmit() || !canPublish()) return
@@ -14,6 +14,7 @@ import kotlinx.coroutines.launch
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.haorui.app.data.model.AppConfig
import com.haorui.app.automation.selection.VideoSelectionPolicy
import com.haorui.app.ui.components.ButtonRow
import com.haorui.app.ui.components.CheckRow
import com.haorui.app.ui.components.HaoRuiButton
@@ -29,7 +30,7 @@ import com.haorui.app.ui.components.TextRow
/**
* 头条采集设置(原「参数页」)— 18 项数值 + 类目 + 作品声明 + 排除关键词
* 对照 docs/ui-prototype.html #toutiao
* 对照 docs/技术架构与代码说明.md
*/
@Composable
fun ToutiaoConfigScreen(
@@ -68,6 +69,14 @@ fun ToutiaoConfigScreen(
CheckRow("随机封面", t.randomCover, { upd(t.copy(randomCover = it)) },
note = "发布时从视频帧随机选取封面")
CheckRow("只采集视频", t.videoOnly, { upd(t.copy(videoOnly = it)) })
CheckRow("热度优选", t.hotSelectionEnabled, { upd(t.copy(hotSelectionEnabled = it)) },
note = "比较合格候选的每小时点赞、相对粉丝表现和新鲜度")
if (t.hotSelectionEnabled) {
NumberField("每轮考察候选数(1~20)", t.candidateSampleSize,
{ upd(t.copy(candidateSampleSize = it)) }, Modifier.fillMaxWidth())
FieldHelp("默认考察 5 条后选出最优一条;达到 2 分钟或滑动上限也会选出当前最佳候选")
}
FieldHelp("点赞数、作者粉丝数和发布时间均须符合范围;数据重试后仍无法读取的作品会跳过")
}
Section(title = "数值参数", tag = "18 项") {
@@ -99,6 +108,7 @@ fun ToutiaoConfigScreen(
NumberField("点赞数 · 下限", t.likeMin, { upd(t.copy(likeMin = it)) }, Modifier.weight(1f))
NumberField("点赞数 · 上限", t.likeMax, { upd(t.copy(likeMax = it)) }, Modifier.weight(1f))
}
FieldHelp("点赞上限是硬限制,超过上限的热点也会跳过")
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
NumberField("粉丝数 · 下限", t.fansMin, { upd(t.copy(fansMin = it)) }, Modifier.weight(1f))
NumberField("粉丝数 · 上限", t.fansMax, { upd(t.copy(fansMax = it)) }, Modifier.weight(1f))
@@ -119,14 +129,16 @@ fun ToutiaoConfigScreen(
)
// 配置变更实时保存(onConfigChange → DataStore),无需手动保存按钮
FieldHelp("修改后自动保存到本机,无需点保存")
HaoRuiButton("离线筛选自检", { onToast("离线筛选自检完成") }, Modifier.fillMaxWidth())
HaoRuiButton("检查筛选参数", {
onToast(VideoSelectionPolicy.invalidConfigReason(t) ?: "筛选参数有效;采集时将逐条核对点赞、粉丝和发布时间")
}, Modifier.fillMaxWidth())
}
}
}
/**
* 百度采集设置 — 11 项数值 + 频道 + 行为
* 对照 docs/ui-prototype.html #baidu
* 对照 docs/技术架构与代码说明.md
*/
@Composable
fun BaiduConfigScreen(
@@ -203,7 +215,7 @@ fun BaiduConfigScreen(
/**
* 互动设置 — 新粉互动 / 随机回关 / 信用分门控 / 评论辅助
* 对照 docs/ui-prototype.html #interact
* 对照 docs/技术架构与代码说明.md
*/
@Composable
fun InteractScreen(
@@ -0,0 +1,151 @@
package com.haorui.app.automation.selection
import com.haorui.app.data.model.ToutiaoConfig
import java.time.Instant
import java.time.ZoneId
import kotlinx.serialization.json.Json
import org.junit.Assert.*
import org.junit.Test
class VideoSelectionPolicyTest {
private val zone = ZoneId.of("Asia/Shanghai")
private val now = Instant.parse("2026-11-13T04:30:00Z").toEpochMilli()
private val hour = 3_600_000L
private val config = ToutiaoConfig(likeMin = 10, likeMax = 300, fansMin = 100, fansMax = 20_000, ageHours = 72)
private fun metrics(likes: Long = 100, fans: Long = 1000, age: Long = hour) =
VideoMetrics(likes, fans, now - age)
@Test fun parsesCountsFromActualControlsAndChineseUnits() {
mapOf("24" to 24L, "点赞24" to 24L, "点赞,24" to 24L, "1,234" to 1234L,
"1.2万" to 12000L, "2937万" to 29370000L, "2.5亿" to 250000000L,
"2.5万" to 25000L, "2.3千" to 2300L, "1.5k" to 1500L, "1.2M" to 1200000L, "0" to 0L)
.forEach { (text, expected) -> assertEquals(text, expected, VideoMetricParser.parseCount(text)) }
}
@Test fun neverTurnsMissingCountsOrUnrelatedDigitsIntoZero() {
listOf(null, "", "点赞", "粉丝", "评论24", "2026-11-13", "新闻123", "-1", "1.2", "1万+", "999999999999999999999亿")
.forEach { assertNull(it, VideoMetricParser.parseCount(it)) }
}
@Test fun parsesActualDetailTimeAndItsAccessibilityDescriptionIdentically() {
val expected = Instant.parse("2026-10-23T03:28:00Z").toEpochMilli()
assertEquals(expected, VideoMetricParser.parsePublishedAt("2026-10-23 11:28", now, zone))
assertEquals(expected, VideoMetricParser.parsePublishedAt("2026年10月23日11时28分发布", now, zone))
assertEquals(expected, VideoMetricParser.parsePublishedAt("2026-10-23 11:28", now, zone))
}
@Test fun handlesRelativeAndYearlessDatesInTheDeviceZone() {
assertEquals(now - 3 * hour, VideoMetricParser.parsePublishedAt("3小时前", now, zone))
assertEquals(now - 15 * 60_000L, VideoMetricParser.parsePublishedAt("15分钟前", now, zone))
assertEquals(now, VideoMetricParser.parsePublishedAt("刚刚", now, zone))
assertEquals(Instant.parse("2026-11-12T12:00:00Z").toEpochMilli(), VideoMetricParser.parsePublishedAt("昨天 20:00", now, zone))
val january = Instant.parse("2026-01-01T04:30:00Z").toEpochMilli()
assertEquals(Instant.parse("2025-12-31T15:00:00Z").toEpochMilli(), VideoMetricParser.parsePublishedAt("12-31 23:00", january, zone))
}
@Test fun invalidOrUnknownDatesRemainUnknown() {
listOf(null, "", "未知", "发布时间", "2026-02-30 12:00", "2026-11-13 25:00", "昨天 25:00", "999999999999999999999小时前")
.forEach { assertNull(it, VideoMetricParser.parsePublishedAt(it, now, zone)) }
}
@Test fun enforcesAllThreeRangesIncludingExactBoundaries() {
assertNull(VideoSelectionPolicy.rejection(metrics(likes = 10, fans = 100, age = 72 * hour), config, now))
assertNull(VideoSelectionPolicy.rejection(metrics(likes = 300, fans = 20000, age = 0), config, now))
assertNotNull(VideoSelectionPolicy.rejection(metrics(likes = 9), config, now))
assertNotNull(VideoSelectionPolicy.rejection(metrics(likes = 301), config, now))
assertNotNull(VideoSelectionPolicy.rejection(metrics(fans = 99), config, now))
assertNotNull(VideoSelectionPolicy.rejection(metrics(fans = 20001), config, now))
assertNotNull(VideoSelectionPolicy.rejection(metrics(age = 72 * hour + 1), config, now))
assertNotNull(VideoSelectionPolicy.rejection(metrics(age = -1), config, now))
}
@Test fun rejectsMissingDataButAllowsFansToBeReadInTheNextPhase() {
assertNotNull(VideoSelectionPolicy.rejection(metrics().copy(likes = null), config, now))
assertNotNull(VideoSelectionPolicy.rejection(metrics().copy(fans = null), config, now))
assertNotNull(VideoSelectionPolicy.rejection(metrics().copy(publishedAtMs = null), config, now))
assertNull(VideoSelectionPolicy.rejection(metrics().copy(fans = null), config, now, requireFans = false))
}
@Test fun rejectsInvalidSettingsRatherThanSwappingOrIgnoringThem() {
listOf(config.copy(likeMin = -1), config.copy(likeMin = 301), config.copy(fansMin = -1),
config.copy(fansMin = 20001), config.copy(ageHours = 0), config.copy(candidateSampleSize = 0), config.copy(candidateSampleSize = 21))
.forEach { assertNotNull(VideoSelectionPolicy.rejection(metrics(), it, now)) }
}
@Test fun favorsRecentMomentumAndRelativeAudienceResponse() {
assertTrue(VideoSelectionPolicy.score(metrics(likes = 100, age = hour), now) >
VideoSelectionPolicy.score(metrics(likes = 200, age = 48 * hour), now))
assertTrue(VideoSelectionPolicy.score(metrics(fans = 1000), now) >
VideoSelectionPolicy.score(metrics(fans = 20000), now))
assertTrue(VideoSelectionPolicy.score(metrics(age = 0), now).isFinite())
assertEquals(VideoSelectionPolicy.score(metrics(age = 0), now),
VideoSelectionPolicy.score(metrics(age = 1000), now), 0.001)
}
@Test fun comparesTheWholeBatchRatherThanChoosingTheFirstAcceptedVideo() {
val batch = VideoSelectionBatch<String>()
repeat(4) { batch.recordAttempt(now) }
batch.offer("先出现的旧视频", metrics(likes = 200, age = 48 * hour))
batch.offer("后出现的近期热点", metrics(likes = 100, age = hour))
assertFalse(batch.isReady(config, now))
batch.recordAttempt(now)
assertTrue(batch.isReady(config, now))
assertEquals("后出现的近期热点", batch.takeBest(config, now)?.value)
assertEquals(0, batch.examined)
assertNull(batch.takeBest(config, now))
}
@Test fun finishesSparseBatchesOnTimeoutAndSupportsFirstQualifiedMode() {
val batch = VideoSelectionBatch<String>()
batch.recordAttempt(now)
batch.offer("唯一合格候选", metrics())
assertFalse(batch.isReady(config, now + VideoSelectionPolicy.BATCH_TIMEOUT_MS - 1))
assertTrue(batch.isReady(config, now + VideoSelectionPolicy.BATCH_TIMEOUT_MS))
assertTrue(batch.isReady(config.copy(hotSelectionEnabled = false), now))
assertEquals("唯一合格候选", batch.takeBest(config, now)?.value)
}
@Test fun rechecksExpirationAndChangedThresholdsWhenTakingTheWinner() {
val batch = VideoSelectionBatch<String>()
batch.recordAttempt(now)
batch.offer("即将过期", metrics(age = 72 * hour))
assertNull(batch.takeBest(config, now + 1))
batch.recordAttempt(now)
batch.offer("新阈值不再允许", metrics(likes = 100))
assertNull(batch.takeBest(config.copy(likeMin = 200), now))
}
@Test fun requiresTheSameAuthorBeforeUsingProfileFans() {
assertTrue(VideoMetricParser.authorMatches("@示例作者", "示例作者"))
assertTrue(VideoMetricParser.authorMatches(" 示例作者 ", "@示例作者"))
assertFalse(VideoMetricParser.authorMatches("示例作者", "其他作者"))
assertFalse(VideoMetricParser.authorMatches("@", ""))
assertFalse(VideoMetricParser.authorMatches("", ""))
}
@Test fun publicationGateRechecksCategoryKeywordsMissingMetricsAndAge() {
assertNull(VideoSelectionPolicy.candidateRejection("标题", config.category, metrics(), config, now))
assertNotNull(VideoSelectionPolicy.candidateRejection("标题", "其他频道", metrics(), config, now))
assertNotNull(VideoSelectionPolicy.candidateRejection("标题", config.category, null, config, now))
val excluded = config.copy(keywords = "广告,低质\n排除词-其他")
assertNotNull(VideoSelectionPolicy.candidateRejection("一条广告视频", config.category, metrics(), excluded, now))
assertNotNull(VideoSelectionPolicy.candidateRejection("含排除词的视频", config.category, metrics(), excluded, now))
assertNull(VideoSelectionPolicy.candidateRejection("正常视频", config.category, metrics(), excluded, now))
assertNotNull(VideoSelectionPolicy.candidateRejection("标题", config.category, metrics(age = 72 * hour), config, now + 1))
}
@Test fun disablingComparisonStillEnforcesMetricsButIgnoresItsHiddenSampleSetting() {
val firstQualified = config.copy(hotSelectionEnabled = false, candidateSampleSize = 0)
assertNull(VideoSelectionPolicy.invalidConfigReason(firstQualified))
assertNotNull(VideoSelectionPolicy.rejection(metrics(likes = 301), firstQualified, now))
assertNotNull(VideoSelectionPolicy.rejection(metrics().copy(fans = null), firstQualified, now))
}
@Test fun existingSavedConfigurationsLoadTheNewSelectionDefaults() {
val restored = Json.decodeFromString(ToutiaoConfig.serializer(), """{"category":"热点","likeMax":500}""")
assertEquals("热点", restored.category)
assertEquals(500, restored.likeMax)
assertTrue(restored.hotSelectionEnabled)
assertEquals(5, restored.candidateSampleSize)
}
}