diff --git a/docs/decisions.md b/docs/decisions.md
index 85608f0..a5e6a6a 100644
--- a/docs/decisions.md
+++ b/docs/decisions.md
@@ -89,3 +89,4 @@
| DEC-075 | **失效公开图片尝试公共 CDN 缓存/网页归档回退,且绝不用失效或占位响应覆盖已有有效图片**:① 四站点作品图片与封面、直播封面、最近解析缩略图 `thumbs/` 与本地头像 `avatars/` 统一先写临时文件并校验二进制魔数与非失效占位图后再原子落盘;目标位置已存在归属本条目的有效非占位图片时,重缓存、刷新或原帖被删均保留本地有效文件与清单记录,绝不删除或覆盖;② 直连源站(含微博边缘轮换与下载期最多 1 次详情重取)返回 HTTP `403`/`404`/`410` 或已知失效占位图时,仅对无签名公开静态图片 URL(`*.sinaimg.cn` 排除 `*.us.sinaimg.cn`、`pbs.twimg.com` 仅含 `format`/`name`、`*.hdslb.com` 静态图)按顺序无凭证查询 Jetpack Photon(`i0.wp.com`)→ `wsrv.nl`(`n=-1`)→ Internet Archive Wayback(`/web/0id_/`),严禁在 `429`/风控时触发,严禁向第三方发送任何 Cookie、凭证头或带签名/令牌参数的地址 | 用户,2026-11-25(“失效图片尝试第三方CDN缓存的获取方式,以及避免失效图覆盖有效图片”;[#61](https://github.com/chialecode/trace/issues/61)) | 遵循用户系统代理与 `GuardedMediaDialer` 私网拦截,返回字节须通过严格图片魔数与非占位校验;自动化测试仅连 `127.0.0.1` 合成提供方。[数据与缓存设计 §1、§2.4、§2.5](design/data-and-cache.md#cache)、[公共 CDN 回退研究](research/2026-11-25-expired-image-cdn.md) |
| DEC-076 | **全部缓存检查已缓存资源更新与任务页内容冲突保护(归档优先、零数据丢失)**:① 全部缓存(手动与 7 天定期 `fullCache`)顺带检查已缓存条目能否同源无损升级或补齐;抖音/微博/X 与 B 站动态直接复用列表页数据做零额外请求对比,B 站投稿采用三道门限(列表级标题/简介/时长比对、`cacheStandardVersion` 与规格上限跳过、7 天 `recheckedAt` 冷却 + `cache-queue` 40~150s 节奏)并将 `source="queue"` 纳入自动请求每小时额度记账,`trace-server` 远程版保持不执行;② 遇到远端已删除/不可用/试看或付费未购/地域受限/失效灰图占位 GIF/画质降级时,严禁覆盖本地有效缓存(即便选择“用新版替换”在执行期遇到失效降级也硬拦截 `ErrRemoteDegradedRefused`);③ 同源升级单调保护已有已校验弹幕快照(`Pxx.danmaku.xml`)、字幕、Hi-Res/杜比独立音轨、有效转发原帖 `Origin` 与完整 `LongText`;④ 遇到 V1/V2 资源不一致(换源改 `cid`、删减重排分 P、替换增删媒体、实质编辑正文,含手动重缓存/补全/升级/重试全入口冲突绊线)一律不静默覆盖,记入 `/cache-conflicts.json`(v1,零 URL/查询串/Cookie,含 `ignoredRevisions` 避免“保留本地”后每 7 天重复提示);⑤ 任务页新增“内容冲突(N)”(左栏全局任务角标仍只统计排队与进行中下载任务),批量默认采用无损的 **保留两版(推荐)**(先在 `.trace-stage-*` 完整下载校验 V2,通过后将 V1 归档为独立条目 `__v1-` 标 `archivedOf`、独立删除且不重复计入作品数,混合编辑时复用本地已校验未改动附件;覆盖替换先移入 `.trace-prev-*` 支持 Windows 文件锁失败立即回滚与启动自愈) | 用户,2026-11-25(“全部缓存时也检查已缓存条目是否有更新……不一致的在任务页面专门处理,防失效或 V2 覆盖 V1”“用更安全不易丢失数据的方式”;[#58](https://github.com/chialecode/trace/issues/58)) | 更新 [DEC-061](#dec-061) ①、[DEC-063](#dec-063) ③ 中已完整缓存条目一律跳过的规则。新增独立文件 `cache-conflicts.json`(`version: 1`),`item.json` 保持 v1 不升结构版本。正本:[需求 FR-CACHE-010、NFR-DATA-005](requirements.md#cache-scope)、[路线与验收 AC-89、90](delivery/roadmap.md#acceptance)、[订阅 §4](design/subscriptions.md#full-cache)、[数据与缓存 §1、§2.10](design/data-and-cache.md#cache-conflicts)、[界面规范 §3.6](ui.md#library) |
| DEC-078 | **微博图片改为双份保存(官方原图 + 无水印最大版伴侣文件)及看图层切换**:基于 [ACT-023](https://github.com/chialecode/trace/issues/19) V-07 与单帖对照实测证实微博 `/oslarge/` 会将原图降采样至 690px 宽(虽无平台水印,并非无损原分辨率),撤回以 `/oslarge/` 替换主图的做法,改为双份保存:① 静态图与实况静帧的主图 `images/NN.`(`role: "image"`)恒定保存官方最高清原图 `largest`(`/large/` 或 `/mw2000/`),绝不降分辨率;② 「设置 › 缓存与下载」保留 `weiboRemoveWatermark` 键(默认开启,文案「微博同时保存无水印版」),开启时额外拉取无水印最大版 `/oslarge/` 保存为伴侣文件 `images/NN_nowm.`(`role: "image_nowm"`,`notePages[].noWatermark` 指向它;GIF 跳过;与主图 SHA-256 相同时去重不重复落盘;`/oslarge/` 失效、404/403 或占位图时静默跳过,不拖垮主图也不记缺失黄点;对已缓存旧条目再次缓存/补全时复用有效主图并顺带补齐伴侣文件);③ 媒体库与信息流仅展示主图卡片不重复展示伴侣文件,删除/归档/导入合并/刷新完整同步伴侣文件;④ 看图层打开含无水印伴侣图的已缓存图片时默认显示原图,并在顶部悬浮栏提供「原图 / 无水印」一键切换胶囊 | 用户,2026-11-26(基于 ACT-023 与单帖对照实测拍板;[#103](https://github.com/chialecode/trace/issues/103)) | `settings.json`(v1)、`item.json`(v1)与 `library.db`(v2)均保持结构版本不变,新增字段向后兼容。正本:[需求 FR-WB-006](requirements.md#weibo-scope)、[数据与缓存 §2.1~2.3](design/data-and-cache.md#cache)、[微博协议 §4.4、§13.1](research/weibo.md#a-review-choices)、[界面规范 §3.5、§3.7](ui.md#viewer) |
+| DEC-079 | **历史缓存一键补全队列、全部缓存联动、纯 CDN 2~5 秒加速节奏与单条强制重新下载**:① **微博缓存标准版本与纯离线检测**:新增 `library.WeiboCacheStandardVersion = 3`(保持 `CurrentCacheStandardVersion = 2` 不变,避免触发哔哩哔哩门限 B 无谓的 PlayURL 重探);纯离线统计 `BackfillSummary`(0 网络请求)识别两类历史微博条目(排除 `archivedOf` 归档快照与纯 GIF):开启 `weiboRemoveWatermark` 且存在静态有效主图缺 `images/NN_nowm.*` 且 `cacheStandardVersion < 3` 的条目,以及正文仍含 DEC-073 前旧格式内联 `(URL)` 的条目;补全执行完毕后写入 `cacheStandardVersion = 3`(即使部分 `/oslarge/` 404 或同 SHA-256 去重跳过也不无限重复补全)。② **「全部缓存」自动联动**:手动与 7 天定期 `fullCache` 的 `inspectWeiboCachedPost` 顺带检出缺无水印伴侣图且远端可补的已缓存条目并直接复用列表数据排队补齐(0 额外 `statuses/show` 请求,保留有效主图仅补 `NN_nowm` 并记 v3),以及纯离线清洗等价正文中的旧格式内联 URL。③ **一键持久化历史补全队列与纯 CDN 加速节奏**:复用 `cache-queue.json`(保持 v3,新增可选 `omitempty` 字段,支持暂停/取消/重启续跑),按三级零浪费策略执行——(A) 纯离线旧格式链接升级(0 网络请求、0 延迟);(B) 已落盘 `pic_id`(`assetIds`/`notePages[].mediaId`)的条目走无 Cookie `sinaimg.cn/oslarge/` **纯 CDN 2~5 秒随机间隔加速节奏**(0 微博 API 请求、不占微博每小时 100 次 JSON API 额度、不触发 10~25 分钟长歇,不覆盖主图);(C) 缺少 `pic_id` 的历史条目优先按已订阅博主 UID 批量翻 `mymblog` 匹配并立刻转 2~5 秒 CDN 补齐,列表未覆盖项(转发/非订阅/可见范围外)再兜底逐条调 `statuses/show`,**站点 JSON API 全程严格遵守微博原间隔、100 次/小时额度与风控/限流退避**。入口位于「设置 › 存储」与「任务 › 缓存队列」。④ **单条安全补全与手动强制重新下载**:微博/X 详情主按钮「重新缓存」维持无损按新标准补全;四站点联网已缓存详情页(微博帖子/视频、X 帖子、抖音作品、B 站视频)的 `⋯` 菜单新增需二次确认的 **「强制重新下载」**(仅限显式手动触发,自动/队列绝不启用 `ForceOverwrite`),跳过本地媒体复用在 `.trace-stage-*` 从源站完整重拉,但**仍严格执行 `ErrRemoteDegradedRefused` 硬拦截保护**(源站 404/已删/占位图/试看/受限时中止并保留本机原文件),全部校验通过后经 `.trace-prev-*` 原子覆盖替换 | 用户,2026-11-26([#104](https://github.com/chialecode/trace/issues/104)) | `item.json`(v1)、`cache-queue.json`(v3)、`settings.json`(v1)与 `library.db`(v2)均保持结构版本不变,新增字段全为可选 `omitempty` 向后兼容。正本:[需求 FR-CACHE-003、FR-CACHE-010、FR-WB-006](requirements.md#cache-scope)、[数据与缓存 §1、§2.2、§2.10](design/data-and-cache.md#conflict-protection)、[订阅 §4](design/subscriptions.md#full-cache)、[界面规范 §3.4、§3.6、§3.7](ui.md#library) |
diff --git a/docs/design/data-and-cache.md b/docs/design/data-and-cache.md
index 979f738..1144047 100644
--- a/docs/design/data-and-cache.md
+++ b/docs/design/data-and-cache.md
@@ -24,7 +24,7 @@
- `subscriptions.json`(当前结构版本 5,见[下文版本 5 说明](#schema-v5)):订阅及其缓存能力标签(`tags`,与 `rules` 一一对应,[DEC-070](../decisions.md#dec-070))的正本([订阅 §1](subscriptions.md#model))。原子写;损坏时改名保留、提示一次、从空开始(订阅不能从别处重建,所以每次成功写入前把上一版保存为 `subscriptions.json.bak`,损坏时提示里给出“从上一版恢复”)。
- `updates.db`:检查更新的状态与更新记录([订阅 §2](subscriptions.md#update-check)),独立于 `library.db`。DEC-061 新增表 `account_works`(每个账号上次解析得到的作品总数与时间、上次“全部缓存”的时间,[订阅 §4](subscriptions.md#account-works)),启动时 `CREATE TABLE IF NOT EXISTS`,结构版本不变,旧版程序不读它。损坏时改名保留后重新开始,所有账号回到“未建立起点”,下次检查只建立起点,旧动态不会进入更新列表。旧首次检查快照的可逆标志与迁移边界以订阅设计为准。
- `ui-state.json`(当前结构版本 4,见[下文版本 4 说明](#schema-v4)):主页看过的最新一条(`anchor: {order: "newest", key, pubTs}`,作为没有 `homeSeen` 项的订阅在下次启动时的初始已读基准,DEC-040、DEC-053,第 4 节)、主页阅读位置 `homePositions`(可选,`{"all"|"bilibili"|"douyin"|"weibo"|"x": {key, pubTs, offsetPx}}`,每个站点筛选下主时间线可见区最上面那条与偏移;旧文件没有时照常读,DEC-053 ①)、主页侧栏订阅的已看最新时间戳 `homeSeen`(`{"sub:": }`;旧的 `mid:` 与作者键保留不删、不再写,Q-009、DEC-053 ②)、任务页里移除的“最近结束的录制” `dismissedLiveSessions`(可选,`{"<录像条目键>": "<移除时间 RFC3339>"}`,只用来隐藏列表行,8 天后规范化时删除,DEC-057 ①)、窗口/路由及播放偏好。旧文件中若 `anchor.order` 为 `"oldest"`,规范化时统一改为 `"newest"` 并保留 `key`、`pubTs`、`offsetPx`;媒体库固定按发布时间排序(DEC-049 ③),旧文件里若留有按缓存时间排序的偏好则静默忽略。`player` 保存 `volume`(0~1,0 为有效静音音量)、`muted`、`danmakuVisible`、`danmakuOpacity`、`danmakuArea`、`danmakuDensity`(`low`/`medium`/`high`/`unlimited`,默认 `medium`)、`subtitleLang`;旧文件缺少新字段时采用默认值。原子写,失败保留原文件与状态并在界面显示原因;读取和更新返回的状态不与已提交状态共享 `homeSeen`、`homePositions` 映射;`homePositions` 只保留五个筛选键(`all`/`bilibili`/`douyin`/`weibo`/`x`)、键或时间有效的项,偏移小于 0 时取 0;损坏时改名保留后恢复默认值。更新状态 `update`:`lastRunVersion`(上次运行的版本,用来在更新后第一次启动时说明一次)、`lastCheck`、已下载待重启的 `readyVersion` 与 `readyNotes`、为更新而退出的记录 `restart`(`reason`、`windowOpen`、`fromVersion`、`at`,下次启动读到后删除,[架构 §8](architecture.md#tray))。
-- `cache-queue.json`(当前结构版本 3,DEC-050 ①,FR-USER-004,见[下文版本 4 说明](#schema-v4)):保存“全部缓存”后台慢速缓存队列任务,使用独立文件与顶层结构版本 `version: 3`(由后端启动时的 `storage.GuardDataSchemas` 统一核对,遇到高于当前支持的未知版本时在打开任何数据库前返回 `NewerDataError` 拒绝覆盖;v2 → v3 迁移前留 `.premigrate-2` 备份并经 `WriteMigratedJSONAtomic` 原子落盘)。JSON 损坏时改名保留并从空队列恢复。每个任务只存公开调度元数据:任务 ID、站点(`bilibili` / `douyin` / `weibo` / `x`)、账号 ID(B 站 `mid`、抖音 `sec_uid`、微博 `uid` 或 X `rest_id`)、显示名称、本机头像键(如有)、列表类型(B 站 `dynamics` / `videos`,抖音 `works`,微博 `posts`,X `posts`)、可选的来源 `origin`(`full_cache` 表示由缓存规则的“全部缓存”开的,DEC-061 ①)、翻页游标(微博为 `:`,X 为时间线 `Bottom` 游标,拒绝 URL、查询串与敏感字段)与 `hasMore`、可选的完成说明 `completionNote`(如微博可见范围提示或 X“已到达 X 时间线可见上限”)、计数(已缓存、跳过)、最近缓存的若干条本机摘要(本机条目键 `key` 与标题,供任务页详情点击打开本机内容,封面按条目键从媒体库读)、状态(`queued`、`running`、`waiting`、`waiting_backoff`、`paused`、`completed`、`stopped`)、暂停或停止原因、下次计划执行时间与创建/更新时间戳。**字段边界(NFR-SEC-001~005)**:严禁保存任何 Cookie、签名 URL 或带查询串的地址;应用退出时停下并保存进度,启动后随机等 1~5 分钟继续。结束的任务(`completed`、`stopped`)可以逐个或一次全部从文件中移除(DEC-057 ①),未结束的要先取消;移除不删已缓存的条目。
+- `cache-queue.json`(当前结构版本 3,DEC-050 ①,FR-USER-004,[DEC-079](../decisions.md#dec-079),见[下文版本 4 说明](#schema-v4)):保存“全部缓存”后台慢速缓存队列与“历史缓存补全”队列任务,使用独立文件与顶层结构版本 `version: 3`(由后端启动时的 `storage.GuardDataSchemas` 统一核对,遇到高于当前支持的未知版本时在打开任何数据库前返回 `NewerDataError` 拒绝覆盖;v2 → v3 迁移前留 `.premigrate-2` 备份并经 `WriteMigratedJSONAtomic` 原子落盘)。JSON 损坏时改名保留并从空队列恢复。每个任务只存公开调度元数据:任务 ID、站点(`bilibili` / `douyin` / `weibo` / `x`)、账号 ID(B 站 `mid`、抖音 `sec_uid`、微博 `uid`、X `rest_id` 或补全队列 `all`)、显示名称、本机头像键(如有)、列表类型(B 站 `dynamics` / `videos`,抖音 `works`,微博 `posts` / `weibo_backfill`,X `posts`)、可选的队列类别 `kind`(`weibo_backfill` 等,`omitempty` 向后兼容)、补全进度可选字段(`backfillPhase`、`backfillTotal`、`backfillSubUids`、`backfillSubIndex`、`backfillSubCursor`,全 `omitempty` 严格脱敏)、可选的来源 `origin`(`full_cache` 表示由缓存规则的“全部缓存”开的,DEC-061 ①;`backfill` 表示历史缓存补全,DEC-079)、翻页游标(微博为 `:`,X 为时间线 `Bottom` 游标,拒绝 URL、查询串与敏感字段)与 `hasMore`、可选的完成说明 `completionNote`(如微博可见范围提示或 X“已到达 X 时间线可见上限”)、计数(已缓存、跳过)、最近缓存的若干条本机摘要(本机条目键 `key` 与标题,供任务页详情点击打开本机内容,封面按条目键从媒体库读)、状态(`queued`、`running`、`waiting`、`waiting_backoff`、`paused`、`completed`、`stopped`)、暂停或停止原因、下次计划执行时间与创建/更新时间戳。**字段边界(NFR-SEC-001~005)**:严禁保存任何 Cookie、签名 URL 或带查询串的地址;应用退出时停下并保存进度,启动后随机等 1~5 分钟继续。结束的任务(`completed`、`stopped`)可以逐个或一次全部从文件中移除(DEC-057 ①),未结束的要先取消;移除不删已缓存的条目。
- `update-history.json`(DEC-051 ①,FR-UPD-001~003):保存设置“更新”页的检查记录与版本更新记录,同样使用独立新文件与自带顶层结构版本 `version: 1`(**不改动现有 v2 数据文件结构**)。原子写(临时文件 + `fsync` + 改名,权限 `0600`);遇到高于当前程序支持的 `version > 1` 时拒绝启动且绝不覆盖;JSON 损坏时改名保留备份并从空记录重建,记入损坏恢复提示或日志。保存最近 20 次检查记录 `checks`(时间 RFC3339、触发方式 `auto` / `manual`、脱敏结果文字如“已是最新版本”“发现 x.y.z”“检查失败:<原因>”;仅正式版写入,开发版不联网检查)与最近 50 次更新记录 `updates`(时间 RFC3339、`fromVersion`、`toVersion`、方式:`auto_update`“自动更新” / `dev_install`“本机打包安装” / `manual_install`“手动安装”)。**隐私边界(NFR-SEC-001~003)**:只保存版本号、时间、方式与脱敏结果文字,严禁保存任何下载地址、URL、查询串或凭证,读写均做清洗校验。
- `cache-conflicts.json`([DEC-076](../decisions.md#dec-076) ④,FR-CACHE-010,NFR-DATA-005):保存全部缓存复查及下载层冲突绊线发现的 V1/V2 缓存内容冲突与已忽略版本指纹,使用独立新文件与顶层结构版本 `version: 1`(桌面端 `service.NewBackend` 将其加入 `allSchemas` 交给 `storage.GuardDataSchemas` 统一核对,遇到 `version > 1` 在打开数据库前返回 `NewerDataError` 拒绝启动且绝不覆盖,JSON 损坏时经 `BackupCorruptFile` 改名保留备份并从空账本恢复;`trace-server` 远程版不使用该文件)。通过 `storage.WriteJSONAtomic(..., 0600)` 原子落盘。包含两部分:① `conflicts[]`(按 `itemKey` 去重,保存待处理 `pending`、处理中 `resolving` 与上次失败 `failed` 的冲突项:`id`、`itemKey`、`site`、`kind`、`targetId`、`authorUid`、`authorName`、`title`、`detectedAt`、来源 `origin`、冲突原因类别 `reasonKind`——`part_changed` / `media_changed` / `text_edited` / `resource_mismatch`、两行脱敏摘要 `localSummary` 与 `remoteSummary`、远端结构 SHA-256 指纹 `remoteFingerprint`、可选 `via`、`state`、`lastError`);② `ignoredRevisions`(`itemKey -> {remoteFingerprint, ignoredAt}`:用户选择“保留本地”后记录当时远端指纹,后续 7 天定期 `fullCache` 扫到同一 `remoteFingerprint` 时静默跳过不重复提示,若源站再次修改产生新的 V3 指纹则重新登记冲突)。**隐私边界(NFR-SEC-001~005)**:入盘前全字段强制脱敏清洗,**严禁保存任何 `http://`/`https://` URL、CDN 主机名、查询串(`?`、`&`、`=`)、Cookie 或令牌**。
@@ -140,7 +140,7 @@ X(DEC-066)的作者目录用稳定的纯数字 `rest_id`(不随 `@handle`
可选的 `cachedBy`(DEC-062)记缓存这一条的安装:`node`(`<数据目录>/node.json` 里随机生成的节点 ID)与 `name`;旧条目没有这个字段时照常读取,结构版本不变。导入与合并时保留本地的 `cachedBy`。导出、上传到网盘的副本去掉 `itemDir`、`itemKey`、`rawId`、`totalBytes`,导入后由 `SaveItem` 按内容重新算出([远程 §6.1](remote.md#export-format))。
-为支持全部缓存更新复查与 V1/V2 冲突保护([DEC-076](../decisions.md#dec-076),`item.json` 保持 `version: 1` 不升结构版本,旧清单照常读取),清单向后兼容地支持以下可选字段:`cacheStandardVersion`(`int`,当前 `CurrentCacheStandardVersion = 2`,记录缓存或复查通过时的完整性与规格标准基线,`0` 表示旧版清单)、`recheckedAt`(RFC3339 时间戳,上次全部缓存深度复查时间)、`editTs` 与 `editCount`(源站脱敏编辑时间戳与编辑次数)、`assetIds`(`[]string`,按顺序记录经 `SanitizeMediaToken` 清洗的平台媒体标识,严禁含 URL、查询串、路径分隔符或凭证)、`archivedOf`(当本条目为“保留两版”生成的独立旧版归档快照时,记录原正本规范条目键 `::`,经 `ValidateCanonicalItemKey` 校验且禁止自指),以及 `douyinVideo.mediaId` 与 `notePages[].mediaId`(单视频或混排图文页的脱敏媒体标识,用于同源升级判定与混合编辑本地文件复用)。`SanitizeItemMetadata`、`MergeItemMetadata` 与导出 `PortableManifest` 统一清洗并保留这些字段。
+为支持全部缓存更新复查与 V1/V2 冲突保护([DEC-076](../decisions.md#dec-076)、[DEC-079](../decisions.md#dec-079),`item.json` 保持 `version: 1` 不升结构版本,旧清单照常读取),清单向后兼容地支持以下可选字段:`cacheStandardVersion`(`int`,通用基线 `CurrentCacheStandardVersion = 2` 保持不变以免影响哔哩哔哩门限 B;微博双份无水印伴侣图与规范链接基线 `WeiboCacheStandardVersion = 3`,记录缓存、复查或历史补全评估通过时的完整性标准基线,`0` 表示旧版清单;微博条目完成无水印补全评估后写入 `3`,即便部分图 `/oslarge/` 404 或与主图同 SHA-256 跳过也不再重复补全)、`recheckedAt`(RFC3339 时间戳,上次全部缓存深度复查时间)、`editTs` 与 `editCount`(源站脱敏编辑时间戳与编辑次数)、`assetIds`(`[]string`,按顺序记录经 `SanitizeMediaToken` 清洗的平台媒体标识,严禁含 URL、查询串、路径分隔符或凭证)、`archivedOf`(当本条目为“保留两版”生成的独立旧版归档快照时,记录原正本规范条目键 `::`,经 `ValidateCanonicalItemKey` 校验且禁止自指),以及 `douyinVideo.mediaId` 与 `notePages[].mediaId`(单视频或混排图文页的脱敏媒体标识,用于同源升级判定、微博纯 CDN 无水印补齐与混合编辑本地文件复用)。`SanitizeItemMetadata`、`MergeItemMetadata` 与导出 `PortableManifest` 统一清洗并保留这些字段。
抖音条目的作者另记 `site`、`uid`(`sec_uid`)与抖音号;视频作品记实际与可选的档位(分辨率、编码、帧率、码率、档位名);图文记配乐(标题、作者、时长、文件)。微博条目的作者记 `site: "weibo"` 与数字 `uid`,视频微博及混排视频记实际与可选档位;媒体库筛选“视频”除 `kind = video` 外也匹配 `media[role='video']`(排除 `gif: true`)与 `notePages[kind='video']`(排除 `gif: true`),使 `weibo:dynamic:` 与 `x:dynamic:` 的视频与混排条目在“视频”下可见。X 条目的作者记 `site: "x"`、数字 `rest_id` 与 `@handle`,另向后兼容地支持可选字段 `thread`(`[]ItemThreadPart{id, pubTs, text, mediaIndexes}`,缓存当刻一并保存的作者自回复线程)与 `notePages[].gif` / `media[].gif`(`gif: true`,标记 X 的 MP4 动图,在看图层与播放层静音循环播放,并在媒体库中归类到“图片”而非“视频”);仅提供 HLS 分段流的视频记入 `missing`(原因“这条视频只有分段流,暂不支持缓存”)。直播录像条目([直播 §4](live.md#recording-item))的 `live` 对象另含可选字段 `live.incidents`(录制异常事件列表:`reconnect`、`lost_segments`、`slow`、`disk`、`convert_failed`,每场最多 200 条,DEC-051 ③)与 `live.lastSequenceAt`(RFC3339Nano,记录上次写入的 HLS 分片时间,供同场重启或续录时防误判跳号;均不改清单结构版本,旧清单照常读取)。
@@ -284,6 +284,7 @@ X 内容(FR-X-005、FR-X-006,[X 协议 §5~§6、§15.1](../research/x.md#
4. **混合编辑复用本地已校验附件**:执行 `keep_both` 或 `use_remote` 组装 V2 时,若 V2 保留了未改动的分 P 或图片/视频页(`cid` 或 `mediaId` 与本地 V1 一致,且本地正式文件存在并与 `item.json` 登记的 SHA-256 吻合),当该未改动附件在远端 CDN 已过期失败时,直接把本地已校验 V1 文件复用到 `.trace-stage-/` 中,避免丢失未改动附件。
5. **归档优先(`keep_both`)**:任务页批量默认选项为无损的 **保留两版(推荐)**。全部 V2 文件在 `/.trace-stage-/` 完整下载并通过容器、时长与 SHA-256 校验后,先调用 `ArchiveItemSnapshot` 将本地 V1 完整归档到独立目录 `__v1-/`(标 `archivedOf`);归档失败则立即中止并保留原 V1 不动。
6. **`.trace-stage-*` / `.trace-prev-*` 原子交换、文件锁回滚与启动自愈**:条目目录内的新版暂存目录 `.trace-stage-/` 与旧版备份目录 `.trace-prev-/` 均以 `.trace-` 开头(满足 `storage.IsTempName`,远程与网盘同步过滤规则 `*.part`、`.trace-*` 自动忽略,[远程 §6.1](remote.md#export-format))。正式切换时先将将被替换的 V1 正式文件移入 `.trace-prev-/`,再把 `.trace-stage-/` 中的 V2 文件移入 `itemDir`、调用 `SaveItem` 原子写回 `item.json` 与索引,全部成功后才清理 `.trace-prev-/` 及 V2 不再引用的多余登记旧文件(`RegisteredFiles(v1) - RegisteredFiles(v2)`)与空子目录;若任一改名(如内置播放器正在播放触发 Windows 共享锁)或 `SaveItem` 失败,立即将 `.trace-prev-/` 中的全部原文件移回原位并清理 `.trace-stage-/`,冲突项标为 `failed` 并附“(本地原文件未改动)”。若进程在切换瞬间崩溃,下次启动或读取条目时发现 `.trace-prev-*` 内文件匹配当前 `item.json` 登记的 SHA-256 而正式路径缺失,先自动恢复正式文件,再清理残留 `.trace-stage-*`。
+7. **显式手动「强制重新下载」(`ForceOverwrite`,[DEC-079](../decisions.md#dec-079))**:仅允许用户从已缓存详情页 `⋯ → 强制重新下载` 经二次确认弹窗手动触发(`download.WithForceOverwrite(ctx)` / `ForceRecacheItem`),`source="auto"`、`source="queue"` 与 `site.WithAutomaticRequests` 路径严禁开启。执行时跳过本地既有图片/视频/音频/伴侣文件复用,全部媒体在 `.trace-stage-/` 中重新从源站下载并校验(拒绝半残覆盖),但**仍严格执行第 2 条 `ErrRemoteDegradedRefused` 硬拦截**:源站已删除、404/410、占位图、试看、受限或降级时立即报错并清理暂存目录,**绝不覆盖或破坏本机原文件**;全部校验通过后再经第 6 条 `.trace-prev-*` 原子替换本地文件并在文件锁失败时回滚。微博与 X 详情页已缓存时的主按钮「重新缓存」则保持非破坏性按新标准补全(复用有效主图、补齐缺失的 `NN_nowm` 伴侣图与规范链接)。
## 3. 本机媒体路径白名单(`Library.MediaPath`)
diff --git a/docs/design/subscriptions.md b/docs/design/subscriptions.md
index 8750bc7..1f98780 100644
--- a/docs/design/subscriptions.md
+++ b/docs/design/subscriptions.md
@@ -108,10 +108,11 @@ TRACE 以订阅为逻辑入口(DEC-026):一个订阅代表一个被追踪
- **全部缓存与已缓存更新复查(DEC-061 ①、DEC-063 ③、DEC-065、DEC-066、[DEC-076](../decisions.md#dec-076))**:规则的 `fullCache` 打开时,桌面端后台每 10 分钟看一次哪些账号到期(`updates.db` 的 `account_works.full_cache_at` 为空或早于 7 天前,`FullCacheInterval`;远程版 `ProfileRemote` / `trace-server` 不运行缓存队列与冲突检查,所有 `ConflictService` 接口受 `requireDesktop()` 保护,[远程 §4](remote.md#sync)),按上次全部缓存时间从早到晚,为它建一个 DEC-050 ① 的缓存队列(哔哩哔哩列表 `videos`,抖音 `works`,微博 `posts`,X `posts`,`origin = "full_cache"`,持久化至 `cache-queue.json` v3),并把 `full_cache_at` 记为现在。队列自己从新到旧翻完整个列表:没缓存的、失败的和不完整的(`library.NeedsCompletion`)按慢速、不规律的节奏(40~150 秒随机间隔,每 15~25 条长歇 10~25 分钟)一条一条排入下载队列(标记 `source = "queue"`,内部 API 统一纳入 `site.WithAutomaticRequests` 额度记账);正在缓存与已暂停的直接跳过;由“保留两版”生成的独立归档快照(`meta.IsArchivedSnapshot()`,即 `archivedOf` 非空)直接跳过;其余**已缓存条目**按四站点额度安全策略顺带复查更新与冲突:
- - **抖音 `works`、微博 `posts`、X `posts` 与哔哩哔哩 `dynamics`(零额外请求列表级比对)**:直接复用翻页已拉取的列表条目在内存中与本机 `item.json` 对比,不额外请求单条详情。其中抖音 `ListUserPosts` 同步填充无水印候选 `OriginalURLs` 与脱敏媒体标识,并写入进程内短期计划缓存 `douyinWorkPlanCache`(与 `weiboPostPlanCache`、`xPostPlanCache` 一致:5 分钟 TTL、上限 128 条、退出登录即清),队列为抖音未缓存或可升级作品建任务时直接命中内存计划、零额外作品详情请求。
+ - **抖音 `works`、微博 `posts`、X `posts` 与哔哩哔哩 `dynamics`(零额外请求列表级比对)**:直接复用翻页已拉取的列表条目在内存中与本机 `item.json` 对比,不额外请求单条详情。其中微博已缓存条目在开启 `weiboRemoveWatermark` 且存在缺无水印伴侣图的静态有效主图(`library.WeiboNeedsNoWMBackfill`)且远端 `post` 含可补伴侣图时直接排入补全(0 额外 `statuses/show` 请求,保留有效主图仅补 `NN_nowm` 并写入 `WeiboCacheStandardVersion = 3`);仅含 DEC-073 前旧格式内联 URL 且等价正文未变时纯离线清洗补写 `text`/`links`(不动媒体文件,[DEC-079](../decisions.md#dec-079))。抖音 `ListUserPosts` 同步填充无水印候选 `OriginalURLs` 与脱敏媒体标识,并写入进程内短期计划缓存 `douyinWorkPlanCache`(与 `weiboPostPlanCache`、`xPostPlanCache` 一致:5 分钟 TTL、上限 128 条、退出登录即清),队列为抖音未缓存或可升级作品建任务时直接命中内存计划、零额外作品详情请求。
- **哔哩哔哩 `videos`(三道门限 + 7 天冷却 + 队列节奏)**:投稿列表不含分 P `cid` 与 DASH 流档位,采用三道门限将自动请求压在每小时 200 次额度内:① **门限 A(零请求列表快筛)**:对比列表返回的标题、简介或时长(`|DurationSec - meta.Duration| > 2`);若有变化,按 `cache-queue` 的 40~150 秒节奏并经 `site.WithAutomaticRequests` 请求 `VideoDetail` 进一步判定;② **门限 B(缓存标准版本与规格上限跳过)**:门限 A 无变化,且本地条目 `status == "complete"`、`!library.NeedsCompletion(meta)`、`!meta.UpgradeAvailable`、`meta.CacheStandardVersion >= library.CurrentCacheStandardVersion`(当前为 `2`)且已达当前清晰度/音质上限(未降级、非最近 14 天内新投稿)时,0 延迟、0 请求跳过;③ **门限 C(7 天 `recheckedAt` 冷却)**:定期 `fullCache` 中若 `meta.RecheckedAt`(或 `UpgradeCheckedAt`)在 7 天以内直接跳过;到期后才按 `cache-queue` 40~150 秒节奏探测 `VideoDetail` / `PlayURL`。
- **四路分类处理**:(a) **无变化**:零操作跳过(B 站到期探测无变化时写回 `recheckedAt` 与 `cacheStandardVersion`);(b) **同源安全升级或补齐**:同一媒体标识(相同 `cid`、`mediaId`、`assetIds`)下有更高流规格(如抖音原非 `original` 现可取原画、微博更高短边档、X 更高码率/分辨率 MP4、B 站更高清晰度或高音质)、新支持附件(实况片段、配乐、完整长文、作者线程续帖)或缺失项时,排入 `source = "queue"` 任务无损升级补齐,单调保留已有弹幕、字幕、独立音轨、有效转发 `Origin` 与完整长文([数据与缓存 §2.10](data-and-cache.md#conflict-protection));(c) **远端失效、受限或降级**(已删除/不可见、试看/付费未购/加密、地域受限、微博失效灰图占位 GIF、仅剩 HLS 分段流或清晰度低于本地):严禁触碰本地 V1,直接跳过;(d) **V1/V2 资源不一致**(换源改 `cid`、删减重排分 P、作品类型翻转、媒体标识/页数/页类型改变,或编辑计数/时间戳推进且正文实质改写):不覆盖本地文件,写入 `/cache-conflicts.json`(命中 `ignoredRevisions` 同指纹则静默跳过,后续若有新版本 V3 指纹仍重新提醒)并发出 `conflicts:changed` 事件([数据与缓存 §1](data-and-cache.md#cache-conflicts))。
- 遇到风控、限流或额度用完照常进入 `waiting_backoff` 等待。每个站点同时只有一个没结束的缓存队列时才开新的,所以全部缓存的账号一个接一个做,也不和用户自己点的“全部缓存”同时跑。取消的队列不会马上重开,等下一个 7 天。抖音、微博与 X 开始前读一次账号资料(自动请求,退避或额度用完时跳过)记下作品总数。**微博全部缓存范围**:只补博主的原创微博(跳过转发与快转,默认 `feature=0` 在本机过滤,支持经 `FullCacheUseFeatureOriginal` 切换);优先复用内存里的列表计划(`cache-queue.json` 只存 `mid` 与游标,不存签名地址);到达博主可见范围边界(`BottomTipsVisible`)时正常结束,并把站点的 `BottomTipsText` 写进队列摘要(`Note`/`StatusText`)。**X 全部缓存范围**:沿 `UserTweets` 只补用户的原创帖子(跳过转帖、引用帖与回复他人),优先复用内存计划(`cache-queue.json` 只存 `status_id` 与游标,不存签名地址);到达 X 时间线可见上限时正常结束并写明“已到达 X 时间线可见上限”,不调用 `SearchTimeline`。
+- **历史缓存一键补全队列([DEC-079](../decisions.md#dec-079))**:通过 `BackfillSummary()`(0 网络请求,经 `ListItemsMetaOnlyBySite` 离线扫描)统计待补全历史微博条目,并经 `StartWeiboBackfill` 在 `cache-queue.json`(v3)内建立持久化补全队列(`kind = "weibo_backfill"`,`origin = "backfill"`,重启自动续跑),按三级零浪费策略执行:① **A 级(纯离线旧格式链接升级)**:仅需清洗 DEC-073 前内联 URL 的条目零延迟、零网络请求调用 `SaveItemMetadataOnly` 写回规范 `text`/`links` 与 `WeiboCacheStandardVersion = 3`;② **B 级(纯 CDN 2~5 秒快速补齐)**:已落盘 `pic_id`(`assetIds` / `notePages[].mediaId`)的微博图片条目直接走无 Cookie `sinaimg.cn/oslarge/.` 媒体通道补齐缺失的 `images/NN_nowm.`(不覆盖主图、与主图同 SHA-256 去重、跳过占位图与 404,评估完即标 `WeiboCacheStandardVersion = 3`),队列项间隔 **2~5 秒随机延迟**,**0 微博 JSON API 请求、不占微博每小时 100 次额度、不触发 10~25 分钟长歇**(仅在站点处于风控/限流退避期暂停);③ **C 级(缺 `pic_id` 的历史条目,严格遵守微博原 API 节奏与 100 次/小时额度)**:先按已订阅微博博主 UID 分组逐页拉取 `mymblog` 批量匹配(命中条目的 `pic_infos` 立刻转 2~5 秒纯 CDN 补齐,遇可见范围限制或翻到底则剩余未匹配项转兜底),对转发(`forwards/`)、收藏与非订阅等未覆盖条目再逐条调 `GetPost`(`statuses/show`)按 40~150 秒节奏与 100 次/小时额度补齐。
- **作品总数与已缓存数(DEC-061 ②、[DEC-076](../decisions.md#dec-076) ⑤)**:`account_works(site, uid, works_total, works_at, full_cache_at)` 记每个账号上次解析时站点给的作品总数(`-1` 表示还不知道):打开哔哩哔哩用户页(`card` 的 `archive_count`)、读投稿列表第一页(`arc/search` 的总数,包括全部缓存翻的第一页)、打开抖音用户页或全部缓存开始时(资料的 `aweme_count`)、打开微博用户页或全部缓存开始时(`profile/info` 的 `statuses_count`,含转发)、打开 X 用户页或全部缓存开始时(资料的 `statuses_count`)。`SubscriptionAccountWorks()` 只读本机:总数来自这张表,已缓存数由单条 `GROUP BY` 查询的 `library.CountCachedWorks` 从 `library_items` 数(哔哩哔哩 `kind = video` 且投稿人是他或 `via` 是为他缓存的合作视频;抖音 `kind` 为 `video` 或 `dynamic` 且作者或 `via` 是他;微博与 X 统计该作者的非转发条目及 `via.uid` 指向他的全部条目;所有站点均排除 `archivedOf` 非空的独立旧版归档快照,保留两版不会重复计入已缓存作品数)。
diff --git a/docs/requirements.md b/docs/requirements.md
index 4d9aca9..08c67f0 100644
--- a/docs/requirements.md
+++ b/docs/requirements.md
@@ -52,14 +52,14 @@ TRACE 是 Windows 桌面应用,以“订阅”(被追踪的人)为入口
| --- | --- | --- |
| FR-CACHE-001 | 手动缓存:动态条目和投稿条目的“⋯”菜单里有“缓存”,视频详情页有“缓存视频”按钮(DEC-038)。缓存一条动态保存它的正文、发布信息、全部原图,以及其中的视频;转发同时保存原动态。视频按 `bvid` 只存一份,动态和投稿共用。转发的动态和它带的图片、视频存在转发者的文件夹里、与他自己的投稿分开;哔哩哔哩合作视频为某位成员缓存时存在这位成员的文件夹里(DEC-056) | 已实现 |
| FR-CACHE-002 | 最高画质与音质(DEC-024):视频默认缓存这次能拿到的最高清晰度(同档内按编码偏好),音频默认缓存能拿到的最高音质(Hi-Res 无损 > 杜比全景声 > 192K > 132K > 64K);多 P 默认缓存全部分 P。清单记录每个分 P 实际缓存的清晰度、编码、分辨率、帧率和音质,以及缓存时站点列出的全部档位。设置页可以改成设定上限(以后需要时) | 已实现 |
-| FR-CACHE-003 | 缓存任务(DEC-022、DEC-049 ①、DEC-050 ②、DEC-051 ③、DEC-057 ①②、[DEC-076](decisions.md#dec-076) ⑤):图标栏“任务”入口(角标只数排队和进行中的下载任务,不数直播录制、缓存队列等待项与内容冲突)通过上下文侧栏切换“下载任务”“缓存队列”“内容冲突”“直播录制”“录制异常”“检查计划”和“导入导出”;“下载任务”列出每个下载任务的对象、进度、速度和状态,可以暂停、继续、取消、重试、移除,应用重启后未完成的下载任务恢复为“已暂停”、用户点继续后从断点续传;每个任务有“详情”,列出出错的分段、节点域名、错误类别与时间(不含签名地址);“缓存队列”按卡片列出全部队列,点开看进度与最近缓存的内容(带封面),结束的队列可以移除;“内容冲突”列出待处理的 V1/V2 缓存冲突供批量或逐条处理(FR-CACHE-010);最近结束的录制可以从列表移除,结束场次的录制异常记录可以删除;这些删除都不删已缓存的文件 | 已实现 |
+| FR-CACHE-003 | 缓存任务(DEC-022、DEC-049 ①、DEC-050 ②、DEC-051 ③、DEC-057 ①②、[DEC-076](decisions.md#dec-076) ⑤、[DEC-079](decisions.md#dec-079)):图标栏“任务”入口(角标只数排队和进行中的下载任务,不数直播录制、缓存队列等待项与内容冲突)通过上下文侧栏切换“下载任务”“缓存队列”“内容冲突”“直播录制”“录制异常”“检查计划”和“导入导出”;“下载任务”列出每个下载任务的对象、进度、速度和状态,可以暂停、继续、取消、重试、移除,应用重启后未完成的下载任务恢复为“已暂停”、用户点继续后从断点续传;每个任务有“详情”,列出出错的分段、节点域名、错误类别与时间(不含签名地址);“缓存队列”按卡片列出全部队列(含“历史缓存补全 · 微博”队列,顶部在有待补全历史微博且未运行时提供紧凑“发现 N 条历史微博可补全”+“一键补全”操作条),点开看进度与最近缓存的内容(带封面),结束的队列可以移除;“内容冲突”列出待处理的 V1/V2 缓存冲突供批量或逐条处理(FR-CACHE-010);最近结束的录制可以从列表移除,结束场次的录制异常记录可以删除;这些删除都不删已缓存的文件 | 已实现 |
| FR-CACHE-004 | 状态圆点(DEC-024):动态、投稿、视频详情、主页信息流和媒体库条目上用小圆点表示缓存状态(DEC-039 起媒体库、DEC-046 ⑦ 起主页不显示;主页只列已缓存的内容):绿 = 已完整缓存且是能拿到的最高档;黄 = 部分缓存、已暂停或有更高档可升级;红 = 失败、文件缺失或清单损坏;缓存中显示进度圆环;未缓存不显示。圆点带图形符号、悬停说明和无障碍名称,不只靠颜色。重启后保持,删除后同步消失 | 已实现 |
| FR-CACHE-005 | 下载稳定性:媒体文件分段下载;某段提前断开、超时、连接重置或服务器 5xx 时,在任务内自动重试并从断点续传,在主地址和备用地址之间轮换;地址过期时每个分 P 最多重新取一次播放地址;重试用完后任务“已暂停(网络)”并写明原因。遇到风控立即暂停,不重试([媒体与存储选型 §5](research/2026-11-05-media.md#download)) | 已实现 |
| FR-CACHE-006 | 画质升级提醒(DEC-024):打开已缓存视频的详情页时(同一视频 24 小时内最多一次),以及在任务页手动“检查画质更新”时,探测当前能拿到的最高档;比已缓存的高时,圆点变黄并提示“可升级到 4K”等,点“升级缓存”只重新下载档位较低的分 P,新文件校验通过后才替换旧文件 | 已实现 |
| FR-CACHE-007 | 自动缓存(DEC-027、DEC-070):自动缓存按类型拆为订阅的能力标签(`自动缓存视频`、`自动缓存图文`、`自动缓存文字`、`自动缓存转发`,FR-SUBS-004);检查更新(手动或定时,FR-SUB-001/002)发现的、在该订阅首次开启自动缓存标签之后发布且类型匹配的新动态,自动建立普通缓存任务(任务标“自动”,用当前画质与音质设置)。一轮检查最多自动建立 20 个任务,多出的留到下一轮并在订阅里写明;风控、限流、未登录时不建任务。移除自动缓存标签不影响已建立的任务 | 已实现 |
| FR-CACHE-008 | 弹幕、字幕与视频章节(DEC-027):缓存视频时,每个分 P 同时保存弹幕(缓存那一刻站点给出的全部弹幕,存成通用的 XML 弹幕格式)和全部 CC 字幕(每种语言一份 WebVTT 与 SRT,AI 生成的字幕标明“AI”),并复用同一次 `player/wbi/v2` 请求零额外网络开销顺手解析 `view_points` 章节看点写入 `item.json` 可选字段 `parts[].chapters`(不升结构版本、完全向后兼容)。设置可以分别关闭弹幕与字幕;没有字幕或章节不算缺失;弹幕或字幕取不到时记为缺失项(黄点,可“补全”)。在本功能之前缓存的视频保持原圆点,详情页提供“补存弹幕和字幕” | 已实现 |
| FR-CACHE-009 | 任务详情逐文件进度:任务“详情”列出每个文件(每张图片、每个分 P 的视频流与音频流、弹幕、字幕、合并后的文件)的状态、已下载 / 总大小与速度 | 已实现 |
-| FR-CACHE-010 | 全部缓存更新检查与内容冲突保护([DEC-076](decisions.md#dec-076)):① **四站点额度安全复查**:手动与 7 天定期 `fullCache` 缓存队列遍历已缓存条目(跳过 `archivedOf` 归档快照)时,抖音、微博、X 与哔哩哔哩动态直接复用已拉取的列表页数据做零额外请求比对,哔哩哔哩投稿按三道门限(列表级标题/简介/时长比对、`cacheStandardVersion` 与画质上限跳过、7 天 `recheckedAt` 冷却 + `cache-queue` 40~150 秒节奏)复查且 `source="queue"` 计入站点每小时自动请求额度,远程程序 `trace-server` 不执行全部缓存与冲突检查;② **四分类、防失效覆盖与单调保护**:(a) 无变化且达当前缓存标准上限的零延迟跳过;(b) 同一媒体标识(相同 `cid` / `mediaId` / `assetIds`)有更高画质音质、新支持实况/配乐/完整长文/线程续帖或缺失项时排队无损升级补齐,单调保留本地已校验弹幕快照(`Pxx.danmaku.xml`)、字幕、Hi-Res/杜比独立音轨、有效转发原帖 `Origin`(含原帖媒体)与完整长文;(c) 远端已删除、不可用、试看/付费未购/加密、地域受限、微博失效灰图占位 GIF、仅剩分段流或画质降级时,严禁覆盖本地有效缓存(即便选择“用新版替换”,执行期遇到远端失效降级也硬拦截 `ErrRemoteDegradedRefused` 并保持 V1 原封不动);(d) 源站换源改 `cid`、删减重排分 P、替换增删媒体或实质编辑正文(含手动重缓存、补全、升级、重试全入口下载层冲突绊线)一律不静默覆盖,记入 `/cache-conflicts.json`(v1,不含 URL、查询串或凭证,带 `ignoredRevisions` 避免选“保留本地”后每 7 天重复提示、后续出现新版本 V3 仍再次提醒);③ **任务页“内容冲突”归档优先处理**:任务页显示“内容冲突(N)”,批量默认选中无损的 **保留两版(推荐)**(`keep_both`:先在 `.trace-stage-*` 完整下载校验 V2,未改动附件若远端过期则复用本地已校验文件,通过后将本地 V1 归档为独立条目 `__v1-` 标 `archivedOf`——独立删除且不重复计入作品数),另提供 **保留本地**(`keep_local`,零请求记忽略指纹)、行内确认的 **用新版替换**(`use_remote`,先移入 `.trace-prev-*` 原子替换,失败回滚并注明“(本地原文件未改动)”)与纯离线 **查看本地**(打开 `/library/item`) | 已实现 |
+| FR-CACHE-010 | 全部缓存更新检查与内容冲突保护([DEC-076](decisions.md#dec-076)、[DEC-079](decisions.md#dec-079)):① **四站点额度安全复查**:手动与 7 天定期 `fullCache` 缓存队列遍历已缓存条目(跳过 `archivedOf` 归档快照)时,抖音、微博、X 与哔哩哔哩动态直接复用已拉取的列表页数据做零额外请求比对(其中微博顺带检出开启无水印时缺失 `images/NN_nowm.*` 伴侣图且 `cacheStandardVersion < 3` 的静态图条目排队补齐,以及纯离线清洗等价正文里的 DEC-073 前旧格式内联 URL),哔哩哔哩投稿按三道门限(列表级标题/简介/时长比对、`cacheStandardVersion` 与画质上限跳过、7 天 `recheckedAt` 冷却 + `cache-queue` 40~150 秒节奏)复查且 `source="queue"` 计入站点每小时自动请求额度,远程程序 `trace-server` 不执行全部缓存与冲突检查;② **四分类、防失效覆盖与单调保护**:(a) 无变化且达当前缓存标准上限的零延迟跳过;(b) 同一媒体标识(相同 `cid` / `mediaId` / `assetIds`)有更高画质音质、新支持实况/配乐/完整长文/线程续帖、微博无水印伴侣图或缺失项时排队无损升级补齐,单调保留本地已校验弹幕快照(`Pxx.danmaku.xml`)、字幕、Hi-Res/杜比独立音轨、有效转发原帖 `Origin`(含原帖媒体)与完整长文;(c) 远端已删除、不可用、试看/付费未购/加密、地域受限、微博失效灰图占位 GIF、仅剩分段流或画质降级时,严禁覆盖本地有效缓存(即便选择“用新版替换”或手动“强制重新下载”,执行期遇到远端失效降级也硬拦截 `ErrRemoteDegradedRefused` 并保持 V1 原封不动);(d) 源站换源改 `cid`、删减重排分 P、替换增删媒体或实质编辑正文(含手动重缓存、补全、升级、重试全入口下载层冲突绊线)一律不静默覆盖,记入 `/cache-conflicts.json`(v1,不含 URL、查询串或凭证,带 `ignoredRevisions` 避免选“保留本地”后每 7 天重复提示、后续出现新版本 V3 仍再次提醒);③ **任务页“内容冲突”归档优先处理**:任务页显示“内容冲突(N)”,批量默认选中无损的 **保留两版(推荐)**(`keep_both`:先在 `.trace-stage-*` 完整下载校验 V2,未改动附件若远端过期则复用本地已校验文件,通过后将本地 V1 归档为独立条目 `__v1-` 标 `archivedOf`——独立删除且不重复计入作品数),另提供 **保留本地**(`keep_local`,零请求记忽略指纹)、行内确认的 **用新版替换**(`use_remote`,先移入 `.trace-prev-*` 原子替换,失败回滚并注明“(本地原文件未改动)”)与纯离线 **查看本地**(打开 `/library/item`);④ **历史缓存一键补全与手动强制重新下载([DEC-079](decisions.md#dec-079))**:“设置 › 存储”与“任务 › 缓存队列”展示离线待补全统计(0 网络请求)并提供一键持久化历史微博补全队列(A 级离线链接升级 0 延迟 → B 级已落盘 `pic_id` 纯 CDN 2~5 秒快速补齐且 0 API 消耗 → C 级订阅 `mymblog` 批量匹配与兜底 `statuses/show`,严格守微博 100 次/小时 API 额度与风控退避);四站点联网已缓存详情页 `⋯` 菜单另提供需二次确认的“强制重新下载”,跳过本地媒体复用在 `.trace-stage-*` 完整重拉并通过 `ErrRemoteDegradedRefused` 保护与 `.trace-prev-*` 原子替换覆盖本地 | 已实现 |
### 2.3 主页、媒体库与设置
@@ -166,7 +166,7 @@ TRACE 是 Windows 桌面应用,以“订阅”(被追踪的人)为入口
| FR-WB-003 | 单条微博详情:作者(头像、昵称,点击进入用户页)、发布时间、正文(长微博自动取全文,正文里的短链按站点给出的标题显示)、转发(显示原微博;原微博已删除或看不到时保留转发正文,原微博处说明原因)、图片(超过 9 张也完整显示,GIF 动图,实况照片标“实况”可播放片段)、图片与视频混排(按原顺序)、视频(封面、时长、清晰度)与可见范围提示(如“仅粉丝可见”);头条文章、投票、音乐、外链与直播卡片显示摘要与“在浏览器中打开”,不当成视频下载;转发、评论、点赞数只在线显示、不缓存。“⋯”里有缓存、复制链接、在浏览器中打开 | 已实现(只经合成样本验证;真实站点待 ACT-023) |
| FR-WB-004 | 微博用户页:头像、昵称、简介、认证说明、关注、粉丝与微博数;一个“微博”列表按发布时间倒序(样式同哔哩哔哩动态),置顶的标“置顶”,滚到底取下一页、两页之间不重复,支持“全部 / 未缓存”筛选;博主设了“只展示最近半年”等可见范围时,列表底部如实显示站点的提示;未登录或失效、风控空壳、真的没有微博与正常到底分别说明,失败停在原处可重试。显示所属订阅或“加入订阅”(FR-USER-003),“⋯”有“全部缓存”(FR-USER-004) | 已实现(只经合成样本验证;真实站点待 ACT-023) |
| FR-WB-005 | 缓存微博视频:按微博 `mid` 只存一份(没有所属微博的视频页按视频对象 ID);去掉进度条预览图和隐藏档后,取当前登录账号能拿到的最高分辨率单文件 MP4(同档按编码偏好,再按帧率与码率),`moov` 在前、应用内与系统播放器都能播放,连同封面与清单保存;清单记录实际与可选的档位、编码、分辨率、帧率;任务、进度、续传、暂停、重试、圆点与删除同另外两个站点。会员专享或加密的档位不绕过;不做画质升级提醒 | 已实现(只经合成样本验证;真实站点待 ACT-023) |
-| FR-WB-006 | 缓存微博正文、图片、实况与混排([DEC-078](decisions.md#dec-078)):保存全文(长微博的全文)、发布信息、按原顺序的全部官方原图(超过 9 张、GIF 保存原动图,扩展名按实际格式;主图恒定保存官方最高清原图 `largest`/`original`,默认开启“微博同时保存无水印版”开关,开启时对静态图与实况静帧额外保存无水印最大版 `/oslarge/` 伴侣文件 `images/NN_nowm.`,GIF 跳过、SHA-256 相同自动去重、`/oslarge/` 失效静默跳过不拖垮主图,看图层支持「原图 / 无水印」一键切换,可在“设置 › 缓存与下载”随时开关并立即生效)、实况照片的静帧与片段(QuickTime `.mov` 经 `mp4ff` 无损改封装为 `.mp4`)、混排里的视频与封面;单个主媒体缺失记黄点、不让整条失败。转发的微博连同其中的图片与视频存到转发者的 `forwards/`,清单记 `via`(DEC-056),原微博看不到时完整保存转发正文。媒体地址带签名的一律不落盘 | 已实现(ACT-023 核心实测完成,双份保存与看图层切换经合成样本与自动化验证) |
+| FR-WB-006 | 缓存微博正文、图片、实况与混排([DEC-078](decisions.md#dec-078)、[DEC-079](decisions.md#dec-079)):保存全文(长微博的全文)、发布信息、按原顺序的全部官方原图(超过 9 张、GIF 保存原动图,扩展名按实际格式;主图恒定保存官方最高清原图 `largest`/`original`,默认开启“微博同时保存无水印版”开关,开启时对静态图与实况静帧额外保存无水印最大版 `/oslarge/` 伴侣文件 `images/NN_nowm.`,GIF 跳过、SHA-256 相同自动去重、`/oslarge/` 失效静默跳过不拖垮主图,看图层支持「原图 / 无水印」一键切换,可在“设置 › 缓存与下载”随时开关并立即生效;历史旧缓存可通过“设置 › 存储”/“任务 › 缓存队列”一键补全队列或“全部缓存”自动联动补齐伴侣图与旧格式链接并标记 `WeiboCacheStandardVersion = 3`)、实况照片的静帧与片段(QuickTime `.mov` 经 `mp4ff` 无损改封装为 `.mp4`)、混排里的视频与封面;单个主媒体缺失记黄点、不让整条失败。转发的微博连同其中的图片与视频存到转发者的 `forwards/`,清单记 `via`(DEC-056),原微博看不到时完整保存转发正文。媒体地址带签名的一律不落盘 | 已实现(ACT-023 核心实测完成,双份保存、看图层切换与历史补全经合成样本与自动化验证) |
| FR-WB-007 | 订阅与微博账号:订阅可以关联微博账号(贴主页链接、分享文本或 UID,先确认头像昵称;主键是 UID),一个订阅可以同时有三个站点的账号;“检查更新”“定时检查”“自动缓存”“全部缓存”对微博账号同样有效(第一次只建立起点;置顶与快转只按 ID 判断、不打断“到起点就停”;不是博主本人的推广卡片剔除;结果不确定时本轮不移动起点)。缓存规则的“视频 / 图文 / 文字 / 转发”对应微博的同类内容;“全部缓存”只补博主的原创微博(Q-023)。没登录微博时跳过微博账号并写明原因,不中断另外两个站点。“从关注列表导入”增加微博(全部关注里勾选导入;按分组筛选只在真实检查确认分组接口后提供) | 已实现(只经合成样本验证;真实站点待 ACT-023) |
| FR-WB-008 | 我的 › 微博(DEC-047):“我的”侧栏增加“微博”一组,只读、只在内存里、退出登录即清;提供登录账号的**关注**(点进用户页,“⋯ → 加入订阅”)与**收藏**(点进微博详情,“⋯ → 缓存”)。按自定义分组筛选关注、“赞过”只在真实检查(ACT-023 的 V-13、V-14)确认接口可用后显示入口,否则不显示(FR-WB-010) | 已实现(只经合成样本验证;真实站点待 ACT-023) |
| FR-WB-009 | 远程版与微博(DEC-062):本地“设置 › 远程”可以推送微博 Cookie(远程校验后保存、从不续期,登录失效时停止微博请求并提示重新同步);订阅同步包含微博账号,远程按规则检查微博更新与自动缓存(远程本来就不做全部缓存) | 已实现(假站点与远程冒烟通过;真实 VPS 与站点待 H-003 / ACT-023) |
diff --git a/docs/ui.md b/docs/ui.md
index b18b689..c28dd79 100644
--- a/docs/ui.md
+++ b/docs/ui.md
@@ -99,7 +99,8 @@
### 3.4 视频详情与用户页
-- **视频详情页**(解析路由):顶部返回箭头与“视频”;UP 主行(头像与昵称,点击进入空间;右侧“缓存视频”主按钮与状态圆点);标题(大号,充电专属视频并列“充电专属”或“充电专属(已解锁)”标记,未开通权益时在标题下方显示提醒横幅并禁用“缓存视频”按钮);大封面(已缓存时点击播放本机文件);简介(超过 6 行折叠);发布时间、分区;统计行(图标加数字);多 P 列表(已缓存时每 P 显示实际清晰度,如“1080P 高码率 · AV1 · 杜比全景声”,有 `chapters` 时在分 P 卡片下展示“章节看点”时间点胶囊,点击直接打开播放层并跳转到对应秒数)。在解析路由打开已缓存视频时集中提供缓存维护操作(DEC-037):探测到更高档时,标题上方显示黄色横幅与“升级缓存”按钮;同时在详情操作行提供“补存弹幕和字幕”按钮。
+- **视频详情页**(解析路由):顶部返回箭头与“视频”;UP 主行(头像与昵称,点击进入空间;右侧“缓存视频”主按钮、状态圆点,已缓存非归档条目另带“⋯”菜单提供“强制重新下载”“复制链接”“在浏览器中打开”“打开文件夹”,[DEC-079](decisions.md#dec-079));标题(大号,充电专属视频并列“充电专属”或“充电专属(已解锁)”标记,未开通权益时在标题下方显示提醒横幅并禁用“缓存视频”按钮);大封面(已缓存时点击播放本机文件);简介(超过 6 行折叠);发布时间、分区;统计行(图标加数字);多 P 列表(已缓存时每 P 显示实际清晰度,如“1080P 高码率 · AV1 · 杜比全景声”,有 `chapters` 时在分 P 卡片下展示“章节看点”时间点胶囊,点击直接打开播放层并跳转到对应秒数)。在解析路由打开已缓存视频时集中提供缓存维护操作(DEC-037):探测到更高档时,标题上方显示黄色横幅与“升级缓存”按钮;同时在详情操作行提供“补存弹幕和字幕”按钮。
+- **单条强制重新下载确认弹窗**([DEC-079](decisions.md#dec-079)):四站点联网已缓存详情页(微博帖子/视频、X 帖子、抖音作品、B 站视频,不含离线 `/library/item` 与 `archivedOf` 归档快照)的“⋯”菜单提供 **「强制重新下载」**;点击后先弹出二次确认对话框(标题“强制重新下载”,说明“将从源站重新完整下载并覆盖本机已有文件;若源站已删除或失效,仍会保留本机原文件不覆盖。”,取消 / 危险描边确认按钮),确认后从源站完整重拉并在校验通过后原子覆盖本地。微博与 X 详情页已缓存时的主按钮「重新缓存」维持非破坏性按新标准补全。
- **站点标记**(FR-SITE-002,DEC-043、DEC-065、DEC-066):用次要文字色、12px、无底色的小字“B 站”“抖音”“微博”“X”,紧跟在作者名或元信息后面(中间一个“ · ”)。出现在用户页头部、订阅详情“账号”列表、主页帖子作者行、媒体库卡片的元信息行、任务行、最近解析条目六处;订阅网格的头像不加。不使用站点的图标与品牌色。
- **本机内容详情**(`/library/item`,DEC-049 ③):从媒体库条目右下角“⋯ → 详情”进入媒体库自己的本机详情路由,图标栏仍高亮“媒体库”,上下文侧栏仍保持媒体库侧栏,返回箭头回到媒体库原来的筛选与滚动位置。只读本机清单和媒体,不发任何站点请求,缺图用占位图;不显示互动数据(播放数等会变,不缓存,DEC-040),未知时长不冒充 0;动态详情保留本机图片和引用视频卡片,直播录像显示“直播录像详情”、直播间、清晰度与分段原地播放,详情里的图片、视频、多 P、实况、配乐与录像分段点击都原地打开看图层或播放层。隐藏所有需要联网的操作(缓存、补存弹幕和字幕、升级缓存、刷新元数据),只在右上角“⋯”菜单保留一项“在解析页打开”供用户明确选择联网查看。
- **用户页**:横幅(带头像、昵称、`UID`、等级);下面一行“关注 N · 粉丝 N · 投稿 N”,右侧只有一个订阅按钮(未订阅时强调色“订阅”,点击打开[加入订阅对话框](#subscribe-picker);已订阅时“已订阅”,点击进入所属订阅)和一个“⋯”(“全部缓存”或“在缓存队列中查看”,“在浏览器中打开空间”,直播中另有“在浏览器中观看直播”);签名;标签栏为“动态”(默认)和“投稿”,标签不带数字,标签栏右侧是筛选“全部 / 未缓存”。动态是帖子(充电专属锁定动态标“充电专属”并显示锁定说明,不提供“缓存”菜单项);“投稿”标签下方提供简洁工具栏——关键词搜索框(仅在中文输入法非组合态按回车或点击“搜索”时发请求,绝不在输入过程防抖发请求;可“清空”)、排序切换(最新发布 / 最多播放 / 最多收藏)与分区筛选胶囊(服务端返回 `tlist` 非空时显示),切换条件重置分页并与本机“全部 / 未缓存”筛选协同;投稿是缩略图在左、标题和时长/播放数在右的紧凑行,点行打开视频,“缓存”“在浏览器中打开”在行右侧的“⋯”里。**整个头部是列表的第一行,随内容一起滚走**,窗口矮时也能看到内容(DEC-038)。两种列表都滚动到底自动加载。
@@ -140,7 +141,7 @@
- 空状态:“还没有符合筛选的媒体。缓存图片、视频或直播录像后,它们会出现在这里”。
- **任务**(图标栏“任务”,DEC-049 ①、DEC-050 ②、DEC-051 ③、[DEC-076](decisions.md#dec-076) ⑤):通过上下文侧栏(≥ 1000 宽;窄窗 `< 1000` 时退回为页面顶部的可换行分段选择,720 宽无横向溢出)组织七部分内容,点哪一项主面板显示哪一项:
1. **下载任务(N)**(N 为排队与进行中的下载任务数,与图标栏“任务”角标一致):顶部栏右侧提供“检查画质更新”按钮(执行时显示“检查 M / N · 取消”),列表上方固定批量操作栏——存在可重试任务(失败、部分完成或非用户手动暂停的暂停任务,按 `IsRetryableTask` 计数,不含用户手动暂停)时提供强调色“批量重试(N)”按钮(点击调用 `RetryAllTasks` 并按已登录站点隔离批量重新入队、在顶部横幅反馈重试/缺登录跳过/重复跳过结果),存在已结束(已完成 / 已取消)的任务时并排提供“清除已结束(N)”按钮。任务列表使用 `ui.List` 虚拟化滚动(仅渲染可见卡片,配合轻量摘要查询 `ListTasksSummary`、256px 缩略图与按 `libraryRev` 缓存的封面,不随每秒下载进度清空重查,单条操作只刷新任务列表),任务增多时仍流畅滚动。每行是对象缩略图、标题、站点小字、进度条与“已下载 / 总大小”、状态文字和操作(进行中/排队可暂停或取消;已暂停可继续;失败/部分完成可重试或移除;已完成/已取消可移除,不能取消;DEC-033)。失败原因(`LastError`)直接显示在任务行内;移除失败或部分完成的任务前,行内弹出确认提示“确认移除该任务?会删除未完成的临时文件,已缓存完成的文件会保留”。点“展开详情”(FR-CACHE-009)按需读取逐文件进度清单与脱敏后的分段重试记录。
- 2. **缓存队列(N)**(DEC-057 ②,替代每个队列占侧栏一行;N 为未结束的队列数):主面板顶部一行小字“取消或移除队列不会删除已缓存到媒体库的内容”,有结束的队列时右侧“清除已结束(N)”;下面每个队列一张卡片:头像、“账号名称 · 列表类型”、站点小字、状态(或下次时间)与“已缓存 x · 跳过 y”,右侧展开箭头与操作(进行中“暂停”“取消”,已暂停“继续”“取消”,已结束“移除”)。点卡片展开:当前正在缓存的条目、暂停或等待的原因、“最近缓存的内容”(本机封面——动态没有图片时用它引用的视频封面——、标题与缓存时间,点击直接打开本机内容)。从用户页“在缓存队列中查看”进入时展开对应的卡片。
+ 2. **缓存队列(N)**(DEC-057 ②、[DEC-079](decisions.md#dec-079),替代每个队列占侧栏一行;N 为未结束的队列数):当离线统计发现待补全历史微博且当前没有进行中的补全队列时,顶部展示一行紧凑操作条「发现 N 条历史微博可补全」与强调色「一键补全」按钮;下方一行小字“取消或移除队列不会删除已缓存到媒体库的内容”,有结束的队列时右侧“清除已结束(N)”;下面每个队列一张卡片:头像、“账号名称 · 列表类型”(历史补全队列固定标题为「历史缓存补全 · 微博」)、站点小字、状态(或下次时间)与“已缓存 x · 跳过 y”(补全队列显示“已补全 x / z 条 · 跳过 y 条”),右侧展开箭头与操作(进行中“暂停”“取消”,已暂停“继续”“取消”,已结束“移除”)。点卡片展开:当前正在缓存/补全的条目、暂停或等待的原因、“最近缓存的内容”(本机封面——动态没有图片时用它引用的视频封面——、标题与缓存时间,点击直接打开本机内容)。从用户页“在缓存队列中查看”或设置页“查看补全队列”进入时展开对应的卡片。
3. **内容冲突(N)**([DEC-076](decisions.md#dec-076) ⑤,[数据与缓存 §2.10](design/data-and-cache.md#conflict-protection);N 为待处理的缓存内容冲突数,为 0 时侧栏与窄窗分段显示“内容冲突”不带数字,图标栏“任务”角标不计入冲突数):专门展示全部缓存复查或下载层绊线发现的 V1/V2 资源不一致项,每个区域严格遵守最多一个强调色主按钮([§3](#main))。主面板上方为可换行的**批量操作栏**:左侧一行次要文字说明“源站内容与本地已缓存版本不一致时不会自动覆盖,默认可同时保留本地旧版与源站新版”,右侧为“全部待处理:”下拉框(选项依次为默认选中的 **保留两版(推荐)**、**保留本地**、**用新版替换**)与该栏唯一的强调色主按钮 **批量应用**(若批量选择“用新版替换”,点击后先在栏内展开行内二次确认再执行,确认行不使用强调色按钮)。下方按发现时间从新到旧排列白底 1px 细边框圆角**冲突卡片**:① 头部行显示纯离线本地缩略图(仅经 `GetLibraryItemMetaOnly` 与 `MediaPath` 读取本机已缓存封面或首图,缺图用占位块,**零网络请求**)、浅琥珀色警告原因标签(`分P变更` / `媒体替换` / `正文编辑` / `资源不一致`)、单行省略标题、站点小字、作者昵称与发现时间;② 浅灰圆角两行差异对比框:第一行“本地已缓存:<本地摘要>”,第二行“源站当前:<源站摘要>”(均严格脱敏,不含 URL 与查询串);③ 当上次处理失败(如未登录、远端失效降级硬拦截 `ErrRemoteDegradedRefused` 或文件共享锁回滚)时显示浅红底错误横幅并保留“(本地原文件未改动)”说明;④ 底部可换行操作行(每张卡片最多一个强调色主按钮):强调色主按钮 **保留两版**(异步执行 `keep_both`,执行中禁用卡片操作并显示“处理中…”)、白底灰描边次按钮 **保留本地**(`keep_local`,零请求记录忽略指纹)、红色描边按钮 **用新版替换**(点击后在该卡片内展开行内确认行:“确认用源站新版替换本地已缓存内容?” + 红色描边“确认替换” + 灰描边“取消”,确认行不放强调色按钮)与白底灰描边次按钮 **对比差异**(打开内容冲突并列对比弹窗)和 **查看本地**(纯离线打开 `/library/item` 查看本地已缓存 V1 详情,零网络请求)。没有待处理冲突时显示居中的次要文字空状态说明。
- **内容冲突并列对比弹窗**:点击冲突卡片的“对比差异”打开(支持 Esc 与点击遮罩关闭;窄窗 `720px` 自适应宽度、零横向溢出)。弹窗顶部显示冲突原因、标题、站点小字与“刷新对比”,下方固定左右双栏栏头(左“本地已缓存(旧版 V1)”、右“源站当前(新版 V2)”;源站不可用或未登录时仍保留本地栏并说明原因);主体分两区——**文字差异对比**(标题与正文/简介左右并排,字级差异在左侧以淡红底高亮旧文字、右侧以淡绿底高亮新文字;当任一侧存在安全外部超链接时,在正文左右两栏下方并排展示可点击的强调色超链接胶囊列表——悬停提示完整目标链接、点击经安全校验在系统浏览器打开,仅一侧有链接时另一侧明确显示“(无超链接)”,不含签名流地址或 Cookie;仅因 DEC-073 之前旧缓存内联 `(URL)` 格式造成的纯文字误报冲突会在读取或复核时自动清洗补写规范 `text`/`links` 并消解,不改动媒体文件)与**图片与视频并列对比**(按分 P `CID`/媒体标识对齐左右媒体卡片并标 `已变更` / `仅本地有` / `源站新增` / `可升级` / `相同`,展示分辨率、时长、编码与 `CID`,本地图片与视频可直接点击看图或播放,源站预览图仅内存按需加载、不写入 `cache-conflicts.json`);底部提供“查看本地详情”“保留本地”“用新版替换(行内确认)”与强调色“保留两版(推荐)”。
4. **直播录制(N)**(N 为正在录制的场数):列出正在录制的直播行与最近结束的录制行(主播头像、直播标题、站点小字、橙色“录制中”标记、已录时长、大小、速度、段数与清晰度编码如“原画 · AVC”,进行中右侧“停止录制”);有录制异常的场次在行上显示“⚠ N 处异常”小字(可点开查看异常);没有录制在进行时显示“现在没有直播在录制”。
@@ -166,7 +167,7 @@
- **画质与音质**:视频清晰度(能拿到的最高(推荐)/ 不超过 4K / 1080P / 720P);编码偏好(顺序:AVC 兼容性最好 / AV1 / HEVC,HEVC 注明“部分电脑无法在应用内播放”);音质(能拿到的最高(推荐)/ 192K);多 P 视频(全部分 P / 只缓存第 1 P);打开已缓存视频时检查画质更新(开关)。
- **缓存标签**(DEC-051 ⑧、[DEC-070](decisions.md#dec-070)):一个标签对应一项缓存能力,共 7 个固定原子标签——`定时检查`、`自动缓存视频`、`自动缓存图文`、`自动缓存文字`、`自动缓存转发`、`全部缓存`(DEC-061 ①,说明“每 7 天检查一次每个账号的全部作品(哔哩哔哩为投稿视频),将未缓存作品放入慢速缓存队列补齐”)、`开播录制`;新增订阅默认没有任何标签。顶部右对齐放置强调色“批量设置标签…”按钮(不带说明小字,DEC-038 ⑤;也可从订阅列表右上角“⋯ → 批量设置缓存标签…”打开):点击弹出“批量设置缓存标签”对话框,顶部为三段模式切换“添加标签 / 移除标签 / 替换标签”(替换模式下不选任何标签即清空所选订阅的全部标签),下面是 7 个能力标签的可多选胶囊、订阅搜索框(按订阅名称、备注或账号昵称过滤,支持输入法组合输入)、“全选”与“全不选”、全部订阅复选列表(本机头像、订阅名称与备注、右侧显示当前标签摘要或“无缓存标签”),底部“取消”与强调色确认按钮(“为 N 个订阅添加标签”/“从 N 个订阅移除标签”/“替换 N 个订阅的标签”/“清空 N 个订阅的标签”),一次原子写入。下方按细线列出全部 7 个能力标签:每行只显示标签名称、“N 个订阅”与右侧“管理订阅…”按钮(不带说明小字,DEC-038 ⑤);点“管理订阅…”弹出按单个标签批量管理订阅的对话框,包含标题“管理「<标签名>」的订阅”、功能说明、搜索框(支持输入法组合输入)、“全选”与“全不选”、全部订阅复选列表(已拥有该标签的预先勾上,右侧显示当前标签摘要),底部“取消”与强调色“应用到 N 个订阅”,一次写入更新该标签的归属并保留每个订阅原有的其他标签。
- **订阅与直播**(DEC-051 ③):定时检查更新(开关,说明“只在 TRACE 打开时检查;遇到风控会自动放慢”);检查间隔(30 分钟 / 1 小时 / 2 小时 / 6 小时,定时检查关闭时禁用);上次与下次检查时间,退避按站点分行写,如“抖音:因风控放慢到 1 小时,11 月 7 日 12:00 恢复”;开播检查间隔(1~30 分钟,说明“只在有订阅开启开播自动录制时运行”;间隔下一行写当前实际间隔,如“现在:B 站每轮查全部账号;抖音 17 个账号,每个约每 3 分钟查一次”,再下面一段小字“开播检查规则”:B 站一个请求查完全部账号、每轮一查;抖音每个账号单独一个请求、两个请求至少隔 6 秒、一轮最多几个账号,不超过时每个都按间隔查,超过后轮流查、每多一个账号间隔约多 6 秒;开播检查不占每小时额度,风控或限流时一起暂停;手动刷新、检查更新看到开播也马上录制。数字随所选间隔变化,DEC-060 ④⑤;不设同时录制数上限)。
- - **存储**:安装位置、数据目录、缓存位置(只读路径 + “打开文件夹”、“重建索引”,缓存位置的修改也在本页);显示当前是正式版还是开发版;媒体库占用空间;“添加已有的缓存文件夹”(选择文件夹后显示“接入了 N 条,跳过 M 条(已存在)”,说明“文件留在原处”)。
+ - **存储**:安装位置、数据目录、缓存位置(只读路径 + “打开文件夹”、“重建索引”,缓存位置的修改也在本页);紧凑一行 **“历史缓存标准”**([DEC-079](decisions.md#dec-079),纯离线统计 0 网络请求:全部符合最新标准时简洁显示“历史缓存已全部符合最新标准”;存在待补全历史微博时显示计数与强调色“补全历史缓存”按钮;补全进行中显示实时进度与“查看补全队列”按钮跳转至任务页);显示当前是正式版还是开发版;媒体库占用空间;“添加已有的缓存文件夹”(选择文件夹后显示“接入了 N 条,跳过 M 条(已存在)”,说明“文件留在原处”)。
- **常规**(滑杆图标):关闭窗口时(最小化到托盘(推荐)/ 退出),说明“最小化到托盘时,TRACE 会释放界面占用的内存,缓存、定时检查和录制在后台继续”。
- **网络**(链接图标,DEC-046 ⑤):“代理”下拉框:跟随系统(推荐)/ 不用代理 / 自定义,说明“站点接口、缓存下载和直播录制都走这里的设置,改动立即生效”。跟随系统时下面一行小字“使用 Windows 的代理设置(含自动配置脚本);设置了 HTTP_PROXY / HTTPS_PROXY 环境变量时以环境变量为准”。选“自定义”后出现地址输入框(`http://`、`https://` 或 `socks5://`,只写协议、主机和端口,没写协议按 `http://`;带账号密码的地址不接受,红字提示改用不需要登录的本机代理)与“保存”按钮;地址通过检查才改用,不通过时在框下红字说明原因。
- **远程**(上传图标,DEC-062,[远程 §7](design/remote.md#status)):没有连接时一节“连接远程”:一段说明(远程是 VPS 上的 `trace-server`,在 VPS 上运行 `trace-server init` 后把连接码粘贴到这里)、“远程连接码”输入框(或切换为分别填写地址、令牌、证书指纹三个输入框)、强调色“连接”(连接中“正在连接…”)与“分别填写地址、令牌与指纹 / 粘贴连接码”切换;失败时红字写原因(无法连接、证书变了、令牌错、版本不同各自的文案);底部小字说明只连接指纹一致的远程、令牌存本机凭证。连接后:顶部一张浅灰卡片(名字、地址 · 版本 · 已运行时长、证书指纹缩写,右侧“刷新”与红色描边“断开”,断开前行内确认);有错误时一条红底提示;下面按细线分节——**订阅**(“已同步”绿点或“有改动未同步”、远程订阅与账号数、上次同步时间,右侧强调色“同步订阅”,一行说明远程只缓存同步之后的新内容、“全部缓存”不在远程执行);**登录**(哔哩哔哩、抖音、微博、X 四个站点各一行:状态圆点与“有效 · 昵称 · Cookie 同步于 …”/“需要重新同步”/“未登录”/“退避到 …”,前三个站点本地标了“Cookie 待同步”时写出来,右侧“同步 Cookie”,有登录时另有红色描边“清除远程登录”;点击 X 行的“同步 Cookie”不直接发请求,先弹出确认对话框说明云服务器机房 IP 风险——“在云服务器的网络上用网页 Cookie 访问 X,被要求验证或锁号的可能明显高于家里的网络,不建议本地和远程同时用同一个 X 账号检查”——确认仅对本次推送有效,取消零请求;下方一行说明 B 站/抖音/微博自动推送、X 绝不自动推送以及远程不续期);**检查与缓存**(定时检查的账号数与下次时间、缓存中与排队数、录制中的场次、最近完成与失败);**上传与空间**(上传方式与目标、待上传条目与大小、今天已传、正在上传的条目、最近一次失败的原因与下次重试,rclone 找不到等按类别说明;导出目录剩余 / 总空间,低于 5 GiB 警告、低于 1 GiB 写“已暂停新的缓存”);**最近错误**(时间、类别、脱敏说明)。页面显示时每 30 秒刷新一次,离开页面不请求远程。
diff --git a/internal/download/conflict_contract.go b/internal/download/conflict_contract.go
index 42013ac..25dd44c 100644
--- a/internal/download/conflict_contract.go
+++ b/internal/download/conflict_contract.go
@@ -14,6 +14,7 @@ import (
"unicode/utf8"
"github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/site"
"github.com/chialecode/trace/internal/site/bilibili"
)
@@ -47,6 +48,7 @@ var (
)
type conflictResolutionCtxKey struct{}
+type forceOverwriteCtxKey struct{}
// WithConflictResolution tags ctx with an explicit conflict resolution mode
// ("keep_both" or "use_remote") so download entrypoints permit staged V2 execution.
@@ -66,6 +68,43 @@ func ConflictResolutionFromContext(ctx context.Context) string {
return strings.TrimSpace(v)
}
+// WithForceOverwrite marks ctx as an explicit manual force-redownload request
+// (DEC-079). Automatic tasks, queues, and scheduled checks MUST NEVER set this
+// and are rejected by effectiveForceOverwrite even if a caller passes it.
+func WithForceOverwrite(ctx context.Context) context.Context {
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ return context.WithValue(ctx, forceOverwriteCtxKey{}, true)
+}
+
+// ForceOverwriteFromContext reports whether ctx requests manual force overwrite.
+func ForceOverwriteFromContext(ctx context.Context) bool {
+ if ctx == nil {
+ return false
+ }
+ v, _ := ctx.Value(forceOverwriteCtxKey{}).(bool)
+ return v
+}
+
+// effectiveForceOverwrite returns true only for explicit manual requests; any
+// automatic, queue, or background-sourced download always returns false.
+func effectiveForceOverwrite(ctx context.Context, source string, flags ...bool) bool {
+ src := strings.ToLower(strings.TrimSpace(source))
+ if src == "auto" || src == "queue" || site.AutomaticRequestSource(ctx) != "" {
+ return false
+ }
+ if ForceOverwriteFromContext(ctx) {
+ return true
+ }
+ for _, f := range flags {
+ if f {
+ return true
+ }
+ }
+ return false
+}
+
func normalizeConflictResolution(raw string) string {
switch strings.ToLower(strings.TrimSpace(raw)) {
case ConflictResolveKeepBoth:
@@ -176,9 +215,41 @@ func (m *Manager) taskResolutionAndPages(taskID string) (string, []int) {
return normalizeConflictResolution(mode), pages
}
+func (m *Manager) storeTaskForceOverwrite(taskID string, force bool) {
+ if m == nil || taskID == "" || !force {
+ return
+ }
+ m.mu.Lock()
+ if m.forceOverwrites == nil {
+ m.forceOverwrites = make(map[string]bool)
+ }
+ m.forceOverwrites[taskID] = true
+ if ip, ok := m.initialPlans[taskID]; ok {
+ ip.ForceOverwrite = true
+ m.initialPlans[taskID] = ip
+ }
+ m.mu.Unlock()
+}
+
+func (m *Manager) taskForceOverwrite(taskID string) bool {
+ if m == nil || taskID == "" {
+ return false
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.forceOverwrites[taskID] {
+ return true
+ }
+ if ip, ok := m.initialPlans[taskID]; ok && ip.ForceOverwrite {
+ return true
+ }
+ return false
+}
+
func (m *Manager) clearTaskResolutionStateLocked(taskID string) {
delete(m.conflictResolutions, taskID)
delete(m.conflictPages, taskID)
+ delete(m.forceOverwrites, taskID)
}
func (m *Manager) recordTaskOutcome(taskID string, err error) {
diff --git a/internal/download/douyin_note.go b/internal/download/douyin_note.go
index 9bab664..752437c 100644
--- a/internal/download/douyin_note.go
+++ b/internal/download/douyin_note.go
@@ -23,6 +23,7 @@ func (m *Manager) executeDouyinNoteTask(ctx context.Context, t *Task, plan WorkD
hasProtectedLocal := exists && localHasProtectedContent(previous)
mode := effectiveConflictResolution(ctx, t.ConflictResolution, plan.ConflictResolution)
+ forceOverwrite := effectiveForceOverwrite(ctx, t.Source, t.ForceOverwrite, plan.ForceOverwrite)
isConflict := false
if hasProtectedLocal {
notice, conflict, degErr := classifyWorkPlanVsLocal(previous, plan, t.ItemKey, t.TargetID, t)
@@ -30,15 +31,18 @@ func (m *Manager) executeDouyinNoteTask(ctx context.Context, t *Task, plan WorkD
return degErr
}
isConflict = conflict
- if isConflict && mode != ConflictResolveKeepBoth && mode != ConflictResolveUseRemote {
+ if isConflict && !forceOverwrite && mode != ConflictResolveKeepBoth && mode != ConflictResolveUseRemote {
m.emitConflict(notice)
return ErrConflictDetected
}
+ if forceOverwrite && mode == "" {
+ mode = ConflictResolveUseRemote
+ }
}
title := firstNonEmptyStr(plan.Title, plan.Desc, t.Title, "抖音图文 "+t.TargetID)
desc := plan.Desc
- if hasProtectedLocal && !isConflict {
+ if hasProtectedLocal && !isConflict && !forceOverwrite {
title = preserveMonotonicText(previous.Title, title, false)
desc = preserveMonotonicText(previous.Desc, desc, false)
}
@@ -127,7 +131,7 @@ func (m *Manager) executeDouyinNoteTask(ctx context.Context, t *Task, plan WorkD
// Optional cover. when explicitly provided.
if cfg.SaveCover && len(plan.CoverURLs) > 0 {
reusedCover := false
- if hasProtectedLocal && !isConflict {
+ if hasProtectedLocal && !isConflict && !forceOverwrite {
for _, mf := range previous.Media {
if mf.Role == "cover" && mediaIsValid(previous, mf.Path) {
if copied, rErr := copyLocalMediaToStageAs(previous, mf.Path, mf.Path, "cover", workDir); rErr == nil {
@@ -165,6 +169,9 @@ func (m *Manager) executeDouyinNoteTask(ctx context.Context, t *Task, plan WorkD
prefix := fmt.Sprintf("images/%02d", pageIdx)
cleanPageMediaID := library.SanitizeMediaToken(page.MediaID)
reusableLP, canReuseLocal := findReusableLocalPage(previous, page, pageIdx, isConflict)
+ if forceOverwrite {
+ canReuseLocal = false
+ }
pageKind := strings.ToLower(strings.TrimSpace(page.Kind))
if pageKind == "" {
if len(page.VideoURLs) > 0 {
@@ -199,7 +206,7 @@ func (m *Manager) executeDouyinNoteTask(ctx context.Context, t *Task, plan WorkD
if isSiteStopError(imgErr) || isStorageError(imgErr) || ctx.Err() != nil {
return imgErr
}
- if hasProtectedLocal && isConflict && isDegradedSiteError(imgErr) {
+ if hasProtectedLocal && (isConflict || forceOverwrite) && isDegradedSiteError(imgErr) {
return wrapRemoteDegraded(imgErr)
}
reason := fmt.Sprintf("第 %02d 页图片下载失败 (%s)", pageIdx, classifyDownloadError(imgErr))
@@ -242,7 +249,7 @@ func (m *Manager) executeDouyinNoteTask(ctx context.Context, t *Task, plan WorkD
if isSiteStopError(imgErr) || isStorageError(imgErr) || ctx.Err() != nil {
return imgErr
}
- if hasProtectedLocal && isConflict && isDegradedSiteError(imgErr) {
+ if hasProtectedLocal && (isConflict || forceOverwrite) && isDegradedSiteError(imgErr) {
return wrapRemoteDegraded(imgErr)
}
reason := fmt.Sprintf("第 %02d 页实况静帧下载失败 (%s)", pageIdx, classifyDownloadError(imgErr))
@@ -285,7 +292,7 @@ func (m *Manager) executeDouyinNoteTask(ctx context.Context, t *Task, plan WorkD
if isSiteStopError(mErr) || isStorageError(mErr) || ctx.Err() != nil {
return mErr
}
- if hasProtectedLocal && isConflict && isDegradedSiteError(mErr) {
+ if hasProtectedLocal && (isConflict || forceOverwrite) && isDegradedSiteError(mErr) {
return wrapRemoteDegraded(mErr)
}
reason := fmt.Sprintf("第 %02d 页实况视频下载失败 (%s)", pageIdx, classifyDownloadError(mErr))
@@ -371,7 +378,7 @@ func (m *Manager) executeDouyinNoteTask(ctx context.Context, t *Task, plan WorkD
if isSiteStopError(vErr) || isStorageError(vErr) || ctx.Err() != nil {
return vErr
}
- if hasProtectedLocal && isConflict && isDegradedSiteError(vErr) {
+ if hasProtectedLocal && (isConflict || forceOverwrite) && isDegradedSiteError(vErr) {
return wrapRemoteDegraded(vErr)
}
reason := fmt.Sprintf("第 %02d 页视频下载失败 (%s)", pageIdx, classifyDownloadError(vErr))
@@ -455,7 +462,7 @@ func (m *Manager) executeDouyinNoteTask(ctx context.Context, t *Task, plan WorkD
Cover: musicCover,
Original: plan.Music.Original,
}
- sameMusic := previous.Music != nil && previous.Music.File != "" && mediaIsValid(previous, previous.Music.File) &&
+ sameMusic := !forceOverwrite && previous.Music != nil && previous.Music.File != "" && mediaIsValid(previous, previous.Music.File) &&
(!isConflict || (previous.Music.ID != "" && plan.Music.ID == previous.Music.ID))
if len(plan.Music.PlayURLs) == 0 {
if hasProtectedLocal && sameMusic {
@@ -505,7 +512,7 @@ func (m *Manager) executeDouyinNoteTask(ctx context.Context, t *Task, plan WorkD
mediaFiles = append(mediaFiles, *musicMedia)
}
}
- } else if hasProtectedLocal && !isConflict && previous.Music != nil && previous.Music.File != "" && mediaIsValid(previous, previous.Music.File) {
+ } else if hasProtectedLocal && !isConflict && !forceOverwrite && previous.Music != nil && previous.Music.File != "" && mediaIsValid(previous, previous.Music.File) {
cp := *previous.Music
if copied, rErr := copyLocalMediaToStageAs(previous, previous.Music.File, previous.Music.File, "audio", workDir); rErr == nil {
cp.File = copied.Path
@@ -514,7 +521,7 @@ func (m *Manager) executeDouyinNoteTask(ctx context.Context, t *Task, plan WorkD
}
}
- if hasProtectedLocal && isConflict && len(partialErrors) > 0 {
+ if hasProtectedLocal && (isConflict || forceOverwrite) && len(partialErrors) > 0 {
return wrapRemoteDegradedMsg(fmt.Sprintf("新版部分媒体下载失败,已保留本地原文件 (%s)", strings.Join(partialErrors, "; ")))
}
@@ -525,7 +532,7 @@ func (m *Manager) executeDouyinNoteTask(ctx context.Context, t *Task, plan WorkD
t.ErrorMessage = summarizeMissingReasons(missing)
}
- mediaFiles, notePages = preserveValidPreviousImagesForStage(itemDir, workDir, previous, exists && !isConflict, mediaFiles, notePages)
+ mediaFiles, notePages = preserveValidPreviousImagesForStage(itemDir, workDir, previous, exists && !isConflict && !forceOverwrite, mediaFiles, notePages)
meta := library.ItemMetadata{
Version: 1,
diff --git a/internal/download/douyin_plan.go b/internal/download/douyin_plan.go
index 211939f..09d2690 100644
--- a/internal/download/douyin_plan.go
+++ b/internal/download/douyin_plan.go
@@ -120,6 +120,7 @@ type WorkDownloadPlan struct {
EditCount int // sanitized remote edit counter
AssetIDs []string // sanitized ordered platform asset IDs
ConflictResolution string // explicit "keep_both" or "use_remote" when resolving a conflict
+ ForceOverwrite bool `json:"-"` // explicit manual-only force redownload & atomic overwrite (DEC-079)
Transport site.MediaTransportSpec
}
@@ -411,10 +412,13 @@ func (m *Manager) EnqueueDouyinWork(ctx context.Context, req DouyinWorkEnqueueRe
ctx = site.WithAutomaticRequests(ctx, "download")
}
var reqPlanMode string
+ var reqPlanForce bool
if req.Plan != nil {
reqPlanMode = req.Plan.ConflictResolution
+ reqPlanForce = req.Plan.ForceOverwrite
}
mode := effectiveConflictResolution(ctx, reqPlanMode)
+ forceOverwrite := effectiveForceOverwrite(ctx, source, reqPlanForce)
var plan WorkDownloadPlan
if req.Plan != nil {
@@ -447,6 +451,7 @@ func (m *Manager) EnqueueDouyinWork(ctx context.Context, req DouyinWorkEnqueueRe
if mode != "" {
plan.ConflictResolution = mode
}
+ plan.ForceOverwrite = forceOverwrite
kind := normalizeDouyinTaskKind(firstNonEmptyStr(plan.Kind, req.Kind), len(plan.Pages) > 0)
plan.Kind = kind
@@ -512,6 +517,7 @@ func (m *Manager) EnqueueDouyinWork(ctx context.Context, req DouyinWorkEnqueueRe
ItemDir: itemDir,
Via: via,
ConflictResolution: mode,
+ ForceOverwrite: forceOverwrite,
}, &plan)
if err != nil {
return Task{}, err
@@ -519,6 +525,9 @@ func (m *Manager) EnqueueDouyinWork(ctx context.Context, req DouyinWorkEnqueueRe
if mode != "" {
m.storeTaskResolutionAndPages(t.TaskID, mode, nil)
}
+ if forceOverwrite {
+ m.storeTaskForceOverwrite(t.TaskID, true)
+ }
m.notifyWake()
return t, nil
@@ -650,6 +659,9 @@ func (m *Manager) consumeInitialOrFetchDouyinPlan(ctx context.Context, taskID, t
if hasInitial && initial.ConflictResolution != "" && plan.ConflictResolution == "" {
plan.ConflictResolution = initial.ConflictResolution
}
+ if hasInitial && initial.ForceOverwrite {
+ plan.ForceOverwrite = true
+ }
if len(plan.Transport.AllowedDomains) == 0 {
plan.Transport = site.DouyinVODTransport("", false)
}
@@ -676,6 +688,12 @@ func (m *Manager) executeDouyinTask(ctx context.Context, t *Task) error {
mode = effectiveConflictResolution(ctx, t.ConflictResolution, storedMode, plan.ConflictResolution)
plan.ConflictResolution = mode
t.ConflictResolution = mode
+ forceOverwrite := effectiveForceOverwrite(ctx, t.Source, t.ForceOverwrite, m.taskForceOverwrite(t.TaskID), plan.ForceOverwrite)
+ plan.ForceOverwrite = forceOverwrite
+ t.ForceOverwrite = forceOverwrite
+ if forceOverwrite {
+ ctx = WithForceOverwrite(ctx)
+ }
normUID, err := site.NormalizeUID(site.Douyin, firstNonEmptyStr(plan.AuthorUID, t.AuthorUID))
if err != nil {
diff --git a/internal/download/douyin_video.go b/internal/download/douyin_video.go
index 24cfa50..ef236c3 100644
--- a/internal/download/douyin_video.go
+++ b/internal/download/douyin_video.go
@@ -30,6 +30,7 @@ func (m *Manager) executeDouyinVideoTask(ctx context.Context, t *Task, plan Work
hasProtectedLocal := exists && localHasProtectedContent(previous)
mode := effectiveConflictResolution(ctx, t.ConflictResolution, plan.ConflictResolution)
+ forceOverwrite := effectiveForceOverwrite(ctx, t.Source, t.ForceOverwrite, plan.ForceOverwrite)
isConflict := false
if hasProtectedLocal {
notice, conflict, degErr := classifyWorkPlanVsLocal(previous, plan, t.ItemKey, t.TargetID, t)
@@ -37,15 +38,18 @@ func (m *Manager) executeDouyinVideoTask(ctx context.Context, t *Task, plan Work
return degErr
}
isConflict = conflict
- if isConflict && mode != ConflictResolveKeepBoth && mode != ConflictResolveUseRemote {
+ if isConflict && !forceOverwrite && mode != ConflictResolveKeepBoth && mode != ConflictResolveUseRemote {
m.emitConflict(notice)
return ErrConflictDetected
}
+ if forceOverwrite && mode == "" {
+ mode = ConflictResolveUseRemote
+ }
}
title := firstNonEmptyStr(plan.Title, plan.Desc, t.Title, "抖音视频 "+t.TargetID)
desc := plan.Desc
- if hasProtectedLocal && !isConflict {
+ if hasProtectedLocal && !isConflict && !forceOverwrite {
title = preserveMonotonicText(previous.Title, title, false)
desc = preserveMonotonicText(previous.Desc, desc, false)
}
@@ -464,13 +468,14 @@ func (m *Manager) executeDouyinVideoStaged(
t.Attempts = subTask.Attempts
}()
+ forceOverwrite := effectiveForceOverwrite(ctx, t.Source, t.ForceOverwrite, plan.ForceOverwrite)
refreshOncePlan := m.makeSinglePlanRefresher(ctx, t.TargetID, planner)
var v2Media []library.MediaFile
var v2Missing []library.MissingRecord
- // 1. Cover: stage fresh cover on conflict, or reuse verified local cover.
+ // 1. Cover: stage fresh cover on conflict or ForceOverwrite, otherwise reuse verified local cover.
reusedCover := false
- if !isConflict {
+ if !isConflict && !forceOverwrite {
for _, mf := range previous.Media {
if mf.Role == "cover" && mediaIsValid(previous, mf.Path) {
if copied, cErr := copyLocalMediaToStageAs(previous, mf.Path, mf.Path, "cover", stageDir); cErr == nil {
@@ -490,13 +495,15 @@ func (m *Manager) executeDouyinVideoStaged(
} else if cErr != nil && (isSiteStopError(cErr) || isStorageError(cErr) || ctx.Err() != nil) {
return cErr
} else {
- for _, mf := range previous.Media {
- if mf.Role == "cover" && mediaIsValid(previous, mf.Path) {
- if copied, rErr := copyLocalMediaToStageAs(previous, mf.Path, mf.Path, "cover", stageDir); rErr == nil {
- v2Media = append(v2Media, *copied)
- reusedCover = true
+ if !forceOverwrite {
+ for _, mf := range previous.Media {
+ if mf.Role == "cover" && mediaIsValid(previous, mf.Path) {
+ if copied, rErr := copyLocalMediaToStageAs(previous, mf.Path, mf.Path, "cover", stageDir); rErr == nil {
+ v2Media = append(v2Media, *copied)
+ reusedCover = true
+ }
+ break
}
- break
}
}
if !reusedCover {
@@ -516,7 +523,7 @@ func (m *Manager) executeDouyinVideoStaged(
sameMediaID = true
}
- if !isConflict && !planUpgradesSingleVideo(previous, plan) && mediaIsValid(previous, videoRel) {
+ if !isConflict && !forceOverwrite && !planUpgradesSingleVideo(previous, plan) && mediaIsValid(previous, videoRel) {
copied, err := copyLocalMediaToStageAs(previous, videoRel, videoRel, "video", stageDir)
if err != nil {
return err
@@ -553,8 +560,8 @@ func (m *Manager) executeDouyinVideoStaged(
}
if !original {
// On safe upgrade where local already had the transcoded tier and only OriginalURLs was new,
- // reuse verified local video if OriginalURLs failed instead of re-downloading the same tier.
- if !isConflict && mediaIsValid(previous, videoRel) && previous.DouyinVideo != nil &&
+ // reuse verified local video if OriginalURLs failed instead of re-downloading the same tier (never on ForceOverwrite).
+ if !isConflict && !forceOverwrite && mediaIsValid(previous, videoRel) && previous.DouyinVideo != nil &&
plan.Width*plan.Height <= previous.DouyinVideo.Width*previous.DouyinVideo.Height {
copied, cErr := copyLocalMediaToStageAs(previous, videoRel, videoRel, "video", stageDir)
if cErr == nil {
@@ -576,7 +583,7 @@ func (m *Manager) executeDouyinVideoStaged(
})
vidMedia, vErr := m.cacheDouyinSingleMP4(ctx, &subTask, stageDir, previous, false, "video", videoRel, plan.VideoURLs, plan.NeedSetToken, plan.DurationSec, plan.Width, plan.Height, plan.Transport, planner, refreshVideoURLs)
if vErr != nil {
- if (!isConflict || sameMediaID) && mediaIsValid(previous, videoRel) && ctx.Err() == nil && !isStorageError(vErr) {
+ if !forceOverwrite && (!isConflict || sameMediaID) && mediaIsValid(previous, videoRel) && ctx.Err() == nil && !isStorageError(vErr) {
if copied, cErr := copyLocalMediaToStageAs(previous, videoRel, videoRel, "video", stageDir); cErr == nil {
v2Media = append(v2Media, *copied)
if previous.DouyinVideo != nil {
diff --git a/internal/download/dynamic.go b/internal/download/dynamic.go
index 8fb401a..fcd12fc 100644
--- a/internal/download/dynamic.go
+++ b/internal/download/dynamic.go
@@ -32,6 +32,7 @@ func (m *Manager) executeDynamicTask(ctx context.Context, t *Task) (result error
storedMode, _ := m.taskResolutionAndPages(t.TaskID)
mode := effectiveConflictResolution(ctx, t.ConflictResolution, storedMode)
+ forceOverwrite := effectiveForceOverwrite(ctx, t.Source, t.ForceOverwrite, m.taskForceOverwrite(t.TaskID))
previous, exists, err := m.lib.GetItem("dynamic:" + t.TargetID)
if err != nil {
@@ -135,11 +136,15 @@ func (m *Manager) executeDynamicTask(ctx context.Context, t *Task) (result error
if degErr != nil {
return degErr
}
- if isConflict && mode != ConflictResolveKeepBoth && mode != ConflictResolveUseRemote {
+ if isConflict && !forceOverwrite && mode != ConflictResolveKeepBoth && mode != ConflictResolveUseRemote {
m.emitConflict(notice)
return ErrConflictDetected
}
- return m.executeBilibiliDynamicStaged(ctx, t, dyn, previous, itemDir, authorDir, cacheRoot, forward, multiPart, videoRefs, dynAssets, mode, isConflict)
+ effectiveMode := mode
+ if forceOverwrite && effectiveMode == "" {
+ effectiveMode = ConflictResolveUseRemote
+ }
+ return m.executeBilibiliDynamicStaged(ctx, t, dyn, previous, itemDir, authorDir, cacheRoot, forward, multiPart, videoRefs, dynAssets, effectiveMode, isConflict)
}
for idx, img := range dyn.Images {
@@ -504,6 +509,7 @@ func (m *Manager) executeBilibiliDynamicStaged(
_ = library.RemoveTempSubdirSafe(itemDir, stageDir)
}()
+ forceOverwrite := effectiveForceOverwrite(ctx, t.Source, t.ForceOverwrite)
var mediaFiles []library.MediaFile
var partialErrors []string
@@ -518,16 +524,18 @@ func (m *Manager) executeBilibiliDynamicStaged(
return err
}
mediaFiles = append(mediaFiles, library.MediaFile{Role: "snapshot", Path: "orig.json", Bytes: n, SHA256: sha})
- } else if !isConflict && mediaIsValid(previous, "orig.json") {
+ } else if !isConflict && !forceOverwrite && mediaIsValid(previous, "orig.json") {
if mf, err := copyLocalMediaToStageAs(previous, "orig.json", "orig.json", "snapshot", stageDir); err == nil {
mediaFiles = append(mediaFiles, *mf)
}
}
localBySource := make(map[string]library.MediaFile, len(previous.Media))
- for _, mf := range previous.Media {
- if mf.Role == "image" && mf.Source != "" && mediaIsValid(previous, mf.Path) {
- localBySource[bilibiliSourceKey(mf.Source)] = mf
+ if !forceOverwrite {
+ for _, mf := range previous.Media {
+ if mf.Role == "image" && mf.Source != "" && mediaIsValid(previous, mf.Path) {
+ localBySource[bilibiliSourceKey(mf.Source)] = mf
+ }
}
}
@@ -568,7 +576,7 @@ func (m *Manager) executeBilibiliDynamicStaged(
if isStopError(dlErr) || isStorageError(dlErr) || ctx.Err() != nil {
return dlErr
}
- if isDegradedSiteError(dlErr) && isConflict {
+ if isDegradedSiteError(dlErr) && (isConflict || forceOverwrite) {
return wrapRemoteDegraded(dlErr)
}
partialErrors = append(partialErrors, fmt.Sprintf("img_%02d: %v", idx+1, dlErr))
@@ -668,6 +676,7 @@ func (m *Manager) executeBilibiliDynamicStaged(
Page: page.Page,
Source: t.Source,
ConflictResolution: mode,
+ ForceOverwrite: forceOverwrite,
LinkedVideo: true,
ProgressOwner: t,
ProgressPrefix: "videos/" + v.BVID + "/",
@@ -696,7 +705,7 @@ func (m *Manager) executeBilibiliDynamicStaged(
}
}
- if len(partialErrors) > 0 && isConflict {
+ if len(partialErrors) > 0 && (isConflict || forceOverwrite) {
return wrapRemoteDegradedMsg(fmt.Sprintf("新版部分媒体已失效,已保留本地原文件 (%s)", strings.Join(partialErrors, "; ")))
}
@@ -709,9 +718,9 @@ func (m *Manager) executeBilibiliDynamicStaged(
missing = append(missing, library.MissingRecord{Item: "media", Reason: pe})
}
}
- mediaFiles, _ = preserveValidPreviousImagesForStage(itemDir, stageDir, previous, !isConflict, mediaFiles, nil)
+ mediaFiles, _ = preserveValidPreviousImagesForStage(itemDir, stageDir, previous, !isConflict && !forceOverwrite, mediaFiles, nil)
v2Text := dyn.Text
- if !isConflict {
+ if !isConflict && !forceOverwrite {
v2Text = preserveMonotonicText(previous.Text, dyn.Text, false)
}
v2Meta := library.ItemMetadata{
diff --git a/internal/download/force_recache_and_backfill_test.go b/internal/download/force_recache_and_backfill_test.go
new file mode 100644
index 0000000..de68ec0
--- /dev/null
+++ b/internal/download/force_recache_and_backfill_test.go
@@ -0,0 +1,855 @@
+package download
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "image/color"
+ "io"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/site"
+ "github.com/chialecode/trace/internal/site/bilibili"
+)
+
+func sha256HexBytes(data []byte) string {
+ sum := sha256.Sum256(data)
+ return hex.EncodeToString(sum[:])
+}
+
+func TestEffectiveForceOverwriteManualOnlyContract(t *testing.T) {
+ ctx := WithForceOverwrite(context.Background())
+ if !ForceOverwriteFromContext(ctx) {
+ t.Fatal("ForceOverwriteFromContext should be true")
+ }
+ if !effectiveForceOverwrite(ctx, "manual") {
+ t.Fatal("manual source with WithForceOverwrite must allow forceOverwrite")
+ }
+ if !effectiveForceOverwrite(ctx, "") {
+ t.Fatal("empty manual source with WithForceOverwrite must allow forceOverwrite")
+ }
+ if effectiveForceOverwrite(ctx, "auto") {
+ t.Fatal("auto source must NEVER honor forceOverwrite")
+ }
+ if effectiveForceOverwrite(ctx, "queue") {
+ t.Fatal("queue source must NEVER honor forceOverwrite")
+ }
+ if effectiveForceOverwrite(site.WithAutomaticRequests(ctx, "queue"), "manual") {
+ t.Fatal("automatic request context must NEVER honor forceOverwrite")
+ }
+ if effectiveForceOverwrite(context.Background(), "manual") {
+ t.Fatal("plain context without flag must not enable forceOverwrite")
+ }
+}
+
+func TestBackfillWeiboNoWMCompanionsDirectCDNAndRateLimitStop(t *testing.T) {
+ orig1 := makeWatermarkTestJPEG(t, 48, 36, color.RGBA{R: 200, G: 60, B: 40, A: 255})
+ nowm1 := makeWatermarkTestJPEG(t, 32, 24, color.RGBA{R: 30, G: 130, B: 210, A: 255})
+ orig2 := makeWatermarkTestJPEG(t, 40, 30, color.RGBA{R: 60, G: 180, B: 80, A: 255})
+ orig3 := makeWatermarkTestJPEG(t, 44, 32, color.RGBA{R: 150, G: 90, B: 200, A: 255})
+ gif4 := makeWatermarkTestAnimatedGIF(t)
+
+ var (
+ mu sync.Mutex
+ hitPaths []string
+ sawCookie bool
+ sawRef bool
+ mode429 atomic.Bool
+ )
+
+ rt := roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ mu.Lock()
+ hitPaths = append(hitPaths, req.URL.Path)
+ if req.Header.Get("Cookie") != "" {
+ sawCookie = true
+ }
+ if req.Header.Get("Referer") == "https://weibo.com/" {
+ sawRef = true
+ }
+ mu.Unlock()
+
+ if mode429.Load() {
+ return &http.Response{
+ StatusCode: http.StatusTooManyRequests,
+ Header: http.Header{"Content-Type": []string{"text/plain"}},
+ Body: io.NopCloser(strings.NewReader("rate limited")),
+ }, nil
+ }
+
+ switch req.URL.Path {
+ case "/oslarge/001picSlot1.jpg":
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ ContentLength: int64(len(nowm1)),
+ Header: http.Header{"Content-Type": []string{"image/jpeg"}},
+ Body: io.NopCloser(bytes.NewReader(nowm1)),
+ }, nil
+ case "/oslarge/002picSlot2.jpg":
+ // Identical SHA-256 to primary -> deduped, no companion saved.
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ ContentLength: int64(len(orig2)),
+ Header: http.Header{"Content-Type": []string{"image/jpeg"}},
+ Body: io.NopCloser(bytes.NewReader(orig2)),
+ }, nil
+ case "/oslarge/003picSlot3.jpg":
+ return &http.Response{
+ StatusCode: http.StatusNotFound,
+ Header: http.Header{"Content-Type": []string{"text/plain"}},
+ Body: io.NopCloser(strings.NewReader("404")),
+ }, nil
+ default:
+ return &http.Response{
+ StatusCode: http.StatusNotFound,
+ Header: http.Header{"Content-Type": []string{"text/plain"}},
+ Body: io.NopCloser(strings.NewReader("unexpected")),
+ }, nil
+ }
+ })
+
+ mgr, libStore, _, dbPath, _ := setupDouyinDownloadTestEnv(t, http.NotFoundHandler(), 2)
+ cacheDir := filepath.Join(filepath.Dir(dbPath), "cache")
+ mgr.SetMediaTransportWrap(func(_ http.RoundTripper) http.RoundTripper {
+ return rt
+ })
+
+ itemDir := filepath.Join(cacheDir, "weibo", "100001", "posts", "5091000000000001")
+ imgDir := filepath.Join(itemDir, "images")
+ if err := os.MkdirAll(imgDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(imgDir, "01.jpg"), orig1, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(imgDir, "02.jpg"), orig2, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(imgDir, "03.jpg"), orig3, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(imgDir, "04.gif"), gif4, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ userNote := filepath.Join(itemDir, "notes.txt")
+ if err := os.WriteFile(userNote, []byte("keep-me"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ saved, err := libStore.SaveItem(itemDir, library.ItemMetadata{
+ Site: "weibo",
+ Kind: "dynamic",
+ ID: "5091000000000001",
+ RawID: "5091000000000001",
+ Title: "历史微博",
+ Text: "历史微博",
+ Status: "complete",
+ CacheStandardVersion: 2,
+ Author: library.ItemAuthor{Site: "weibo", UID: "100001", Name: "合成博主"},
+ AssetIDs: []string{"001picSlot1", "002picSlot2", "003picSlot3", "004picGif"},
+ Media: []library.MediaFile{
+ {Role: "image", Path: "images/01.jpg", Bytes: int64(len(orig1)), SHA256: sha256HexBytes(orig1), Width: 48, Height: 36},
+ {Role: "image", Path: "images/02.jpg", Bytes: int64(len(orig2)), SHA256: sha256HexBytes(orig2), Width: 40, Height: 30},
+ {Role: "image", Path: "images/03.jpg", Bytes: int64(len(orig3)), SHA256: sha256HexBytes(orig3), Width: 44, Height: 32},
+ {Role: "image", Path: "images/04.gif", Bytes: int64(len(gif4)), SHA256: sha256HexBytes(gif4), Width: 16, Height: 16},
+ },
+ NotePages: []library.NotePageRecord{
+ {Index: 1, Kind: "image", Image: "images/01.jpg", MediaID: "001picSlot1"},
+ {Index: 2, Kind: "image", Image: "images/02.jpg", MediaID: "002picSlot2"},
+ {Index: 3, Kind: "image", Image: "images/03.jpg", MediaID: "003picSlot3"},
+ {Index: 4, Kind: "image", Image: "images/04.gif", MediaID: "004picGif", GIF: true},
+ },
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // First test 429 abort: must NOT stamp WeiboCacheStandardVersion = 3!
+ mode429.Store(true)
+ _, err429 := mgr.BackfillWeiboNoWMCompanions(context.Background(), saved.ItemKey, site.WeiboMediaTransport("Mozilla/5.0 Test", false), nil, nil)
+ var sErr *site.Error
+ if !errors.As(err429, &sErr) || sErr.Kind != site.ErrKindRateLimited {
+ t.Fatalf("expected rate_limited error on HTTP 429, got %v", err429)
+ }
+ after429, ok, _ := libStore.GetItem(saved.ItemKey)
+ if !ok || after429.CacheStandardVersion >= library.WeiboCacheStandardVersion {
+ t.Fatalf("429 must NOT stamp WeiboCacheStandardVersion=3, got %d", after429.CacheStandardVersion)
+ }
+
+ // Now run normally.
+ mode429.Store(false)
+ mu.Lock()
+ hitPaths = nil
+ mu.Unlock()
+
+ res, err := mgr.BackfillWeiboNoWMCompanions(context.Background(), saved.ItemKey, site.WeiboMediaTransport("Mozilla/5.0 Test", false), nil, nil)
+ if err != nil {
+ t.Fatalf("BackfillWeiboNoWMCompanions: %v", err)
+ }
+ if res.AddedCompanions != 1 || !res.StampedStandard {
+ t.Fatalf("unexpected backfill result: %+v", res)
+ }
+ if sawCookie {
+ t.Fatal("CDN backfill must never send Cookie header")
+ }
+ if !sawRef {
+ t.Fatal("CDN backfill should send Referer: https://weibo.com/")
+ }
+ for _, p := range hitPaths {
+ if strings.Contains(p, "004picGif") {
+ t.Fatalf("GIF slot must be skipped, got request %q", p)
+ }
+ }
+
+ after, ok, err := libStore.GetItem(saved.ItemKey)
+ if err != nil || !ok {
+ t.Fatalf("GetItem after backfill: ok=%v err=%v", ok, err)
+ }
+ if after.CacheStandardVersion != library.WeiboCacheStandardVersion {
+ t.Fatalf("CacheStandardVersion = %d, want %d", after.CacheStandardVersion, library.WeiboCacheStandardVersion)
+ }
+ if library.WeiboNeedsNoWMBackfill(after, true) {
+ t.Fatal("item must no longer need backfill after completion")
+ }
+ if after.Status != "complete" || len(after.Missing) != 0 {
+ t.Fatalf("item must stay green complete: status=%q missing=%+v", after.Status, after.Missing)
+ }
+ if after.NotePages[0].NoWatermark != "images/01_nowm.jpg" {
+ t.Fatalf("slot 1 NoWatermark = %q, want images/01_nowm.jpg", after.NotePages[0].NoWatermark)
+ }
+ if after.NotePages[1].NoWatermark != "" || after.NotePages[2].NoWatermark != "" || after.NotePages[3].NoWatermark != "" {
+ t.Fatalf("slots 2/3/4 should not have companions: %+v", after.NotePages)
+ }
+ gotOrig1, _ := os.ReadFile(filepath.Join(itemDir, "images", "01.jpg"))
+ if !bytes.Equal(gotOrig1, orig1) {
+ t.Fatal("primary image 01.jpg must NOT be modified by companion backfill")
+ }
+ gotNoWM1, err := os.ReadFile(filepath.Join(itemDir, "images", "01_nowm.jpg"))
+ if err != nil || !bytes.Equal(gotNoWM1, nowm1) {
+ t.Fatalf("companion 01_nowm.jpg mismatch: err=%v len=%d want=%d", err, len(gotNoWM1), len(nowm1))
+ }
+ gotNote, err := os.ReadFile(userNote)
+ if err != nil || string(gotNote) != "keep-me" {
+ t.Fatalf("unregistered user file was touched: err=%v content=%q", err, string(gotNote))
+ }
+}
+
+func TestForceOverwriteAcrossSitesAndDegradedRefusal(t *testing.T) {
+ v1Img := makeWatermarkTestJPEG(t, 40, 30, color.RGBA{R: 210, G: 40, B: 40, A: 255})
+ v1NoWM := makeWatermarkTestJPEG(t, 28, 21, color.RGBA{R: 180, G: 80, B: 20, A: 255})
+ v2Img := makeWatermarkTestJPEG(t, 44, 34, color.RGBA{R: 30, G: 160, B: 220, A: 255})
+ v2NoWM := makeWatermarkTestJPEG(t, 30, 22, color.RGBA{R: 40, G: 200, B: 90, A: 255})
+ placeholderGIF := makeWatermarkTestPlaceholderGIF(t)
+
+ var (
+ mu sync.RWMutex
+ curImg = v1Img
+ curNoWM = v1NoWM
+ imgMode = "ok" // "ok" | "placeholder" | "404"
+ nowmMode = "ok"
+ )
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/img/main.jpg", func(w http.ResponseWriter, r *http.Request) {
+ mu.RLock()
+ mode := imgMode
+ data := curImg
+ mu.RUnlock()
+ switch mode {
+ case "404":
+ http.NotFound(w, r)
+ case "placeholder":
+ w.Header().Set("Content-Type", "image/gif")
+ _, _ = w.Write(placeholderGIF)
+ default:
+ w.Header().Set("Content-Type", "image/jpeg")
+ _, _ = w.Write(data)
+ }
+ })
+ mux.HandleFunc("/img/nowm.jpg", func(w http.ResponseWriter, r *http.Request) {
+ mu.RLock()
+ mode := nowmMode
+ data := curNoWM
+ mu.RUnlock()
+ if mode != "ok" {
+ http.NotFound(w, r)
+ return
+ }
+ w.Header().Set("Content-Type", "image/jpeg")
+ _, _ = w.Write(data)
+ })
+
+ mgr, libStore, srv := setupDownloadEnv(t, mux, 2)
+ weiboPlanner := newFakeGenericWorkPlanner(site.Weibo)
+ xPlanner := newFakeGenericWorkPlanner(site.X)
+ douyinPlanner := newFakeGenericWorkPlanner(site.Douyin)
+ mgr.RegisterWorkPlanner(weiboPlanner)
+ mgr.RegisterWorkPlanner(xPlanner)
+ mgr.RegisterWorkPlanner(douyinPlanner)
+ if err := mgr.Start(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ defer mgr.Stop()
+
+ ctx := context.Background()
+
+ // --- 1. Weibo post: normal recache preserves V1 primary, ForceOverwrite overwrites BOTH primary + companion, degraded refuses ---
+ wbTarget := "5092000000000001"
+ weiboPlanner.setPlan(wbTarget, func(_ context.Context, _ int) (WorkDownloadPlan, error) {
+ return WorkDownloadPlan{
+ Site: site.Weibo,
+ Kind: "dynamic",
+ TargetID: wbTarget,
+ AuthorUID: "1700000009",
+ AuthorName: "WBForce",
+ Title: "微博重下测试",
+ Desc: "微博重下测试",
+ Transport: localhostTransport(site.Weibo),
+ Pages: []PlannedNotePage{
+ {
+ Index: 1,
+ Kind: "image",
+ MediaID: "wb_same_pic",
+ Width: 40,
+ Height: 30,
+ ImageURLs: []string{srv.URL + "/img/main.jpg"},
+ WatermarkFreeURL: srv.URL + "/img/nowm.jpg",
+ },
+ },
+ }, nil
+ })
+ tk1, err := mgr.EnqueueWeiboWork(ctx, WeiboWorkEnqueueRequest{TargetID: wbTarget})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := mgr.WaitTasks(ctx, tk1.TaskID); err != nil {
+ t.Fatalf("Weibo V1 cache failed: %v", err)
+ }
+ wbItem, _, _ := libStore.GetItem("weibo:dynamic:" + wbTarget)
+ if wbItem.CacheStandardVersion != library.WeiboCacheStandardVersion {
+ t.Fatalf("Weibo dual-save CacheStandardVersion = %d, want %d", wbItem.CacheStandardVersion, library.WeiboCacheStandardVersion)
+ }
+
+ // Switch CDN payload to V2 with same MediaID.
+ mu.Lock()
+ curImg = v2Img
+ curNoWM = v2NoWM
+ mu.Unlock()
+
+ // Normal recache (without ForceOverwrite) reuses valid local primary image!
+ tkSafe, err := mgr.EnqueueWeiboWork(ctx, WeiboWorkEnqueueRequest{TargetID: wbTarget})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := mgr.WaitTasks(ctx, tkSafe.TaskID); err != nil {
+ t.Fatalf("Weibo safe recache failed: %v", err)
+ }
+ gotSafe, _ := os.ReadFile(filepath.Join(wbItem.ItemDir, "images", "01.jpg"))
+ if !bytes.Equal(gotSafe, v1Img) {
+ t.Fatal("normal safe recache unexpectedly replaced valid primary image")
+ }
+
+ // Explicit manual ForceOverwrite skips reuse and atomically overwrites BOTH primary + companion!
+ tkForce, err := mgr.EnqueueWeiboWork(WithForceOverwrite(ctx), WeiboWorkEnqueueRequest{TargetID: wbTarget, Source: "manual"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := mgr.WaitTasks(ctx, tkForce.TaskID); err != nil {
+ t.Fatalf("Weibo ForceOverwrite failed: %v", err)
+ }
+ gotForcedOrig, _ := os.ReadFile(filepath.Join(wbItem.ItemDir, "images", "01.jpg"))
+ gotForcedNoWM, _ := os.ReadFile(filepath.Join(wbItem.ItemDir, "images", "01_nowm.jpg"))
+ if !bytes.Equal(gotForcedOrig, v2Img) {
+ t.Fatal("ForceOverwrite did not overwrite Weibo primary image with fresh V2 bytes")
+ }
+ if !bytes.Equal(gotForcedNoWM, v2NoWM) {
+ t.Fatal("ForceOverwrite did not overwrite Weibo no-watermark companion with fresh V2 bytes")
+ }
+
+ // Now source returns Sina placeholder GIF -> ForceOverwrite MUST refuse and preserve local V2!
+ mu.Lock()
+ imgMode = "placeholder"
+ mu.Unlock()
+ tkDegraded, err := mgr.EnqueueWeiboWork(WithForceOverwrite(ctx), WeiboWorkEnqueueRequest{TargetID: wbTarget, Source: "manual"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if waitErr := mgr.WaitTasks(ctx, tkDegraded.TaskID); !errors.Is(waitErr, ErrRemoteDegradedRefused) {
+ t.Fatalf("expected ErrRemoteDegradedRefused on Weibo ForceOverwrite placeholder, got %v", waitErr)
+ }
+ stillOrig, _ := os.ReadFile(filepath.Join(wbItem.ItemDir, "images", "01.jpg"))
+ stillNoWM, _ := os.ReadFile(filepath.Join(wbItem.ItemDir, "images", "01_nowm.jpg"))
+ if !bytes.Equal(stillOrig, v2Img) || !bytes.Equal(stillNoWM, v2NoWM) {
+ t.Fatal("Weibo local files were damaged after ForceOverwrite degraded refusal!")
+ }
+
+ // --- 2. X post ForceOverwrite & 404 degraded refusal ---
+ mu.Lock()
+ imgMode = "ok"
+ curImg = v1Img
+ mu.Unlock()
+ xTarget := "1892000000000000001"
+ xPlanner.setPlan(xTarget, func(_ context.Context, _ int) (WorkDownloadPlan, error) {
+ return WorkDownloadPlan{
+ Site: site.X,
+ Kind: "dynamic",
+ TargetID: xTarget,
+ AuthorUID: "1900000009",
+ AuthorName: "XForce",
+ Title: "X重下测试",
+ Desc: "X重下测试",
+ Transport: localhostTransport(site.X),
+ Pages: []PlannedNotePage{
+ {Index: 1, Kind: "image", MediaID: "x_same_pic", Width: 40, Height: 30, ImageURLs: []string{srv.URL + "/img/main.jpg"}},
+ },
+ }, nil
+ })
+ tX1, err := mgr.EnqueueXWork(ctx, XWorkEnqueueRequest{TargetID: xTarget})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := mgr.WaitTasks(ctx, tX1.TaskID); err != nil {
+ t.Fatal(err)
+ }
+ xItem, _, _ := libStore.GetItem("x:dynamic:" + xTarget)
+
+ mu.Lock()
+ curImg = v2Img
+ mu.Unlock()
+ tXForce, err := mgr.EnqueueXWork(WithForceOverwrite(ctx), XWorkEnqueueRequest{TargetID: xTarget, Source: "manual"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := mgr.WaitTasks(ctx, tXForce.TaskID); err != nil {
+ t.Fatalf("X ForceOverwrite failed: %v", err)
+ }
+ gotX, _ := os.ReadFile(filepath.Join(xItem.ItemDir, "images", "01.jpg"))
+ if !bytes.Equal(gotX, v2Img) {
+ t.Fatal("X ForceOverwrite did not overwrite local image")
+ }
+ mu.Lock()
+ imgMode = "404"
+ mu.Unlock()
+ tX404, err := mgr.EnqueueXWork(WithForceOverwrite(ctx), XWorkEnqueueRequest{TargetID: xTarget, Source: "manual"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if waitErr := mgr.WaitTasks(ctx, tX404.TaskID); !errors.Is(waitErr, ErrRemoteDegradedRefused) {
+ t.Fatalf("expected ErrRemoteDegradedRefused on X ForceOverwrite 404, got %v", waitErr)
+ }
+ stillX, _ := os.ReadFile(filepath.Join(xItem.ItemDir, "images", "01.jpg"))
+ if !bytes.Equal(stillX, v2Img) {
+ t.Fatal("X local file was damaged on ForceOverwrite 404 refusal")
+ }
+
+ // --- 3. Douyin note ForceOverwrite & 404 degraded refusal ---
+ mu.Lock()
+ imgMode = "ok"
+ curImg = v1Img
+ mu.Unlock()
+ dyTarget := "7392000000000000001"
+ douyinPlanner.setPlan(dyTarget, func(_ context.Context, _ int) (WorkDownloadPlan, error) {
+ return WorkDownloadPlan{
+ Site: site.Douyin,
+ Kind: "note",
+ TargetID: dyTarget,
+ AuthorUID: "MS4wLjABAAAA_force",
+ AuthorName: "DYForce",
+ Title: "抖音图文重下",
+ Desc: "抖音图文重下",
+ Transport: localhostTransport(site.Douyin),
+ Pages: []PlannedNotePage{
+ {Index: 1, Kind: "image", MediaID: "dy_same_pic", Width: 40, Height: 30, ImageURLs: []string{srv.URL + "/img/main.jpg"}},
+ },
+ }, nil
+ })
+ tDY1, err := mgr.EnqueueDouyinWork(ctx, DouyinWorkEnqueueRequest{AwemeID: dyTarget})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := mgr.WaitTasks(ctx, tDY1.TaskID); err != nil {
+ t.Fatal(err)
+ }
+ dyItem, _, _ := libStore.GetItem("douyin:dynamic:" + dyTarget)
+
+ mu.Lock()
+ curImg = v2Img
+ mu.Unlock()
+ tDYForce, err := mgr.EnqueueDouyinWork(WithForceOverwrite(ctx), DouyinWorkEnqueueRequest{AwemeID: dyTarget, Source: "manual"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := mgr.WaitTasks(ctx, tDYForce.TaskID); err != nil {
+ t.Fatalf("Douyin ForceOverwrite failed: %v", err)
+ }
+ gotDY, _ := os.ReadFile(filepath.Join(dyItem.ItemDir, "images", "01.jpg"))
+ if !bytes.Equal(gotDY, v2Img) {
+ t.Fatal("Douyin ForceOverwrite did not overwrite local image")
+ }
+ mu.Lock()
+ imgMode = "404"
+ mu.Unlock()
+ tDY404, err := mgr.EnqueueDouyinWork(WithForceOverwrite(ctx), DouyinWorkEnqueueRequest{AwemeID: dyTarget, Source: "manual"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if waitErr := mgr.WaitTasks(ctx, tDY404.TaskID); !errors.Is(waitErr, ErrRemoteDegradedRefused) {
+ t.Fatalf("expected ErrRemoteDegradedRefused on Douyin ForceOverwrite 404, got %v", waitErr)
+ }
+ stillDY, _ := os.ReadFile(filepath.Join(dyItem.ItemDir, "images", "01.jpg"))
+ if !bytes.Equal(stillDY, v2Img) {
+ t.Fatal("Douyin local file was damaged on ForceOverwrite 404 refusal")
+ }
+
+ // Verify no .trace-stage-* or .trace-prev-* leftovers exist in any item dir.
+ for _, dir := range []string{wbItem.ItemDir, xItem.ItemDir, dyItem.ItemDir} {
+ entries, _ := os.ReadDir(dir)
+ for _, e := range entries {
+ if strings.HasPrefix(e.Name(), ".trace-") {
+ t.Fatalf("leftover temp dir %q in %s", e.Name(), dir)
+ }
+ }
+ }
+}
+
+func TestForceOverwriteBilibiliVideoAndDegradedRefusal(t *testing.T) {
+ v1Bytes, err := BuildSyntheticVideoM4S(60, 30)
+ if err != nil {
+ t.Fatal(err)
+ }
+ v2Bytes, err := BuildSyntheticVideoM4S(90, 30)
+ if err != nil {
+ t.Fatal(err)
+ }
+ a1Bytes, err := BuildSyntheticAudioM4S(94)
+ if err != nil {
+ t.Fatal(err)
+ }
+ a2Bytes, err := BuildSyntheticAudioM4S(141)
+ if err != nil {
+ t.Fatal(err)
+ }
+ coverV1 := makeWatermarkTestJPEG(t, 40, 30, color.RGBA{R: 200, G: 60, B: 60, A: 255})
+ coverV2 := makeWatermarkTestJPEG(t, 44, 34, color.RGBA{R: 40, G: 160, B: 220, A: 255})
+
+ var (
+ mu sync.RWMutex
+ phase = 1 // 1=V1, 2=V2 same cid fresh bytes, 3=degraded trial/empty
+ srvURL string
+ bvidTest = "BV17x411w7FR"
+ )
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/x/web-interface/wbi/view", func(w http.ResponseWriter, r *http.Request) {
+ mu.RLock()
+ ph := phase
+ mu.RUnlock()
+ dur := 2
+ if ph == 2 {
+ dur = 3
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": 0,
+ "data": map[string]any{
+ "bvid": bvidTest,
+ "aid": 170099,
+ "title": "B站强制重下视频",
+ "desc": "Desc",
+ "pic": srvURL + "/media/cover.jpg",
+ "pubdate": 1700000000,
+ "duration": dur,
+ "owner": map[string]any{"mid": 889, "name": "Creator889"},
+ "pages": []map[string]any{
+ {"cid": 1009, "page": 1, "part": "P1", "duration": dur, "dimension": map[string]any{"width": 16, "height": 16}},
+ },
+ },
+ })
+ })
+ mux.HandleFunc("/x/player/wbi/playurl", func(w http.ResponseWriter, r *http.Request) {
+ mu.RLock()
+ ph := phase
+ mu.RUnlock()
+ if ph == 3 {
+ // Return trial-only / degraded lower quality stream (360p) -> must be refused!
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": 0,
+ "data": map[string]any{
+ "quality": 16,
+ "accept_format": "dash",
+ "accept_quality": []int{16},
+ "is_preview": true,
+ "dash": map[string]any{
+ "duration": 1,
+ "video": []map[string]any{
+ {"id": 16, "baseUrl": srvURL + "/media/v1.m4s", "codecid": 7, "codecs": "avc1.42c00a", "width": 16, "height": 16, "frameRate": "30.0", "bandwidth": 100000},
+ },
+ "audio": []map[string]any{
+ {"id": 30216, "baseUrl": srvURL + "/media/a1.m4s", "codecs": "mp4a.40.2", "bandwidth": 64000},
+ },
+ },
+ },
+ })
+ return
+ }
+ vPath, aPath, dur := "/media/v1.m4s", "/media/a1.m4s", 2
+ if ph == 2 {
+ vPath, aPath, dur = "/media/v2.m4s", "/media/a2.m4s", 3
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": 0,
+ "data": map[string]any{
+ "quality": 80,
+ "accept_format": "dash",
+ "accept_quality": []int{80},
+ "dash": map[string]any{
+ "duration": dur,
+ "video": []map[string]any{
+ {"id": 80, "baseUrl": srvURL + vPath, "codecid": 7, "codecs": "avc1.42c00a", "width": 16, "height": 16, "frameRate": "30.0", "bandwidth": 500000},
+ },
+ "audio": []map[string]any{
+ {"id": 30280, "baseUrl": srvURL + aPath, "codecs": "mp4a.40.2", "bandwidth": 192000},
+ },
+ },
+ },
+ })
+ })
+ mux.HandleFunc("/x/v2/dm/web/seg.so", func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write(bilibili.EncodeDmSegMobileReply([]bilibili.DanmakuElem{
+ {ID: 1, IDStr: "1", Progress: 300, Mode: 1, Fontsize: 25, Color: 0xFFFFFF, Content: "dm"},
+ }))
+ })
+ mux.HandleFunc("/x/player/wbi/v2", func(w http.ResponseWriter, r *http.Request) {
+ cidInt, _ := strconv.ParseInt(r.URL.Query().Get("cid"), 10, 64)
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": 0,
+ "data": map[string]any{"bvid": bvidTest, "cid": cidInt, "subtitle": map[string]any{"subtitles": []any{}}},
+ })
+ })
+ mux.HandleFunc("/media/cover.jpg", func(w http.ResponseWriter, r *http.Request) {
+ mu.RLock()
+ ph := phase
+ mu.RUnlock()
+ w.Header().Set("Content-Type", "image/jpeg")
+ if ph == 2 {
+ _, _ = w.Write(coverV2)
+ } else {
+ _, _ = w.Write(coverV1)
+ }
+ })
+ mux.HandleFunc("/media/v1.m4s", func(w http.ResponseWriter, r *http.Request) {
+ http.ServeContent(w, r, "v1.m4s", time.Time{}, bytes.NewReader(v1Bytes))
+ })
+ mux.HandleFunc("/media/v2.m4s", func(w http.ResponseWriter, r *http.Request) {
+ http.ServeContent(w, r, "v2.m4s", time.Time{}, bytes.NewReader(v2Bytes))
+ })
+ mux.HandleFunc("/media/a1.m4s", func(w http.ResponseWriter, r *http.Request) {
+ http.ServeContent(w, r, "a1.m4s", time.Time{}, bytes.NewReader(a1Bytes))
+ })
+ mux.HandleFunc("/media/a2.m4s", func(w http.ResponseWriter, r *http.Request) {
+ http.ServeContent(w, r, "a2.m4s", time.Time{}, bytes.NewReader(a2Bytes))
+ })
+
+ mgr, libStore, srv := setupDownloadEnv(t, mux, 2)
+ srvURL = srv.URL
+ if err := mgr.Start(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ defer mgr.Stop()
+
+ ctx := context.Background()
+ tk1, err := mgr.EnqueueVideo(ctx, VideoEnqueueRequest{BVID: bvidTest, Source: "manual"})
+ if err != nil || len(tk1) == 0 {
+ t.Fatalf("EnqueueVideo V1: err=%v len=%d", err, len(tk1))
+ }
+ if err := mgr.WaitTasks(ctx, tk1[0].TaskID); err != nil {
+ t.Fatalf("Bilibili V1 failed: %v", err)
+ }
+ biliItem, ok, err := libStore.GetItem("bilibili:video:" + bvidTest)
+ if err != nil || !ok {
+ t.Fatalf("GetItem V1: ok=%v err=%v", ok, err)
+ }
+ p1Before, err := os.ReadFile(filepath.Join(biliItem.ItemDir, "P01.mp4"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ covBefore, _ := os.ReadFile(filepath.Join(biliItem.ItemDir, "cover.jpg"))
+ if !bytes.Equal(covBefore, coverV1) {
+ t.Fatal("expected V1 cover")
+ }
+
+ // Switch to V2 (same CID, fresh stream & cover bytes) and run manual ForceOverwrite!
+ mu.Lock()
+ phase = 2
+ mu.Unlock()
+ tkForce, err := mgr.EnqueueVideo(WithForceOverwrite(ctx), VideoEnqueueRequest{BVID: bvidTest, Source: "manual"})
+ if err != nil || len(tkForce) == 0 {
+ t.Fatalf("EnqueueVideo ForceOverwrite: err=%v len=%d", err, len(tkForce))
+ }
+ if err := mgr.WaitTasks(ctx, tkForce[0].TaskID); err != nil {
+ t.Fatalf("Bilibili ForceOverwrite failed: %v", err)
+ }
+ p1After, err := os.ReadFile(filepath.Join(biliItem.ItemDir, "P01.mp4"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ covAfter, _ := os.ReadFile(filepath.Join(biliItem.ItemDir, "cover.jpg"))
+ if bytes.Equal(p1After, p1Before) {
+ t.Fatal("Bilibili ForceOverwrite did not overwrite P01.mp4 with fresh V2 stream")
+ }
+ if !bytes.Equal(covAfter, coverV2) {
+ t.Fatal("Bilibili ForceOverwrite did not overwrite cover.jpg with fresh V2 cover")
+ }
+
+ // Switch to degraded preview-only stream -> ForceOverwrite MUST refuse & preserve V2!
+ mu.Lock()
+ phase = 3
+ mu.Unlock()
+ tkDeg, err := mgr.EnqueueVideo(WithForceOverwrite(ctx), VideoEnqueueRequest{BVID: bvidTest, Source: "manual"})
+ if err != nil || len(tkDeg) == 0 {
+ t.Fatalf("EnqueueVideo Degraded: err=%v len=%d", err, len(tkDeg))
+ }
+ if waitErr := mgr.WaitTasks(ctx, tkDeg[0].TaskID); !errors.Is(waitErr, ErrRemoteDegradedRefused) {
+ t.Fatalf("expected ErrRemoteDegradedRefused on degraded Bilibili preview stream, got %v", waitErr)
+ }
+ p1Still, _ := os.ReadFile(filepath.Join(biliItem.ItemDir, "P01.mp4"))
+ covStill, _ := os.ReadFile(filepath.Join(biliItem.ItemDir, "cover.jpg"))
+ if !bytes.Equal(p1Still, p1After) || !bytes.Equal(covStill, coverV2) {
+ t.Fatal("Bilibili V2 local files were damaged after ForceOverwrite degraded refusal!")
+ }
+}
+
+func TestBackfillWeiboMultiSlotMidAbortNoOrphanAndRetrySucceeds(t *testing.T) {
+ orig1 := makeWatermarkTestJPEG(t, 44, 34, color.RGBA{R: 200, G: 60, B: 40, A: 255})
+ orig2 := makeWatermarkTestJPEG(t, 40, 30, color.RGBA{R: 60, G: 180, B: 80, A: 255})
+ nowm1 := makeWatermarkTestJPEG(t, 30, 22, color.RGBA{R: 30, G: 130, B: 210, A: 255})
+ nowm2 := makeWatermarkTestJPEG(t, 28, 20, color.RGBA{R: 180, G: 90, B: 220, A: 255})
+
+ var slot2RateLimit atomic.Bool
+ slot2RateLimit.Store(true)
+
+ rt := roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ switch req.URL.Path {
+ case "/oslarge/001multiA.jpg":
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ ContentLength: int64(len(nowm1)),
+ Header: http.Header{"Content-Type": []string{"image/jpeg"}},
+ Body: io.NopCloser(bytes.NewReader(nowm1)),
+ }, nil
+ case "/oslarge/002multiB.jpg":
+ if slot2RateLimit.Load() {
+ return &http.Response{
+ StatusCode: http.StatusTooManyRequests,
+ Header: http.Header{"Content-Type": []string{"text/plain"}},
+ Body: io.NopCloser(strings.NewReader("rate limited")),
+ }, nil
+ }
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ ContentLength: int64(len(nowm2)),
+ Header: http.Header{"Content-Type": []string{"image/jpeg"}},
+ Body: io.NopCloser(bytes.NewReader(nowm2)),
+ }, nil
+ default:
+ return &http.Response{StatusCode: http.StatusNotFound, Body: io.NopCloser(strings.NewReader("404"))}, nil
+ }
+ })
+
+ mgr, libStore, _, dbPath, _ := setupDouyinDownloadTestEnv(t, http.NotFoundHandler(), 2)
+ cacheDir := filepath.Join(filepath.Dir(dbPath), "cache")
+ mgr.SetMediaTransportWrap(func(_ http.RoundTripper) http.RoundTripper { return rt })
+
+ itemDir := filepath.Join(cacheDir, "weibo", "100001", "posts", "5099000000000001")
+ imgDir := filepath.Join(itemDir, "images")
+ if err := os.MkdirAll(imgDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(imgDir, "01.jpg"), orig1, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(imgDir, "02.jpg"), orig2, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ saved, err := libStore.SaveItem(itemDir, library.ItemMetadata{
+ Site: "weibo",
+ Kind: "dynamic",
+ ID: "5099000000000001",
+ RawID: "5099000000000001",
+ Title: "多图补全防孤儿回归",
+ Text: "多图补全防孤儿回归",
+ Status: "complete",
+ CacheStandardVersion: 2,
+ Author: library.ItemAuthor{Site: "weibo", UID: "100001", Name: "合成博主"},
+ AssetIDs: []string{"001multiA", "002multiB"},
+ Media: []library.MediaFile{
+ {Role: "image", Path: "images/01.jpg", Bytes: int64(len(orig1)), SHA256: sha256HexBytes(orig1), Width: 44, Height: 34},
+ {Role: "image", Path: "images/02.jpg", Bytes: int64(len(orig2)), SHA256: sha256HexBytes(orig2), Width: 40, Height: 30},
+ },
+ NotePages: []library.NotePageRecord{
+ {Index: 1, Kind: "image", Image: "images/01.jpg", MediaID: "001multiA"},
+ {Index: 2, Kind: "image", Image: "images/02.jpg", MediaID: "002multiB"},
+ },
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // Run 1: slot 1 downloads OK, slot 2 hits 429 -> must NOT leave orphan 01_nowm.jpg in itemDir and must NOT stamp v3.
+ _, err1 := mgr.BackfillWeiboNoWMCompanions(context.Background(), saved.ItemKey, site.WeiboMediaTransport("Mozilla/5.0 Test", false), nil, nil)
+ var sErr *site.Error
+ if !errors.As(err1, &sErr) || sErr.Kind != site.ErrKindRateLimited {
+ t.Fatalf("expected rate_limited on slot 2 HTTP 429, got %v", err1)
+ }
+ if _, stErr := os.Lstat(filepath.Join(imgDir, "01_nowm.jpg")); !os.IsNotExist(stErr) {
+ t.Fatalf("slot 1 companion leaked as orphan file into itemDir on mid-item 429! lstat err=%v", stErr)
+ }
+ if entries, _ := os.ReadDir(itemDir); len(entries) > 0 {
+ for _, e := range entries {
+ if strings.HasPrefix(e.Name(), ".trace-") {
+ t.Fatalf("leftover stage dir %q after 429 abort", e.Name())
+ }
+ }
+ }
+ midItem, _, _ := libStore.GetItem(saved.ItemKey)
+ if midItem.CacheStandardVersion >= library.WeiboCacheStandardVersion {
+ t.Fatalf("must not stamp v3 after mid-item 429, got %d", midItem.CacheStandardVersion)
+ }
+
+ // Run 2: retry after 429 clears -> BOTH slot 1 & slot 2 commit cleanly and register in item.json!
+ slot2RateLimit.Store(false)
+ res2, err2 := mgr.BackfillWeiboNoWMCompanions(context.Background(), saved.ItemKey, site.WeiboMediaTransport("Mozilla/5.0 Test", false), nil, nil)
+ if err2 != nil {
+ t.Fatalf("retry BackfillWeiboNoWMCompanions failed: %v", err2)
+ }
+ if res2.AddedCompanions != 2 || !res2.StampedStandard {
+ t.Fatalf("retry expected 2 companions + v3 stamped, got %+v", res2)
+ }
+ after, ok, _ := libStore.GetItem(saved.ItemKey)
+ if !ok || after.CacheStandardVersion != library.WeiboCacheStandardVersion {
+ t.Fatalf("retry item standard version mismatch: %+v", after)
+ }
+ if after.NotePages[0].NoWatermark != "images/01_nowm.jpg" || after.NotePages[1].NoWatermark != "images/02_nowm.jpg" {
+ t.Fatalf("retry missing companion registration on slot 1 or 2: %+v", after.NotePages)
+ }
+
+ // Also verify OS storage error classification (*os.LinkError & *os.PathError -> site.ErrKindStorage).
+ linkErr := &os.LinkError{Op: "rename", Old: "a", New: "b", Err: os.ErrPermission}
+ if !isStorageError(linkErr) {
+ t.Fatal("isStorageError must recognize *os.LinkError")
+ }
+ wrapped := wrapWeiboBackfillStorageErr(linkErr)
+ if !site.IsKind(wrapped, site.ErrKindStorage) {
+ t.Fatalf("wrapWeiboBackfillStorageErr(*os.LinkError) = %v, want site.ErrKindStorage", wrapped)
+ }
+}
diff --git a/internal/download/image_guard_fallback.go b/internal/download/image_guard_fallback.go
index 7ce42e1..a79ce04 100644
--- a/internal/download/image_guard_fallback.go
+++ b/internal/download/image_guard_fallback.go
@@ -119,6 +119,9 @@ func (m *Manager) findExistingValidImageSlot(
width, height int,
isGIFSlot bool,
) (*library.MediaFile, bool) {
+ if t != nil && t.ForceOverwrite {
+ return nil, false
+ }
stem := trimKnownImageExt(relStem)
matchesStem := func(p string) bool {
if p == relStem || p == stem {
diff --git a/internal/download/manager.go b/internal/download/manager.go
index 75e03d2..5b8152e 100644
--- a/internal/download/manager.go
+++ b/internal/download/manager.go
@@ -82,6 +82,7 @@ type Task struct {
// writes it.
Via *library.ItemVia `json:"via,omitempty"`
ConflictResolution string `json:"-"` // explicit "keep_both" or "use_remote" during conflict resolution
+ ForceOverwrite bool `json:"-"` // explicit manual-only force redownload & atomic overwrite (DEC-079)
ProgressOwner *Task `json:"-"`
ProgressPrefix string `json:"-"`
Status string `json:"status"` // "queued", "running", "paused", "completed", "failed", "canceled", "partial"
@@ -152,6 +153,7 @@ type Manager struct {
initialPlans map[string]WorkDownloadPlan
conflictResolutions map[string]string
conflictPages map[string][]int
+ forceOverwrites map[string]bool
taskWaitMu sync.Mutex
taskWaitCh chan struct{}
taskOutcomes map[string]error
@@ -190,6 +192,7 @@ func NewManager(
initialPlans: make(map[string]WorkDownloadPlan),
conflictResolutions: make(map[string]string),
conflictPages: make(map[string][]int),
+ forceOverwrites: make(map[string]bool),
taskWaitCh: make(chan struct{}),
taskOutcomes: make(map[string]error),
wakeCh: make(chan struct{}, 1),
@@ -502,6 +505,7 @@ func (m *Manager) EnqueueVideo(ctx context.Context, req VideoEnqueueRequest) ([]
ctx = site.WithAutomaticRequests(ctx, "download")
}
mode := normalizeConflictResolution(ConflictResolutionFromContext(ctx))
+ forceOverwrite := effectiveForceOverwrite(ctx, source)
candKey := library.CanonicalItemKey("bilibili", "video", req.BVID)
detail := req.Detail
@@ -537,14 +541,14 @@ func (m *Manager) EnqueueVideo(ctx context.Context, req VideoEnqueueRequest) ([]
}
var planHint *WorkDownloadPlan
- if mode != "" {
- planHint = &WorkDownloadPlan{ConflictResolution: mode}
+ if mode != "" || forceOverwrite {
+ planHint = &WorkDownloadPlan{ConflictResolution: mode, ForceOverwrite: forceOverwrite}
}
- // When resolving a V1-vs-V2 conflict ("keep_both" or "use_remote"), enqueue a
- // single whole-video task so all target pages are staged, verified, archived
- // once, and swapped atomically together.
- if mode == ConflictResolveKeepBoth || mode == ConflictResolveUseRemote {
+ // When resolving a V1-vs-V2 conflict ("keep_both" or "use_remote") or manually
+ // forcing a full redownload (DEC-079), enqueue a single whole-video task so all
+ // target pages are staged, verified, and swapped atomically together.
+ if mode == ConflictResolveKeepBoth || mode == ConflictResolveUseRemote || forceOverwrite {
var selectedPages []int
var firstVP bilibili.VideoPage
for _, vp := range detail.Pages {
@@ -579,11 +583,15 @@ func (m *Manager) EnqueueVideo(ctx context.Context, req VideoEnqueueRequest) ([]
ItemKey: itemKey,
ItemDir: itemDir,
ConflictResolution: mode,
+ ForceOverwrite: forceOverwrite,
}, planHint)
if err != nil {
return nil, err
}
m.storeTaskResolutionAndPages(t.TaskID, mode, selectedPages)
+ if forceOverwrite {
+ m.storeTaskForceOverwrite(t.TaskID, true)
+ }
m.notifyWake()
return []Task{t}, nil
}
@@ -638,6 +646,7 @@ func (m *Manager) EnqueueDynamic(ctx context.Context, req DynamicEnqueueRequest)
ctx = site.WithAutomaticRequests(ctx, "download")
}
mode := normalizeConflictResolution(ConflictResolutionFromContext(ctx))
+ forceOverwrite := effectiveForceOverwrite(ctx, source)
candKey := library.CanonicalItemKey("bilibili", "dynamic", req.DynamicID)
dyn := req.Item
@@ -663,8 +672,8 @@ func (m *Manager) EnqueueDynamic(ctx context.Context, req DynamicEnqueueRequest)
}
var planHint *WorkDownloadPlan
- if mode != "" {
- planHint = &WorkDownloadPlan{ConflictResolution: mode}
+ if mode != "" || forceOverwrite {
+ planHint = &WorkDownloadPlan{ConflictResolution: mode, ForceOverwrite: forceOverwrite}
}
t, err := m.enqueueSingleTaskWithPlan(Task{
@@ -680,6 +689,7 @@ func (m *Manager) EnqueueDynamic(ctx context.Context, req DynamicEnqueueRequest)
CacheLinkedVideos: true,
ItemKey: library.CanonicalItemKey("bilibili", "dynamic", dyn.ID),
ConflictResolution: mode,
+ ForceOverwrite: forceOverwrite,
}, planHint)
if err != nil {
return Task{}, err
@@ -687,6 +697,9 @@ func (m *Manager) EnqueueDynamic(ctx context.Context, req DynamicEnqueueRequest)
if mode != "" {
m.storeTaskResolutionAndPages(t.TaskID, mode, nil)
}
+ if forceOverwrite {
+ m.storeTaskForceOverwrite(t.TaskID, true)
+ }
m.notifyWake()
return t, nil
}
@@ -1292,6 +1305,12 @@ func (m *Manager) runTask(ctx context.Context, t Task) {
t.ConflictResolution = mode
ctx = WithConflictResolution(ctx, mode)
}
+ if effectiveForceOverwrite(ctx, t.Source, t.ForceOverwrite, m.taskForceOverwrite(t.TaskID)) {
+ t.ForceOverwrite = true
+ ctx = WithForceOverwrite(ctx)
+ } else {
+ t.ForceOverwrite = false
+ }
var err error
switch site.ID(strings.ToLower(strings.TrimSpace(t.Site))) {
case site.Bilibili:
diff --git a/internal/download/replace.go b/internal/download/replace.go
index ebf8cb2..d6b75c7 100644
--- a/internal/download/replace.go
+++ b/internal/download/replace.go
@@ -295,7 +295,7 @@ func stampCacheStandardAndAssets(meta *library.ItemMetadata, editTs int64, editC
meta.AssetIDs = cleaned
}
}
- if meta.Status == "complete" && len(meta.Missing) == 0 {
+ if meta.Status == "complete" && len(meta.Missing) == 0 && meta.CacheStandardVersion < library.CurrentCacheStandardVersion {
meta.CacheStandardVersion = library.CurrentCacheStandardVersion
}
}
@@ -564,7 +564,7 @@ func (m *Manager) commitStagedItemSwap(
placedV2 = append(placedV2, vs.liveFull)
}
- if v2Meta.Status == "complete" && len(v2Meta.Missing) == 0 {
+ if v2Meta.Status == "complete" && len(v2Meta.Missing) == 0 && v2Meta.CacheStandardVersion < library.CurrentCacheStandardVersion {
v2Meta.CacheStandardVersion = library.CurrentCacheStandardVersion
}
if hook := testSwapHook; hook != nil {
@@ -917,6 +917,8 @@ func (m *Manager) executeBilibiliVideoConflictReplace(
expectedPages = append(expectedPages, vp.Page)
}
+ forceOverwrite := effectiveForceOverwrite(ctx, t.Source, t.ForceOverwrite)
+
// Stage cover if enabled.
if cfg.SaveCover && detail.Cover != "" {
coverRel := "cover" + guessImageExt(detail.Cover)
@@ -931,17 +933,19 @@ func (m *Manager) executeBilibiliVideoConflictReplace(
} else if isStopError(cErr) || isStorageError(cErr) || ctx.Err() != nil {
return cErr
} else {
- // Reuse verified local cover if present.
+ // Reuse verified local cover if present (never on manual ForceOverwrite).
reused := false
- for _, mf := range localMeta.Media {
- if mf.Role == "cover" && mediaIsValid(localMeta, mf.Path) {
- if cn, csha, rErr := copyVerifiedFileToStage(itemDir, mf.Path, mf.SHA256, stageDir); rErr == nil {
- cp := mf
- cp.Bytes, cp.SHA256 = cn, csha
- v2Media = append(v2Media, cp)
- reused = true
+ if !forceOverwrite {
+ for _, mf := range localMeta.Media {
+ if mf.Role == "cover" && mediaIsValid(localMeta, mf.Path) {
+ if cn, csha, rErr := copyVerifiedFileToStage(itemDir, mf.Path, mf.SHA256, stageDir); rErr == nil {
+ cp := mf
+ cp.Bytes, cp.SHA256 = cn, csha
+ v2Media = append(v2Media, cp)
+ reused = true
+ }
+ break
}
- break
}
}
if !reused {
@@ -1043,8 +1047,8 @@ func (m *Manager) executeBilibiliVideoConflictReplace(
partRec, partFiles, dlErr := m.stageSingleBilibiliPart(ctx, t, detail.BVID, vp, opts, cfg, stageDir, hasSameCID, lp, itemDir, localMeta)
if dlErr != nil {
// Invariant #3: on mixed V2 edits, if an unchanged CID fails remote download
- // because CDN expired or degraded, reuse the verified local V1 part!
- if hasSameCID && ctx.Err() == nil && !isStorageError(dlErr) {
+ // because CDN expired or degraded, reuse the verified local V1 part (never on manual ForceOverwrite).
+ if !forceOverwrite && hasSameCID && ctx.Err() == nil && !isStorageError(dlErr) {
reusedPart, reusedFiles, rErr := reuseLocalPartToStage(vp, lp)
if rErr == nil {
v2Parts = append(v2Parts, reusedPart)
@@ -1060,6 +1064,12 @@ func (m *Manager) executeBilibiliVideoConflictReplace(
}
v2Parts = append(v2Parts, partRec)
v2Media = append(v2Media, partFiles...)
+ if forceOverwrite && partRec.DanmakuState == "missing" {
+ v2Missing = append(v2Missing, library.MissingRecord{
+ Item: fmt.Sprintf("P%02d.danmaku.xml", vp.Page),
+ Reason: "弹幕下载失败",
+ })
+ }
}
status := "complete"
@@ -1373,7 +1383,7 @@ func (m *Manager) stageSingleBilibiliPart(
if mainAudio == nil {
return library.VideoPartRecord{}, nil, &bilibili.SiteError{Kind: bilibili.ErrKindUnavailable, Message: "缺少可合并普通音轨"}
}
- } else if hasSameCID && localPart.Audio.SavedAs != "" && localPart.Audio.SavedAs != localPart.File && mediaIsValid(localMeta, localPart.Audio.SavedAs) {
+ } else if hasSameCID && !effectiveForceOverwrite(ctx, parentTask.Source, parentTask.ForceOverwrite) && localPart.Audio.SavedAs != "" && localPart.Audio.SavedAs != localPart.File && mediaIsValid(localMeta, localPart.Audio.SavedAs) {
// Monotonic protection (Invariant #4): preserve verified local Hi-Res/Dolby sidecar audio!
sideRel := fmt.Sprintf("P%02d.audio-%d.m4a", page.Page, localPart.Audio.Quality)
var wantSHA string
@@ -1443,11 +1453,14 @@ func (m *Manager) stageSingleBilibiliPart(
})
m.setFileProgress(parentTask, "video", mp4Rel, "completed", summary.FileBytes, summary.FileBytes, 0)
- // Supplements: preserve monotonic danmaku/subtitles when same CID, otherwise fetch fresh for V2.
+ forceOverwrite := effectiveForceOverwrite(ctx, parentTask.Source, parentTask.ForceOverwrite)
+ reuseMonotonic := hasSameCID && !forceOverwrite
+
+ // Supplements: preserve monotonic danmaku/subtitles when same CID (unless manual ForceOverwrite), otherwise fetch fresh.
dmRel := fmt.Sprintf("P%02d.danmaku.xml", page.Page)
if !cfg.SaveDanmaku {
part.DanmakuState = "skipped"
- } else if hasSameCID && localPart.Danmaku != "" && mediaIsValid(localMeta, localPart.Danmaku) {
+ } else if reuseMonotonic && localPart.Danmaku != "" && mediaIsValid(localMeta, localPart.Danmaku) {
var wantSHA string
for _, mf := range localMeta.Media {
if mf.Path == localPart.Danmaku {
@@ -1472,14 +1485,14 @@ func (m *Manager) stageSingleBilibiliPart(
}
}
- if hasSameCID && len(localPart.Chapters) > 0 {
+ if reuseMonotonic && len(localPart.Chapters) > 0 {
part.Chapters = append([]library.VideoChapter(nil), localPart.Chapters...)
}
if !cfg.SaveSubtitles {
part.SubtitleState = "skipped"
} else {
var savedLangs []string
- if hasSameCID {
+ if reuseMonotonic {
for _, tr := range localPart.SubtitleTracks {
if mediaIsValid(localMeta, tr.VTT) && mediaIsValid(localMeta, tr.SRT) {
lang := library.SanitizeFileName(tr.Language)
diff --git a/internal/download/task_store.go b/internal/download/task_store.go
index 63b8c02..f863827 100644
--- a/internal/download/task_store.go
+++ b/internal/download/task_store.go
@@ -806,8 +806,15 @@ func isStopError(err error) bool {
}
func isStorageError(err error) bool {
+ if err == nil {
+ return false
+ }
var pathErr *os.PathError
- return errors.As(err, &pathErr) || bilibili.IsKind(err, "storage")
+ var linkErr *os.LinkError
+ return errors.As(err, &pathErr) ||
+ errors.As(err, &linkErr) ||
+ site.IsKind(err, site.ErrKindStorage) ||
+ bilibili.IsKind(err, "storage")
}
func targetQuality(quality string) int {
diff --git a/internal/download/video.go b/internal/download/video.go
index 43a9124..04bcbd4 100644
--- a/internal/download/video.go
+++ b/internal/download/video.go
@@ -64,6 +64,7 @@ func (m *Manager) cacheVideoPart(ctx context.Context, t *Task, upgrade bool) (re
storedMode, selectedPages := m.taskResolutionAndPages(t.TaskID)
mode := effectiveConflictResolution(ctx, t.ConflictResolution, storedMode)
+ forceOverwrite := effectiveForceOverwrite(ctx, t.Source, t.ForceOverwrite, m.taskForceOverwrite(t.TaskID))
preMeta, preExists, _ := m.lib.GetItem(t.TargetID)
if preExists && preMeta.ItemDir != "" {
@@ -101,8 +102,12 @@ func (m *Manager) cacheVideoPart(ctx context.Context, t *Task, upgrade bool) (re
}
if hasProtectedLocal {
- if mode == ConflictResolveKeepBoth || mode == ConflictResolveUseRemote {
- return m.executeBilibiliVideoConflictReplace(ctx, t, detail, meta, mode, selectedPages)
+ if mode == ConflictResolveKeepBoth || mode == ConflictResolveUseRemote || forceOverwrite {
+ effectiveMode := mode
+ if effectiveMode == "" {
+ effectiveMode = ConflictResolveUseRemote
+ }
+ return m.executeBilibiliVideoConflictReplace(ctx, t, detail, meta, effectiveMode, selectedPages)
}
notice, isConflict, degErr := classifyBilibiliVideoVsLocal(meta, detail, t)
if degErr != nil {
diff --git a/internal/download/weibo_backfill.go b/internal/download/weibo_backfill.go
new file mode 100644
index 0000000..65ac496
--- /dev/null
+++ b/internal/download/weibo_backfill.go
@@ -0,0 +1,456 @@
+package download
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "io"
+ "net/url"
+ "os"
+ "path"
+ "path/filepath"
+ "strings"
+
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/site"
+)
+
+// WeiboBackfillSlotOverride supplies freshly fetched pic_id and optional /oslarge/
+// URL for a specific 1-based DisplayIndex discovered via mymblog or statuses/show
+// during historical Weibo cache backfill (DEC-079).
+type WeiboBackfillSlotOverride struct {
+ DisplayIndex int
+ PicID string
+ WatermarkFreeURL string
+}
+
+// WeiboBackfillResult summarizes the result of backfilling one historical Weibo
+// item's watermark-free (/oslarge/) companion images and optional legacy links.
+type WeiboBackfillResult struct {
+ AddedCompanions int
+ SkippedSlots int
+ LinksCleaned bool
+ StampedStandard bool
+ Item library.ItemMetadata
+}
+
+// BackfillWeiboNoWMCompanions downloads missing watermark-free (/oslarge/) companion
+// images (images/NN_nowm.) for a cached Weibo post directly from sinaimg.cn
+// CDN with zero Weibo JSON API requests (DEC-079). Primary original images are NEVER
+// overwritten or deleted; companions whose SHA-256 equals the primary image or whose
+// /oslarge/ returns 404/410/403/placeholder are cleanly skipped, and the manifest is
+// stamped with library.WeiboCacheStandardVersion once every static slot is attempted.
+func (m *Manager) BackfillWeiboNoWMCompanions(
+ ctx context.Context,
+ itemKey string,
+ transport site.MediaTransportSpec,
+ overrides []WeiboBackfillSlotOverride,
+ cleanMetaFn func(library.ItemMetadata) (library.ItemMetadata, bool),
+) (WeiboBackfillResult, error) {
+ if m == nil || m.lib == nil {
+ return WeiboBackfillResult{}, fmt.Errorf("download manager not initialized")
+ }
+ cleanKey := strings.TrimSpace(itemKey)
+ if cleanKey == "" {
+ return WeiboBackfillResult{}, fmt.Errorf("empty item key")
+ }
+ rawID := cleanKey
+ if parts := strings.SplitN(cleanKey, ":", 3); len(parts) == 3 {
+ rawID = parts[2]
+ }
+ unlock, err := m.lockItem(ctx, "weibo:"+strings.ReplaceAll(rawID, ":", "_"))
+ if err != nil {
+ return WeiboBackfillResult{}, err
+ }
+ defer unlock()
+ if err := ctx.Err(); err != nil {
+ return WeiboBackfillResult{}, err
+ }
+
+ meta, ok, err := m.lib.GetItem(cleanKey)
+ if err != nil {
+ return WeiboBackfillResult{}, err
+ }
+ if !ok || strings.TrimSpace(meta.ItemDir) == "" {
+ return WeiboBackfillResult{}, nil
+ }
+ _ = library.RecoverInterruptedItemSwap(meta.ItemDir, meta)
+ meta, ok, err = m.lib.GetItem(cleanKey)
+ if err != nil || !ok || strings.TrimSpace(meta.ItemDir) == "" {
+ return WeiboBackfillResult{}, err
+ }
+ if !strings.EqualFold(meta.Site, string(site.Weibo)) || meta.Kind != "dynamic" || meta.IsArchivedSnapshot() {
+ return WeiboBackfillResult{Item: meta}, nil
+ }
+ if err := library.RejectDirectoryLinks(meta.ItemDir); err != nil {
+ return WeiboBackfillResult{}, err
+ }
+
+ var res WeiboBackfillResult
+ if cleanMetaFn != nil {
+ if cleaned, changed := cleanMetaFn(meta); changed {
+ meta = cleaned
+ res.LinksCleaned = true
+ }
+ }
+
+ overrideByIdx := make(map[int]WeiboBackfillSlotOverride, len(overrides))
+ for _, ov := range overrides {
+ if ov.DisplayIndex > 0 {
+ overrideByIdx[ov.DisplayIndex] = ov
+ }
+ }
+
+ // Apply any discovered pic_id overrides to NotePages/AssetIDs even for slots that
+ // already had companions or GIFs so future offline inspections know all pic_ids.
+ assetIDsUpdated := false
+ if len(meta.NotePages) > 0 && len(overrideByIdx) > 0 {
+ for i := range meta.NotePages {
+ idx := meta.NotePages[i].Index
+ if idx <= 0 {
+ idx = i + 1
+ }
+ if ov, has := overrideByIdx[idx]; has {
+ if tok := library.SanitizeMediaToken(ov.PicID); tok != "" && meta.NotePages[i].MediaID == "" {
+ meta.NotePages[i].MediaID = tok
+ assetIDsUpdated = true
+ }
+ }
+ }
+ if len(meta.AssetIDs) == 0 {
+ var ids []string
+ for _, pg := range meta.NotePages {
+ if tok := library.SanitizeMediaToken(pg.MediaID); tok != "" {
+ ids = append(ids, tok)
+ }
+ }
+ if len(ids) == len(meta.NotePages) && len(ids) > 0 {
+ meta.AssetIDs = ids
+ assetIDsUpdated = true
+ }
+ }
+ }
+
+ slots := library.WeiboStaticImageSlotsMissingNoWM(meta)
+ if len(slots) == 0 {
+ needSave := res.LinksCleaned || assetIDsUpdated
+ if meta.CacheStandardVersion < library.WeiboCacheStandardVersion {
+ meta.CacheStandardVersion = library.WeiboCacheStandardVersion
+ res.StampedStandard = true
+ needSave = true
+ }
+ if needSave {
+ saved, sErr := m.lib.SaveItemMetadataOnly(meta.ItemDir, meta)
+ if sErr != nil {
+ return res, wrapWeiboBackfillStorageErr(sErr)
+ }
+ res.Item = saved
+ return res, nil
+ }
+ res.Item = meta
+ return res, nil
+ }
+
+ normTransport := normalizeWeiboMediaTransport(transport)
+ spec := m.transportRangeSpec(normTransport, "image_nowm", false)
+
+ stageDir := filepath.Join(meta.ItemDir, library.SwapStageDirPrefix+newSwapToken())
+ if err := os.MkdirAll(stageDir, 0o700); err != nil {
+ return res, wrapWeiboBackfillStorageErr(err)
+ }
+ defer func() {
+ _ = library.RemoveTempSubdirSafe(meta.ItemDir, stageDir)
+ }()
+
+ stageTask := Task{
+ Site: string(site.Weibo),
+ Kind: "dynamic",
+ Source: "queue",
+ ItemKey: meta.ItemKey,
+ ItemDir: stageDir,
+ }
+
+ type stagedBackfillCompanion struct {
+ slot library.WeiboStaticImageSlot
+ media library.MediaFile
+ stagedFull string
+ finalFull string
+ }
+ var stagedCompanions []stagedBackfillCompanion
+
+ allSlotsAttempted := true
+ for _, slot := range slots {
+ if err := ctx.Err(); err != nil {
+ return res, err
+ }
+ picID := slot.PicID
+ var overrideURL string
+ if ov, has := overrideByIdx[slot.DisplayIndex]; has {
+ if tok := library.SanitizeMediaToken(ov.PicID); tok != "" {
+ picID = tok
+ }
+ overrideURL = strings.TrimSpace(ov.WatermarkFreeURL)
+ }
+ cands := buildWeiboOSLargeBackfillURLs(picID, slot.PrimaryPath, overrideURL)
+ if len(cands) == 0 {
+ allSlotsAttempted = false
+ continue
+ }
+
+ primarySHA := strings.TrimSpace(slot.PrimarySHA256)
+ if primarySHA == "" && strings.TrimSpace(slot.PrimaryPath) != "" {
+ if pFull, rErr := library.ResolveItemPath(meta.ItemDir, slot.PrimaryPath); rErr == nil {
+ if calc, hErr := sha256FileHex(pFull); hErr == nil {
+ primarySHA = calc
+ }
+ }
+ }
+
+ savedMedia, stagedFull, finalFull, dlErr := m.stageWeiboOSLargeBackfillSlot(ctx, &stageTask, stageDir, meta.ItemDir, spec, slot, primarySHA, cands)
+ if dlErr != nil {
+ if ctx.Err() != nil {
+ return res, ctx.Err()
+ }
+ if isSiteStopError(dlErr) || isStorageError(dlErr) {
+ // Risk control / rate limit / auth / disk error: stop immediately WITHOUT
+ // moving staged companions into itemDir or stamping v3.
+ return res, wrapWeiboBackfillStorageErr(dlErr)
+ }
+ res.SkippedSlots++
+ continue
+ }
+ if savedMedia == nil {
+ res.SkippedSlots++
+ continue
+ }
+ stagedCompanions = append(stagedCompanions, stagedBackfillCompanion{
+ slot: slot,
+ media: *savedMedia,
+ stagedFull: stagedFull,
+ finalFull: finalFull,
+ })
+ }
+
+ // Commit staged companions into itemDir ONLY after every slot finishes without
+ // stop/cancel/storage errors, rolling back all newly moved files on any failure.
+ var movedPaths []string
+ rollbackMoved := func() {
+ for _, p := range movedPaths {
+ _ = os.Remove(p)
+ }
+ }
+ for _, st := range stagedCompanions {
+ if err := os.MkdirAll(filepath.Dir(st.finalFull), 0o700); err != nil {
+ rollbackMoved()
+ return res, wrapWeiboBackfillStorageErr(err)
+ }
+ if err := library.RejectDirectoryLinks(filepath.Dir(st.finalFull)); err != nil {
+ rollbackMoved()
+ return res, wrapWeiboBackfillStorageErr(err)
+ }
+ // Never overwrite an existing unregistered user file (INV-09).
+ if _, stErr := os.Lstat(st.finalFull); stErr == nil {
+ res.SkippedSlots++
+ continue
+ } else if !os.IsNotExist(stErr) {
+ rollbackMoved()
+ return res, wrapWeiboBackfillStorageErr(stErr)
+ }
+ if err := os.Rename(st.stagedFull, st.finalFull); err != nil {
+ rollbackMoved()
+ return res, wrapWeiboBackfillStorageErr(err)
+ }
+ movedPaths = append(movedPaths, st.finalFull)
+ meta.Media = mergeMediaFiles(meta.Media, []library.MediaFile{st.media})
+ if st.slot.PageIdx >= 0 && st.slot.PageIdx < len(meta.NotePages) {
+ meta.NotePages[st.slot.PageIdx].NoWatermark = st.media.Path
+ }
+ res.AddedCompanions++
+ }
+
+ if allSlotsAttempted && meta.CacheStandardVersion < library.WeiboCacheStandardVersion {
+ meta.CacheStandardVersion = library.WeiboCacheStandardVersion
+ res.StampedStandard = true
+ }
+
+ if res.AddedCompanions > 0 || res.LinksCleaned || res.StampedStandard || assetIDsUpdated {
+ saved, sErr := m.lib.SaveItem(meta.ItemDir, meta)
+ if sErr != nil {
+ rollbackMoved()
+ return res, wrapWeiboBackfillStorageErr(sErr)
+ }
+ res.Item = saved
+ } else {
+ res.Item = meta
+ }
+ return res, nil
+}
+
+func wrapWeiboBackfillStorageErr(err error) error {
+ if err == nil {
+ return nil
+ }
+ if !isStorageError(err) || site.IsKind(err, site.ErrKindStorage) {
+ return err
+ }
+ return &site.Error{
+ Site: site.Weibo,
+ Kind: site.ErrKindStorage,
+ Message: "存储空间不足或写入失败",
+ Err: err,
+ }
+}
+
+func (m *Manager) stageWeiboOSLargeBackfillSlot(
+ ctx context.Context,
+ stageTask *Task,
+ stageDir, itemDir string,
+ spec rangeDownloadSpec,
+ slot library.WeiboStaticImageSlot,
+ primarySHA string,
+ candidates []string,
+) (*library.MediaFile, string, string, error) {
+ tempRel := slot.NoWMStem + imgSuffix
+ tempFull, err := library.ResolveItemPath(stageDir, tempRel)
+ if err != nil {
+ return nil, "", "", err
+ }
+ if err := os.MkdirAll(filepath.Dir(tempFull), 0o700); err != nil {
+ return nil, "", "", err
+ }
+ cleanupTemp := func() {
+ _ = os.Remove(tempFull)
+ _ = os.Remove(tempFull + ".part")
+ m.removeTempTaskProgress(stageTask, tempRel)
+ }
+ defer cleanupTemp()
+
+ for _, cand := range candidates {
+ if err := ctx.Err(); err != nil {
+ return nil, "", "", err
+ }
+ cleanupTemp()
+ n, sha, ct, dlErr := m.downloadRange(ctx, spec, []string{cand}, tempFull, stageTask)
+ if dlErr != nil {
+ if ctx.Err() != nil {
+ return nil, "", "", ctx.Err()
+ }
+ if isSiteStopError(dlErr) || isStorageError(dlErr) {
+ return nil, "", "", dlErr
+ }
+ continue
+ }
+ if site.LooksLikeExpiredPlaceholderImageFile(tempFull, cand, 0, 0, false) {
+ continue
+ }
+ ext, sErr := sniffImageExtension(tempFull, ct)
+ if sErr != nil {
+ continue
+ }
+ w, h, vErr := validateWeiboOSLargeImageFileWithSize(tempFull, ext)
+ if vErr != nil {
+ continue
+ }
+ // Deduplicate when /oslarge/ is byte-identical to the primary original image.
+ if primarySHA != "" && strings.EqualFold(sha, primarySHA) {
+ return nil, "", "", nil
+ }
+
+ finalRel := slot.NoWMStem + ext
+ finalFull, rErr := library.ResolveItemPath(itemDir, finalRel)
+ if rErr != nil {
+ return nil, "", "", rErr
+ }
+ // Pre-check INV-09 conflict without mutating itemDir yet.
+ if _, stErr := os.Lstat(finalFull); stErr == nil {
+ return nil, "", "", nil
+ } else if !os.IsNotExist(stErr) {
+ return nil, "", "", stErr
+ }
+
+ stagedFull, srErr := library.ResolveItemPath(stageDir, finalRel)
+ if srErr != nil {
+ return nil, "", "", srErr
+ }
+ if err := os.MkdirAll(filepath.Dir(stagedFull), 0o700); err != nil {
+ return nil, "", "", err
+ }
+ if err := os.Rename(tempFull, stagedFull); err != nil {
+ return nil, "", "", err
+ }
+ return &library.MediaFile{
+ Role: "image_nowm",
+ Path: finalRel,
+ FromOrigin: slot.FromOrigin,
+ Bytes: n,
+ SHA256: sha,
+ Width: w,
+ Height: h,
+ }, stagedFull, finalFull, nil
+ }
+ return nil, "", "", nil
+}
+
+func buildWeiboOSLargeBackfillURLs(picID, primaryPath, overrideURL string) []string {
+ var out []string
+ seen := make(map[string]bool, 8)
+ add := func(raw string) {
+ raw = strings.TrimSpace(raw)
+ if raw == "" || seen[raw] {
+ return
+ }
+ seen[raw] = true
+ out = append(out, raw)
+ }
+ altHosts := []string{"wx1.sinaimg.cn", "wx2.sinaimg.cn", "wx3.sinaimg.cn", "wx4.sinaimg.cn"}
+ if overrideURL != "" {
+ add(overrideURL)
+ if u, err := url.Parse(overrideURL); err == nil && strings.EqualFold(u.Scheme, "https") {
+ host := strings.ToLower(u.Hostname())
+ if host == "wx1.sinaimg.cn" || host == "wx2.sinaimg.cn" || host == "wx3.sinaimg.cn" || host == "wx4.sinaimg.cn" {
+ for _, h := range altHosts {
+ if h == host {
+ continue
+ }
+ cp := *u
+ cp.Host = h
+ add(cp.String())
+ }
+ }
+ }
+ }
+ cleanPicID := library.SanitizeMediaToken(picID)
+ if cleanPicID == "" {
+ return out
+ }
+ ext := strings.ToLower(path.Ext(strings.TrimSpace(primaryPath)))
+ exts := []string{".jpg"}
+ switch ext {
+ case ".png", ".webp":
+ exts = []string{ext, ".jpg"}
+ case ".jpeg":
+ exts = []string{".jpg", ".jpeg"}
+ case ".jpg", "":
+ exts = []string{".jpg"}
+ }
+ for _, e := range exts {
+ for _, h := range altHosts {
+ add("https://" + h + "/oslarge/" + cleanPicID + e)
+ }
+ }
+ return out
+}
+
+func sha256FileHex(fullPath string) (string, error) {
+ f, err := os.Open(fullPath)
+ if err != nil {
+ return "", err
+ }
+ defer f.Close()
+ h := sha256.New()
+ if _, err := io.Copy(h, f); err != nil {
+ return "", err
+ }
+ return hex.EncodeToString(h.Sum(nil)), nil
+}
diff --git a/internal/download/weibo_plan.go b/internal/download/weibo_plan.go
index 4c09fa3..3f81f95 100644
--- a/internal/download/weibo_plan.go
+++ b/internal/download/weibo_plan.go
@@ -86,10 +86,13 @@ func (m *Manager) EnqueueWeiboWork(ctx context.Context, req WeiboWorkEnqueueRequ
ctx = site.WithAutomaticRequests(ctx, "download")
}
var reqPlanMode string
+ var reqPlanForce bool
if req.Plan != nil {
reqPlanMode = req.Plan.ConflictResolution
+ reqPlanForce = req.Plan.ForceOverwrite
}
mode := effectiveConflictResolution(ctx, reqPlanMode)
+ forceOverwrite := effectiveForceOverwrite(ctx, source, reqPlanForce)
var plan WorkDownloadPlan
switch {
@@ -129,6 +132,7 @@ func (m *Manager) EnqueueWeiboWork(ctx context.Context, req WeiboWorkEnqueueRequ
if mode != "" {
plan.ConflictResolution = mode
}
+ plan.ForceOverwrite = forceOverwrite
itemKind, rawID, itemKey, plannerTarget, err := resolveWeiboIdentity(req.Kind, plan.ItemKey, plan.TargetID)
if err != nil {
@@ -191,6 +195,7 @@ func (m *Manager) EnqueueWeiboWork(ctx context.Context, req WeiboWorkEnqueueRequ
ItemDir: itemDir,
Via: via,
ConflictResolution: mode,
+ ForceOverwrite: forceOverwrite,
}, &plan)
if err != nil {
return Task{}, err
@@ -198,6 +203,9 @@ func (m *Manager) EnqueueWeiboWork(ctx context.Context, req WeiboWorkEnqueueRequ
if mode != "" {
m.storeTaskResolutionAndPages(t.TaskID, mode, nil)
}
+ if forceOverwrite {
+ m.storeTaskForceOverwrite(t.TaskID, true)
+ }
m.notifyWake()
return t, nil
@@ -240,6 +248,9 @@ func (m *Manager) consumeInitialOrFetchWeiboPlan(ctx context.Context, taskID, ta
if hasInitial && initial.ConflictResolution != "" && plan.ConflictResolution == "" {
plan.ConflictResolution = initial.ConflictResolution
}
+ if hasInitial && initial.ForceOverwrite {
+ plan.ForceOverwrite = true
+ }
plan.Site = site.Weibo
plan.Transport = normalizeWeiboMediaTransport(plan.Transport)
return plan, planner, nil
@@ -266,6 +277,12 @@ func (m *Manager) executeWeiboTask(ctx context.Context, t *Task) error {
mode = effectiveConflictResolution(ctx, t.ConflictResolution, storedMode, plan.ConflictResolution)
plan.ConflictResolution = mode
t.ConflictResolution = mode
+ forceOverwrite := effectiveForceOverwrite(ctx, t.Source, t.ForceOverwrite, m.taskForceOverwrite(t.TaskID), plan.ForceOverwrite)
+ plan.ForceOverwrite = forceOverwrite
+ t.ForceOverwrite = forceOverwrite
+ if forceOverwrite {
+ ctx = WithForceOverwrite(ctx)
+ }
normUID, err := site.NormalizeUID(site.Weibo, firstNonEmptyStr(plan.AuthorUID, t.AuthorUID))
if err != nil {
return &site.Error{
@@ -372,12 +389,13 @@ func (m *Manager) executeWeiboSingleVideoTask(
hasProtectedLocal := exists && localHasProtectedContent(previous)
mode := effectiveConflictResolution(ctx, t.ConflictResolution, plan.ConflictResolution)
+ forceOverwrite := effectiveForceOverwrite(ctx, t.Source, t.ForceOverwrite, plan.ForceOverwrite)
resolvedKey := firstNonEmptyStr(plan.ItemKey, t.ItemKey, library.CanonicalItemKey(string(site.Weibo), itemKind, rawID))
isConflict := false
if hasProtectedLocal {
// Monotonic Origin protection before degraded check: if local had valid fromOrigin video
- // and remote origin vanished on a safe re-check (mode == ""), preserve local without error.
- if mode == "" && previous.Origin != nil && !previous.Origin.Unavailable && plan.OriginUnavailable && mediaIsValid(previous, "video.mp4") {
+ // and remote origin vanished on a safe re-check (mode == "" && !forceOverwrite), preserve local without error.
+ if mode == "" && !forceOverwrite && previous.Origin != nil && !previous.Origin.Unavailable && plan.OriginUnavailable && mediaIsValid(previous, "video.mp4") {
// Safe monotonic preservation below.
} else {
notice, conflict, degErr := classifyWorkPlanVsLocal(previous, plan, resolvedKey, rawID, t)
@@ -385,17 +403,20 @@ func (m *Manager) executeWeiboSingleVideoTask(
return degErr
}
isConflict = conflict
- if isConflict && mode != ConflictResolveKeepBoth && mode != ConflictResolveUseRemote {
+ if isConflict && !forceOverwrite && mode != ConflictResolveKeepBoth && mode != ConflictResolveUseRemote {
m.emitConflict(notice)
return ErrConflictDetected
}
+ if forceOverwrite && mode == "" {
+ mode = ConflictResolveUseRemote
+ }
}
}
editAdvanced := (plan.EditCount > 0 && plan.EditCount > previous.EditCount) ||
(plan.EditTs > 0 && previous.EditTs > 0 && plan.EditTs > previous.EditTs)
desc := plan.Desc
- if hasProtectedLocal && !isConflict {
+ if hasProtectedLocal && !isConflict && !forceOverwrite {
desc = preserveMonotonicText(firstNonEmptyStr(previous.Text, previous.Desc), desc, editAdvanced)
}
title := firstNonEmptyStr(plan.Title, desc, t.Title, "微博视频 "+rawID)
@@ -439,7 +460,7 @@ func (m *Manager) executeWeiboSingleVideoTask(
var v2Media []library.MediaFile
var v2Missing []library.MissingRecord
reusedCover := false
- if !isConflict {
+ if !isConflict && !forceOverwrite {
for _, mf := range previous.Media {
if mf.Role == "cover" && mediaIsValid(previous, mf.Path) {
if copied, rErr := copyLocalMediaToStageAs(previous, mf.Path, mf.Path, "cover", stageDir); rErr == nil {
@@ -468,7 +489,7 @@ func (m *Manager) executeWeiboSingleVideoTask(
sameMediaID := previous.DouyinVideo != nil && previous.DouyinVideo.MediaID != "" && plan.MediaID != "" &&
library.SanitizeMediaToken(previous.DouyinVideo.MediaID) == library.SanitizeMediaToken(plan.MediaID)
- if !isConflict && (!planUpgradesSingleVideo(previous, plan) || len(plan.VideoURLs) == 0) && mediaIsValid(previous, videoRel) {
+ if !isConflict && !forceOverwrite && (!planUpgradesSingleVideo(previous, plan) || len(plan.VideoURLs) == 0) && mediaIsValid(previous, videoRel) {
copied, cErr := copyLocalMediaToStageAs(previous, videoRel, videoRel, "video", stageDir)
if cErr != nil {
return cErr
@@ -490,7 +511,7 @@ func (m *Manager) executeWeiboSingleVideoTask(
})
vidMedia, vErr := m.cacheWeiboSingleMP4(ctx, &stageSub, stageDir, previous, false, "video", videoRel, plan.VideoURLs, plan.DurationSec, plan.Width, plan.Height, plan.Transport, refreshVideoURLs, false)
if vErr != nil {
- if (!isConflict || sameMediaID) && mediaIsValid(previous, videoRel) && ctx.Err() == nil && !isStorageError(vErr) {
+ if !forceOverwrite && (!isConflict || sameMediaID) && mediaIsValid(previous, videoRel) && ctx.Err() == nil && !isStorageError(vErr) {
if copied, cErr := copyLocalMediaToStageAs(previous, videoRel, videoRel, "video", stageDir); cErr == nil {
v2Media = append(v2Media, *copied)
if previous.DouyinVideo != nil {
@@ -760,6 +781,9 @@ func (m *Manager) executeWeiboSingleVideoTask(
t.ErrorMessage = summarizeMissingReasons(meta.Missing)
}
stampCacheStandardAndAssets(&meta, plan.EditTs, plan.EditCount, buildPlanAssetIDs(plan))
+ if meta.Status == "complete" && len(meta.Missing) == 0 && weiboPlanRanNoWMStandard(plan) {
+ meta.CacheStandardVersion = library.WeiboCacheStandardVersion
+ }
saved, err := m.lib.SaveItem(itemDir, meta)
if err != nil {
return err
@@ -787,13 +811,14 @@ func (m *Manager) executeWeiboPostTask(
hasProtectedLocal := exists && localHasProtectedContent(previous)
mode := effectiveConflictResolution(ctx, t.ConflictResolution, plan.ConflictResolution)
+ forceOverwrite := effectiveForceOverwrite(ctx, t.Source, t.ForceOverwrite, plan.ForceOverwrite)
resolvedKey := firstNonEmptyStr(plan.ItemKey, t.ItemKey, library.CanonicalItemKey(string(site.Weibo), itemKind, rawID))
isConflict := false
preserveOriginFiles := false
if hasProtectedLocal {
// Monotonic Origin protection (Invariant #4): if a forwarded post's Origin later
- // became Unavailable while local V1 has valid Origin + media, keep local Origin on mode==""!
- if mode == "" && previous.Origin != nil && !previous.Origin.Unavailable && plan.OriginUnavailable {
+ // became Unavailable while local V1 has valid Origin + media, keep local Origin on mode=="" && !forceOverwrite!
+ if mode == "" && !forceOverwrite && previous.Origin != nil && !previous.Origin.Unavailable && plan.OriginUnavailable {
preserveOriginFiles = true
} else {
notice, conflict, degErr := classifyWorkPlanVsLocal(previous, plan, resolvedKey, rawID, t)
@@ -801,17 +826,20 @@ func (m *Manager) executeWeiboPostTask(
return degErr
}
isConflict = conflict
- if isConflict && mode != ConflictResolveKeepBoth && mode != ConflictResolveUseRemote {
+ if isConflict && !forceOverwrite && mode != ConflictResolveKeepBoth && mode != ConflictResolveUseRemote {
m.emitConflict(notice)
return ErrConflictDetected
}
+ if forceOverwrite && mode == "" {
+ mode = ConflictResolveUseRemote
+ }
}
}
editAdvanced := (plan.EditCount > 0 && plan.EditCount > previous.EditCount) ||
(plan.EditTs > 0 && previous.EditTs > 0 && plan.EditTs > previous.EditTs)
desc := plan.Desc
- if hasProtectedLocal && !isConflict {
+ if hasProtectedLocal && !isConflict && !forceOverwrite {
desc = preserveMonotonicText(firstNonEmptyStr(previous.Text, previous.Desc), desc, editAdvanced)
}
title := firstNonEmptyStr(plan.Title, desc, t.Title, "微博 "+rawID)
@@ -918,7 +946,7 @@ func (m *Manager) executeWeiboPostTask(
if cfg.SaveCover && len(plan.CoverURLs) > 0 && len(plan.Pages) == 0 {
reusedCover := false
- if hasProtectedLocal && !isConflict {
+ if hasProtectedLocal && !isConflict && !forceOverwrite {
for _, mf := range previous.Media {
if mf.Role == "cover" && mediaIsValid(previous, mf.Path) {
if copied, rErr := copyLocalMediaToStageAs(previous, mf.Path, mf.Path, "cover", workDir); rErr == nil {
@@ -956,7 +984,7 @@ func (m *Manager) executeWeiboPostTask(
// Monotonic fromOrigin media preservation when remote Origin became unavailable!
var preservedVideo *library.DouyinVideoInfo
- if hasProtectedLocal && !isConflict && preserveOriginFiles && len(plan.Pages) == 0 {
+ if hasProtectedLocal && !isConflict && !forceOverwrite && preserveOriginFiles && len(plan.Pages) == 0 {
for _, mf := range previous.Media {
if mf.FromOrigin && mediaIsValid(previous, mf.Path) {
if copied, rErr := copyLocalMediaToStageAs(previous, mf.Path, mf.Path, mf.Role, workDir); rErr == nil {
@@ -984,6 +1012,9 @@ func (m *Manager) executeWeiboPostTask(
prefix := fmt.Sprintf("images/%02d", pageIdx)
cleanPageMediaID := library.SanitizeMediaToken(page.MediaID)
reusableLP, canReuseLocal := findReusableLocalPage(previous, page, pageIdx, isConflict)
+ if forceOverwrite {
+ canReuseLocal = false
+ }
pageKind := strings.ToLower(strings.TrimSpace(page.Kind))
if pageKind == "" {
if len(page.VideoURLs) > 0 {
@@ -1018,7 +1049,7 @@ func (m *Manager) executeWeiboPostTask(
if isSiteStopError(imgErr) || isStorageError(imgErr) || ctx.Err() != nil {
return imgErr
}
- if hasProtectedLocal && isConflict && isDegradedSiteError(imgErr) {
+ if hasProtectedLocal && (isConflict || forceOverwrite) && isDegradedSiteError(imgErr) {
return wrapRemoteDegraded(imgErr)
}
reason := fmt.Sprintf("第 %02d 张动图下载失败 (%s)", pageIdx, classifyDownloadError(imgErr))
@@ -1079,7 +1110,7 @@ func (m *Manager) executeWeiboPostTask(
if isSiteStopError(imgErr) || isStorageError(imgErr) || ctx.Err() != nil {
return imgErr
}
- if hasProtectedLocal && (isConflict || isWeiboPlaceholderError(imgErr)) && isDegradedSiteError(imgErr) {
+ if hasProtectedLocal && (isConflict || forceOverwrite || isWeiboPlaceholderError(imgErr)) && isDegradedSiteError(imgErr) {
return wrapRemoteDegraded(imgErr)
}
reason := fmt.Sprintf("第 %02d 张图片下载失败 (%s)", pageIdx, classifyDownloadError(imgErr))
@@ -1138,7 +1169,7 @@ func (m *Manager) executeWeiboPostTask(
if isSiteStopError(imgErr) || isStorageError(imgErr) || ctx.Err() != nil {
return imgErr
}
- if hasProtectedLocal && (isConflict || isWeiboPlaceholderError(imgErr)) && isDegradedSiteError(imgErr) {
+ if hasProtectedLocal && (isConflict || forceOverwrite || isWeiboPlaceholderError(imgErr)) && isDegradedSiteError(imgErr) {
return wrapRemoteDegraded(imgErr)
}
reason := fmt.Sprintf("第 %02d 张实况静帧下载失败 (%s)", pageIdx, classifyDownloadError(imgErr))
@@ -1288,7 +1319,7 @@ func (m *Manager) executeWeiboPostTask(
if isSiteStopError(vErr) || isStorageError(vErr) || ctx.Err() != nil {
return vErr
}
- if hasProtectedLocal && isConflict && isDegradedSiteError(vErr) {
+ if hasProtectedLocal && (isConflict || forceOverwrite) && isDegradedSiteError(vErr) {
return wrapRemoteDegraded(vErr)
}
reason := fmt.Sprintf("第 %02d 项视频下载失败 (%s)", pageIdx, classifyDownloadError(vErr))
@@ -1356,7 +1387,7 @@ func (m *Manager) executeWeiboPostTask(
}
}
- if hasProtectedLocal && isConflict && len(partialErrors) > 0 {
+ if hasProtectedLocal && (isConflict || forceOverwrite) && len(partialErrors) > 0 {
return wrapRemoteDegradedMsg(fmt.Sprintf("新版部分媒体已失效,已保留本地原文件 (%s)", strings.Join(partialErrors, "; ")))
}
@@ -1367,7 +1398,7 @@ func (m *Manager) executeWeiboPostTask(
t.ErrorMessage = summarizeMissingReasons(missing)
}
- mediaFiles, notePages = preserveValidPreviousImagesForStage(itemDir, workDir, previous, exists && !isConflict, mediaFiles, notePages)
+ mediaFiles, notePages = preserveValidPreviousImagesForStage(itemDir, workDir, previous, exists && !isConflict && !forceOverwrite, mediaFiles, notePages)
meta := library.ItemMetadata{
Version: 1,
@@ -1400,6 +1431,9 @@ func (m *Manager) executeWeiboPostTask(
Links: buildWeiboItemLinks(plan.Links, previous.Links),
}
stampCacheStandardAndAssets(&meta, plan.EditTs, plan.EditCount, buildPlanAssetIDs(plan))
+ if meta.Status == "complete" && len(meta.Missing) == 0 && weiboPlanRanNoWMStandard(plan) {
+ meta.CacheStandardVersion = library.WeiboCacheStandardVersion
+ }
if hasProtectedLocal {
saved, sErr := m.commitStagedItemSwap(itemDir, previous, true, meta, workDir, mode)
@@ -1813,11 +1847,12 @@ func (m *Manager) cacheWeiboWatermarkFreeCompanion(
}
inSwapStage := isSwapStageDir(workDir)
- if hasProtectedLocal && !isConflict && canReuseLocal {
+ forceOverwrite := effectiveForceOverwrite(ctx, workTask.Source, workTask.ForceOverwrite)
+ if !forceOverwrite && hasProtectedLocal && !isConflict && canReuseLocal {
if reused := tryCopyPrevNoWM(); reused != nil {
return reused, nil
}
- } else if !inSwapStage {
+ } else if !forceOverwrite && !inSwapStage {
if kept, ok := m.findExistingValidImageSlot(workTask, workDir, previous, inPlaceExists, "image_nowm", nowmStem, page.WatermarkFreeURL, 0, 0, false); ok {
if primaryMedia.SHA256 == "" || !strings.EqualFold(kept.SHA256, primaryMedia.SHA256) {
m.setFileProgress(workTask, "image_nowm", kept.Path, "completed", kept.Bytes, kept.Bytes, 0)
@@ -1856,7 +1891,7 @@ func (m *Manager) cacheWeiboWatermarkFreeCompanion(
m.removeTempTaskProgress(workTask, tempRel)
}
fallbackPrevOrSkip := func() (*library.MediaFile, error) {
- if hasProtectedLocal && canReuseLocal {
+ if !forceOverwrite && hasProtectedLocal && canReuseLocal {
if reused := tryCopyPrevNoWM(); reused != nil {
return reused, nil
}
@@ -1937,6 +1972,22 @@ func (m *Manager) cacheWeiboWatermarkFreeCompanion(
}, nil
}
+// weiboPlanRanNoWMStandard reports whether this Weibo post plan includes at least
+// one static (non-GIF, non-video) page whose /oslarge/ watermark-free companion
+// URL was evaluated during this cache run (DEC-079).
+func weiboPlanRanNoWMStandard(plan WorkDownloadPlan) bool {
+ for _, p := range plan.Pages {
+ k := strings.ToLower(strings.TrimSpace(p.Kind))
+ if k == "gif" || k == "video" {
+ continue
+ }
+ if strings.TrimSpace(p.WatermarkFreeURL) != "" {
+ return true
+ }
+ }
+ return false
+}
+
func (m *Manager) cacheWeiboLivePhotoClip(
ctx context.Context,
t *Task,
diff --git a/internal/download/x_plan.go b/internal/download/x_plan.go
index 4dd32fa..ec62e7f 100644
--- a/internal/download/x_plan.go
+++ b/internal/download/x_plan.go
@@ -62,10 +62,13 @@ func (m *Manager) EnqueueXWork(ctx context.Context, req XWorkEnqueueRequest) (Ta
ctx = site.WithAutomaticRequests(ctx, "download")
}
var reqPlanMode string
+ var reqPlanForce bool
if req.Plan != nil {
reqPlanMode = req.Plan.ConflictResolution
+ reqPlanForce = req.Plan.ForceOverwrite
}
mode := effectiveConflictResolution(ctx, reqPlanMode)
+ forceOverwrite := effectiveForceOverwrite(ctx, source, reqPlanForce)
var plan WorkDownloadPlan
switch {
@@ -105,6 +108,7 @@ func (m *Manager) EnqueueXWork(ctx context.Context, req XWorkEnqueueRequest) (Ta
if mode != "" {
plan.ConflictResolution = mode
}
+ plan.ForceOverwrite = forceOverwrite
itemKind, rawID, itemKey, plannerTarget, err := resolveXIdentity(plan.ItemKey, plan.TargetID)
if err != nil {
@@ -167,6 +171,7 @@ func (m *Manager) EnqueueXWork(ctx context.Context, req XWorkEnqueueRequest) (Ta
ItemDir: itemDir,
Via: via,
ConflictResolution: mode,
+ ForceOverwrite: forceOverwrite,
}, &plan)
if err != nil {
return Task{}, err
@@ -174,6 +179,9 @@ func (m *Manager) EnqueueXWork(ctx context.Context, req XWorkEnqueueRequest) (Ta
if mode != "" {
m.storeTaskResolutionAndPages(t.TaskID, mode, nil)
}
+ if forceOverwrite {
+ m.storeTaskForceOverwrite(t.TaskID, true)
+ }
m.notifyWake()
return t, nil
@@ -216,6 +224,9 @@ func (m *Manager) consumeInitialOrFetchXPlan(ctx context.Context, taskID, target
if hasInitial && initial.ConflictResolution != "" && plan.ConflictResolution == "" {
plan.ConflictResolution = initial.ConflictResolution
}
+ if hasInitial && initial.ForceOverwrite {
+ plan.ForceOverwrite = true
+ }
plan.Site = site.X
plan.Transport = normalizeXMediaTransport(plan.Transport)
return plan, planner, nil
@@ -241,6 +252,12 @@ func (m *Manager) executeXTask(ctx context.Context, t *Task) error {
mode = effectiveConflictResolution(ctx, t.ConflictResolution, storedMode, plan.ConflictResolution)
plan.ConflictResolution = mode
t.ConflictResolution = mode
+ forceOverwrite := effectiveForceOverwrite(ctx, t.Source, t.ForceOverwrite, m.taskForceOverwrite(t.TaskID), plan.ForceOverwrite)
+ plan.ForceOverwrite = forceOverwrite
+ t.ForceOverwrite = forceOverwrite
+ if forceOverwrite {
+ ctx = WithForceOverwrite(ctx)
+ }
normUID, err := site.NormalizeUID(site.X, firstNonEmptyStr(plan.AuthorUID, t.AuthorUID))
if err != nil {
@@ -347,12 +364,13 @@ func (m *Manager) executeXSingleVideoTask(
hasProtectedLocal := exists && localHasProtectedContent(previous)
mode := effectiveConflictResolution(ctx, t.ConflictResolution, plan.ConflictResolution)
+ forceOverwrite := effectiveForceOverwrite(ctx, t.Source, t.ForceOverwrite, plan.ForceOverwrite)
resolvedKey := firstNonEmptyStr(plan.ItemKey, t.ItemKey, library.CanonicalItemKey(string(site.X), "dynamic", rawID))
isConflict := false
if hasProtectedLocal {
// Monotonic Origin protection before degraded check: if local had valid fromOrigin video
- // and remote origin vanished on a safe re-check (mode == ""), preserve local without error.
- if mode == "" && previous.Origin != nil && !previous.Origin.Unavailable && plan.OriginUnavailable && mediaIsValid(previous, "video.mp4") {
+ // and remote origin vanished on a safe re-check (mode == "" && !forceOverwrite), preserve local without error.
+ if mode == "" && !forceOverwrite && previous.Origin != nil && !previous.Origin.Unavailable && plan.OriginUnavailable && mediaIsValid(previous, "video.mp4") {
// Safe monotonic preservation below.
} else {
notice, conflict, degErr := classifyWorkPlanVsLocal(previous, plan, resolvedKey, rawID, t)
@@ -360,17 +378,20 @@ func (m *Manager) executeXSingleVideoTask(
return degErr
}
isConflict = conflict
- if isConflict && mode != ConflictResolveKeepBoth && mode != ConflictResolveUseRemote {
+ if isConflict && !forceOverwrite && mode != ConflictResolveKeepBoth && mode != ConflictResolveUseRemote {
m.emitConflict(notice)
return ErrConflictDetected
}
+ if forceOverwrite && mode == "" {
+ mode = ConflictResolveUseRemote
+ }
}
}
editAdvanced := (plan.EditCount > 0 && plan.EditCount > previous.EditCount) ||
(plan.EditTs > 0 && previous.EditTs > 0 && plan.EditTs > previous.EditTs)
fullText, threadParts := buildXTextAndThread(rawID, plan, previous)
- if hasProtectedLocal && !isConflict {
+ if hasProtectedLocal && !isConflict && !forceOverwrite {
fullText = preserveMonotonicText(previous.Text, fullText, editAdvanced)
}
title := firstNonEmptyStr(plan.Title, plan.Desc, fullText, t.Title, "X 视频 "+rawID)
@@ -419,7 +440,7 @@ func (m *Manager) executeXSingleVideoTask(
var v2Media []library.MediaFile
var v2Missing []library.MissingRecord
reusedCover := false
- if !isConflict {
+ if !isConflict && !forceOverwrite {
for _, mf := range previous.Media {
if mf.Role == "cover" && mediaIsValid(previous, mf.Path) {
if copied, rErr := copyLocalMediaToStageAs(previous, mf.Path, mf.Path, "cover", stageDir); rErr == nil {
@@ -449,7 +470,7 @@ func (m *Manager) executeXSingleVideoTask(
sameMediaID := previous.DouyinVideo != nil && previous.DouyinVideo.MediaID != "" && plan.MediaID != "" &&
library.SanitizeMediaToken(previous.DouyinVideo.MediaID) == library.SanitizeMediaToken(plan.MediaID)
- if !isConflict && (!planUpgradesSingleVideo(previous, plan) || len(progressiveURLs) == 0) && mediaIsValid(previous, videoRel) {
+ if !isConflict && !forceOverwrite && (!planUpgradesSingleVideo(previous, plan) || len(progressiveURLs) == 0) && mediaIsValid(previous, videoRel) {
copied, cErr := copyLocalMediaToStageAs(previous, videoRel, videoRel, "video", stageDir)
if cErr != nil {
return cErr
@@ -480,7 +501,7 @@ func (m *Manager) executeXSingleVideoTask(
})
vidMedia, vErr := m.cacheXSingleMP4(ctx, &stageSub, stageDir, previous, false, videoRel, progressiveURLs, plan.DurationSec, plan.Width, plan.Height, false, plan.Transport, refreshVideoURLs)
if vErr != nil {
- if (!isConflict || sameMediaID) && mediaIsValid(previous, videoRel) && ctx.Err() == nil && !isStorageError(vErr) {
+ if !forceOverwrite && (!isConflict || sameMediaID) && mediaIsValid(previous, videoRel) && ctx.Err() == nil && !isStorageError(vErr) {
if copied, cErr := copyLocalMediaToStageAs(previous, videoRel, videoRel, "video", stageDir); cErr == nil {
v2Media = append(v2Media, *copied)
if previous.DouyinVideo != nil {
@@ -795,13 +816,14 @@ func (m *Manager) executeXPostTask(
hasProtectedLocal := exists && localHasProtectedContent(previous)
mode := effectiveConflictResolution(ctx, t.ConflictResolution, plan.ConflictResolution)
+ forceOverwrite := effectiveForceOverwrite(ctx, t.Source, t.ForceOverwrite, plan.ForceOverwrite)
resolvedKey := firstNonEmptyStr(plan.ItemKey, t.ItemKey, library.CanonicalItemKey(string(site.X), "dynamic", rawID))
isConflict := false
preserveOriginFiles := false
if hasProtectedLocal {
// Monotonic Origin protection (Invariant #4): if a forwarded/quoted post's Origin later
- // became Unavailable while local V1 has valid Origin + media, keep local Origin on mode==""!
- if mode == "" && previous.Origin != nil && !previous.Origin.Unavailable && plan.OriginUnavailable {
+ // became Unavailable while local V1 has valid Origin + media, keep local Origin on mode=="" && !forceOverwrite!
+ if mode == "" && !forceOverwrite && previous.Origin != nil && !previous.Origin.Unavailable && plan.OriginUnavailable {
preserveOriginFiles = true
} else {
notice, conflict, degErr := classifyWorkPlanVsLocal(previous, plan, resolvedKey, rawID, t)
@@ -809,17 +831,20 @@ func (m *Manager) executeXPostTask(
return degErr
}
isConflict = conflict
- if isConflict && mode != ConflictResolveKeepBoth && mode != ConflictResolveUseRemote {
+ if isConflict && !forceOverwrite && mode != ConflictResolveKeepBoth && mode != ConflictResolveUseRemote {
m.emitConflict(notice)
return ErrConflictDetected
}
+ if forceOverwrite && mode == "" {
+ mode = ConflictResolveUseRemote
+ }
}
}
editAdvanced := (plan.EditCount > 0 && plan.EditCount > previous.EditCount) ||
(plan.EditTs > 0 && previous.EditTs > 0 && plan.EditTs > previous.EditTs)
fullText, threadParts := buildXTextAndThread(rawID, plan, previous)
- if hasProtectedLocal && !isConflict {
+ if hasProtectedLocal && !isConflict && !forceOverwrite {
fullText = preserveMonotonicText(previous.Text, fullText, editAdvanced)
}
title := firstNonEmptyStr(plan.Title, plan.Desc, fullText, t.Title, "X 帖子 "+rawID)
@@ -926,7 +951,7 @@ func (m *Manager) executeXPostTask(
if cfg.SaveCover && len(plan.CoverURLs) > 0 && len(plan.Pages) == 0 {
reusedCover := false
- if hasProtectedLocal && !isConflict {
+ if hasProtectedLocal && !isConflict && !forceOverwrite {
for _, mf := range previous.Media {
if mf.Role == "cover" && mediaIsValid(previous, mf.Path) {
if copied, rErr := copyLocalMediaToStageAs(previous, mf.Path, mf.Path, "cover", workDir); rErr == nil {
@@ -961,7 +986,7 @@ func (m *Manager) executeXPostTask(
// Monotonic fromOrigin media preservation when remote Origin became unavailable!
var preservedVideo *library.DouyinVideoInfo
- if hasProtectedLocal && !isConflict && preserveOriginFiles && len(plan.Pages) == 0 {
+ if hasProtectedLocal && !isConflict && !forceOverwrite && preserveOriginFiles && len(plan.Pages) == 0 {
for _, mf := range previous.Media {
if mf.FromOrigin && mediaIsValid(previous, mf.Path) {
if copied, rErr := copyLocalMediaToStageAs(previous, mf.Path, mf.Path, mf.Role, workDir); rErr == nil {
@@ -989,6 +1014,9 @@ func (m *Manager) executeXPostTask(
prefix := fmt.Sprintf("images/%02d", pageIdx)
cleanPageMediaID := library.SanitizeMediaToken(page.MediaID)
reusableLP, canReuseLocal := findReusableLocalPage(previous, page, pageIdx, isConflict)
+ if forceOverwrite {
+ canReuseLocal = false
+ }
pageKind := strings.ToLower(strings.TrimSpace(page.Kind))
if pageKind == "animated_gif" {
pageKind = "gif"
@@ -1027,7 +1055,7 @@ func (m *Manager) executeXPostTask(
if isSiteStopError(imgErr) || isStorageError(imgErr) || ctx.Err() != nil {
return imgErr
}
- if hasProtectedLocal && isConflict && isDegradedSiteError(imgErr) {
+ if hasProtectedLocal && (isConflict || forceOverwrite) && isDegradedSiteError(imgErr) {
return wrapRemoteDegraded(imgErr)
}
reason := fmt.Sprintf("第 %02d 张图片下载失败 (%s)", pageIdx, classifyDownloadError(imgErr))
@@ -1127,7 +1155,7 @@ func (m *Manager) executeXPostTask(
if isSiteStopError(vErr) || isStorageError(vErr) || ctx.Err() != nil {
return vErr
}
- if hasProtectedLocal && isConflict && isDegradedSiteError(vErr) {
+ if hasProtectedLocal && (isConflict || forceOverwrite) && isDegradedSiteError(vErr) {
return wrapRemoteDegraded(vErr)
}
reason := fmt.Sprintf("第 %02d 项动图视频下载失败 (%s)", pageIdx, classifyDownloadError(vErr))
@@ -1247,7 +1275,7 @@ func (m *Manager) executeXPostTask(
if isSiteStopError(vErr) || isStorageError(vErr) || ctx.Err() != nil {
return vErr
}
- if hasProtectedLocal && isConflict && isDegradedSiteError(vErr) {
+ if hasProtectedLocal && (isConflict || forceOverwrite) && isDegradedSiteError(vErr) {
return wrapRemoteDegraded(vErr)
}
reason := fmt.Sprintf("第 %02d 项视频下载失败 (%s)", pageIdx, classifyDownloadError(vErr))
@@ -1316,6 +1344,10 @@ func (m *Manager) executeXPostTask(
}
}
+ if hasProtectedLocal && (isConflict || forceOverwrite) && len(partialErrors) > 0 {
+ return wrapRemoteDegradedMsg(fmt.Sprintf("新版部分媒体已失效,已保留本地原文件 (%s)", strings.Join(partialErrors, "; ")))
+ }
+
status := "complete"
if len(missing) > 0 || len(partialErrors) > 0 {
status = "partial"
@@ -1323,7 +1355,7 @@ func (m *Manager) executeXPostTask(
t.ErrorMessage = summarizeMissingReasons(missing)
}
- mediaFiles, notePages = preserveValidPreviousImagesForStage(itemDir, workDir, previous, exists && !isConflict, mediaFiles, notePages)
+ mediaFiles, notePages = preserveValidPreviousImagesForStage(itemDir, workDir, previous, exists && !isConflict && !forceOverwrite, mediaFiles, notePages)
meta := library.ItemMetadata{
Version: 1,
diff --git a/internal/library/feed.go b/internal/library/feed.go
index 0ccd390..07feaf7 100644
--- a/internal/library/feed.go
+++ b/internal/library/feed.go
@@ -245,6 +245,52 @@ func (s *Store) ListItems(filter FeedFilter) ([]ItemMetadata, error) {
return out, nil
}
+// ListItemsMetaOnlyBySite returns all cached items for a single site directly
+// from SQLite with zero disk syscalls and no row cap (used for offline backfill
+// statistics and historical cache standard scans, DEC-079).
+func (s *Store) ListItemsMetaOnlyBySite(site string) ([]ItemMetadata, error) {
+ normSite := strings.ToLower(strings.TrimSpace(site))
+ if normSite == "" {
+ return nil, nil
+ }
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ rows, err := s.db.Query(
+ `SELECT json_data, item_dir, status, total_bytes, upgrade_available, upgrade_hint
+ FROM library_items
+ WHERE site = ?
+ ORDER BY pub_ts DESC, item_key DESC`,
+ normSite,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer func() { _ = rows.Close() }()
+ var out []ItemMetadata
+ for rows.Next() {
+ var jsonStr, itemDir, status, upHint string
+ var totalBytes int64
+ var upAvail int
+ if err := rows.Scan(&jsonStr, &itemDir, &status, &totalBytes, &upAvail, &upHint); err != nil {
+ return nil, err
+ }
+ meta, err := ParseItemMetadata([]byte(jsonStr))
+ if err != nil {
+ continue
+ }
+ meta.ItemDir = itemDir
+ meta.Status = status
+ meta.TotalBytes = totalBytes
+ meta.UpgradeAvailable = upAvail == 1
+ meta.UpgradeHint = upHint
+ out = append(out, meta)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
// FeedPage implements bidirectional keyset pagination over (pub_ts, feed_key) for the home feed (FR-FEED-001).
// It excludes videos that are referenced by a cached dynamic item so videos referenced by dynamics do not appear twice.
func (s *Store) FeedPage(req FeedPageRequest) (FeedPageResult, error) {
diff --git a/internal/library/merge.go b/internal/library/merge.go
index d7de8db..7cbbf95 100644
--- a/internal/library/merge.go
+++ b/internal/library/merge.go
@@ -256,7 +256,7 @@ func MergeItemMetadata(local, imported ItemMetadata, mode string, sameContent fu
} else if out.DouyinVideo != nil && imported.DouyinVideo != nil && out.DouyinVideo.MediaID == "" {
out.DouyinVideo.MediaID = imported.DouyinVideo.MediaID
}
- if out.CacheStandardVersion == 0 && imported.CacheStandardVersion > 0 {
+ if imported.CacheStandardVersion > out.CacheStandardVersion {
out.CacheStandardVersion = imported.CacheStandardVersion
}
if out.RecheckedAt == "" && imported.RecheckedAt != "" {
diff --git a/internal/library/schema.go b/internal/library/schema.go
index af7e135..54e8e17 100644
--- a/internal/library/schema.go
+++ b/internal/library/schema.go
@@ -20,6 +20,12 @@ const CurrentSchemaVersion = 2
// item.json manifests (item.json schema version remains 1).
const CurrentCacheStandardVersion = 2
+// WeiboCacheStandardVersion identifies the Weibo-specific cache standard
+// baseline including dual-save watermark-free (/oslarge/) companion images
+// and DEC-073 clean structured links (DEC-078, DEC-079). CurrentCacheStandardVersion
+// stays at 2 so Bilibili Gate B does not trigger unnecessary PlayURL re-probes.
+const WeiboCacheStandardVersion = 3
+
// ItemMetadata is the canonical on-disk schema for item.json (INV-02).
// It is backward-compatible with earlier TRACE item.json files in trace-data/library/.
type ItemMetadata struct {
@@ -1578,6 +1584,165 @@ func NeedsCompletion(meta ItemMetadata) bool {
return false
}
+// WeiboStaticImageSlot describes a cached Weibo static (non-GIF) primary image
+// slot that does not yet have a watermark-free companion (images/NN_nowm.*).
+type WeiboStaticImageSlot struct {
+ PageIdx int // index into ItemMetadata.NotePages, or -1 if NotePages is empty
+ DisplayIndex int // 1-based display ordinal
+ PrimaryPath string // e.g. "images/01.jpg"
+ PrimarySHA256 string
+ NoWMStem string // e.g. "images/01_nowm"
+ PicID string // sanitized Weibo pic_id when known offline
+ FromOrigin bool
+}
+
+// WeiboStaticImageSlotsMissingNoWM returns all static (non-GIF, non-video)
+// primary image slots on a cached Weibo post that currently lack a companion
+// image_nowm file (pure offline inspection, 0 network requests, DEC-079).
+func WeiboStaticImageSlotsMissingNoWM(meta ItemMetadata) []WeiboStaticImageSlot {
+ if !strings.EqualFold(strings.TrimSpace(meta.Site), "weibo") || meta.Kind != "dynamic" || meta.IsArchivedSnapshot() {
+ return nil
+ }
+ if meta.Status != "complete" && meta.Status != "partial" {
+ return nil
+ }
+ mediaByPath := make(map[string]MediaFile, len(meta.Media))
+ existingNoWMStems := make(map[string]bool)
+ for _, mf := range meta.Media {
+ rel := strings.TrimSpace(mf.Path)
+ if rel == "" {
+ continue
+ }
+ lower := strings.ToLower(rel)
+ mediaByPath[lower] = mf
+ if mf.Role == "image_nowm" {
+ existingNoWMStems[strings.ToLower(stripFileExt(rel))] = true
+ }
+ }
+
+ var slots []WeiboStaticImageSlot
+ if len(meta.NotePages) > 0 {
+ for i, pg := range meta.NotePages {
+ imgPath := strings.TrimSpace(pg.Image)
+ if imgPath == "" || pg.GIF {
+ continue
+ }
+ kind := strings.ToLower(strings.TrimSpace(pg.Kind))
+ if kind == "video" || kind == "gif" || strings.HasSuffix(strings.ToLower(imgPath), ".gif") {
+ continue
+ }
+ mf := mediaByPath[strings.ToLower(imgPath)]
+ if mf.GIF {
+ continue
+ }
+ if strings.TrimSpace(pg.NoWatermark) != "" {
+ continue
+ }
+ nowmStem := stripFileExt(imgPath) + "_nowm"
+ if existingNoWMStems[strings.ToLower(nowmStem)] {
+ continue
+ }
+ picID := SanitizeMediaToken(pg.MediaID)
+ if picID == "" && len(meta.AssetIDs) == len(meta.NotePages) {
+ picID = SanitizeMediaToken(meta.AssetIDs[i])
+ }
+ idx := pg.Index
+ if idx <= 0 {
+ idx = i + 1
+ }
+ slots = append(slots, WeiboStaticImageSlot{
+ PageIdx: i,
+ DisplayIndex: idx,
+ PrimaryPath: imgPath,
+ PrimarySHA256: mf.SHA256,
+ NoWMStem: nowmStem,
+ PicID: picID,
+ FromOrigin: pg.FromOrigin || mf.FromOrigin,
+ })
+ }
+ return slots
+ }
+
+ var imageMedias []MediaFile
+ for _, mf := range meta.Media {
+ if mf.Role == "image" && strings.TrimSpace(mf.Path) != "" {
+ imageMedias = append(imageMedias, mf)
+ }
+ }
+ for i, mf := range imageMedias {
+ if mf.GIF || strings.HasSuffix(strings.ToLower(mf.Path), ".gif") {
+ continue
+ }
+ nowmStem := stripFileExt(mf.Path) + "_nowm"
+ if existingNoWMStems[strings.ToLower(nowmStem)] {
+ continue
+ }
+ picID := ""
+ if len(meta.AssetIDs) == len(imageMedias) {
+ picID = SanitizeMediaToken(meta.AssetIDs[i])
+ }
+ slots = append(slots, WeiboStaticImageSlot{
+ PageIdx: -1,
+ DisplayIndex: i + 1,
+ PrimaryPath: mf.Path,
+ PrimarySHA256: mf.SHA256,
+ NoWMStem: nowmStem,
+ PicID: picID,
+ FromOrigin: mf.FromOrigin,
+ })
+ }
+ return slots
+}
+
+func stripFileExt(rel string) string {
+ slash := strings.LastIndexByte(rel, '/')
+ dot := strings.LastIndexByte(rel, '.')
+ if dot > slash && dot > 0 {
+ return rel[:dot]
+ }
+ return rel
+}
+
+// WeiboNeedsNoWMBackfill reports whether a cached Weibo image post should be
+// backfilled for watermark-free (/oslarge/) companion images under DEC-078/DEC-079.
+// Items already stamped with CacheStandardVersion >= WeiboCacheStandardVersion are
+// skipped even if some images had no /oslarge/ variant or matched primary SHA-256.
+func WeiboNeedsNoWMBackfill(meta ItemMetadata, removeWatermark bool) bool {
+ if !removeWatermark || meta.CacheStandardVersion >= WeiboCacheStandardVersion {
+ return false
+ }
+ return len(WeiboStaticImageSlotsMissingNoWM(meta)) > 0
+}
+
+// WeiboHasAllFastCDNPicIDs reports whether every missing static image slot on a
+// Weibo item already carries a persisted pic_id (in NotePages[].MediaID or AssetIDs),
+// allowing direct /oslarge/ CDN backfill with zero Weibo API calls.
+func WeiboHasAllFastCDNPicIDs(meta ItemMetadata) bool {
+ slots := WeiboStaticImageSlotsMissingNoWM(meta)
+ if len(slots) == 0 {
+ return false
+ }
+ for _, s := range slots {
+ if s.PicID == "" {
+ return false
+ }
+ }
+ return true
+}
+
+// WeiboIsForwardItem reports whether a cached Weibo item is a forwarded/retweeted
+// post (stored under forwards/ or carrying via.reason == "forward" or an Origin).
+func WeiboIsForwardItem(meta ItemMetadata) bool {
+ if meta.Via != nil && meta.Via.Reason == ViaForward {
+ return true
+ }
+ if meta.Origin != nil || strings.EqualFold(strings.TrimSpace(meta.DynamicType), "DYNAMIC_TYPE_FORWARD") {
+ return true
+ }
+ normDir := strings.ReplaceAll(strings.ToLower(meta.ItemDir), `\`, "/")
+ return strings.Contains(normDir, "/forwards/")
+}
+
func parseFlexibleUnix(v any) int64 {
switch val := v.(type) {
case float64:
diff --git a/internal/library/weibo_backfill_test.go b/internal/library/weibo_backfill_test.go
new file mode 100644
index 0000000..a53657d
--- /dev/null
+++ b/internal/library/weibo_backfill_test.go
@@ -0,0 +1,193 @@
+package library
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/chialecode/trace/internal/storage"
+)
+
+func TestWeiboCacheStandardVersionAndOfflineHelpers(t *testing.T) {
+ if CurrentCacheStandardVersion != 2 {
+ t.Fatalf("CurrentCacheStandardVersion = %d, want 2 (must not bump to avoid Bilibili Gate B re-probes)", CurrentCacheStandardVersion)
+ }
+ if WeiboCacheStandardVersion != 3 {
+ t.Fatalf("WeiboCacheStandardVersion = %d, want 3", WeiboCacheStandardVersion)
+ }
+
+ staticMissing := ItemMetadata{
+ Site: "weibo",
+ Kind: "dynamic",
+ ID: "5090000000000001",
+ RawID: "5090000000000001",
+ Status: "complete",
+ CacheStandardVersion: 2,
+ AssetIDs: []string{"001picA"},
+ Media: []MediaFile{
+ {Role: "image", Path: "images/01.jpg", Bytes: 1024, SHA256: "abc"},
+ },
+ NotePages: []NotePageRecord{
+ {Index: 1, Kind: "image", Image: "images/01.jpg", MediaID: "001picA"},
+ },
+ }
+
+ if !WeiboNeedsNoWMBackfill(staticMissing, true) {
+ t.Fatal("expected staticMissing with removeWatermark=true to need backfill")
+ }
+ if WeiboNeedsNoWMBackfill(staticMissing, false) {
+ t.Fatal("expected staticMissing with removeWatermark=false NOT to need backfill")
+ }
+ if !WeiboHasAllFastCDNPicIDs(staticMissing) {
+ t.Fatal("expected staticMissing with MediaID/AssetIDs to qualify for fast CDN backfill")
+ }
+
+ // Already stamped with WeiboCacheStandardVersion = 3 -> never repeats infinitely.
+ v3Done := staticMissing
+ v3Done.CacheStandardVersion = WeiboCacheStandardVersion
+ if WeiboNeedsNoWMBackfill(v3Done, true) {
+ t.Fatal("item stamped with WeiboCacheStandardVersion=3 must not need backfill again")
+ }
+
+ // Already has verified NoWatermark companion -> does not need backfill.
+ hasCompanion := staticMissing
+ hasCompanion.Media = append(append([]MediaFile(nil), staticMissing.Media...), MediaFile{
+ Role: "image_nowm", Path: "images/01_nowm.jpg", Bytes: 800, SHA256: "def",
+ })
+ hasCompanion.NotePages = []NotePageRecord{
+ {Index: 1, Kind: "image", Image: "images/01.jpg", NoWatermark: "images/01_nowm.jpg", MediaID: "001picA"},
+ }
+ if WeiboNeedsNoWMBackfill(hasCompanion, true) {
+ t.Fatal("item already containing verified companion must not need backfill")
+ }
+
+ // Archived snapshot -> skipped.
+ archived := staticMissing
+ archived.ArchivedOf = "weibo:dynamic:5090000000000001"
+ if WeiboNeedsNoWMBackfill(archived, true) {
+ t.Fatal("archived snapshot must not need backfill")
+ }
+
+ // GIF-only post -> skipped.
+ gifOnly := ItemMetadata{
+ Site: "weibo",
+ Kind: "dynamic",
+ ID: "5090000000000002",
+ Status: "complete",
+ CacheStandardVersion: 0,
+ Media: []MediaFile{{Role: "image", Path: "images/01.gif", Bytes: 2048}},
+ NotePages: []NotePageRecord{{Index: 1, Kind: "image", Image: "images/01.gif", GIF: true}},
+ }
+ if WeiboNeedsNoWMBackfill(gifOnly, true) {
+ t.Fatal("GIF-only Weibo post must not need no-watermark backfill")
+ }
+
+ // Non-Weibo item -> skipped.
+ xItem := staticMissing
+ xItem.Site = "x"
+ if WeiboNeedsNoWMBackfill(xItem, true) {
+ t.Fatal("non-Weibo item must not trigger Weibo backfill")
+ }
+
+ // Missing pic_id -> cannot use fast CDN directly.
+ noPicID := staticMissing
+ noPicID.AssetIDs = nil
+ noPicID.NotePages = []NotePageRecord{{Index: 1, Kind: "image", Image: "images/01.jpg"}}
+ if WeiboHasAllFastCDNPicIDs(noPicID) {
+ t.Fatal("item without AssetIDs or NotePages[].MediaID must not qualify for fast CDN")
+ }
+
+ // Forward detection.
+ fwdByVia := staticMissing
+ fwdByVia.Via = &ItemVia{Reason: ViaForward, Site: "weibo", UID: "1001"}
+ if !WeiboIsForwardItem(fwdByVia) {
+ t.Fatal("expected ViaForward item to be detected as forward")
+ }
+ fwdByDir := staticMissing
+ fwdByDir.ItemDir = filepath.Join("cache", "weibo", "1001", "forwards", "5090000000000001")
+ if !WeiboIsForwardItem(fwdByDir) {
+ t.Fatal("expected forwards/ itemDir to be detected as forward")
+ }
+ if WeiboIsForwardItem(staticMissing) {
+ t.Fatal("ordinary original post must not be detected as forward")
+ }
+
+ // MergeItemMetadata preserves higher CacheStandardVersion (v2 -> v3, v3 stays v3).
+ mergedUp, _ := MergeItemMetadata(staticMissing, v3Done, "", nil)
+ if mergedUp.CacheStandardVersion != WeiboCacheStandardVersion {
+ t.Fatalf("MergeItemMetadata v2+v3 CacheStandardVersion = %d, want %d", mergedUp.CacheStandardVersion, WeiboCacheStandardVersion)
+ }
+ mergedKeep, _ := MergeItemMetadata(v3Done, staticMissing, "", nil)
+ if mergedKeep.CacheStandardVersion != WeiboCacheStandardVersion {
+ t.Fatalf("MergeItemMetadata v3+v2 CacheStandardVersion = %d, want %d", mergedKeep.CacheStandardVersion, WeiboCacheStandardVersion)
+ }
+}
+
+func TestListItemsMetaOnlyBySiteNo200Cap(t *testing.T) {
+ tmp := t.TempDir()
+ db, _, _, err := storage.OpenSQLite(filepath.Join(tmp, "library.db"))
+ if err != nil {
+ t.Fatalf("OpenSQLite: %v", err)
+ }
+ defer db.Close()
+ cacheDir := filepath.Join(tmp, "cache")
+ st, err := OpenWithDataDir(db, cacheDir, tmp)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ const weiboCount = 215
+ for i := 1; i <= weiboCount; i++ {
+ mid := fmt.Sprintf("509000000000%04d", i)
+ dir := filepath.Join(cacheDir, "weibo", "100001", "posts", mid)
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.SaveItem(dir, ItemMetadata{
+ Site: "weibo",
+ Kind: "dynamic",
+ ID: mid,
+ RawID: mid,
+ Title: "微博条目",
+ PubTs: int64(1700000000 + i),
+ Status: "complete",
+ Author: ItemAuthor{Site: "weibo", UID: "100001", Name: "合成博主"},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // Seed a few non-Weibo items to confirm site isolation.
+ for i := 1; i <= 3; i++ {
+ bvid := fmt.Sprintf("BV1meta00000%d", i)
+ dir := filepath.Join(cacheDir, "bilibili", "20001", "videos", bvid)
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.SaveItem(dir, ItemMetadata{
+ Site: "bilibili",
+ Kind: "video",
+ ID: bvid,
+ RawID: bvid,
+ Title: "B站视频",
+ PubTs: int64(1700001000 + i),
+ Status: "complete",
+ Author: ItemAuthor{Site: "bilibili", Mid: 20001, Name: "UP"},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ got, err := st.ListItemsMetaOnlyBySite("weibo")
+ if err != nil {
+ t.Fatalf("ListItemsMetaOnlyBySite: %v", err)
+ }
+ if len(got) != weiboCount {
+ t.Fatalf("ListItemsMetaOnlyBySite(weibo) returned %d items, want %d", len(got), weiboCount)
+ }
+ for _, it := range got {
+ if it.Site != "weibo" {
+ t.Fatalf("unexpected non-weibo item %q", it.ItemKey)
+ }
+ }
+}
diff --git a/internal/service/backfill.go b/internal/service/backfill.go
new file mode 100644
index 0000000..e73b219
--- /dev/null
+++ b/internal/service/backfill.go
@@ -0,0 +1,1030 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "slices"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/chialecode/trace/internal/download"
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/site"
+ "github.com/chialecode/trace/internal/site/bilibili"
+ "github.com/chialecode/trace/internal/site/weibo"
+)
+
+type backfillMatchedItem struct {
+ itemKey string
+ title string
+ overrides []download.WeiboBackfillSlotOverride
+ remoteLinks []TextLinkDTO
+}
+
+type weiboBackfillBuckets struct {
+ offlineLinkOnly []library.ItemMetadata
+ fastCDN []library.ItemMetadata
+ subscribedByUID map[string][]library.ItemMetadata
+ subscribedUIDs []string
+ fallbackDetail []library.ItemMetadata
+ summary BackfillSummaryDTO
+}
+
+func weiboNeedsLegacyLinkUpgrade(meta library.ItemMetadata) bool {
+ if !strings.EqualFold(strings.TrimSpace(meta.Site), string(site.Weibo)) || meta.IsArchivedSnapshot() {
+ return false
+ }
+ if meta.Status != "complete" && meta.Status != "partial" {
+ return false
+ }
+ _, hadLegacy := cleanLegacyInlineLinksInItem(meta, nil)
+ return hadLegacy
+}
+
+func (b *Backend) subscribedWeiboUIDSet() map[string]bool {
+ out := make(map[string]bool)
+ if b == nil || b.subs == nil {
+ return out
+ }
+ subs, err := b.subs.List()
+ if err != nil {
+ return out
+ }
+ for _, sub := range subs {
+ for _, acc := range sub.Accounts {
+ if strings.EqualFold(strings.TrimSpace(acc.Site), string(site.Weibo)) {
+ if norm, uErr := site.NormalizeUID(site.Weibo, acc.UID); uErr == nil && norm != "" {
+ out[norm] = true
+ }
+ }
+ }
+ }
+ return out
+}
+
+func (b *Backend) scanWeiboBackfillBuckets(excludeKeys map[string]bool) (weiboBackfillBuckets, error) {
+ var out weiboBackfillBuckets
+ out.subscribedByUID = make(map[string][]library.ItemMetadata)
+ if b == nil || b.profile == ProfileRemote || b.lib == nil {
+ return out, nil
+ }
+ items, err := b.lib.ListItemsMetaOnlyBySite(string(site.Weibo))
+ if err != nil {
+ return out, err
+ }
+ removeWM := b.weiboRemoveWatermarkEnabled()
+ subUIDs := b.subscribedWeiboUIDSet()
+
+ for _, meta := range items {
+ if meta.IsArchivedSnapshot() || (meta.Status != "complete" && meta.Status != "partial") {
+ continue
+ }
+ if len(excludeKeys) > 0 && excludeKeys[meta.ItemKey] {
+ continue
+ }
+ missingNoWM := library.WeiboNeedsNoWMBackfill(meta, removeWM)
+ legacyLinks := weiboNeedsLegacyLinkUpgrade(meta)
+ if !missingNoWM && !legacyLinks {
+ continue
+ }
+ out.summary.TotalItems++
+ if missingNoWM {
+ out.summary.WeiboMissingNoWM++
+ }
+ if legacyLinks {
+ out.summary.WeiboLegacyLinks++
+ }
+
+ if !missingNoWM {
+ out.offlineLinkOnly = append(out.offlineLinkOnly, meta)
+ continue
+ }
+ if library.WeiboHasAllFastCDNPicIDs(meta) {
+ out.summary.WeiboFastCDNCandidates++
+ out.fastCDN = append(out.fastCDN, meta)
+ continue
+ }
+ authorUID, uErr := site.NormalizeUID(site.Weibo, itemAuthorUIDString(meta))
+ if !library.WeiboIsForwardItem(meta) && uErr == nil && subUIDs[authorUID] {
+ out.summary.WeiboSubscribedCount++
+ out.subscribedByUID[authorUID] = append(out.subscribedByUID[authorUID], meta)
+ } else {
+ out.summary.WeiboFallbackDetailCount++
+ out.fallbackDetail = append(out.fallbackDetail, meta)
+ }
+ }
+ if len(out.subscribedByUID) > 0 {
+ out.subscribedUIDs = make([]string, 0, len(out.subscribedByUID))
+ for uid := range out.subscribedByUID {
+ out.subscribedUIDs = append(out.subscribedUIDs, uid)
+ }
+ sort.Strings(out.subscribedUIDs)
+ }
+ return out, nil
+}
+
+// BackfillSummary computes offline statistics of historical cache items eligible
+// for standard upgrades (missing Weibo /oslarge/ companions or pre-DEC-073 inline
+// URLs) with zero network requests (DEC-079).
+func (b *Backend) BackfillSummary() (BackfillSummaryDTO, error) {
+ if b == nil || b.profile == ProfileRemote || b.lib == nil {
+ return BackfillSummaryDTO{}, nil
+ }
+ buckets, err := b.scanWeiboBackfillBuckets(nil)
+ if err != nil {
+ return BackfillSummaryDTO{}, err
+ }
+ return buckets.summary, nil
+}
+
+// StartWeiboBackfill enqueues or deduplicates the persistent historical Weibo
+// cache backfill queue in cache-queue.json (v3, DEC-079). Offline legacy-link
+// upgrades and pure-CDN /oslarge/ items (with known pic_id) run with 0 Weibo
+// JSON API calls; items needing pic_id lookup run under Weibo API login/quota.
+func (b *Backend) StartWeiboBackfill(ctx context.Context) (CacheQueueTask, error) {
+ _ = ctx
+ if err := b.requireDesktop(); err != nil {
+ return CacheQueueTask{}, err
+ }
+ if b.queue == nil {
+ return CacheQueueTask{}, fmt.Errorf("service: cache queue not initialized")
+ }
+
+ // Return any existing unfinished backfill queue task without duplicating.
+ if existing, ok := b.FindCacheQueueTask(string(site.Weibo), CacheQueueBackfillUser, CacheQueueListWeiboBackfill); ok {
+ return existing, nil
+ }
+
+ buckets, err := b.scanWeiboBackfillBuckets(nil)
+ if err != nil {
+ return CacheQueueTask{}, err
+ }
+ if buckets.summary.TotalItems == 0 {
+ return CacheQueueTask{}, &site.Error{
+ Site: site.Weibo,
+ Kind: site.ErrKindBadRequest,
+ Message: "历史微博缓存已全部符合最新标准",
+ }
+ }
+ // If every pending item requires Weibo API lookup (no offline-only or fast-CDN items),
+ // fail fast with auth_required when Weibo is not logged in.
+ if len(buckets.offlineLinkOnly) == 0 && len(buckets.fastCDN) == 0 {
+ if authErr := b.requireSiteLogin(site.Weibo); authErr != nil {
+ return CacheQueueTask{}, authErr
+ }
+ }
+
+ m := b.queue
+ m.mu.Lock()
+ now := m.nowRFC3339()
+
+ for _, e := range m.tasks {
+ if isWeiboBackfillRecord(e.rec) && isUnfinishedQueueStatus(e.rec.Status) {
+ dto := m.toDTOLocked(e)
+ m.mu.Unlock()
+ return dto, nil
+ }
+ }
+
+ prevTasks := append([]*cacheQueueEntry(nil), m.tasks...)
+ taskID := makeCacheQueueID(string(site.Weibo), CacheQueueListWeiboBackfill, CacheQueueBackfillUser)
+ for i, e := range m.tasks {
+ if isWeiboBackfillRecord(e.rec) {
+ taskID = e.rec.ID
+ m.tasks = append(m.tasks[:i], m.tasks[i+1:]...)
+ break
+ }
+ }
+
+ rec := cacheQueueRecord{
+ ID: taskID,
+ Site: string(site.Weibo),
+ User: CacheQueueBackfillUser,
+ UserName: "历史缓存补全",
+ List: CacheQueueListWeiboBackfill,
+ Kind: CacheQueueKindWeiboBackfill,
+ Origin: CacheQueueOriginBackfill,
+ BackfillTotal: buckets.summary.TotalItems,
+ BackfillSubUIDs: append([]string(nil), buckets.subscribedUIDs...),
+ HasMore: true,
+ RestThreshold: m.pickRestThresholdLocked(),
+ Status: CacheQueueQueued,
+ CreatedAt: now,
+ UpdatedAt: now,
+ }
+ entry := &cacheQueueEntry{
+ rec: rec,
+ rt: cacheQueueRuntime{
+ seenKeys: make(map[string]bool),
+ },
+ }
+ m.tasks = append(m.tasks, entry)
+ if err := m.saveLocked(); err != nil {
+ m.tasks = prevTasks
+ m.mu.Unlock()
+ return CacheQueueTask{}, err
+ }
+ notifyRec := entry.rec
+ dto := m.toDTOLocked(entry)
+ m.mu.Unlock()
+
+ m.notifyState(notifyRec)
+ m.wakeSite(site.Weibo)
+ return dto, nil
+}
+
+func isWeiboBackfillRecord(r cacheQueueRecord) bool {
+ return strings.EqualFold(strings.TrimSpace(r.Site), string(site.Weibo)) &&
+ strings.EqualFold(strings.TrimSpace(r.List), CacheQueueListWeiboBackfill)
+}
+
+func (m *cacheQueueManager) siteRiskBackoffOnly(siteID site.ID, now time.Time) (bool, time.Time) {
+ if m.b == nil || m.b.subs == nil {
+ return false, time.Time{}
+ }
+ nowUTC := now.UTC()
+ if inBackoff, until := m.b.subs.IsSiteInBackoff(string(siteID)); inBackoff && until.After(nowUTC) {
+ return true, until.UTC()
+ }
+ return false, time.Time{}
+}
+
+func buildWeiboOverridesFromPost(post weibo.Post) ([]download.WeiboBackfillSlotOverride, []TextLinkDTO) {
+ images, _ := post.EffectiveMedia()
+ var overrides []download.WeiboBackfillSlotOverride
+ for i, img := range images {
+ if img.Kind == weibo.MediaKindGIF || img.Kind == weibo.MediaKindVideo {
+ continue
+ }
+ idx := img.Index
+ if idx <= 0 {
+ idx = i + 1
+ }
+ wmURL := strings.TrimSpace(img.WatermarkFreeURL)
+ if wmURL == "" && img.URL != "" {
+ if rewritten, ok := weibo.RewriteWatermarkFreeImageURL(img.URL); ok {
+ wmURL = rewritten
+ }
+ }
+ overrides = append(overrides, download.WeiboBackfillSlotOverride{
+ DisplayIndex: idx,
+ PicID: library.SanitizeMediaToken(img.PicID),
+ WatermarkFreeURL: wmURL,
+ })
+ }
+ return overrides, MapSiteTextLinks(post.Links)
+}
+
+func (m *cacheQueueManager) appendBackfillRecentLocked(entry *cacheQueueEntry, itemKey, title, nowStr string) {
+ if itemKey == "" {
+ return
+ }
+ summary := CacheQueueRecentItem{
+ ItemKey: itemKey,
+ Title: sanitizeQueueText(firstNonEmpty(title, itemKey)),
+ CachedAt: nowStr,
+ }
+ entry.rec.RecentItems = append([]CacheQueueRecentItem{summary}, entry.rec.RecentItems...)
+ if len(entry.rec.RecentItems) > maxCacheQueueRecentItems {
+ entry.rec.RecentItems = entry.rec.RecentItems[:maxCacheQueueRecentItems]
+ }
+}
+
+func (m *cacheQueueManager) markBackfillProcessedLocked(entry *cacheQueueEntry, itemKey string) {
+ if itemKey == "" {
+ return
+ }
+ if entry.rt.seenKeys == nil {
+ entry.rt.seenKeys = make(map[string]bool)
+ }
+ entry.rt.seenKeys[itemKey] = true
+ if !slices.Contains(entry.rec.ProcessedKeys, itemKey) {
+ entry.rec.ProcessedKeys = append(entry.rec.ProcessedKeys, itemKey)
+ }
+}
+
+func (m *cacheQueueManager) completeBackfillLocked(entry *cacheQueueEntry) cacheQueueRecord {
+ nowStr := m.nowRFC3339()
+ entry.rec.Status = CacheQueueCompleted
+ entry.rec.PauseReason = ""
+ entry.rec.StopReason = ""
+ entry.rec.NextRunAt = ""
+ entry.rec.ActiveItemKey = ""
+ entry.rec.ActiveTitle = ""
+ entry.rec.HasMore = false
+ entry.rec.BackfillPhase = ""
+ entry.rec.BackfillSubCursor = ""
+ entry.rec.Note = fmt.Sprintf("已补全 %d 条,跳过 %d 条", entry.rec.CachedCount, entry.rec.SkippedCount)
+ entry.rec.UpdatedAt = nowStr
+ entry.rt.backfillMatched = nil
+ entry.rt.backfillPendingCursor = ""
+ entry.rt.backfillPendingUIDDone = false
+ m.saveLoggedLocked("backfill_complete")
+ return entry.rec
+}
+
+func (m *cacheQueueManager) scheduleFastCDNWaitLocked(entry *cacheQueueEntry, phase, reason string) cacheQueueRecord {
+ delay := m.fastCDNDelayLocked()
+ now := m.clock.Now().UTC()
+ entry.rec.Status = CacheQueueWaiting
+ entry.rec.BackfillPhase = phase
+ entry.rec.PauseReason = ""
+ entry.rec.StopReason = reason
+ entry.rec.ActiveItemKey = ""
+ entry.rec.ActiveTitle = ""
+ entry.rec.NextRunAt = now.Add(delay).Format(time.RFC3339)
+ entry.rec.UpdatedAt = now.Format(time.RFC3339)
+ m.saveLoggedLocked("backfill_fast_wait")
+ return entry.rec
+}
+
+func isBackfillStorageError(err error) bool {
+ if err == nil {
+ return false
+ }
+ var pathErr *os.PathError
+ var linkErr *os.LinkError
+ return site.KindOf(err) == site.ErrKindStorage ||
+ errors.As(err, &pathErr) ||
+ errors.As(err, &linkErr) ||
+ bilibili.IsKind(err, "storage")
+}
+
+func (m *cacheQueueManager) scheduleSlowAPIWaitLocked(entry *cacheQueueEntry, phase, defaultReason string, cached bool) cacheQueueRecord {
+ if entry.rec.RestThreshold <= 0 {
+ entry.rec.RestThreshold = m.pickRestThresholdLocked()
+ }
+ if cached {
+ entry.rec.SinceRestCount++
+ }
+ var delay time.Duration
+ reason := defaultReason
+ if reason == "" {
+ reason = "等待下一条"
+ }
+ if cached && entry.rec.SinceRestCount >= entry.rec.RestThreshold {
+ delay = m.randDurationLocked(m.pacing.LongRestMinDelay, m.pacing.LongRestMaxDelay)
+ entry.rec.SinceRestCount = 0
+ entry.rec.RestThreshold = m.pickRestThresholdLocked()
+ reason = "已完成一批补全,长歇等待中"
+ } else {
+ delay = m.randDurationLocked(m.pacing.ItemMinDelay, m.pacing.ItemMaxDelay)
+ }
+ if phase == "" || phase == backfillPhaseFastCDN || phase == backfillPhaseOfflineLinks {
+ phase = backfillPhaseFallbackDetail
+ }
+ now := m.clock.Now().UTC()
+ entry.rec.Status = CacheQueueWaiting
+ entry.rec.BackfillPhase = phase
+ entry.rec.PauseReason = ""
+ entry.rec.StopReason = reason
+ entry.rec.ActiveItemKey = ""
+ entry.rec.ActiveTitle = ""
+ entry.rec.NextRunAt = now.Add(delay).Format(time.RFC3339)
+ entry.rec.UpdatedAt = now.Format(time.RFC3339)
+ m.saveLoggedLocked("backfill_api_wait")
+ return entry.rec
+}
+
+// advanceWeiboBackfillStep executes one unit of work for the 3-tier historical
+// Weibo backfill queue (Tier A offline links -> Tier B pure CDN 2-5s -> Tier C1
+// subscribed mymblog -> Tier C2 fallback statuses/show).
+// Caller holds m.mu on entry; this method unlocks m.mu before returning.
+func (m *cacheQueueManager) advanceWeiboBackfillStep(ctx context.Context, entry *cacheQueueEntry) {
+ if m.b == nil || m.b.lib == nil || m.b.dl == nil {
+ rec := m.completeBackfillLocked(entry)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+
+ processed := make(map[string]bool, len(entry.rec.ProcessedKeys))
+ for _, k := range entry.rec.ProcessedKeys {
+ if k != "" {
+ processed[k] = true
+ }
+ }
+ for k := range entry.rt.seenKeys {
+ processed[k] = true
+ }
+
+ // If we have buffered matched posts from the last mymblog page, drain one
+ // at 2–5s fast CDN pacing before fetching the next page!
+ if len(entry.rt.backfillMatched) > 0 {
+ if inBackoff, _ := m.siteRiskBackoffOnly(site.Weibo, m.clock.Now()); inBackoff {
+ rec := m.enterWaitingBackoffLocked(entry, site.Weibo, site.ErrKindBackoff)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+ match := entry.rt.backfillMatched[0]
+ entry.rt.backfillMatched = entry.rt.backfillMatched[1:]
+ entry.rec.BackfillPhase = backfillPhaseFastCDN
+ entry.rec.ActiveItemKey = match.itemKey
+ entry.rec.ActiveTitle = sanitizeQueueText(match.title)
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ stepCtx, stepCancel := context.WithCancel(ctx)
+ entry.rt.stepCancel = stepCancel
+ m.mu.Unlock()
+
+ res, bErr := m.b.dl.BackfillWeiboNoWMCompanions(
+ stepCtx,
+ match.itemKey,
+ m.b.weibo.MediaTransport(),
+ match.overrides,
+ func(meta library.ItemMetadata) (library.ItemMetadata, bool) {
+ return cleanLegacyInlineLinksInItem(meta, match.remoteLinks)
+ },
+ )
+
+ m.mu.Lock()
+ stepCancel()
+ entry.rt.stepCancel = nil
+ if entry.rec.Status != CacheQueueRunning || ctx.Err() != nil {
+ // Put item back if paused/canceled mid-step so it is not lost.
+ if bErr != nil && ctx.Err() == nil {
+ entry.rt.backfillMatched = append([]backfillMatchedItem{match}, entry.rt.backfillMatched...)
+ }
+ m.mu.Unlock()
+ return
+ }
+ if bErr != nil {
+ kind := site.KindOf(bErr)
+ if kind == site.ErrKindAuthRequired {
+ entry.rt.backfillMatched = append([]backfillMatchedItem{match}, entry.rt.backfillMatched...)
+ m.mu.Unlock()
+ m.pauseForSite(site.Weibo, "auth_required", "微博登录已失效,重新登录后自动继续")
+ return
+ }
+ if isBackoffOrQuotaKind(kind) {
+ entry.rt.backfillMatched = append([]backfillMatchedItem{match}, entry.rt.backfillMatched...)
+ rec := m.enterWaitingBackoffLocked(entry, site.Weibo, kind)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+ if isBackfillStorageError(bErr) {
+ entry.rt.backfillMatched = append([]backfillMatchedItem{match}, entry.rt.backfillMatched...)
+ entry.rec.Status = CacheQueuePaused
+ entry.rec.PauseReason = "storage"
+ entry.rec.StopReason = "存储空间不足或写入失败,已暂停补全"
+ entry.rec.NextRunAt = ""
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ m.saveLoggedLocked("backfill_storage_pause")
+ rec := entry.rec
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+ m.markBackfillProcessedLocked(entry, match.itemKey)
+ entry.rec.SkippedCount++
+ } else {
+ m.markBackfillProcessedLocked(entry, match.itemKey)
+ if res.AddedCompanions > 0 || res.LinksCleaned {
+ entry.rec.CachedCount++
+ m.appendBackfillRecentLocked(entry, match.itemKey, match.title, m.nowRFC3339())
+ } else {
+ entry.rec.SkippedCount++
+ }
+ }
+ // Once the buffered page matches drain completely, commit the pending mymblog cursor advance
+ // and pace the next JSON API call under slow API pacing (40–150s), NOT 2–5s CDN pacing!
+ var rec cacheQueueRecord
+ if len(entry.rt.backfillMatched) > 0 {
+ rec = m.scheduleFastCDNWaitLocked(entry, backfillPhaseFastCDN, "纯 CDN 快速补全中")
+ } else {
+ if entry.rt.backfillPendingUIDDone {
+ entry.rec.BackfillSubIndex++
+ entry.rec.BackfillSubCursor = ""
+ } else if entry.rt.backfillPendingCursor != "" {
+ entry.rec.BackfillSubCursor = sanitizeQueueCursor(entry.rt.backfillPendingCursor)
+ }
+ entry.rt.backfillPendingCursor = ""
+ entry.rt.backfillPendingUIDDone = false
+ rec = m.scheduleSlowAPIWaitLocked(entry, backfillPhaseSubscribedTimeline, "等待下一次微博列表检查", false)
+ }
+ m.mu.Unlock()
+ if bErr == nil && m.b.events != nil {
+ m.b.events.PublishSite(EventLibraryChanged, string(site.Weibo), match.itemKey)
+ }
+ m.notifyState(rec)
+ return
+ }
+
+ // Scan current offline library state (outside lock so SQLite never blocks queue lock).
+ m.mu.Unlock()
+ buckets, scanErr := m.b.scanWeiboBackfillBuckets(processed)
+ m.mu.Lock()
+ if entry.rec.Status != CacheQueueRunning || ctx.Err() != nil {
+ m.mu.Unlock()
+ return
+ }
+ if scanErr != nil {
+ entry.rec.Status = CacheQueuePaused
+ entry.rec.PauseReason = "storage"
+ entry.rec.StopReason = sanitizeQueueText("读取本地媒体库失败:" + scanErr.Error())
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ m.saveLoggedLocked("backfill_scan_err")
+ rec := entry.rec
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+
+ doneSoFar := entry.rec.CachedCount + entry.rec.SkippedCount
+ if total := doneSoFar + buckets.summary.TotalItems; total > entry.rec.BackfillTotal {
+ entry.rec.BackfillTotal = total
+ }
+
+ if buckets.summary.TotalItems == 0 {
+ rec := m.completeBackfillLocked(entry)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ if m.b.events != nil {
+ m.b.events.PublishSite(EventLibraryChanged, string(site.Weibo), "backfill:completed")
+ }
+ return
+ }
+
+ // --- Tier A: Pure offline legacy inline-URL cleanup (0 network requests, 0 delay) ---
+ if len(buckets.offlineLinkOnly) > 0 {
+ batch := buckets.offlineLinkOnly
+ entry.rec.BackfillPhase = backfillPhaseOfflineLinks
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ m.mu.Unlock()
+
+ removeWM := m.b.weiboRemoveWatermarkEnabled()
+ var updatedKeys []string
+ var processedKeys []string
+ var recentAdded []CacheQueueRecentItem
+ var storagePauseErr error
+ nowStr := m.nowRFC3339()
+ for _, item := range batch {
+ if ctx.Err() != nil {
+ break
+ }
+ fresh, ok, gErr := m.b.lib.GetItem(item.ItemKey)
+ if gErr != nil {
+ if isBackfillStorageError(gErr) {
+ storagePauseErr = gErr
+ break
+ }
+ processedKeys = append(processedKeys, item.ItemKey)
+ continue
+ }
+ if !ok || strings.TrimSpace(fresh.ItemDir) == "" {
+ processedKeys = append(processedKeys, item.ItemKey)
+ continue
+ }
+ cleaned, hadLegacy := cleanLegacyInlineLinksInItem(fresh, nil)
+ if !hadLegacy {
+ processedKeys = append(processedKeys, item.ItemKey)
+ continue
+ }
+ if removeWM && !library.WeiboNeedsNoWMBackfill(cleaned, true) && cleaned.CacheStandardVersion < library.WeiboCacheStandardVersion {
+ cleaned.CacheStandardVersion = library.WeiboCacheStandardVersion
+ }
+ if _, sErr := m.b.lib.SaveItemMetadataOnly(fresh.ItemDir, cleaned); sErr != nil {
+ m.b.logError("backfill.offline_links", sErr)
+ if isBackfillStorageError(sErr) {
+ storagePauseErr = sErr
+ break
+ }
+ processedKeys = append(processedKeys, item.ItemKey)
+ continue
+ }
+ updatedKeys = append(updatedKeys, item.ItemKey)
+ processedKeys = append(processedKeys, item.ItemKey)
+ recentAdded = append(recentAdded, CacheQueueRecentItem{
+ ItemKey: item.ItemKey,
+ Title: sanitizeQueueText(trimQueueSummaryTitle(firstNonEmpty(cleaned.Title, cleaned.Text, item.RawID))),
+ CachedAt: nowStr,
+ })
+ }
+
+ m.mu.Lock()
+ for _, k := range processedKeys {
+ m.markBackfillProcessedLocked(entry, k)
+ }
+ entry.rec.CachedCount += len(updatedKeys)
+ entry.rec.SkippedCount += len(processedKeys) - len(updatedKeys)
+ for _, r := range recentAdded {
+ m.appendBackfillRecentLocked(entry, r.ItemKey, r.Title, r.CachedAt)
+ }
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ if storagePauseErr != nil {
+ entry.rec.Status = CacheQueuePaused
+ entry.rec.PauseReason = "storage"
+ entry.rec.StopReason = "存储空间不足或写入失败,已暂停补全"
+ entry.rec.NextRunAt = ""
+ m.saveLoggedLocked("backfill_storage_pause")
+ rec := entry.rec
+ m.mu.Unlock()
+ if m.b.events != nil {
+ for _, k := range updatedKeys {
+ m.b.events.PublishSite(EventLibraryChanged, string(site.Weibo), k)
+ }
+ }
+ m.notifyState(rec)
+ return
+ }
+ // If nothing remains after Tier A, complete right away!
+ if len(buckets.fastCDN) == 0 && len(buckets.subscribedUIDs) == 0 && len(buckets.fallbackDetail) == 0 {
+ rec := m.completeBackfillLocked(entry)
+ m.mu.Unlock()
+ if m.b.events != nil {
+ for _, k := range updatedKeys {
+ m.b.events.PublishSite(EventLibraryChanged, string(site.Weibo), k)
+ }
+ }
+ m.notifyState(rec)
+ return
+ }
+ m.saveLoggedLocked("backfill_tier_a")
+ rec := entry.rec
+ m.mu.Unlock()
+ if m.b.events != nil {
+ for _, k := range updatedKeys {
+ m.b.events.PublishSite(EventLibraryChanged, string(site.Weibo), k)
+ }
+ }
+ m.notifyState(rec)
+ return
+ }
+
+ // --- Tier B: Pure CDN /oslarge/ fast backfill (0 Weibo JSON API calls, 2–5s pacing, no 100/h quota, no 10–25m rest) ---
+ if len(buckets.fastCDN) > 0 {
+ if inBackoff, _ := m.siteRiskBackoffOnly(site.Weibo, m.clock.Now()); inBackoff {
+ rec := m.enterWaitingBackoffLocked(entry, site.Weibo, site.ErrKindBackoff)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+ item := buckets.fastCDN[0]
+ title := trimQueueSummaryTitle(firstNonEmpty(item.Title, item.Text, item.RawID))
+ entry.rec.BackfillPhase = backfillPhaseFastCDN
+ entry.rec.ActiveItemKey = item.ItemKey
+ entry.rec.ActiveTitle = sanitizeQueueText(title)
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ stepCtx, stepCancel := context.WithCancel(ctx)
+ entry.rt.stepCancel = stepCancel
+ m.mu.Unlock()
+
+ res, bErr := m.b.dl.BackfillWeiboNoWMCompanions(
+ stepCtx,
+ item.ItemKey,
+ m.b.weibo.MediaTransport(),
+ nil,
+ func(meta library.ItemMetadata) (library.ItemMetadata, bool) {
+ return cleanLegacyInlineLinksInItem(meta, nil)
+ },
+ )
+
+ m.mu.Lock()
+ stepCancel()
+ entry.rt.stepCancel = nil
+ if entry.rec.Status != CacheQueueRunning || ctx.Err() != nil {
+ m.mu.Unlock()
+ return
+ }
+ if bErr != nil {
+ kind := site.KindOf(bErr)
+ if kind == site.ErrKindAuthRequired {
+ m.mu.Unlock()
+ m.pauseForSite(site.Weibo, "auth_required", "微博登录已失效,重新登录后自动继续")
+ return
+ }
+ if isBackoffOrQuotaKind(kind) {
+ rec := m.enterWaitingBackoffLocked(entry, site.Weibo, kind)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+ if isBackfillStorageError(bErr) {
+ entry.rec.Status = CacheQueuePaused
+ entry.rec.PauseReason = "storage"
+ entry.rec.StopReason = "存储空间不足或写入失败,已暂停补全"
+ entry.rec.NextRunAt = ""
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ m.saveLoggedLocked("backfill_storage_pause")
+ rec := entry.rec
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+ m.markBackfillProcessedLocked(entry, item.ItemKey)
+ entry.rec.SkippedCount++
+ } else {
+ m.markBackfillProcessedLocked(entry, item.ItemKey)
+ if res.AddedCompanions > 0 || res.LinksCleaned {
+ entry.rec.CachedCount++
+ m.appendBackfillRecentLocked(entry, item.ItemKey, title, m.nowRFC3339())
+ } else {
+ entry.rec.SkippedCount++
+ }
+ }
+ var rec cacheQueueRecord
+ switch {
+ case len(buckets.fastCDN) > 1:
+ rec = m.scheduleFastCDNWaitLocked(entry, backfillPhaseFastCDN, "纯 CDN 快速补全中")
+ case len(buckets.subscribedUIDs) > 0:
+ rec = m.scheduleSlowAPIWaitLocked(entry, backfillPhaseSubscribedTimeline, "准备按已订阅博主列表补全历史条目", false)
+ case len(buckets.fallbackDetail) > 0:
+ rec = m.scheduleSlowAPIWaitLocked(entry, backfillPhaseFallbackDetail, "准备按单条详情补全历史条目", false)
+ default:
+ rec = m.completeBackfillLocked(entry)
+ }
+ m.mu.Unlock()
+ if bErr == nil && m.b.events != nil {
+ m.b.events.PublishSite(EventLibraryChanged, string(site.Weibo), item.ItemKey)
+ }
+ m.notifyState(rec)
+ return
+ }
+
+ // --- Tier C: Items missing pic_id require Weibo API (strict login + 100/hour quota + backoff) ---
+ if !m.hasSiteLogin(site.Weibo) {
+ entry.rec.Status = CacheQueuePaused
+ entry.rec.PauseReason = "auth_required"
+ entry.rec.StopReason = "剩余历史条目需查询微博接口,请先登录微博后继续"
+ entry.rec.NextRunAt = ""
+ entry.rec.ActiveItemKey = ""
+ entry.rec.ActiveTitle = ""
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ m.saveLoggedLocked("backfill_auth_pause")
+ rec := entry.rec
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+
+ // --- Tier C1: Batch-match subscribed Weibo authors via mymblog ---
+ if len(entry.rec.BackfillSubUIDs) == 0 && len(buckets.subscribedUIDs) > 0 {
+ entry.rec.BackfillSubUIDs = append([]string(nil), buckets.subscribedUIDs...)
+ entry.rec.BackfillSubIndex = 0
+ entry.rec.BackfillSubCursor = ""
+ }
+ for entry.rec.BackfillSubIndex < len(entry.rec.BackfillSubUIDs) {
+ uid := entry.rec.BackfillSubUIDs[entry.rec.BackfillSubIndex]
+ if len(buckets.subscribedByUID[uid]) > 0 {
+ break
+ }
+ entry.rec.BackfillSubIndex++
+ entry.rec.BackfillSubCursor = ""
+ }
+ if entry.rec.BackfillSubIndex < len(entry.rec.BackfillSubUIDs) {
+ if blocked, _ := m.siteBackoffOrQuotaEnd(site.Weibo, m.clock.Now()); blocked {
+ kind := site.ErrKindBackoff
+ if m.b.subs != nil && !m.b.subs.CanUseSiteQuotaTokens(string(site.Weibo), 1) {
+ kind = site.ErrKindQuota
+ }
+ rec := m.enterWaitingBackoffLocked(entry, site.Weibo, kind)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+ uid := entry.rec.BackfillSubUIDs[entry.rec.BackfillSubIndex]
+ cur := entry.rec.BackfillSubCursor
+ pendingForUID := make(map[string]library.ItemMetadata, len(buckets.subscribedByUID[uid]))
+ for _, item := range buckets.subscribedByUID[uid] {
+ pendingForUID[strings.TrimSpace(item.RawID)] = item
+ }
+
+ entry.rec.BackfillPhase = backfillPhaseSubscribedTimeline
+ entry.rec.ActiveItemKey = ""
+ entry.rec.ActiveTitle = sanitizeQueueText("查询已订阅微博列表 · " + uid)
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ stepCtx, stepCancel := context.WithCancel(site.WithAutomaticRequests(ctx, "cache_queue"))
+ entry.rt.stepCancel = stepCancel
+ m.mu.Unlock()
+
+ pageNum, sinceID := weibo.ParseCursor(cur)
+ pg, fetchErr := m.b.weibo.GetUserPosts(stepCtx, weibo.UserPostsRequest{
+ UID: uid,
+ Page: pageNum,
+ SinceID: sinceID,
+ Feature: weibo.FeatureAll,
+ StreamOptions: weibo.StreamSelectOptions{
+ PreferredCodec: m.b.preferredWeiboCodec(),
+ MaxResolution: m.b.currentWeiboMaxResolution(),
+ },
+ })
+ if fetchErr == nil && pg.UncertainEmpty {
+ fetchErr = &site.Error{
+ Site: site.Weibo,
+ Kind: site.ErrKindRiskControl,
+ Message: firstNonEmpty(pg.UncertainReason, "微博返回空列表,可能被拦截或登录已失效"),
+ }
+ }
+
+ m.mu.Lock()
+ stepCancel()
+ entry.rt.stepCancel = nil
+ if entry.rec.Status != CacheQueueRunning || ctx.Err() != nil {
+ m.mu.Unlock()
+ return
+ }
+ if fetchErr != nil {
+ kind := site.KindOf(fetchErr)
+ if kind == site.ErrKindAuthRequired {
+ m.mu.Unlock()
+ m.pauseForSite(site.Weibo, "auth_required", "微博登录已失效,重新登录后自动继续")
+ return
+ }
+ if isBackoffOrQuotaKind(kind) {
+ rec := m.enterWaitingBackoffLocked(entry, site.Weibo, kind)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+ // Account unavailable/schema/network on timeline: skip remaining pages for this UID
+ // so unmatched items automatically fall back to Tier C2 statuses/show, while strictly
+ // pacing the next Weibo JSON API request under slow API intervals (40–150s).
+ entry.rec.BackfillSubIndex++
+ entry.rec.BackfillSubCursor = ""
+ rec := m.scheduleSlowAPIWaitLocked(entry, backfillPhaseSubscribedTimeline, "跳过异常博主,等待下一次微博列表检查", false)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+
+ var matched []backfillMatchedItem
+ matchedCount := 0
+ for _, post := range pg.Posts {
+ meta, ok := pendingForUID[strings.TrimSpace(post.Mid)]
+ if !ok {
+ continue
+ }
+ delete(pendingForUID, strings.TrimSpace(post.Mid))
+ overrides, remoteLinks := buildWeiboOverridesFromPost(post)
+ matched = append(matched, backfillMatchedItem{
+ itemKey: meta.ItemKey,
+ title: trimQueueSummaryTitle(firstNonEmpty(meta.Title, meta.Text, post.Text, meta.RawID)),
+ overrides: overrides,
+ remoteLinks: remoteLinks,
+ })
+ matchedCount++
+ }
+
+ nextCur := ""
+ if pg.HasMore && !pg.BottomTipsVisible {
+ nextCur = weibo.FormatCursor(pg.NextPage, pg.NextSinceID)
+ }
+ uidDone := !pg.HasMore || pg.BottomTipsVisible || nextCur == "" || nextCur == cur || len(pendingForUID) == 0
+
+ if matchedCount > 0 {
+ entry.rt.backfillMatched = matched
+ entry.rt.backfillPendingCursor = nextCur
+ entry.rt.backfillPendingUIDDone = uidDone
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ m.saveLoggedLocked("backfill_sub_matched")
+ rec := entry.rec
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+
+ if uidDone {
+ entry.rec.BackfillSubIndex++
+ entry.rec.BackfillSubCursor = ""
+ } else {
+ entry.rec.BackfillSubCursor = sanitizeQueueCursor(nextCur)
+ }
+ // Next step calls a Weibo JSON API (mymblog or statuses/show), so strictly pace at 40–150s.
+ rec := m.scheduleSlowAPIWaitLocked(entry, backfillPhaseSubscribedTimeline, "正在按已订阅博主列表匹配历史条目", false)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+
+ // --- Tier C2: Fallback per-item GetPost (statuses/show) under strict Weibo slow pacing & 100/h quota ---
+ var remaining []library.ItemMetadata
+ remaining = append(remaining, buckets.fallbackDetail...)
+ for _, uid := range buckets.subscribedUIDs {
+ remaining = append(remaining, buckets.subscribedByUID[uid]...)
+ }
+ if len(remaining) == 0 {
+ rec := m.completeBackfillLocked(entry)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ if m.b.events != nil {
+ m.b.events.PublishSite(EventLibraryChanged, string(site.Weibo), "backfill:completed")
+ }
+ return
+ }
+
+ if blocked, _ := m.siteBackoffOrQuotaEnd(site.Weibo, m.clock.Now()); blocked {
+ kind := site.ErrKindBackoff
+ if m.b.subs != nil && !m.b.subs.CanUseSiteQuotaTokens(string(site.Weibo), 1) {
+ kind = site.ErrKindQuota
+ }
+ rec := m.enterWaitingBackoffLocked(entry, site.Weibo, kind)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+
+ item := remaining[0]
+ title := trimQueueSummaryTitle(firstNonEmpty(item.Title, item.Text, item.RawID))
+ entry.rec.BackfillPhase = backfillPhaseFallbackDetail
+ entry.rec.ActiveItemKey = item.ItemKey
+ entry.rec.ActiveTitle = sanitizeQueueText(title)
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ stepCtx, stepCancel := context.WithCancel(site.WithAutomaticRequests(ctx, "cache_queue"))
+ entry.rt.stepCancel = stepCancel
+ m.mu.Unlock()
+
+ postOpt := weibo.PostOptions{
+ StreamOptions: weibo.StreamSelectOptions{
+ PreferredCodec: m.b.preferredWeiboCodec(),
+ MaxResolution: m.b.currentWeiboMaxResolution(),
+ },
+ }
+ post, getErr := m.b.weibo.GetPost(stepCtx, item.RawID, postOpt)
+
+ var backfillRes download.WeiboBackfillResult
+ var backfillErr error
+ var didCache bool
+ if getErr == nil && post != nil && !post.Unavailable {
+ overrides, remoteLinks := buildWeiboOverridesFromPost(*post)
+ backfillRes, backfillErr = m.b.dl.BackfillWeiboNoWMCompanions(
+ stepCtx,
+ item.ItemKey,
+ m.b.weibo.MediaTransport(),
+ overrides,
+ func(meta library.ItemMetadata) (library.ItemMetadata, bool) {
+ return cleanLegacyInlineLinksInItem(meta, remoteLinks)
+ },
+ )
+ if backfillErr == nil && (backfillRes.AddedCompanions > 0 || backfillRes.LinksCleaned) {
+ didCache = true
+ }
+ }
+
+ m.mu.Lock()
+ stepCancel()
+ entry.rt.stepCancel = nil
+ if entry.rec.Status != CacheQueueRunning || ctx.Err() != nil {
+ m.mu.Unlock()
+ return
+ }
+ opErr := getErr
+ if opErr == nil {
+ opErr = backfillErr
+ }
+ if opErr != nil {
+ kind := site.KindOf(opErr)
+ if kind == site.ErrKindAuthRequired {
+ m.mu.Unlock()
+ m.pauseForSite(site.Weibo, "auth_required", "微博登录已失效,重新登录后自动继续")
+ return
+ }
+ if isBackoffOrQuotaKind(kind) {
+ rec := m.enterWaitingBackoffLocked(entry, site.Weibo, kind)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+ if isBackfillStorageError(opErr) {
+ entry.rec.Status = CacheQueuePaused
+ entry.rec.PauseReason = "storage"
+ entry.rec.StopReason = "存储空间不足或写入失败,已暂停补全"
+ entry.rec.NextRunAt = ""
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ m.saveLoggedLocked("backfill_storage_pause")
+ rec := entry.rec
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+ // Post deleted / unavailable / forbidden: skip without modifying local files!
+ m.markBackfillProcessedLocked(entry, item.ItemKey)
+ entry.rec.SkippedCount++
+ } else if post == nil || post.Unavailable {
+ m.markBackfillProcessedLocked(entry, item.ItemKey)
+ entry.rec.SkippedCount++
+ } else {
+ m.markBackfillProcessedLocked(entry, item.ItemKey)
+ if didCache {
+ entry.rec.CachedCount++
+ m.appendBackfillRecentLocked(entry, item.ItemKey, title, m.nowRFC3339())
+ } else {
+ entry.rec.SkippedCount++
+ }
+ }
+
+ var rec cacheQueueRecord
+ if len(remaining) <= 1 {
+ rec = m.completeBackfillLocked(entry)
+ } else {
+ rec = m.scheduleSlowAPIWaitLocked(entry, backfillPhaseFallbackDetail, "等待下一条", didCache)
+ }
+ m.mu.Unlock()
+ if didCache && m.b.events != nil {
+ m.b.events.PublishSite(EventLibraryChanged, string(site.Weibo), item.ItemKey)
+ }
+ m.notifyState(rec)
+}
diff --git a/internal/service/backfill_and_force_recache_test.go b/internal/service/backfill_and_force_recache_test.go
new file mode 100644
index 0000000..044277c
--- /dev/null
+++ b/internal/service/backfill_and_force_recache_test.go
@@ -0,0 +1,1132 @@
+package service
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "image"
+ "image/color"
+ "image/jpeg"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/chialecode/trace/internal/appdirs"
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/site"
+ "github.com/chialecode/trace/internal/site/bilibili"
+ "github.com/chialecode/trace/internal/site/weibo"
+ "github.com/chialecode/trace/internal/subscription"
+)
+
+func makeServiceTestJPEG(t *testing.T, w, h int, c color.RGBA) []byte {
+ t.Helper()
+ img := image.NewRGBA(image.Rect(0, 0, w, h))
+ for y := 0; y < h; y++ {
+ for x := 0; x < w; x++ {
+ img.SetRGBA(x, y, c)
+ }
+ }
+ var buf bytes.Buffer
+ if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 90}); err != nil {
+ t.Fatalf("jpeg.Encode: %v", err)
+ }
+ return buf.Bytes()
+}
+
+type serviceRoundTripFunc func(*http.Request) (*http.Response, error)
+
+func (f serviceRoundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
+
+func seedWeiboStaticItemForBackfill(t *testing.T, b *Backend, uid, mid, picID string, imgBytes []byte, stdVer int, via *library.ItemVia, text string, extraMedia []library.MediaFile, pages []library.NotePageRecord) library.ItemMetadata {
+ t.Helper()
+ subDir := "posts"
+ if via != nil && via.Reason == library.ViaForward {
+ subDir = "forwards"
+ }
+ itemDir := filepath.Join(b.GetSettings().CacheDir, "weibo", uid, subDir, mid)
+ if err := os.MkdirAll(itemDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ var media []library.MediaFile
+ var notePages []library.NotePageRecord
+ var assetIDs []string
+ if len(imgBytes) > 0 {
+ mf := writeVerifiedLocalFile(t, itemDir, "images/01.jpg", imgBytes, "image", 48, 36, 0)
+ media = append(media, mf)
+ notePages = []library.NotePageRecord{{Index: 1, Kind: "image", Image: "images/01.jpg", MediaID: picID}}
+ if picID != "" {
+ assetIDs = []string{picID}
+ }
+ }
+ if len(extraMedia) > 0 {
+ media = append(media, extraMedia...)
+ }
+ if len(pages) > 0 {
+ notePages = pages
+ }
+ if text == "" {
+ text = "微博历史测试 " + mid
+ }
+ saved, err := b.lib.SaveItem(itemDir, library.ItemMetadata{
+ Site: "weibo",
+ Kind: "dynamic",
+ ID: mid,
+ RawID: mid,
+ Title: text,
+ Text: text,
+ PubTs: 1700000000,
+ Status: "complete",
+ CacheStandardVersion: stdVer,
+ Author: library.ItemAuthor{Site: "weibo", UID: uid, Name: "合成博主"},
+ Via: via,
+ AssetIDs: assetIDs,
+ Media: media,
+ NotePages: notePages,
+ })
+ if err != nil {
+ t.Fatalf("SaveItem %s: %v", mid, err)
+ }
+ return saved
+}
+
+func TestBackfillSummaryZeroNetworkAndCounts(t *testing.T) {
+ loc := testLocations(t)
+ b, err := NewBackend(Options{
+ Locations: loc,
+ Desktop: NewMockDesktop(),
+ DisableBgWorkers: true,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = b.Close() }()
+
+ if _, err := b.subs.Create("合成博主", "", []subscription.AccountRef{
+ {Site: "weibo", UID: "100001", Name: "合成博主"},
+ }, subscription.SubRules{}); err != nil {
+ t.Fatal(err)
+ }
+
+ jpg := makeServiceTestJPEG(t, 40, 30, color.RGBA{R: 180, G: 70, B: 40, A: 255})
+
+ // 1. Missing NoWM + has AssetIDs -> FastCDN candidate.
+ seedWeiboStaticItemForBackfill(t, b, "100001", "5093000000000001", "001fastA", jpg, 2, nil, "", nil, nil)
+ // 2. Missing NoWM + no AssetIDs + subscribed author -> Subscribed candidate.
+ seedWeiboStaticItemForBackfill(t, b, "100001", "5093000000000002", "", jpg, 2, nil, "", nil, nil)
+ // 3. Missing NoWM + no AssetIDs + forward -> Fallback detail candidate.
+ seedWeiboStaticItemForBackfill(t, b, "100001", "5093000000000003", "", jpg, 2, &library.ItemVia{Reason: library.ViaForward, Site: "weibo", UID: "100001"}, "", nil, nil)
+ // 4. Text-only legacy inline URL -> LegacyLinks candidate.
+ seedWeiboStaticItemForBackfill(t, b, "100001", "5093000000000004", "", nil, 2, nil, "查看公告 (https://example.com/post/4)", nil, nil)
+ // 5. GIF-only -> excluded.
+ gifDir := filepath.Join(b.GetSettings().CacheDir, "weibo", "100001", "posts", "5093000000000005")
+ gifMF := writeVerifiedLocalFile(t, gifDir, "images/01.gif", []byte("GIF89a123456"), "image", 16, 16, 0)
+ if _, err := b.lib.SaveItem(gifDir, library.ItemMetadata{
+ Site: "weibo", Kind: "dynamic", ID: "5093000000000005", RawID: "5093000000000005",
+ Status: "complete", CacheStandardVersion: 0,
+ Author: library.ItemAuthor{Site: "weibo", UID: "100001", Name: "合成博主"},
+ Media: []library.MediaFile{gifMF},
+ NotePages: []library.NotePageRecord{{Index: 1, Kind: "image", Image: "images/01.gif", GIF: true}},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ // 6. Already at WeiboCacheStandardVersion = 3 -> excluded.
+ seedWeiboStaticItemForBackfill(t, b, "100001", "5093000000000006", "006done", jpg, library.WeiboCacheStandardVersion, nil, "", nil, nil)
+ // 7. Archived snapshot -> excluded.
+ archDir := filepath.Join(b.GetSettings().CacheDir, "weibo", "100001", "posts", "5093000000000001__v1-1700000001")
+ archMF := writeVerifiedLocalFile(t, archDir, "images/01.jpg", jpg, "image", 40, 30, 0)
+ if _, err := b.lib.SaveItem(archDir, library.ItemMetadata{
+ Site: "weibo", Kind: "dynamic", ID: "5093000000000001__v1-1700000001", RawID: "5093000000000001__v1-1700000001",
+ Status: "complete", CacheStandardVersion: 2, ArchivedOf: "weibo:dynamic:5093000000000001",
+ Author: library.ItemAuthor{Site: "weibo", UID: "100001", Name: "合成博主"},
+ Media: []library.MediaFile{archMF},
+ NotePages: []library.NotePageRecord{{Index: 1, Kind: "image", Image: "images/01.jpg"}},
+ }); err != nil {
+ t.Fatal(err)
+ }
+
+ // Zero login, zero network!
+ sum, err := b.BackfillSummary()
+ if err != nil {
+ t.Fatalf("BackfillSummary: %v", err)
+ }
+ if sum.WeiboMissingNoWM != 3 || sum.WeiboLegacyLinks != 1 || sum.WeiboFastCDNCandidates != 1 ||
+ sum.WeiboSubscribedCount != 1 || sum.WeiboFallbackDetailCount != 1 || sum.TotalItems != 4 {
+ t.Fatalf("unexpected BackfillSummary(on): %+v", sum)
+ }
+
+ // Disable WeiboRemoveWatermark -> only legacy link item remains.
+ cur := b.GetSettings()
+ cur.WeiboRemoveWatermark = false
+ if _, err := b.UpdateSettings(cur); err != nil {
+ t.Fatal(err)
+ }
+ sumOff, err := b.BackfillSummary()
+ if err != nil {
+ t.Fatalf("BackfillSummary(off): %v", err)
+ }
+ if sumOff.WeiboMissingNoWM != 0 || sumOff.WeiboLegacyLinks != 1 || sumOff.TotalItems != 1 {
+ t.Fatalf("unexpected BackfillSummary(off): %+v", sumOff)
+ }
+}
+
+func TestFullCacheLinkageWeiboNoWMAndLegacyLinks(t *testing.T) {
+ clock := newFakeQueueClock(time.Date(2026, 11, 26, 8, 0, 0, 0, time.UTC))
+ b := newBatchTestBackend(t, clock)
+
+ jpg := makeServiceTestJPEG(t, 40, 30, color.RGBA{R: 120, G: 90, B: 200, A: 255})
+ saved := seedWeiboStaticItemForBackfill(t, b, "100001", "5094000000000001", "001linkPic", jpg, 2, nil, "图文联动测试", nil, nil)
+
+ post := weibo.Post{
+ Mid: "5094000000000001",
+ Text: "图文联动测试",
+ CreatedAt: 1700000000,
+ Author: weibo.AuthorSummary{UID: "100001", ScreenName: "合成博主"},
+ Images: []weibo.ImageAsset{
+ {
+ Index: 1,
+ PicID: "001linkPic",
+ Kind: weibo.MediaKindImage,
+ URL: "https://wx1.sinaimg.cn/large/001linkPic.jpg",
+ WatermarkFreeURL: "https://wx1.sinaimg.cn/oslarge/001linkPic.jpg",
+ Width: 40,
+ Height: 30,
+ },
+ },
+ }
+
+ // 1. Local v2 missing NN_nowm + remote post provides WatermarkFreeURL -> inspectEnqueue (0 extra statuses/show calls!).
+ res := b.inspectWeiboCachedPost(post, saved, "full_cache")
+ if res.action != inspectEnqueue {
+ t.Fatalf("expected inspectEnqueue for Weibo missing NoWM companion, got %+v", res)
+ }
+
+ // 2. Once stamped with WeiboCacheStandardVersion = 3 -> inspectSkipNoOp.
+ savedV3 := saved
+ savedV3.CacheStandardVersion = library.WeiboCacheStandardVersion
+ resV3 := b.inspectWeiboCachedPost(post, savedV3, "full_cache")
+ if resV3.action != inspectSkipNoOp {
+ t.Fatalf("expected inspectSkipNoOp for v3 item, got %+v", resV3)
+ }
+
+ // 3. Pre-DEC-073 inline URL item -> silently migrated offline without touching media!
+ legacySaved := seedWeiboStaticItemForBackfill(t, b, "100001", "5094000000000002", "", nil, 2, nil, "请查看 原文链接 (https://example.com/article/2)", nil, nil)
+ legacyPost := weibo.Post{
+ Mid: "5094000000000002",
+ Text: "请查看 原文链接",
+ Links: []site.TextLink{{Label: "原文链接", URL: "https://example.com/article/2"}},
+ CreatedAt: 1700000000,
+ Author: weibo.AuthorSummary{UID: "100001", ScreenName: "合成博主"},
+ }
+ resLegacy := b.inspectWeiboCachedPost(legacyPost, legacySaved, "full_cache")
+ if resLegacy.action != inspectSkipNoOp {
+ t.Fatalf("expected inspectSkipNoOp after offline legacy link upgrade, got %+v", resLegacy)
+ }
+ upgraded, ok, err := b.lib.GetItem(legacySaved.ItemKey)
+ if err != nil || !ok {
+ t.Fatalf("GetItem upgraded legacy: ok=%v err=%v", ok, err)
+ }
+ if strings.Contains(upgraded.Text, "https://example.com") || len(upgraded.Links) != 1 || upgraded.Links[0].URL != "https://example.com/article/2" {
+ t.Fatalf("legacy inline link was not cleanly migrated offline: text=%q links=%+v", upgraded.Text, upgraded.Links)
+ }
+}
+
+func TestWeiboBackfillQueueThreeTierFastCDNQuotaAndRestartRecovery(t *testing.T) {
+ orig1 := makeServiceTestJPEG(t, 44, 34, color.RGBA{R: 200, G: 60, B: 40, A: 255})
+ nowm1 := makeServiceTestJPEG(t, 30, 22, color.RGBA{R: 30, G: 160, B: 220, A: 255})
+ nowmC1 := makeServiceTestJPEG(t, 32, 24, color.RGBA{R: 60, G: 190, B: 90, A: 255})
+ nowmC2 := makeServiceTestJPEG(t, 28, 20, color.RGBA{R: 180, G: 90, B: 220, A: 255})
+
+ var (
+ mymblogHits atomic.Int32
+ showHits atomic.Int32
+ cdnHits atomic.Int32
+ show429 atomic.Bool
+ )
+
+ const (
+ uidSub = "100001"
+ midA = "5095000000000001"
+ midB1 = "5095000000000002"
+ midB2 = "5095000000000003"
+ midB3 = "5095000000000004"
+ midC1a = "5095000000000005"
+ midC1b = "5095000000000006"
+ midC2 = "5095000000000007"
+ )
+
+ wbSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ switch r.URL.Path {
+ case "/ajax/setting/getBasicInfo":
+ _, _ = w.Write([]byte(`{"ok":1,"data":{"screen_name":"合成博主"}}`))
+ case "/ajax/profile/info":
+ _, _ = w.Write([]byte(`{"ok":1,"data":{"user":{"idstr":"100001","screen_name":"合成博主","statuses_count":20}}}`))
+ case "/ajax/statuses/mymblog":
+ mymblogHits.Add(1)
+ m1, _ := weibo.MidToMblogID(midC1a)
+ m2, _ := weibo.MidToMblogID(midC1b)
+ _, _ = w.Write([]byte(fmt.Sprintf(`{
+ "ok": 1,
+ "data": {
+ "since_id": "",
+ "bottom_tips_visible": true,
+ "bottom_tips_text": "仅展示最近半年微博",
+ "list": [
+ {
+ "idstr": %q, "mblogid": %q, "created_at": "Sat Nov 21 15:00:00 +0800 2026",
+ "text_raw": "订阅批量匹配A",
+ "user": {"idstr": "100001", "screen_name": "合成博主"},
+ "pic_ids": ["picC1a"],
+ "pic_infos": {"picC1a": {"pic_id": "picC1a", "type": "pic", "largest": {"url": "https://wx1.sinaimg.cn/large/picC1a.jpg", "width": 44, "height": 34}}}
+ },
+ {
+ "idstr": %q, "mblogid": %q, "created_at": "Sat Nov 21 14:00:00 +0800 2026",
+ "text_raw": "订阅批量匹配B",
+ "user": {"idstr": "100001", "screen_name": "合成博主"},
+ "pic_ids": ["picC1b"],
+ "pic_infos": {"picC1b": {"pic_id": "picC1b", "type": "pic", "largest": {"url": "https://wx1.sinaimg.cn/large/picC1b.jpg", "width": 44, "height": 34}}}
+ }
+ ]
+ }
+ }`, midC1a, m1, midC1b, m2)))
+ case "/ajax/statuses/show":
+ showHits.Add(1)
+ if show429.Load() {
+ w.WriteHeader(http.StatusTooManyRequests)
+ _, _ = w.Write([]byte(`{"ok":0,"msg":"rate limited"}`))
+ return
+ }
+ mC2, _ := weibo.MidToMblogID(midC2)
+ _, _ = w.Write([]byte(fmt.Sprintf(`{
+ "ok": 1,
+ "idstr": %q, "mblogid": %q, "created_at": "Sat Nov 21 13:00:00 +0800 2026",
+ "text_raw": "兜底详情补全",
+ "user": {"idstr": "100001", "screen_name": "合成博主"},
+ "pic_ids": ["picC2"],
+ "pic_infos": {"picC2": {"pic_id": "picC2", "type": "pic", "largest": {"url": "https://wx1.sinaimg.cn/large/picC2.jpg", "width": 44, "height": 34}}}
+ }`, midC2, mC2)))
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ defer wbSrv.Close()
+
+ cdnRT := serviceRoundTripFunc(func(req *http.Request) (*http.Response, error) {
+ cdnHits.Add(1)
+ var body []byte
+ switch {
+ case strings.Contains(req.URL.Path, "/oslarge/picFast"):
+ body = nowm1
+ case strings.Contains(req.URL.Path, "/oslarge/picC1"):
+ body = nowmC1
+ case strings.Contains(req.URL.Path, "/oslarge/picC2"):
+ body = nowmC2
+ default:
+ return &http.Response{
+ StatusCode: http.StatusNotFound,
+ Header: http.Header{"Content-Type": []string{"text/plain"}},
+ Body: io.NopCloser(strings.NewReader("404")),
+ }, nil
+ }
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ ContentLength: int64(len(body)),
+ Header: http.Header{"Content-Type": []string{"image/jpeg"}},
+ Body: io.NopCloser(bytes.NewReader(body)),
+ }, nil
+ })
+
+ makeLoc := func(name string) appdirs.Locations {
+ tmp := t.TempDir()
+ l, err := appdirs.ResolveWithOptions(appdirs.Options{
+ Channel: "dev",
+ ForceMode: "portable",
+ DataDir: filepath.Join(tmp, name+"-data"),
+ CacheDir: filepath.Join(tmp, name+"-cache"),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ return l
+ }
+
+ biliSrv := newTestBiliServer(t)
+ defer biliSrv.Close()
+
+ makeBackend := func(l appdirs.Locations, clk *fakeQueueClock) *Backend {
+ b, err := NewBackend(Options{
+ Locations: l,
+ Desktop: NewMockDesktop(),
+ DisableBgWorkers: true,
+ CacheQueueClock: clk,
+ CacheQueueRand: func(n int) int { return n / 2 },
+ CacheQueuePacing: &CacheQueuePacing{
+ ItemMinDelay: 40 * time.Second,
+ ItemMaxDelay: 60 * time.Second,
+ FastCDNMinDelay: 2 * time.Second,
+ FastCDNMaxDelay: 5 * time.Second,
+ LongRestMinItems: 2,
+ LongRestMaxItems: 2,
+ LongRestMinDelay: 10 * time.Minute,
+ LongRestMaxDelay: 15 * time.Minute,
+ BackoffCoolMinDelay: 10 * time.Minute,
+ BackoffCoolMaxDelay: 10 * time.Minute,
+ StartupMinDelay: 0,
+ StartupMaxDelay: 0,
+ },
+ BilibiliOpts: bilibili.ClientOptions{
+ Endpoints: bilibili.Endpoints{
+ APIBase: biliSrv.URL,
+ PassportBase: biliSrv.URL,
+ WWWBase: biliSrv.URL,
+ SpaceBase: biliSrv.URL,
+ DynamicBase: biliSrv.URL,
+ LiveAPIBase: biliSrv.URL,
+ LiveWebBase: biliSrv.URL,
+ },
+ PacingInterval: time.Millisecond,
+ AllowLocalhost: true,
+ },
+ WeiboOpts: weibo.ClientOptions{
+ Endpoints: weibo.Endpoints{
+ PCBasicInfo: wbSrv.URL + "/ajax/setting/getBasicInfo",
+ ProfileInfo: wbSrv.URL + "/ajax/profile/info",
+ StatusesMyMblog: wbSrv.URL + "/ajax/statuses/mymblog",
+ StatusesShow: wbSrv.URL + "/ajax/statuses/show",
+ },
+ MinInterval: -1,
+ JitterMax: -1,
+ AllowLocalhost: true,
+ },
+ })
+ if err != nil {
+ t.Fatalf("NewBackend: %v", err)
+ }
+ b.dl.SetMediaTransportWrap(func(_ http.RoundTripper) http.RoundTripper { return cdnRT })
+ return b
+ }
+
+ // ---- PART 1: Tier A (offline) + Tier B (3 pure CDN items > LongRestMinItems=2) under EXHAUSTED 100/h Weibo API quota! ----
+ loc1 := makeLoc("part1")
+ clock1 := newFakeQueueClock(time.Now().UTC())
+ b1 := makeBackend(loc1, clock1)
+ b1Closed := false
+ defer func() {
+ if !b1Closed {
+ _ = b1.Close()
+ }
+ }()
+ ctx := context.Background()
+ // Log in ONLY to Bilibili so HasAnyLogin() is true while Weibo remains LOGGED OUT!
+ if _, err := b1.ImportCookie(ctx, "SESSDATA=s; bili_jct=j; DedeUserID=778899", ""); err != nil {
+ t.Fatalf("ImportCookie bilibili: %v", err)
+ }
+
+ // Exhaust Weibo 100/h JSON API quota completely before starting Tier A + Tier B!
+ if !b1.subs.ConsumeSiteQuotaTokens("weibo", subscription.DefaultWeiboHourlyQuota) {
+ t.Fatal("failed to exhaust Weibo hourly quota")
+ }
+ if b1.subs.CanUseSiteQuotaTokens("weibo", 1) {
+ t.Fatal("expected Weibo hourly quota to be exhausted")
+ }
+
+ seedWeiboStaticItemForBackfill(t, b1, uidSub, midA, "", nil, 2, nil, "旧格式 (https://example.com/a)", nil, nil)
+ seedWeiboStaticItemForBackfill(t, b1, uidSub, midB1, "picFast1", orig1, 2, nil, "", nil, nil)
+ seedWeiboStaticItemForBackfill(t, b1, uidSub, midB2, "picFast2", orig1, 2, nil, "", nil, nil)
+ seedWeiboStaticItemForBackfill(t, b1, uidSub, midB3, "picFast3", orig1, 2, nil, "", nil, nil)
+
+ // Start backfill WITHOUT even logging into Weibo (Tier A + Tier B require 0 login & 0 API quota!).
+ b1.queue.Start(ctx)
+ task1, err := b1.StartWeiboBackfill(ctx)
+ if err != nil {
+ t.Fatalf("StartWeiboBackfill(Tier A+B): %v", err)
+ }
+ if task1.Kind != CacheQueueKindWeiboBackfill || task1.BackfillTotal != 4 {
+ t.Fatalf("unexpected backfill task: %+v", task1)
+ }
+
+ deadline := time.Now().Add(8 * time.Second)
+ for {
+ list := b1.ListCacheQueue()
+ if len(list) == 1 && list[0].Status == CacheQueueCompleted {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("timed out waiting for Tier A+B backfill; queues=%+v", list)
+ }
+ if _, ok := clock1.AdvanceToNextTimer(); !ok {
+ time.Sleep(15 * time.Millisecond)
+ }
+ }
+
+ if mymblogHits.Load() != 0 || showHits.Load() != 0 {
+ t.Fatalf("Tier A+B must make ZERO Weibo API calls, got mymblog=%d show=%d", mymblogHits.Load(), showHits.Load())
+ }
+ if cdnHits.Load() != 3 {
+ t.Fatalf("expected 3 CDN hits for 3 Tier B items, got %d", cdnHits.Load())
+ }
+ // Verify every non-zero timer scheduled during Tier A+B was strictly in [2s, 5s] (NO 40s+, NO 10m long rest!).
+ fastWaits := 0
+ for _, d := range clock1.History() {
+ if d == 0 {
+ continue
+ }
+ if d < 2*time.Second || d > 5*time.Second {
+ t.Fatalf("Tier B scheduled non-fast delay %v (history=%v); must stay 2-5s without long rest", d, clock1.History())
+ }
+ fastWaits++
+ }
+ if fastWaits < 2 {
+ t.Fatalf("expected at least 2 fast 2-5s CDN pacing waits across 3 Tier B items, got %d (history=%v)", fastWaits, clock1.History())
+ }
+
+ afterA, ok, _ := b1.lib.GetItem("weibo:dynamic:" + midA)
+ if !ok || strings.Contains(afterA.Text, "https://example.com") || len(afterA.Links) != 1 || afterA.CacheStandardVersion != library.WeiboCacheStandardVersion {
+ t.Fatalf("Tier A item not properly upgraded: %+v", afterA)
+ }
+ for _, mid := range []string{midB1, midB2, midB3} {
+ it, ok, _ := b1.lib.GetItem("weibo:dynamic:" + mid)
+ if !ok || it.CacheStandardVersion != library.WeiboCacheStandardVersion || len(it.NotePages) != 1 || it.NotePages[0].NoWatermark != "images/01_nowm.jpg" {
+ t.Fatalf("Tier B item %s not properly backfilled: %+v", mid, it)
+ }
+ gotOrig, _ := os.ReadFile(filepath.Join(it.ItemDir, "images", "01.jpg"))
+ if !bytes.Equal(gotOrig, orig1) {
+ t.Fatalf("Tier B item %s primary image was altered!", mid)
+ }
+ }
+ if _, err := b1.RemoveFinishedCacheQueues(); err != nil {
+ t.Fatal(err)
+ }
+ _ = b1.Close()
+ b1Closed = true
+
+ // ---- PART 2: Tier C1 (subscribed mymblog batch) + Tier C2 (statuses/show fallback) + 429 pause + restart recovery! ----
+ loc2 := makeLoc("part2")
+ clock2 := newFakeQueueClock(time.Now().UTC())
+ b2 := makeBackend(loc2, clock2)
+ b2Closed := false
+ defer func() {
+ if !b2Closed {
+ _ = b2.Close()
+ }
+ }()
+ if _, err := b2.LoginWithCookie(ctx, "weibo", "SUB=SYNTH_SUB_BF_C; SUBP=SYNTH_SUBP_BF_C", ""); err != nil {
+ t.Fatalf("LoginWithCookie: %v", err)
+ }
+ if _, err := b2.subs.Create("合成博主", "", []subscription.AccountRef{{Site: "weibo", UID: uidSub, Name: "合成博主"}}, subscription.SubRules{}); err != nil {
+ t.Fatal(err)
+ }
+
+ seedWeiboStaticItemForBackfill(t, b2, uidSub, midC1a, "", orig1, 2, nil, "", nil, nil)
+ seedWeiboStaticItemForBackfill(t, b2, uidSub, midC1b, "", orig1, 2, nil, "", nil, nil)
+ seedWeiboStaticItemForBackfill(t, b2, uidSub, midC2, "", orig1, 2, &library.ItemVia{Reason: library.ViaForward, Site: "weibo", UID: uidSub}, "", nil, nil)
+
+ show429.Store(true)
+ b2.queue.Start(ctx)
+ if _, err := b2.StartWeiboBackfill(ctx); err != nil {
+ t.Fatalf("StartWeiboBackfill(Tier C): %v", err)
+ }
+
+ deadline = time.Now().Add(8 * time.Second)
+ for {
+ list := b2.ListCacheQueue()
+ if len(list) == 1 && list[0].Status == CacheQueueWaitingBackoff {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("timed out waiting for Tier C2 429 waiting_backoff; queues=%+v", list)
+ }
+ if _, ok := clock2.AdvanceToNextTimer(); !ok {
+ time.Sleep(15 * time.Millisecond)
+ }
+ }
+
+ if mymblogHits.Load() != 1 {
+ t.Fatalf("expected 1 mymblog batch call for Tier C1, got %d", mymblogHits.Load())
+ }
+ for _, mid := range []string{midC1a, midC1b} {
+ it, ok, _ := b2.lib.GetItem("weibo:dynamic:" + mid)
+ if !ok || it.CacheStandardVersion != library.WeiboCacheStandardVersion || it.NotePages[0].NoWatermark != "images/01_nowm.jpg" {
+ t.Fatalf("Tier C1 item %s should already be backfilled before C2 429: %+v", mid, it)
+ }
+ }
+
+ rawQueueJSON, err := os.ReadFile(filepath.Join(loc2.DataDir, "cache-queue.json"))
+ if err != nil {
+ t.Fatalf("read cache-queue.json: %v", err)
+ }
+ var qDoc struct {
+ Version int `json:"version"`
+ }
+ if err := json.Unmarshal(rawQueueJSON, &qDoc); err != nil || qDoc.Version != 3 {
+ t.Fatalf("cache-queue.json version = %d (err=%v), want 3", qDoc.Version, err)
+ }
+ if strings.Contains(string(rawQueueJSON), "http://") || strings.Contains(string(rawQueueJSON), "https://") || strings.Contains(string(rawQueueJSON), "SYNTH_SUB") {
+ t.Fatalf("cache-queue.json leaked URL or secret: %s", string(rawQueueJSON))
+ }
+
+ // Simulate app restart! Close b2, reopen b3 past backoff with 429 cleared.
+ _ = b2.Close()
+ b2Closed = true
+ show429.Store(false)
+ clock3 := newFakeQueueClock(time.Now().UTC().Add(6 * time.Hour))
+ b3 := makeBackend(loc2, clock3)
+ defer func() { _ = b3.Close() }()
+ b3.queue.Start(ctx)
+
+ deadline = time.Now().Add(8 * time.Second)
+ for {
+ list := b3.ListCacheQueue()
+ if len(list) == 1 && list[0].Status == CacheQueueCompleted {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("timed out waiting for resumed Tier C2 backfill after restart; queues=%+v", list)
+ }
+ if _, ok := clock3.AdvanceToNextTimer(); !ok {
+ time.Sleep(15 * time.Millisecond)
+ }
+ }
+
+ afterC2, ok, _ := b3.lib.GetItem("weibo:dynamic:" + midC2)
+ if !ok || afterC2.CacheStandardVersion != library.WeiboCacheStandardVersion || afterC2.NotePages[0].NoWatermark != "images/01_nowm.jpg" {
+ t.Fatalf("Tier C2 item %s not completed after restart: %+v", midC2, afterC2)
+ }
+ if mymblogHits.Load() != 1 {
+ t.Fatalf("mymblog was unexpectedly re-called after restart: hits=%d", mymblogHits.Load())
+ }
+ finalSum, err := b3.BackfillSummary()
+ if err != nil || finalSum.TotalItems != 0 {
+ t.Fatalf("expected BackfillSummary TotalItems=0 after full completion, got %+v (err=%v)", finalSum, err)
+ }
+}
+
+func TestServiceForceRecacheItemOverwriteAndGuards(t *testing.T) {
+ v1Img := makeServiceTestJPEG(t, 40, 30, color.RGBA{R: 220, G: 50, B: 50, A: 255})
+ v2Img := makeServiceTestJPEG(t, 44, 34, color.RGBA{R: 40, G: 180, B: 220, A: 255})
+ v2NoWM := makeServiceTestJPEG(t, 28, 20, color.RGBA{R: 50, G: 210, B: 100, A: 255})
+
+ const mid = "5096000000000001"
+ mblogID, _ := weibo.MidToMblogID(mid)
+
+ var (
+ mu sync.RWMutex
+ deleted bool
+ )
+
+ wbSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ switch r.URL.Path {
+ case "/ajax/setting/getBasicInfo":
+ _, _ = w.Write([]byte(`{"ok":1,"data":{"screen_name":"强制重下号"}}`))
+ case "/ajax/profile/info":
+ _, _ = w.Write([]byte(`{"ok":1,"data":{"user":{"idstr":"100001","screen_name":"强制重下号"}}}`))
+ case "/ajax/statuses/show":
+ mu.RLock()
+ isDel := deleted
+ mu.RUnlock()
+ if isDel {
+ _, _ = w.Write([]byte(`{"ok":0,"msg":"该微博已被作者删除"}`))
+ return
+ }
+ _, _ = w.Write([]byte(fmt.Sprintf(`{
+ "ok": 1,
+ "idstr": %q, "mblogid": %q, "created_at": "Sat Nov 21 15:00:00 +0800 2026",
+ "text_raw": "强制重下微博",
+ "user": {"idstr": "100001", "screen_name": "强制重下号"},
+ "pic_ids": ["forcePic1"],
+ "pic_infos": {"forcePic1": {"pic_id": "forcePic1", "type": "pic", "largest": {"url": "https://wx1.sinaimg.cn/large/forcePic1.jpg", "width": 44, "height": 34}}}
+ }`, mid, mblogID)))
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ defer wbSrv.Close()
+
+ cdnRT := serviceRoundTripFunc(func(req *http.Request) (*http.Response, error) {
+ var body []byte
+ switch req.URL.Path {
+ case "/large/forcePic1.jpg":
+ body = v2Img
+ case "/oslarge/forcePic1.jpg":
+ body = v2NoWM
+ default:
+ return &http.Response{StatusCode: http.StatusNotFound, Body: io.NopCloser(strings.NewReader("404"))}, nil
+ }
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ ContentLength: int64(len(body)),
+ Header: http.Header{"Content-Type": []string{"image/jpeg"}},
+ Body: io.NopCloser(bytes.NewReader(body)),
+ }, nil
+ })
+
+ loc := testLocations(t)
+ b, err := NewBackend(Options{
+ Locations: loc,
+ Desktop: NewMockDesktop(),
+ DisableBgWorkers: true,
+ WeiboOpts: weibo.ClientOptions{
+ Endpoints: weibo.Endpoints{
+ PCBasicInfo: wbSrv.URL + "/ajax/setting/getBasicInfo",
+ ProfileInfo: wbSrv.URL + "/ajax/profile/info",
+ StatusesShow: wbSrv.URL + "/ajax/statuses/show",
+ },
+ MinInterval: -1,
+ JitterMax: -1,
+ AllowLocalhost: true,
+ },
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = b.Close() }()
+ b.dl.SetMediaTransportWrap(func(_ http.RoundTripper) http.RoundTripper { return cdnRT })
+ if err := b.dl.Start(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+
+ ctx := context.Background()
+ if _, err := b.LoginWithCookie(ctx, "weibo", "SUB=SYNTH_SUB_FORCE; SUBP=SYNTH_SUBP_FORCE", ""); err != nil {
+ t.Fatal(err)
+ }
+
+ // Reject archived snapshot & live item.
+ archDir := filepath.Join(b.GetSettings().CacheDir, "weibo", "100001", "posts", mid+"__v1-1700000001")
+ archMF := writeVerifiedLocalFile(t, archDir, "images/01.jpg", v1Img, "image", 40, 30, 0)
+ arch, err := b.lib.SaveItem(archDir, library.ItemMetadata{
+ Site: "weibo", Kind: "dynamic", ID: mid + "__v1-1700000001", RawID: mid + "__v1-1700000001",
+ Status: "complete", ArchivedOf: "weibo:dynamic:" + mid,
+ Media: []library.MediaFile{archMF},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := b.ForceRecacheItem(ctx, arch.ItemKey); err == nil {
+ t.Fatal("ForceRecacheItem must reject archived snapshots")
+ }
+
+ liveDir := filepath.Join(b.GetSettings().CacheDir, "bilibili", "20001", "lives", "9001")
+ if err := os.MkdirAll(liveDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ liveItem, err := b.lib.SaveItem(liveDir, library.ItemMetadata{
+ Site: "bilibili", Kind: "live", ID: "9001", RawID: "9001", Status: "complete",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := b.ForceRecacheItem(ctx, liveItem.ItemKey); err == nil {
+ t.Fatal("ForceRecacheItem must reject live recordings")
+ }
+
+ // Seed V1 Weibo item, force-recache -> overwrites with V2 primary + companion!
+ saved := seedWeiboStaticItemForBackfill(t, b, "100001", mid, "forcePic1", v1Img, 2, nil, "强制重下微博", nil, nil)
+ task, err := b.ForceRecacheItem(ctx, saved.ItemKey)
+ if err != nil {
+ t.Fatalf("ForceRecacheItem: %v", err)
+ }
+ if err := b.dl.WaitTasks(ctx, task.TaskID); err != nil {
+ t.Fatalf("WaitTasks ForceRecacheItem: %v", err)
+ }
+ gotPrimary, _ := os.ReadFile(filepath.Join(saved.ItemDir, "images", "01.jpg"))
+ gotNoWM, _ := os.ReadFile(filepath.Join(saved.ItemDir, "images", "01_nowm.jpg"))
+ if !bytes.Equal(gotPrimary, v2Img) || !bytes.Equal(gotNoWM, v2NoWM) {
+ sumGot := sha256.Sum256(gotPrimary)
+ sumWant := sha256.Sum256(v2Img)
+ t.Fatalf("ForceRecacheItem did not overwrite local files: got=%s want=%s nowmLen=%d",
+ hex.EncodeToString(sumGot[:]), hex.EncodeToString(sumWant[:]), len(gotNoWM))
+ }
+
+ // Remote deleted -> ForceRecacheItem refuses and leaves V2 local files untouched!
+ mu.Lock()
+ deleted = true
+ mu.Unlock()
+ if _, err := b.ForceRecacheItem(ctx, saved.ItemKey); err == nil {
+ t.Fatal("ForceRecacheItem should fail when remote post is deleted")
+ }
+ stillPrimary, _ := os.ReadFile(filepath.Join(saved.ItemDir, "images", "01.jpg"))
+ stillNoWM, _ := os.ReadFile(filepath.Join(saved.ItemDir, "images", "01_nowm.jpg"))
+ if !bytes.Equal(stillPrimary, v2Img) || !bytes.Equal(stillNoWM, v2NoWM) {
+ t.Fatal("local files were damaged when ForceRecacheItem hit deleted remote post")
+ }
+}
+
+func TestBackfillTierC1MultiPageMissAndErrorUseSlowAPIPacing(t *testing.T) {
+ orig1 := makeServiceTestJPEG(t, 40, 30, color.RGBA{R: 200, G: 60, B: 40, A: 255})
+ nowm1 := makeServiceTestJPEG(t, 28, 20, color.RGBA{R: 30, G: 160, B: 220, A: 255})
+
+ const (
+ uidErr = "100001" // returns non-backoff unavailable error -> must slow-pace before next UID
+ uidOK = "100002" // 2 miss pages, match on page 3
+ midHit = "5097000000000003"
+ )
+
+ var mymblogPageHits atomic.Int32
+ wbSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ switch r.URL.Path {
+ case "/ajax/setting/getBasicInfo":
+ _, _ = w.Write([]byte(`{"ok":1,"data":{"screen_name":"慢速回归号"}}`))
+ case "/ajax/profile/info":
+ _, _ = w.Write([]byte(`{"ok":1,"data":{"user":{"idstr":"100009","screen_name":"慢速回归号"}}}`))
+ case "/ajax/statuses/mymblog":
+ uid := r.URL.Query().Get("uid")
+ page := r.URL.Query().Get("page")
+ mymblogPageHits.Add(1)
+ if uid == uidErr {
+ // Non-backoff unavailable error.
+ _, _ = w.Write([]byte(`{"ok":0,"msg":"用户不存在"}`))
+ return
+ }
+ switch page {
+ case "", "1":
+ m, _ := weibo.MidToMblogID("5097000000000091")
+ _, _ = w.Write([]byte(fmt.Sprintf(`{"ok":1,"data":{"since_id":"cur_p2","list":[{"idstr":"5097000000000091","mblogid":%q,"created_at":"Sat Nov 21 15:00:00 +0800 2026","text_raw":"未命中页1","user":{"idstr":"100002","screen_name":"博主2"}}]}}`, m)))
+ case "2":
+ m, _ := weibo.MidToMblogID("5097000000000092")
+ _, _ = w.Write([]byte(fmt.Sprintf(`{"ok":1,"data":{"since_id":"cur_p3","list":[{"idstr":"5097000000000092","mblogid":%q,"created_at":"Sat Nov 21 14:00:00 +0800 2026","text_raw":"未命中页2","user":{"idstr":"100002","screen_name":"博主2"}}]}}`, m)))
+ default:
+ m, _ := weibo.MidToMblogID(midHit)
+ _, _ = w.Write([]byte(fmt.Sprintf(`{
+ "ok":1,
+ "data":{
+ "since_id":"",
+ "bottom_tips_visible":true,
+ "list":[{
+ "idstr":%q,"mblogid":%q,"created_at":"Sat Nov 21 13:00:00 +0800 2026","text_raw":"命中页3",
+ "user":{"idstr":"100002","screen_name":"博主2"},
+ "pic_ids":["picSlowHit"],
+ "pic_infos":{"picSlowHit":{"pic_id":"picSlowHit","type":"pic","largest":{"url":"https://wx1.sinaimg.cn/large/picSlowHit.jpg","width":40,"height":30}}}
+ }]
+ }
+ }`, midHit, m)))
+ }
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ defer wbSrv.Close()
+
+ cdnRT := serviceRoundTripFunc(func(req *http.Request) (*http.Response, error) {
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ ContentLength: int64(len(nowm1)),
+ Header: http.Header{"Content-Type": []string{"image/jpeg"}},
+ Body: io.NopCloser(bytes.NewReader(nowm1)),
+ }, nil
+ })
+
+ clock := newFakeQueueClock(time.Now().UTC())
+ b, err := NewBackend(Options{
+ Locations: testLocations(t),
+ Desktop: NewMockDesktop(),
+ DisableBgWorkers: true,
+ CacheQueueClock: clock,
+ CacheQueueRand: func(n int) int { return n / 2 },
+ CacheQueuePacing: &CacheQueuePacing{
+ ItemMinDelay: 40 * time.Second,
+ ItemMaxDelay: 60 * time.Second,
+ FastCDNMinDelay: 2 * time.Second,
+ FastCDNMaxDelay: 5 * time.Second,
+ LongRestMinItems: 20,
+ LongRestMaxItems: 20,
+ LongRestMinDelay: 10 * time.Minute,
+ LongRestMaxDelay: 15 * time.Minute,
+ BackoffCoolMinDelay: 10 * time.Minute,
+ BackoffCoolMaxDelay: 10 * time.Minute,
+ StartupMinDelay: 0,
+ StartupMaxDelay: 0,
+ },
+ WeiboOpts: weibo.ClientOptions{
+ Endpoints: weibo.Endpoints{
+ PCBasicInfo: wbSrv.URL + "/ajax/setting/getBasicInfo",
+ ProfileInfo: wbSrv.URL + "/ajax/profile/info",
+ StatusesMyMblog: wbSrv.URL + "/ajax/statuses/mymblog",
+ StatusesShow: wbSrv.URL + "/ajax/statuses/show",
+ },
+ MinInterval: -1,
+ JitterMax: -1,
+ AllowLocalhost: true,
+ },
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = b.Close() }()
+ b.dl.SetMediaTransportWrap(func(_ http.RoundTripper) http.RoundTripper { return cdnRT })
+
+ ctx := context.Background()
+ if _, err := b.LoginWithCookie(ctx, "weibo", "SUB=SYNTH_SUB_SLOW; SUBP=SYNTH_SUBP_SLOW", ""); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := b.subs.Create("双博主订阅", "", []subscription.AccountRef{
+ {Site: "weibo", UID: uidErr, Name: "博主1"},
+ {Site: "weibo", UID: uidOK, Name: "博主2"},
+ }, subscription.SubRules{}); err != nil {
+ t.Fatal(err)
+ }
+
+ // Seed 1 item for uidErr (will fail mymblog & skip to uidOK, then fall back to C2 statuses/show 404)
+ // and 1 item for uidOK (matched on page 3 after 2 miss pages).
+ seedWeiboStaticItemForBackfill(t, b, uidErr, "5097000000000001", "", orig1, 2, nil, "", nil, nil)
+ seedWeiboStaticItemForBackfill(t, b, uidOK, midHit, "", orig1, 2, nil, "", nil, nil)
+
+ b.queue.Start(ctx)
+ if _, err := b.StartWeiboBackfill(ctx); err != nil {
+ t.Fatal(err)
+ }
+
+ deadline := time.Now().Add(8 * time.Second)
+ for {
+ list := b.ListCacheQueue()
+ if len(list) == 1 && list[0].Status == CacheQueueCompleted {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("timed out waiting for Tier C1 slow-pacing test; queues=%+v", list)
+ }
+ if _, ok := clock.AdvanceToNextTimer(); !ok {
+ time.Sleep(15 * time.Millisecond)
+ }
+ }
+
+ if mymblogPageHits.Load() != 4 {
+ t.Fatalf("expected 4 mymblog hits (1 error + 2 misses + 1 hit), got %d", mymblogPageHits.Load())
+ }
+ // Every scheduled timer in this Tier C1+C2 run (error skip, 2 miss pages, post-drain transition to C2)
+ // MUST be in slow API pacing [40s, 60s], NEVER 2–5s pure CDN pacing!
+ slowWaits := 0
+ for _, d := range clock.History() {
+ if d == 0 {
+ continue
+ }
+ if d >= 2*time.Second && d <= 5*time.Second {
+ t.Fatalf("Tier C1 API paging wrongly used fast 2-5s CDN delay %v (history=%v)", d, clock.History())
+ }
+ if d >= 40*time.Second && d <= 60*time.Second {
+ slowWaits++
+ }
+ }
+ if slowWaits < 4 {
+ t.Fatalf("expected >=4 slow API waits (error skip + 2 miss pages + post-drain), got %d (history=%v)", slowWaits, clock.History())
+ }
+}
+
+func TestBackfillStorageErrorPausesQueueAndPreservesPendingItem(t *testing.T) {
+ orig1 := makeServiceTestJPEG(t, 40, 30, color.RGBA{R: 180, G: 70, B: 40, A: 255})
+ nowm1 := makeServiceTestJPEG(t, 28, 20, color.RGBA{R: 40, G: 180, B: 220, A: 255})
+
+ biliSrv := newTestBiliServer(t)
+ defer biliSrv.Close()
+ clock := newFakeQueueClock(time.Now().UTC())
+ b, err := NewBackend(Options{
+ Locations: testLocations(t),
+ Desktop: NewMockDesktop(),
+ DisableBgWorkers: true,
+ CacheQueueClock: clock,
+ CacheQueueRand: func(int) int { return 0 },
+ BilibiliOpts: bilibili.ClientOptions{
+ Endpoints: bilibili.Endpoints{
+ APIBase: biliSrv.URL,
+ PassportBase: biliSrv.URL,
+ WWWBase: biliSrv.URL,
+ SpaceBase: biliSrv.URL,
+ DynamicBase: biliSrv.URL,
+ LiveAPIBase: biliSrv.URL,
+ LiveWebBase: biliSrv.URL,
+ },
+ PacingInterval: time.Millisecond,
+ AllowLocalhost: true,
+ },
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = b.Close() }()
+ var saved library.ItemMetadata
+ b.dl.SetMediaTransportWrap(func(_ http.RoundTripper) http.RoundTripper {
+ return serviceRoundTripFunc(func(req *http.Request) (*http.Response, error) {
+ // Replace item.json with a non-empty directory after GetItem succeeded so
+ // WriteJSONAtomic's os.Rename(tmp, item.json) deterministically returns
+ // *os.LinkError on BOTH Linux (EISDIR) and Windows (ERROR_ACCESS_DENIED),
+ // exercising both rollbackMoved() and *os.LinkError -> site.ErrKindStorage!
+ manifestPath := filepath.Join(saved.ItemDir, "item.json")
+ _ = os.Remove(manifestPath)
+ _ = os.MkdirAll(filepath.Join(manifestPath, "nested"), 0o700)
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ ContentLength: int64(len(nowm1)),
+ Header: http.Header{"Content-Type": []string{"image/jpeg"}},
+ Body: io.NopCloser(bytes.NewReader(nowm1)),
+ }, nil
+ })
+ })
+
+ ctx := context.Background()
+ if _, err := b.ImportCookie(ctx, "SESSDATA=s; bili_jct=j; DedeUserID=778899", ""); err != nil {
+ t.Fatal(err)
+ }
+
+ saved = seedWeiboStaticItemForBackfill(t, b, "100001", "5098000000000001", "picDiskErr", orig1, 2, nil, "", nil, nil)
+
+ b.queue.Start(ctx)
+ if _, err := b.StartWeiboBackfill(ctx); err != nil {
+ t.Fatal(err)
+ }
+
+ deadline := time.Now().Add(6 * time.Second)
+ for {
+ list := b.ListCacheQueue()
+ if len(list) == 1 && list[0].Status == CacheQueuePaused {
+ if list[0].PauseReason != "storage" {
+ t.Fatalf("expected PauseReason=storage, got %+v", list[0])
+ }
+ if list[0].SkippedCount != 0 {
+ t.Fatalf("storage error must NOT skip pending item: %+v", list[0])
+ }
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("timed out waiting for storage pause; queues=%+v", list)
+ }
+ if _, ok := clock.AdvanceToNextTimer(); !ok {
+ time.Sleep(15 * time.Millisecond)
+ }
+ }
+
+ // Verify item was NOT recorded in ProcessedKeys so resuming after storage fix still processes it!
+ b.queue.mu.Lock()
+ var processed []string
+ if len(b.queue.tasks) == 1 {
+ processed = append([]string(nil), b.queue.tasks[0].rec.ProcessedKeys...)
+ }
+ b.queue.mu.Unlock()
+ if len(processed) != 0 {
+ t.Fatalf("storage error must NOT mark item in ProcessedKeys: %v", processed)
+ }
+ // Also verify rollbackMoved() cleaned up images/01_nowm.jpg when SaveItem failed with *os.LinkError!
+ if _, stErr := os.Lstat(filepath.Join(saved.ItemDir, "images", "01_nowm.jpg")); !os.IsNotExist(stErr) {
+ t.Fatalf("companion images/01_nowm.jpg was not rolled back after SaveItem storage failure: err=%v", stErr)
+ }
+}
+
+func TestFullCacheLegacyLinkInspectionNoDeadlockWithSyncSubscriber(t *testing.T) {
+ const (
+ uid = "100001"
+ mid = "5099000000000010"
+ )
+ mblogID, _ := weibo.MidToMblogID(mid)
+
+ wbSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ switch r.URL.Path {
+ case "/ajax/setting/getBasicInfo":
+ _, _ = w.Write([]byte(`{"ok":1,"data":{"screen_name":"防死锁测试号"}}`))
+ case "/ajax/profile/info":
+ _, _ = w.Write([]byte(`{"ok":1,"data":{"user":{"idstr":"100001","screen_name":"防死锁测试号","statuses_count":1}}}`))
+ case "/ajax/statuses/mymblog":
+ _, _ = w.Write([]byte(fmt.Sprintf(`{
+ "ok":1,
+ "data":{
+ "since_id":"",
+ "list":[{
+ "idstr":%q,"mblogid":%q,"created_at":"Sat Nov 21 15:00:00 +0800 2026",
+ "text":"请看 原文链接",
+ "text_raw":"请看 原文链接",
+ "user":{"idstr":"100001","screen_name":"防死锁测试号"}
+ }]
+ }
+ }`, mid, mblogID)))
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ defer wbSrv.Close()
+
+ clock := newFakeQueueClock(time.Now().UTC())
+ b, err := NewBackend(Options{
+ Locations: testLocations(t),
+ Desktop: NewMockDesktop(),
+ DisableBgWorkers: true,
+ CacheQueueClock: clock,
+ CacheQueueRand: func(int) int { return 0 },
+ WeiboOpts: weibo.ClientOptions{
+ Endpoints: weibo.Endpoints{
+ PCBasicInfo: wbSrv.URL + "/ajax/setting/getBasicInfo",
+ ProfileInfo: wbSrv.URL + "/ajax/profile/info",
+ StatusesMyMblog: wbSrv.URL + "/ajax/statuses/mymblog",
+ StatusesShow: wbSrv.URL + "/ajax/statuses/show",
+ },
+ MinInterval: -1,
+ JitterMax: -1,
+ AllowLocalhost: true,
+ },
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = b.Close() }()
+
+ ctx := context.Background()
+ if _, err := b.LoginWithCookie(ctx, "weibo", "SUB=SYNTH_SUB_DL; SUBP=SYNTH_SUBP_DL", ""); err != nil {
+ t.Fatal(err)
+ }
+ saved := seedWeiboStaticItemForBackfill(t, b, uid, mid, "", nil, 2, nil, "请看 原文链接 (https://example.com/no-deadlock)", nil, nil)
+
+ // Attach a synchronous EventLibraryChanged subscriber that calls b.ListCacheQueue()
+ // (which acquires cacheQueueManager.mu). If EventLibraryChanged were published while
+ // holding cacheQueueManager.mu, this would immediately self-deadlock!
+ var syncCallbackCalled atomic.Int32
+ unsub := b.SubscribeEvents(func(ev Event) {
+ if ev.Type == EventLibraryChanged && ev.Message == saved.ItemKey {
+ _ = b.ListCacheQueue()
+ _, _ = b.FindCacheQueueTask("weibo", uid, "posts")
+ syncCallbackCalled.Add(1)
+ }
+ })
+ defer unsub()
+
+ b.queue.Start(ctx)
+ if _, err := b.EnqueueCacheQueue(ctx, CacheQueueRequest{
+ Site: "weibo",
+ User: uid,
+ UserName: "防死锁测试号",
+ List: "posts",
+ }); err != nil {
+ t.Fatalf("EnqueueCacheQueue: %v", err)
+ }
+
+ deadline := time.Now().Add(6 * time.Second)
+ for {
+ list := b.ListCacheQueue()
+ if len(list) == 1 && list[0].Status == CacheQueueCompleted {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("timed out (potential deadlock!) waiting for Weibo full-cache legacy link sweep; queues=%+v", list)
+ }
+ if _, ok := clock.AdvanceToNextTimer(); !ok {
+ time.Sleep(15 * time.Millisecond)
+ }
+ }
+
+ if syncCallbackCalled.Load() == 0 {
+ t.Fatal("expected synchronous EventLibraryChanged callback to run cleanly after unlocking m.mu")
+ }
+ upgraded, ok, _ := b.lib.GetItem(saved.ItemKey)
+ if !ok || strings.Contains(upgraded.Text, "https://example.com") || len(upgraded.Links) != 1 {
+ t.Fatalf("legacy link item was not upgraded by full-cache sweep: text=%q links=%+v", upgraded.Text, upgraded.Links)
+ }
+}
diff --git a/internal/service/batch_cache.go b/internal/service/batch_cache.go
index 2b5c916..68c0094 100644
--- a/internal/service/batch_cache.go
+++ b/internal/service/batch_cache.go
@@ -92,6 +92,9 @@ func normalizeCacheQueueTarget(rawSite, rawList, rawUser string) (site.ID, strin
if list == "" {
list = "posts"
}
+ if list == CacheQueueListWeiboBackfill {
+ return site.Weibo, CacheQueueListWeiboBackfill, CacheQueueBackfillUser, nil
+ }
if list != "posts" {
return "", "", "", &site.Error{Site: siteID, Kind: site.ErrKindBadRequest, Message: "不支持的微博列表类型"}
}
@@ -124,6 +127,9 @@ func cacheQueueListLabel(siteID, list string) string {
case string(site.Douyin):
return "作品"
case string(site.Weibo):
+ if strings.EqualFold(strings.TrimSpace(list), CacheQueueListWeiboBackfill) {
+ return "历史缓存补全"
+ }
return "微博"
case string(site.X):
return "帖子"
@@ -591,7 +597,7 @@ func (b *Backend) weiboPostQueueCandidate(p weibo.Post) queueCandidate {
var inspectFn func(meta library.ItemMetadata, queueOrigin string) cachedInspectDecision
if !nonOriginal {
inspectFn = func(meta library.ItemMetadata, queueOrigin string) cachedInspectDecision {
- return b.inspectWeiboCachedPost(postCopy, meta, queueOrigin)
+ return b.inspectWeiboCachedPostDeferred(postCopy, meta, queueOrigin)
}
}
return queueCandidate{
diff --git a/internal/service/cache_conflicts.go b/internal/service/cache_conflicts.go
index d39d873..a2c8390 100644
--- a/internal/service/cache_conflicts.go
+++ b/internal/service/cache_conflicts.go
@@ -729,9 +729,10 @@ const (
)
type cachedInspectDecision struct {
- action cachedInspectAction
- conflict cacheConflictRecord
- enqueue func(ctx context.Context) (queueEnqueued, error)
+ action cachedInspectAction
+ conflict cacheConflictRecord
+ enqueue func(ctx context.Context) (queueEnqueued, error)
+ postInspect func()
}
func hasValidLocalCache(meta library.ItemMetadata) bool {
@@ -1086,6 +1087,19 @@ func (b *Backend) inspectDouyinCachedWork(detail douyin.WorkDetail, meta library
// 2. Weibo posts 0-call list inspection.
func (b *Backend) inspectWeiboCachedPost(post weibo.Post, meta library.ItemMetadata, queueOrigin string) cachedInspectDecision {
+ dec := b.inspectWeiboCachedPostDeferred(post, meta, queueOrigin)
+ if dec.postInspect != nil {
+ dec.postInspect()
+ dec.postInspect = nil
+ }
+ return dec
+}
+
+// inspectWeiboCachedPostDeferred performs the pure read-only comparison of a
+// cached Weibo item while deferring any metadata write / synchronous event
+// publication into dec.postInspect so callers holding cacheQueueManager.mu
+// never perform disk/SQLite writes or publish events under the queue lock.
+func (b *Backend) inspectWeiboCachedPostDeferred(post weibo.Post, meta library.ItemMetadata, queueOrigin string) cachedInspectDecision {
if meta.IsArchivedSnapshot() {
return cachedInspectDecision{action: inspectSkipNoOp}
}
@@ -1154,6 +1168,12 @@ func (b *Backend) inspectWeiboCachedPost(post weibo.Post, meta library.ItemMetad
}
}
+ var postInspectFn func()
+ withPostInspect := func(dec cachedInspectDecision) cachedInspectDecision {
+ dec.postInspect = postInspectFn
+ return dec
+ }
+
localSingleVid := meta.DouyinVideo != nil && len(meta.NotePages) == 0
localPages := len(meta.NotePages)
@@ -1203,22 +1223,55 @@ func (b *Backend) inspectWeiboCachedPost(post weibo.Post, meta library.ItemMetad
return makeConflict(ConflictReasonText, "源站微博正文内容已修改")
}
}
- if fullRemoteTextAvailable && !substantiveTextChanged(localBody, post.Text) &&
- b.conflicts != nil && b.conflicts.hasPendingTextConflictForItem(meta.ItemKey) {
- b.reconcileLiveLegacyTextConflict(meta.ItemKey, MapSiteTextLinks(post.Links))
+ if fullRemoteTextAvailable && !substantiveTextChanged(localBody, post.Text) {
+ remoteLinks := MapSiteTextLinks(post.Links)
+ hasPendingTextConflict := b.conflicts != nil && b.conflicts.hasPendingTextConflictForItem(meta.ItemKey)
+ if cleanedMeta, hadLegacy := cleanLegacyInlineLinksInItem(meta, remoteLinks); hadLegacy {
+ if b.weiboRemoveWatermarkEnabled() && !library.WeiboNeedsNoWMBackfill(cleanedMeta, true) &&
+ cleanedMeta.CacheStandardVersion < library.WeiboCacheStandardVersion {
+ cleanedMeta.CacheStandardVersion = library.WeiboCacheStandardVersion
+ }
+ itemKeyCopy := meta.ItemKey
+ linksCopy := append([]TextLinkDTO(nil), remoteLinks...)
+ meta = cleanedMeta
+ postInspectFn = func() {
+ if hasPendingTextConflict {
+ _, _ = b.reconcileLiveLegacyTextConflict(itemKeyCopy, linksCopy)
+ return
+ }
+ if b.lib == nil {
+ return
+ }
+ fresh, ok, gErr := b.lib.GetItem(itemKeyCopy)
+ if gErr != nil || !ok || strings.TrimSpace(fresh.ItemDir) == "" {
+ return
+ }
+ cleaned, stillLegacy := cleanLegacyInlineLinksInItem(fresh, linksCopy)
+ if !stillLegacy {
+ return
+ }
+ if b.weiboRemoveWatermarkEnabled() && !library.WeiboNeedsNoWMBackfill(cleaned, true) &&
+ cleaned.CacheStandardVersion < library.WeiboCacheStandardVersion {
+ cleaned.CacheStandardVersion = library.WeiboCacheStandardVersion
+ }
+ if _, sErr := b.lib.SaveItemMetadataOnly(fresh.ItemDir, cleaned); sErr == nil && b.events != nil {
+ b.events.PublishSite(EventLibraryChanged, string(site.Weibo), itemKeyCopy)
+ }
+ }
+ }
}
}
// (c) Degraded / downgraded checks.
if remoteSingleVid {
if singleVideo.Selected == nil || strings.TrimSpace(singleVideo.Selected.URL) == "" {
- return cachedInspectDecision{action: inspectSkipNoOp}
+ return withPostInspect(cachedInspectDecision{action: inspectSkipNoOp})
}
if meta.DouyinVideo != nil {
localShort := shortEdgePixels(meta.DouyinVideo.Width, meta.DouyinVideo.Height)
remoteShort := firstPositiveInt(singleVideo.Selected.ShortEdge, shortEdgePixels(singleVideo.Selected.Width, singleVideo.Selected.Height))
if localShort > 0 && remoteShort > 0 && remoteShort < localShort {
- return cachedInspectDecision{action: inspectSkipNoOp}
+ return withPostInspect(cachedInspectDecision{action: inspectSkipNoOp})
}
}
}
@@ -1227,30 +1280,62 @@ func (b *Backend) inspectWeiboCachedPost(post weibo.Post, meta library.ItemMetad
if library.NeedsCompletion(meta) {
// Avoid re-downloading when every missing item is a permanently unavailable Sina placeholder GIF and media IDs are unchanged.
if !allMissingAreWeiboUnavailable(meta.Missing) {
- return cachedInspectDecision{action: inspectEnqueue}
+ return withPostInspect(cachedInspectDecision{action: inspectEnqueue})
}
}
if remoteSingleVid && singleVideo.Selected != nil && meta.DouyinVideo != nil {
localShort := shortEdgePixels(meta.DouyinVideo.Width, meta.DouyinVideo.Height)
remoteShort := firstPositiveInt(singleVideo.Selected.ShortEdge, shortEdgePixels(singleVideo.Selected.Width, singleVideo.Selected.Height))
if localShort > 0 && remoteShort > localShort {
- return cachedInspectDecision{action: inspectEnqueue}
+ return withPostInspect(cachedInspectDecision{action: inspectEnqueue})
}
}
for i := 0; i < localPages && i < len(images); i++ {
if images[i].Kind == weibo.MediaKindLivePhoto && strings.TrimSpace(meta.NotePages[i].Motion) == "" {
- return cachedInspectDecision{action: inspectEnqueue}
+ return withPostInspect(cachedInspectDecision{action: inspectEnqueue})
}
}
if post.IsLongText {
localBody := strings.TrimSpace(firstNonEmpty(meta.Text, meta.Desc))
if strings.HasSuffix(localBody, "...展开") || strings.HasSuffix(localBody, "…展开") ||
(post.LongTextFetched && utf8.RuneCountInString(strings.TrimSpace(post.Text)) > utf8.RuneCountInString(localBody)+10) {
- return cachedInspectDecision{action: inspectEnqueue}
+ return withPostInspect(cachedInspectDecision{action: inspectEnqueue})
}
}
+ if b.weiboRemoveWatermarkEnabled() && library.WeiboNeedsNoWMBackfill(meta, true) && weiboImagesHaveWatermarkFreeCandidate(images, meta) {
+ return withPostInspect(cachedInspectDecision{action: inspectEnqueue})
+ }
- return cachedInspectDecision{action: inspectSkipNoOp}
+ return withPostInspect(cachedInspectDecision{action: inspectSkipNoOp})
+}
+
+func weiboImagesHaveWatermarkFreeCandidate(images []weibo.ImageAsset, meta library.ItemMetadata) bool {
+ if len(images) == 0 {
+ return false
+ }
+ for i, img := range images {
+ if img.Kind == weibo.MediaKindGIF || img.Kind == weibo.MediaKindVideo {
+ continue
+ }
+ if strings.TrimSpace(img.WatermarkFreeURL) == "" {
+ continue
+ }
+ if len(meta.NotePages) > 0 {
+ if i >= len(meta.NotePages) {
+ continue
+ }
+ pg := meta.NotePages[i]
+ if strings.TrimSpace(pg.Image) == "" || pg.GIF || strings.EqualFold(pg.Kind, "video") || strings.EqualFold(pg.Kind, "gif") {
+ continue
+ }
+ if strings.TrimSpace(pg.NoWatermark) == "" {
+ return true
+ }
+ } else {
+ return true
+ }
+ }
+ return false
}
func allMissingAreWeiboUnavailable(missing []library.MissingRecord) bool {
diff --git a/internal/service/cache_queue_api.go b/internal/service/cache_queue_api.go
index 4e40746..c6efbfd 100644
--- a/internal/service/cache_queue_api.go
+++ b/internal/service/cache_queue_api.go
@@ -66,6 +66,9 @@ func (b *Backend) EnqueueCacheQueue(ctx context.Context, req CacheQueueRequest)
// queueListLabel names the list; a run a full-cache rule started says so.
func queueListLabel(rec cacheQueueRecord) string {
+ if rec.List == CacheQueueListWeiboBackfill {
+ return "历史缓存补全"
+ }
label := cacheQueueListLabel(rec.Site, rec.List)
if rec.Origin == QueueOriginFullCache {
return "定期全部缓存 · " + label
@@ -74,7 +77,7 @@ func queueListLabel(rec cacheQueueRecord) string {
}
func queueOrigin(o string) string {
- if o == QueueOriginFullCache {
+ if o == QueueOriginFullCache || o == CacheQueueOriginBackfill {
return o
}
return ""
@@ -259,10 +262,12 @@ func (b *Backend) ResumeCacheQueue(id string) (CacheQueueTask, error) {
m.mu.Lock()
var siteID site.ID
var found bool
+ var needLoginCheck bool
for _, e := range m.tasks {
if e.rec.ID == target {
siteID = site.ID(e.rec.Site)
found = true
+ needLoginCheck = !isWeiboBackfillRecord(e.rec) || e.rec.PauseReason == "auth_required"
break
}
}
@@ -271,8 +276,10 @@ func (b *Backend) ResumeCacheQueue(id string) (CacheQueueTask, error) {
return CacheQueueTask{}, &site.Error{Kind: site.ErrKindUnavailable, Message: "未找到该缓存队列任务"}
}
- if err := b.requireSiteLogin(siteID); err != nil {
- return CacheQueueTask{}, err
+ if needLoginCheck {
+ if err := b.requireSiteLogin(siteID); err != nil {
+ return CacheQueueTask{}, err
+ }
}
m.mu.Lock()
diff --git a/internal/service/cache_queue_store.go b/internal/service/cache_queue_store.go
index 4afdf1f..e5b088a 100644
--- a/internal/service/cache_queue_store.go
+++ b/internal/service/cache_queue_store.go
@@ -28,15 +28,26 @@ const (
CacheQueueCompleted = "completed"
CacheQueueStopped = "stopped"
- cacheQueueFileName = "cache-queue.json"
- cacheQueueSchemaVersion = 3
- maxCacheQueueRecentItems = 30
+ cacheQueueFileName = "cache-queue.json"
+ cacheQueueSchemaVersion = 3
+ maxCacheQueueRecentItems = 30
+ CacheQueueListWeiboBackfill = "weibo_backfill"
+ CacheQueueKindWeiboBackfill = "weibo_backfill"
+ CacheQueueOriginBackfill = "backfill"
+ CacheQueueBackfillUser = "all"
+
+ backfillPhaseOfflineLinks = "offline_links"
+ backfillPhaseFastCDN = "fast_cdn"
+ backfillPhaseSubscribedTimeline = "subscribed_timeline"
+ backfillPhaseFallbackDetail = "fallback_detail"
)
// CacheQueuePacing centralizes all conservative anti-risk-control delays and thresholds (Q-017).
type CacheQueuePacing struct {
ItemMinDelay time.Duration
ItemMaxDelay time.Duration
+ FastCDNMinDelay time.Duration
+ FastCDNMaxDelay time.Duration
LongRestMinItems int
LongRestMaxItems int
LongRestMinDelay time.Duration
@@ -47,10 +58,13 @@ type CacheQueuePacing struct {
StartupMaxDelay time.Duration
}
-// DefaultCacheQueuePacing defines the default Q-017 pacing intervals for background list caching.
+// DefaultCacheQueuePacing defines the default Q-017 pacing intervals for background list caching,
+// plus the DEC-079 user-authorized 2–5s fast pacing for pure-CDN /oslarge/ backfill.
var DefaultCacheQueuePacing = CacheQueuePacing{
ItemMinDelay: 40 * time.Second,
ItemMaxDelay: 150 * time.Second,
+ FastCDNMinDelay: 2 * time.Second,
+ FastCDNMaxDelay: 5 * time.Second,
LongRestMinItems: 15,
LongRestMaxItems: 25,
LongRestMinDelay: 10 * time.Minute,
@@ -138,6 +152,9 @@ type CacheQueueTask struct {
AvatarPath string `json:"avatarPath,omitempty"`
List string `json:"list"`
ListLabel string `json:"listLabel"`
+ Kind string `json:"kind,omitempty"`
+ BackfillPhase string `json:"backfillPhase,omitempty"`
+ BackfillTotal int `json:"backfillTotal,omitempty"`
Origin string `json:"origin,omitempty"`
Status string `json:"status"`
StatusText string `json:"statusText"`
@@ -169,7 +186,13 @@ type cacheQueueRecord struct {
UserName string `json:"userName,omitempty"`
AvatarKey string `json:"avatarKey,omitempty"`
List string `json:"list"`
+ Kind string `json:"kind,omitempty"`
Origin string `json:"origin,omitempty"`
+ BackfillPhase string `json:"backfillPhase,omitempty"`
+ BackfillTotal int `json:"backfillTotal,omitempty"`
+ BackfillSubUIDs []string `json:"backfillSubUids,omitempty"`
+ BackfillSubIndex int `json:"backfillSubIndex,omitempty"`
+ BackfillSubCursor string `json:"backfillSubCursor,omitempty"`
Cursor string `json:"cursor,omitempty"`
HasMore bool `json:"hasMore"`
ProcessedKeys []string `json:"processedKeys,omitempty"`
@@ -203,6 +226,9 @@ type cacheQueueRuntime struct {
nextPartEnqueuers []queuePartEnqueuer
resumePendingDownloads bool
stepCancel context.CancelFunc
+ backfillMatched []backfillMatchedItem
+ backfillPendingCursor string
+ backfillPendingUIDDone bool
}
type cacheQueueEntry struct {
@@ -403,9 +429,38 @@ func sanitizeQueueRecord(r cacheQueueRecord) cacheQueueRecord {
r.User = normUser
r.ID = sanitizeCursor(r.ID)
r.UserName = sanitizeQueueText(r.UserName)
- if r.Origin != QueueOriginFullCache {
+ if r.Origin != QueueOriginFullCache && r.Origin != CacheQueueOriginBackfill {
r.Origin = ""
}
+ if r.List == CacheQueueListWeiboBackfill {
+ r.Kind = CacheQueueKindWeiboBackfill
+ switch r.BackfillPhase {
+ case backfillPhaseOfflineLinks, backfillPhaseFastCDN, backfillPhaseSubscribedTimeline, backfillPhaseFallbackDetail:
+ default:
+ r.BackfillPhase = ""
+ }
+ if r.BackfillTotal < 0 {
+ r.BackfillTotal = 0
+ }
+ if r.BackfillSubIndex < 0 {
+ r.BackfillSubIndex = 0
+ }
+ var cleanUIDs []string
+ for _, u := range r.BackfillSubUIDs {
+ if norm, uErr := site.NormalizeUID(site.Weibo, u); uErr == nil && !slices.Contains(cleanUIDs, norm) {
+ cleanUIDs = append(cleanUIDs, norm)
+ }
+ }
+ r.BackfillSubUIDs = cleanUIDs
+ r.BackfillSubCursor = sanitizeQueueCursor(r.BackfillSubCursor)
+ } else {
+ r.Kind = ""
+ r.BackfillPhase = ""
+ r.BackfillTotal = 0
+ r.BackfillSubUIDs = nil
+ r.BackfillSubIndex = 0
+ r.BackfillSubCursor = ""
+ }
if !avatarFileRe.MatchString(r.AvatarKey) {
r.AvatarKey = ""
}
@@ -573,6 +628,21 @@ func (m *cacheQueueManager) pickRestThresholdLocked() int {
return m.randIntInclusiveLocked(m.pacing.LongRestMinItems, m.pacing.LongRestMaxItems)
}
+func (m *cacheQueueManager) fastCDNDelayLocked() time.Duration {
+ minD, maxD := m.pacing.FastCDNMinDelay, m.pacing.FastCDNMaxDelay
+ if minD <= 0 && maxD <= 0 {
+ if m.pacing.ItemMinDelay > 0 && m.pacing.ItemMinDelay < 2*time.Second {
+ minD, maxD = m.pacing.ItemMinDelay, m.pacing.ItemMaxDelay
+ } else {
+ minD, maxD = DefaultCacheQueuePacing.FastCDNMinDelay, DefaultCacheQueuePacing.FastCDNMaxDelay
+ }
+ }
+ if maxD < minD {
+ maxD = minD
+ }
+ return m.randDurationLocked(minD, maxD)
+}
+
func (m *cacheQueueManager) nowRFC3339() string {
return m.clock.Now().UTC().Format(time.RFC3339)
}
@@ -651,6 +721,9 @@ func (m *cacheQueueManager) toDTOLocked(e *cacheQueueEntry) CacheQueueTask {
AvatarPath: avatarPath,
List: rec.List,
ListLabel: queueListLabel(rec),
+ Kind: rec.Kind,
+ BackfillPhase: rec.BackfillPhase,
+ BackfillTotal: rec.BackfillTotal,
Origin: rec.Origin,
Status: rec.Status,
StatusText: m.statusTextLocked(rec),
diff --git a/internal/service/cache_queue_worker.go b/internal/service/cache_queue_worker.go
index 416666b..a289372 100644
--- a/internal/service/cache_queue_worker.go
+++ b/internal/service/cache_queue_worker.go
@@ -49,7 +49,7 @@ func (m *cacheQueueManager) Start(ctx context.Context) {
if e.rec.Status == CacheQueuePaused && e.rec.PauseReason == "user" {
continue
}
- if !loggedIn {
+ if !loggedIn && !isWeiboBackfillRecord(e.rec) {
if e.rec.Status != CacheQueuePaused || e.rec.PauseReason != "auth_required" {
e.rec.Status = CacheQueuePaused
e.rec.PauseReason = "auth_required"
@@ -359,7 +359,7 @@ func (m *cacheQueueManager) selectActiveSiteEntryLocked(siteID site.ID) (*cacheQ
if e.rec.Site != string(siteID) || e.rec.Status != CacheQueueQueued {
continue
}
- if !m.hasSiteLogin(siteID) {
+ if !m.hasSiteLogin(siteID) && !isWeiboBackfillRecord(e.rec) {
e.rec.Status = CacheQueuePaused
e.rec.PauseReason = "auth_required"
e.rec.StopReason = "未登录或登录已失效,重新登录后自动继续"
@@ -434,12 +434,22 @@ func (m *cacheQueueManager) runSiteLoop(ctx context.Context, siteID site.ID) {
continue
}
- if !m.hasSiteLogin(siteID) {
+ isBackfill := isWeiboBackfillRecord(entry.rec)
+ if !isBackfill && !m.hasSiteLogin(siteID) {
m.mu.Unlock()
m.pauseForSite(siteID, "auth_required", "未登录或登录已失效,重新登录后自动继续")
continue
}
- if blocked, _ := m.siteBackoffOrQuotaEnd(siteID, m.clock.Now()); blocked {
+ pureCDNWaiting := isBackfill && entry.rec.Status == CacheQueueWaiting &&
+ (entry.rec.BackfillPhase == backfillPhaseFastCDN || entry.rec.BackfillPhase == backfillPhaseOfflineLinks)
+ if pureCDNWaiting {
+ if inBackoff, _ := m.siteRiskBackoffOnly(siteID, m.clock.Now()); inBackoff {
+ rec := m.enterWaitingBackoffLocked(entry, siteID, site.ErrKindBackoff)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ continue
+ }
+ } else if blocked, _ := m.siteBackoffOrQuotaEnd(siteID, m.clock.Now()); blocked {
kind := site.ErrKindBackoff
if !m.b.subs.CanUseSiteQuotaTokens(string(siteID), 1) {
kind = site.ErrKindQuota
@@ -461,6 +471,11 @@ func (m *cacheQueueManager) runSiteLoop(ctx context.Context, siteID site.ID) {
continue
}
+ if isWeiboBackfillRecord(entry.rec) {
+ m.advanceWeiboBackfillStep(ctx, entry)
+ continue
+ }
+
if !m.hasSiteLogin(siteID) {
m.mu.Unlock()
m.pauseForSite(siteID, "auth_required", "未登录或登录已失效,重新登录后自动继续")
@@ -919,7 +934,15 @@ func (m *cacheQueueManager) advanceCandidateStep(ctx context.Context, siteID sit
skippedAny := false
var conflictNotifications []cacheConflictRecord
+ var postInspectActions []func()
publishConflicts := func() {
+ if len(postInspectActions) > 0 {
+ actions := postInspectActions
+ postInspectActions = nil
+ for _, fn := range actions {
+ fn()
+ }
+ }
if m.b == nil || m.b.events == nil || len(conflictNotifications) == 0 {
return
}
@@ -971,6 +994,9 @@ func (m *cacheQueueManager) advanceCandidateStep(ctx context.Context, siteID sit
}
if localMeta.Status != "failed" && localMeta.Status != "missing_files" && localMeta.Status != "corrupt" {
dec := cand.inspectCached(localMeta, entry.rec.Origin)
+ if dec.postInspect != nil {
+ postInspectActions = append(postInspectActions, dec.postInspect)
+ }
switch dec.action {
case inspectSkipNoOp:
entry.rt.seenKeys[cand.key] = true
diff --git a/internal/service/interfaces.go b/internal/service/interfaces.go
index 0dc390f..0d1e610 100644
--- a/internal/service/interfaces.go
+++ b/internal/service/interfaces.go
@@ -168,6 +168,17 @@ type HistoryService interface {
HistoryThumbPath(name string) (string, error)
}
+// BackfillSummaryDTO summarizes offline-detectable historical cache items that can
+// be upgraded to the latest cache standard with zero network requests (DEC-079).
+type BackfillSummaryDTO struct {
+ WeiboMissingNoWM int `json:"weiboMissingNoWm"`
+ WeiboLegacyLinks int `json:"weiboLegacyLinks"`
+ WeiboFastCDNCandidates int `json:"weiboFastCdnCandidates"`
+ WeiboSubscribedCount int `json:"weiboSubscribedCount"`
+ WeiboFallbackDetailCount int `json:"weiboFallbackDetailCount"`
+ TotalItems int `json:"totalItems"`
+}
+
// CacheService defines download queue, background list cache queue, supplement, and quality upgrade operations.
type CacheService interface {
EnqueueVideoCache(ctx context.Context, req download.VideoEnqueueRequest) ([]download.Task, error)
@@ -177,6 +188,9 @@ type CacheService interface {
CacheWeiboPost(ctx context.Context, mid string, via *library.ItemVia) (download.Task, error)
CacheWeiboVideo(ctx context.Context, oid string) (download.Task, error)
CacheXPost(ctx context.Context, statusID string, via *library.ItemVia) (download.Task, error)
+ ForceRecacheItem(ctx context.Context, itemKey string) (download.Task, error)
+ BackfillSummary() (BackfillSummaryDTO, error)
+ StartWeiboBackfill(ctx context.Context) (CacheQueueTask, error)
ListCacheQueue() []CacheQueueTask
FindCacheQueueTask(siteID, user, list string) (CacheQueueTask, bool)
EnqueueCacheQueue(ctx context.Context, req CacheQueueRequest) (CacheQueueTask, error)
diff --git a/internal/service/library_service.go b/internal/service/library_service.go
index 2c77096..dd73117 100644
--- a/internal/service/library_service.go
+++ b/internal/service/library_service.go
@@ -10,6 +10,8 @@ import (
"github.com/chialecode/trace/internal/library"
"github.com/chialecode/trace/internal/site"
"github.com/chialecode/trace/internal/site/bilibili"
+ "github.com/chialecode/trace/internal/site/douyin"
+ "github.com/chialecode/trace/internal/site/weibo"
"github.com/chialecode/trace/internal/uistate"
)
@@ -98,17 +100,23 @@ func (b *Backend) enqueueDouyinWorkWithPlan(
}
cleanID := strings.TrimSpace(awemeID)
mode := download.ConflictResolutionFromContext(ctx)
+ force := download.ForceOverwriteFromContext(ctx)
plan := explicitPlan
- if plan == nil && mode == "" && b.douyinWorkCache != nil {
+ if plan == nil && mode == "" && !force && b.douyinWorkCache != nil {
if cachedDetail, ok := b.douyinWorkCache.get(cleanID, b.preferredDouyinCodec()); ok {
if built, bErr := b.buildDouyinWorkPlanFromDetail(ctx, cachedDetail, b.currentWorkPlanOptions()); bErr == nil {
plan = &built
}
}
}
- if plan != nil && mode != "" {
+ if plan != nil && (mode != "" || force) {
cp := *plan
- cp.ConflictResolution = mode
+ if mode != "" {
+ cp.ConflictResolution = mode
+ }
+ if force {
+ cp.ForceOverwrite = true
+ }
plan = &cp
}
t, err := b.dl.EnqueueDouyinWork(ctx, download.DouyinWorkEnqueueRequest{
@@ -177,17 +185,23 @@ func (b *Backend) enqueueWeiboPostWithSource(
}
cleanMid := strings.TrimSpace(mid)
mode := download.ConflictResolutionFromContext(ctx)
+ force := download.ForceOverwriteFromContext(ctx)
plan := explicitPlan
- if plan == nil && mode == "" && b.weiboPostCache != nil {
+ if plan == nil && mode == "" && !force && b.weiboPostCache != nil {
if cachedPost, ok := b.weiboPostCache.get(cleanMid, b.preferredWeiboCodec(), b.currentWeiboMaxResolution(), b.weiboRemoveWatermarkEnabled()); ok {
if built, bErr := b.buildWeiboWorkPlanFromPost(cachedPost); bErr == nil {
plan = &built
}
}
}
- if plan != nil && mode != "" {
+ if plan != nil && (mode != "" || force) {
cp := *plan
- cp.ConflictResolution = mode
+ if mode != "" {
+ cp.ConflictResolution = mode
+ }
+ if force {
+ cp.ForceOverwrite = true
+ }
plan = &cp
}
t, err := b.dl.EnqueueWeiboWork(ctx, download.WeiboWorkEnqueueRequest{
@@ -229,17 +243,23 @@ func (b *Backend) enqueueXPostWithSource(
}
cleanID := strings.TrimSpace(statusID)
mode := download.ConflictResolutionFromContext(ctx)
+ force := download.ForceOverwriteFromContext(ctx)
plan := explicitPlan
- if plan == nil && mode == "" && b.xPostCache != nil {
+ if plan == nil && mode == "" && !force && b.xPostCache != nil {
if cachedPost, ok := b.xPostCache.get(cleanID); ok {
if built, bErr := b.buildXWorkPlanFromPost(cachedPost); bErr == nil {
plan = &built
}
}
}
- if plan != nil && mode != "" {
+ if plan != nil && (mode != "" || force) {
cp := *plan
- cp.ConflictResolution = mode
+ if mode != "" {
+ cp.ConflictResolution = mode
+ }
+ if force {
+ cp.ForceOverwrite = true
+ }
plan = &cp
}
t, err := b.dl.EnqueueXWork(ctx, download.XWorkEnqueueRequest{
@@ -256,6 +276,242 @@ func (b *Backend) enqueueXPostWithSource(
return t, nil
}
+// ForceRecacheItem triggers an explicit manual full redownload of an already
+// cached item across all 4 sites (DEC-079). Media is freshly downloaded and
+// verified inside .trace-stage-* without reusing local files, then atomically
+// swapped via .trace-prev-*; if the remote item is deleted, unavailable,
+// degraded, or placeholder-only, ErrRemoteDegradedRefused aborts cleanly and
+// preserves the local files untouched.
+func (b *Backend) ForceRecacheItem(ctx context.Context, itemKey string) (download.Task, error) {
+ if err := b.requireDesktop(); err != nil {
+ return download.Task{}, err
+ }
+ if b.lib == nil || b.dl == nil {
+ return download.Task{}, &site.Error{Kind: site.ErrKindUnavailable, Message: "下载服务尚未初始化"}
+ }
+ cleanKey := strings.TrimSpace(itemKey)
+ if cleanKey == "" {
+ return download.Task{}, &site.Error{Kind: site.ErrKindBadRequest, Message: "条目键不能为空"}
+ }
+ meta, ok, err := b.lib.GetItem(cleanKey)
+ if err != nil {
+ return download.Task{}, err
+ }
+ if !ok {
+ return download.Task{}, &site.Error{Kind: site.ErrKindUnavailable, Message: "未找到该已缓存条目"}
+ }
+ if meta.Kind == "live" {
+ return download.Task{}, &site.Error{Kind: site.ErrKindBadRequest, Message: "直播录像不支持强制重新下载"}
+ }
+ if meta.IsArchivedSnapshot() {
+ return download.Task{}, &site.Error{Kind: site.ErrKindBadRequest, Message: "旧版归档条目不支持强制重新下载"}
+ }
+ siteID, sErr := normalizeExplicitSiteID(meta.Site)
+ if sErr != nil {
+ return download.Task{}, sErr
+ }
+ if err := b.requireSiteLogin(siteID); err != nil {
+ return download.Task{}, err
+ }
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ forceCtx := download.WithForceOverwrite(ctx)
+ localHadMedia := hasValidLocalMedia(meta)
+ var via *library.ItemVia
+ if meta.Via != nil {
+ cp := *meta.Via
+ via = &cp
+ }
+
+ switch siteID {
+ case site.Bilibili:
+ if meta.Kind == "video" {
+ vd, err := b.bili.VideoDetail(forceCtx, meta.RawID)
+ if err != nil {
+ return download.Task{}, wrapDegradedIfRemoteInvalid(err)
+ }
+ if vd.IsUpowerLocked() {
+ return download.Task{}, wrapDegradedIfRemoteInvalid(bilibili.NewUpowerLockedError("/x/web-interface/wbi/view"))
+ }
+ if len(vd.Pages) == 0 {
+ return download.Task{}, fmt.Errorf("%w:源站视频已无可用分P", ErrRemoteDegradedRefused)
+ }
+ if _, pErr := b.bili.PlayURL(forceCtx, vd.BVID, vd.Pages[0].CID, b.bilibiliPlaySelectionOpts()); pErr != nil {
+ return download.Task{}, wrapDegradedIfRemoteInvalid(pErr)
+ }
+ var forMid int64
+ if via != nil && via.Reason == library.ViaCollab {
+ forMid, _ = strconv.ParseInt(strings.TrimSpace(via.UID), 10, 64)
+ }
+ tasks, err := b.EnqueueVideoCache(forceCtx, download.VideoEnqueueRequest{
+ BVID: vd.BVID,
+ Detail: &vd,
+ Source: "manual",
+ ForMid: forMid,
+ })
+ if err != nil {
+ return download.Task{}, wrapDegradedIfRemoteInvalid(err)
+ }
+ if len(tasks) == 0 {
+ return download.Task{}, fmt.Errorf("未创建强制重新下载任务")
+ }
+ return tasks[0], nil
+ }
+
+ dyn, err := b.bili.DynamicDetail(forceCtx, meta.RawID)
+ if err != nil {
+ return download.Task{}, wrapDegradedIfRemoteInvalid(err)
+ }
+ if dyn.Degraded || dyn.Blocked {
+ return download.Task{}, fmt.Errorf("%w:源站动态已不可用或受限", ErrRemoteDegradedRefused)
+ }
+ if hasSnapshotMedia(meta, "orig.json") && dyn.Origin == nil {
+ return download.Task{}, fmt.Errorf("%w:转发原动态已在源站失效", ErrRemoteDegradedRefused)
+ }
+ effImgs, effVids := effectiveBiliDynamicMedia(dyn)
+ if localHadMedia && len(effImgs) == 0 && len(effVids) == 0 {
+ return download.Task{}, fmt.Errorf("%w:源站动态已无有效媒体附件", ErrRemoteDegradedRefused)
+ }
+ return b.EnqueueDynamicCache(forceCtx, download.DynamicEnqueueRequest{
+ DynamicID: dyn.ID,
+ Item: &dyn,
+ Source: "manual",
+ })
+
+ case site.Douyin:
+ detail, err := b.douyin.GetWorkDetail(forceCtx, meta.RawID, douyin.StreamSelectOptions{
+ PreferredCodec: b.preferredDouyinCodec(),
+ })
+ if err != nil {
+ return download.Task{}, wrapDegradedIfRemoteInvalid(err)
+ }
+ if detail == nil || detail.Uncacheable || detail.Kind == douyin.WorkKindUnsupported {
+ reason := "源站作品当前受限或不可缓存"
+ if detail != nil && strings.TrimSpace(detail.UncacheableReason) != "" {
+ reason = detail.UncacheableReason
+ }
+ return download.Task{}, fmt.Errorf("%w:%s", ErrRemoteDegradedRefused, reason)
+ }
+ if localHadMedia {
+ if detail.Kind == douyin.WorkKindNote && len(detail.Pages) == 0 {
+ return download.Task{}, fmt.Errorf("%w:源站图文已无有效页面", ErrRemoteDegradedRefused)
+ }
+ if detail.Kind == douyin.WorkKindVideo && (detail.Video == nil || len(detail.Video.URLs) == 0) {
+ return download.Task{}, fmt.Errorf("%w:源站视频已无可用播放流", ErrRemoteDegradedRefused)
+ }
+ }
+ plan, err := b.buildDouyinWorkPlanFromDetail(forceCtx, detail, b.currentWorkPlanOptions())
+ if err != nil {
+ return download.Task{}, wrapDegradedIfRemoteInvalid(err)
+ }
+ plan.ForceOverwrite = true
+ var forUID, forName string
+ if via != nil && via.Reason == library.ViaCollab {
+ forUID, forName = via.UID, via.Name
+ }
+ return b.enqueueDouyinWorkWithPlan(forceCtx, meta.RawID, "manual", forUID, forName, &plan)
+
+ case site.Weibo:
+ postOpt := weibo.PostOptions{
+ StreamOptions: weibo.StreamSelectOptions{
+ PreferredCodec: b.preferredWeiboCodec(),
+ MaxResolution: b.currentWeiboMaxResolution(),
+ },
+ }
+ if meta.Kind == "video" {
+ oid := meta.RawID
+ if strings.HasPrefix(oid, "1034_") {
+ oid = "1034:" + strings.TrimPrefix(oid, "1034_")
+ }
+ vr, err := b.weibo.GetVideo(forceCtx, oid, postOpt)
+ if err != nil {
+ return download.Task{}, wrapDegradedIfRemoteInvalid(err)
+ }
+ if vr == nil ||
+ (vr.HostPost != nil && vr.HostPost.Unavailable) ||
+ (vr.HostPost == nil && (vr.Video == nil || vr.Video.Selected == nil || strings.TrimSpace(vr.Video.Selected.URL) == "")) {
+ return download.Task{}, fmt.Errorf("%w:源站微博视频已失效", ErrRemoteDegradedRefused)
+ }
+ var plan download.WorkDownloadPlan
+ if vr.HostPost != nil {
+ plan, err = b.buildWeiboWorkPlanFromPost(vr.HostPost)
+ } else {
+ plan, err = b.buildWeiboWorkPlanFromStandaloneVideo(vr)
+ }
+ if err != nil {
+ return download.Task{}, wrapDegradedIfRemoteInvalid(err)
+ }
+ plan.ForceOverwrite = true
+ t, err := b.dl.EnqueueWeiboWork(forceCtx, download.WeiboWorkEnqueueRequest{
+ TargetID: oid,
+ Kind: "video",
+ Source: "manual",
+ Via: via,
+ Plan: &plan,
+ })
+ if err != nil {
+ b.logError("ForceRecacheItem.weibo_video", err)
+ return download.Task{}, err
+ }
+ b.events.PublishSite(EventTaskUpdated, string(site.Weibo), "enqueued:"+t.TargetID)
+ return t, nil
+ }
+ post, err := b.weibo.GetPost(forceCtx, meta.RawID, postOpt)
+ if err != nil {
+ return download.Task{}, wrapDegradedIfRemoteInvalid(err)
+ }
+ if post == nil || post.Unavailable {
+ reason := "源站微博已不可见或已删除"
+ if post != nil && strings.TrimSpace(post.UnavailableReason) != "" {
+ reason = post.UnavailableReason
+ }
+ return download.Task{}, fmt.Errorf("%w:%s", ErrRemoteDegradedRefused, reason)
+ }
+ if post.Retweeted != nil && post.Retweeted.Unavailable && meta.Origin != nil && !meta.Origin.Unavailable {
+ return download.Task{}, fmt.Errorf("%w:源站转发原帖已失效", ErrRemoteDegradedRefused)
+ }
+ imgs, vid := post.EffectiveMedia()
+ if localHadMedia && len(imgs) == 0 && (vid == nil || vid.Selected == nil || strings.TrimSpace(vid.Selected.URL) == "") {
+ return download.Task{}, fmt.Errorf("%w:源站微博已无有效媒体附件", ErrRemoteDegradedRefused)
+ }
+ plan, err := b.buildWeiboWorkPlanFromPost(post)
+ if err != nil {
+ return download.Task{}, wrapDegradedIfRemoteInvalid(err)
+ }
+ plan.ForceOverwrite = true
+ return b.enqueueWeiboPostWithSource(forceCtx, meta.RawID, "manual", via, &plan)
+
+ case site.X:
+ post, err := b.x.GetPost(forceCtx, meta.RawID)
+ if err != nil {
+ return download.Task{}, wrapDegradedIfRemoteInvalid(err)
+ }
+ if post == nil || post.Unavailable || post.IsPreviewDisplay {
+ reason := "源站帖子已不可用或仅展示付费预览"
+ if post != nil && strings.TrimSpace(post.UnavailableReason) != "" {
+ reason = post.UnavailableReason
+ }
+ return download.Task{}, fmt.Errorf("%w:%s", ErrRemoteDegradedRefused, reason)
+ }
+ if post.OriginUnavailable && meta.Origin != nil && !meta.Origin.Unavailable {
+ return download.Task{}, fmt.Errorf("%w:源站引用或转推原帖已失效", ErrRemoteDegradedRefused)
+ }
+ if localHadMedia && !xPostHasValidDownloadableMedia(post) {
+ return download.Task{}, fmt.Errorf("%w:源站帖子已无有效可下载媒体", ErrRemoteDegradedRefused)
+ }
+ plan, err := b.buildXWorkPlanFromPost(post)
+ if err != nil {
+ return download.Task{}, wrapDegradedIfRemoteInvalid(err)
+ }
+ plan.ForceOverwrite = true
+ return b.enqueueXPostWithSource(forceCtx, meta.RawID, "manual", via, &plan)
+
+ default:
+ return download.Task{}, &site.Error{Site: siteID, Kind: site.ErrKindBadRequest, Message: "不支持的站点"}
+ }
+}
+
// CacheSupplement re-downloads missing danmaku/subtitle/cover sidecars for an already cached Bilibili video without re-downloading video/audio.
func (b *Backend) CacheSupplement(ctx context.Context, bvid string) (download.Task, error) {
if err := b.requireDesktop(); err != nil {
diff --git a/internal/ui/app.go b/internal/ui/app.go
index 72cb6f1..bca1ab0 100644
--- a/internal/ui/app.go
+++ b/internal/ui/app.go
@@ -125,6 +125,13 @@ type DeleteConfirmState struct {
DeleteFiles bool
}
+// ForceRecacheConfirmState holds state for the manual force-redownload confirmation modal.
+type ForceRecacheConfirmState struct {
+ Open bool
+ ItemKey string
+ Title string
+}
+
// HomeUpdatedActor is a subscription as a row of the Home panel, with its
// newest cached post under the site filter (DEC-053 ②).
type HomeUpdatedActor struct {
@@ -546,14 +553,16 @@ type App struct {
// parse) and cached count, keyed "site:uid" (DEC-061).
accountWorks map[string]service.AccountWorks
// videoCacheFor is the creator page the open video came from (DEC-061).
- videoCacheFor videoCacheContext
- douyinCacheFor douyinCacheContext
- weiboCacheFor weiboCacheContext
- xCacheFor xCacheContext
- libraryOffset int
- LibraryAuthorMenu bool
- ExpandedItemKey string
- DeleteConfirm DeleteConfirmState
+ videoCacheFor videoCacheContext
+ douyinCacheFor douyinCacheContext
+ weiboCacheFor weiboCacheContext
+ xCacheFor xCacheContext
+ libraryOffset int
+ LibraryAuthorMenu bool
+ ExpandedItemKey string
+ DeleteConfirm DeleteConfirmState
+ ForceRecacheConfirm ForceRecacheConfirmState
+ BackfillSummary service.BackfillSummaryDTO
// Tasks Page
TasksSection string // "downloads" | "queue" | "conflicts" | "live" | "incidents" | "checks" | "transfers"
@@ -860,6 +869,7 @@ func (a *App) handleBackendEvent(ev service.Event) {
case service.EventSettingsChanged:
a.cachedDiagAt = time.Time{}
a.cachedUpdateHistAt = time.Time{}
+ a.refreshBackfillSummary()
case service.EventAccountChanged:
a.cacheStateRev++ // dots read "登录后查看" while signed out
a.cachedDiagAt = time.Time{}
@@ -881,6 +891,7 @@ func (a *App) handleBackendEvent(ev service.Event) {
case service.EventCacheQueueUpdated:
a.cacheStateRev++
a.CacheQueue = a.backend.ListCacheQueue()
+ a.refreshBackfillSummary()
case service.EventCacheConflictsChanged:
a.cacheStateRev++
a.refreshCacheConflicts()
@@ -900,6 +911,7 @@ func (a *App) handleBackendEvent(ev service.Event) {
a.libraryItemsDirty = a.CurrentRoute != RouteLibrary && a.CurrentRoute != RouteLibraryItem
} else {
a.refreshLibraryStatistics()
+ a.refreshBackfillSummary()
a.refreshAccountWorks()
if len(a.FeedItems) == 0 && a.HomeActorFilter == nil {
a.loadInitialFeed()
@@ -951,6 +963,7 @@ func (a *App) RefreshData() {
a.cachedDiagAt = time.Time{}
a.HistoryItems = a.backend.ListHistory()
a.refreshLibraryStatistics()
+ a.refreshBackfillSummary()
if len(a.FeedItems) == 0 {
a.loadInitialFeed()
}
@@ -1176,6 +1189,9 @@ func (a *App) View(c *ui.Context) {
if a.DeleteConfirm.Open {
a.renderDeleteConfirmOverlay(c, w, h)
}
+ if a.ForceRecacheConfirm.Open {
+ a.renderForceRecacheConfirmOverlay(c, w, h)
+ }
if a.RestartConfirmOpen && a.updater != nil {
a.renderRestartConfirmOverlay(c, w, h)
}
diff --git a/internal/ui/backfill_actions.go b/internal/ui/backfill_actions.go
new file mode 100644
index 0000000..b9e04e6
--- /dev/null
+++ b/internal/ui/backfill_actions.go
@@ -0,0 +1,101 @@
+package ui
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/chialecode/trace/internal/service"
+)
+
+func (a *App) refreshBackfillSummary() {
+ if a.backend == nil {
+ a.BackfillSummary = service.BackfillSummaryDTO{}
+ return
+ }
+ if sum, err := a.backend.BackfillSummary(); err == nil {
+ a.BackfillSummary = sum
+ }
+}
+
+func (a *App) activeWeiboBackfillQueue() (service.CacheQueueTask, bool) {
+ for _, q := range a.CacheQueue {
+ if (q.Kind == service.CacheQueueKindWeiboBackfill || q.List == service.CacheQueueListWeiboBackfill) && isUnfinishedCacheQueueStatus(q.Status) {
+ return q, true
+ }
+ }
+ return service.CacheQueueTask{}, false
+}
+
+func (a *App) startWeiboBackfill() {
+ if a.backend == nil {
+ return
+ }
+ backend := a.backend
+ requestGuarded(a, "start-weibo-backfill", nil, func(ctx context.Context) (service.CacheQueueTask, error) {
+ return backend.StartWeiboBackfill(ctx)
+ }, func(task service.CacheQueueTask) {
+ a.CacheQueue = a.backend.ListCacheQueue()
+ a.refreshBackfillSummary()
+ a.BannerInfo = "已启动历史缓存补全队列"
+ if task.ID != "" {
+ a.OpenCacheQueueTask(task.ID)
+ }
+ }, func(err error) {
+ a.showError(err)
+ })
+}
+
+func (a *App) openForceRecacheConfirm(itemKey, title string) {
+ itemKey = strings.TrimSpace(itemKey)
+ if itemKey == "" {
+ return
+ }
+ a.ForceRecacheConfirm = ForceRecacheConfirmState{
+ Open: true,
+ ItemKey: itemKey,
+ Title: strings.TrimSpace(title),
+ }
+}
+
+func (a *App) confirmForceRecache() {
+ if a.backend == nil {
+ return
+ }
+ itemKey := strings.TrimSpace(a.ForceRecacheConfirm.ItemKey)
+ if itemKey == "" {
+ return
+ }
+ backend := a.backend
+ requestGuarded(a, "force-recache:"+itemKey, nil, func(ctx context.Context) (struct{}, error) {
+ _, err := backend.ForceRecacheItem(ctx, itemKey)
+ return struct{}{}, err
+ }, func(struct{}) {
+ a.BannerInfo = "已加入强制重新下载任务"
+ a.RefreshData()
+ }, func(err error) {
+ a.showError(err)
+ })
+}
+
+func formatBackfillSummaryBreakdown(sum service.BackfillSummaryDTO) string {
+ var parts []string
+ if sum.WeiboMissingNoWM > 0 {
+ parts = append(parts, fmt.Sprintf("缺无水印伴侣图 %d 条", sum.WeiboMissingNoWM))
+ }
+ if sum.WeiboLegacyLinks > 0 {
+ parts = append(parts, fmt.Sprintf("旧格式链接 %d 条", sum.WeiboLegacyLinks))
+ }
+ if sum.WeiboFastCDNCandidates > 0 {
+ parts = append(parts, fmt.Sprintf("%d 条可快速直连补齐", sum.WeiboFastCDNCandidates))
+ }
+ return strings.Join(parts, ",")
+}
+
+func formatBackfillSummaryDetail(sum service.BackfillSummaryDTO) string {
+ detail := formatBackfillSummaryBreakdown(sum)
+ if detail == "" {
+ return fmt.Sprintf("发现 %d 条历史微博可补全", sum.TotalItems)
+ }
+ return fmt.Sprintf("发现 %d 条历史微博可补全(%s)", sum.TotalItems, detail)
+}
diff --git a/internal/ui/backfill_and_force_recache_ui_test.go b/internal/ui/backfill_and_force_recache_ui_test.go
new file mode 100644
index 0000000..a97fd71
--- /dev/null
+++ b/internal/ui/backfill_and_force_recache_ui_test.go
@@ -0,0 +1,385 @@
+package ui
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "sync"
+ "testing"
+
+ "github.com/chialecode/trace/internal/download"
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/service"
+ "github.com/chialecode/trace/internal/site/bilibili"
+ "github.com/egoist/mygo/ui"
+)
+
+type backfillAndForceStub struct {
+ service.BackendAPI
+ mu sync.Mutex
+ summary service.BackfillSummaryDTO
+ queue []service.CacheQueueTask
+ startedCalls int
+ forcedKeys []string
+ cachedByKey map[string]library.ItemMetadata
+}
+
+func (s *backfillAndForceStub) BackfillSummary() (service.BackfillSummaryDTO, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.summary, nil
+}
+
+func (s *backfillAndForceStub) ListCacheQueue() []service.CacheQueueTask {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ out := make([]service.CacheQueueTask, len(s.queue))
+ copy(out, s.queue)
+ return out
+}
+
+func (s *backfillAndForceStub) StartWeiboBackfill(_ context.Context) (service.CacheQueueTask, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.startedCalls++
+ task := service.CacheQueueTask{
+ ID: "cq_bf_1",
+ Kind: service.CacheQueueKindWeiboBackfill,
+ Site: "weibo",
+ User: service.CacheQueueBackfillUser,
+ UserName: "历史缓存补全",
+ List: service.CacheQueueListWeiboBackfill,
+ ListLabel: "历史缓存补全",
+ Status: service.CacheQueueRunning,
+ StatusText: "正在补全微博无水印伴侣图",
+ BackfillPhase: "fast_cdn",
+ BackfillTotal: s.summary.TotalItems,
+ CachedCount: 1,
+ }
+ s.queue = []service.CacheQueueTask{task}
+ return task, nil
+}
+
+func (s *backfillAndForceStub) ForceRecacheItem(_ context.Context, itemKey string) (download.Task, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.forcedKeys = append(s.forcedKeys, itemKey)
+ return download.Task{TaskID: "force_" + itemKey, Status: "queued"}, nil
+}
+
+func (s *backfillAndForceStub) GetLibraryItem(itemKey string) (library.ItemMetadata, bool, error) {
+ s.mu.Lock()
+ it, ok := s.cachedByKey[itemKey]
+ s.mu.Unlock()
+ if ok {
+ return it, true, nil
+ }
+ return s.BackendAPI.GetLibraryItem(itemKey)
+}
+
+func (s *backfillAndForceStub) States(keys []string) map[string]library.DotState {
+ out := s.BackendAPI.States(keys)
+ if out == nil {
+ out = make(map[string]library.DotState)
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ for _, k := range keys {
+ if _, ok := s.cachedByKey[k]; ok {
+ out[k] = library.DotState{Dot: "green", Label: "已完整缓存"}
+ }
+ }
+ return out
+}
+
+func TestSettingsStorageAndTasksQueueBackfillUI(t *testing.T) {
+ app, _, cleanup := newTestUIApp(t)
+ defer cleanup()
+ posted := make(chan func(), 32)
+ app.dispatch = func(fn func()) { posted <- fn }
+ drain := func() {
+ for {
+ select {
+ case fn := <-posted:
+ fn()
+ default:
+ return
+ }
+ }
+ }
+
+ seedUIFeed(t, app, 0)
+ stub := &backfillAndForceStub{
+ BackendAPI: app.backend,
+ summary: service.BackfillSummaryDTO{TotalItems: 0},
+ }
+ app.backend = stub
+ app.BackfillSummary = stub.summary
+ app.CacheQueue = nil
+
+ // 1. Settings › 存储 with TotalItems == 0 shows up-to-date copy and no action button.
+ app.Navigate(RouteSettings)
+ app.SettingsCategory = "storage"
+ tt := ui.NewTester(app.View, 1280, 860)
+ tt.Frame()
+ if !tt.HasText("历史缓存已全部符合最新标准") {
+ t.Fatal("Settings › 存储 should show up-to-date message when TotalItems == 0")
+ }
+ if _, ok := tt.Find("补全历史缓存"); ok {
+ t.Fatal("Settings › 存储 must not show 补全历史缓存 button when TotalItems == 0")
+ }
+
+ // 2. Settings › 存储 with TotalItems == 3 shows count + 补全历史缓存 button; clicking starts backfill & opens Tasks queue!
+ stub.mu.Lock()
+ stub.summary = service.BackfillSummaryDTO{
+ WeiboMissingNoWM: 2,
+ WeiboLegacyLinks: 1,
+ WeiboFastCDNCandidates: 2,
+ TotalItems: 3,
+ }
+ stub.mu.Unlock()
+ app.BackfillSummary = stub.summary
+ tt.Frame()
+ if !tt.HasText("发现 3 条历史微博可补全") {
+ t.Fatal("Settings › 存储 should show pending backfill count")
+ }
+ if err := tt.Click("补全历史缓存"); err != nil {
+ t.Fatalf("failed to click 补全历史缓存 button: %v", err)
+ }
+ // Wait for async requestGuarded goroutine and drain UI dispatch.
+ for i := 0; i < 50; i++ {
+ drain()
+ if app.CurrentRoute == RouteTasks && len(app.CacheQueue) == 1 {
+ break
+ }
+ tt.Frame()
+ }
+ stub.mu.Lock()
+ started := stub.startedCalls
+ stub.mu.Unlock()
+ if started != 1 || app.CurrentRoute != RouteTasks || app.TasksSection != "queue" {
+ t.Fatalf("expected StartWeiboBackfill + navigation to /tasks queue; started=%d route=%s sec=%s", started, app.CurrentRoute, app.TasksSection)
+ }
+
+ // 3. Tasks › 缓存队列 renders card titled "历史缓存补全 · 微博" and hides the top prompt bar while active.
+ tt.Frame()
+ if !tt.HasText("历史缓存补全 · 微博") {
+ t.Fatal("Tasks › 缓存队列 must render backfill queue card titled 历史缓存补全 · 微博")
+ }
+ if _, ok := tt.Find("队列详情计数:cq_bf_1"); !ok {
+ t.Fatal("Tasks › 缓存队列 must render backfill progress count element 队列详情计数:cq_bf_1")
+ }
+ if _, ok := tt.Find("历史缓存补全提示条"); ok {
+ t.Fatal("top backfill action bar must be hidden while backfill queue is active")
+ }
+
+ // 4. Settings › 存储 switches to "查看补全队列" while active.
+ app.Navigate(RouteSettings)
+ app.SettingsCategory = "storage"
+ tt.Frame()
+ if _, ok := tt.Find("查看历史缓存补全队列"); !ok {
+ t.Fatal("Settings › 存储 should show 查看补全队列 button when backfill is active")
+ }
+
+ // 5. Tasks › 缓存队列 with empty CacheQueue & TotalItems == 3 renders top bar "发现 3 条历史微博可补全" + "一键补全".
+ stub.mu.Lock()
+ stub.queue = nil
+ stub.mu.Unlock()
+ app.CacheQueue = nil
+ app.Navigate(RouteTasks)
+ app.TasksSection = "queue"
+ tt.Frame()
+ if !tt.HasText("发现 3 条历史微博可补全") {
+ t.Fatal("Tasks › 缓存队列 should show 发现 3 条历史微博可补全 top bar even when queue list is empty")
+ }
+ if _, ok := tt.Find("一键补全历史微博缓存"); !ok {
+ t.Fatal("Tasks › 缓存队列 missing 一键补全 button")
+ }
+}
+
+func TestDetailMenusForceRecacheConfirmModalAllFourSites(t *testing.T) {
+ app, _, cleanup := newTestUIApp(t)
+ defer cleanup()
+ posted := make(chan func(), 32)
+ app.dispatch = func(fn func()) { posted <- fn }
+ drain := func() {
+ for {
+ select {
+ case fn := <-posted:
+ fn()
+ default:
+ return
+ }
+ }
+ }
+
+ seedUIFeed(t, app, 0)
+ cacheDir := app.backend.GetSettings().CacheDir
+ dummyDir := filepath.Join(cacheDir, "dummy")
+ if err := os.MkdirAll(dummyDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+
+ items := map[string]library.ItemMetadata{
+ "weibo:dynamic:5098000000000001": {
+ ItemKey: "weibo:dynamic:5098000000000001", Site: "weibo", Kind: "dynamic", ID: "5098000000000001", RawID: "5098000000000001",
+ Title: "微博详情测试", Text: "微博详情测试", Status: "complete", ItemDir: dummyDir,
+ },
+ "weibo:video:1034:5098000000000002": {
+ ItemKey: "weibo:video:1034:5098000000000002", Site: "weibo", Kind: "video", ID: "1034:5098000000000002", RawID: "1034:5098000000000002",
+ Title: "微博视频测试", Status: "complete", ItemDir: dummyDir,
+ },
+ "x:dynamic:1898000000000000001": {
+ ItemKey: "x:dynamic:1898000000000000001", Site: "x", Kind: "dynamic", ID: "1898000000000000001", RawID: "1898000000000000001",
+ Title: "X详情测试", Text: "X详情测试", Status: "complete", ItemDir: dummyDir,
+ },
+ "douyin:video:7398000000000000001": {
+ ItemKey: "douyin:video:7398000000000000001", Site: "douyin", Kind: "video", ID: "7398000000000000001", RawID: "7398000000000000001",
+ Title: "抖音详情测试", Status: "complete", ItemDir: dummyDir,
+ },
+ "bilibili:video:BV1force00001": {
+ ItemKey: "bilibili:video:BV1force00001", Site: "bilibili", Kind: "video", ID: "BV1force00001", RawID: "BV1force00001",
+ Title: "B站视频测试", Status: "complete", ItemDir: dummyDir,
+ },
+ }
+
+ stub := &backfillAndForceStub{
+ BackendAPI: app.backend,
+ cachedByKey: items,
+ }
+ app.backend = stub
+
+ tt := ui.NewTester(app.View, 1280, 860)
+
+ cases := []struct {
+ name string
+ setup func()
+ menuLabel string
+ wantKey string
+ }{
+ {
+ name: "weibo_post",
+ setup: func() {
+ it := items["weibo:dynamic:5098000000000001"]
+ app.CurrentRoute = RouteWeiboPost
+ app.CurrentWeiboVideo = nil
+ app.CurrentWeiboPost = &service.WeiboPostView{
+ Mid: "5098000000000001", Text: "微博详情测试", CacheKey: it.ItemKey,
+ Author: service.WeiboAuthorDTO{UID: "100001", ScreenName: "微博作者"}, CachedItem: &it,
+ }
+ },
+ menuLabel: "微博详情更多",
+ wantKey: "weibo:dynamic:5098000000000001",
+ },
+ {
+ name: "weibo_video",
+ setup: func() {
+ it := items["weibo:video:1034:5098000000000002"]
+ app.CurrentRoute = RouteWeiboPost
+ app.CurrentWeiboPost = nil
+ app.CurrentWeiboVideo = &service.WeiboVideoView{
+ ObjectID: "1034:5098000000000002", Title: "微博视频测试", AuthorUID: "100001", AuthorName: "微博作者",
+ CacheKey: it.ItemKey, CachedItem: &it,
+ }
+ },
+ menuLabel: "微博视频详情更多",
+ wantKey: "weibo:video:1034:5098000000000002",
+ },
+ {
+ name: "x_post",
+ setup: func() {
+ it := items["x:dynamic:1898000000000000001"]
+ app.CurrentRoute = RouteXPost
+ app.CurrentXPost = &service.XPostDTO{
+ ID: "1898000000000000001", Text: "X详情测试", CacheKey: it.ItemKey,
+ Author: service.XAuthorDTO{RestID: "190001", Name: "X作者", ScreenName: "xauthor"}, CachedItem: &it,
+ }
+ },
+ menuLabel: "X详情更多",
+ wantKey: "x:dynamic:1898000000000000001",
+ },
+ {
+ name: "douyin_work",
+ setup: func() {
+ it := items["douyin:video:7398000000000000001"]
+ app.CurrentRoute = RouteDouyinWork
+ app.CurrentDouyinWork = &service.DouyinWorkView{
+ ID: "7398000000000000001", Kind: "video", Title: "抖音详情测试", CacheKey: it.ItemKey,
+ Author: service.DouyinAuthorDTO{SecUID: "MS4w_1", Nickname: "抖音作者"},
+ }
+ app.CurrentLibraryDetail = nil
+ _ = it
+ },
+ menuLabel: "抖音作品更多",
+ wantKey: "douyin:video:7398000000000000001",
+ },
+ {
+ name: "bilibili_video",
+ setup: func() {
+ app.CurrentRoute = RouteVideo
+ app.CurrentLibraryDetail = nil
+ app.CurrentVideoItemKey = "bilibili:video:BV1force00001"
+ app.CurrentVideo = &bilibili.VideoDetail{
+ BVID: "BV1force00001", Title: "B站视频测试",
+ Author: bilibili.AuthorInfo{Mid: 20001, Name: "UP主"},
+ }
+ },
+ menuLabel: "视频详情更多",
+ wantKey: "bilibili:video:BV1force00001",
+ },
+ }
+
+ const expectedModalCopy = "将从源站重新完整下载并覆盖本机已有文件;若源站已删除或失效,仍会保留本机原文件不覆盖。"
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ app.PostMenuKey = ""
+ app.ForceRecacheConfirm = ForceRecacheConfirmState{}
+ app.cacheStateRev++
+ tc.setup()
+ tt.Frame()
+
+ if err := tt.Click(tc.menuLabel); err != nil {
+ t.Fatalf("failed to open menu %q: %v", tc.menuLabel, err)
+ }
+ tt.Frame()
+ if err := tt.Click("强制重新下载"); err != nil {
+ t.Fatalf("menu %q missing 强制重新下载 item: %v", tc.menuLabel, err)
+ }
+ tt.Frame()
+
+ if !app.ForceRecacheConfirm.Open || app.ForceRecacheConfirm.ItemKey != tc.wantKey {
+ t.Fatalf("confirm dialog not opened for %q: %+v", tc.wantKey, app.ForceRecacheConfirm)
+ }
+ if !tt.HasText(expectedModalCopy) {
+ t.Fatalf("confirm modal missing expected warning copy %q", expectedModalCopy)
+ }
+ if err := tt.Click("确认强制重新下载"); err != nil {
+ t.Fatalf("failed to click confirm button 确认强制重新下载: %v", err)
+ }
+ for i := 0; i < 40; i++ {
+ drain()
+ stub.mu.Lock()
+ n := len(stub.forcedKeys)
+ stub.mu.Unlock()
+ if n > 0 && stub.forcedKeys[n-1] == tc.wantKey {
+ break
+ }
+ tt.Frame()
+ }
+ stub.mu.Lock()
+ found := len(stub.forcedKeys) > 0 && stub.forcedKeys[len(stub.forcedKeys)-1] == tc.wantKey
+ stub.mu.Unlock()
+ if !found {
+ t.Fatalf("ForceRecacheItem not called with %q; got %v", tc.wantKey, stub.forcedKeys)
+ }
+ })
+ }
+
+ // Verify TriggerAuthExpired closes ForceRecacheConfirm.Open.
+ app.ForceRecacheConfirm = ForceRecacheConfirmState{Open: true, ItemKey: "weibo:dynamic:5098000000000001"}
+ app.TriggerAuthExpired("expired")
+ if app.ForceRecacheConfirm.Open {
+ t.Fatal("TriggerAuthExpired must close ForceRecacheConfirm modal")
+ }
+}
diff --git a/internal/ui/douyin_work_view.go b/internal/ui/douyin_work_view.go
index 4e4c1d4..36ab79f 100644
--- a/internal/ui/douyin_work_view.go
+++ b/internal/ui/douyin_work_view.go
@@ -243,6 +243,11 @@ func (a *App) renderDouyinWorkRoute(c *ui.Context, viewportHeight float32) {
a.showError(a.backend.Desktop().OpenExternalURL(canonicalURL))
}
if cachedItem != nil && itemKey != "" {
+ if !cachedItem.IsArchivedSnapshot() {
+ if m.Item("强制重新下载").Chosen() {
+ a.openForceRecacheConfirm(itemKey, firstNonEmptyStrUI(title, desc, awemeID))
+ }
+ }
if m.Item("打开文件夹").Chosen() {
a.showError(a.backend.OpenItemFolder(itemKey))
}
diff --git a/internal/ui/navigation.go b/internal/ui/navigation.go
index eead284..0136c0e 100644
--- a/internal/ui/navigation.go
+++ b/internal/ui/navigation.go
@@ -150,6 +150,7 @@ func (a *App) closeAllModalsAndOverlays() {
a.ConfirmLogoutOpen = false
a.Remote.ConfirmPushXOpen = false
a.DeleteConfirm.Open = false
+ a.ForceRecacheConfirm.Open = false
a.RestartConfirmOpen = false
a.AddSubDialogOpen = false
a.RuleBatch.Open = false
diff --git a/internal/ui/overlays.go b/internal/ui/overlays.go
index 3833b20..1f1a3dd 100644
--- a/internal/ui/overlays.go
+++ b/internal/ui/overlays.go
@@ -213,3 +213,22 @@ func (a *App) renderDeleteConfirmOverlay(c *ui.Context, w, h float32) {
})
})
}
+
+func (a *App) renderForceRecacheConfirmOverlay(c *ui.Context, w, h float32) {
+ renderConfirmDialog(
+ c,
+ &a.ForceRecacheConfirm.Open,
+ "关闭强制重新下载确认对话框(点击空白处)",
+ "强制重新下载确认对话框",
+ "强制重新下载",
+ "将从源站重新完整下载并覆盖本机已有文件;若源站已删除或失效,仍会保留本机原文件不覆盖。",
+ "取消",
+ "取消强制重新下载",
+ "确认重新下载",
+ "确认强制重新下载",
+ true,
+ func() {
+ a.confirmForceRecache()
+ },
+ )
+}
diff --git a/internal/ui/settings_view.go b/internal/ui/settings_view.go
index 92c0c7b..8adf1f6 100644
--- a/internal/ui/settings_view.go
+++ b/internal/ui/settings_view.go
@@ -698,6 +698,38 @@ func (a *App) renderStorageSettings(c *ui.Context) {
}
})
})
+ // Historical cache standard backfill row (DEC-079)
+ activeBackfill, hasActiveBackfill := a.activeWeiboBackfillQueue()
+ startingBackfill := a.isPending("start-weibo-backfill")
+ ui.Row(c).Label("存储历史缓存标准行").FillWidth().AlignItems(ui.Center).Justify(ui.SpaceBetween).Gap(8).ClipX().Children(func() {
+ ui.Column(c).Grow(1).Gap(2).ClipX().Children(func() {
+ ui.Text(c, "历史缓存标准").FontSize(13).FontWeight(600).TextColor(ColorTextMain).SingleLine()
+ if hasActiveBackfill {
+ progressText := fmt.Sprintf("正在补全微博历史缓存 · 已补全 %d 条 · 跳过 %d 条", activeBackfill.CachedCount, activeBackfill.SkippedCount)
+ if activeBackfill.BackfillTotal > 0 {
+ progressText = fmt.Sprintf("正在补全微博历史缓存 · 已补全 %d / %d 条 · 跳过 %d 条", activeBackfill.CachedCount, activeBackfill.BackfillTotal, activeBackfill.SkippedCount)
+ }
+ ui.Text(c, progressText).FontSize(12).TextColor(ColorAccent).SingleLine()
+ } else if a.BackfillSummary.TotalItems > 0 {
+ ui.Text(c, formatBackfillSummaryDetail(a.BackfillSummary)).FontSize(12).TextColor(ColorTextMuted).MaxLines(2)
+ } else {
+ ui.Text(c, "历史缓存已全部符合最新标准").FontSize(12).TextColor(ColorTextMuted).SingleLine()
+ }
+ })
+ if hasActiveBackfill {
+ if OutlinePillButton(c, "查看补全队列", "查看历史缓存补全队列").Clicked() {
+ a.OpenCacheQueueTask(activeBackfill.ID)
+ }
+ } else if a.BackfillSummary.TotalItems > 0 {
+ btnLabel := "补全历史缓存"
+ if startingBackfill {
+ btnLabel = "正在启动…"
+ }
+ if AccentPillButton(c, btnLabel, "补全历史缓存").Disabled(startingBackfill).Clicked() && !startingBackfill {
+ a.startWeiboBackfill()
+ }
+ }
+ })
})
// Change Cache Directory
diff --git a/internal/ui/tasks_queue_view.go b/internal/ui/tasks_queue_view.go
index 5959ab0..cf83520 100644
--- a/internal/ui/tasks_queue_view.go
+++ b/internal/ui/tasks_queue_view.go
@@ -109,6 +109,38 @@ func (a *App) renderTasksQueueView(c *ui.Context) {
if a.TaskActionError != "" {
renderErrorBanner(c, "", a.TaskActionError, nil)
}
+ _, hasActiveBackfill := a.activeWeiboBackfillQueue()
+ if !hasActiveBackfill && a.BackfillSummary.TotalItems > 0 {
+ startingBackfill := a.isPending("start-weibo-backfill")
+ ui.Row(c).
+ Label("历史缓存补全提示条").
+ FillWidth().
+ Padding(10, 14).
+ Radius(12).
+ Background(ColorBgSecondary).
+ Border(1, ColorBorder).
+ AlignItems(ui.Center).
+ Justify(ui.SpaceBetween).
+ Gap(10).
+ ClipX().
+ Children(func() {
+ ui.Column(c).Grow(1).Gap(2).ClipX().Children(func() {
+ ui.Text(c, fmt.Sprintf("发现 %d 条历史微博可补全", a.BackfillSummary.TotalItems)).
+ FontSize(13).FontWeight(600).TextColor(ColorTextMain).SingleLine()
+ if detail := formatBackfillSummaryBreakdown(a.BackfillSummary); detail != "" {
+ ui.Text(c, detail).
+ FontSize(12).TextColor(ColorTextMuted).SingleLine()
+ }
+ })
+ btnText := "一键补全"
+ if startingBackfill {
+ btnText = "正在启动…"
+ }
+ if AccentPillButton(c, btnText, "一键补全历史微博缓存").Disabled(startingBackfill).Clicked() && !startingBackfill {
+ a.startWeiboBackfill()
+ }
+ })
+ }
if len(a.CacheQueue) == 0 {
ui.Column(c).FillWidth().Padding(40, 16).AlignItems(ui.Center).Gap(8).Children(func() {
ui.Text(c, "当前没有缓存队列任务").FontSize(15).FontWeight(600).TextColor(ColorTextMain).SingleLine()
@@ -151,6 +183,7 @@ func (a *App) finishCacheQueueAction(err error) {
func (a *App) renderCacheQueueCard(c *ui.Context, cur service.CacheQueueTask, expanded bool) {
qSite := normalizeSiteIDUI(cur.Site)
+ isBackfill := cur.Kind == service.CacheQueueKindWeiboBackfill || cur.List == service.CacheQueueListWeiboBackfill
unfinished := isUnfinishedCacheQueueStatus(cur.Status)
borderCol := ColorBorder
if expanded {
@@ -186,7 +219,9 @@ func (a *App) renderCacheQueueCard(c *ui.Context, cur service.CacheQueueTask, ex
ui.Column(c).Grow(1).Gap(4).ClipX().Children(func() {
ui.Row(c).FillWidth().AlignItems(ui.Center).Gap(6).ClipX().Children(func() {
title := firstNonEmptyStrUI(cur.UserName, cur.User)
- if cur.ListLabel != "" {
+ if isBackfill {
+ title = "历史缓存补全 · 微博"
+ } else if cur.ListLabel != "" {
title += " · " + cur.ListLabel
}
ui.Text(c, title).FontSize(14).FontWeight(600).TextColor(ColorTextMain).SingleLine().Shrink(1)
@@ -209,7 +244,15 @@ func (a *App) renderCacheQueueCard(c *ui.Context, cur service.CacheQueueTask, ex
}
ui.Row(c).FillWidth().AlignItems(ui.Center).Gap(6).ClipX().Children(func() {
ui.Text(c, statusLine).Label("队列详情状态:" + cur.ID).FontSize(12).FontWeight(600).TextColor(statusColor).SingleLine()
- ui.Text(c, fmt.Sprintf("· 已缓存 %d 条 · 跳过 %d 条", cur.CachedCount, cur.SkippedCount)).
+ countLine := fmt.Sprintf("· 已缓存 %d 条 · 跳过 %d 条", cur.CachedCount, cur.SkippedCount)
+ if isBackfill {
+ if cur.BackfillTotal > 0 {
+ countLine = fmt.Sprintf("· 已补全 %d / %d 条 · 跳过 %d 条", cur.CachedCount, cur.BackfillTotal, cur.SkippedCount)
+ } else {
+ countLine = fmt.Sprintf("· 已补全 %d 条 · 跳过 %d 条", cur.CachedCount, cur.SkippedCount)
+ }
+ }
+ ui.Text(c, countLine).
Label("队列详情计数:" + cur.ID).
FontSize(12).TextColor(ColorTextMuted).SingleLine()
})
@@ -259,7 +302,11 @@ func (a *App) renderCacheQueueCard(c *ui.Context, cur service.CacheQueueTask, ex
ui.Text(c, cur.Note).FontSize(12).TextColor(ColorTextMuted).MaxLines(2)
}
if cur.Status == service.CacheQueueRunning && cur.ActiveTitle != "" {
- ui.Text(c, "当前正在缓存:"+cur.ActiveTitle).FontSize(12).FontWeight(600).TextColor(ColorAccent).SingleLine()
+ prefix := "当前正在缓存:"
+ if isBackfill {
+ prefix = "当前正在补全:"
+ }
+ ui.Text(c, prefix+cur.ActiveTitle).FontSize(12).FontWeight(600).TextColor(ColorAccent).SingleLine()
}
if expanded {
a.renderCacheQueueRecent(c, cur)
diff --git a/internal/ui/video_view.go b/internal/ui/video_view.go
index f5c1b4a..cecbd0e 100644
--- a/internal/ui/video_view.go
+++ b/internal/ui/video_view.go
@@ -151,6 +151,33 @@ func (a *App) renderVideoRoute(c *ui.Context) {
}
if offline && cachedItem != nil {
a.renderLibraryItemMoreMenu(c, *cachedItem, 32)
+ } else if !offline && cachedItem != nil && itemKey != "" {
+ menuKey := "bili-video:" + itemKey
+ open := a.PostMenuKey == menuKey
+ MoreMenuButton(c, "视频详情更多", 32, &open, func(m *ui.Menu) {
+ if !cachedItem.IsArchivedSnapshot() {
+ if m.Item("强制重新下载").Chosen() {
+ a.openForceRecacheConfirm(itemKey, firstNonEmptyStrUI(vd.Title, vd.BVID))
+ }
+ }
+ if vd.BVID != "" {
+ targetURL := "https://www.bilibili.com/video/" + vd.BVID
+ if m.Item("复制链接").Chosen() {
+ c.WriteClipboard(targetURL)
+ c.Toast("已复制链接")
+ a.BannerInfo = "已复制链接"
+ }
+ if m.Item("在浏览器中打开").Chosen() {
+ if err := a.backend.Desktop().OpenExternalURL(targetURL); err != nil {
+ a.showError(err)
+ }
+ }
+ }
+ if m.Item("打开文件夹").Chosen() {
+ a.showError(a.backend.OpenItemFolder(itemKey))
+ }
+ })
+ keyedMenuOpen(&a.PostMenuKey, menuKey, open)
}
})
})
diff --git a/internal/ui/weibo_post_view.go b/internal/ui/weibo_post_view.go
index cb4249f..f03c95b 100644
--- a/internal/ui/weibo_post_view.go
+++ b/internal/ui/weibo_post_view.go
@@ -856,6 +856,11 @@ func (a *App) renderWeiboOnlinePostDetail(c *ui.Context, post *service.WeiboPost
}
}
if cachedItem != nil && itemKey != "" {
+ if !cachedItem.IsArchivedSnapshot() {
+ if m.Item("强制重新下载").Chosen() {
+ a.openForceRecacheConfirm(itemKey, firstNonEmptyStrUI(cachedItem.Title, post.Text, post.Mid))
+ }
+ }
if m.Item("打开文件夹").Chosen() {
a.showError(a.backend.OpenItemFolder(itemKey))
}
@@ -1172,6 +1177,11 @@ func (a *App) renderWeiboStandaloneVideo(c *ui.Context, vv *service.WeiboVideoVi
}
}
if cachedItem != nil && itemKey != "" {
+ if !cachedItem.IsArchivedSnapshot() {
+ if m.Item("强制重新下载").Chosen() {
+ a.openForceRecacheConfirm(itemKey, firstNonEmptyStrUI(cachedItem.Title, vv.Title, vv.ObjectID))
+ }
+ }
if m.Item("打开文件夹").Chosen() {
a.showError(a.backend.OpenItemFolder(itemKey))
}
diff --git a/internal/ui/x_post_view.go b/internal/ui/x_post_view.go
index df4fcce..f2febf0 100644
--- a/internal/ui/x_post_view.go
+++ b/internal/ui/x_post_view.go
@@ -760,6 +760,11 @@ func (a *App) renderXPostDetail(c *ui.Context, post *service.XPostDTO) {
}
}
if cachedItem != nil && itemKey != "" {
+ if !cachedItem.IsArchivedSnapshot() {
+ if m.Item("强制重新下载").Chosen() {
+ a.openForceRecacheConfirm(itemKey, firstNonEmptyStrUI(cachedItem.Title, post.Text, post.ID))
+ }
+ }
if m.Item("打开文件夹").Chosen() {
a.showError(a.backend.OpenItemFolder(itemKey))
}