From 00e79cee4f73bee9cffb4fa5bf1785d0e4dedc70 Mon Sep 17 00:00:00 2001 From: chialecode <315431287+chialecode@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:56:50 +0800 Subject: [PATCH 1/5] feat(weibo,ui): dual-save original and watermark-free companion images Keep Weibo primary images strictly at official full-resolution originals (/large/ or /mw2000/) and save the /oslarge/ watermark-free maximum tier as an optional companion file (images/NN_nowm., role image_nowm) with SHA-256 deduplication, silent skip on unavailable /oslarge/, old cached item backfill, library lifecycle support, anti-duplication in media library/feed, and an Original/Watermark-free toggle pill in the image viewer. Record DEC-078 and minimally adapt ACT-023 dual-save tests. Closes #103 Signed-off-by: chialecode <315431287+chialecode@users.noreply.github.com> --- docs/decisions.md | 1 + docs/delivery/roadmap.md | 2 +- docs/design/data-and-cache.md | 6 +- docs/requirements.md | 2 +- docs/research/weibo.md | 4 +- docs/ui.md | 4 +- internal/download/douyin_plan.go | 64 ++-- internal/download/image_guard_fallback.go | 7 +- internal/download/range_download.go | 2 +- internal/download/replace.go | 2 +- internal/download/sniff.go | 2 +- internal/download/weibo_plan.go | 240 +++++++++++++- internal/download/weibo_watermark_test.go | 330 +++++++++++++++---- internal/library/files.go | 3 + internal/library/merge.go | 6 + internal/library/schema.go | 3 +- internal/library/weibo_dual_nowm_test.go | 157 +++++++++ internal/service/weibo_queue_account_test.go | 11 +- internal/service/weibo_watermark_test.go | 48 ++- internal/site/types.go | 25 +- internal/site/weibo/adapter.go | 18 +- internal/site/weibo/post.go | 22 +- internal/site/weibo/post_media_fallback.go | 24 +- internal/site/weibo/post_test.go | 12 +- internal/site/weibo/watermark_test.go | 94 ++++-- internal/ui/app.go | 64 ++-- internal/ui/douyin_media.go | 54 ++- internal/ui/image_viewer.go | 75 ++++- internal/ui/media_controls.go | 4 + internal/ui/media_open.go | 108 +++++- internal/ui/settings_view.go | 2 +- internal/ui/weibo_post_view.go | 5 +- internal/ui/weibo_watermark_ui_test.go | 198 ++++++++++- tools/actcheck/act022.go | 16 +- tools/actcheck/act022_test.go | 29 +- tools/uishots/scenes.go | 2 +- 36 files changed, 1347 insertions(+), 299 deletions(-) create mode 100644 internal/library/weibo_dual_nowm_test.go diff --git a/docs/decisions.md b/docs/decisions.md index 2b4b001..85608f0 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -88,3 +88,4 @@ | DEC-074 | **每个订阅支持添加自定义外部链接**:可为单个订阅保存若干自定义外部链接(如 `link3.cc`、`linktr.ee`、个人主页等),每条含可选显示名与 `http://`/`https://` 地址(未填名称时自动取去 `www.` 的域名与路径),在订阅详情头部下方以可点击胶囊展示并在系统浏览器打开,由详情头部“⋯ → 自定义链接”(及有链接时的“管理链接”胶囊)集中增删改 | 用户,2026-11-24(“给每个订阅加一些自定义的链接,例如可以添加 link3.cc、linktree之类的”;[#63](https://github.com/chialecode/trace/issues/63)) | `subscriptions.json` 新增可选字段 `links`(`omitempty`,结构版本保持 `4` 不变,旧版忽略),随订阅快照导出/导入与远程同步一起携带;严格只允许 `http://`/`https://` 并拒绝 `javascript:`/`file:`/凭证参数。[需求 FR-SUBS-001、FR-SUBS-002](requirements.md#subscription-scope)、[订阅设计 §1](design/subscriptions.md#model)、[界面规范 §3.9](ui.md#subscriptions) | | 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) | diff --git a/docs/delivery/roadmap.md b/docs/delivery/roadmap.md index 69f7d49..3975159 100644 --- a/docs/delivery/roadmap.md +++ b/docs/delivery/roadmap.md @@ -179,4 +179,4 @@ AC-01~04、AC-08~11、AC-15、AC-17、AC-19~22 的哔哩哔哩真实站点 | OSS-008 | 二维码传递模块归档遗漏 LICENSE | 已核对官方仅增加 MIT LICENSE 的下一提交,将许可原文作为精确版本补充嵌入通知,其他缺许可模块停止打包([来源与移除条件](../../tools/internal/build/licenses/README.md)) | | OSS-009 | 抖音网页签名(`a_bogus`、`x-secsdk-web-signature`)由 TRACE 按协议规格自写;站点前端约每 3~6 个月局部收紧一次 | 签名模块隔离在 `internal/site/douyin/sign`(纯标准库,不联网、不读凭证),国标 SM3 向量、规格附录固定向量及 ACT-010 真实站点 V-02 全部通过;未来失效时抖音请求按风控停下并建“站点限制” `blocked` issue,不影响哔哩哔哩([选型 §4](../research/2026-11-12-douyin.md#a-review)) | -已知限制:没有可用 GPU 的电脑走软件解码,界面不会卡死,但高分辨率 60 fps 视频可能掉帧;本机没有 cgo 工具链,`go test -race` 无法运行(记为 `not-run`);大于 2 GiB 的 `co64` 大文件门控默认未执行;抖音直播仅提供 HLS(MPEG-TS)或为纯音频电台模式时不录制并说明原因(见 [LOOP-008](https://github.com/chialecode/trace/issues/32)、[LOOP-009](https://github.com/chialecode/trace/issues/33));抖音真实直播的 HEVC(`CodecID=12`/`hvc1`)流没在真实站点见到,只由合成测试覆盖(ACT-014 的直播间只给 AVC);微博目前只经合成样本与自动化测试验证(ACT-022 单次运行在步骤 6 因本机 typed-nil 异常中断且未写出脱敏回执,本机缺陷已修,完整真实站点校验与 AC-65/67~70/75 的真实站点部分仍待 [ACT-023](https://github.com/chialecode/trace/issues/19)),微博扫码登录、直播录制、赞过与关注分组均暂未开放(见 FR-WB-010、[LOOP-017](https://github.com/chialecode/trace/issues/39)),微博静态原图去平台水印开关(`/oslarge/` 优先并自动回退原地址)已开放、真实无损校验随 [ACT-023](https://github.com/chialecode/trace/issues/19) V-07 补录;**X 已于 2026-11-25 完成 ACT-025([#18](https://github.com/chialecode/trace/issues/18),`artifacts/site-check/act025.json`)核心真实站点校验(V-01/V-04 核心/V-05/V-06/V-07 与 `Following` 两页通过,零限流/风控);`Bookmarks` 懒加载分包缺 `queryId`(`schema_changed`)、`t.co` 返回 HTTP 200 未展开、`Likes`/`BookmarkFoldersSlice` 与 V-09 错误码未运行及用户资料 `statuses_count`/`pinned_tweet_ids_str` 解析为 0 仍待后续修复与补测**,且 X 网页前端变动频繁,首次真实使用仍可能需要跟进修复;X 官方 API、直播与 Spaces、`x-xp-forwarded-for`、仅 HLS 视频、回复与媒体标签、书签文件夹与列表等暂未开放(见 FR-X-010、[LOOP-018](https://github.com/chialecode/trace/issues/40));远程版只经本机、WSL Ubuntu 与假站点、假 rclone 验证,真实 VPS、真实 Cookie 推送与 Google Drive 是 `not-run`(H-003);本地一次只连一个远程;导入、导出与订阅文件的路径直接输入,没有系统的文件夹选择框;Windows 上的远程冒烟不能发控制台信号,改为结束进程后再启动(`SIGTERM` 收尾在 Linux 上验证)。 +已知限制:没有可用 GPU 的电脑走软件解码,界面不会卡死,但高分辨率 60 fps 视频可能掉帧;本机没有 cgo 工具链,`go test -race` 无法运行(记为 `not-run`);大于 2 GiB 的 `co64` 大文件门控默认未执行;抖音直播仅提供 HLS(MPEG-TS)或为纯音频电台模式时不录制并说明原因(见 [LOOP-008](https://github.com/chialecode/trace/issues/32)、[LOOP-009](https://github.com/chialecode/trace/issues/33));抖音真实直播的 HEVC(`CodecID=12`/`hvc1`)流没在真实站点见到,只由合成测试覆盖(ACT-014 的直播间只给 AVC);微博目前只经合成样本与自动化测试验证(ACT-022 单次运行在步骤 6 因本机 typed-nil 异常中断且未写出脱敏回执,本机缺陷已修,完整真实站点校验与 AC-65/67~70/75 的真实站点部分仍待 [ACT-023](https://github.com/chialecode/trace/issues/19)),微博扫码登录、直播录制、赞过与关注分组均暂未开放(见 FR-WB-010、[LOOP-017](https://github.com/chialecode/trace/issues/39)),微博静态图片默认双份保存(主图恒存官方原图 `/large/`,同时额外保存 `/oslarge/` 690px 宽无水印最大版伴侣文件并在看图层支持切换,[DEC-078](../decisions.md#dec-078));**X 已于 2026-11-25 完成 ACT-025([#18](https://github.com/chialecode/trace/issues/18),`artifacts/site-check/act025.json`)核心真实站点校验(V-01/V-04 核心/V-05/V-06/V-07 与 `Following` 两页通过,零限流/风控);`Bookmarks` 懒加载分包缺 `queryId`(`schema_changed`)、`t.co` 返回 HTTP 200 未展开、`Likes`/`BookmarkFoldersSlice` 与 V-09 错误码未运行及用户资料 `statuses_count`/`pinned_tweet_ids_str` 解析为 0 仍待后续修复与补测**,且 X 网页前端变动频繁,首次真实使用仍可能需要跟进修复;X 官方 API、直播与 Spaces、`x-xp-forwarded-for`、仅 HLS 视频、回复与媒体标签、书签文件夹与列表等暂未开放(见 FR-X-010、[LOOP-018](https://github.com/chialecode/trace/issues/40));远程版只经本机、WSL Ubuntu 与假站点、假 rclone 验证,真实 VPS、真实 Cookie 推送与 Google Drive 是 `not-run`(H-003);本地一次只连一个远程;导入、导出与订阅文件的路径直接输入,没有系统的文件夹选择框;Windows 上的远程冒烟不能发控制台信号,改为结束进程后再启动(`SIGTERM` 收尾在 Linux 上验证)。 diff --git a/docs/design/data-and-cache.md b/docs/design/data-and-cache.md index 82981db..979f738 100644 --- a/docs/design/data-and-cache.md +++ b/docs/design/data-and-cache.md @@ -105,7 +105,7 @@ ```text <保存位置>/weibo//posts//item.json、cover.<扩展名>、video.mp4(视频微博或独立视频页) -<保存位置>/weibo//posts//item.json、images/01.<扩展名>…、images/01_live.mp4…、images/02.mp4…(图文、GIF、实况、混排) +<保存位置>/weibo//posts//item.json、images/01.<扩展名>…、images/01_nowm.<扩展名>…、images/01_live.mp4…、images/02.mp4…(图文、GIF、实况、混排;`NN_nowm` 为可选无水印最大版伴侣图,DEC-078) <保存位置>/weibo//forwards//item.json…(这位博主转发或快转的微博,结构同 posts/,记 via) ``` @@ -136,7 +136,7 @@ X(DEC-066)的作者目录用稳定的纯数字 `rest_id`(不随 `@handle` - `available`:缓存当时站点列出的档位快照(`accept_quality`、`support_formats` 的 `quality`/`need_vip`、返回流里的最高档、是否有杜比/无损音频)与探测时间; - `danmaku`:弹幕文件、条数、取得时间(没开设置时记 `skipped`);`subtitles`:每种语言的 `lan`、`lan_doc`、是否 AI、VTT 与 SRT 文件;`chapters`(可选,`json:"chapters,omitempty"`,结构 `{fromSec, toSec, title}`,复用 `player/wbi/v2` 的 `view_points` 零额外请求写入,旧清单无此字段完全兼容,`item.json` 保持 `version: 1` 不升结构版本)。 -可选的 `via`(DEC-056,见 2.1)说明条目为谁缓存、存在谁的文件夹:`reason`(`forward` 或 `collab`)、`site`、`uid`、`name`,转发另记 `dynamicId`;`author` 仍是原作者或投稿人。另向后兼容地支持可选字段 `links`(`[]library.ItemLink{label, url}`,按正文出现顺序记录可读超链接标签与安全 `http(s)://` 跳转地址,DEC-073)、`origin`(`*library.ItemOrigin`:原博 `site`、`id`、`mblogId`、`canonicalUrl`、`author`、`pubTs`、`title`、`text`、`links`、`card`、`unavailable`、`unavailableReason`、`videoFromOrigin`)、`card`(`*library.ItemRichCard`:`kind`、`label`、`title`、`desc`、`url`)以及 `notePages[].fromOrigin` / `media[].fromOrigin`(区分外层与原博媒体;`item.json` 保持 v1、`library.db` 保持 v2 不升结构版本);`SanitizeItemMetadata` 自动清洗 `links`、`origin`、`thread[].links` 与 `card` 中的非 `http(s)` 协议、用户凭证、签名参数、Cookie 令牌及媒体 CDN 地址(`weibocdn.com`、`sinaimg.cn`、`video.weibo.com`、`pbs.twimg.com`、`video.twimg.com` 等)同时保留公开跳转地址与正文,`MergeItemMetadata` 与导入导出 `PortableManifest` 完整保留并合并这些字段。旧清单没有这些字段时照常读取,结构版本不变。媒体库把 `via.reason = forward` 或动态类型为 `DYNAMIC_TYPE_FORWARD` 的条目算作“转发”(`FeedFilter.Kind = "forward"`),“图片”“视频”用 `ExcludeForward` 只列作者自己的内容;按作者筛选时也匹配 `via.uid`,`library.db` 为此建表达式索引 `idx_library_items_via (site, json_extract(json_data, '$.via.uid'))`。 +可选的 `via`(DEC-056,见 2.1)说明条目为谁缓存、存在谁的文件夹:`reason`(`forward` 或 `collab`)、`site`、`uid`、`name`,转发另记 `dynamicId`;`author` 仍是原作者或投稿人。另向后兼容地支持可选字段 `links`(`[]library.ItemLink{label, url}`,按正文出现顺序记录可读超链接标签与安全 `http(s)://` 跳转地址,DEC-073)、`origin`(`*library.ItemOrigin`:原博 `site`、`id`、`mblogId`、`canonicalUrl`、`author`、`pubTs`、`title`、`text`、`links`、`card`、`unavailable`、`unavailableReason`、`videoFromOrigin`)、`card`(`*library.ItemRichCard`:`kind`、`label`、`title`、`desc`、`url`)以及 `notePages[].fromOrigin` / `notePages[].noWatermark` / `media[].fromOrigin`(区分外层与原博媒体及微博无水印伴侣图 `role: "image_nowm"`,`item.json` 保持 v1、`library.db` 保持 v2 不升结构版本);`SanitizeItemMetadata` 自动清洗 `links`、`origin`、`thread[].links` 与 `card` 中的非 `http(s)` 协议、用户凭证、签名参数、Cookie 令牌及媒体 CDN 地址(`weibocdn.com`、`sinaimg.cn`、`video.weibo.com`、`pbs.twimg.com`、`video.twimg.com` 等)同时保留公开跳转地址与正文,`MergeItemMetadata` 与导入导出 `PortableManifest` 完整保留并合并这些字段。旧清单没有这些字段时照常读取,结构版本不变。媒体库把 `via.reason = forward` 或动态类型为 `DYNAMIC_TYPE_FORWARD` 的条目算作“转发”(`FeedFilter.Kind = "forward"`),“图片”“视频”用 `ExcludeForward` 只列作者自己的内容;按作者筛选时也匹配 `via.uid`,`library.db` 为此建表达式索引 `idx_library_items_via (site, json_extract(json_data, '$.via.uid'))`。 可选的 `cachedBy`(DEC-062)记缓存这一条的安装:`node`(`<数据目录>/node.json` 里随机生成的节点 ID)与 `name`;旧条目没有这个字段时照常读取,结构版本不变。导入与合并时保留本地的 `cachedBy`。导出、上传到网盘的副本去掉 `itemDir`、`itemKey`、`rawId`、`totalBytes`,导入后由 `SaveItem` 按内容重新算出([远程 §6.1](remote.md#export-format))。 @@ -171,7 +171,7 @@ X(DEC-066)的作者目录用稳定的纯数字 `rest_id`(不随 `@handle` | 微博类型 | 保存 | | --- | --- | | 视频微博 / 独立视频页(`1034:`) | 正文与发布信息、封面 `cover.<扩展名>`、一个单文件 MP4 `video.mp4`(第 2.5 节选流,第 2.6 节校验并保证 `moov` 前置);有宿主微博的独立视频页归一为 `weibo:dynamic:` | -| 图文、长微博、超过 9 图、GIF、实况、混排 | 完整正文(长微博全文)与按 `pic_ids` / `mix_media_info` 原顺序的每一项:原图 `images/NN.<按文件头定的扩展名>`(GIF 原样存 `.gif`)、实况照片静帧与伴侣片段 `images/NN_live.mp4`(角色 `motion`,静帧 `motion` 指向它;QuickTime `.mov` 经 `mp4ff` 无损改封装为 ISO BMFF `.mp4`)、混排视频 `images/NN.mp4`(角色 `video`)与封面;单个附件缺失记黄点,不让整条失败 | +| 图文、长微博、超过 9 图、GIF、实况、混排 | 完整正文(长微博全文)与按 `pic_ids` / `mix_media_info` 原顺序的每一项:主图 `images/NN.<按文件头定的扩展名>`(`role: "image"`,恒存官方最高清原图,GIF 原样存 `.gif`);开启“微博同时保存无水印版”时对非 GIF 静态图与实况静帧额外保存 `/oslarge/` 伴侣图 `images/NN_nowm.<扩展名>`(`role: "image_nowm"`,`notePages[].noWatermark` 指向它,同 SHA-256 去重、`/oslarge/` 失效静默跳过不记缺失,旧条目重缓存复用主图并补齐伴侣图;媒体库与信息流不重复展示为第二张图,删除/归档/合并/刷新一并同步,[DEC-078](../decisions.md#dec-078));实况照片伴侣片段 `images/NN_live.mp4`(角色 `motion`,静帧 `motion` 指向它;QuickTime `.mov` 经 `mp4ff` 无损改封装为 ISO BMFF `.mp4`)、混排视频 `images/NN.mp4`(角色 `video`)与封面;单个主附件缺失记黄点,不让整条失败 | | 纯文字 | 完整正文(含长微博全文) | | 转发 / 快转 | 转发正文 + 原微博快照与媒体,统一存在转发者的 `weibo/<转发者 uid>/forwards//` 并记 `via`(DEC-056);原微博已删除或不可见时完整保留转发正文并说明原因 | | 头条文章、投票、音乐、外链、直播卡片 | 正文与卡片摘要(不把外链或直播卡片当成视频下载),可在浏览器中打开 | diff --git a/docs/requirements.md b/docs/requirements.md index 94638a6..4d9aca9 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -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 | 缓存微博正文、图片、实况与混排:保存全文(长微博的全文)、发布信息、按原顺序的全部原图(超过 9 张、GIF 保存原动图,扩展名按实际格式;默认开启“微博图片去平台水印”开关,仅对静态图片优先尝试无损 `/oslarge/` 并在 404/HTML/坏图时自动回退原始 `largest`/`original` 地址,GIF 保持原地址,可在“设置 › 缓存与下载”随时关闭并立即生效)、实况照片的静帧与片段(QuickTime `.mov` 经 `mp4ff` 无损改封装为 `.mp4`)、混排里的视频与封面;单个文件缺失记黄点、不让整条失败。转发的微博连同其中的图片与视频存到转发者的 `forwards/`,清单记 `via`(DEC-056),原微博看不到时完整保存转发正文。媒体地址带签名的一律不落盘 | 已实现(只经合成样本验证;真实站点与无损去水印校验待 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-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/research/weibo.md b/docs/research/weibo.md index 2bac5c8..58f51f0 100644 --- a/docs/research/weibo.md +++ b/docs/research/weibo.md @@ -311,7 +311,7 @@ 3. **各尺寸档位与去平台水印边界**: - `pic_infos[id]` 内常见尺寸对象(含 `{url, width, height, cut_type, type}`):`thumbnail`、`bmiddle`、`large`、`mw2000`、`original`、`largest`、`largecover`(`社区资料(2026-11-21)`)。 - **默认最高清优先级**:`largest` → `original` → `mw2000` → `large` → `bmiddle`(并在非空档位中核对 `width * height` 最大者)。TRACE 只缓存原图:备用地址只用与原图同尺寸的档位,不退到 `bmiddle` 与缩略图(2026-11-24 用户要求)(`源码阅读(多站点订阅参考,2026-11-21)`、`社区资料(2026-11-21)`)。 - - **去平台水印变体(`unknown`,列 V-07)**:单链接解析参考观察到 `sinaimg.cn` 的 `/mw690/`、`/mw2000/`、`/large/`、`/woriginal/` 可能带右下角平台昵称水印,改写路径为 `/osj1080/` 或 `/oslarge/` 可去水印(`源码阅读(单链接解析参考,2026-11-21)`);社区另见原图下载接口 `GET https://weibo.com/ajax/common/download?pid=`(`社区资料(2026-11-21)`)。但 `/osj1080/` 可能限宽 1080px、`/oslarge/` 对部分 PNG/GIF/历史图可能 404、`common/download` 是否需登录 Cookie 均为 `unknown`。**推荐策略**:MVP 默认使用 `largest` / `original` 直链保证原分辨率与动图完整,待 **V-07** 实测确认无损后再评估去水印开关(见 [§12.3](#q-drafts) `Q-WB-6`)。 + - **去平台水印变体(已在 ACT-023 V-07 实测,按 [DEC-078](../decisions.md#dec-078) 改为双份保存)**:`sinaimg.cn` 的 `/mw690/`、`/mw2000/`、`/large/`、`/woriginal/` 可能带右下角平台昵称水印,而 `/oslarge/` 与 `/osj1080/` 均会降采样至 690px 宽(虽无水印,并非无损原分辨率)。**最终策略(DEC-078)**:主图 `ImageAsset.URL` 与 `images/NN.` 恒定保持官方最高清原图 `largest`(`/large/` 或 `/mw2000/`);开启「微博同时保存无水印版」(`weiboRemoveWatermark`,默认开启)时,额外将 `/oslarge/` 写入运行期字段 `WatermarkFreeURL`(`json:"-"`)并另存伴侣文件 `images/NN_nowm.`(GIF 跳过、SHA-256 相同去重、`/oslarge/` 失效静默跳过不拖垮主图),看图层提供「原图 / 无水印」一键切换。 4. **GIF 动图(`type == "gif"`)**: - `pic_infos[id].type == "gif"` 同时给出 `largest.url`(原始 `.gif`,`wx1..4.sinaimg.cn`)与 `video`(转码 MP4,常见 `g.us.sinaimg.cn` 或 `f.video.weibocdn.com`,带签名)(`社区资料(2026-11-21)`)。推荐默认保存 `largest.url` 原始 `.gif`(与看图面板兼容、无签名过期风险),在 **V-08** 中确认其确为多帧 GIF 而非静态首帧。 5. **实况照片(`type == "livephoto"`)**: @@ -823,7 +823,7 @@ A 按[站点规则](../dev-rules/sources-and-safety.md#site-rules)审阅了第 1 7. **检查更新**:没有起点时只读第 1 页;之后每个账号每次最多 2 页;第 6.3、6.5 节的置顶、快转、推广卡片与不确定空结果规则照用。 8. **请求节奏**:采用第 9.3 节的建议值,写成 [NFR-NET-004](../requirements.md#nfr)。 9. **媒体白名单**:后缀 `sinaimg.cn`、`weibocdn.com`;`video.weibo.com` 只为实况首跳 `/media/play` 单独放行;`Referer: https://weibo.com/`,不带 Cookie;视频与实况的 `PublicRedirects` 默认关,V-12 发现跳到第三方边缘域名时再照抖音的做法打开。 -10. **图片与水印**:默认按 `largest` → `original` → `mw2000` → `large` 取最大的一档;微博原图、长图与多帧 GIF 经常超过 JSON 接口的 4 MiB 上限乃至 50 MiB,因此在线原图读取(`FetchImage`)、预览暂存与分段下载统一采用单张 128 MiB 上限与按次读取空闲超时(不与 JSON 响应的 4 MiB 上限混用);PR #95 开放了设置项「微博图片去平台水印」(`settings.json` 的 `weiboRemoveWatermark`,当前默认开启、随时可关且立即生效并清空 5 分钟内存 `weiboPostPlanCache`),对静态图片将 `sinaimg.cn` 路径段改写为 `/oslarge/` 并将原始地址保留在 `FallbackURLs[0]`、GIF 保持不改写;**2026-11-25 [ACT-023](https://github.com/chialecode/trace/issues/19) V-07 实测证实 `/oslarge/` 与 `/osj1080/` 均会将原图降采样至宽 `690px`(`1280×1706` 849 KiB → `690×920` 317 KiB / 172 KiB),并非无损原分辨率**(详见 §13.2 V-07,后续需复核默认开关与文案)。 +10. **图片与水印([DEC-078](../decisions.md#dec-078))**:默认按 `largest` → `original` → `mw2000` → `large` 取最大的一档作为主图 `ImageAsset.URL`;微博原图、长图与多帧 GIF 经常超过 JSON 接口的 4 MiB 上限乃至 50 MiB,因此在线原图读取(`FetchImage`)、预览暂存与分段下载统一采用单张 128 MiB 上限与按次读取空闲超时(不与 JSON 响应的 4 MiB 上限混用);2026-11-25 [ACT-023](https://github.com/chialecode/trace/issues/19) V-07 实测证实 `/oslarge/` 与 `/osj1080/` 均会将原图降采样至宽 `690px`(`1280×1706` 849 KiB → `690×920` 317 KiB / 172 KiB),并非无损原分辨率(详见 §13.2 V-07)。据此用户拍板 [DEC-078](../decisions.md#dec-078) 改为**双份保存**:主图 `images/NN.`(`role: "image"`)恒存官方最高清原图,设置项「微博同时保存无水印版」(`settings.json` 沿用 `weiboRemoveWatermark`,默认开启、随时可关且立即清空 5 分钟内存 `weiboPostPlanCache`)对非 GIF 静态图与实况静帧生成运行期 `WatermarkFreeURL`(`/oslarge/`)并另存无水印伴侣文件 `images/NN_nowm.`(`role: "image_nowm"`,`notePages[].noWatermark` 指向它;SHA-256 与主图相同时去重不落盘,`/oslarge/` 失效静默跳过不拖垮主图,看图层支持「原图 / 无水印」切换)。 11. **实况片段容器**:按实际容器保存,用 `mp4ff` 校验有视频轨与 `moov`;应用内播放器打不开 `.mov` 时用 `mp4ff` 无损改封装成 `.mp4`(不转码、不加依赖)。 12. **直播**:不录制、不巡检;直播链接与直播卡片按第 8.4 节提示;微博账号不进开播检查。 13. **我的**:关注先按社区资料较完整的 `ajax/friendships/friends?uid=<自己>` 实现(`followContent` 可作备选),收藏 `ajax/favorites/all_fav`;“赞过”与关注分组各有一个开关常量,默认关,V-13、V-14 通过后才打开(同抖音观看历史的做法)。 diff --git a/docs/ui.md b/docs/ui.md index f118445..a51af2c 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -123,7 +123,7 @@ ### 3.5 看图层(DEC-033) - 点击任何图片打开看图层:一个浮在应用上方的深色圆角面板(四周留边,背后的应用变暗,点面板外面关闭;DEC-040),默认按面板适应显示**原图**(已缓存的用本机文件,否则用去掉尺寸后缀的原图地址)。 -- 滚轮、快捷键(`+` / `-` / `0`)或双击缩放,按住拖动平移;只保留少量半透明圆形悬浮按钮:右上角**关闭**,左右两侧**上一张 / 下一张**,底部居中**适应窗口 / 原始大小(1:1)**,左上角轻量胶囊显示“当前 / 总数 · 缩放百分比”。 +- 滚轮、快捷键(`+` / `-` / `0`)或双击缩放,按住拖动平移;只保留少量半透明圆形悬浮按钮:右上角**关闭**,左右两侧**上一张 / 下一张**,底部居中**适应窗口 / 原始大小(1:1)**,左上角轻量胶囊显示“当前 / 总数 · 缩放百分比”;当当前已缓存图片存在无水印伴侣文件(微博 `images/NN_nowm.`,[DEC-078](decisions.md#dec-078))时,左上角进度胶囊旁显示简洁的 **「原图 / 无水印」** 分段胶囊切换按钮(默认显示原图,点击即时切图且平滑加载;切到无伴侣文件的图片时自动隐藏按钮并显示原图,不报错)。 - 鼠标静止约 2 秒后悬浮控件自动隐藏,鼠标移动或按键时重新出现;左右键切换同一条动态里的图片,Esc 关闭。 - 实况照片与 X GIF(MP4 静音循环)翻到这一页就在看图层里原地自动播放动态片段(DEC-040、DEC-046 ①、DEC-049),底部圆形“播放”按钮用来重播:已缓存的播放本机片段,没缓存的先从站点取到临时文件再播放(哔哩哔哩、抖音、微博与 X 均一致,按 `InlineSite` 区分站点通道),不跳到播放层。 - 抖音图文的视频页在看图层里直接播放(点画面暂停/继续,底部一条细进度条与时长,没缓存时播放在线地址);切到别的页时停止。视频页或实况片段播放时,配乐条暂停,停止后不自动恢复。 @@ -162,7 +162,7 @@ - 每个设置项一行:名称 + 当前值 + 操作,用细线分隔。**设置项默认没有说明小字**;只有需要提醒后果或限制的具体设置才有一行说明(如“关闭窗口时”“定时检查更新”“缓存保存位置”)。下拉框显示中文选项名(如“能拿到的最高(推荐)”“最小化到托盘(推荐)”),不显示内部值。改动立即保存,保存失败在该行下方显示原因。 - 分类: - **账号**(FR-AUTH-007、FR-WB-001、FR-X-001):按站点分成四组,组标题“哔哩哔哩”“抖音”“微博”“X(原 Twitter)”,组之间细线分隔。抖音一组:已登录时头像、昵称、抖音号、“登录方式:粘贴 Cookie”、“自动续期:不可用,粘贴的 Cookie 与浏览器共用会话;过期后请重新粘贴”、“重新粘贴”“退出登录”(确认里说明会暂停抖音的缓存任务和录制,另外三个站点不受影响);未登录时一个“登录抖音”按钮,打开登录页并预选抖音。微博一组:已登录时头像、昵称、`UID`、“登录方式:粘贴 Cookie”、“自动续期:不可用,粘贴的 Cookie 不续期;过期后请重新粘贴”、“重新粘贴”“退出登录”(独立确认“退出微博登录?”,只暂停微博的缓存任务与规则请求,另外三个站点不受影响);未登录时一个“登录微博”按钮,打开登录页并预选微博。X 一组:已登录时头像、昵称、`@handle` 与 `ID`、“登录方式:粘贴 Cookie”、“自动续期:不可用,粘贴的 Cookie 不续期;过期后请重新粘贴”、一行简版“风险说明”(非官方 API,建议使用专用账号,只读不写,遇验证或锁号即停)、“重新粘贴”“退出登录”(独立确认“退出 X 登录?”,只暂停 X 的缓存任务与规则请求,另外三个站点不受影响);未登录时一个“登录 X”按钮,打开登录页并预选 X。哔哩哔哩一组如下:头像、昵称、`UID`、登录方式(扫码 / 手动凭证);“自动续期”(扫码登录:“可用 · 上次续期 11 月 7 日 08:30”,失败时附原因;粘贴凭证:“不可用:粘贴的 Cookie 与浏览器共用会话,续期会让浏览器那边掉线。过期后请重新粘贴,或改用扫码登录”);“重新登录”“退出登录”(退出时确认,说明会暂停缓存任务和录制)。 - - **缓存与下载**:同时下载数(1~4);多 P 视频(全部分 P / 只缓存第 1 P);缓存弹幕(开关);缓存字幕(开关);包括 AI 字幕(开关,缓存字幕关闭时禁用);自动保存视频封面(开关);微博图片去平台水印(开关,默认开启,一行说明“优先尝试无损无水印原图,不支持的老图自动回退原地址;GIF 动图保持原样。”,切换后立即生效)。 + - **缓存与下载**:同时下载数(1~4);多 P 视频(全部分 P / 只缓存第 1 P);缓存弹幕(开关);缓存字幕(开关);包括 AI 字幕(开关,缓存字幕关闭时禁用);自动保存视频封面(开关);微博同时保存无水印版(开关,默认开启,一行说明“主图保存官方原图,同时额外保存无水印最大版(oslarge),GIF 跳过。”,切换后立即生效,[DEC-078](decisions.md#dec-078))。 - **画质与音质**:视频清晰度(能拿到的最高(推荐)/ 不超过 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 ④⑤;不设同时录制数上限)。 diff --git a/internal/download/douyin_plan.go b/internal/download/douyin_plan.go index 8204014..211939f 100644 --- a/internal/download/douyin_plan.go +++ b/internal/download/douyin_plan.go @@ -21,24 +21,25 @@ type WorkPlanOptions struct { // PlannedNotePage describes one 1-based page in a Douyin/Weibo/X image or mixed note. type PlannedNotePage struct { - Index int - Kind string // "image", "gif", "live_photo", "video", "unknown" - MediaID string `json:"mediaId,omitempty"` - FromOrigin bool - HLSOnly bool - UnknownKind string - UnknownReason string - Width int - Height int - DurationSec int - ImageURLs []string - VideoURLs []string - NeedSetToken bool - Gear string - QualityName string - Codec string - FPS int - Bitrate int64 + Index int + Kind string // "image", "gif", "live_photo", "video", "unknown" + MediaID string `json:"mediaId,omitempty"` + FromOrigin bool + HLSOnly bool + UnknownKind string + UnknownReason string + Width int + Height int + DurationSec int + ImageURLs []string + WatermarkFreeURL string `json:"-"` + VideoURLs []string + NeedSetToken bool + Gear string + QualityName string + Codec string + FPS int + Bitrate int64 } // PlannedThreadPart describes one author self-reply segment saved into the same item (e.g. X threads). @@ -289,19 +290,20 @@ func convertSiteDownloadPlan(p site.DownloadPlan) WorkDownloadPlan { } } pages = append(pages, PlannedNotePage{ - Index: idx, - Kind: pageKind, - FromOrigin: img.FromOrigin, - HLSOnly: pageHLSOnly, - Width: img.Width, - Height: img.Height, - DurationSec: img.DurationSec, - ImageURLs: append([]string(nil), img.ImageURLs...), - VideoURLs: append([]string(nil), img.VideoURLs...), - QualityName: img.QualityLabel, - Codec: img.VideoCodec, - FPS: img.FPS, - Bitrate: img.Bitrate, + Index: idx, + Kind: pageKind, + FromOrigin: img.FromOrigin, + HLSOnly: pageHLSOnly, + Width: img.Width, + Height: img.Height, + DurationSec: img.DurationSec, + ImageURLs: append([]string(nil), img.ImageURLs...), + WatermarkFreeURL: img.WatermarkFreeURL, + VideoURLs: append([]string(nil), img.VideoURLs...), + QualityName: img.QualityLabel, + Codec: img.VideoCodec, + FPS: img.FPS, + Bitrate: img.Bitrate, }) } var music *PlannedMusic diff --git a/internal/download/image_guard_fallback.go b/internal/download/image_guard_fallback.go index ebb2290..7ce42e1 100644 --- a/internal/download/image_guard_fallback.go +++ b/internal/download/image_guard_fallback.go @@ -237,14 +237,14 @@ func preserveValidPreviousImages( coveredStems := make(map[string]bool, len(mediaFiles)) for _, mf := range mediaFiles { coveredPaths[mf.Path] = true - if mf.Role == "image" || mf.Role == "cover" { + if mf.Role == "image" || mf.Role == "cover" || mf.Role == "image_nowm" { coveredStems[mf.Role+":"+trimKnownImageExt(mf.Path)] = true } } var keptImagePaths map[string]bool for _, old := range previous.Media { - if old.Role != "image" && old.Role != "cover" { + if old.Role != "image" && old.Role != "cover" && old.Role != "image_nowm" { continue } stemKey := old.Role + ":" + trimKnownImageExt(old.Path) @@ -335,6 +335,9 @@ func preserveValidPreviousImagesForStage( filteredPages := notePages[:0] for _, pg := range notePages { if pg.Image == "" || keptPaths[pg.Image] { + if pg.NoWatermark != "" && !keptPaths[pg.NoWatermark] { + pg.NoWatermark = "" + } filteredPages = append(filteredPages, pg) } } diff --git a/internal/download/range_download.go b/internal/download/range_download.go index f3b51b6..953d582 100644 --- a/internal/download/range_download.go +++ b/internal/download/range_download.go @@ -561,7 +561,7 @@ func (m *Manager) fetchRangeSegment( } } } - isImage := role == "image" || role == "cover" + isImage := role == "image" || role == "cover" || role == "image_nowm" if spec.checkDisguised { if err := rejectDisguisedMediaContentType(spec.site, rawCT, role, resp.StatusCode); err != nil { return segmentResult{newOffset: offset}, rawCT, err diff --git a/internal/download/replace.go b/internal/download/replace.go index 67cadf2..ebf8cb2 100644 --- a/internal/download/replace.go +++ b/internal/download/replace.go @@ -2103,7 +2103,7 @@ func findReusableLocalPage(localMeta library.ItemMetadata, page PlannedNotePage, } if !isConflictReplace { for _, lp := range localMeta.NotePages { - if lp.Index == pageIdx && lp.MediaID == "" && pID == "" { + if lp.Index == pageIdx && lp.MediaID == "" { return lp, true } } diff --git a/internal/download/sniff.go b/internal/download/sniff.go index d0201d1..9f10a8c 100644 --- a/internal/download/sniff.go +++ b/internal/download/sniff.go @@ -28,7 +28,7 @@ func rejectDisguisedMediaContentType(siteID site.ID, rawCT, role string, statusC Message: fmt.Sprintf("媒体请求返回了非媒体类型 (%s)", mediaType), } } - if (role == "image" || role == "cover") && mediaType != "" && + if (role == "image" || role == "cover" || role == "image_nowm") && mediaType != "" && !strings.HasPrefix(mediaType, "image/") && mediaType != "application/octet-stream" { return &site.Error{ Site: siteID, diff --git a/internal/download/weibo_plan.go b/internal/download/weibo_plan.go index 9852e83..d223bb6 100644 --- a/internal/download/weibo_plan.go +++ b/internal/download/weibo_plan.go @@ -1093,14 +1093,25 @@ func (m *Manager) executeWeiboPostTask( } imgMedia.FromOrigin = page.FromOrigin mediaFiles = append(mediaFiles, *imgMedia) + var noWMPath string + nowmMedia, nowmErr := m.cacheWeiboWatermarkFreeCompanion(ctx, workTask, workDir, previous, exists && !hasProtectedLocal, hasProtectedLocal, isConflict, canReuseLocal, reusableLP, pageIdx, page, imgMedia, plan.Transport) + if nowmErr != nil { + return nowmErr + } + if nowmMedia != nil { + nowmMedia.FromOrigin = page.FromOrigin + noWMPath = nowmMedia.Path + mediaFiles = append(mediaFiles, *nowmMedia) + } notePages = append(notePages, library.NotePageRecord{ - Index: pageIdx, - Kind: "image", - MediaID: cleanPageMediaID, - FromOrigin: page.FromOrigin, - Image: imgMedia.Path, - Width: page.Width, - Height: page.Height, + Index: pageIdx, + Kind: "image", + MediaID: cleanPageMediaID, + FromOrigin: page.FromOrigin, + Image: imgMedia.Path, + NoWatermark: noWMPath, + Width: page.Width, + Height: page.Height, }) case "live_photo", "motion": @@ -1169,6 +1180,15 @@ func (m *Manager) executeWeiboPostTask( } if imgMedia != nil { rec.Image = imgMedia.Path + nowmMedia, nowmErr := m.cacheWeiboWatermarkFreeCompanion(ctx, workTask, workDir, previous, exists && !hasProtectedLocal, hasProtectedLocal, isConflict, canReuseLocal, reusableLP, pageIdx, page, imgMedia, plan.Transport) + if nowmErr != nil { + return nowmErr + } + if nowmMedia != nil { + nowmMedia.FromOrigin = page.FromOrigin + rec.NoWatermark = nowmMedia.Path + mediaFiles = append(mediaFiles, *nowmMedia) + } } if mErr != nil { if isSiteStopError(mErr) || isStorageError(mErr) || ctx.Err() != nil { @@ -1688,32 +1708,222 @@ func isWeiboOSLargeURL(rawURL string) bool { } // validateWeiboOSLargeImageFile enforces strict binary magic-byte and image-header validation -// on /oslarge/ responses so corrupt or fake-image payloads immediately fall back to the original -// largest/original URL instead of being saved as broken files. +// on /oslarge/ responses so corrupt or fake-image payloads are rejected instead of being saved +// as broken files. func validateWeiboOSLargeImageFile(filePath, ext string) error { + _, _, err := validateWeiboOSLargeImageFileWithSize(filePath, ext) + return err +} + +func validateWeiboOSLargeImageFileWithSize(filePath, ext string) (int, int, error) { f, err := os.Open(filePath) if err != nil { - return err + return 0, 0, err } defer f.Close() var head [64]byte n, _ := f.Read(head[:]) magicExt, ok := site.SniffImageMagicBytes(head[:n]) if !ok { - return site.ErrUnsupportedImageHeader + return 0, 0, site.ErrUnsupportedImageHeader } if magicExt == ".avif" || magicExt == ".heic" { - return nil + return 0, 0, nil } if _, err := f.Seek(0, 0); err != nil { - return err + return 0, 0, err } cfg, _, err := image.DecodeConfig(f) if err != nil || cfg.Width <= 0 || cfg.Height <= 0 { - return errors.New("去水印原图头部损坏或无法解码") + return 0, 0, errors.New("去水印伴侣图头部损坏或无法解码") } _ = ext - return nil + return cfg.Width, cfg.Height, nil +} + +// cacheWeiboWatermarkFreeCompanion saves the optional /oslarge/ watermark-free companion image +// (images/NN_nowm., role "image_nowm") alongside the official original primary image (DEC-078). +// Reuse of verified local companions, SHA-256 deduplication against the primary image, and silent +// skip on non-fatal /oslarge/ errors ensure primary caching is never degraded or turned yellow. +func (m *Manager) cacheWeiboWatermarkFreeCompanion( + ctx context.Context, + workTask *Task, + workDir string, + previous library.ItemMetadata, + inPlaceExists bool, + hasProtectedLocal bool, + isConflict bool, + canReuseLocal bool, + reusableLP library.NotePageRecord, + pageIdx int, + page PlannedNotePage, + primaryMedia *library.MediaFile, + transport site.MediaTransportSpec, +) (*library.MediaFile, error) { + if primaryMedia == nil { + return nil, nil + } + nowmStem := fmt.Sprintf("images/%02d_nowm", pageIdx) + findPrevNoWMRel := func() string { + if strings.TrimSpace(reusableLP.NoWatermark) != "" && mediaIsValid(previous, reusableLP.NoWatermark) { + return reusableLP.NoWatermark + } + for _, mf := range previous.Media { + if mf.Role == "image_nowm" && strings.HasPrefix(mf.Path, nowmStem+".") && mediaIsValid(previous, mf.Path) { + return mf.Path + } + } + return "" + } + tryCopyPrevNoWM := func() *library.MediaFile { + srcRel := findPrevNoWMRel() + if srcRel == "" { + return nil + } + if strings.EqualFold(filepath.Ext(srcRel), ".gif") { + if full, rErr := library.ResolveItemPath(previous.ItemDir, srcRel); rErr == nil { + if looksLikeWeiboPlaceholderGIF(full, page.WatermarkFreeURL, 0, 0) { + return nil + } + } + } + copied, err := copyLocalMediaToStageAs(previous, srcRel, nowmStem, "image_nowm", workDir) + if err != nil || copied == nil { + return nil + } + if primaryMedia.SHA256 != "" && strings.EqualFold(copied.SHA256, primaryMedia.SHA256) { + if stFull, sErr := stagedFullPath(workDir, copied.Path); sErr == nil { + _ = os.Remove(stFull) + } + return nil + } + copied.FromOrigin = page.FromOrigin + return copied + } + + inSwapStage := isSwapStageDir(workDir) + if hasProtectedLocal && !isConflict && canReuseLocal { + if reused := tryCopyPrevNoWM(); reused != nil { + return reused, nil + } + } else if !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) + kept.FromOrigin = page.FromOrigin + return kept, nil + } + } + } + + cand := strings.TrimSpace(page.WatermarkFreeURL) + if cand == "" { + return nil, nil + } + + tempRel := nowmStem + imgSuffix + tempFull, err := library.ResolveItemPath(workDir, tempRel) + if err != nil { + return nil, err + } + if err := m.claimTaskFile(workTask, workDir, tempRel, tempFull); err != nil { + return nil, err + } + if err := ctx.Err(); err != nil { + return nil, err + } + if err := os.MkdirAll(filepath.Dir(tempFull), 0o700); err != nil { + return nil, err + } + _ = os.Remove(tempFull) + _ = os.Remove(tempFull + ".part") + m.resetFileProgress(workTask, tempRel) + + discardTemp := func() { + _ = os.Remove(tempFull) + _ = os.Remove(tempFull + ".part") + m.removeTempTaskProgress(workTask, tempRel) + } + fallbackPrevOrSkip := func() (*library.MediaFile, error) { + if hasProtectedLocal && canReuseLocal { + if reused := tryCopyPrevNoWM(); reused != nil { + return reused, nil + } + } + return nil, nil + } + + spec := m.transportRangeSpec(transport, "image_nowm", false) + n, sha, ct, dlErr := m.downloadRange(ctx, spec, []string{cand}, tempFull, workTask) + if dlErr != nil { + if ctx.Err() != nil { + return nil, ctx.Err() + } + discardTemp() + if isSiteStopError(dlErr) || isStorageError(dlErr) { + return nil, dlErr + } + return fallbackPrevOrSkip() + } + + if site.LooksLikeExpiredPlaceholderImageFile(tempFull, cand, 0, 0, false) { + discardTemp() + return fallbackPrevOrSkip() + } + ext, sErr := sniffImageExtension(tempFull, ct) + if sErr != nil { + discardTemp() + return fallbackPrevOrSkip() + } + w, h, vErr := validateWeiboOSLargeImageFileWithSize(tempFull, ext) + if vErr != nil { + discardTemp() + return fallbackPrevOrSkip() + } + // Deduplicate when /oslarge/ bytes are identical to the official original primary image. + if primaryMedia.SHA256 != "" && strings.EqualFold(sha, primaryMedia.SHA256) { + discardTemp() + return nil, nil + } + + finalRel := nowmStem + ext + writeFinalRel := finalRel + if inSwapStage { + writeFinalRel = stagedRelPath(finalRel) + } + finalFull, err := library.ResolveItemPath(workDir, writeFinalRel) + if err != nil { + if ctx.Err() == nil { + discardTemp() + } + return nil, err + } + if err := m.claimTaskFile(workTask, workDir, writeFinalRel, finalFull); err != nil { + if ctx.Err() == nil { + discardTemp() + } + return nil, err + } + if err := ctx.Err(); err != nil { + return nil, err + } + if err := os.Rename(tempFull, finalFull); err != nil { + if ctx.Err() == nil { + discardTemp() + } + return nil, err + } + m.removeTempTaskProgress(workTask, tempRel) + m.setFileProgress(workTask, "image_nowm", finalRel, "completed", n, n, 0) + return &library.MediaFile{ + Role: "image_nowm", + Path: finalRel, + FromOrigin: page.FromOrigin, + Bytes: n, + SHA256: sha, + Width: w, + Height: h, + }, nil } func (m *Manager) cacheWeiboLivePhotoClip( diff --git a/internal/download/weibo_watermark_test.go b/internal/download/weibo_watermark_test.go index f3c1cac..a7d9753 100644 --- a/internal/download/weibo_watermark_test.go +++ b/internal/download/weibo_watermark_test.go @@ -16,6 +16,7 @@ import ( "testing" "time" + "github.com/chialecode/trace/internal/library" "github.com/chialecode/trace/internal/site" ) @@ -47,9 +48,30 @@ func makeWatermarkTestPlaceholderGIF(t *testing.T) []byte { return buf.Bytes() } -func TestWeiboDownloadOSLargeSuccessAndAutomaticFallback(t *testing.T) { - validJPG := makeWatermarkTestJPEG(t, 24, 18, color.RGBA{R: 20, G: 120, B: 200, A: 255}) - fallbackJPG := makeWatermarkTestJPEG(t, 32, 24, color.RGBA{R: 200, G: 80, B: 40, A: 255}) +func makeWatermarkTestAnimatedGIF(t *testing.T) []byte { + t.Helper() + pal := color.Palette{ + color.RGBA{R: 30, G: 160, B: 220, A: 255}, + color.RGBA{R: 240, G: 90, B: 40, A: 255}, + } + f1 := image.NewPaletted(image.Rect(0, 0, 16, 16), pal) + f2 := image.NewPaletted(image.Rect(0, 0, 16, 16), pal) + for i := range f2.Pix { + f2.Pix[i] = 1 + } + var buf bytes.Buffer + if err := gif.EncodeAll(&buf, &gif.GIF{ + Image: []*image.Paletted{f1, f2}, + Delay: []int{10, 10}, + }); err != nil { + t.Fatalf("gif.EncodeAll: %v", err) + } + return buf.Bytes() +} + +func TestWeiboDualSaveCompanionDedupAndSilentSkip(t *testing.T) { + origJPG := makeWatermarkTestJPEG(t, 40, 30, color.RGBA{R: 200, G: 80, B: 40, A: 255}) + nowmJPG := makeWatermarkTestJPEG(t, 24, 18, color.RGBA{R: 20, G: 120, B: 200, A: 255}) placeholderGIF := makeWatermarkTestPlaceholderGIF(t) cases := []struct { @@ -57,56 +79,69 @@ func TestWeiboDownloadOSLargeSuccessAndAutomaticFallback(t *testing.T) { oslargeStatus int oslargeCT string oslargeBody []byte - wantBody []byte - wantFallback bool + wantNoWM bool + wantNoWMBody []byte + wantNoWMW int + wantNoWMH int }{ { - name: "oslarge_success", + name: "dual_save_distinct_oslarge", oslargeStatus: http.StatusOK, oslargeCT: "image/jpeg", - oslargeBody: validJPG, - wantBody: validJPG, - wantFallback: false, + oslargeBody: nowmJPG, + wantNoWM: true, + wantNoWMBody: nowmJPG, + wantNoWMW: 24, + wantNoWMH: 18, }, { - name: "oslarge_404_falls_back_to_largest", + name: "identical_sha256_deduplicated", + oslargeStatus: http.StatusOK, + oslargeCT: "image/jpeg", + oslargeBody: origJPG, + wantNoWM: false, + }, + { + name: "oslarge_404_silent_skip_primary_green", oslargeStatus: http.StatusNotFound, oslargeCT: "text/plain", oslargeBody: []byte("not found"), - wantBody: fallbackJPG, - wantFallback: true, + wantNoWM: false, + }, + { + name: "oslarge_403_silent_skip_primary_green", + oslargeStatus: http.StatusForbidden, + oslargeCT: "text/plain", + oslargeBody: []byte("forbidden"), + wantNoWM: false, }, { - name: "oslarge_html_falls_back_to_largest", + name: "oslarge_html_silent_skip_primary_green", oslargeStatus: http.StatusOK, oslargeCT: "text/html; charset=utf-8", oslargeBody: []byte("blocked"), - wantBody: fallbackJPG, - wantFallback: true, + wantNoWM: false, }, { - name: "oslarge_corrupt_bytes_falls_back_to_largest", + name: "oslarge_corrupt_silent_skip_primary_green", oslargeStatus: http.StatusOK, oslargeCT: "image/jpeg", oslargeBody: []byte("NOT_A_VALID_IMAGE_HEADER_BYTES_1234567890"), - wantBody: fallbackJPG, - wantFallback: true, + wantNoWM: false, }, { - name: "oslarge_truncated_jpeg_falls_back_to_largest", + name: "oslarge_truncated_jpeg_silent_skip_primary_green", oslargeStatus: http.StatusOK, oslargeCT: "image/jpeg", oslargeBody: []byte{0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x01, 0x02}, - wantBody: fallbackJPG, - wantFallback: true, + wantNoWM: false, }, { - name: "oslarge_placeholder_gif_falls_back_to_largest", + name: "oslarge_placeholder_gif_silent_skip_primary_green", oslargeStatus: http.StatusOK, oslargeCT: "image/gif", oslargeBody: placeholderGIF, - wantBody: fallbackJPG, - wantFallback: true, + wantNoWM: false, }, } @@ -125,6 +160,13 @@ func TestWeiboDownloadOSLargeSuccessAndAutomaticFallback(t *testing.T) { mu.Unlock() switch req.URL.Path { + case "/large/001SynWmPic.jpg": + return &http.Response{ + StatusCode: http.StatusOK, + ContentLength: int64(len(origJPG)), + Header: http.Header{"Content-Type": []string{"image/jpeg"}}, + Body: io.NopCloser(bytes.NewReader(origJPG)), + }, nil case "/oslarge/001SynWmPic.jpg": return &http.Response{ StatusCode: tc.oslargeStatus, @@ -132,13 +174,6 @@ func TestWeiboDownloadOSLargeSuccessAndAutomaticFallback(t *testing.T) { Header: http.Header{"Content-Type": []string{tc.oslargeCT}}, Body: io.NopCloser(bytes.NewReader(tc.oslargeBody)), }, nil - case "/mw2000/001SynWmPic.jpg": - return &http.Response{ - StatusCode: http.StatusOK, - ContentLength: int64(len(fallbackJPG)), - Header: http.Header{"Content-Type": []string{"image/jpeg"}}, - Body: io.NopCloser(bytes.NewReader(fallbackJPG)), - }, nil default: return &http.Response{ StatusCode: http.StatusNotFound, @@ -163,15 +198,16 @@ func TestWeiboDownloadOSLargeSuccessAndAutomaticFallback(t *testing.T) { CanonicalURL: "https://weibo.com/1000000001/O000002lH", AuthorUID: "1000000001", AuthorName: "合成博主", - Title: "去水印回退单测", - Desc: "去水印回退单测", + Title: "双份无水印单测", + Desc: "双份无水印单测", Images: []site.MediaImageAsset{ { - Index: 1, - MediaRole: "image", - Width: 1200, - Height: 900, - ImageURLs: []string{"https://wx1.sinaimg.cn/oslarge/001SynWmPic.jpg", "https://wx1.sinaimg.cn/mw2000/001SynWmPic.jpg"}, + Index: 1, + MediaRole: "image", + Width: 1200, + Height: 900, + ImageURLs: []string{"https://wx1.sinaimg.cn/large/001SynWmPic.jpg"}, + WatermarkFreeURL: "https://wx1.sinaimg.cn/oslarge/001SynWmPic.jpg", }, }, Media: site.WeiboMediaTransport("Mozilla/5.0 Test", false), @@ -195,33 +231,215 @@ func TestWeiboDownloadOSLargeSuccessAndAutomaticFallback(t *testing.T) { meta, ok, err := libStore.GetItem(plan.ItemKey) if err != nil || !ok || len(meta.NotePages) != 1 || meta.NotePages[0].Image == "" { - t.Fatalf("saved item missing image: ok=%v err=%v meta=%+v", ok, err, meta) + t.Fatalf("saved item missing primary image: ok=%v err=%v meta=%+v", ok, err, meta) + } + if meta.Status != "complete" || len(meta.Missing) != 0 { + t.Fatalf("primary item must stay green complete with 0 missing: status=%q missing=%+v", meta.Status, meta.Missing) } - gotBytes, err := os.ReadFile(filepath.Join(meta.ItemDir, filepath.FromSlash(meta.NotePages[0].Image))) + + gotPrimary, err := os.ReadFile(filepath.Join(meta.ItemDir, filepath.FromSlash(meta.NotePages[0].Image))) if err != nil { - t.Fatalf("read saved image: %v", err) + t.Fatalf("read saved primary image: %v", err) } - if !bytes.Equal(gotBytes, tc.wantBody) { - t.Fatalf("saved image bytes len=%d, want len=%d", len(gotBytes), len(tc.wantBody)) + if !bytes.Equal(gotPrimary, origJPG) { + t.Fatalf("primary image bytes len=%d, want official original len=%d", len(gotPrimary), len(origJPG)) } - if len(hitPaths) == 0 || hitPaths[0] != "/oslarge/001SynWmPic.jpg" { - t.Fatalf("first requested path = %v, want /oslarge/001SynWmPic.jpg", hitPaths) + var nowmMedia *library.MediaFile + for i := range meta.Media { + if meta.Media[i].Role == "image_nowm" { + cp := meta.Media[i] + nowmMedia = &cp + break + } } - if tc.wantFallback { - foundFallback := false - for _, p := range hitPaths[1:] { - if p == "/mw2000/001SynWmPic.jpg" { - foundFallback = true - break - } + + if tc.wantNoWM { + if meta.NotePages[0].NoWatermark != "images/01_nowm.jpg" { + t.Fatalf("NotePages[0].NoWatermark = %q, want images/01_nowm.jpg", meta.NotePages[0].NoWatermark) + } + if nowmMedia == nil || nowmMedia.Path != "images/01_nowm.jpg" || nowmMedia.SHA256 == "" || + nowmMedia.Width != tc.wantNoWMW || nowmMedia.Height != tc.wantNoWMH { + t.Fatalf("unexpected image_nowm MediaFile: %+v", nowmMedia) + } + gotNoWM, err := os.ReadFile(filepath.Join(meta.ItemDir, filepath.FromSlash(nowmMedia.Path))) + if err != nil { + t.Fatalf("read companion image: %v", err) + } + if !bytes.Equal(gotNoWM, tc.wantNoWMBody) { + t.Fatalf("companion bytes mismatch: got=%d want=%d", len(gotNoWM), len(tc.wantNoWMBody)) } - if !foundFallback { - t.Fatalf("expected fallback to /mw2000/001SynWmPic.jpg, got %v", hitPaths) + } else { + if meta.NotePages[0].NoWatermark != "" || nowmMedia != nil { + t.Fatalf("expected no companion saved, got NoWatermark=%q media=%+v", meta.NotePages[0].NoWatermark, nowmMedia) } - } else if len(hitPaths) != 1 { - t.Fatalf("successful /oslarge/ should not hit fallback: %v", hitPaths) + if _, statErr := os.Stat(filepath.Join(meta.ItemDir, "images", "01_nowm.jpg")); !os.IsNotExist(statErr) { + t.Fatalf("expected no stray 01_nowm.jpg on disk, statErr=%v", statErr) + } + } + + if len(hitPaths) != 2 || hitPaths[0] != "/large/001SynWmPic.jpg" || hitPaths[1] != "/oslarge/001SynWmPic.jpg" { + t.Fatalf("requested paths = %v, want [/large/001SynWmPic.jpg, /oslarge/001SynWmPic.jpg]", hitPaths) } }) } } + +func TestWeiboDualSaveSkipsGIFAndBackfillsOldCachedItem(t *testing.T) { + origJPG := makeWatermarkTestJPEG(t, 40, 30, color.RGBA{R: 180, G: 60, B: 40, A: 255}) + nowmJPG := makeWatermarkTestJPEG(t, 24, 18, color.RGBA{R: 30, G: 130, B: 210, A: 255}) + animGIF := makeWatermarkTestAnimatedGIF(t) + + var mu sync.Mutex + var hitPaths []string + rt := roundTripFunc(func(req *http.Request) (*http.Response, error) { + mu.Lock() + hitPaths = append(hitPaths, req.URL.Path) + mu.Unlock() + switch req.URL.Path { + case "/large/pic01.jpg": + return &http.Response{ + StatusCode: http.StatusOK, + ContentLength: int64(len(origJPG)), + Header: http.Header{"Content-Type": []string{"image/jpeg"}}, + Body: io.NopCloser(bytes.NewReader(origJPG)), + }, nil + case "/oslarge/pic01.jpg": + return &http.Response{ + StatusCode: http.StatusOK, + ContentLength: int64(len(nowmJPG)), + Header: http.Header{"Content-Type": []string{"image/jpeg"}}, + Body: io.NopCloser(bytes.NewReader(nowmJPG)), + }, nil + case "/large/anim02.gif": + return &http.Response{ + StatusCode: http.StatusOK, + ContentLength: int64(len(animGIF)), + Header: http.Header{"Content-Type": []string{"image/gif"}}, + Body: io.NopCloser(bytes.NewReader(animGIF)), + }, nil + default: + return &http.Response{ + StatusCode: http.StatusNotFound, + Header: http.Header{"Content-Type": []string{"text/plain"}}, + Body: io.NopCloser(strings.NewReader("missing")), + }, nil + } + }) + + mgr, libStore, _, _, _ := setupDouyinDownloadTestEnv(t, http.NotFoundHandler(), 2) + mgr.SetMediaTransportWrap(func(_ http.RoundTripper) http.RoundTripper { return rt }) + planner := newFakeWeiboSitePlanner() + mgr.RegisterSitePlanner(planner) + + // Step 1: Initial cache simulating an older cached item (WatermarkFreeURL empty -> no companion yet). + planV1 := WorkDownloadPlanFromSite(site.DownloadPlan{ + Site: site.Weibo, + ItemKey: "weibo:dynamic:5000000000009002", + TargetID: "5000000000009002", + Kind: "image_note", + CanonicalURL: "https://weibo.com/1000000001/O000002lI", + AuthorUID: "1000000001", + AuthorName: "合成博主", + Title: "旧条目补齐无水印与GIF跳过", + Desc: "旧条目补齐无水印与GIF跳过", + Images: []site.MediaImageAsset{ + {Index: 1, MediaRole: "image", Width: 1200, Height: 900, ImageURLs: []string{"https://wx1.sinaimg.cn/large/pic01.jpg"}}, + {Index: 2, MediaRole: "gif", Width: 16, Height: 16, ImageURLs: []string{"https://wx1.sinaimg.cn/large/anim02.gif"}}, + }, + Media: site.WeiboMediaTransport("Mozilla/5.0 Test", false), + }) + planV1.Pages[0].MediaID = "pic01" + planV1.Pages[1].MediaID = "anim02" + + task1, err := mgr.EnqueueWeiboWork(context.Background(), WeiboWorkEnqueueRequest{ + TargetID: planV1.TargetID, + Kind: "dynamic", + Plan: &planV1, + }) + if err != nil { + t.Fatalf("EnqueueWeiboWork initial: %v", err) + } + if ft := waitForTaskTerminal(t, mgr, task1.TaskID, 10*time.Second); ft.Status != "completed" { + t.Fatalf("initial task = %+v", ft) + } + meta1, ok, err := libStore.GetItem(planV1.ItemKey) + if err != nil || !ok || len(meta1.NotePages) != 2 || meta1.NotePages[0].NoWatermark != "" { + t.Fatalf("initial item unexpected: ok=%v err=%v meta=%+v", ok, err, meta1) + } + + // Step 2: Re-cache same item with WatermarkFreeURL enabled -> MUST reuse primary images/01.jpg + // (0 requests to /large/pic01.jpg or /large/anim02.gif!), fetch ONLY /oslarge/pic01.jpg, + // skip GIF completely, and write images/01_nowm.jpg into item.json! + mu.Lock() + hitPaths = nil + mu.Unlock() + + planV2 := planV1 + planV2.Pages = append([]PlannedNotePage(nil), planV1.Pages...) + planV2.Pages[0].WatermarkFreeURL = "https://wx1.sinaimg.cn/oslarge/pic01.jpg" + // Deliberately also set a bogus WatermarkFreeURL on the GIF page to confirm case "gif" ignores it. + planV2.Pages[1].WatermarkFreeURL = "https://wx1.sinaimg.cn/oslarge/anim02.gif" + + task2, err := mgr.EnqueueWeiboWork(context.Background(), WeiboWorkEnqueueRequest{ + TargetID: planV2.TargetID, + Kind: "dynamic", + Plan: &planV2, + }) + if err != nil { + t.Fatalf("EnqueueWeiboWork backfill: %v", err) + } + if ft := waitForTaskTerminal(t, mgr, task2.TaskID, 10*time.Second); ft.Status != "completed" { + t.Fatalf("backfill task = %+v (hits=%v)", ft, hitPaths) + } + + mu.Lock() + gotBackfillHits := append([]string(nil), hitPaths...) + mu.Unlock() + if len(gotBackfillHits) != 1 || gotBackfillHits[0] != "/oslarge/pic01.jpg" { + t.Fatalf("backfill hits = %v, want ONLY [/oslarge/pic01.jpg] (primary reused, GIF skipped)", gotBackfillHits) + } + + meta2, ok, err := libStore.GetItem(planV2.ItemKey) + if err != nil || !ok || meta2.Status != "complete" || len(meta2.Missing) != 0 { + t.Fatalf("backfilled item unexpected: ok=%v err=%v status=%q missing=%+v", ok, err, meta2.Status, meta2.Missing) + } + if len(meta2.NotePages) != 2 || meta2.NotePages[0].Image != "images/01.jpg" || meta2.NotePages[0].NoWatermark != "images/01_nowm.jpg" { + t.Fatalf("backfilled NotePages[0] = %+v", meta2.NotePages) + } + if meta2.NotePages[1].Image != "images/02.gif" || meta2.NotePages[1].NoWatermark != "" { + t.Fatalf("GIF page must never save companion: %+v", meta2.NotePages[1]) + } + gotNoWM, err := os.ReadFile(filepath.Join(meta2.ItemDir, "images", "01_nowm.jpg")) + if err != nil || !bytes.Equal(gotNoWM, nowmJPG) { + t.Fatalf("backfilled companion read = (len=%d, err=%v), want len=%d", len(gotNoWM), err, len(nowmJPG)) + } + + // Step 3: Re-cache again with WatermarkFreeURL empty (setting turned off) -> + // monotonically preserves existing verified companion without extra requests! + mu.Lock() + hitPaths = nil + mu.Unlock() + + task3, err := mgr.EnqueueWeiboWork(context.Background(), WeiboWorkEnqueueRequest{ + TargetID: planV1.TargetID, + Kind: "dynamic", + Plan: &planV1, + }) + if err != nil { + t.Fatalf("EnqueueWeiboWork preserve: %v", err) + } + if ft := waitForTaskTerminal(t, mgr, task3.TaskID, 10*time.Second); ft.Status != "completed" { + t.Fatalf("preserve task = %+v", ft) + } + mu.Lock() + gotPreserveHits := append([]string(nil), hitPaths...) + mu.Unlock() + if len(gotPreserveHits) != 0 { + t.Fatalf("expected 0 network requests when reusing both primary & companion, got %v", gotPreserveHits) + } + meta3, ok, err := libStore.GetItem(planV1.ItemKey) + if err != nil || !ok || meta3.NotePages[0].NoWatermark != "images/01_nowm.jpg" { + t.Fatalf("companion was not monotonically preserved: ok=%v err=%v pages=%+v", ok, err, meta3.NotePages) + } +} diff --git a/internal/library/files.go b/internal/library/files.go index 4ad999c..ffc7150 100644 --- a/internal/library/files.go +++ b/internal/library/files.go @@ -64,6 +64,9 @@ func visitManifestFiles(meta ItemMetadata, fn func(ManifestFile)) { if np.Image != "" { fn(ManifestFile{Path: np.Image, Role: "image"}) } + if np.NoWatermark != "" { + fn(ManifestFile{Path: np.NoWatermark, Role: "image_nowm"}) + } if np.Cover != "" { fn(ManifestFile{Path: np.Cover, Role: "cover"}) } diff --git a/internal/library/merge.go b/internal/library/merge.go index e3c0ade..d7de8db 100644 --- a/internal/library/merge.go +++ b/internal/library/merge.go @@ -215,6 +215,9 @@ func MergeItemMetadata(local, imported ItemMetadata, mode string, sameContent fu if dst.Image == "" { dst.Image = src.Image } + if dst.NoWatermark == "" { + dst.NoWatermark = src.NoWatermark + } if dst.Cover == "" { dst.Cover = src.Cover } @@ -621,6 +624,9 @@ func KeepListedFiles(meta ItemMetadata, keep func(rel string) bool) (ItemMetadat if !ok(np.Image) { np.Image = "" } + if !ok(np.NoWatermark) { + np.NoWatermark = "" + } if !ok(np.Cover) { np.Cover = "" } diff --git a/internal/library/schema.go b/internal/library/schema.go index 5abd916..6926024 100644 --- a/internal/library/schema.go +++ b/internal/library/schema.go @@ -284,6 +284,7 @@ type NotePageRecord struct { FromOrigin bool `json:"fromOrigin,omitempty"` UnknownKind string `json:"unknownKind,omitempty"` Image string `json:"image,omitempty"` + NoWatermark string `json:"noWatermark,omitempty"` Cover string `json:"cover,omitempty"` Motion string `json:"motion,omitempty"` Video string `json:"video,omitempty"` @@ -305,7 +306,7 @@ type MusicInfo struct { } type MediaFile struct { - Role string `json:"role"` // "cover", "video", "audio", "danmaku", "subtitle", "image", "motion", "live_segment" + Role string `json:"role"` // "cover", "video", "audio", "danmaku", "subtitle", "image", "image_nowm", "motion", "live_segment" Path string `json:"path"` // relative to item directory GIF bool `json:"gif,omitempty"` FromOrigin bool `json:"fromOrigin,omitempty"` diff --git a/internal/library/weibo_dual_nowm_test.go b/internal/library/weibo_dual_nowm_test.go new file mode 100644 index 0000000..e5f0f1f --- /dev/null +++ b/internal/library/weibo_dual_nowm_test.go @@ -0,0 +1,157 @@ +package library + +import ( + "crypto/sha256" + "encoding/hex" + "os" + "path/filepath" + "testing" + "time" + + "github.com/chialecode/trace/internal/storage" +) + +func TestWeiboNoWatermarkCompanionLifecycleDeleteMergeArchiveRefresh(t *testing.T) { + base := t.TempDir() + db, _, _, err := storage.OpenSQLite(filepath.Join(base, "library.db")) + if err != nil { + t.Fatalf("OpenSQLite: %v", err) + } + defer db.Close() + + cacheDir := filepath.Join(base, "cache") + store, err := OpenWithDataDir(db, cacheDir, base) + if err != nil { + t.Fatalf("OpenWithDataDir: %v", err) + } + + itemDir := filepath.Join(cacheDir, "weibo", "1000000001", "posts", "5000000000009101") + if err := os.MkdirAll(filepath.Join(itemDir, "images"), 0o700); err != nil { + t.Fatal(err) + } + primaryBytes := []byte("synthetic-primary-original-jpeg-bytes-01") + nowmBytes := []byte("synthetic-nowm-companion-jpeg-bytes-01") + if err := os.WriteFile(filepath.Join(itemDir, "images", "01.jpg"), primaryBytes, 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(itemDir, "images", "01_nowm.jpg"), nowmBytes, 0o600); err != nil { + t.Fatal(err) + } + sumPrimary := sha256.Sum256(primaryBytes) + sumNoWM := sha256.Sum256(nowmBytes) + + meta := ItemMetadata{ + Version: 1, + ID: "dynamic:5000000000009101", + Site: "weibo", + Kind: "dynamic", + Status: "complete", + Title: "微博双份原图与无水印生命周期测试", + Text: "微博双份原图与无水印生命周期测试", + DynamicType: "draw", + TypeLabel: "图文", + URL: "https://weibo.com/1000000001/O000002m1", + PubTs: 1764000000, + DirectCached: true, + Author: ItemAuthor{Site: "weibo", UID: "1000000001", Name: "合成博主"}, + Media: []MediaFile{ + {Role: "image", Path: "images/01.jpg", Bytes: int64(len(primaryBytes)), SHA256: hex.EncodeToString(sumPrimary[:]), Width: 1280, Height: 960}, + {Role: "image_nowm", Path: "images/01_nowm.jpg", Bytes: int64(len(nowmBytes)), SHA256: hex.EncodeToString(sumNoWM[:]), Width: 690, Height: 518}, + }, + NotePages: []NotePageRecord{ + {Index: 1, Kind: "image", MediaID: "pic01", Image: "images/01.jpg", NoWatermark: "images/01_nowm.jpg", Width: 1280, Height: 960}, + }, + } + + saved, err := store.SaveItem(itemDir, meta) + if err != nil { + t.Fatalf("SaveItem: %v", err) + } + + // 1. RegisteredFiles & MediaPath include companion file. + reg := RegisteredFiles(saved) + foundPrimary, foundNoWM := false, false + for _, f := range reg { + if f.Path == "images/01.jpg" && f.Role == "image" { + foundPrimary = true + } + if f.Path == "images/01_nowm.jpg" && f.Role == "image_nowm" { + foundNoWM = true + } + } + if !foundPrimary || !foundNoWM { + t.Fatalf("RegisteredFiles missing image or image_nowm: %+v", reg) + } + if p, err := store.MediaPath(saved.ItemKey, "images/01_nowm.jpg"); err != nil || p == "" { + t.Fatalf("MediaPath(image_nowm) = (%q, %v)", p, err) + } + + // 2. ListItems(Kind="image") returns the item once (not duplicated). + listed, err := store.ListItems(FeedFilter{Site: "weibo", Kind: "image", CachedOnly: true}) + if err != nil || len(listed) != 1 { + t.Fatalf("ListItems(image) = (len=%d, err=%v), want 1", len(listed), err) + } + + // 3. MergeItemMetadata supplements NoWatermark & KeepListedFiles prunes missing NoWatermark. + baseMeta := saved + baseMeta.NotePages = []NotePageRecord{{Index: 1, Kind: "image", MediaID: "pic01", Image: "images/01.jpg"}} + baseMeta.Media = []MediaFile{saved.Media[0]} + merged, _ := MergeItemMetadata(baseMeta, saved, "merge", func(rel string) bool { return rel == "images/01.jpg" }) + if len(merged.NotePages) != 1 || merged.NotePages[0].NoWatermark != "images/01_nowm.jpg" { + t.Fatalf("MergeItemMetadata did not supplement NoWatermark: %+v", merged.NotePages) + } + pruned, _ := KeepListedFiles(merged, func(rel string) bool { return rel == "images/01.jpg" }) + if pruned.NotePages[0].NoWatermark != "" || len(pruned.Media) != 1 { + t.Fatalf("KeepListedFiles did not prune omitted image_nowm: pages=%+v media=%+v", pruned.NotePages, pruned.Media) + } + + // 4. ArchiveItemSnapshot preserves both primary and companion in archived V1 snapshot. + archMeta, err := store.ArchiveItemSnapshot(saved.ItemKey, time.Unix(1764000100, 0).UTC()) + if err != nil { + t.Fatalf("ArchiveItemSnapshot: %v", err) + } + if len(archMeta.NotePages) != 1 || archMeta.NotePages[0].NoWatermark != "images/01_nowm.jpg" { + t.Fatalf("archived snapshot lost NoWatermark: %+v", archMeta.NotePages) + } + if _, err := os.Stat(filepath.Join(archMeta.ItemDir, "images", "01_nowm.jpg")); err != nil { + t.Fatalf("archived snapshot missing companion file on disk: %v", err) + } + + // 5. RefreshIndex detects missing companion when manually removed on disk, then Delete removes all. + if err := os.Remove(filepath.Join(itemDir, "images", "01_nowm.jpg")); err != nil { + t.Fatal(err) + } + report, err := store.RefreshIndex() + if err != nil { + t.Fatalf("RefreshIndex: %v", err) + } + if report.MissingFiles < 1 || len(report.NewlyMissing) != 1 || report.NewlyMissing[0].ItemKey != saved.ItemKey { + t.Fatalf("RefreshIndex expected missing companion reported for %s, got %+v", saved.ItemKey, report) + } + + // Restore companion and verify PlanDelete + Delete cleans up both primary and companion. + if err := os.WriteFile(filepath.Join(itemDir, "images", "01_nowm.jpg"), nowmBytes, 0o600); err != nil { + t.Fatal(err) + } + plan, err := store.PlanDelete(saved.ItemKey) + if err != nil { + t.Fatalf("PlanDelete: %v", err) + } + if len(plan.RegisteredFiles) < 2 { + t.Fatalf("PlanDelete RegisteredFiles = %+v, want >= 2 (primary + companion)", plan.RegisteredFiles) + } + res, err := store.Delete(saved.ItemKey) + if err != nil { + t.Fatalf("Delete: %v", err) + } + if len(res.PreservedUserFiles) != 0 { + t.Fatalf("Delete unexpectedly preserved user files (companion leaked?): %+v", res.PreservedUserFiles) + } + if _, err := os.Stat(filepath.Join(itemDir, "images", "01_nowm.jpg")); !os.IsNotExist(err) { + t.Fatalf("Delete left 01_nowm.jpg behind: %v", err) + } + // Archived V1 snapshot stays intact after deleting V2. + if _, err := os.Stat(filepath.Join(archMeta.ItemDir, "images", "01_nowm.jpg")); err != nil { + t.Fatalf("deleting V2 affected archived V1 companion: %v", err) + } +} diff --git a/internal/service/weibo_queue_account_test.go b/internal/service/weibo_queue_account_test.go index e5b114b..eb5b379 100644 --- a/internal/service/weibo_queue_account_test.go +++ b/internal/service/weibo_queue_account_test.go @@ -788,15 +788,13 @@ func TestWeiboFavoritesAccountPageMediaRetweetCacheStateAndPlanReuseGuard(t *tes t.Fatalf("len(Items) = %d, want 2", len(page.Items)) } - // Item 1: wrapped status unwrapped, 2 synthesized /large/ images rewritten to /oslarge/ with /large/ fallback, CacheState=green. + // Item 1: wrapped status unwrapped, 2 synthesized /large/ images stay official original (DEC-078), CacheState=green. it1 := page.Items[0] if it1.ID != "5090000000000101" || it1.Post == nil || len(it1.Post.Images) != 2 || it1.Post.CacheState.Dot != "green" { t.Fatalf("unexpected it1: %+v post=%+v", it1, it1.Post) } - if it1.Post.Images[0].ImageURL != "https://wx2.sinaimg.cn/oslarge/synfavpic1.jpg" || - len(it1.Post.Images[0].FallbackURLs) == 0 || - it1.Post.Images[0].FallbackURLs[0] != "https://wx2.sinaimg.cn/large/synfavpic1.jpg" || - it1.Cover != "https://wx2.sinaimg.cn/oslarge/synfavpic1.jpg" { + if it1.Post.Images[0].ImageURL != "https://wx2.sinaimg.cn/large/synfavpic1.jpg" || + it1.Cover != "https://wx2.sinaimg.cn/large/synfavpic1.jpg" { t.Fatalf("it1 image/cover = (%q, fb=%v, cover=%q)", it1.Post.Images[0].ImageURL, it1.Post.Images[0].FallbackURLs, it1.Cover) } @@ -806,8 +804,7 @@ func TestWeiboFavoritesAccountPageMediaRetweetCacheStateAndPlanReuseGuard(t *tes t.Fatalf("unexpected it2 retweet: %+v", it2.Post) } rt := it2.Post.Retweeted - if len(rt.Images) != 1 || rt.Images[0].ImageURL != "https://wx1.sinaimg.cn/oslarge/synrtfav1.jpg" || - len(rt.Images[0].FallbackURLs) == 0 || rt.Images[0].FallbackURLs[0] != "https://wx1.sinaimg.cn/large/synrtfav1.jpg" { + if len(rt.Images) != 1 || rt.Images[0].ImageURL != "https://wx1.sinaimg.cn/large/synrtfav1.jpg" { t.Fatalf("unexpected rt.Images: %+v", rt.Images) } if rt.Video == nil || rt.Video.Title != "SYNTH_FAV_ORIGIN_VIDEO_TITLE" || rt.Video.CoverURL != "https://wx3.sinaimg.cn/large/synrtvidcover.jpg" || rt.Video.DurationSec != 52 { diff --git a/internal/service/weibo_watermark_test.go b/internal/service/weibo_watermark_test.go index 310d7d1..a488896 100644 --- a/internal/service/weibo_watermark_test.go +++ b/internal/service/weibo_watermark_test.go @@ -109,7 +109,8 @@ func TestWeiboRemoveWatermarkDynamicToggleCacheClearAndSnapshotSync(t *testing.T t.Fatalf("LoginWithCookie: %v", err) } - // 1. Default enabled -> static image & LivePhoto still rewrite to /oslarge/ with original in FallbackURLs[0]; GIF untouched. + // 1. Default enabled -> display URLs ALWAYS stay at official originals (/mw2000/, /large/), + // while download planning populates WatermarkFreeURL (/oslarge/) for static & LivePhoto still (GIF empty). pvOn, err := b.WeiboPost(ctx, mid) if err != nil { t.Fatalf("WeiboPost(on): %v", err) @@ -117,22 +118,36 @@ func TestWeiboRemoveWatermarkDynamicToggleCacheClearAndSnapshotSync(t *testing.T if len(pvOn.Images) != 3 { t.Fatalf("len(Images) = %d, want 3", len(pvOn.Images)) } - if pvOn.Images[0].ImageURL != "https://wx1.sinaimg.cn/oslarge/wm_static_1.jpg" || - len(pvOn.Images[0].FallbackURLs) == 0 || - pvOn.Images[0].FallbackURLs[0] != "https://wx1.sinaimg.cn/mw2000/wm_static_1.jpg" { - t.Fatalf("enabled static pic = (%q, fb=%v)", pvOn.Images[0].ImageURL, pvOn.Images[0].FallbackURLs) + if pvOn.Images[0].ImageURL != "https://wx1.sinaimg.cn/mw2000/wm_static_1.jpg" || + strings.Contains(pvOn.Images[0].ImageURL, "/oslarge/") { + t.Fatalf("enabled static pic URL must stay official original: %q", pvOn.Images[0].ImageURL) } if pvOn.Images[1].ImageURL != "https://wx1.sinaimg.cn/large/wm_gif_2.gif" { t.Fatalf("enabled gif pic = %q, want original .gif", pvOn.Images[1].ImageURL) } - if pvOn.Images[2].ImageURL != "https://wx2.sinaimg.cn/oslarge/wm_live_3.jpg" || - len(pvOn.Images[2].FallbackURLs) == 0 || - pvOn.Images[2].FallbackURLs[0] != "https://wx2.sinaimg.cn/large/wm_live_3.jpg" { - t.Fatalf("enabled livephoto still = (%q, fb=%v)", pvOn.Images[2].ImageURL, pvOn.Images[2].FallbackURLs) + if pvOn.Images[2].ImageURL != "https://wx2.sinaimg.cn/large/wm_live_3.jpg" || + strings.Contains(pvOn.Images[2].ImageURL, "/oslarge/") { + t.Fatalf("enabled livephoto still URL must stay official original: %q", pvOn.Images[2].ImageURL) } - if _, ok := b.weiboPostCache.get(mid, b.preferredWeiboCodec(), b.currentWeiboMaxResolution(), true); !ok { + cachedPostOn, ok := b.weiboPostCache.get(mid, b.preferredWeiboCodec(), b.currentWeiboMaxResolution(), true) + if !ok { t.Fatal("expected post to be cached in weiboPostCache after WeiboPost") } + planOn, err := b.buildWeiboWorkPlanFromPost(cachedPostOn) + if err != nil || len(planOn.Pages) != 3 { + t.Fatalf("buildWeiboWorkPlanFromPost(on) = (%+v, %v)", planOn, err) + } + if planOn.Pages[0].ImageURLs[0] != "https://wx1.sinaimg.cn/mw2000/wm_static_1.jpg" || + planOn.Pages[0].WatermarkFreeURL != "https://wx1.sinaimg.cn/oslarge/wm_static_1.jpg" { + t.Fatalf("planOn static page = %+v", planOn.Pages[0]) + } + if planOn.Pages[1].WatermarkFreeURL != "" { + t.Fatalf("planOn GIF page must not set WatermarkFreeURL: %+v", planOn.Pages[1]) + } + if planOn.Pages[2].ImageURLs[0] != "https://wx2.sinaimg.cn/large/wm_live_3.jpg" || + planOn.Pages[2].WatermarkFreeURL != "https://wx2.sinaimg.cn/oslarge/wm_live_3.jpg" { + t.Fatalf("planOn livephoto page = %+v", planOn.Pages[2]) + } // 2. Disable via UpdateSettings -> clears weiboPostCache immediately and takes effect without restart! cfg := b.GetSettings() @@ -162,6 +177,19 @@ func TestWeiboRemoveWatermarkDynamicToggleCacheClearAndSnapshotSync(t *testing.T if showHits.Load() < 2 { t.Fatalf("expected fresh fetch after toggle, showHits=%d", showHits.Load()) } + cachedPostOff, ok := b.weiboPostCache.get(mid, b.preferredWeiboCodec(), b.currentWeiboMaxResolution(), false) + if !ok { + t.Fatal("expected post to be cached in weiboPostCache after WeiboPost(off)") + } + planOff, err := b.buildWeiboWorkPlanFromPost(cachedPostOff) + if err != nil || len(planOff.Pages) != 3 { + t.Fatalf("buildWeiboWorkPlanFromPost(off) = (%+v, %v)", planOff, err) + } + for i, pg := range planOff.Pages { + if pg.WatermarkFreeURL != "" { + t.Fatalf("disabled planOff.Pages[%d].WatermarkFreeURL = %q, want empty", i, pg.WatermarkFreeURL) + } + } // 3. Remote subscription snapshot propagates WeiboRemoveWatermark=false and legacy nil preserves default true. snap, err := b.SubscriptionSnapshot() diff --git a/internal/site/types.go b/internal/site/types.go index 7d5b9e4..b12e0fb 100644 --- a/internal/site/types.go +++ b/internal/site/types.go @@ -481,18 +481,19 @@ type RichCardSummary struct { // MediaImageAsset describes a single image page (and optional Live Photo or mixed video clip) in an image-note post. type MediaImageAsset struct { - Index int `json:"index"` // 1-based page index - MediaRole string `json:"mediaRole,omitempty"` // "", "image", "gif", "live_photo", "video" - FromOrigin bool `json:"fromOrigin,omitempty"` - Width int `json:"width,omitempty"` - Height int `json:"height,omitempty"` - DurationSec int `json:"durationSec,omitempty"` - VideoCodec string `json:"videoCodec,omitempty"` - QualityLabel string `json:"qualityLabel,omitempty"` - FPS int `json:"fps,omitempty"` - Bitrate int64 `json:"bitrate,omitempty"` - ImageURLs []string `json:"-"` - VideoURLs []string `json:"-"` + Index int `json:"index"` // 1-based page index + MediaRole string `json:"mediaRole,omitempty"` // "", "image", "gif", "live_photo", "video" + FromOrigin bool `json:"fromOrigin,omitempty"` + Width int `json:"width,omitempty"` + Height int `json:"height,omitempty"` + DurationSec int `json:"durationSec,omitempty"` + VideoCodec string `json:"videoCodec,omitempty"` + QualityLabel string `json:"qualityLabel,omitempty"` + FPS int `json:"fps,omitempty"` + Bitrate int64 `json:"bitrate,omitempty"` + ImageURLs []string `json:"-"` + WatermarkFreeURL string `json:"-"` + VideoURLs []string `json:"-"` } // TextLink pairs a human-readable link label with a safe HTTP(S) target URL diff --git a/internal/site/weibo/adapter.go b/internal/site/weibo/adapter.go index 71f4537..afe0628 100644 --- a/internal/site/weibo/adapter.go +++ b/internal/site/weibo/adapter.go @@ -273,14 +273,15 @@ func (a *Adapter) PlanDownloadFromPost(post *Post) (site.DownloadPlan, error) { } asset := site.MediaImageAsset{ - Index: idx, - MediaRole: img.Kind, - FromOrigin: img.FromOrigin, - Width: img.Width, - Height: img.Height, - DurationSec: img.DurationSec, - ImageURLs: imgURLs, - VideoURLs: vidURLs, + Index: idx, + MediaRole: img.Kind, + FromOrigin: img.FromOrigin, + Width: img.Width, + Height: img.Height, + DurationSec: img.DurationSec, + ImageURLs: imgURLs, + WatermarkFreeURL: img.WatermarkFreeURL, + VideoURLs: vidURLs, } if img.VideoStream != nil { asset.VideoCodec = img.VideoStream.Codec @@ -545,6 +546,7 @@ func buildPostSnapshot(p *Post) *postSnapshot { img.PublicPreviewURL = SafePublicImageURL(img.PublicPreviewURL) img.URL = "" img.FallbackURLs = nil + img.WatermarkFreeURL = "" img.MotionURL = "" img.MotionFallbackURLs = nil img.GIFVideoURL = "" diff --git a/internal/site/weibo/post.go b/internal/site/weibo/post.go index 2248693..0168ecc 100644 --- a/internal/site/weibo/post.go +++ b/internal/site/weibo/post.go @@ -111,6 +111,7 @@ type ImageAsset struct { PublicPreviewURL string `json:"publicPreviewUrl,omitempty"` // only unsigned sinaimg.cn URL URL string `json:"-"` FallbackURLs []string `json:"-"` + WatermarkFreeURL string `json:"-"` // optional companion /oslarge/ URL (never replaces official original URL) MotionURL string `json:"-"` // LivePhoto .mov/.mp4 or mixed video .mp4 MotionFallbackURLs []string `json:"-"` GIFVideoURL string `json:"-"` // optional transcoded MP4 for GIF (primary is original .gif in URL) @@ -1625,13 +1626,14 @@ func (c *Client) buildImageAsset(index int, picID string, pi *rawPicInfo, rewrit } } - // Optional configurable lossless watermark-free rewrite hook (/oslarge/ with automatic fallback - // to the original largest/original URL). Animated GIFs never rewrite to avoid breaking frames. - primaryURL := primary.url + // Keep URL strictly at the official highest-resolution original (largest/original/mw2000/large). + // When watermark-free dual-save is enabled, populate WatermarkFreeURL with the /oslarge/ + // companion address (690px-wide maximum watermark-free tier per ACT-023 V-07 & DEC-078). + // Animated GIFs never generate a companion URL. + var watermarkFreeURL string if kind != MediaKindGIF && rewriter != nil { - if rewritten, ok := rewriter(picID, primaryURL); ok && rewritten != "" && rewritten != primaryURL { - fallbacks = append([]string{primaryURL}, fallbacks...) - primaryURL = rewritten + if rewritten, ok := rewriter(picID, primary.url); ok && rewritten != "" && rewritten != primary.url { + watermarkFreeURL = rewritten } } @@ -1642,8 +1644,9 @@ func (c *Client) buildImageAsset(index int, picID string, pi *rawPicInfo, rewrit Width: primary.width, Height: primary.height, PublicPreviewURL: SafePublicImageURL(primary.url), - URL: primaryURL, + URL: primary.url, FallbackURLs: fallbacks, + WatermarkFreeURL: watermarkFreeURL, MotionURL: motionURL, GIFVideoURL: gifVideoURL, NeedsLivePhotoHop: needsLivePhotoHop, @@ -1665,8 +1668,9 @@ func isGIFImageURL(rawURL string) bool { return strings.HasSuffix(strings.ToLower(strings.TrimSpace(u.Path)), ".gif") } -// RewriteWatermarkFreeImageURL rewrites a static sinaimg.cn image URL to the lossless /oslarge/ -// path segment (never the resolution-capping /osj1080/ tier). Animated .gif URLs are left untouched. +// RewriteWatermarkFreeImageURL rewrites a static sinaimg.cn image URL to the /oslarge/ +// companion path segment (690px-wide watermark-free maximum tier observed in ACT-023 V-07; +// saved alongside the official original per DEC-078). Animated .gif URLs are left untouched. func RewriteWatermarkFreeImageURL(rawURL string) (string, bool) { if isGIFImageURL(rawURL) { return "", false diff --git a/internal/site/weibo/post_media_fallback.go b/internal/site/weibo/post_media_fallback.go index 5c94e8e..8976444 100644 --- a/internal/site/weibo/post_media_fallback.go +++ b/internal/site/weibo/post_media_fallback.go @@ -244,12 +244,10 @@ func (c *Client) buildSingleMobilePicAsset( } } - primaryURL := baseURL - var fallbacks []string + var watermarkFreeURL string if kind != MediaKindGIF && rewriter != nil { - if rewritten, ok := rewriter(picID, primaryURL); ok && rewritten != "" && rewritten != primaryURL { - fallbacks = []string{primaryURL} - primaryURL = rewritten + if rewritten, ok := rewriter(picID, baseURL); ok && rewritten != "" && rewritten != baseURL { + watermarkFreeURL = rewritten } } @@ -260,8 +258,8 @@ func (c *Client) buildSingleMobilePicAsset( Width: w, Height: h, PublicPreviewURL: SafePublicImageURL(baseURL), - URL: primaryURL, - FallbackURLs: fallbacks, + URL: baseURL, + WatermarkFreeURL: watermarkFreeURL, MotionURL: motionURL, GIFVideoURL: gifVideoURL, NeedsLivePhotoHop: needsLivePhotoHop, @@ -365,12 +363,10 @@ func (c *Client) buildPicIDFallbackAssets(rp *rawPost, rewriter func(picID, rawU if ext == ".gif" { kind = MediaKindGIF } - primaryURL := baseURL - var fallbacks []string + var watermarkFreeURL string if kind != MediaKindGIF && rewriter != nil { - if rewritten, ok := rewriter(picID, primaryURL); ok && rewritten != "" && rewritten != primaryURL { - fallbacks = []string{primaryURL} - primaryURL = rewritten + if rewritten, ok := rewriter(picID, baseURL); ok && rewritten != "" && rewritten != baseURL { + watermarkFreeURL = rewritten } } return ImageAsset{ @@ -378,8 +374,8 @@ func (c *Client) buildPicIDFallbackAssets(rp *rawPost, rewriter func(picID, rawU PicID: picID, Kind: kind, PublicPreviewURL: SafePublicImageURL(baseURL), - URL: primaryURL, - FallbackURLs: fallbacks, + URL: baseURL, + WatermarkFreeURL: watermarkFreeURL, }, true } diff --git a/internal/site/weibo/post_test.go b/internal/site/weibo/post_test.go index 22f2be9..2e81abf 100644 --- a/internal/site/weibo/post_test.go +++ b/internal/site/weibo/post_test.go @@ -227,13 +227,13 @@ func TestPostOver9ImagesOrderGIFLivePhotoMixedAndWatermarkHook(t *testing.T) { t.Fatalf("image[%d] = (%q, idx=%d), want (%q, idx=%d)", i, post.Images[i].PicID, post.Images[i].Index, wantID, i+1) } } - // Image 0: watermark hook rewrote /mw2000/ -> /oslarge/, original kept as first fallback. - if !strings.Contains(post.Images[0].URL, "/oslarge/") || len(post.Images[0].FallbackURLs) == 0 || !strings.Contains(post.Images[0].FallbackURLs[0], "/mw2000/") { - t.Fatalf("watermark hook URL/fallback = (%q, %v)", post.Images[0].URL, post.Images[0].FallbackURLs) + // Image 0: primary URL stays official original /mw2000/, watermark hook populates companion WatermarkFreeURL (/oslarge/). + if !strings.Contains(post.Images[0].URL, "/mw2000/") || !strings.Contains(post.Images[0].WatermarkFreeURL, "/oslarge/") { + t.Fatalf("watermark hook URL/companion = (%q, %q)", post.Images[0].URL, post.Images[0].WatermarkFreeURL) } - // Image 1: GIF takes original .gif largest.url. - if post.Images[1].Kind != MediaKindGIF || !strings.HasSuffix(post.Images[1].URL, ".gif") { - t.Fatalf("GIF image = (%q, %q)", post.Images[1].Kind, post.Images[1].URL) + // Image 1: GIF takes original .gif largest.url and never sets WatermarkFreeURL. + if post.Images[1].Kind != MediaKindGIF || !strings.HasSuffix(post.Images[1].URL, ".gif") || post.Images[1].WatermarkFreeURL != "" { + t.Fatalf("GIF image = (%q, %q, wmFree=%q)", post.Images[1].Kind, post.Images[1].URL, post.Images[1].WatermarkFreeURL) } // Image 2: LivePhoto has still URL + motion video + NeedsLivePhotoHop=true for video.weibo.com/media/play. if post.Images[2].Kind != MediaKindLivePhoto || !post.Images[2].NeedsLivePhotoHop || !strings.Contains(post.Images[2].MotionURL, "video.weibo.com/media/play") { diff --git a/internal/site/weibo/watermark_test.go b/internal/site/weibo/watermark_test.go index 6a09244..ac739d0 100644 --- a/internal/site/weibo/watermark_test.go +++ b/internal/site/weibo/watermark_test.go @@ -106,8 +106,9 @@ func TestBuildImageAssetAndFallbackBuildersSkipGIFAndPreserveOriginalFallback(t }, }) - // 1. Standard pic_infos: static pic + LivePhoto still rewrite to /oslarge/ with largest in FallbackURLs[0]; - // GIF (even if URL omits .gif suffix) NEVER calls rewriter and NEVER rewrites. + // 1. Standard pic_infos: primary URL ALWAYS stays the official original (largest/mw2000/large); + // static pic & LivePhoto still populate WatermarkFreeURL with /oslarge/; + // GIF (even if URL omits .gif suffix) NEVER populates WatermarkFreeURL. rawJSON := `{ "ok": 1, "idstr": "5000000000000801", @@ -160,31 +161,57 @@ func TestBuildImageAssetAndFallbackBuildersSkipGIFAndPreserveOriginalFallback(t if len(post.Images) != 4 { t.Fatalf("len(Images) = %d, want 4", len(post.Images)) } - if post.Images[0].URL != "https://wx1.sinaimg.cn/oslarge/p_static.jpg" || - len(post.Images[0].FallbackURLs) == 0 || - post.Images[0].FallbackURLs[0] != "https://wx1.sinaimg.cn/mw2000/p_static.jpg" { - t.Fatalf("static pic = (%q, fb=%v)", post.Images[0].URL, post.Images[0].FallbackURLs) + if post.Images[0].URL != "https://wx1.sinaimg.cn/mw2000/p_static.jpg" || + post.Images[0].WatermarkFreeURL != "https://wx1.sinaimg.cn/oslarge/p_static.jpg" { + t.Fatalf("static pic = (url=%q, wmFree=%q)", post.Images[0].URL, post.Images[0].WatermarkFreeURL) } - if post.Images[1].Kind != MediaKindGIF || strings.Contains(post.Images[1].URL, "/oslarge/") { - t.Fatalf("typed GIF must not rewrite: kind=%q url=%q", post.Images[1].Kind, post.Images[1].URL) + if post.Images[1].Kind != MediaKindGIF || + post.Images[1].URL != "https://wx1.sinaimg.cn/large/p_gif_typed.jpg" || + post.Images[1].WatermarkFreeURL != "" { + t.Fatalf("typed GIF must not set WatermarkFreeURL: kind=%q url=%q wmFree=%q", post.Images[1].Kind, post.Images[1].URL, post.Images[1].WatermarkFreeURL) } - if post.Images[2].Kind != MediaKindGIF || strings.Contains(post.Images[2].URL, "/oslarge/") { - t.Fatalf("ext GIF must not rewrite: kind=%q url=%q", post.Images[2].Kind, post.Images[2].URL) + if post.Images[2].Kind != MediaKindGIF || + post.Images[2].URL != "https://wx1.sinaimg.cn/large/p_gif_ext.gif" || + post.Images[2].WatermarkFreeURL != "" { + t.Fatalf("ext GIF must not set WatermarkFreeURL: kind=%q url=%q wmFree=%q", post.Images[2].Kind, post.Images[2].URL, post.Images[2].WatermarkFreeURL) } if post.Images[3].Kind != MediaKindLivePhoto || - post.Images[3].URL != "https://wx2.sinaimg.cn/oslarge/p_live.jpg" || - len(post.Images[3].FallbackURLs) == 0 || - post.Images[3].FallbackURLs[0] != "https://wx2.sinaimg.cn/large/p_live.jpg" { - t.Fatalf("livephoto still = (%q, fb=%v)", post.Images[3].URL, post.Images[3].FallbackURLs) + post.Images[3].URL != "https://wx2.sinaimg.cn/large/p_live.jpg" || + post.Images[3].WatermarkFreeURL != "https://wx2.sinaimg.cn/oslarge/p_live.jpg" { + t.Fatalf("livephoto still = (url=%q, wmFree=%q)", post.Images[3].URL, post.Images[3].WatermarkFreeURL) } if post.Retweeted == nil || len(post.Retweeted.Images) != 1 || - post.Retweeted.Images[0].URL != "https://wx3.sinaimg.cn/oslarge/p_orig.jpg" || - len(post.Retweeted.Images[0].FallbackURLs) == 0 || - post.Retweeted.Images[0].FallbackURLs[0] != "https://wx3.sinaimg.cn/mw2000/p_orig.jpg" { + post.Retweeted.Images[0].URL != "https://wx3.sinaimg.cn/mw2000/p_orig.jpg" || + post.Retweeted.Images[0].WatermarkFreeURL != "https://wx3.sinaimg.cn/oslarge/p_orig.jpg" { t.Fatalf("retweeted origin pic = %+v", post.Retweeted) } - // 2. Mobile pics[] fallback builder also skips GIF and preserves fallback for static images. + // Verify Adapter.PlanDownloadFromPost propagates WatermarkFreeURL and buildPostSnapshot strips it. + adapter := NewAdapter(client) + dlPlan, err := adapter.PlanDownloadFromPost(post) + if err != nil { + t.Fatalf("PlanDownloadFromPost: %v", err) + } + if len(dlPlan.Images) != 5 { + t.Fatalf("len(dlPlan.Images) = %d, want 5", len(dlPlan.Images)) + } + if dlPlan.Images[0].ImageURLs[0] != "https://wx1.sinaimg.cn/mw2000/p_static.jpg" || + dlPlan.Images[0].WatermarkFreeURL != "https://wx1.sinaimg.cn/oslarge/p_static.jpg" { + t.Fatalf("dlPlan.Images[0] = %+v", dlPlan.Images[0]) + } + if dlPlan.Images[1].WatermarkFreeURL != "" || dlPlan.Images[2].WatermarkFreeURL != "" { + t.Fatalf("dlPlan GIFs unexpectedly carry WatermarkFreeURL: %+v %+v", dlPlan.Images[1], dlPlan.Images[2]) + } + if dlPlan.Images[3].WatermarkFreeURL != "https://wx2.sinaimg.cn/oslarge/p_live.jpg" || + dlPlan.Images[4].WatermarkFreeURL != "https://wx3.sinaimg.cn/oslarge/p_orig.jpg" { + t.Fatalf("dlPlan live/origin = %+v %+v", dlPlan.Images[3], dlPlan.Images[4]) + } + snap := buildPostSnapshot(post) + if snap == nil || len(snap.Images) != 4 || snap.Images[0].WatermarkFreeURL != "" || snap.Images[0].URL != "" { + t.Fatalf("buildPostSnapshot did not scrub runtime URLs: %+v", snap) + } + + // 2. Mobile pics[] fallback builder also keeps primary at /large/ and populates WatermarkFreeURL only for non-GIF. mobileJSON := `{ "ok": 1, "idstr": "5000000000000802", @@ -200,13 +227,32 @@ func TestBuildImageAssetAndFallbackBuildersSkipGIFAndPreserveOriginalFallback(t if err != nil || len(mPost.Images) != 2 { t.Fatalf("mobile ParseRawPostJSON = (%+v, %v)", mPost, err) } - if mPost.Images[0].URL != "https://wx1.sinaimg.cn/oslarge/mob_pic.jpg" || - len(mPost.Images[0].FallbackURLs) != 1 || - mPost.Images[0].FallbackURLs[0] != "https://wx1.sinaimg.cn/large/mob_pic.jpg" { - t.Fatalf("mobile static pic = (%q, fb=%v)", mPost.Images[0].URL, mPost.Images[0].FallbackURLs) + if mPost.Images[0].URL != "https://wx1.sinaimg.cn/large/mob_pic.jpg" || + mPost.Images[0].WatermarkFreeURL != "https://wx1.sinaimg.cn/oslarge/mob_pic.jpg" { + t.Fatalf("mobile static pic = (url=%q, wmFree=%q)", mPost.Images[0].URL, mPost.Images[0].WatermarkFreeURL) + } + if mPost.Images[1].Kind != MediaKindGIF || + mPost.Images[1].URL != "https://wx1.sinaimg.cn/large/mob_gif.jpg" || + mPost.Images[1].WatermarkFreeURL != "" { + t.Fatalf("mobile gif pic = (kind=%q, url=%q, wmFree=%q)", mPost.Images[1].Kind, mPost.Images[1].URL, mPost.Images[1].WatermarkFreeURL) + } + + // 3. pic_ids fallback builder keeps primary at /large/ and populates WatermarkFreeURL. + picIDJSON := `{ + "ok": 1, + "idstr": "5000000000000803", + "mblogid": "O000000cX", + "text_raw": "pic_ids 回退夹具", + "user": {"idstr": "1000000001", "screen_name": "合成博主"}, + "pic_ids": ["pid_fallback_01"] + }` + pPost, err := client.ParseRawPostJSON([]byte(picIDJSON)) + if err != nil || len(pPost.Images) != 1 { + t.Fatalf("pic_ids ParseRawPostJSON = (%+v, %v)", pPost, err) } - if mPost.Images[1].Kind != MediaKindGIF || mPost.Images[1].URL != "https://wx1.sinaimg.cn/large/mob_gif.jpg" { - t.Fatalf("mobile gif pic = (%q, %q)", mPost.Images[1].Kind, mPost.Images[1].URL) + if pPost.Images[0].URL != "https://wx1.sinaimg.cn/large/pid_fallback_01.jpg" || + pPost.Images[0].WatermarkFreeURL != "https://wx1.sinaimg.cn/oslarge/pid_fallback_01.jpg" { + t.Fatalf("pic_ids fallback = (url=%q, wmFree=%q)", pPost.Images[0].URL, pPost.Images[0].WatermarkFreeURL) } } diff --git a/internal/ui/app.go b/internal/ui/app.go index c5986b2..72cb6f1 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -46,36 +46,40 @@ const ( // ImageViewerState holds state for the in-app image and mixed-page viewer overlay. type ImageViewerState struct { - Open bool - URLs []string - FallbackURLs [][]string - LocalPaths []string - ItemKey string - RelPaths []string - InlineSite string // site whose CDN serves InlineMediaURLs ("bilibili" or "douyin") - InlinePageKinds []string // per page: "image" | "live_photo" | "video" | "unknown" - InlineMediaPaths []string // per page: resolved local motion/video file path - InlineMediaURLs []string // per page: online motion/video URL for uncached preview - InlineDurations []int // per page: duration in seconds when known - InlineLoopMuted []bool // per page: true for looping muted GIF MP4s (e.g. X animated_gif) - InlineActive bool - InlinePageIndex int - InlineLoading bool - InlineError string - InlineMediaPath string - InlineLoopPaused bool - Index int - Zoom float32 - PanX float32 - PanY float32 - Fit bool - Dragging bool - PointerX float32 - PointerY float32 - Bitmaps []*ui.Bitmap - Errors []string - LastActiveAt time.Time - ControlsHidden bool + Open bool + URLs []string + FallbackURLs [][]string + LocalPaths []string + ItemKey string + RelPaths []string + InlineSite string // site whose CDN serves InlineMediaURLs ("bilibili" or "douyin") + InlinePageKinds []string // per page: "image" | "live_photo" | "video" | "unknown" + InlineMediaPaths []string // per page: resolved local motion/video file path + InlineMediaURLs []string // per page: online motion/video URL for uncached preview + InlineDurations []int // per page: duration in seconds when known + InlineLoopMuted []bool // per page: true for looping muted GIF MP4s (e.g. X animated_gif) + InlineActive bool + InlinePageIndex int + InlineLoading bool + InlineError string + InlineMediaPath string + InlineLoopPaused bool + Index int + Zoom float32 + PanX float32 + PanY float32 + Fit bool + Dragging bool + PointerX float32 + PointerY float32 + Bitmaps []*ui.Bitmap + Errors []string + NoWatermarkPaths []string // per page: resolved local companion watermark-free image path + NoWatermarkBitmaps []*ui.Bitmap // decoded companion watermark-free bitmaps (parallel to Bitmaps) + NoWatermarkErrors []string // per page: companion load error (never blocks original) + ShowNoWatermark bool // false = original (default), true = watermark-free companion when available + LastActiveAt time.Time + ControlsHidden bool } // PlayerOverlayState holds state for the in-app media player overlay. diff --git a/internal/ui/douyin_media.go b/internal/ui/douyin_media.go index 3e509ac..0a46a88 100644 --- a/internal/ui/douyin_media.go +++ b/internal/ui/douyin_media.go @@ -22,6 +22,7 @@ type douyinNoteRenderPage struct { ImageURL string FallbackImageURLs []string ImageRel string + NoWatermarkRel string MotionURL string MotionRel string VideoURL string @@ -411,6 +412,7 @@ func (a *App) openNotePagesViewer(itemKey, siteID string, pages []douyinNoteRend urls := make([]string, len(pages)) fallbackURLs := make([][]string, len(pages)) localStills := make([]string, len(pages)) + noWMPaths := make([]string, len(pages)) rels := make([]string, len(pages)) kinds := make([]string, len(pages)) inlinePaths := make([]string, len(pages)) @@ -418,6 +420,22 @@ func (a *App) openNotePagesViewer(itemKey, siteID string, pages []douyinNoteRend inlineDurs := make([]int, len(pages)) inlineLoopMuted := make([]bool, len(pages)) + var cachedItem *library.ItemMetadata + if itemKey != "" && a.backend != nil { + needLookup := false + for _, pg := range pages { + if pg.ImageRel != "" && pg.NoWatermarkRel == "" { + needLookup = true + break + } + } + if needLookup { + if it, ok, err := a.backend.GetLibraryItem(itemKey); err == nil && ok { + cachedItem = &it + } + } + } + offline := a.CurrentRoute == RouteLibrary || a.CurrentRoute == RouteLibraryItem for i, pg := range pages { if !offline { @@ -431,6 +449,7 @@ func (a *App) openNotePagesViewer(itemKey, siteID string, pages []douyinNoteRend if p, err := a.backend.MediaPath(itemKey, pg.ImageRel); err == nil { localStills[i] = p } + noWMPaths[i] = a.resolveCompanionNoWatermarkPath(itemKey, cachedItem, pg.ImageRel, pg.NoWatermarkRel) } normKind := pg.Kind if normKind == "motion" { @@ -461,7 +480,7 @@ func (a *App) openNotePagesViewer(itemKey, siteID string, pages []douyinNoteRend } } - a.OpenImageViewerWithFallbacks(urls, fallbackURLs, localStills, index) + a.openImageViewerWithCompanions(urls, fallbackURLs, localStills, noWMPaths, index) a.ImageViewer.ItemKey = itemKey a.ImageViewer.RelPaths = rels a.ImageViewer.InlinePageKinds = kinds @@ -509,16 +528,18 @@ func buildDouyinNoteRenderPages(work *service.DouyinWorkView, cached *library.It if kind == "motion" || (kind == "image" && rec.Motion != "") { kind = "live_photo" } + imgRel := firstNonEmptyStrUI(rec.Image, rec.Cover) pg := douyinNoteRenderPage{ - Index: rec.Index, - Kind: kind, - IsGIF: rec.GIF, - ImageRel: firstNonEmptyStrUI(rec.Image, rec.Cover), - MotionRel: rec.Motion, - VideoRel: rec.Video, - Width: rec.Width, - Height: rec.Height, - DurationSec: rec.Duration, + Index: rec.Index, + Kind: kind, + IsGIF: rec.GIF, + ImageRel: imgRel, + NoWatermarkRel: firstNonEmptyStrUI(rec.NoWatermark, findCompanionNoWatermarkRel(cached, imgRel)), + MotionRel: rec.Motion, + VideoRel: rec.Video, + Width: rec.Width, + Height: rec.Height, + DurationSec: rec.Duration, } if rec.UnknownKind != "" { pg.UnknownReason = "暂不支持的页面类型:" + rec.UnknownKind @@ -579,12 +600,13 @@ func buildDouyinNoteRenderPages(work *service.DouyinWorkView, cached *library.It kind = "live_photo" } out = append(out, douyinNoteRenderPage{ - Index: idx, - Kind: kind, - ImageRel: m.Path, - MotionRel: m.Motion, - Width: m.Width, - Height: m.Height, + Index: idx, + Kind: kind, + ImageRel: m.Path, + NoWatermarkRel: findCompanionNoWatermarkRel(cached, m.Path), + MotionRel: m.Motion, + Width: m.Width, + Height: m.Height, }) } } diff --git a/internal/ui/image_viewer.go b/internal/ui/image_viewer.go index c2b790c..dfe34f4 100644 --- a/internal/ui/image_viewer.go +++ b/internal/ui/image_viewer.go @@ -58,6 +58,10 @@ func (a *App) renderImageViewerOverlay(c *ui.Context, w, h float32) { a.ImageViewer.Index = total - 1 } + curIdx := a.ImageViewer.Index + hasNoWM := curIdx >= 0 && curIdx < len(a.ImageViewer.NoWatermarkPaths) && a.ImageViewer.NoWatermarkPaths[curIdx] != "" + showingNoWM := hasNoWM && a.ImageViewer.ShowNoWatermark + switchViewerPage := func(nextIdx int) { if nextIdx == a.ImageViewer.Index || nextIdx < 0 || nextIdx >= total { return @@ -152,9 +156,13 @@ func (a *App) renderImageViewerOverlay(c *ui.Context, w, h float32) { ui.Image(c, vBmp).Size(w, h).Fit(ui.Contain).Absolute().Left(0).Top(0) } } else { - bmpIdx := a.ImageViewer.Index - if bmpIdx >= 0 && bmpIdx < len(a.ImageViewer.Bitmaps) && a.ImageViewer.Bitmaps[bmpIdx] != nil { - bmp := a.ImageViewer.Bitmaps[bmpIdx] + var bmp *ui.Bitmap + if showingNoWM && curIdx < len(a.ImageViewer.NoWatermarkBitmaps) && a.ImageViewer.NoWatermarkBitmaps[curIdx] != nil { + bmp = a.ImageViewer.NoWatermarkBitmaps[curIdx] + } else if curIdx >= 0 && curIdx < len(a.ImageViewer.Bitmaps) { + bmp = a.ImageViewer.Bitmaps[curIdx] + } + if bmp != nil { bw, bh := bmp.Size() scale := a.ImageViewer.Zoom if a.ImageViewer.Fit && bw > 0 && bh > 0 { @@ -223,7 +231,7 @@ func (a *App) renderImageViewerOverlay(c *ui.Context, w, h float32) { // Minimal floating circular controls (fade out after 2s of inactivity) if !a.ImageViewer.ControlsHidden { - // Top floating bar: index/zoom badge on left + Close circular button on right + // Top floating bar: index/zoom badge + optional 原图/无水印 toggle on left, Close button on right ui.Row(c). Absolute(). Top(20). @@ -232,9 +240,62 @@ func (a *App) renderImageViewerOverlay(c *ui.Context, w, h float32) { AlignItems(ui.Center). Justify(ui.SpaceBetween). Children(func() { - ui.Box(c).Padding(6, 14).Radius(999).Background(ui.RGBA(255, 255, 255, 0.14)).Border(1, ui.RGBA(255, 255, 255, 0.2)).Children(func() { - ui.Text(c, fmt.Sprintf("%d / %d · %.0f%%", a.ImageViewer.Index+1, total, a.ImageViewer.Zoom*100)). - FontSize(13).FontWeight(600).TextColor(ColorWhite).SingleLine() + ui.Row(c).AlignItems(ui.Center).Gap(10).Children(func() { + ui.Box(c).Padding(6, 14).Radius(999).Background(ui.RGBA(255, 255, 255, 0.14)).Border(1, ui.RGBA(255, 255, 255, 0.2)).Children(func() { + ui.Text(c, fmt.Sprintf("%d / %d · %.0f%%", a.ImageViewer.Index+1, total, a.ImageViewer.Zoom*100)). + FontSize(13).FontWeight(600).TextColor(ColorWhite).SingleLine() + }) + if hasNoWM { + ui.Row(c). + Label("看图切换原图无水印"). + Padding(3). + Radius(999). + Background(ui.RGBA(255, 255, 255, 0.14)). + Border(1, ui.RGBA(255, 255, 255, 0.2)). + Gap(2). + AlignItems(ui.Center). + Children(func() { + origBtn := ui.ButtonBase(c). + Label("看图显示原图"). + Padding(4, 12). + Radius(999) + origColor := ui.RGBA(255, 255, 255, 0.78) + if !a.ImageViewer.ShowNoWatermark { + origBtn.Background(ui.RGBA(255, 255, 255, 0.92)) + origColor = ColorTextMain + } else if origBtn.Hovered() { + origBtn.Background(ui.RGBA(255, 255, 255, 0.14)) + } + origBtn.Children(func() { + ui.Text(c, "原图").FontSize(12).FontWeight(600).TextColor(origColor).SingleLine() + }) + if origBtn.Clicked() { + a.wakeImageViewerControls(now) + a.stopViewerInlinePlayback() + a.ImageViewer.ShowNoWatermark = false + } + + nowmBtn := ui.ButtonBase(c). + Label("看图显示无水印"). + Padding(4, 12). + Radius(999) + nowmColor := ui.RGBA(255, 255, 255, 0.78) + if a.ImageViewer.ShowNoWatermark { + nowmBtn.Background(ui.RGBA(255, 255, 255, 0.92)) + nowmColor = ColorTextMain + } else if nowmBtn.Hovered() { + nowmBtn.Background(ui.RGBA(255, 255, 255, 0.14)) + } + nowmBtn.Children(func() { + ui.Text(c, "无水印").FontSize(12).FontWeight(600).TextColor(nowmColor).SingleLine() + }) + if nowmBtn.Clicked() { + a.wakeImageViewerControls(now) + a.stopViewerInlinePlayback() + a.ImageViewer.ShowNoWatermark = true + } + }) + } }) if FloatingCircleButton(c, "close", "关闭看图", 42).Clicked() { a.closeImageViewer() diff --git a/internal/ui/media_controls.go b/internal/ui/media_controls.go index 397ca4a..c48e9d5 100644 --- a/internal/ui/media_controls.go +++ b/internal/ui/media_controls.go @@ -37,6 +37,10 @@ func (a *App) closeImageViewer() { } a.ImageViewer.Open = false a.ImageViewer.Bitmaps = nil + a.ImageViewer.NoWatermarkPaths = nil + a.ImageViewer.NoWatermarkBitmaps = nil + a.ImageViewer.NoWatermarkErrors = nil + a.ImageViewer.ShowNoWatermark = false a.ImageViewer.InlineLoopMuted = nil a.ImageViewer.InlineLoopPaused = false } diff --git a/internal/ui/media_open.go b/internal/ui/media_open.go index 3db29b2..f2a2d3d 100644 --- a/internal/ui/media_open.go +++ b/internal/ui/media_open.go @@ -191,6 +191,55 @@ func (a *App) lookupAccountAvatarBitmap(siteID, uid string) *ui.Bitmap { return bmp } +func findCompanionNoWatermarkRel(item *library.ItemMetadata, imageRel string) string { + imageRel = strings.TrimSpace(filepath.ToSlash(imageRel)) + if item == nil || imageRel == "" { + return "" + } + for _, pg := range item.NotePages { + if strings.TrimSpace(filepath.ToSlash(pg.Image)) == imageRel && strings.TrimSpace(pg.NoWatermark) != "" { + return strings.TrimSpace(filepath.ToSlash(pg.NoWatermark)) + } + } + ext := filepath.Ext(imageRel) + stem := strings.TrimSuffix(imageRel, ext) + if stem == "" { + return "" + } + wantPrefix := stem + "_nowm." + for _, mf := range item.Media { + if mf.Role == "image_nowm" { + p := strings.TrimSpace(filepath.ToSlash(mf.Path)) + if strings.HasPrefix(p, wantPrefix) { + return p + } + } + } + return "" +} + +func (a *App) resolveCompanionNoWatermarkPath(itemKey string, item *library.ItemMetadata, imageRel, noWMRel string) string { + if a.backend == nil || strings.TrimSpace(itemKey) == "" { + return "" + } + candRel := strings.TrimSpace(filepath.ToSlash(noWMRel)) + if candRel == "" && item != nil { + candRel = findCompanionNoWatermarkRel(item, imageRel) + } + if candRel == "" { + return "" + } + full, err := a.backend.MediaPath(itemKey, candRel) + if err != nil || full == "" { + return "" + } + info, err := os.Stat(full) + if err != nil || !info.Mode().IsRegular() || info.Size() <= 0 { + return "" + } + return full +} + // OpenItemImageViewer resolves registered relative media paths via Backend.MediaPath (INV-08) and opens the image viewer. // A live photo's cached motion clip plays inside the viewer (DEC-046 ①). func (a *App) OpenItemImageViewer(itemKey string, urls []string, relPaths []string, index int) { @@ -221,6 +270,7 @@ func (a *App) openPostImageViewer(itemKey, siteID string, urls, relPaths, liveUR inlinePaths := make([]string, n) inlineURLs := make([]string, n) durations := make([]int, n) + noWMPaths := make([]string, n) hasLive := false if a.backend != nil && itemKey != "" { if item, ok, err := a.backend.GetLibraryItem(itemKey); err == nil && ok { @@ -232,6 +282,7 @@ func (a *App) openPostImageViewer(itemKey, siteID string, urls, relPaths, liveUR if rel == "" { continue } + noWMPaths[i] = a.resolveCompanionNoWatermarkPath(itemKey, &item, rel, "") for _, m := range item.Media { if m.Path != rel || m.Motion == "" { continue @@ -255,7 +306,7 @@ func (a *App) openPostImageViewer(itemKey, siteID string, urls, relPaths, liveUR hasLive = true } } - a.OpenImageViewer(urls, resolved, index) + a.openImageViewerWithCompanions(urls, nil, resolved, noWMPaths, index) if !a.ImageViewer.Open { return } @@ -284,9 +335,12 @@ func (a *App) OpenImageViewer(urls []string, localPaths []string, index int) { a.OpenImageViewerWithFallbacks(urls, nil, localPaths, index) } -// OpenImageViewerWithFallbacks opens the in-app image viewer overlay with optional per-image fallback URLs -// (e.g. falling back from Weibo /oslarge/ to the original largest URL on 404, HTML, or corrupt image). +// OpenImageViewerWithFallbacks opens the in-app image viewer overlay with optional per-image fallback URLs. func (a *App) OpenImageViewerWithFallbacks(urls []string, fallbackURLs [][]string, localPaths []string, index int) { + a.openImageViewerWithCompanions(urls, fallbackURLs, localPaths, nil, index) +} + +func (a *App) openImageViewerWithCompanions(urls []string, fallbackURLs [][]string, localPaths []string, noWatermarkPaths []string, index int) { if len(urls) == 0 && len(localPaths) == 0 { return } @@ -328,7 +382,22 @@ func (a *App) OpenImageViewerWithFallbacks(urls []string, fallbackURLs [][]strin } total := maxInt(len(cleanURLs), len(localPaths)) index = min(index, total-1) - a.ImageViewer = ImageViewerState{Open: true, URLs: cleanURLs, FallbackURLs: cleanFallbacks, LocalPaths: localPaths, Index: index, Zoom: 1, Fit: true, InlinePageIndex: -1} + cleanNoWM := make([]string, total) + for i := 0; i < total && i < len(noWatermarkPaths); i++ { + cleanNoWM[i] = strings.TrimSpace(noWatermarkPaths[i]) + } + a.ImageViewer = ImageViewerState{ + Open: true, + URLs: cleanURLs, + FallbackURLs: cleanFallbacks, + LocalPaths: localPaths, + NoWatermarkPaths: cleanNoWM, + ShowNoWatermark: false, + Index: index, + Zoom: 1, + Fit: true, + InlinePageIndex: -1, + } backend := a.backend requestGuarded(a, fmt.Sprintf("image-%d", revision), func() bool { return a.ImageViewer.Open && a.imageViewerRevision == revision && backend.HasAnyLogin() @@ -336,6 +405,8 @@ func (a *App) OpenImageViewerWithFallbacks(urls []string, fallbackURLs [][]strin defer cancel() bitmaps := make([]*ui.Bitmap, total) errors := make([]string, total) + noWMBitmaps := make([]*ui.Bitmap, total) + noWMErrors := make([]string, total) for i := 0; i < total; i++ { if ctx.Err() != nil { break @@ -387,21 +458,32 @@ func (a *App) OpenImageViewerWithFallbacks(urls []string, fallbackURLs [][]strin errors[i] = lastErr } } + if i < len(cleanNoWM) && cleanNoWM[i] != "" && ctx.Err() == nil { + noWMBitmaps[i] = loadBitmapFromFile(cleanNoWM[i]) + if noWMBitmaps[i] == nil { + noWMErrors[i] = "无水印伴侣图无法读取或格式不支持" + } + } } return ImageViewerState{ - Open: true, - URLs: cleanURLs, - FallbackURLs: cleanFallbacks, - LocalPaths: localPaths, - Index: index, - Zoom: 1, - Fit: true, - Bitmaps: bitmaps, - Errors: errors, + Open: true, + URLs: cleanURLs, + FallbackURLs: cleanFallbacks, + LocalPaths: localPaths, + NoWatermarkPaths: cleanNoWM, + Index: index, + Zoom: 1, + Fit: true, + Bitmaps: bitmaps, + Errors: errors, + NoWatermarkBitmaps: noWMBitmaps, + NoWatermarkErrors: noWMErrors, }, nil }, func(state ImageViewerState) { a.ImageViewer.Bitmaps = state.Bitmaps a.ImageViewer.Errors = state.Errors + a.ImageViewer.NoWatermarkBitmaps = state.NoWatermarkBitmaps + a.ImageViewer.NoWatermarkErrors = state.NoWatermarkErrors a.imageViewerCancel = nil }, nil) } diff --git a/internal/ui/settings_view.go b/internal/ui/settings_view.go index 5920cff..92c0c7b 100644 --- a/internal/ui/settings_view.go +++ b/internal/ui/settings_view.go @@ -471,7 +471,7 @@ func (a *App) renderDownloadSettings(c *ui.Context) { if settingSwitchRow(c, "自动保存视频封面", "", "开关保存封面", &a.DraftSettings.Download.SaveCover) { a.saveSettings() } - if settingSwitchRow(c, "微博图片去平台水印", "优先尝试无损无水印原图,不支持的老图自动回退原地址;GIF 动图保持原样。", "开关微博图片去水印", &a.DraftSettings.WeiboRemoveWatermark) { + if settingSwitchRow(c, "微博同时保存无水印版", "主图保存官方原图,同时额外保存无水印最大版(oslarge),GIF 跳过。", "开关微博图片去水印", &a.DraftSettings.WeiboRemoveWatermark) { a.saveSettings() } }) diff --git a/internal/ui/weibo_post_view.go b/internal/ui/weibo_post_view.go index 69140ec..cb4249f 100644 --- a/internal/ui/weibo_post_view.go +++ b/internal/ui/weibo_post_view.go @@ -354,7 +354,7 @@ func weiboMediaToNotePagesScoped(items []service.WeiboMediaItemDTO, cached *libr recs = origRecs } if len(recs) > 0 { - scopedItem := library.ItemMetadata{NotePages: recs} + scopedItem := library.ItemMetadata{NotePages: recs, Media: cached.Media} pages := buildDouyinNoteRenderPages(nil, &scopedItem) for i := range pages { if isWeiboGIFURL(pages[i].ImageRel) { @@ -423,6 +423,9 @@ func weiboMediaToNotePagesScoped(items []service.WeiboMediaItemDTO, cached *libr if len(chosen) > 0 { pages := buildDouyinNoteRenderPages(nil, &library.ItemMetadata{Media: chosen}) for i := range pages { + if pages[i].NoWatermarkRel == "" { + pages[i].NoWatermarkRel = findCompanionNoWatermarkRel(cached, pages[i].ImageRel) + } if isWeiboGIFURL(pages[i].ImageRel) { pages[i].IsGIF = true } diff --git a/internal/ui/weibo_watermark_ui_test.go b/internal/ui/weibo_watermark_ui_test.go index 65c096e..6edc871 100644 --- a/internal/ui/weibo_watermark_ui_test.go +++ b/internal/ui/weibo_watermark_ui_test.go @@ -3,15 +3,20 @@ package ui import ( "bytes" "context" + "crypto/sha256" + "encoding/hex" "errors" "image" "image/color" "image/png" + "os" + "path/filepath" "strings" "sync" "testing" "time" + "github.com/chialecode/trace/internal/library" "github.com/chialecode/trace/internal/service" "github.com/egoist/mygo/ui" ) @@ -32,11 +37,16 @@ func (b *weiboWatermarkViewerBackend) FetchImage(_ context.Context, rawURL strin } func makeValidPNGBytes(t *testing.T, w, h int) []byte { + t.Helper() + return makeValidColoredPNGBytes(t, w, h, color.RGBA{R: 50, G: 140, B: 220, A: 255}) +} + +func makeValidColoredPNGBytes(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, color.RGBA{R: 50, G: 140, B: 220, A: 255}) + img.SetRGBA(x, y, c) } } var buf bytes.Buffer @@ -46,6 +56,60 @@ func makeValidPNGBytes(t *testing.T, w, h int) []byte { return buf.Bytes() } +func seedWeiboDualSavedItem(t *testing.T, app *App) library.ItemMetadata { + t.Helper() + b := app.backend.(*service.Backend) + cacheDir := b.GetSettings().CacheDir + itemDir := filepath.Join(cacheDir, "weibo", "1000000001", "posts", "5000000000009201") + if err := os.MkdirAll(filepath.Join(itemDir, "images"), 0o700); err != nil { + t.Fatal(err) + } + orig1 := makeValidColoredPNGBytes(t, 40, 30, color.RGBA{R: 200, G: 60, B: 60, A: 255}) + nowm1 := makeValidColoredPNGBytes(t, 20, 15, color.RGBA{R: 40, G: 180, B: 90, A: 255}) + orig2 := makeValidColoredPNGBytes(t, 36, 24, color.RGBA{R: 60, G: 90, B: 210, A: 255}) + if err := os.WriteFile(filepath.Join(itemDir, "images", "01.png"), orig1, 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(itemDir, "images", "01_nowm.png"), nowm1, 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(itemDir, "images", "02.png"), orig2, 0o600); err != nil { + t.Fatal(err) + } + s1 := sha256.Sum256(orig1) + sn1 := sha256.Sum256(nowm1) + s2 := sha256.Sum256(orig2) + + saved, err := b.LibraryStore().SaveItem(itemDir, library.ItemMetadata{ + Version: 1, + ID: "dynamic:5000000000009201", + Site: "weibo", + Kind: "dynamic", + Status: "complete", + Title: "微博双份保存看图测试", + Text: "微博双份保存看图测试", + DynamicType: "draw", + TypeLabel: "图文", + URL: "https://weibo.com/1000000001/O000002n1", + PubTs: 1764000500, + DirectCached: true, + Author: library.ItemAuthor{Site: "weibo", UID: "1000000001", Name: "合成博主"}, + Media: []library.MediaFile{ + {Role: "image", Path: "images/01.png", Bytes: int64(len(orig1)), SHA256: hex.EncodeToString(s1[:]), Width: 40, Height: 30}, + {Role: "image_nowm", Path: "images/01_nowm.png", Bytes: int64(len(nowm1)), SHA256: hex.EncodeToString(sn1[:]), Width: 20, Height: 15}, + {Role: "image", Path: "images/02.png", Bytes: int64(len(orig2)), SHA256: hex.EncodeToString(s2[:]), Width: 36, Height: 24}, + }, + NotePages: []library.NotePageRecord{ + {Index: 1, Kind: "image", MediaID: "pic01", Image: "images/01.png", NoWatermark: "images/01_nowm.png", Width: 40, Height: 30}, + {Index: 2, Kind: "image", MediaID: "pic02", Image: "images/02.png", Width: 36, Height: 24}, + }, + }) + if err != nil { + t.Fatalf("SaveItem: %v", err) + } + return saved +} + func TestWeiboWatermarkViewerFallbackOn404HTMLAndCorruptImage(t *testing.T) { validPNG := makeValidPNGBytes(t, 20, 20) @@ -146,8 +210,8 @@ func TestDownloadSettingsWeiboWatermarkTogglePersists(t *testing.T) { tt := ui.NewTester(app.View, 1280, 860) tt.Frame() - if !tt.HasText("微博图片去平台水印") { - t.Fatal("settings download page missing 微博图片去平台水印 text") + if !tt.HasText("微博同时保存无水印版") { + t.Fatal("settings download page missing 微博同时保存无水印版 text") } if _, ok := tt.Find("开关微博图片去水印"); !ok { t.Fatal("settings download page missing 开关微博图片去水印 switch") @@ -164,3 +228,131 @@ func TestDownloadSettingsWeiboWatermarkTogglePersists(t *testing.T) { t.Fatal("clicking switch did not persist WeiboRemoveWatermark=false") } } + +func TestLibraryGridDoesNotDuplicateWeiboNoWatermarkCompanion(t *testing.T) { + app, _, cleanup := newTestUIApp(t) + defer cleanup() + if _, err := app.backend.ImportCookie(context.Background(), "SESSDATA=fixture; DedeUserID=12345", ""); err != nil { + t.Fatal(err) + } + saved := seedWeiboDualSavedItem(t, app) + app.CompleteLogin() + app.Navigate(RouteLibrary) + app.LibraryItems = []library.ItemMetadata{saved} + app.cacheStateRev++ + + tiles := app.libraryTiles() + if len(tiles) != 2 { + t.Fatalf("libraryTiles count = %d, want 2 (only primary images 01.png & 02.png, never 01_nowm.png)", len(tiles)) + } + for _, tile := range tiles { + if tile.file.Role != "image" || strings.Contains(tile.file.Path, "_nowm") { + t.Fatalf("unexpected companion tile in library grid: %+v", tile.file) + } + } +} + +func TestWeiboImageViewerToggleOriginalAndNoWatermark(t *testing.T) { + app, _, cleanup := newTestUIApp(t) + defer cleanup() + if _, err := app.backend.ImportCookie(context.Background(), "SESSDATA=fixture; DedeUserID=12345", ""); err != nil { + t.Fatal(err) + } + saved := seedWeiboDualSavedItem(t, app) + app.CompleteLogin() + app.Navigate(RouteLibrary) + app.LibraryItems = []library.ItemMetadata{saved} + app.cacheStateRev++ + + posted := make(chan func(), 4) + app.dispatch = func(fn func()) { posted <- fn } + + tiles := app.libraryTiles() + if len(tiles) != 2 { + t.Fatalf("tiles len = %d, want 2", len(tiles)) + } + app.openLibraryTile(tiles[0]) + + select { + case apply := <-posted: + apply() + case <-time.After(3 * time.Second): + t.Fatal("viewer bitmaps did not finish decoding") + } + + if !app.ImageViewer.Open || app.ImageViewer.ShowNoWatermark { + t.Fatalf("expected viewer open on original by default: open=%v showNoWM=%v", app.ImageViewer.Open, app.ImageViewer.ShowNoWatermark) + } + if len(app.ImageViewer.NoWatermarkPaths) != 2 || app.ImageViewer.NoWatermarkPaths[0] == "" || app.ImageViewer.NoWatermarkPaths[1] != "" { + t.Fatalf("unexpected NoWatermarkPaths: %+v", app.ImageViewer.NoWatermarkPaths) + } + if len(app.ImageViewer.Bitmaps) != 2 || app.ImageViewer.Bitmaps[0] == nil || app.ImageViewer.Bitmaps[1] == nil { + t.Fatalf("primary bitmaps missing: %+v", app.ImageViewer.Bitmaps) + } + if len(app.ImageViewer.NoWatermarkBitmaps) != 2 || app.ImageViewer.NoWatermarkBitmaps[0] == nil || app.ImageViewer.NoWatermarkBitmaps[1] != nil { + t.Fatalf("companion bitmaps unexpected: %+v", app.ImageViewer.NoWatermarkBitmaps) + } + bw0, bh0 := app.ImageViewer.Bitmaps[0].Size() + nw0, nh0 := app.ImageViewer.NoWatermarkBitmaps[0].Size() + if bw0 != 40 || bh0 != 30 || nw0 != 20 || nh0 != 15 { + t.Fatalf("decoded sizes mismatch: orig=%dx%d nowm=%dx%d", bw0, bh0, nw0, nh0) + } + + tt := ui.NewTester(app.View, 1280, 860) + tt.Frame() + if _, ok := tt.Find("看图切换原图无水印"); !ok { + t.Fatal("expected 原图/无水印 toggle capsule on slide 1") + } + if !tt.HasText("原图") || !tt.HasText("无水印") { + t.Fatal("expected both 原图 and 无水印 labels in top floating bar") + } + + // Click "无水印" -> switches immediately to companion. + if err := tt.Click("看图显示无水印"); err != nil { + t.Fatalf("click 看图显示无水印: %v", err) + } + tt.Frame() + if !app.ImageViewer.ShowNoWatermark { + t.Fatal("expected ShowNoWatermark=true after clicking 看图显示无水印") + } + + // Advance to slide 2 (has no companion) -> toggle hides, shows slide 2 original cleanly with zero error. + if err := tt.Click("看图下一张"); err != nil { + t.Fatalf("click 看图下一张: %v", err) + } + tt.Frame() + if app.ImageViewer.Index != 1 { + t.Fatalf("Index = %d, want 1", app.ImageViewer.Index) + } + if _, ok := tt.Find("看图切换原图无水印"); ok { + t.Fatal("toggle capsule must not render on slide 2 without companion") + } + if app.ImageViewer.Errors[1] != "" { + t.Fatalf("unexpected error on slide 2: %q", app.ImageViewer.Errors[1]) + } + + // Return to slide 1 and toggle back to "原图". + if err := tt.Click("看图上一张"); err != nil { + t.Fatalf("click 看图上一张: %v", err) + } + tt.Frame() + if err := tt.Click("看图显示原图"); err != nil { + t.Fatalf("click 看图显示原图: %v", err) + } + tt.Frame() + if app.ImageViewer.ShowNoWatermark { + t.Fatal("expected ShowNoWatermark=false after clicking 看图显示原图") + } + + // Verify OpenItemImageViewer (stem fallback path) also associates 01_nowm.png cleanly. + app.OpenItemImageViewer(saved.ItemKey, nil, []string{"images/01.png", "images/02.png"}, 0) + select { + case apply := <-posted: + apply() + case <-time.After(3 * time.Second): + t.Fatal("OpenItemImageViewer bitmaps did not finish decoding") + } + if len(app.ImageViewer.NoWatermarkPaths) != 2 || app.ImageViewer.NoWatermarkPaths[0] == "" || app.ImageViewer.NoWatermarkPaths[1] != "" { + t.Fatalf("OpenItemImageViewer NoWatermarkPaths = %+v", app.ImageViewer.NoWatermarkPaths) + } +} diff --git a/tools/actcheck/act022.go b/tools/actcheck/act022.go index 88b9178..0b81eb9 100644 --- a/tools/actcheck/act022.go +++ b/tools/actcheck/act022.go @@ -842,8 +842,8 @@ func runWeiboAct(parentCtx context.Context, spec weiboActSpec, cfg act022Config) if u, uErr := url.Parse(imgs[0].URL); uErr == nil { v07["firstImageHostClass"] = hostClass(u.Hostname()) } - v07["defaultWatermarkRewriteApplied"] = len(imgs[0].FallbackURLs) > 0 && - strings.Contains(strings.ToLower(imgs[0].URL), "/oslarge/") + v07["defaultWatermarkRewriteApplied"] = !strings.Contains(strings.ToLower(imgs[0].URL), "/oslarge/") && + strings.Contains(strings.ToLower(imgs[0].WatermarkFreeURL), "/oslarge/") } v07["status"] = "verified" } else { @@ -1123,7 +1123,6 @@ func runWeiboAct(parentCtx context.Context, spec weiboActSpec, cfg act022Config) // Step 7: V-07 (watermark probe), V-11 (image CDN), V-12 (video Range + LivePhoto + mp4ff). // Budget: probeCDN <= 10 requests, <= 60 MiB, 0 API calls, strictly NO Cookie! // ------------------------------------------------------------------------- - oslargeUnavailableInStep7 := false runner.run("v07_v11_v12_media_cdn_probes", func(f map[string]any) error { var sampleImgURL, sampleGIFURL, sampleLivePhotoURL string var sampleVideoURL string @@ -1206,9 +1205,6 @@ func runWeiboAct(parentCtx context.Context, spec weiboActSpec, cfg act022Config) } wFact["available"] = false wFact["errKind"] = site.KindOf(wErr) - if variant == "oslarge" { - oslargeUnavailableInStep7 = true - } } else { if wFact == nil { wFact = map[string]any{} @@ -1219,9 +1215,6 @@ func runWeiboAct(parentCtx context.Context, spec weiboActSpec, cfg act022Config) if placeholderGIF { wFact["placeholderGIFDetected"] = true wFact["available"] = false - if variant == "oslarge" { - oslargeUnavailableInStep7 = true - } } else { wFact["available"] = true } @@ -1510,9 +1503,8 @@ func runWeiboAct(parentCtx context.Context, spec weiboActSpec, cfg act022Config) reqs := 1 // cover / metadata headroom for _, im := range imgs { reqs++ // image/still - if oslargeUnavailableInStep7 && im.Kind != weibo.MediaKindGIF && - len(im.FallbackURLs) > 0 && strings.Contains(strings.ToLower(im.URL), "/oslarge/") { - reqs++ // account for /oslarge/ -> FallbackURLs[0] retry + if im.Kind != weibo.MediaKindGIF && strings.TrimSpace(im.WatermarkFreeURL) != "" { + reqs++ // account for dual-save /oslarge/ companion request } if im.Kind == weibo.MediaKindLivePhoto && im.MotionURL != "" { reqs += 2 // possible /media/play redirect + motion clip diff --git a/tools/actcheck/act022_test.go b/tools/actcheck/act022_test.go index 280b8d5..c437d38 100644 --- a/tools/actcheck/act022_test.go +++ b/tools/actcheck/act022_test.go @@ -1220,7 +1220,9 @@ func TestAct023LimitsAndIndependentLedger(t *testing.T) { } func TestAct023DefaultWatermarkRewriteAndFallback(t *testing.T) { - pngData := buildSyntheticPNGBytes(t, 32, 24) + // /oslarge/ returns a distinct smaller PNG (modeling real-world 690px-wide watermark-free + // companion vs official /large/ original per ACT-023 V-07 & DEC-078). + oslargePNG := buildSyntheticPNGBytes(t, 20, 15) mblogOver9, _ := weibo.MidToMblogID(synthWeiboMidOver9) mblogMixed, _ := weibo.MidToMblogID(synthWeiboMidMixed) @@ -1228,15 +1230,15 @@ func TestAct023DefaultWatermarkRewriteAndFallback(t *testing.T) { name string oslargeAvailable bool }{ - {name: "oslarge_404_falls_back_cleanly", oslargeAvailable: false}, - {name: "oslarge_200_lossless_succeeds", oslargeAvailable: true}, + {name: "oslarge_404_primary_unaffected", oslargeAvailable: false}, + {name: "oslarge_200_dual_save_succeeds", oslargeAvailable: true}, } { t.Run(tc.name, func(t *testing.T) { env := setupAct022MockEnv(t, 0, false) var oslargeHits, largeHits atomic.Int64 - // Return real https://wx1.sinaimg.cn/large/... image URLs so PR #95's default - // weiboRemoveWatermark=true rewrites static images to /oslarge/ with /large/ fallback. + // Return real https://wx1.sinaimg.cn/large/... image URLs so default + // weiboRemoveWatermark=true keeps primary at /large/ and populates /oslarge/ companion. env.hook = func(w http.ResponseWriter, r *http.Request) bool { switch { case strings.HasPrefix(r.URL.Path, "/cdn/oslarge/"): @@ -1250,7 +1252,7 @@ func TestAct023DefaultWatermarkRewriteAndFallback(t *testing.T) { return true } w.Header().Set("Content-Type", "image/png") - _, _ = w.Write(pngData) + _, _ = w.Write(oslargePNG) return true case strings.HasPrefix(r.URL.Path, "/cdn/large/"): largeHits.Add(1) @@ -1398,11 +1400,22 @@ func TestAct023DefaultWatermarkRewriteAndFallback(t *testing.T) { if multi["taskStatus"] != "completed" || multi["missingCount"] != 0 { t.Fatalf("Step9 multiImagePost = %+v, want completed with 0 missing", multi) } + roles, _ := multi["mediaRoles"].(map[string]int) + if roles["image"] < 1 { + t.Fatalf("Step9 multiImagePost mediaRoles = %+v, want image >= 1", roles) + } + if tc.oslargeAvailable { + if roles["image_nowm"] < 1 { + t.Fatalf("Step9 dual-save expected image_nowm >= 1 when /oslarge/ available, got %+v", roles) + } + } else if roles["image_nowm"] != 0 { + t.Fatalf("Step9 expected image_nowm == 0 when /oslarge/ returns 404, got %+v", roles) + } if oslargeHits.Load() < 2 { t.Fatalf("expected /oslarge/ hits in both Step 7 and Step 9, got %d", oslargeHits.Load()) } - if !tc.oslargeAvailable && largeHits.Load() < 2 { - t.Fatalf("expected /large/ fallback hits when /oslarge/ returns 404, got %d", largeHits.Load()) + if largeHits.Load() < 2 { + t.Fatalf("expected official original /large/ hits in both Step 7 and Step 9, got %d", largeHits.Load()) } }) } diff --git a/tools/uishots/scenes.go b/tools/uishots/scenes.go index 31e8aa6..30b6701 100644 --- a/tools/uishots/scenes.go +++ b/tools/uishots/scenes.go @@ -572,7 +572,7 @@ func buildCoreScenes(env *fixtureEnv, app *ui.App) []sceneSpec { app.SettingsCategory = "download" app.Navigate(ui.RouteSettings) }, - RequiredTexts: []string{"微博图片去平台水印"}, + RequiredTexts: []string{"微博同时保存无水印版"}, RequiredLabels: []string{"开关微博图片去水印"}, }, { From 30fc09bd2fa0221949f1a85d32f1c99efe47e92f Mon Sep 17 00:00:00 2001 From: chialecode <315431287+chialecode@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:27:08 +0800 Subject: [PATCH 2/5] fix(download): match previous no-watermark companion by original image stem When resolving conflict deletions/reorders where a surviving page shifts to an earlier index, derive the fallback companion stem from reusableLP.Image instead of the new page index so a deleted page's NN_nowm file is never misbound to a different surviving image. Signed-off-by: chialecode <315431287+chialecode@users.noreply.github.com> --- internal/download/weibo_plan.go | 13 +- internal/download/weibo_watermark_test.go | 212 ++++++++++++++++++++++ 2 files changed, 224 insertions(+), 1 deletion(-) diff --git a/internal/download/weibo_plan.go b/internal/download/weibo_plan.go index d223bb6..4c09fa3 100644 --- a/internal/download/weibo_plan.go +++ b/internal/download/weibo_plan.go @@ -1768,8 +1768,19 @@ func (m *Manager) cacheWeiboWatermarkFreeCompanion( if strings.TrimSpace(reusableLP.NoWatermark) != "" && mediaIsValid(previous, reusableLP.NoWatermark) { return reusableLP.NoWatermark } + var prevNoWMStem string + if imgRel := strings.TrimSpace(filepath.ToSlash(reusableLP.Image)); imgRel != "" { + if stem := trimKnownImageExt(imgRel); stem != "" { + prevNoWMStem = stem + "_nowm" + } + } else if !isConflict { + prevNoWMStem = nowmStem + } + if prevNoWMStem == "" { + return "" + } for _, mf := range previous.Media { - if mf.Role == "image_nowm" && strings.HasPrefix(mf.Path, nowmStem+".") && mediaIsValid(previous, mf.Path) { + if mf.Role == "image_nowm" && strings.HasPrefix(filepath.ToSlash(mf.Path), prevNoWMStem+".") && mediaIsValid(previous, mf.Path) { return mf.Path } } diff --git a/internal/download/weibo_watermark_test.go b/internal/download/weibo_watermark_test.go index a7d9753..0c6cf8f 100644 --- a/internal/download/weibo_watermark_test.go +++ b/internal/download/weibo_watermark_test.go @@ -443,3 +443,215 @@ func TestWeiboDualSaveSkipsGIFAndBackfillsOldCachedItem(t *testing.T) { t.Fatalf("companion was not monotonically preserved: ok=%v err=%v pages=%+v", ok, err, meta3.NotePages) } } + +func TestWeiboConflictDeleteReorderDoesNotMisbindCompanion(t *testing.T) { + picAOrig := makeWatermarkTestJPEG(t, 40, 30, color.RGBA{R: 210, G: 40, B: 40, A: 255}) + picANoWM := makeWatermarkTestJPEG(t, 24, 18, color.RGBA{R: 250, G: 120, B: 40, A: 255}) + picBOrig := makeWatermarkTestJPEG(t, 44, 32, color.RGBA{R: 40, G: 90, B: 210, A: 255}) + picCOrig := makeWatermarkTestJPEG(t, 38, 28, color.RGBA{R: 40, G: 180, B: 90, A: 255}) + picCNoWM := makeWatermarkTestJPEG(t, 22, 16, color.RGBA{R: 90, G: 220, B: 140, A: 255}) + + rt := roundTripFunc(func(req *http.Request) (*http.Response, error) { + switch req.URL.Path { + case "/large/picA.jpg": + return &http.Response{StatusCode: http.StatusOK, ContentLength: int64(len(picAOrig)), Header: http.Header{"Content-Type": []string{"image/jpeg"}}, Body: io.NopCloser(bytes.NewReader(picAOrig))}, nil + case "/oslarge/picA.jpg": + return &http.Response{StatusCode: http.StatusOK, ContentLength: int64(len(picANoWM)), Header: http.Header{"Content-Type": []string{"image/jpeg"}}, Body: io.NopCloser(bytes.NewReader(picANoWM))}, nil + case "/large/picB.jpg": + return &http.Response{StatusCode: http.StatusOK, ContentLength: int64(len(picBOrig)), Header: http.Header{"Content-Type": []string{"image/jpeg"}}, Body: io.NopCloser(bytes.NewReader(picBOrig))}, nil + case "/large/picC.jpg": + return &http.Response{StatusCode: http.StatusOK, ContentLength: int64(len(picCOrig)), Header: http.Header{"Content-Type": []string{"image/jpeg"}}, Body: io.NopCloser(bytes.NewReader(picCOrig))}, nil + case "/oslarge/picC.jpg": + return &http.Response{StatusCode: http.StatusOK, ContentLength: int64(len(picCNoWM)), Header: http.Header{"Content-Type": []string{"image/jpeg"}}, Body: io.NopCloser(bytes.NewReader(picCNoWM))}, nil + default: + return &http.Response{StatusCode: http.StatusNotFound, Header: http.Header{"Content-Type": []string{"text/plain"}}, Body: io.NopCloser(strings.NewReader("missing"))}, nil + } + }) + + t.Run("keep_both_delete_first_image_does_not_steal_picA_companion_for_picB", func(t *testing.T) { + mgr, libStore, _, _, _ := setupDouyinDownloadTestEnv(t, http.NotFoundHandler(), 2) + mgr.SetMediaTransportWrap(func(_ http.RoundTripper) http.RoundTripper { return rt }) + mgr.RegisterSitePlanner(newFakeWeiboSitePlanner()) + + // V1: [picA (has 01_nowm), picB (/oslarge/picB -> 404, no 02_nowm)]. + planV1 := WorkDownloadPlanFromSite(site.DownloadPlan{ + Site: site.Weibo, + ItemKey: "weibo:dynamic:5000000000009003", + TargetID: "5000000000009003", + Kind: "image_note", + CanonicalURL: "https://weibo.com/1000000001/O000002lJ", + AuthorUID: "1000000001", + AuthorName: "合成博主", + Title: "冲突删图重排回归", + Desc: "冲突删图重排回归", + Images: []site.MediaImageAsset{ + {Index: 1, MediaRole: "image", Width: 40, Height: 30, ImageURLs: []string{"https://wx1.sinaimg.cn/large/picA.jpg"}, WatermarkFreeURL: "https://wx1.sinaimg.cn/oslarge/picA.jpg"}, + {Index: 2, MediaRole: "image", Width: 44, Height: 32, ImageURLs: []string{"https://wx1.sinaimg.cn/large/picB.jpg"}, WatermarkFreeURL: "https://wx1.sinaimg.cn/oslarge/picB.jpg"}, + }, + Media: site.WeiboMediaTransport("Mozilla/5.0 Test", false), + }) + planV1.Pages[0].MediaID = "picA" + planV1.Pages[1].MediaID = "picB" + + task1, err := mgr.EnqueueWeiboWork(context.Background(), WeiboWorkEnqueueRequest{TargetID: planV1.TargetID, Kind: "dynamic", Plan: &planV1}) + if err != nil { + t.Fatalf("EnqueueWeiboWork V1: %v", err) + } + if ft := waitForTaskTerminal(t, mgr, task1.TaskID, 10*time.Second); ft.Status != "completed" { + t.Fatalf("V1 task = %+v", ft) + } + v1Meta, ok, err := libStore.GetItem(planV1.ItemKey) + if err != nil || !ok || len(v1Meta.NotePages) != 2 || v1Meta.NotePages[0].NoWatermark != "images/01_nowm.jpg" || v1Meta.NotePages[1].NoWatermark != "" { + t.Fatalf("unexpected V1 state: ok=%v err=%v pages=%+v", ok, err, v1Meta.NotePages) + } + + // V2 (keep_both): picA deleted, picB shifts to index 1 while /oslarge/picB still 404s. + planV2 := WorkDownloadPlanFromSite(site.DownloadPlan{ + Site: site.Weibo, + ItemKey: planV1.ItemKey, + TargetID: planV1.TargetID, + Kind: "image_note", + CanonicalURL: planV1.CanonicalURL, + AuthorUID: planV1.AuthorUID, + AuthorName: planV1.AuthorName, + Title: planV1.Title, + Desc: planV1.Desc, + Images: []site.MediaImageAsset{ + {Index: 1, MediaRole: "image", Width: 44, Height: 32, ImageURLs: []string{"https://wx1.sinaimg.cn/large/picB.jpg"}, WatermarkFreeURL: "https://wx1.sinaimg.cn/oslarge/picB.jpg"}, + }, + Media: site.WeiboMediaTransport("Mozilla/5.0 Test", false), + }) + planV2.Pages[0].MediaID = "picB" + planV2.ConflictResolution = ConflictResolveKeepBoth + + task2, err := mgr.EnqueueWeiboWork(WithConflictResolution(context.Background(), ConflictResolveKeepBoth), WeiboWorkEnqueueRequest{ + TargetID: planV2.TargetID, + Kind: "dynamic", + Plan: &planV2, + }) + if err != nil { + t.Fatalf("EnqueueWeiboWork V2: %v", err) + } + if ft := waitForTaskTerminal(t, mgr, task2.TaskID, 10*time.Second); ft.Status != "completed" { + t.Fatalf("V2 task = %+v", ft) + } + + v2Meta, ok, err := libStore.GetItem(planV2.ItemKey) + if err != nil || !ok || len(v2Meta.NotePages) != 1 { + t.Fatalf("unexpected V2 meta: ok=%v err=%v meta=%+v", ok, err, v2Meta) + } + if v2Meta.NotePages[0].NoWatermark != "" { + t.Fatalf("picB must NOT inherit picA's 01_nowm.jpg, got NoWatermark=%q", v2Meta.NotePages[0].NoWatermark) + } + for _, mf := range v2Meta.Media { + if mf.Role == "image_nowm" { + t.Fatalf("V2 unexpectedly kept image_nowm %+v from deleted picA", mf) + } + } + if _, statErr := os.Stat(filepath.Join(v2Meta.ItemDir, "images", "01_nowm.jpg")); !os.IsNotExist(statErr) { + t.Fatalf("V2 directory unexpectedly contains images/01_nowm.jpg: statErr=%v", statErr) + } + gotPrimary, err := os.ReadFile(filepath.Join(v2Meta.ItemDir, filepath.FromSlash(v2Meta.NotePages[0].Image))) + if err != nil || !bytes.Equal(gotPrimary, picBOrig) { + t.Fatalf("V2 primary mismatch: err=%v len=%d want=%d", err, len(gotPrimary), len(picBOrig)) + } + }) + + t.Run("use_remote_shift_recovers_own_previous_companion_by_original_image_stem", func(t *testing.T) { + mgr, libStore, _, _, _ := setupDouyinDownloadTestEnv(t, http.NotFoundHandler(), 2) + oslargeCDown := false + var mu sync.Mutex + rt2 := roundTripFunc(func(req *http.Request) (*http.Response, error) { + mu.Lock() + down := oslargeCDown + mu.Unlock() + if down && req.URL.Path == "/oslarge/picC.jpg" { + return &http.Response{StatusCode: http.StatusNotFound, Header: http.Header{"Content-Type": []string{"text/plain"}}, Body: io.NopCloser(strings.NewReader("gone"))}, nil + } + return rt(req) + }) + mgr.SetMediaTransportWrap(func(_ http.RoundTripper) http.RoundTripper { return rt2 }) + mgr.RegisterSitePlanner(newFakeWeiboSitePlanner()) + + // V1: [picA (has 01_nowm), picC (has 02_nowm)]. + planV1 := WorkDownloadPlanFromSite(site.DownloadPlan{ + Site: site.Weibo, + ItemKey: "weibo:dynamic:5000000000009004", + TargetID: "5000000000009004", + Kind: "image_note", + CanonicalURL: "https://weibo.com/1000000001/O000002lK", + AuthorUID: "1000000001", + AuthorName: "合成博主", + Title: "冲突重排精准复用自身伴侣图", + Desc: "冲突重排精准复用自身伴侣图", + Images: []site.MediaImageAsset{ + {Index: 1, MediaRole: "image", Width: 40, Height: 30, ImageURLs: []string{"https://wx1.sinaimg.cn/large/picA.jpg"}, WatermarkFreeURL: "https://wx1.sinaimg.cn/oslarge/picA.jpg"}, + {Index: 2, MediaRole: "image", Width: 38, Height: 28, ImageURLs: []string{"https://wx1.sinaimg.cn/large/picC.jpg"}, WatermarkFreeURL: "https://wx1.sinaimg.cn/oslarge/picC.jpg"}, + }, + Media: site.WeiboMediaTransport("Mozilla/5.0 Test", false), + }) + planV1.Pages[0].MediaID = "picA" + planV1.Pages[1].MediaID = "picC" + + task1, err := mgr.EnqueueWeiboWork(context.Background(), WeiboWorkEnqueueRequest{TargetID: planV1.TargetID, Kind: "dynamic", Plan: &planV1}) + if err != nil { + t.Fatalf("EnqueueWeiboWork V1: %v", err) + } + if ft := waitForTaskTerminal(t, mgr, task1.TaskID, 10*time.Second); ft.Status != "completed" { + t.Fatalf("V1 task = %+v", ft) + } + // Simulate an item where NotePages[1].NoWatermark was empty so stem lookup from reusableLP.Image is exercised. + v1Meta, ok, err := libStore.GetItem(planV1.ItemKey) + if err != nil || !ok || len(v1Meta.NotePages) != 2 { + t.Fatalf("load V1: ok=%v err=%v", ok, err) + } + v1Meta.NotePages[1].NoWatermark = "" + if _, err := libStore.SaveItem(v1Meta.ItemDir, v1Meta); err != nil { + t.Fatalf("SaveItem V1: %v", err) + } + + // Now /oslarge/picC expires (404), and V2 deletes picA shifting picC to index 1. + mu.Lock() + oslargeCDown = true + mu.Unlock() + + planV2 := WorkDownloadPlanFromSite(site.DownloadPlan{ + Site: site.Weibo, + ItemKey: planV1.ItemKey, + TargetID: planV1.TargetID, + Kind: "image_note", + CanonicalURL: planV1.CanonicalURL, + AuthorUID: planV1.AuthorUID, + AuthorName: planV1.AuthorName, + Title: planV1.Title, + Desc: planV1.Desc, + Images: []site.MediaImageAsset{ + {Index: 1, MediaRole: "image", Width: 38, Height: 28, ImageURLs: []string{"https://wx1.sinaimg.cn/large/picC.jpg"}, WatermarkFreeURL: "https://wx1.sinaimg.cn/oslarge/picC.jpg"}, + }, + Media: site.WeiboMediaTransport("Mozilla/5.0 Test", false), + }) + planV2.Pages[0].MediaID = "picC" + planV2.ConflictResolution = ConflictResolveUseRemote + + task2, err := mgr.EnqueueWeiboWork(WithConflictResolution(context.Background(), ConflictResolveUseRemote), WeiboWorkEnqueueRequest{ + TargetID: planV2.TargetID, + Kind: "dynamic", + Plan: &planV2, + }) + if err != nil { + t.Fatalf("EnqueueWeiboWork V2: %v", err) + } + if ft := waitForTaskTerminal(t, mgr, task2.TaskID, 10*time.Second); ft.Status != "completed" { + t.Fatalf("V2 task = %+v", ft) + } + + v2Meta, ok, err := libStore.GetItem(planV2.ItemKey) + if err != nil || !ok || len(v2Meta.NotePages) != 1 || v2Meta.NotePages[0].NoWatermark != "images/01_nowm.jpg" { + t.Fatalf("expected picC's own companion recovered at images/01_nowm.jpg, got ok=%v err=%v pages=%+v", ok, err, v2Meta.NotePages) + } + gotNoWM, err := os.ReadFile(filepath.Join(v2Meta.ItemDir, "images", "01_nowm.jpg")) + if err != nil || !bytes.Equal(gotNoWM, picCNoWM) { + t.Fatalf("V2 companion bytes mismatch: err=%v len=%d want picCNoWM len=%d (must not be picANoWM len=%d)", err, len(gotNoWM), len(picCNoWM), len(picANoWM)) + } + }) +} From 30adf9015aa69c4618755cd0bfc889170699ad4f Mon Sep 17 00:00:00 2001 From: chialecode <315431287+chialecode@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:51:18 +0800 Subject: [PATCH 3/5] feat(cache): add historical backfill queue, fast CDN pacing, and force redownload MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements Issue #104 and records DEC-079: - Add WeiboCacheStandardVersion = 3 (keeping CurrentCacheStandardVersion = 2) and zero-network BackfillSummary offline detection. - Link manual and 7-day fullCache sweeps (inspectWeiboCachedPost) to detect missing Weibo /oslarge/ companions and silently migrate pre-DEC-073 inline URLs. - Add persistent 3-tier historical Weibo backfill queue in cache-queue.json (v3, optional omitempty fields): offline links (0 network), pure CDN 2-5s fast pacing (0 API calls, 0 hourly quota, no 10-25m long rest), subscribed mymblog batch match, and statuses/show fallback under strict Weibo API quota/pacing. - Add manual-only ForceOverwrite (⋯ -> 强制重新下载) with confirmation modal across all 4 sites, skipping local reuse while preserving strict ErrRemoteDegradedRefused protection and atomic .trace-prev-* swap. - Add Settings › 存储 and Tasks › 缓存队列 UI entrypoints, update DEC-079 and docs, and add unit tests across library/download/service/ui. Signed-off-by: chialecode <315431287+chialecode@users.noreply.github.com> --- docs/decisions.md | 1 + docs/design/data-and-cache.md | 5 +- docs/design/subscriptions.md | 3 +- docs/requirements.md | 6 +- docs/ui.md | 7 +- internal/download/conflict_contract.go | 71 ++ internal/download/douyin_note.go | 29 +- internal/download/douyin_plan.go | 18 + internal/download/douyin_video.go | 35 +- internal/download/dynamic.go | 29 +- .../force_recache_and_backfill_test.go | 730 +++++++++++++ internal/download/image_guard_fallback.go | 3 + internal/download/manager.go | 35 +- internal/download/replace.go | 43 +- internal/download/video.go | 9 +- internal/download/weibo_backfill.go | 391 +++++++ internal/download/weibo_plan.go | 95 +- internal/download/x_plan.go | 66 +- internal/library/feed.go | 46 + internal/library/merge.go | 2 +- internal/library/schema.go | 165 +++ internal/library/weibo_backfill_test.go | 193 ++++ internal/service/backfill.go | 972 ++++++++++++++++++ .../backfill_and_force_recache_test.go | 764 ++++++++++++++ internal/service/batch_cache.go | 6 + internal/service/cache_conflicts.go | 55 +- internal/service/cache_queue_api.go | 13 +- internal/service/cache_queue_store.go | 83 +- internal/service/cache_queue_worker.go | 23 +- internal/service/interfaces.go | 14 + internal/service/library_service.go | 250 ++++- internal/ui/app.go | 32 +- internal/ui/backfill_actions.go | 96 ++ .../ui/backfill_and_force_recache_ui_test.go | 385 +++++++ internal/ui/douyin_work_view.go | 5 + internal/ui/navigation.go | 1 + internal/ui/overlays.go | 19 + internal/ui/settings_view.go | 32 + internal/ui/tasks_queue_view.go | 51 +- internal/ui/video_view.go | 27 + internal/ui/weibo_post_view.go | 10 + internal/ui/x_post_view.go | 5 + 42 files changed, 4678 insertions(+), 147 deletions(-) create mode 100644 internal/download/force_recache_and_backfill_test.go create mode 100644 internal/download/weibo_backfill.go create mode 100644 internal/library/weibo_backfill_test.go create mode 100644 internal/service/backfill.go create mode 100644 internal/service/backfill_and_force_recache_test.go create mode 100644 internal/ui/backfill_actions.go create mode 100644 internal/ui/backfill_and_force_recache_ui_test.go 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..8d0f51e --- /dev/null +++ b/internal/download/force_recache_and_backfill_test.go @@ -0,0 +1,730 @@ +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!") + } +} 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..0a06a6a 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) @@ -1373,7 +1377,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 +1447,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 +1479,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/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..4e222d3 --- /dev/null +++ b/internal/download/weibo_backfill.go @@ -0,0 +1,391 @@ +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, 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, err + } + defer func() { + _ = library.RemoveTempSubdirSafe(meta.ItemDir, stageDir) + }() + + stageTask := Task{ + Site: string(site.Weibo), + Kind: "dynamic", + Source: "queue", + ItemKey: meta.ItemKey, + ItemDir: stageDir, + } + + 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, dlErr := m.downloadWeiboOSLargeBackfillSlot(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 stamping v3. + return res, dlErr + } + res.SkippedSlots++ + continue + } + if savedMedia == nil { + res.SkippedSlots++ + continue + } + meta.Media = mergeMediaFiles(meta.Media, []library.MediaFile{*savedMedia}) + if slot.PageIdx >= 0 && slot.PageIdx < len(meta.NotePages) { + meta.NotePages[slot.PageIdx].NoWatermark = savedMedia.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 { + return res, sErr + } + res.Item = saved + } else { + res.Item = meta + } + return res, nil +} + +func (m *Manager) downloadWeiboOSLargeBackfillSlot( + ctx context.Context, + stageTask *Task, + stageDir, itemDir string, + spec rangeDownloadSpec, + slot library.WeiboStaticImageSlot, + primarySHA string, + candidates []string, +) (*library.MediaFile, 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 + } + if err := os.MkdirAll(filepath.Dir(finalFull), 0o700); err != nil { + return nil, err + } + if err := library.RejectDirectoryLinks(filepath.Dir(finalFull)); err != nil { + return nil, err + } + // Never overwrite an existing unregistered user file (INV-09). + if _, stErr := os.Lstat(finalFull); stErr == nil { + return nil, nil + } else if !os.IsNotExist(stErr) { + return nil, stErr + } + if err := os.Rename(tempFull, finalFull); err != nil { + return nil, err + } + return &library.MediaFile{ + Role: "image_nowm", + Path: finalRel, + FromOrigin: slot.FromOrigin, + Bytes: n, + SHA256: sha, + Width: w, + Height: h, + }, 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..1353329 --- /dev/null +++ b/internal/service/backfill.go @@ -0,0 +1,972 @@ +package service + +import ( + "context" + "fmt" + "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/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 (m *cacheQueueManager) scheduleSlowAPIWaitLocked(entry *cacheQueueEntry, cached bool) cacheQueueRecord { + if entry.rec.RestThreshold <= 0 { + entry.rec.RestThreshold = m.pickRestThresholdLocked() + } + if cached { + entry.rec.SinceRestCount++ + } + var delay time.Duration + 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) + } + now := m.clock.Now().UTC() + entry.rec.Status = CacheQueueWaiting + entry.rec.BackfillPhase = backfillPhaseFallbackDetail + 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 kind == site.ErrKindStorage { + 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! + if len(entry.rt.backfillMatched) == 0 { + 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.scheduleFastCDNWaitLocked(entry, backfillPhaseFastCDN, "纯 CDN 快速补全中") + 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 + nowStr := m.nowRFC3339() + for _, item := range batch { + if ctx.Err() != nil { + break + } + fresh, ok, gErr := m.b.lib.GetItem(item.ItemKey) + if gErr != nil || !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) + 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 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 kind == site.ErrKindStorage { + 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++ + } + } + hasMoreWork := len(buckets.fastCDN) > 1 || len(buckets.subscribedUIDs) > 0 || len(buckets.fallbackDetail) > 0 + var rec cacheQueueRecord + if !hasMoreWork { + rec = m.completeBackfillLocked(entry) + } else { + rec = m.scheduleFastCDNWaitLocked(entry, backfillPhaseFastCDN, "纯 CDN 快速补全中") + } + 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. + entry.rec.BackfillSubIndex++ + entry.rec.BackfillSubCursor = "" + entry.rec.UpdatedAt = m.nowRFC3339() + m.saveLoggedLocked("backfill_sub_skip") + rec := entry.rec + 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) + } + rec := m.scheduleFastCDNWaitLocked(entry, backfillPhaseSubscribedTimeline, "正在按已订阅博主列表匹配历史条目") + 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 kind == site.ErrKindStorage { + 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, 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..dc0f63d --- /dev/null +++ b/internal/service/backfill_and_force_recache_test.go @@ -0,0 +1,764 @@ +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") + } +} diff --git a/internal/service/batch_cache.go b/internal/service/batch_cache.go index 2b5c916..ace45c3 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 "帖子" diff --git a/internal/service/cache_conflicts.go b/internal/service/cache_conflicts.go index d39d873..c9f1c7f 100644 --- a/internal/service/cache_conflicts.go +++ b/internal/service/cache_conflicts.go @@ -1203,9 +1203,26 @@ 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) + if b.conflicts != nil && b.conflicts.hasPendingTextConflictForItem(meta.ItemKey) { + if updated, reconciled := b.reconcileLiveLegacyTextConflict(meta.ItemKey, remoteLinks); reconciled { + meta = updated + } + } else if strings.TrimSpace(meta.ItemDir) != "" && b.lib != nil { + if cleanedMeta, hadLegacy := cleanLegacyInlineLinksInItem(meta, remoteLinks); hadLegacy { + if b.weiboRemoveWatermarkEnabled() && !library.WeiboNeedsNoWMBackfill(cleanedMeta, true) && + cleanedMeta.CacheStandardVersion < library.WeiboCacheStandardVersion { + cleanedMeta.CacheStandardVersion = library.WeiboCacheStandardVersion + } + if savedMeta, sErr := b.lib.SaveItemMetadataOnly(meta.ItemDir, cleanedMeta); sErr == nil { + meta = savedMeta + if b.events != nil { + b.events.PublishSite(EventLibraryChanged, string(site.Weibo), meta.ItemKey) + } + } + } + } } } @@ -1249,10 +1266,42 @@ func (b *Backend) inspectWeiboCachedPost(post weibo.Post, meta library.ItemMetad return cachedInspectDecision{action: inspectEnqueue} } } + if b.weiboRemoveWatermarkEnabled() && library.WeiboNeedsNoWMBackfill(meta, true) && weiboImagesHaveWatermarkFreeCandidate(images, meta) { + return cachedInspectDecision{action: inspectEnqueue} + } return 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 { if len(missing) == 0 { return false 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..3cafc39 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", "未登录或登录已失效,重新登录后自动继续") 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..43dddb5 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,218 @@ 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.Video == nil || vr.Video.Selected == nil || strings.TrimSpace(vr.Video.Selected.URL) == "")) { + return download.Task{}, fmt.Errorf("%w:源站微博视频已失效", ErrRemoteDegradedRefused) + } + return b.CacheWeiboVideo(forceCtx, oid) + } + 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..d0ac78d --- /dev/null +++ b/internal/ui/backfill_actions.go @@ -0,0 +1,96 @@ +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 formatBackfillSummaryDetail(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)) + } + if len(parts) == 0 { + return fmt.Sprintf("发现 %d 条历史微博可补全", sum.TotalItems) + } + return fmt.Sprintf("发现 %d 条历史微博可补全(%s)", sum.TotalItems, strings.Join(parts, ",")) +} 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..eac6a0a 100644 --- a/internal/ui/tasks_queue_view.go +++ b/internal/ui/tasks_queue_view.go @@ -109,6 +109,36 @@ 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() + ui.Text(c, formatBackfillSummaryDetail(a.BackfillSummary)). + 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 +181,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 +217,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 +242,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 +300,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)) } From b5674061af5910944203b0a31e2f429538e573b0 Mon Sep 17 00:00:00 2001 From: chialecode <315431287+chialecode@users.noreply.github.com> Date: Thu, 26 Nov 2026 05:40:49 +0800 Subject: [PATCH 4/5] fix(cache): address PR #108 P1 review findings for backfill pacing, staging, storage pause, and lock safety Fixes all 4 P1 findings and 3 non-blocking items from independent review: 1. Enforce slow API pacing (40-150s, non-CDN phase) before every Weibo JSON API step (mymblog miss pages, post-drain transitions, and non-backoff timeline errors). 2. Stage all Weibo /oslarge/ companions inside .trace-stage-* until every slot finishes, then atomically move and SaveItem with rollback so mid-item 429/cancel never leaves orphan files or causes INV-09 permanent skip on retry. 3. Classify *os.PathError, *os.LinkError, site.ErrKindStorage, and bilibili storage errors consistently and wrap storage failures as site.ErrKindStorage so backfill pauses with PauseReason=storage without skipping pending items. 4. Defer legacy inline-URL metadata writes and synchronous EventLibraryChanged publication out of cacheQueueManager.mu into post-unlock callbacks to eliminate self-deadlock risk. 5. Also reuse GetVideo response in ForceRecacheItem (rejecting unavailable HostPost), deduplicate Tasks queue backfill banner copy, and record missing danmaku on ForceOverwrite. Signed-off-by: chialecode <315431287+chialecode@users.noreply.github.com> --- .../force_recache_and_backfill_test.go | 125 ++++++ internal/download/replace.go | 6 + internal/download/task_store.go | 9 +- internal/download/weibo_backfill.go | 127 ++++-- internal/service/backfill.go | 98 ++++- .../backfill_and_force_recache_test.go | 363 ++++++++++++++++++ internal/service/batch_cache.go | 2 +- internal/service/cache_conflicts.go | 84 ++-- internal/service/cache_queue_worker.go | 11 + internal/service/library_service.go | 28 +- internal/ui/backfill_actions.go | 11 +- internal/ui/tasks_queue_view.go | 6 +- 12 files changed, 786 insertions(+), 84 deletions(-) diff --git a/internal/download/force_recache_and_backfill_test.go b/internal/download/force_recache_and_backfill_test.go index 8d0f51e..de68ec0 100644 --- a/internal/download/force_recache_and_backfill_test.go +++ b/internal/download/force_recache_and_backfill_test.go @@ -728,3 +728,128 @@ func TestForceOverwriteBilibiliVideoAndDegradedRefusal(t *testing.T) { 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/replace.go b/internal/download/replace.go index 0a06a6a..d6b75c7 100644 --- a/internal/download/replace.go +++ b/internal/download/replace.go @@ -1064,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" 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/weibo_backfill.go b/internal/download/weibo_backfill.go index 4e222d3..65ac496 100644 --- a/internal/download/weibo_backfill.go +++ b/internal/download/weibo_backfill.go @@ -143,7 +143,7 @@ func (m *Manager) BackfillWeiboNoWMCompanions( if needSave { saved, sErr := m.lib.SaveItemMetadataOnly(meta.ItemDir, meta) if sErr != nil { - return res, sErr + return res, wrapWeiboBackfillStorageErr(sErr) } res.Item = saved return res, nil @@ -157,7 +157,7 @@ func (m *Manager) BackfillWeiboNoWMCompanions( stageDir := filepath.Join(meta.ItemDir, library.SwapStageDirPrefix+newSwapToken()) if err := os.MkdirAll(stageDir, 0o700); err != nil { - return res, err + return res, wrapWeiboBackfillStorageErr(err) } defer func() { _ = library.RemoveTempSubdirSafe(meta.ItemDir, stageDir) @@ -171,6 +171,14 @@ func (m *Manager) BackfillWeiboNoWMCompanions( 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 { @@ -199,14 +207,15 @@ func (m *Manager) BackfillWeiboNoWMCompanions( } } - savedMedia, dlErr := m.downloadWeiboOSLargeBackfillSlot(ctx, &stageTask, stageDir, meta.ItemDir, spec, slot, primarySHA, cands) + 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 stamping v3. - return res, 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 @@ -215,9 +224,47 @@ func (m *Manager) BackfillWeiboNoWMCompanions( res.SkippedSlots++ continue } - meta.Media = mergeMediaFiles(meta.Media, []library.MediaFile{*savedMedia}) - if slot.PageIdx >= 0 && slot.PageIdx < len(meta.NotePages) { - meta.NotePages[slot.PageIdx].NoWatermark = savedMedia.Path + 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++ } @@ -230,7 +277,8 @@ func (m *Manager) BackfillWeiboNoWMCompanions( if res.AddedCompanions > 0 || res.LinksCleaned || res.StampedStandard || assetIDsUpdated { saved, sErr := m.lib.SaveItem(meta.ItemDir, meta) if sErr != nil { - return res, sErr + rollbackMoved() + return res, wrapWeiboBackfillStorageErr(sErr) } res.Item = saved } else { @@ -239,7 +287,22 @@ func (m *Manager) BackfillWeiboNoWMCompanions( return res, nil } -func (m *Manager) downloadWeiboOSLargeBackfillSlot( +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, @@ -247,14 +310,14 @@ func (m *Manager) downloadWeiboOSLargeBackfillSlot( slot library.WeiboStaticImageSlot, primarySHA string, candidates []string, -) (*library.MediaFile, error) { +) (*library.MediaFile, string, string, error) { tempRel := slot.NoWMStem + imgSuffix tempFull, err := library.ResolveItemPath(stageDir, tempRel) if err != nil { - return nil, err + return nil, "", "", err } if err := os.MkdirAll(filepath.Dir(tempFull), 0o700); err != nil { - return nil, err + return nil, "", "", err } cleanupTemp := func() { _ = os.Remove(tempFull) @@ -265,16 +328,16 @@ func (m *Manager) downloadWeiboOSLargeBackfillSlot( for _, cand := range candidates { if err := ctx.Err(); err != nil { - return nil, err + 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() + return nil, "", "", ctx.Err() } if isSiteStopError(dlErr) || isStorageError(dlErr) { - return nil, dlErr + return nil, "", "", dlErr } continue } @@ -291,28 +354,30 @@ func (m *Manager) downloadWeiboOSLargeBackfillSlot( } // Deduplicate when /oslarge/ is byte-identical to the primary original image. if primarySHA != "" && strings.EqualFold(sha, primarySHA) { - return nil, nil + return nil, "", "", nil } finalRel := slot.NoWMStem + ext finalFull, rErr := library.ResolveItemPath(itemDir, finalRel) if rErr != nil { - return nil, rErr + return nil, "", "", rErr } - if err := os.MkdirAll(filepath.Dir(finalFull), 0o700); err != nil { - return nil, err - } - if err := library.RejectDirectoryLinks(filepath.Dir(finalFull)); err != nil { - return nil, err - } - // Never overwrite an existing unregistered user file (INV-09). + // Pre-check INV-09 conflict without mutating itemDir yet. if _, stErr := os.Lstat(finalFull); stErr == nil { - return nil, nil + return nil, "", "", nil } else if !os.IsNotExist(stErr) { - return nil, 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, finalFull); err != nil { - return nil, err + if err := os.Rename(tempFull, stagedFull); err != nil { + return nil, "", "", err } return &library.MediaFile{ Role: "image_nowm", @@ -322,9 +387,9 @@ func (m *Manager) downloadWeiboOSLargeBackfillSlot( SHA256: sha, Width: w, Height: h, - }, nil + }, stagedFull, finalFull, nil } - return nil, nil + return nil, "", "", nil } func buildWeiboOSLargeBackfillURLs(picID, primaryPath, overrideURL string) []string { diff --git a/internal/service/backfill.go b/internal/service/backfill.go index 1353329..e73b219 100644 --- a/internal/service/backfill.go +++ b/internal/service/backfill.go @@ -2,7 +2,9 @@ package service import ( "context" + "errors" "fmt" + "os" "slices" "sort" "strings" @@ -11,6 +13,7 @@ import ( "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" ) @@ -338,7 +341,19 @@ func (m *cacheQueueManager) scheduleFastCDNWaitLocked(entry *cacheQueueEntry, ph return entry.rec } -func (m *cacheQueueManager) scheduleSlowAPIWaitLocked(entry *cacheQueueEntry, cached bool) cacheQueueRecord { +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() } @@ -346,7 +361,10 @@ func (m *cacheQueueManager) scheduleSlowAPIWaitLocked(entry *cacheQueueEntry, ca entry.rec.SinceRestCount++ } var delay time.Duration - reason := "等待下一条" + 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 @@ -355,9 +373,12 @@ func (m *cacheQueueManager) scheduleSlowAPIWaitLocked(entry *cacheQueueEntry, ca } 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 = backfillPhaseFallbackDetail + entry.rec.BackfillPhase = phase entry.rec.PauseReason = "" entry.rec.StopReason = reason entry.rec.ActiveItemKey = "" @@ -445,7 +466,7 @@ func (m *cacheQueueManager) advanceWeiboBackfillStep(ctx context.Context, entry m.notifyState(rec) return } - if kind == site.ErrKindStorage { + if isBackfillStorageError(bErr) { entry.rt.backfillMatched = append([]backfillMatchedItem{match}, entry.rt.backfillMatched...) entry.rec.Status = CacheQueuePaused entry.rec.PauseReason = "storage" @@ -469,8 +490,12 @@ func (m *cacheQueueManager) advanceWeiboBackfillStep(ctx context.Context, entry entry.rec.SkippedCount++ } } - // Once the buffered page matches drain completely, commit the pending mymblog cursor advance! - if len(entry.rt.backfillMatched) == 0 { + // 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 = "" @@ -479,8 +504,8 @@ func (m *cacheQueueManager) advanceWeiboBackfillStep(ctx context.Context, entry } entry.rt.backfillPendingCursor = "" entry.rt.backfillPendingUIDDone = false + rec = m.scheduleSlowAPIWaitLocked(entry, backfillPhaseSubscribedTimeline, "等待下一次微博列表检查", false) } - rec := m.scheduleFastCDNWaitLocked(entry, backfillPhaseFastCDN, "纯 CDN 快速补全中") m.mu.Unlock() if bErr == nil && m.b.events != nil { m.b.events.PublishSite(EventLibraryChanged, string(site.Weibo), match.itemKey) @@ -535,13 +560,22 @@ func (m *cacheQueueManager) advanceWeiboBackfillStep(ctx context.Context, entry 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 || !ok || strings.TrimSpace(fresh.ItemDir) == "" { + 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 } @@ -555,6 +589,10 @@ func (m *cacheQueueManager) advanceWeiboBackfillStep(ctx context.Context, entry } 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 } @@ -577,6 +615,22 @@ func (m *cacheQueueManager) advanceWeiboBackfillStep(ctx context.Context, entry 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) @@ -649,7 +703,7 @@ func (m *cacheQueueManager) advanceWeiboBackfillStep(ctx context.Context, entry m.notifyState(rec) return } - if kind == site.ErrKindStorage { + if isBackfillStorageError(bErr) { entry.rec.Status = CacheQueuePaused entry.rec.PauseReason = "storage" entry.rec.StopReason = "存储空间不足或写入失败,已暂停补全" @@ -672,12 +726,16 @@ func (m *cacheQueueManager) advanceWeiboBackfillStep(ctx context.Context, entry entry.rec.SkippedCount++ } } - hasMoreWork := len(buckets.fastCDN) > 1 || len(buckets.subscribedUIDs) > 0 || len(buckets.fallbackDetail) > 0 var rec cacheQueueRecord - if !hasMoreWork { - rec = m.completeBackfillLocked(entry) - } else { + 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 { @@ -783,12 +841,11 @@ func (m *cacheQueueManager) advanceWeiboBackfillStep(ctx context.Context, entry return } // Account unavailable/schema/network on timeline: skip remaining pages for this UID - // so unmatched items automatically fall back to Tier C2 statuses/show. + // 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 = "" - entry.rec.UpdatedAt = m.nowRFC3339() - m.saveLoggedLocked("backfill_sub_skip") - rec := entry.rec + rec := m.scheduleSlowAPIWaitLocked(entry, backfillPhaseSubscribedTimeline, "跳过异常博主,等待下一次微博列表检查", false) m.mu.Unlock() m.notifyState(rec) return @@ -836,7 +893,8 @@ func (m *cacheQueueManager) advanceWeiboBackfillStep(ctx context.Context, entry } else { entry.rec.BackfillSubCursor = sanitizeQueueCursor(nextCur) } - rec := m.scheduleFastCDNWaitLocked(entry, backfillPhaseSubscribedTimeline, "正在按已订阅博主列表匹配历史条目") + // 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 @@ -930,7 +988,7 @@ func (m *cacheQueueManager) advanceWeiboBackfillStep(ctx context.Context, entry m.notifyState(rec) return } - if kind == site.ErrKindStorage { + if isBackfillStorageError(opErr) { entry.rec.Status = CacheQueuePaused entry.rec.PauseReason = "storage" entry.rec.StopReason = "存储空间不足或写入失败,已暂停补全" @@ -962,7 +1020,7 @@ func (m *cacheQueueManager) advanceWeiboBackfillStep(ctx context.Context, entry if len(remaining) <= 1 { rec = m.completeBackfillLocked(entry) } else { - rec = m.scheduleSlowAPIWaitLocked(entry, didCache) + rec = m.scheduleSlowAPIWaitLocked(entry, backfillPhaseFallbackDetail, "等待下一条", didCache) } m.mu.Unlock() if didCache && m.b.events != nil { diff --git a/internal/service/backfill_and_force_recache_test.go b/internal/service/backfill_and_force_recache_test.go index dc0f63d..f703cf1 100644 --- a/internal/service/backfill_and_force_recache_test.go +++ b/internal/service/backfill_and_force_recache_test.go @@ -762,3 +762,366 @@ func TestServiceForceRecacheItemOverwriteAndGuards(t *testing.T) { 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) { + // Simulate mid-backfill storage/filesystem corruption after GetItem succeeded: + // replacing itemDir/images with a regular file forces os.Lstat / os.MkdirAll + // during companion commit to return a real *os.PathError on both Windows & Linux! + imgDir := filepath.Join(saved.ItemDir, "images") + _ = os.RemoveAll(imgDir) + _ = os.WriteFile(imgDir, []byte("block-images-dir"), 0o600) + 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) + } +} + +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 ace45c3..68c0094 100644 --- a/internal/service/batch_cache.go +++ b/internal/service/batch_cache.go @@ -597,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 c9f1c7f..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) @@ -1205,21 +1225,37 @@ func (b *Backend) inspectWeiboCachedPost(post weibo.Post, meta library.ItemMetad } if fullRemoteTextAvailable && !substantiveTextChanged(localBody, post.Text) { remoteLinks := MapSiteTextLinks(post.Links) - if b.conflicts != nil && b.conflicts.hasPendingTextConflictForItem(meta.ItemKey) { - if updated, reconciled := b.reconcileLiveLegacyTextConflict(meta.ItemKey, remoteLinks); reconciled { - meta = updated + 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 } - } else if strings.TrimSpace(meta.ItemDir) != "" && b.lib != nil { - 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 savedMeta, sErr := b.lib.SaveItemMetadataOnly(meta.ItemDir, cleanedMeta); sErr == nil { - meta = savedMeta - if b.events != nil { - b.events.PublishSite(EventLibraryChanged, string(site.Weibo), meta.ItemKey) - } + if _, sErr := b.lib.SaveItemMetadataOnly(fresh.ItemDir, cleaned); sErr == nil && b.events != nil { + b.events.PublishSite(EventLibraryChanged, string(site.Weibo), itemKeyCopy) } } } @@ -1229,13 +1265,13 @@ func (b *Backend) inspectWeiboCachedPost(post weibo.Post, meta library.ItemMetad // (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}) } } } @@ -1244,33 +1280,33 @@ 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 cachedInspectDecision{action: inspectEnqueue} + return withPostInspect(cachedInspectDecision{action: inspectEnqueue}) } - return cachedInspectDecision{action: inspectSkipNoOp} + return withPostInspect(cachedInspectDecision{action: inspectSkipNoOp}) } func weiboImagesHaveWatermarkFreeCandidate(images []weibo.ImageAsset, meta library.ItemMetadata) bool { diff --git a/internal/service/cache_queue_worker.go b/internal/service/cache_queue_worker.go index 3cafc39..a289372 100644 --- a/internal/service/cache_queue_worker.go +++ b/internal/service/cache_queue_worker.go @@ -934,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 } @@ -986,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/library_service.go b/internal/service/library_service.go index 43dddb5..dd73117 100644 --- a/internal/service/library_service.go +++ b/internal/service/library_service.go @@ -428,10 +428,34 @@ func (b *Backend) ForceRecacheItem(ctx context.Context, itemKey string) (downloa if err != nil { return download.Task{}, wrapDegradedIfRemoteInvalid(err) } - if vr == nil || (vr.HostPost == nil && (vr.Video == nil || vr.Video.Selected == nil || strings.TrimSpace(vr.Video.Selected.URL) == "")) { + 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) } - return b.CacheWeiboVideo(forceCtx, oid) + 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 { diff --git a/internal/ui/backfill_actions.go b/internal/ui/backfill_actions.go index d0ac78d..b9e04e6 100644 --- a/internal/ui/backfill_actions.go +++ b/internal/ui/backfill_actions.go @@ -78,7 +78,7 @@ func (a *App) confirmForceRecache() { }) } -func formatBackfillSummaryDetail(sum service.BackfillSummaryDTO) string { +func formatBackfillSummaryBreakdown(sum service.BackfillSummaryDTO) string { var parts []string if sum.WeiboMissingNoWM > 0 { parts = append(parts, fmt.Sprintf("缺无水印伴侣图 %d 条", sum.WeiboMissingNoWM)) @@ -89,8 +89,13 @@ func formatBackfillSummaryDetail(sum service.BackfillSummaryDTO) string { if sum.WeiboFastCDNCandidates > 0 { parts = append(parts, fmt.Sprintf("%d 条可快速直连补齐", sum.WeiboFastCDNCandidates)) } - if len(parts) == 0 { + 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, strings.Join(parts, ",")) + return fmt.Sprintf("发现 %d 条历史微博可补全(%s)", sum.TotalItems, detail) } diff --git a/internal/ui/tasks_queue_view.go b/internal/ui/tasks_queue_view.go index eac6a0a..cf83520 100644 --- a/internal/ui/tasks_queue_view.go +++ b/internal/ui/tasks_queue_view.go @@ -127,8 +127,10 @@ func (a *App) renderTasksQueueView(c *ui.Context) { 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() - ui.Text(c, formatBackfillSummaryDetail(a.BackfillSummary)). - FontSize(12).TextColor(ColorTextMuted).SingleLine() + if detail := formatBackfillSummaryBreakdown(a.BackfillSummary); detail != "" { + ui.Text(c, detail). + FontSize(12).TextColor(ColorTextMuted).SingleLine() + } }) btnText := "一键补全" if startingBackfill { From fa640706fde4fdb6dbc6ecf5ae4deed6b8f3609e Mon Sep 17 00:00:00 2001 From: chialecode <315431287+chialecode@users.noreply.github.com> Date: Thu, 26 Nov 2026 05:55:07 +0800 Subject: [PATCH 5/5] test(service): make backfill storage-error pause test cross-platform on Linux and Windows Signed-off-by: chialecode <315431287+chialecode@users.noreply.github.com> --- .../service/backfill_and_force_recache_test.go | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/internal/service/backfill_and_force_recache_test.go b/internal/service/backfill_and_force_recache_test.go index f703cf1..044277c 100644 --- a/internal/service/backfill_and_force_recache_test.go +++ b/internal/service/backfill_and_force_recache_test.go @@ -958,12 +958,13 @@ func TestBackfillStorageErrorPausesQueueAndPreservesPendingItem(t *testing.T) { var saved library.ItemMetadata b.dl.SetMediaTransportWrap(func(_ http.RoundTripper) http.RoundTripper { return serviceRoundTripFunc(func(req *http.Request) (*http.Response, error) { - // Simulate mid-backfill storage/filesystem corruption after GetItem succeeded: - // replacing itemDir/images with a regular file forces os.Lstat / os.MkdirAll - // during companion commit to return a real *os.PathError on both Windows & Linux! - imgDir := filepath.Join(saved.ItemDir, "images") - _ = os.RemoveAll(imgDir) - _ = os.WriteFile(imgDir, []byte("block-images-dir"), 0o600) + // 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)), @@ -1015,6 +1016,10 @@ func TestBackfillStorageErrorPausesQueueAndPreservesPendingItem(t *testing.T) { 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) {