diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 8817f58..d118f39 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -20,6 +20,11 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
- name: Run quality gates
run: go run ./tools/check
+
+ - name: Remote smoke (trace-server, fake rclone, no network)
+ run: go run ./tools/smoke -server
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 2dc074d..e4bb309 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -1,6 +1,6 @@
name: Release
-# Weekly release of TRACE (W8): every Monday 00:00 UTC (08:00 Beijing time)
+# Weekly release of TRACE: every Monday 00:00 UTC (08:00 Beijing time)
# or by hand. It builds only when main has changes merged since the last
# release, and publishes only once the user has turned publishing on
# (repository variable TRACE_RELEASE_PUBLISH=1, USER-ACTIONS ACT-009); a
@@ -113,14 +113,14 @@ jobs:
set -euo pipefail
cd release/dist/trace
sha256sum -c SHA256SUMS
- grep -qx "version=${VERSION}" VERSION.txt
- grep -qx "channel=stable" VERSION.txt
- mapfile -t files < <(awk '{print $2}' SHA256SUMS | grep -vx 'update-windows-amd64.json')
+ grep -Fqx "version=${VERSION}" VERSION.txt
+ grep -Fqx "channel=stable" VERSION.txt
+ mapfile -t files < <(awk '{print $2}' SHA256SUMS | grep -Fvx 'update-windows-amd64.json')
gh release create "v${VERSION}" --target "$TARGET" --title "TRACE ${VERSION}" \
--notes-file ../../artifacts/release/notes.md --draft "${files[@]}" SHA256SUMS
gh release upload "v${VERSION}" update-windows-amd64.json
assets="$(gh release view "v${VERSION}" --json assets --jq '.assets[].name')"
for f in "${files[@]}" SHA256SUMS update-windows-amd64.json; do
- grep -qx "$f" <<<"$assets" || { echo "the draft release lacks $f"; exit 1; }
+ grep -Fqx "$f" <<<"$assets" || { echo "the draft release lacks $f"; exit 1; }
done
gh release edit "v${VERSION}" --draft=false --latest
diff --git a/.gitignore b/.gitignore
index 5e5f353..de9841d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,6 +3,8 @@
/.mygo/
dist/
*.syso
+# 本机 go build 出来的工具程序
+/*.exe
# 运行与测试输出
/artifacts/
diff --git a/AGENTS.md b/AGENTS.md
index 83c17aa..156cb2e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -24,6 +24,7 @@
| 数据文件、缓存、下载、媒体协议、信息流 | [数据与缓存设计](docs/design/data-and-cache.md) |
| 订阅、检查更新、定时规则、自动缓存 | [订阅设计](docs/design/subscriptions.md) |
| 直播状态与录制 | [直播设计](docs/design/live.md) |
+| 远程版、上传、订阅与资源库的导入导出 | [远程设计](docs/design/remote.md) |
| UI、文案、交互 | [界面规范](docs/ui.md) |
| 站点协议 | [哔哩哔哩协议资料](docs/research/bilibili.md)、[抖音协议资料](docs/research/douyin.md) |
diff --git a/README.md b/README.md
index 9f84b97..94fca62 100644
--- a/README.md
+++ b/README.md
@@ -1,12 +1,12 @@
# TRACE
-TRACE 是一个 Windows 桌面应用,用社交网络式的界面浏览并缓存站点内容。当前范围只有哔哩哔哩:登录后粘贴视频链接或用户主页(UID),解析出视频详情、用户资料、动态和投稿;把动态连同原图和视频以最高画质缓存到本机,在主页信息流和媒体库里浏览。
+TRACE 是一个 Windows 桌面应用(并附带面向 Linux VPS 的无界面远程服务端 `trace-server`),用社交网络式的界面订阅、浏览、缓存并录制站点内容。当前支持哔哩哔哩与抖音:按站点登录,粘贴链接或通过“我的”浏览视频、动态、图文与用户主页;按最高画质与音质缓存到本机,支持订阅检查更新、共用缓存规则、慢速全部缓存队列、不限路数的直播录制与页内实时预览,在主页信息流和纯离线媒体库里浏览;远程版只缓存启动后的新内容与直播并经 `rclone` 上传网盘,支持资源库增量导入导出与订阅同步。
技术栈:全 Go 语言 + [MyGo](https://github.com/egoist/mygo) 原生界面(`github.com/egoist/mygo/ui`,Windows Direct3D 11 / DirectWrite 渲染,不依赖系统 WebView2)。选型依据见[技术选型研究](docs/research/2026-11-05-stack.md)。
## 状态
-当前阶段在[当前计划](docs/delivery/stage-plan.md)里,已实现的能力见[交付状态](docs/delivery/status.md)。工程尚未建立时,命令以[工程规则](docs/dev-rules/engineering.md#commands)记录的实际情况为准。
+当前阶段在[当前计划](docs/delivery/stage-plan.md)里,已实现的能力见[交付状态](docs/delivery/status.md),构建、门禁、打包与冒烟命令见[工程规则](docs/dev-rules/engineering.md#commands)。
## 入口
diff --git a/USER-ACTIONS.md b/USER-ACTIONS.md
index c81f641..b30c5ed 100644
--- a/USER-ACTIONS.md
+++ b/USER-ACTIONS.md
@@ -1,6 +1,6 @@
# 用户待办
-核对日期:2026-11-19。
+核对日期:2026-11-21。
这里列出需要你本人做的全部事情:待你决定的事(每项写明 Agent 当前在用的默认值)、待你授权的操作、人工检查,以及站点规则暂时做不到的情况。Agent 的开发不等这一页:每一项你都可以以后再处理,期间按默认值继续。只有列在[阻塞项](#blocking)里的事会让 Agent 暂停依赖它的那部分。
@@ -9,19 +9,22 @@
## 推荐你做的
-现在是 M4:把哔哩哔哩和抖音“我的账号”里的内容集中到图标栏的“我的”([DEC-047](docs/decisions.md#dec-047))——哔哩哔哩的关注、收藏夹、稍后再看、历史记录,抖音的关注、喜欢、收藏,点开就是解析里的详情页。**2026-11-14 B 已交付,A 同日审查收敛**([阶段报告 §6](docs/delivery/stage-report.md#a-review))。**你随后的 8 条实机反馈(2026-11-14)与 2026-11-15 补充的 4 条**:A 已直接修完 7 条(缓存规则缩起闪退、直播录像转换失败、抖音订阅头像重启后丢失、实况照片翻到即播、抖音“喜欢”空响应连带“收藏”失败、托盘原生两项菜单与抖音用户页卡顿,[阶段报告 §7](docs/delivery/stage-report.md#feedback-1));**B 已于 2026-11-15 完成交给 B 的 5 条功能调整**(解析页侧栏“最近解析”与居中大输入框、媒体库固定发布时间排序与纯离线详情、任务角标只数下载任务及任务页侧栏与直播录制实时预览、用户页“全部缓存”慢速不规律队列,[DEC-049](docs/decisions.md#dec-049)、[DEC-050](docs/decisions.md#dec-050),[阶段报告 §8](docs/delivery/stage-report.md#b-feedback-1));**A 同日集中审查收敛**,直接修了 2 处(缓存队列遇到失败的条目也照常等待、窄窗时解析页的“最近解析”放到输入框下方,[阶段报告 §9](docs/delivery/stage-report.md#a-review-feedback-1))。**你 2026-11-15 的第二轮 8 条反馈**([DEC-051](docs/decisions.md#dec-051)):A 已直接处理 4 条——删掉作者最后一条后不留空文件夹、订阅图标橙点的说明、订阅头像(两站点存本机、用户页订阅带头像)、更新开发版时先关再装再打开,并按你的要求看了本机日志(修了下载进度刷屏与闪退不留记录,[阶段报告 §10](docs/delivery/stage-report.md#feedback-2));**B 已于 2026-11-15 按 [Q-018](#q-018) 默认值完成另外 4 条**——设置“更新”页与检查/更新记录、不限同时录制数与“任务 › 录制异常”、订阅详情“内容 / 账号”标签、缓存规则“选择订阅…”批量应用([计划 §13](docs/delivery/stage-plan.md#feedback-2)),**A 同日集中审查收敛**,直接修了 1 处(开发版“设置 › 更新”仅在卸载项版本高于当前运行版本时提示重启生效,[阶段报告 §11、§12](docs/delivery/stage-report.md#a-review-feedback-2))。**你 2026-11-16 的第四轮反馈**:A 修了直播录制收尾与序号重置、空间页解析、只读默认规则与媒体库“刷新”([阶段报告 §14](docs/delivery/stage-report.md#feedback-4));**B 已按 [Q-019](#q-019) 的答复完成主页调整**(回到上次阅读位置、侧栏订阅未读圆点,[DEC-053](docs/decisions.md#dec-053),[阶段报告 §15](docs/delivery/stage-report.md#b-feedback-4)),待 A 审查。第五轮反馈(7 条与 3 条补充)A 已实现([DEC-056](docs/decisions.md#dec-056)、[DEC-057](docs/decisions.md#dec-057),[阶段报告 §16](docs/delivery/stage-report.md#feedback-5))。2026-11-17 A 审查收敛([阶段报告 §17](docs/delivery/stage-report.md#a-review-feedback-4-5)),新增“加入订阅”对话框([DEC-058](docs/decisions.md#dec-058))。本机 TRACE Dev 已更新至 `0.1.2-dev.202611161744`,已在托盘运行,可按 [H-001](#h-001) 第 28~33 步实机复查;默认参数见 [Q-016](#q-016)~[Q-018](#q-018)。推送与合并([ACT-021](#act-021))你 2026-11-17 已授权:A 推送并创建 PR,CI 通过后合并;“我的”的实现细节按 [Q-015](#q-015) 的默认值。[ACT-020](#act-020) 与之后的复查:哔哩哔哩四项、抖音关注与收藏真实通过,抖音“喜欢”只给浏览器(Q-016 第 1 条)。M3 已按你的授权(ACT-013)合并为 `main @ f080483`。
+现在是 M5:远程版([DEC-062](docs/decisions.md#dec-062))——单独打包的 `trace-server` 在 Linux VPS 上只缓存启动后的新内容与录制,内置 rclone 上传到网盘;本地 TRACE 在“设置 › 远程”看它的状态、同步订阅与 Cookie,并把网盘下载下来的文件夹增量导入媒体库。**2026-11-21 已完成 M5 全部实现、全仓库代码审查重构、依赖更新、无用代码清理与开发版下载/归属/任务卡片修复**([阶段报告 §8](docs/delivery/stage-report.md#full-audit-20261121));你的四个选择(内置 HTTPS + 令牌、只由本地续期、随订阅同步缓存规则、手动选文件夹导入)与“内置上传”都按推荐实现,其余默认值见 [Q-022](#q-022)。本机 TRACE Dev 已更新至 `0.1.3-dev.202611210624`(安装命令在作业对象内运行,若托盘未常驻请从开始菜单打开一次)。M4 与合并后的三轮反馈已合并为 `main @ 8327803`(PR #10);实机检查 [H-001](#h-001) 与 [H-003](#h-003) 随时可做。
| 顺序 | 事项 | 需要你做什么 | 暂时不做会怎样 |
| --- | --- | --- | --- |
+| 0 | [Q-022](#q-022):远程版的默认做法(端口、同步哪些设置、上传后删除、导入默认复制等) | 回复“按推荐”或要改的条目;已按推荐实现 | 保持推荐做法 |
+| 0 | [H-003](#h-003):远程版在你的 VPS 与 Google Drive 上的实机检查 | 按步骤部署一次(包在 `dist/trace-server/`);需要你的 VPS、rclone 配置与测试账号 | 远程版只有本机、CI 与假站点、假 rclone 的自动化证据 |
+| 0 | [H-001](#h-001) 第 37 步:2026-11-20 反馈与 2026-11-21 全仓与下载修复复查(抖音 `need_set_token` 播放跳转、配乐白名单、B 站 4101152/转发归属、共创详情页入口、任务卡片布局) | 本机 TRACE Dev 已更新至 `0.1.3-dev.202611210624`,按第 37 步复查并在任务页对原“部分完成”抖音图文点“重试” | 实机体验未确认(核心下载路径已做有界真实站点临时验证) |
| 0 | [H-001](#h-001) 第 36 步与 [Q-021](#q-021):2026-11-19 反馈的实机复查(缓存规则“全部缓存”、账号的作品数与已缓存数、合作视频算在为其缓存的账号下) | 本机 TRACE Dev 更新后按第 36 步看一遍;Q-021 回复“按推荐”或要改的条目 | 这些改动只有自动化测试;保持推荐默认值 |
| 0 | [H-001](#h-001) 第 35 步:2026-11-18 第二次反馈的实机复查(BV1tw411t7Pu 重试后完成、账号页手动刷新开播即开始录制、检查计划的“检查全部”与单个账号“检查”、抖音开播检查约每 3 分钟一次及软件里的规则说明) | 本机 TRACE Dev 更新后按第 35 步看一遍 | 这些修复只有自动化测试 |
| 0 | [H-001](#h-001) 第 34 步:2026-11-18 反馈的实机复查(任务页“检查计划”、新加入订阅的抖音账号的检查与录制、录制异常不再重复、换段不再丢片段、主页订阅信息流点头像不再闪退) | 本机 TRACE Dev 更新后按第 34 步看一遍 | 这些修复只有自动化测试 |
| 0 | [Q-018](#q-018):第二轮反馈的理解与默认值(更新页、录制不限数与异常、订阅详情、批量规则等 8 条) | 回复“按推荐”或要改的条目;A 与 B 已按推荐实现 | 保持推荐做法 |
-| 0 | [H-001](#h-001) 第 33 步:第五轮反馈的实机复查(任务页删除与缓存队列卡片、转发与合作视频的文件夹、媒体库“转发”、图标栏、主页头像、切换速度、全部账号、抖音私密账号) | 本机 TRACE Dev 已更新至 `0.1.2-dev.202611161316`([阶段报告 §16](docs/delivery/stage-report.md#feedback-5)),按第 33 步看一遍;BV1DDpE68E56 要搬到灰泽满Hazel 下需在媒体库删除后重新缓存 | 这些调整只有截图和自动化测试(抖音私密账号你已确认可以列出作品) |
-| 0 | [H-001](#h-001) 第 32 步:第四轮反馈的实机复查(主页回到上次阅读的位置、侧栏订阅列表与未读圆点、窄窗头像条,以及 A 修的直播录制收尾、空间页、只读的默认规则与媒体库“刷新”) | 本机 TRACE Dev 已更新至 `0.1.2-dev.202611160535`([阶段报告 §14、§15](docs/delivery/stage-report.md#b-feedback-4)),按第 32 步看一遍 | 这些调整只有截图和自动化测试,没有实机确认 |
-| 0 | [H-001](#h-001) 第 31 步:第二轮 8 条反馈的实机复查(空文件夹、订阅点的提示、订阅头像、更新时关闭重开,以及设置“更新”页、多路录制不限数与“录制异常”、订阅详情“内容 / 账号”、缓存规则批量“选择订阅…”) | 本机 TRACE Dev 已更新至 `0.1.2-dev.202611151241`([阶段报告 §11、§12](docs/delivery/stage-report.md#a-review-feedback-2);如未打开请从开始菜单或桌面点开一次),按第 31 步看一遍 | 这些修复与调整只有截图和自动化测试,没有实机确认 |
-| 0 | [H-001](#h-001) 第 30 步:第一轮反馈及补充 5 项调整的实机体验(解析页侧栏与居中大输入框、媒体库纯离线、全部缓存队列与任务页侧栏、直播录制实时预览) | 本机 TRACE Dev 已更新(含 A 审查的 2 处修复,[阶段报告 §8、§9](docs/delivery/stage-report.md#a-review-feedback-1)),按第 30 步看一遍 | 这些改动只有截图和自动化测试,没有实机确认 |
-| 0 | [H-001](#h-001) 第 29 步:复查 A 修的 7 条反馈 | 本机 TRACE Dev 已更新(版本见[阶段报告 §7、§8](docs/delivery/stage-report.md#feedback-1)),按第 29 步看一遍 | 这些修复只有自动化测试与你的录像文件的离线转换,没有实机确认 |
+| 0 | [H-001](#h-001) 第 33 步:第五轮反馈的实机复查(任务页删除与缓存队列卡片、转发与合作视频的文件夹、媒体库“转发”、图标栏、主页头像、切换速度、全部账号、抖音私密账号) | 本机 TRACE Dev 已更新至 `0.1.2-dev.202611161316`([阶段报告 §16](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-report.md#feedback-5)),按第 33 步看一遍;BV1DDpE68E56 要搬到灰泽满Hazel 下需在媒体库删除后重新缓存 | 这些调整只有截图和自动化测试(抖音私密账号你已确认可以列出作品) |
+| 0 | [H-001](#h-001) 第 32 步:第四轮反馈的实机复查(主页回到上次阅读的位置、侧栏订阅列表与未读圆点、窄窗头像条,以及 A 修的直播录制收尾、空间页、只读的默认规则与媒体库“刷新”) | 本机 TRACE Dev 已更新至 `0.1.2-dev.202611160535`([阶段报告 §14、§15](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-report.md#b-feedback-4)),按第 32 步看一遍 | 这些调整只有截图和自动化测试,没有实机确认 |
+| 0 | [H-001](#h-001) 第 31 步:第二轮 8 条反馈的实机复查(空文件夹、订阅点的提示、订阅头像、更新时关闭重开,以及设置“更新”页、多路录制不限数与“录制异常”、订阅详情“内容 / 账号”、缓存规则批量“选择订阅…”) | 本机 TRACE Dev 已更新至 `0.1.2-dev.202611151241`([阶段报告 §11、§12](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-report.md#a-review-feedback-2);如未打开请从开始菜单或桌面点开一次),按第 31 步看一遍 | 这些修复与调整只有截图和自动化测试,没有实机确认 |
+| 0 | [H-001](#h-001) 第 30 步:第一轮反馈及补充 5 项调整的实机体验(解析页侧栏与居中大输入框、媒体库纯离线、全部缓存队列与任务页侧栏、直播录制实时预览) | 本机 TRACE Dev 已更新(含 A 审查的 2 处修复,[阶段报告 §8、§9](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-report.md#a-review-feedback-1)),按第 30 步看一遍 | 这些改动只有截图和自动化测试,没有实机确认 |
+| 0 | [H-001](#h-001) 第 29 步:复查 A 修的 7 条反馈 | 本机 TRACE Dev 已更新(版本见[阶段报告 §7、§8](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-report.md#feedback-1)),按第 29 步看一遍 | 这些修复只有自动化测试与你的录像文件的离线转换,没有实机确认 |
| 0 | [Q-017](#q-017):缓存队列的节奏(多久缓存一条、多久长歇一次) | 回复“按推荐”或给出你想要的速度;B 已按推荐实现 | 保持推荐节奏 |
| 0 | [Q-016](#q-016):第一轮反馈的理解与默认值(抖音“喜欢”、媒体库排序、任务角标、实时弹幕) | 回复“按推荐”或要改的条目;B 已按推荐实现 | 保持推荐默认值 |
| 0 | [H-001](#h-001) 第 28 步:实机看“我的” | 本机 TRACE Dev 已更新(版本见[阶段报告](docs/delivery/stage-report.md)),按第 28 步看一遍 | “我的”只有截图、自动化与 ACT-020 的列表检查,没有实机确认 |
@@ -51,207 +54,6 @@
- **抖音“我的”的复查(2026-11-14,已完成)**:你反馈“喜欢和收藏返回空响应,确认是否风控”后,Agent 按 ACT-020 的抖音额度复查了 1 次(测试 Cookie,5 次 API,没有验证码与限流):“收藏”真实返回 18 条;“喜欢”对三种写法都回空内容,同一会话其他接口正常,所以是这个接口不回应非浏览器请求,不是账号风控。之前“收藏”也空,是“喜欢”被误判为风控、暂停了整个抖音,已修。收藏夹与观看历史仍没有真实证据(LOOP-014),不需要你做什么。
-
-### ACT-021:推送 M4、创建 PR 并合并(已授权,2026-11-17)
-
-| 项 | 内容 |
-| --- | --- |
-| 动作 | 把 `codex/m4-account`(基点 `main @ f080483`,一个 DCO 阶段提交,A 交付 SHA 见阶段报告 §6、§9、§12 与 A 的交付消息)推送到 `chialecode/trace`,创建标题为“M4:我的(登录账号的站点内容)”的 PR 到 `main`;等 `repository-quality` 与 DCO 检查结果,CI 失败时在同一提交上修复并说明;通过后 squash 合并并清理分支 |
-| 授权 | 你 2026-11-17 授权:A 审查没有问题后推送、创建 PR,CI 通过后合并([阶段报告 §17](docs/delivery/stage-report.md#a-review-feedback-4-5)) |
-| 不包括 | 打标签、发布(之后每周自动发布按 ACT-009 照常) |
-| 前提 | B 已完成第一轮反馈实现([阶段报告 §8](docs/delivery/stage-report.md#b-feedback-1),A 于 [§9](docs/delivery/stage-report.md#a-review-feedback-1) 审查收敛)与第二轮反馈实现([DEC-051](docs/decisions.md#dec-051),[计划 §13](docs/delivery/stage-plan.md#feedback-2),[阶段报告 §11](docs/delivery/stage-report.md#b-feedback-2)),A 已于 [§12](docs/delivery/stage-report.md#a-review-feedback-2) 完成第二轮集中审查并收敛;第四轮 B 的实现、第五轮与加入订阅对话框 A 于 [§17](docs/delivery/stage-report.md#a-review-feedback-4-5) 审查收敛 |
-| 合并前请知道 | 现有数据文件结构没有变(仍是版本 2):缓存队列新增独立文件 `cache-queue.json`(版本 1)、更新页新增独立文件 `update-history.json`(版本 1),直播清单 `item.json` 新增可选字段 `live.incidents`,条目清单新增可选字段 `via`,`ui-state.json` 新增可选字段 `homePositions` 与 `dismissedLiveSessions`,`library.db` 新增表达式索引 `idx_library_items_via`(都不改结构版本,旧版程序忽略该可选字段且不读新增的 v1 文件,仍可装回上一个开发版);抖音“收藏”真实通过,“喜欢”取不到(只给浏览器,Q-016 第 1 条),“收藏夹”只经合成验证(LOOP-014),“观看历史”不显示;H-001 第 28~33 步仍为 not-run(第 33 步 ⑧ 已确认),合并不代表产品验收 |
-
-
-### ACT-020:“我的”接口的真实站点只读检查(2026-11-14 已运行 1 次:哔哩哔哩通过,抖音部分 not-run)
-
-| 项 | 内容 |
-| --- | --- |
-| 依据 | [常设授权](#standing-site-requests)(2026-11-08);只读,不做任何写操作 |
-| 对象 | 只用测试 Cookie 对应的登录账号自己的列表:哔哩哔哩 `TRACE_TEST_BILIBILI_COOKIE_FILE`,抖音 `TRACE_TEST_DOUYIN_COOKIE_FILE`(`.env.local`)。不需要你另给对象;某个收藏夹、稍后再看或历史为空时照实记录为空,不另找账号 |
-| 动作与额度 | `go run ./tools/actcheck -act act020`,1 次(`.local/site-check/usage-act020.json` 账本在发出前拒绝超额)。哔哩哔哩 API ≤ 12 次:`nav` 1、`relation/tags` 1、`relation/followings` 1、`fav/folder/created/list-all` 1、`fav/resource/list` 2、`history/toview/web` 2(全部、未看完)、`history/cursor` 2,另留 2 次给 WBI 密钥刷新;抖音 API ≤ 10 次:`profile/self` 1、`user/following/list` 2、`aweme/favorite` 1、`aweme/listcollection`(POST)2、`collects/list` 1、`collects/video/list` 1、`history/read` 1,另留 1 次。不下载任何媒体与图片 |
-| 停止条件 | 哔哩哔哩 `-352`、`-412`、HTTP 412、`-101`;抖音 HTTP 403/429/444、网关拦截、验证页或验证字段、未登录空壳;任何一个出现就停下这个站点剩余的请求(另一个站点照常) |
-| 验证点 | [哔哩哔哩协议 §21](docs/research/bilibili.md#account-lists) 的 B-V1~B-V4,[抖音协议 §12](docs/research/douyin.md#account-lists) 的 D-V1~D-V5。D-V5 决定抖音“观看历史”是否显示([Q-015](#q-015) 第 3 条) |
-| 回执 | `artifacts/site-check/act020.json` 由程序写出:只有每个接口的次数、HTTP 状态、错误类别、条数、是否有下一页、游标是否前进与字段是否齐全;不写标题、昵称、ID、Cookie、签名地址 |
-| 现状 | 2026-11-14 运行 1 次(账本 `runs=1`,API 15/22,`secretScanClean=true`,临时数据已删)。哔哩哔哩:B-V0 关注(3 个分组、第 1 页 20 人)、B-V1 收藏夹(4 个、默认 1 个在前)、B-V2 收藏夹内容(2 页各 20 条、0 重复、1 条失效)、B-V3 稍后再看(WBI 通过,全部 92、未看完 91)、B-V4 历史(2 页游标推进、0 重复)全部通过。抖音:登录与 D-V1 关注(2 页各 20 人、0 重复)通过;D-V2 喜欢 HTTP 200 被判 `risk_control`,按停止条件停下抖音,D-V3~D-V5 `not-run`。所以抖音“观看历史”不显示(Q-015 第 3 条)。这一次额度已用完,复查要新的授权([待你统一处理](#site-pending)) |
-
-
-
-### ACT-007:复跑 ACT-006 没完成的缓存与直播两步(2026-11-08 已执行,通过)
-
-ACT-006 的 `nav`、动态、投稿、开播状态和 `room_init` 额度已经用完,不能在原授权内复跑。
-
-| 项 | 内容 |
-| --- | --- |
-| 对象 | 你在 2026-11-08 对话里指定的直播间与 2 位用户(已写进本机 `.local/site-check/targets-act007.json`);只读 |
-| 凭证 | 同 ACT-006 |
-| 额度 | 1 次运行;API 合计 ≤ 20:`nav` ≤ 2、动态列表 ≤ 1、空间页面 ≤ 1、投稿列表 ≤ 1、视频详情 ≤ 2、播放地址 ≤ 3、弹幕分段 ≤ 2、字幕列表 ≤ 1、`cookie/info` ≤ 1(不刷新)、开播状态 ≤ 1、`room_init` ≤ 2(多 1 次用于断流后重连的下播判断)、取流 ≤ 2;点播媒体 ≤ 30 次、≤ 200 MiB;直播录制 ≤ 30 秒(≤ 60 次、≤ 60 MiB,不在直播就跳过);扫码、刷新、写操作 0 次。用量写进 `.local/site-check/usage-act007.json`,超额的请求在发出前拒绝 |
-| 停止条件、记录 | 同 ACT-006;另外记录直播的停止原因与播放列表结构(只记标签和计数,不记地址) |
-
-你在 2026-11-08 给出真实站点验证的常设授权后,A 运行 `go run ./tools/actcheck -act act007` 1 次,**全部通过**(回执 `artifacts/site-check/act007.json`,账本 API `13/20`;全部 HTTP 200/206,没有风控、限流或验证码):登录、用户动态第 1 页(12 条)、投稿第 1 页(30 条,总计 615)通过;从动态里选最短的视频(7 秒,竖屏 1080×1920,`avc1.640033`,音质 `30280`)缓存完成,生成 MP4 `9,124,240` 字节,弹幕已存,没有字幕不算缺失,条目状态 `complete`、缺失项 0(点播媒体 4 次请求、`9,794,313` 字节);直播间正在直播,录制 20.1 秒(`avc`、`qn=10000` 原画,播放列表 52 次请求、`15,765,109` 字节),按“用户停止”结束,收尾成 1 段 MP4 `15,729,116` 字节,条目状态 `complete`。这次直播播放列表是普通媒体列表(带站点自定义标签 `#EXT-BILI-AUX`),不是多码率索引,所以 ACT-006 那次停止的确切原因没能复现确认,见阶段报告 §7。临时数据目录已删除。
-
-### ACT-006:M1 新实现的真实站点小额复核(2026-11-08 已执行 1 次,未通过;额度已用完)
-
-ACT-004、ACT-005 的回执只证明当时的代码。M1 的代码是新写的,需要用小额度确认新代码对真实站点仍然兼容。
-
-| 项 | 内容 |
-| --- | --- |
-| 对象 | 本机 `.local/site-check/targets.json` 里的同一位用户与 `liveRoom`;只读 |
-| 凭证 | 本机测试 Cookie(`.env.local` 的 `TRACE_TEST_BILIBILI_COOKIE_FILE`),只读取、不打印 |
-| 额度 | API 合计 ≤ 20:`nav` ≤ 2、动态列表 ≤ 1、空间页面(取 `w_webid`)≤ 1、投稿列表 ≤ 1、视频详情 ≤ 2、播放地址 ≤ 3、弹幕分段 ≤ 2、字幕列表 ≤ 1、`cookie/info` ≤ 1(不刷新)、开播状态 ≤ 1、`room_init` ≤ 1、取流 ≤ 2;媒体请求 ≤ 30 次、≤ 200 MiB;直播录制 ≤ 30 秒(分片与列表请求 ≤ 60 次、≤ 60 MiB,不在直播就跳过);扫码、刷新、写操作 0 次。用量写进 `.local/site-check/usage-act006.json`,超额的请求在发出前拒绝 |
-| 停止条件 | 遇到 `-352`、`-412`、HTTP 412、`-101`、验证码或权限不明时立即停止,判为失败,不重试 |
-| 记录 | 只记类别、状态码、计数、字节数、清晰度与音质、录制时长;不记 Cookie、签名地址;临时媒体校验后删除;脱敏回执写到 `artifacts/site-check/act006.json` |
-
-你在 2026-11-08 回复“授权 ACT-006”,并在对话里指定了直播间与 2 位用户。同日执行 1 次(检查程序 `tools/actcheck`,回执 `artifacts/site-check/act006.json`,账本 API `9/20`;全部 HTTP 200,没有风控、限流或验证码):登录、用户动态第 1 页(12 条)、投稿第 1 页(30 条,总计 615)通过;缓存视频一步因检查程序先入队、后启动下载管理器,任务被启动恢复改为暂停,没有执行到下载(检查程序的错误,已改);直播录制在 0.23 秒停止,原因是直播播放列表的多码率索引没被识别(已修并补回归)。这两步在 [ACT-007](#act-007) 复跑。
-
-
-### ACT-005:订阅、续期检查、弹幕字幕与直播的真实站点有界检查(已完成,额度已记账)
-
-你在 2026-11-07 回复“授权 ACT-005”,并指定直播录制用的直播间(已写进本机 `targets.json` 的 `liveRoom`)。
-
-| 项 | 内容 |
-| --- | --- |
-| 对象 | 本机 `.local/site-check/targets.json` 里的哔哩哔哩用户(与 ACT-004 相同):对他检查更新 2 次(第一次建立起点,第二次比较);从他已有的视频里选 1 个有 CC 字幕的(没有就选任意 1 个)取弹幕与字幕;查他的开播状态。测试账号自己的关注分组与关注列表第 1 页(只读,不导入以外的写操作)。`cookie/info` 只问“是否需要刷新”,**不执行刷新**(刷新会让测试 Cookie 和你浏览器里的同一会话失效)。对 `targets.json` 里的 `liveRoom`(你指定的直播间):用 `room_init` 换长号与主播,查开播状态;正在直播就取流并录制不超过 60 秒,录完转成 MP4 并校验后删除;不在直播就跳过录制、记为 `skipped`(不为等开播重复请求) |
-| 凭证 | 本机测试 Cookie(`.env.local` 的 `TRACE_TEST_BILIBILI_COOKIE_FILE`),只读取、不打印 |
-| 额度 | API 请求合计不超过 30 次:`nav` ≤ 2、动态列表 ≤ 2、用户资料 ≤ 1、视频详情 ≤ 2、弹幕分段 ≤ 3、字幕列表 ≤ 2、关注分组 ≤ 1、关注列表 ≤ 1、`cookie/info` ≤ 1、开播状态 ≤ 2、直播间信息 ≤ 1、取流 ≤ 3;字幕文件 ≤ 2 个;直播分片与播放列表请求 ≤ 120 次、合计 ≤ 100 MiB;扫码、刷新、任何写操作接口 0 次。用量写进 `.local/site-check/usage-act005.json` 跨运行累计,超额的请求在发出前被拒绝 |
-| 停止条件 | 遇到 `-352`、`-412`、HTTP 412、`-101`、验证码或任何权限不明的情况立即停止,检查判为失败;不重试 |
-| 记录 | 只记类别、状态码、计数、字节数、节点域名、弹幕条数、字幕语言、录制的编码与时长;不记 Cookie、签名地址、关注列表里的账号信息;临时媒体目录在校验后删除 |
-
-2026-11-07 执行,全部通过:对目标用户完成 2 次检查更新(第 1 次读取第 1 页 12 条动态建立起点,没看过 0 条;第 2 次读取第 1 页 12 条动态命中起点即停,没看过 0 条);在额度内探测该用户 2 个视频均无 CC 字幕(字幕文件 `0/2`),对其中 18 秒视频拉取第 1 段 protobuf 弹幕并解码合并写出 XML(`107` 条弹幕、`9,976` 字节);只读拉取测试账号自己的关注分组(`2` 个分组)与关注列表第 1 页(`50` 条,`total=244`);调用 `cookie/info` 检查是否需要刷新(返回 `refresh=true`,按授权未执行刷新,`refreshExecuted=false`);查询目标用户开播状态为轮播(`round`,`live_status=2`);对指定直播间经 `room_init` 解析长房间号与主播 UID,查询开播状态为直播中(`live`,`live_status=1`),优选 `http_hls`/`fmp4` 流(`avc`、`原画`)录制 1 段并经 mp4ff `Defragment` 收尾为普通 MP4(`9,073,932` 字节、时长 `21.01s`、`moov` 在前),校验通过后删除临时数据目录(`tempMediaDeleted=true`,敏感信息与目标标识扫描 `secretScanClean=true`)。累计用量在 `.local/site-check/usage-act005.json`:API `17/30`(`nav` 2/2、动态列表 2/2 已用完),直播分片与播放列表请求 `36/120`、字节 `9,098,637/104,857,600`。脱敏回执保存在 `artifacts/site-check/act005.json`;该额度账本与脱敏回执原样保留;它们只证明当时的实现。M1 新代码对真实站点的兼容性由 [ACT-006](#act-006) 复核。
-
-
-### ACT-004:M1 的真实站点有界检查(已完成,额度已记账)
-
-| 项 | 内容 |
-| --- | --- |
-| 对象 | 本机 `.local/site-check/targets.json` 里的哔哩哔哩用户:读 1 页动态;从中缓存 1 条图文动态、1 条视频动态;再缓存该用户投稿里的 1 个多 P 视频(没有多 P 时跳过并记录);对已缓存的视频做 1 次画质升级探测 |
-| 凭证 | 本机测试 Cookie(`.env.local` 的 `TRACE_TEST_BILIBILI_COOKIE_FILE`),只读取、不打印 |
-| 额度 | API 请求合计不超过 25 次:`nav` ≤ 2、动态列表 ≤ 1、视频详情 ≤ 4、播放地址 ≤ 10(含重取与升级探测)、动态详情 ≤ 2;用户主页 ≤ 1;二维码 0;媒体文件请求 ≤ 300 次(分段下载按段计)、合计 ≤ 800 MiB。用量写进 `.local/site-check/usage-act004.json` 跨运行累计,超额的请求在发出前被拒绝 |
-| 停止条件 | 遇到 `-352`、`-412`、HTTP 412、`-101`、验证码或任何权限不明的情况立即停止,检查判为失败;不重试 |
-| 记录 | 只记类别、状态码、计数、字节数、节点域名、实际清晰度与音质;不记 Cookie、签名地址;临时媒体目录在校验后删除 |
-
-2026-11-05 执行,2026-11-06 A 复核通过:读取动态第 1 页(13 条),缓存 1 条图文动态(原图 1 张,`3,208,287` 字节,SHA-256 校验通过)和 1 条视频动态(1P,`qn=116` `1080P 60帧` AVC + `30280` `192K` 音频,视频流分 3 段 Range 拉取合并后时长 `12.93s` / 站点 `13s`,误差 `0.07s`,`moov` 在前、交错存放、带 `elst`);对已缓存视频完成 1 次画质升级探测并验证 24 小时内不重复请求;临时媒体目录校验后已删除。累计用量在 `.local/site-check/usage-act004.json`:API 8/25(`nav` 2/2、动态列表 1/1 已用完),媒体文件请求 6/300、字节 `21,617,429/838,860,800`。脱敏回执保存在 `artifacts/site-check/result.json`。
-
-
-### ACT-015:按正式流程缓存你指定的 1 条抖音视频(2026-11-13,常设授权内,A 运行 1 次)
-
-你反馈抖音视频都提示“付费专享内容,不支持缓存”。原因是 TRACE 把普通作品也带有的 `entertainment_product_info.market_info.limit_free.in_free == false` 当成了付费标记,A 已删掉这条判断并补回归测试。2026-11-13 你给了 1 条视频(写进本机 `.local/site-check/targets-act015.json`,不进仓库),说原画下载后应不少于 50MB。本项用真实站点确认修复后能从头到尾缓存成功、大小与画质符合预期。
-
-| 项 | 内容 |
-| --- | --- |
-| 执行 | `go run ./tools/actcheck -act act015`:走 TRACE 正式后端与下载管理器(登录、解析作品、选流、分段下载、收尾 MP4、入库);下载管理器的媒体请求经检查程序计数(`download.Manager.SetMediaTransportWrap`,应用本身不设) |
-| 对象、凭证 | 这 1 条视频,只读;Cookie 只读取、不打印,点播 CDN 不带 Cookie |
-| 额度 | 1 次运行;抖音 API 合计 ≤ 4:`profile/self` ≤ 1、`aweme/detail` ≤ 3(计划 1 次 + 地址过期重取备用 2 次);点播与封面 CDN ≤ 40 次、≤ 200 MiB;直播、扫码、写操作 0 次。全程串行,间隔 ≥ 1.2 秒。独立账本 `.local/site-check/usage-act015.json`,超额请求在发出前拒绝 |
-| 要回答的问题 | 作品不再被判为付费;选中的档位、编码、分辨率、可选档位;文件大小 ≥ 50,000,000 字节;`moov` 在 `mdat` 之前、入库校验通过 |
-| 停止条件、记录 | 同 ACT-010。脱敏回执写到 `artifacts/site-check/act015.json`;临时数据目录校验后删除 |
-
-**结果(2026-11-13,A 运行 1 次,未通过;转 [ACT-016](#act-016))**:账本 `usage-act015.json` 为 `runs=1/1`、API `2/4`(`profile_self 1`、`aweme_detail 1`,`status_code` 都是 0),点播 `2` 次、`0` 字节;没有触发停止条件,回执脱敏扫描干净、临时目录已删。**付费误判已修复**:作品正常进入下载。下载两次都在本机被拒(`blocked`),没有请求到达 CDN:本机环境变量 `HTTP_PROXY`/`HTTPS_PROXY` 指向 `127.0.0.1` 的代理,抖音点播下载器与直播录制器的防内网拨号检查把代理本身当成了回环地址。这是 TRACE 自己的问题(ACT-014 的直播短录用的是检查程序自己的客户端,所以没暴露),A 已修:代理来自用户配置,直接拨号;经代理时仍先检查媒体主机解析出的地址。
-
-
-### ACT-016:代理拨号修复后复跑 ACT-015(2026-11-13,常设授权内,A 运行 1 次)
-
-ACT-015 没有触发停止条件,失败在 TRACE 本机的拨号检查;按规定不在原额度里复跑,单列本项。对象、凭证、额度、问题、停止条件与 ACT-015 相同;执行 `go run ./tools/actcheck -act act016`,独立账本 `.local/site-check/usage-act016.json`,回执 `artifacts/site-check/act016.json`。
-
-**结果(2026-11-13,A 运行 1 次,下载通过、大小未达预期;转 [ACT-017](#act-017))**:账本 `runs=1/1`、API `2/4`,点播 `2` 次 `206`、共 `6,076,103` 字节;没有触发停止条件,回执干净、临时目录已删。代理修复有效,正式流程完整缓存并入库:选中 `4K`(档位 `adapt_lowest_4_1`)、HEVC、`2160×3840`、60 帧、码率约 3.6 Mbps,`13.4` 秒,`6,045,201` 字节,`moov` 在前。可选档位 `4K/2K/1080P/720P/540P` 全是站点转码版,所以达不到你说的 50MB:50MB/13 秒约 30 Mbps,只有未转码的原画能到。TRACE 以前有意不用原画跳转地址(协议资料 §6.4),按你的要求改为“先取原画,失败再用最高转码档”。
-
-
-### ACT-017:原画优先缓存复测(2026-11-13,常设授权内,A 运行 1 次)
-
-对象与凭证同 ACT-015。执行 `go run ./tools/actcheck -act act017`;独立账本 `usage-act017.json`。额度:API ≤ 4(`profile/self` ≤ 1、`aweme/detail` ≤ 3),点播 CDN(含原画跳转地址 `aweme.snssdk.com/aweme/v1/play/` 每次请求与跳转)≤ 40 次、≤ 200 MiB;其余为 0。要回答:原画跳转能否不带 Cookie 拿到无水印 MP4,文件是否 ≥ 50,000,000 字节;拿不到时是否回退到最高转码档。停止条件、记录同 ACT-010。
-
-**结果(2026-11-13,A 运行 1 次,未覆盖原画;转 [ACT-018](#act-018))**:账本 `runs=1/1`、API `2/4`、点播 `2` 次共 `6,076,103` 字节,结果与 ACT-016 相同,原画跳转 0 次请求。原因:应用实际用的是服务层的抖音缓存计划(`internal/service/douyin_planner.go`),A 只在站点适配器里加了原画地址,服务层没有传下去。这是 TRACE 自己的问题,已补(画质设置为“最高”时才取原画)。
-
-
-### ACT-018:原画优先缓存复测(补服务层后,2026-11-13,常设授权内,A 运行 1 次)
-
-对象、凭证、额度、问题、停止条件同 [ACT-017](#act-017);执行 `go run ./tools/actcheck -act act018`,独立账本 `usage-act018.json`。
-
-**结果(2026-11-13,A 运行 1 次,通过)**:账本 `runs=1/1`、API `2/4`(`profile_self 1`、`aweme_detail 1`),点播 `15` 次(`302` 7 次、`206` 8 次)共 `53,314,717` 字节,原画跳转都落到公共 HTTPS 443 域名、不带 Cookie;没有触发停止条件,回执脱敏扫描干净、临时目录已删。缓存为原画:HEVC+AAC,`2160×3840`,`13.4` 秒,约 31.8 Mbps,**`53,282,617` 字节**(≥ 50,000,000),`moov` 在前,入库校验通过,可选档位记为“原画、4K、2K、1080P、720P、540P”。
-
-
-### ACT-019:哔哩哔哩实况动态的缓存与片段格式检查(2026-11-13,常设授权内,B 运行 1 次)
-
-你反馈哔哩哔哩的实况动态在看图层不能播放动态片段([DEC-046](docs/decisions.md#dec-046) ①)。本项用你给的那条实况动态(本机 `.local/site-check/targets-bilibili-live-photo.json`,不进仓库)查清片段在哪一步丢了:解析没拿到 `live_url`、缓存没存、片段格式不对,还是看图层没接上。
-
-| 项 | 内容 |
-| --- | --- |
-| 执行 | `go run ./tools/actcheck -act act019`:走 TRACE 正式后端与下载管理器(登录、入队、取动态详情、下载静帧与片段、入库),再在本机检查片段的容器结构 |
-| 对象、凭证 | 这 1 条动态,只读;哔哩哔哩测试 Cookie 只读取、不打印 |
-| 额度 | 1 次运行;API 合计 ≤ 4:`nav` ≤ 2、动态详情 ≤ 2(入队 1 次 + 下载时重取 1 次);图片与片段 CDN ≤ 10 次、≤ 50 MiB;其他接口、直播、扫码、刷新、写操作 0 次。独立账本 `.local/site-check/usage-act019.json`,超额请求在发出前拒绝 |
-| 要回答的问题 | 详情里有几张图、几张带非空 `live_url`(只记扩展名与域名后缀);缓存后有几个片段、是否挂在对应静帧上;片段的顶层 box 顺序(`moov` 是否在 `mdat` 前、有没有 `moof`)、编码、时长与尺寸 |
-| 停止条件、记录 | 遇到 `-352`、`-412`、HTTP 412、`-101`、验证码或权限不明立即停止,不重试。脱敏回执写到 `artifacts/site-check/act019.json`,不含 Cookie、地址与动态 ID;临时数据目录校验后删除 |
-
-**结果(2026-11-13,B 运行 1 次,通过)**:账本 `runs=1/1`、API `3/4`(`nav 1`、动态详情 `2`,都是 HTTP 200),CDN `2/10` 次、`1,220,383` 字节(静帧 JPEG 与片段 MP4 各 1 次 `206`);没有触发停止条件,回执脱敏扫描干净(不含地址与 ID)、临时目录已删。结论:**解析、缓存和片段格式都没问题**——详情里 1 张图、1 张带非空 `live_url`(`.mp4`,`*.hdslb.com`);缓存后 1 个片段挂在对应静帧上,条目 `complete`;片段顶层 box 为 `ftyp, moov, free, mdat`(`moov` 在前、无 `moof`),AVC、`1080×1440`、`2.576` 秒,与静帧 `4284×5712` 同为 3:4。问题在**看图层**:以前只有已缓存的实况才有播放按钮,而且点了会关掉看图层改用播放层;没缓存的帖子(用户页、动态详情)根本没有播放入口。B 已改为两种情况都在看图层里原地播放(没缓存的经哔哩哔哩 CDN 取到临时文件),并在缓存时按单文件 MP4 校验片段、必要时把 `moov` 移到前面,保证系统播放器也能预览。
-
-
-### ACT-014:跳转修复后补测抖音直播 FLV 短录(2026-11-13 你授权后 A 已运行 1 次,通过)
-
-[ACT-012](#act-012) 查明:抖音直播 FLV 地址第一跳 `302` 到白名单外的 HTTPS 443 域名,录制器拒绝跳转,所以没录到(A 审查 F-004)。A 已改跳转规则:首个地址仍查白名单,之后的跳转只要求 HTTPS、443 端口、公共域名(不接受 IP 和本地主机名),仍不带 Cookie。这次在真实站点上确认修复有效。问题出在 TRACE 自己的规则,按规定不在 ACT-012 的额度里重跑,所以单列一项请你确认。
-
-| 项 | 内容 |
-| --- | --- |
-| 执行 | `go run ./tools/actcheck -act act014`,你确认后由 A 运行 1 次 |
-| 对象、凭证 | 同 [ACT-012](#act-012):同一个直播间,只读;Cookie 只读取、不打印,直播流不带 Cookie。没在直播就跳过录制,保持 not-run |
-| 额度 | 1 次运行;抖音 API 合计 ≤ 3:`profile/self` ≤ 1、`webcast/room/web/enter` ≤ 2;`reflow/info`、HLS 播放列表、点播都是 0;直播 FLV 请求 ≤ 4(2 次连接,每次含 1 跳)、录制 ≤ 25 秒、≤ 50 MiB;扫码、写操作 0 次。全程串行,间隔 ≥ 1.2 秒。独立账本 `.local/site-check/usage-act014.json`,超额请求在发出前拒绝 |
-| 要回答的问题 | 按新跳转规则能否连上并录到;V-07:FLV 流头是 `CodecID=12` 还是 Enhanced FLV `hvc1`、按 GOP 写的分片能否收尾为可播放 MP4 |
-| 停止条件、记录 | 同 ACT-010;带 `Location` 的 3xx 跳转不算验证页。脱敏回执写到 `artifacts/site-check/act014.json`(跳转只记形状,不记地址) |
-
-**结果(2026-11-13,A 运行 1 次,一次通过)**:账本 `usage-act014.json` 为 `runs=1/1`、API `2/3`、FLV `2/4` 次共 `751,453` 字节(第一跳 `302`,按新规则跟随后 `200`);其他账本没动。回执由程序写出、脱敏扫描干净、临时目录已删,没有遇到验证、限流或登录失效。选中“原画”,FLV 视频标签是 AVC(`CodecID=7`,不是 `12`/`hvc1`),`1280×720`,音视频 `avc1`+`mp4a`;录了 `21.56` 秒、`15` 个分片、`1` 个分段,收尾为 `735,389` 字节的 MP4,`moov` 在 `mdat` 之前,状态 `completed`。也就是说,跳转修复在真实站点有效。这个直播间只给 AVC,HEVC 流没见到,仍只由合成测试覆盖。没有新问题,所以不需要再修再测。
-
-
-### ACT-012:补测抖音直播 FLV 短录(2026-11-13 你授权后 A 已运行 1 次;查明跳转被拒,已修,短录转 ACT-014)
-
-ACT-011 走到直播一步时,FLV 地址第一跳返回 `302`,带一段 258 字节的“302 Found”网页正文。检查程序把它当成验证页并按规则立即停止,没有录到(A 审查 F-003)。A 判断这是 CDN 的正常跳转,不是验证码,已修好检查程序;但上一次毕竟触发了停止条件,所以这次不直接在常设授权里重跑,先请你确认。
-
-| 项 | 内容 |
-| --- | --- |
-| 执行 | `go run ./tools/actcheck -act act012`,你确认后由 A 运行 1 次 |
-| 对象 | `.local/site-check/targets-douyin.json` 里同一个直播间(不变的数字抖音号);只读。没在直播就跳过录制,保持 not-run |
-| 凭证 | 同 ACT-010(`.env.local` 的 `TRACE_TEST_DOUYIN_COOKIE_FILE`),只读取、不打印;直播流不带 Cookie |
-| 额度 | 1 次运行;抖音 API 合计 ≤ 3:`profile/self` ≤ 1、`webcast/room/web/enter` ≤ 2(1 次 + 断流重取 1 次);`reflow/info`、HLS 播放列表、点播都是 0;直播 FLV 请求 ≤ 4(2 次连接,每次最多跟随 1 跳)、录制 ≤ 25 秒、≤ 50 MiB;扫码、写操作 0 次。全程串行,间隔 ≥ 1.2 秒。用量写进独立账本 `.local/site-check/usage-act012.json`,超额请求在发出前拒绝 |
-| 要回答的问题 | V-07:FLV 流头是 `CodecID=12` 还是 Enhanced FLV `hvc1`、按 GOP 写的分片能否收尾为可播放 MP4;F-004:CDN 的 302 跳到哪类地址(协议、IP 还是域名,只记形状不记地址),生产录制器的跳转策略会不会拒绝 |
-| 停止条件、记录 | 同 ACT-010;带 `Location` 的 3xx 跳转不算验证页。脱敏回执写到 `artifacts/site-check/act012.json` |
-
-**结果(2026-11-13,A 运行 1 次)**:账本 `usage-act012.json` 为 `runs=1/1`、API `3/3`(`profile_self 1`、`web_enter 2`,都正常返回)、FLV `2/4` 次共 `516` 字节;`usage-act010.json`、`usage-act011.json` 没动。回执由程序写出、脱敏扫描干净、临时目录已删,没有遇到验证、限流或登录失效。直播间在播。**F-004 已回答**:两次连接的第一跳都是 `302`,跳到白名单外的另一个 HTTPS 443 域名(不是 IP),录制器的跳转规则拒绝了它,所以没录到。也就是说,修复前抖音直播录制在真实站点上会全部失败。A 已按你的授权改好跳转规则([阶段报告 §9.5](https://github.com/chialecode/trace/blob/f080483/docs/delivery/stage-report.md#a-act012)),修复后的真实录制见 [ACT-014](#act-014)。
-
-
-### ACT-011:补测 ACT-010 未走完的离线 `room_id=2` 与抖音直播 FLV 录制(2026-11-13 A 已运行 1 次;离线换号已回答,FLV 短录转 ACT-012)
-
-ACT-010 的单次运行额度(`runs=1/1`)已记入 `.local/site-check/usage-act010.json`;按 ACT-010“因 TRACE 自己的错误没走完时,修复后另开一项申请剩余步骤的额度,不在原额度里复跑”的规则,把未发出请求的两小步单列为 ACT-011(隶属你在 2026-11-08、2026-11-12 给出的真实站点验证常设授权)。
-
-| 项 | 内容 |
-| --- | --- |
-| 执行 | `go run ./tools/actcheck -act act011`(B 已在 `tools/actcheck` 建立并通过合成门禁测试);A 审查时或目标直播间处于开播态时运行 1 次 |
-| 对象 | 本机 `.local/site-check/targets-douyin.json` 里的第 1 位用户(测离线占位 `room_id=2` 反查)与同一直播间(测 HTTP-FLV 流头、重封装与 ≤ 25 秒短录收尾);只读 |
-| 凭证 | 同 ACT-010(`.env.local` 的 `TRACE_TEST_DOUYIN_COOKIE_FILE`),只读取、不打印 |
-| 额度 | 1 次运行;抖音 API 合计 ≤ 4:`profile/self` ≤ 1、`reflow/info` ≤ 1、`webcast/room/web/enter` ≤ 2;直播 HLS 播放列表文本 ≤ 1(≤ 2 MiB);点播媒体 0 次;直播 FLV 连接 ≤ 2 次、录制 ≤ 25 秒、≤ 50 MiB(检查时直播间没开播就跳过录制,V-07 短录保持 not-run)。扫码、写操作 0 次。全程串行,间隔 ≥ 1.2 秒。用量写进独立账本 `.local/site-check/usage-act011.json`(不改动 `usage-act010.json`),超额请求在发出前拒绝 |
-| 停止条件、记录 | 停止条件与脱敏规则同 ACT-010;临时媒体目录校验后立即删除,脱敏回执写到 `artifacts/site-check/act011.json` |
-
-**结果(2026-11-13,A 审查时运行 1 次)**:账本 `usage-act011.json` 为 `runs=1/1`、API `3/4`(`profile_self 1`、`reflow_info 1`、`web_enter 1`)、HLS 播放列表 `1/1`、FLV `1` 次 `258` 字节;`usage-act010.json` 没动。回执 `artifacts/site-check/act011.json` 由程序写出、脱敏扫描干净、临时目录已删。测试 Cookie 仍有效。**V-06**:离线占位 `room_id=2` 的 `reflow/info` 返回 `status_code=10011`,拿不到 `web_rid`。也就是说,离线且没缓存过直播间号的订阅账号要等开播后才能换到,现有实现就是这样做的。**V-07**:直播间在播,原画同时有 FLV 与 HLS;FLV 第一跳 `302` 后检查程序误停(`stoppedBy=html_verify_page`),短录没做成,剩余一步见 [ACT-012](#act-012)。
-
-
-### ACT-010:抖音的真实站点有界检查(2026-11-13 已执行 1 次,V-01~V-05 与 V-08 通过;剩余两小步转 ACT-011)
-
-你在 2026-11-12 确认 2026-11-08 的常设授权也适用于抖音([DEC-043](docs/decisions.md#dec-043))。2026-11-12 你放好了测试 Cookie,并授权后续按本项进行真实站点检查。下面是检查程序与额度;Agent 只在额度内执行,用账本在发出前拒绝超额;超出本项的真实请求另开一项。
-
-**你要提供的**
-
-1. **测试 Cookie**(建议用小号):在浏览器里登录抖音网页版并正常浏览一下首页,打开开发者工具(F12)→“网络”,点任意一个发往 `www.douyin.com` 的请求,复制请求头里 `Cookie` 的整串,存进 `.local/site-secrets/douyin.cookie`(只有这一行),再在 `.env.local` 加一行 `TRACE_TEST_DOUYIN_COOKIE_FILE=.local/site-secrets/douyin.cookie`。不要发在对话里。
-2. **检查对象**:2026-11-13 你给了 2 位用户的主页、1 条置顶视频、1 条新视频、1 条普通图文和 1 条图片/视频/配乐混排的图文,A 已写进本机 `.local/site-check/targets-douyin.json`(不进仓库)。同日你又给了 1 个直播间的两种链接:主播的数字抖音号(不变)和另一个会变的数字,两者是同一个直播间。
-
-| 项 | 内容 |
-| --- | --- |
-| 执行 | `go run ./tools/actcheck -act act010`(B 在 M3 建立),走 TRACE 的正式代码;B 实现完成后或 A 审查时,谁先具备条件谁运行 1 次。因 TRACE 自己的错误没走完时,修复后另开一项申请剩余步骤的额度,不在原额度里复跑 |
-| 对象 | `targets-douyin.json` 里的 2 位用户、4 条作品,以及 1 个直播间(两种链接);只读 |
-| 额度 | 抖音 API 合计 ≤ 18:`profile/self` ≤ 2(不带 Cookie 1 次作对照 + 带 Cookie 1 次)、`profile/other` ≤ 2(每位用户 1 次)、`aweme/post` ≤ 3(第 1 位用户第 1、2 页,第 2 位用户第 1 页)、`aweme/detail` ≤ 4(每条作品 1 次)、`webcast/room/web/enter` ≤ 4(两种直播间号各 1 次对照 + 断开后重新取流 1 + 备用 1)、`reflow/info` ≤ 2(离线换号核对 1 + 开播换号 1)、直播 HLS 播放列表文本 ≤ 1(只看分片格式);短链跳转 0(没有短链对象,短链只用夹具测)。媒体与图片 CDN ≤ 16 次、合计 ≤ 64 MiB(不带 Cookie;单个文件超过 24 MiB 时只取开头 8 MiB 和结尾 1 MiB 判断封装);直播 FLV 连接 ≤ 2 次、录制 ≤ 25 秒、≤ 50 MiB(检查时直播间没开播就跳过录制,V-07 记 not-run)。扫码、写操作 0 次。全程串行,间隔 ≥ 1.2 秒。用量写进 `.local/site-check/usage-act010.json`。2026-11-13 按你给的对象从 16 次调整为 18 次(多的是作品详情与两种直播间号的对照) |
-| 要回答的问题 | 抖音协议资料的 V-01~V-08([§10.1](docs/research/douyin.md#act-010)):登录对照、签名与网关是否通过、置顶与翻页、图文与实况格式(含混排图文的视频页)、点播 Range 下载、离线账号能否换到直播间号、直播流的格式与编码、同一直播间两种号码的关系(V-08) |
-| 停止条件 | 遇到 HTTP 403(含 `ArgusSecurityPlugin`)、429、444、0 字节响应、验证码页、非空的 `verify_*` 或滑块挑战、带 Cookie 的请求被判为未登录时,立即停止全部后续请求,判为失败,不重试、不换会话,绝不尝试解验证码 |
-| 记录 | 只记端点名、次数、HTTP 状态、`status_code`、流的封装与编码、字节数、段数、时长误差;不记 Cookie、签名地址和对象的真实 ID;临时数据目录校验后删除;脱敏回执写到 `artifacts/site-check/act010.json` |
-
-2026-11-13(UTC `2026-11-12T20:40:14Z`~`20:40:43Z`)B 执行 `go run ./tools/actcheck -act act010` 1 次(`artifacts/site-check/act010.json` 不是程序写出的回执:程序写盘被自己的脱敏校验误拦,文件是 B 事后按账本与控制台输出补写的,逐请求状态没有记录,见[阶段报告 F-001](https://github.com/chialecode/trace/blob/f080483/docs/delivery/stage-report.md#a-findings);账本 `.local/site-check/usage-act010.json`:`runs=1/1`,接口与播放列表 `15/18`[`profile_self: 2`、`profile_other: 2`、`aweme_post: 3`、`aweme_detail: 4`、`web_enter: 2`、`reflow_info: 1`、`hls_playlist: 1`],点播与图片 CDN `6/16` 次、共 `10,602,566` 字节且不带 Cookie,直播媒体 `0` 次;`stoppedBy=""`,即没有触发任何停止条件:HTTP 403/429/444、`ArgusSecurityPlugin` 拦截、验证页与验证字段都会触发停止;`tempMediaDeleted=true`):
-- **已验证通过(V-01~V-05、V-06 在线路径、V-08)**:① `profile/self` 不带 Cookie 返回未登录、带粘贴 Cookie(已清洗掉 `bd_ticket_guard_*` 且初始不含 `msToken`)一次返回有效账号;② 纯 Go 标准库 SM3 + `a_bogus`(`dhzx`)+ `x-secsdk-web-signature` 在主站与直播全部受测接口一次通过;③ 第 1 位用户作品列表含置顶翻第 2 页及第 2 位用户第 1 页均通过;④ 普通图文与图片/视频/配乐混排图文正确解析,无水印图片、混排视频与配乐直链拉取及容器校验通过;⑤ 点播视频在不带 Cookie 下分段拉取并通过单文件 MP4 校验;⑥ 同一直播间的两种号码(主播数字 `short_id` 与可变房间号)经 `web/enter` 均指向同一开播直播间与主播 `sec_uid`,且在线 `room_id` 经 `reflow/info` 换号通过、HLS `.m3u8` 播放列表拉取通过。详细协议结论已回写[抖音协议 §11](docs/research/douyin.md#a-review)。
-- **未发出请求的两小步(已修复,移入 [ACT-011](#act-011))**:① 离线占位 `room_id=2` 反查因首轮客户端本地正则要求 `>= 4` 位数字,在发包前本地拒绝(0 次网络请求),已改为接受 1~24 位正整数;② 开播直播间的 HTTP-FLV 短录因首轮 `EnterLiveRoom` 误把外层 `data.enter_mode == 1` 当成语音直播,在拉完 `.m3u8` 后提前报错退出(0 次 FLV 连接),已修正语音房判定条件并补齐合成回归测试(另修复检查器脱敏对布尔字面量 `false` 的误替换),遵守规则未重跑 `act010`。
-
### ACT-008:备份更新密钥,配置仓库的发布环境(仓库设置已完成,2026-11-09)
@@ -265,30 +67,30 @@ ACT-010 的单次运行额度(`runs=1/1`)已记入 `.local/site-check/usage-
- M2 合并后,在 GitHub 上手动运行一次 `release.yml`(只构建、演练,不发布),确认 Windows 运行器上能完成。
3. **不包括**:创建标签和 Release、打开自动发布(见 ACT-009)。
-
-### ACT-009:打开每周自动发布正式版(2026-11-12 已完成)
-
-**结果**:你 2026-11-12 授权完成剩余操作直到发布成功。A 把仓库变量 `TRACE_RELEASE_PUBLISH` 设为 `1`,手动运行 `release.yml`(`publish=true`,[运行 43138195253](https://github.com/chialecode/trace/actions/runs/43138195253)),`check`、`build`、`publish` 全部通过,发布了 [v0.1.1](https://github.com/chialecode/trace/releases/tag/v0.1.1)。发布后从 `releases/latest` 取回更新清单,版本证明签名用内置公钥验证通过,更新包大小一致、地址为 HTTPS。以后每周一自动发布。以下为原说明。
-
-授权后,A 把仓库变量 `TRACE_RELEASE_PUBLISH` 设为 `1`:`release.yml` 每周一 00:00 UTC(北京时间 08:00)运行,上次发布以来 `main` 上有新合并的 PR 时,检查、构建、演练都通过就创建标签 `v0.1.x` 和 GitHub Release,装着正式版的电脑随后收到更新。第一次发布是 `0.1.1`。不授权时可以每次单独说“发布 0.1.x”,由 Agent 在本机用 `go run ./tools/release -publish` 发布那一次。随时可以说“停止自动发布”撤回。
-
-
-### ACT-001:推送并合并 M1(2026-11-09 已完成)
-
-你授权后,`codex/m1-mygo-bilibili` 已推送为 PR #1,CI 修复一次(没有显示器的 Linux 上跳过托盘真实窗口测试)后 `repository-quality` 与 DCO 通过,squash 合并为 `main @ 29c2678`。H-001 仍为 not-run,合并不代表产品验收。
-
-
-### ACT-002:哔哩哔哩真实站点有界检查(已完成)
-
-2026-11-04 共跑两轮:第一轮访客在投稿列表遇 `-412` 停止、已登录因 Cookie 失效停止;你更新 Cookie 后第二轮全部通过。结论见[协议资料第 1 节](docs/research/bilibili.md)。
+
+## 待你决定的事
-
-### ACT-003:动态列表与缓存的真实站点检查(已完成,额度已用完)
+
+### Q-022:远程版的默认做法(B 已按推荐实现)
-2026-11-04 执行,全部通过:登录态动态第 1、2 页(13 条、12 条,无重复),图文动态原图 1 张(`3,208,287` 字节),视频动态 `qn=112` AVC 视频流 + `30280` 音频流合并后时长误差 `0.00s`。累计用量在 `.local/site-check/usage.json`。
+你 2026-11-19 的要求与四个选择记为 [DEC-062](docs/decisions.md#dec-062),设计在[远程设计](docs/design/remote.md)。下面是 A 定的默认值,都可以改:
-
-## 待你决定的事
+| 条目 | 现在的做法(推荐) | 还可以调 |
+| --- | --- | --- |
+| 1. 上传方式 | 远程内置上传,调用 VPS 上的 rclone(你用 `rclone config` 配好 Google Drive,建议用自己的 client_id):按条目先传媒体文件、最后传 `item.json`,成功后删除 VPS 上的文件;你原来的定时 rclone 也能用,加上 `--exclude "*.part" --exclude ".trace-*"` | 上传后保留 VPS 上的文件;只用外部定时任务 |
+| 2. “启动后的新内容”怎么算 | 远程第一次检查一个账号时建立起点,之后发布的都缓存;远程停机期间发布的内容恢复后照常补上 | 每次重启都重新建立起点(停机期间的不补) |
+| 3. 同步哪些设置 | 订阅、共用缓存规则,以及画质、编码、音质、多 P、并发、弹幕、字幕、检查间隔、开播检查间隔;不同步代理与保存位置 | 增减条目 |
+| 4. 同步方式 | 远程的订阅整体换成本地的(本地是唯一正本);从本地移出的账号远程不再检查,文件不删 | 只增不删 |
+| 5. 端口与地址 | 默认监听 `:47380`,`init` 时可改;不需要域名 | — |
+| 6. 导入 | 默认复制,下载文件夹不动;可以勾选“导入后删除来源里已导入的文件”;校验大小与 SHA-256 | 默认移动;只校验大小(更快) |
+| 7. 本地导出 | 媒体库可以导出全部或当前筛选的条目到文件夹,格式与远程导出相同 | 不做 |
+| 8. 发行平台 | `linux/amd64` 与 `linux/arm64`;不发行 Windows 版远程程序 | 加 Windows |
+| 9. 远程状态刷新 | “设置 › 远程”打开时每 30 秒刷新一次;关着时不请求,只有“Cookie 待同步”每 10 分钟重试 | 改间隔 |
+| 10. 空间不够时 | 导出目录剩余少于 5 GiB 时提醒,少于 1 GiB 时暂停新的缓存任务(录制按已有的磁盘规则) | 改阈值 |
+| 11. 选文件夹(B 定) | 导入、导出与订阅文件的位置直接输入或粘贴路径,没有系统的文件夹选择框 | 加系统选择框 |
+| 12. 任务页的入口(B 定) | 任务侧栏一项“导入导出”,导入与导出都列在这里(计划里叫“导入”) | 只叫“导入”,导出另放 |
+| 13. 冲突没有选的(B 定) | 逐条和“全部冲突都……”都没选的冲突这次跳过,下次导入还会再列出;本地条目在另一个作者文件夹时,写进本地原来的文件夹,不搬动 | 没选时默认合并 |
+| 14. 导出的范围(B 定) | “当前筛选”就是媒体库现在的全部筛选:类型、站点、来源或作者、搜索词 | 只按作者与站点 |
### Q-021:2026-11-19 三条反馈的默认值(A 已按推荐实现)
@@ -317,7 +119,7 @@ ACT-010 的单次运行额度(`runs=1/1`)已记入 `.local/site-check/usage-
### Q-019:第四轮实机反馈的理解与默认值(已答复,2026-11-16;B 已按答复实现)
-你 2026-11-16 的反馈:直播录制的两个问题与空间页“解析接口数据字段失败”A 已修好([阶段报告 §14](docs/delivery/stage-report.md#feedback-4));主页的两条记为 [DEC-053](docs/decisions.md#dec-053),B 已按你的答复实现([阶段报告 §15](docs/delivery/stage-report.md#b-feedback-4)),实机复查见 [H-001](#h-001) 第 32 步。
+你 2026-11-16 的反馈:直播录制的两个问题与空间页“解析接口数据字段失败”A 已修好([阶段报告 §14](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-report.md#feedback-4));主页的两条记为 [DEC-053](docs/decisions.md#dec-053),B 已按你的答复实现([阶段报告 §15](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-report.md#b-feedback-4)),实机复查见 [H-001](#h-001) 第 32 步。
| 条目 | 你的答复(按此实现) |
| --- | --- |
@@ -504,17 +306,29 @@ M3 按下面的默认值实现([M3 计划](https://github.com/chialecode/trace
28. 我的(DEC-047,本机 TRACE Dev 已于 2026-11-14 更新):① 图标栏“订阅”下面有“我的”;进去后侧栏“哔哩哔哩”“抖音”都折叠,页面提示选择功能。② 展开“哔哩哔哩”,依次点“关注”(换一个分组)、“收藏夹”(换一个收藏夹,私密的有标记,失效视频灰着点不了)、“稍后再看”(切“未看完”,看进度对不对)、“历史记录”(今天、昨天、更早分组);每个列表滚到底能继续加载。③ 展开“抖音”,看“关注”“喜欢”“收藏”(切到一个收藏夹)。④ 在任一列表点一个视频、作品或用户:打开的是解析里的详情页,返回后回到原来的位置、列表没有重新加载;在“⋯”里缓存一条,任务页出现任务;在关注里把一个人加入订阅。⑤ 退出其中一个站点:“我的”里这个站点只剩“未登录 · 登录”。 ⑥ 抖音“喜欢”显示取不到的说明是预期的(见第 29 步⑤、Q-016 第 1 条);“收藏”或收藏夹显示别的错误时,记下文字告诉 Agent;“观看历史”目前不显示是预期的。
29. 第一轮反馈的复查(本机 TRACE Dev 已更新):① 设置 › 缓存规则:点一条规则展开,再点它缩起,反复几次不闪退。② 那场转换失败的哔哩哔哩直播录像(直播间 80397):重启 TRACE 后在媒体库或订阅“内容”里能播放、可以拖动,`item.json` 里不再有“转换失败”。③ 抖音订阅的头像:打开一次这个订阅(或等一次检查更新)后退出再打开 TRACE,头像仍是真实头像。④ 打开那条哔哩哔哩实况动态(`opus/1269437400365400067`)的图片:不用点按钮,实况片段自己动起来;按钮可以重播。⑤ 我的 › 抖音:“收藏”能列出内容;“喜欢”显示“抖音只把‘喜欢’列表给浏览器里的抖音网页……”,之后“收藏”和抖音订阅检查照常(不再出现“站点暂停访问中”)。⑥ 托盘:右键托盘图标,菜单紧贴指针打开、字体是系统菜单的大小,只有“打开 TRACE Dev”“退出”;左键打开窗口;悬停提示里能看到正在缓存与录制的数量。⑦ 打开一个作品多的抖音用户页,往下滚到加载出几百个作品(或开启“全部缓存”后在下载进行中滚动),滚动应当流畅。
30. 第一轮反馈及补充 5 项功能调整的体验(DEC-049 ①~③、DEC-050 ①②,本机 TRACE Dev 已更新至 `0.1.2-dev.202611150921` 及后续构建):① **解析页布局**:进入图标栏“解析”,左侧出现与视频页、用户页一样的“最近解析”侧栏(点条目打开详情,“⋯”可浏览器打开/删除单条,标题栏“⋯”可全部清空),右边主面板在留白中央只有一个较大的圆角输入框,不再在主面板下排历史列表;把窗口拉窄到 1000 以下时侧栏收起,输入框移到上方,“最近解析”显示在输入框下面。② **媒体库离线与排序**:进入“媒体库”,顶部没有“发布时间 / 缓存时间”切换(固定按发布时间从新到旧排列);断网(或观察运行日志确认无接口请求)后点卡片直接播放本机视频或打开看图层,点卡片“⋯ → 详情”进入媒体库自己的离线本机详情(图标栏仍停在“媒体库”,最近解析不增加条目,页面只读本机文件与清单,不显示在线统计);再点详情右上角“⋯ → 在解析页打开”(联网状态下)才跳到“解析”并请求最新站点详情。③ **全部缓存队列与任务页侧栏**:在哔哩哔哩用户页(动态或投稿标签)或抖音用户页点右上角“⋯ → 全部缓存”,不再出现 10/20/50 条子菜单,顶部提示已加入缓存队列,再点“⋯”显示“在缓存队列中查看”;进入“任务”,左侧上下文侧栏有“下载任务”“缓存队列”“直播录制”“录制异常”四项(窄窗在顶部切换;“录制异常”见第 31 步⑦),在“缓存队列”里能看到该账号任务正在逐条慢速排队(每次只排 1 条下载,两条间随机等待,展开能看到最近缓存的条目并点击打开本机详情),试一下暂停、继续,再从托盘退出重启 TRACE Dev 确认队列任务还在并会稍等后继续,点“取消”后未完成的下载停止而已经缓存进媒体库的视频仍在。④ **直播录制角标与页内实时预览**:找一个正在直播的主播开始录制,确认最左图标栏“任务”在没有下载任务时不出现数字角标(只有下载任务排队或进行中才显示数字角标);进入“任务 › 直播录制”(侧栏显示“直播录制(1)”),展开该录制行或点“实时预览”,直接在页内看到正在录制的实时画面与声音(没有实时弹幕,日志中无额外直播流请求),切到别的页面或点“停止录制”后预览立即关闭、文件正常收尾转为可播放录像。
-31. 第二轮反馈的复查(DEC-051,A 处理 4 条 + B 实现 4 条;本机 TRACE Dev 已更新至 `0.1.2-dev.202611151241`,[阶段报告 §11、§12](docs/delivery/stage-report.md#a-review-feedback-2);如未在桌面或托盘运行,先从开始菜单或桌面打开一次):① 在媒体库删掉某个作者的全部内容,打开缓存文件夹(设置 › 存储 › 打开缓存文件夹),这个作者的文件夹已经不在,`bilibili`/`douyin` 文件夹还在;② 把鼠标停在图标栏“订阅”上:有订阅在直播时提示“订阅 · 有订阅正在直播”;③ 订阅列表里新加的哔哩哔哩订阅:打开一次它们的用户页(或等下次检查更新)后显示真实头像,重启 TRACE Dev 后仍在;从用户页新订阅一个人,头像立刻是真实头像;④ 下次 Agent 打包时让 TRACE Dev 开着(在托盘里),安装后它自己重新出现在托盘,“设置 › 更新”里是新版本并多出一条“本机打包安装”更新记录;⑤ 如果遇到闪退,数据目录 `logs` 里会多一个 `crash-<时间>.log`,回复时告诉 Agent 即可(不用打开);⑥ **设置“更新”页**:进入“设置”,左侧分类“关于”上方有“更新”(点“关于”里的说明行也能切到“更新”);开发版显示当前运行版本、提交、构建时间与“开发版不会自己联网检查;Agent 打包后会自动安装,正在运行的 TRACE Dev 会先退出、装完再打开”(不显示“立即检查”按钮和自动更新开关),同时显示本机已安装的开发版版本(若本机刚装了更新的包尚未重启,提示重启生效)、检查记录与最近更新记录(含从旧版本升到新版本及“本机打包安装”);⑦ **多路直播同时录制与“任务 › 录制异常”**:“设置 › 订阅与直播”不再有“同时录制数”上限,找 2~3 个正在直播的直播间可同时开始录制而不排队等待;录制中若出现断流重连、因网速跟不上丢失片段、速度持续 30 秒低于媒体码率、磁盘空间不足或收尾转换失败,录制行显示橙色“⚠ N 处异常”,点开或切到任务侧栏第 4 项“录制异常”(最近 7 天含进行中有异常的录制场数大于 0 时显示场数,0 场不显示数字)可按场查看时间、异常类型与说明(丢失片段含估算秒数),点进行中的场次跳到“直播录制”,点已结束的场次直接打开媒体库纯离线详情(不发站点请求、不弹系统通知);⑧ **订阅详情“内容 / 账号”标签**:进入任一订阅详情,默认停在“内容”标签,按发布时间倒序列出该订阅关联的全部哔哩哔哩与抖音账号已缓存的动态、视频、作品和直播录像(样式与主页一致,断网也能直接看、零站点请求;还没有缓存时显示“还没有缓存这个订阅的内容”并提示点右上角“⋯ → 检查更新”);切到“账号”标签,每个关联账号一行直接显示直播状态、“录制 / 停止录制”按钮与“⋯”菜单(打开主页、在浏览器中观看、用作头像、解除关联、刷新直播状态),下方仍可粘贴链接关联新账号,不再有单独的“直播”标签或重复的已录列表;⑨ **缓存规则批量“选择订阅…”**:进入“设置 › 缓存规则”,点开一条自定义规则,下方显示“使用这条规则的订阅(N)”和“选择订阅…”按钮;点“选择订阅…”弹出对话框,可按名称搜索、“全选 / 全不选”或逐个勾选订阅(每行带本机头像和“当前:<原规则名>”),把原先用这条规则的某个订阅取消勾选并新勾几个其他订阅,点“应用到 N 个订阅”:勾选的订阅一次切换到该规则,取消勾选的订阅回到“默认”规则。
-32. 第四轮反馈的复查(DEC-053,B 实现;DEC-054、DEC-055 与录制修复,A 处理;本机 TRACE Dev 已更新至 `0.1.2-dev.202611160535`,[阶段报告 §14、§15](docs/delivery/stage-report.md#b-feedback-4)):① 在主页“全部”往下翻到中间某条停一下,切到“B 站”再翻到另一处,然后从托盘“退出”再打开:“全部”回到刚才那条(连同露出的那一截),切到“B 站”回到它自己的位置,“抖音”第一次从最新处开始;往上滑能看到之后缓存的内容,看着的那条不跳;② 主页侧栏在“全部动态”和站点筛选下面直接是订阅列表,没有“正在直播”“有更新”之类的标题,也没有状态文字;正在直播的排最前、头像一圈橙色,其后是头像右下角带蓝色小圆点的未读订阅,再是已读的;③ 点一个带圆点的订阅:圆点马上消失、这一行不挪;去别的页面再回到主页,它移到已读那一组;④ 切到“抖音”时列表只剩有抖音内容的订阅;⑤ 把窗口拉窄到没有侧栏:时间线上方是一排圆形头像,最前面是“全部动态”,直播圈与圆点同上;⑥ A 修的几项:长时间的哔哩哔哩直播录制结束后录像正常转成 MP4、不再出现上亿段“分片丢失”;打开没有直播间的 UP 主空间页不再提示“解析接口数据字段失败”;设置“缓存规则”里“默认”只读、全关;媒体库“刷新”列出在资源管理器里删掉的文件
-33. 第五轮反馈的复查(DEC-056、DEC-057,A 实现;本机 TRACE Dev 已更新至 `0.1.2-dev.202611161316`,[阶段报告 §16](docs/delivery/stage-report.md#feedback-5)):① **任务页**:侧栏只有一项“缓存队列(N)”,点开是队列卡片,点卡片展开,“最近缓存的内容”有封面;结束的队列可以“移除”或“清除已结束”;“直播录制”里最近结束的录制可以“移除”或“全部移除”;“录制异常”里结束的场次可以“删除记录”(录像仍在媒体库);② **转发**:缓存一条转发了别人视频的动态,确认动态和视频都在转发者文件夹的 `forwards\` 下、没有新建原作者的文件夹;媒体库“转发”里能看到它们,“图片”“视频”里没有;③ **合作视频**:从灰泽满Hazel 的订阅或用户页缓存一个合作视频,确认存到她的 `videos\` 下。已缓存的 BV1DDpE68E56 不会自动搬家:想移过去就在媒体库删除它,再从灰泽满Hazel 那里重新缓存;④ 图标栏第一个按钮紧挨着顶部的“T”;⑤ 主页点已订阅作者的头像进入订阅,没订阅的进用户页;⑥ 主页“全部 / B 站 / 抖音”来回切换,回到看过的筛选时图片立即出现;⑦ 订阅侧栏“全部账号”:按站点列出账号与所属订阅,点一行进入订阅;⑧ 在 TRACE Dev 里打开你说的那位私密抖音用户(`douyin.com/user/MS4wLjABAAAA66TI…`):如果你登录的抖音账号在网页上能看到作品,这里也应列出作品,底部一行“私密账号:当前登录的抖音账号可以看到这些作品”;仍提示看不到时告诉我(A 没有对这个账号发请求)。**⑧ 你 2026-11-16 已确认:作品可以列出。** ⑨ **加入订阅**(DEC-058,`0.1.2-dev.202611161744`):在没订阅的用户页点“订阅”,弹窗里可以搜索并加入现有订阅,或新建订阅;“我的”里关注的人“⋯ → 加入订阅”和订阅页“添加订阅”预览账号后的“加入现有订阅…”也会打开它。
+31. 第二轮反馈的复查(DEC-051,A 处理 4 条 + B 实现 4 条;本机 TRACE Dev 已更新至 `0.1.2-dev.202611151241`,[阶段报告 §11、§12](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-report.md#a-review-feedback-2);如未在桌面或托盘运行,先从开始菜单或桌面打开一次):① 在媒体库删掉某个作者的全部内容,打开缓存文件夹(设置 › 存储 › 打开缓存文件夹),这个作者的文件夹已经不在,`bilibili`/`douyin` 文件夹还在;② 把鼠标停在图标栏“订阅”上:有订阅在直播时提示“订阅 · 有订阅正在直播”;③ 订阅列表里新加的哔哩哔哩订阅:打开一次它们的用户页(或等下次检查更新)后显示真实头像,重启 TRACE Dev 后仍在;从用户页新订阅一个人,头像立刻是真实头像;④ 下次 Agent 打包时让 TRACE Dev 开着(在托盘里),安装后它自己重新出现在托盘,“设置 › 更新”里是新版本并多出一条“本机打包安装”更新记录;⑤ 如果遇到闪退,数据目录 `logs` 里会多一个 `crash-<时间>.log`,回复时告诉 Agent 即可(不用打开);⑥ **设置“更新”页**:进入“设置”,左侧分类“关于”上方有“更新”(点“关于”里的说明行也能切到“更新”);开发版显示当前运行版本、提交、构建时间与“开发版不会自己联网检查;Agent 打包后会自动安装,正在运行的 TRACE Dev 会先退出、装完再打开”(不显示“立即检查”按钮和自动更新开关),同时显示本机已安装的开发版版本(若本机刚装了更新的包尚未重启,提示重启生效)、检查记录与最近更新记录(含从旧版本升到新版本及“本机打包安装”);⑦ **多路直播同时录制与“任务 › 录制异常”**:“设置 › 订阅与直播”不再有“同时录制数”上限,找 2~3 个正在直播的直播间可同时开始录制而不排队等待;录制中若出现断流重连、因网速跟不上丢失片段、速度持续 30 秒低于媒体码率、磁盘空间不足或收尾转换失败,录制行显示橙色“⚠ N 处异常”,点开或切到任务侧栏第 4 项“录制异常”(最近 7 天含进行中有异常的录制场数大于 0 时显示场数,0 场不显示数字)可按场查看时间、异常类型与说明(丢失片段含估算秒数),点进行中的场次跳到“直播录制”,点已结束的场次直接打开媒体库纯离线详情(不发站点请求、不弹系统通知);⑧ **订阅详情“内容 / 账号”标签**:进入任一订阅详情,默认停在“内容”标签,按发布时间倒序列出该订阅关联的全部哔哩哔哩与抖音账号已缓存的动态、视频、作品和直播录像(样式与主页一致,断网也能直接看、零站点请求;还没有缓存时显示“还没有缓存这个订阅的内容”并提示点右上角“⋯ → 检查更新”);切到“账号”标签,每个关联账号一行直接显示直播状态、“录制 / 停止录制”按钮与“⋯”菜单(打开主页、在浏览器中观看、用作头像、解除关联、刷新直播状态),下方仍可粘贴链接关联新账号,不再有单独的“直播”标签或重复的已录列表;⑨ **缓存规则批量“选择订阅…”**:进入“设置 › 缓存规则”,点开一条自定义规则,下方显示“使用这条规则的订阅(N)”和“选择订阅…”按钮;点“选择订阅…”弹出对话框,可按名称搜索、“全选 / 全不选”或逐个勾选订阅(每行带本机头像和“当前:<原规则名>”),把原先用这条规则的某个订阅取消勾选并新勾几个其他订阅,点“应用到 N 个订阅”:勾选的订阅一次切换到该规则,取消勾选的订阅回到“默认”规则。
+32. 第四轮反馈的复查(DEC-053,B 实现;DEC-054、DEC-055 与录制修复,A 处理;本机 TRACE Dev 已更新至 `0.1.2-dev.202611160535`,[阶段报告 §14、§15](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-report.md#b-feedback-4)):① 在主页“全部”往下翻到中间某条停一下,切到“B 站”再翻到另一处,然后从托盘“退出”再打开:“全部”回到刚才那条(连同露出的那一截),切到“B 站”回到它自己的位置,“抖音”第一次从最新处开始;往上滑能看到之后缓存的内容,看着的那条不跳;② 主页侧栏在“全部动态”和站点筛选下面直接是订阅列表,没有“正在直播”“有更新”之类的标题,也没有状态文字;正在直播的排最前、头像一圈橙色,其后是头像右下角带蓝色小圆点的未读订阅,再是已读的;③ 点一个带圆点的订阅:圆点马上消失、这一行不挪;去别的页面再回到主页,它移到已读那一组;④ 切到“抖音”时列表只剩有抖音内容的订阅;⑤ 把窗口拉窄到没有侧栏:时间线上方是一排圆形头像,最前面是“全部动态”,直播圈与圆点同上;⑥ A 修的几项:长时间的哔哩哔哩直播录制结束后录像正常转成 MP4、不再出现上亿段“分片丢失”;打开没有直播间的 UP 主空间页不再提示“解析接口数据字段失败”;设置“缓存规则”里“默认”只读、全关;媒体库“刷新”列出在资源管理器里删掉的文件
+33. 第五轮反馈的复查(DEC-056、DEC-057,A 实现;本机 TRACE Dev 已更新至 `0.1.2-dev.202611161316`,[阶段报告 §16](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-report.md#feedback-5)):① **任务页**:侧栏只有一项“缓存队列(N)”,点开是队列卡片,点卡片展开,“最近缓存的内容”有封面;结束的队列可以“移除”或“清除已结束”;“直播录制”里最近结束的录制可以“移除”或“全部移除”;“录制异常”里结束的场次可以“删除记录”(录像仍在媒体库);② **转发**:缓存一条转发了别人视频的动态,确认动态和视频都在转发者文件夹的 `forwards\` 下、没有新建原作者的文件夹;媒体库“转发”里能看到它们,“图片”“视频”里没有;③ **合作视频**:从灰泽满Hazel 的订阅或用户页缓存一个合作视频,确认存到她的 `videos\` 下。已缓存的 BV1DDpE68E56 不会自动搬家:想移过去就在媒体库删除它,再从灰泽满Hazel 那里重新缓存;④ 图标栏第一个按钮紧挨着顶部的“T”;⑤ 主页点已订阅作者的头像进入订阅,没订阅的进用户页;⑥ 主页“全部 / B 站 / 抖音”来回切换,回到看过的筛选时图片立即出现;⑦ 订阅侧栏“全部账号”:按站点列出账号与所属订阅,点一行进入订阅;⑧ 在 TRACE Dev 里打开你说的那位私密抖音用户(`douyin.com/user/MS4wLjABAAAA66TI…`):如果你登录的抖音账号在网页上能看到作品,这里也应列出作品,底部一行“私密账号:当前登录的抖音账号可以看到这些作品”;仍提示看不到时告诉我(A 没有对这个账号发请求)。**⑧ 你 2026-11-16 已确认:作品可以列出。** ⑨ **加入订阅**(DEC-058,`0.1.2-dev.202611161744`):在没订阅的用户页点“订阅”,弹窗里可以搜索并加入现有订阅,或新建订阅;“我的”里关注的人“⋯ → 加入订阅”和订阅页“添加订阅”预览账号后的“加入现有订阅…”也会打开它。
34. 2026-11-18 反馈的复查([DEC-059](docs/decisions.md#dec-059),A 实现):① **检查计划**:任务页侧栏最后一项“检查计划”,每个订阅账号有上次检查更新的时间与结果、右侧“下次 …”;开了开播录制的订阅还有“开播检查:上次 … · 约每 N 分钟”;② **新加的抖音账号**:“一只约约-v-”在一轮定时检查后显示“更新检查:上次 … · 正常”,开播检查在几轮内查到它;开播时自动开始录制(约 3 分钟内,见 Q-020);③ **录制异常**:一场录像的异常只出现在这一场的卡片上,不再多出一张没有“查看录像详情”的卡片;④ **换段**:长时间录制换段时不再出现十几段的“分片丢失”;⑤ **不再闪退**:在主页点开一个订阅的信息流后,点帖子的头像打开订阅,不再闪退。
35. 2026-11-18 第二次反馈的复查([DEC-060](docs/decisions.md#dec-060),A 实现):① **视频下载**:任务页里失败的 BV1tw411t7Pu“欢迎回家,哥哥”点重试,P01.mp4 完成(站点标称 129 秒,实际 126.5 秒,现在算正常);② **手动刷新开播即录**:开了开播录制的订阅里有账号在播时,在账号页或订阅详情刷新开播状态,几秒内任务页“直播录制”出现这一场(手动停过的这一场不会再自动开始);③ **手动检查**:任务页“检查计划”右上“检查全部”,检查时显示“正在检查 x / y”与“取消”;某个账号右侧点“检查”,这一行显示“检查中…”,完成后“更新检查:上次 今天 …”更新;④ **开播检查规则**:设置 › 订阅与直播“开播检查间隔”下一行写着“现在:B 站每轮查全部账号;抖音 17 个账号,每个约每 3 分钟查一次”,下面一段“开播检查规则”;任务页“检查计划”顶部有摘要,开了开播录制的抖音账号显示“开播检查:上次 … · 约每 3 分钟”;⑤ **抖音开播检查与更新检查不再互相挤占**:录制正常时,抖音账号的“更新检查:上次 …”按定时检查的间隔更新,不再出现“本小时额度用完,已顺延”。
36. 2026-11-19 反馈的复查([DEC-061](docs/decisions.md#dec-061),A 实现):① **合作视频**:媒体库作者列表里南梦tammy 下能看到 BV1Ryui6nE4G,TMT 官方旗舰店不再因为这条出现在作者列表;主页按南梦tammy 的订阅筛选、她的订阅“内容”里都有这条;从她的用户页点开一个合作视频,在视频页点“缓存视频”,存到她的文件夹。② **作品数**:订阅 › 全部账号、订阅详情 › 账号,每个账号写“作品 N · 已缓存 M · <时间> 统计”;没打开过主页的写“已缓存 M · 作品总数在打开主页后统计”,打开一次她的主页再回来就有总数。③ **全部缓存**:设置 › 缓存规则 新建或编辑一条规则,打开“全部缓存”并用到一个订阅上;约 3~10 分钟后任务页“缓存队列”出现“<账号> · 定期全部缓存 · 投稿”(抖音是“作品”),已缓存的跳过,没缓存的慢慢缓存;同一站点一次只有一个;同一账号 7 天内不再重开。
+37. 2026-11-20 反馈的复查([DEC-063](docs/decisions.md#dec-063) 与三处修复,B 实现;本机 TRACE Dev 已更新至 `0.1.3-dev.202611201130`,[阶段报告 §7](docs/delivery/stage-report.md#feedback-1)):① **抖音共创作品**:已经缓存在“悠长假期”下的 `7229580276903447820` 和 `7229197081628396832` 不会自动搬动;想放到猫九酱下,在媒体库删掉这两条,再到猫九酱的用户页对它们点“缓存”(或重新对猫九酱点“全部缓存”):文件夹在 `文档\trace-dev\douyin\cfedc7b61afa\works\` 下,媒体库作者列表里它们算在猫九酱下,打开后作者仍显示悠长假期。② **配乐**:在任务页对“部分完成”的抖音图文点“重试”:原来“配乐无可用地址”的应该大多能补上配乐;还缺的,在条目的缺失原因里看具体原因(原来写“blocked”的,现在会写出被拦截的原因或域名),把原因发给我。③ **主页订阅名**:主页每条帖子的账号名后面有一行蓝色小字是它的订阅名(订阅名与账号名相同时不显示),点它打开这个订阅。④ **定时检查不再卡住**:开了自动录制的抖音账号开播后,订阅检查仍每小时完成一次(日志里有“subscription check finished”),退出 TRACE Dev 不再要等几分钟。⑤ **全部缓存补不完整的条目**:对一个有“部分完成”作品的账号(比如有缺配乐图文的抖音账号)再点一次“全部缓存”:队列跳过完整的作品,把部分完成的那几条重新缓存(只补缺的部分),任务页这个队列的“已缓存”计数包括这几条;用户页的“已缓存数”包含为这个账号缓存的共创作品。
+
结果直接回复编号和步骤,例如“H-001 全部通过”或“H-001 第 9 步:断网恢复后一直显示连接中断”。
+
+### H-003:远程版在 VPS 与 Google Drive 上的实机检查(not-run,B 交付后)
+
+| 项 | 内容 |
+| --- | --- |
+| 适用 | `dist/trace-server/` 里的包(`trace-server-<版本>-linux-amd64.tar.gz` 或 `arm64`,版本与 SHA-256 见阶段报告)与本机 TRACE Dev(同一提交) |
+| 准备 | 一台 Debian 12 或 Ubuntu 22.04 以上的 VPS(能 SSH、有 sudo);VPS 上装好 `rclone`;云服务商安全组放行 TCP 47380(或你选的端口);本地两个站点都已登录,至少一个订阅选了带“定时检查”“自动缓存”的规则 |
+| 步骤与预期 | 部署命令都在包里的 `README.md`(同 `cmd/trace-server/deploy/README.md`),按默认布局:① 把包传到 VPS,`sha256sum -c SHA256SUMS --ignore-missing` 通过;建用户 `trace`、解压到 `/opt/trace`,`/opt/trace/trace-server version` 显示版本(README 第 1 节);② `sudo -u trace /opt/trace/trace-server init --data /var/lib/trace/data --export /srv/trace/export --public-address `:打印连接码、证书指纹与 rclone 排除规则(第 2 节);`ufw` 放行端口(第 3 节);③ 用 `trace` 用户 `rclone config` 配 Google Drive(建议自己的 client_id,配置写到 `/var/lib/trace/rclone/rclone.conf`),改 `server.json` 的 `upload` 为 `rclone` 与 `gdrive:trace`,`upload-test` 显示“上传测试通过”(第 4 节);④ 装 `trace-server.service` 并 `systemctl enable --now trace-server`,`systemctl status` 为 running(第 5 节);⑤ 本地“设置 › 远程”粘贴连接码 → 连接:显示远程版本、运行时长、导出目录空间、两个站点“未登录”;⑥ 点“同步订阅”:显示“已同步”与远程的订阅数、账号数;每个站点点“同步 Cookie”:显示“有效 · 昵称”;⑦ 等一轮检查(规则的检查间隔):远程“检查与缓存”里账号有上次检查时间,第一次只建立起点、不缓存旧内容;⑧ 之后有账号发新内容或开播:“检查与缓存”出现缓存或录制,完成后“上传与空间”的“今天已传”增加,VPS 的 `/srv/trace/export` 里这条被删掉,网盘 `trace/` 下出现条目文件夹与 `item.json`;⑨ 把网盘上的文件夹下载到本地,媒体库“⋯ → 导入…”填这个文件夹 → 扫描:预览分类正确,开始导入后在任务页“导入导出”看到进度与摘要,条目在媒体库与主页能播放;直播只传了一部分时,等传完再下载、再导入一次,这一条变成“可补充”并补齐;⑩ 本地在“设置 › 账号”重新扫码登录哔哩哔哩:远程的登录行“Cookie 同步于”时间更新,没有“Cookie 待同步”;⑪ `sudo systemctl restart trace-server`:本地刷新后运行时长归零,订阅与登录都还在;`journalctl -u trace-server` 与 `/var/lib/trace/data/logs/` 里没有 Cookie、令牌和签名地址 |
+| 状态 | not-run |
+
### H-002:安装与更新的实机检查(not-run)
@@ -542,6 +356,7 @@ M3 按下面的默认值实现([M3 计划](https://github.com/chialecode/trace
| --- | --- | --- |
| `%LOCALAPPDATA%\TRACE\WebView2`、`%APPDATA%\trace.exe\EBWebView` | 早期 WebView 原型和打包测试运行时留下的浏览器配置(2026-11-05),没有你的登录凭证和缓存;原生界面(DEC-032)不再使用 WebView2 | 可以直接删除这两个文件夹 |
| `%LOCALAPPDATA%\trace-ptest`(以及以后的 `trace-ptest.previous`) | 安装与更新演练用的测试身份 TRACE PTest 的数据(没有登录、没有缓存);演练最后卸载程序、按设计保留数据,下次演练会把它移到 `.previous` | 可以随时删除;不删也只占几百 KB |
+| 仓库里 `artifacts/backup-20261116/`、`artifacts/repair-20261115/`(Git 忽略) | 之前修复时备份的你的真实数据:一份 `subscriptions.json`(2026-11-16)与一份 `library.db` 和 `item.json`(2026-11-15),共约 350 KB;不是工具生成物,Agent 不删 | 确认现在的订阅与媒体库都正常后可以删除;想留着就移到仓库外 |
| 被删除的 Cookie 对应的网站会话 | 删除文件不会让网站上的登录失效 | 在抖音、微博、小红书、Instagram、X、TikTok 上退出当时测试用的会话 |
@@ -554,9 +369,17 @@ M3 按下面的默认值实现([M3 计划](https://github.com/chialecode/trace
| 日期 | 事项 | 结果 |
| --- | --- | --- |
+| 2026-11-19 | ACT-021:推送 M4、创建 PR 并合并 | 你授权后 A 推送 `codex/m4-account`,PR #8 squash 合并为 `main @ a613735`;合并后的三轮反馈经 PR #10 合并为 `main @ 8327803`;不含标签与发布 |
+| 2026-11-14 | ACT-020:“我的”接口的真实站点只读检查 | 运行 1 次(API 15/22,回执 `artifacts/site-check/act020.json` 脱敏干净):哔哩哔哩关注、收藏夹、稍后再看、历史通过;抖音关注与“全部收藏”通过,“喜欢”对非浏览器请求固定回空,收藏夹与观看历史没有真实证据(LOOP-014) |
+| 2026-11-13 | ACT-019:哔哩哔哩实况动态的缓存与片段格式 | B 运行 1 次通过:解析、缓存与片段格式都没问题,片段是 `moov` 在前的 AVC MP4 |
+| 2026-11-13 | ACT-015~018:按正式流程缓存指定的抖音视频(原画优先) | A 各运行 1 次:015 发现代理拨号被拒(已修);016 缓存成功但不是原画;017 查明服务层没传原画地址(已修);018 通过,缓存为原画 HEVC+AAC `2160×3840` |
+| 2026-11-13 | ACT-010~012、014:抖音的真实站点有界检查与直播 FLV 短录 | 010 通过 V-01~V-05 与 V-08;011 回答离线换号;012 查明 FLV 第一跳 `302` 到白名单外的 HTTPS 域名(已修跳转规则);014 短录一次通过(原画 AVC)。账本与脱敏回执在 `.local/site-check/`、`artifacts/site-check/` |
+| 2026-11-08 | ACT-006、ACT-007:M1 新实现的真实站点小额复核 | 006 运行 1 次未通过、额度用完;没完成的缓存与直播两步由 007 复跑通过 |
+| 2026-11-12 | ACT-009:打开每周自动发布正式版 | A 设仓库变量 `TRACE_RELEASE_PUBLISH=1` 并手动运行一次 `release.yml`(publish),检查、构建、发布全部通过;之后每周一按有无新合并自动发布 |
+| 2026-11-04 | ACT-002、ACT-003:哔哩哔哩真实站点有界检查、动态列表与缓存 | 002 第二轮全部通过(第一轮遇 `-412` 与 Cookie 失效停止);003 全部通过,动态列表额度用完 |
| 2026-11-14 | ACT-013:推送 M3、创建 PR 并合并 | 你授权后 A 推送 `codex/m3-douyin`,PR #7 检查通过后 squash 合并为 `main @ f080483`,并清理了分支;不含标签与发布 |
| 2026-11-12 | Q-013:抖音视频与直播的需求范围 | 你回复“按推荐”:粘贴 Cookie 登录、每站点一个登录账号、按站点强制登录、视频图文缓存与订阅、直播 FLV 录制、站点小字标签;关注导入等留到以后(DEC-043);测试 Cookie 见 ACT-010 |
-| 2026-11-09 | [ACT-001](#act-001):推送并合并 M1 | PR #1 的 CI 修复一次后通过,squash 合并为 `main @ 29c2678`;M2 分支 `codex/m2-install-update` 从这里开始 |
+| 2026-11-09 | ACT-001:推送并合并 M1 | PR #1 的 CI 修复一次后通过,squash 合并为 `main @ 29c2678`;M2 分支 `codex/m2-install-update` 从这里开始 |
| 2026-11-09 | 实机反馈:共用缓存规则与主页(DEC-040) | 共用缓存规则、订阅详情精简为规则按钮与“直播”“账号”;设置页去掉嵌套框;主页掉帧由 A 修复,不再恢复位置或标未读;看图与播放改为浮动面板、视频自动播放;帖子图片按原比例、视频封面在左;实况照片标记并缓存动态片段,在线缩略图失败后可重试(根因未用真实数据确认)([M1 报告](https://github.com/chialecode/trace/blob/29c2678/docs/delivery/stage-report.md#feedback-5));截图断言通过,开发包已重新打包并通过冒烟 |
| 2026-11-08 | 实机反馈:界面改版(DEC-039),Q-010 浮动侧栏 | 拖动进度条卡顿由 A 修复;媒体库去掉状态圆点;改为图标栏 + 上下文侧栏 + 页面、Inter 字体、蓝色强调色(绿色预览见 Q-011)、直播橙色;Q-010 浮动侧栏不再采用([M1 报告](https://github.com/chialecode/trace/blob/29c2678/docs/delivery/stage-report.md#feedback-4));截图断言通过,开发包已重新打包并通过冒烟 |
| 2026-11-08 | 实机反馈:弹出菜单与少按钮(DEC-038)、A 集中复核、清理 | 点开即跳转、列表显示不全、“⋯”浮动菜单与去掉零散按钮、设置侧边栏由 A 修复;B 的界面返工与失败边界经 A 复核通过([M1 报告](https://github.com/chialecode/trace/blob/29c2678/docs/delivery/stage-report.md#a-review-rev4));删除 11 个无用函数、临时文件、全部旧打包与 `.local/` 旧记录(见[本机文件](#local-files));截图断言通过,开发包已重新打包并通过冒烟 |
@@ -564,14 +387,14 @@ M3 按下面的默认值实现([M3 计划](https://github.com/chialecode/trace
| 2026-11-08 | 阶段命名(DEC-035、DEC-036) | 人读阶段与编号用大写、机器标识中的阶段部分用小写;阶段参数兼容大小写并规范化小写,阶段编号与 PR 序号独立 |
| 2026-11-08 | 实机反馈:去掉已看标记、头像网格订阅(DEC-033)与 ACT-006/007 | A 修复播放行距、直播多码率等问题并完成 ACT-007 真实站点复核(视频缓存与直播录制通过);B 完成界面返工与补充复核;A 集中复核通过,开发包换成最新 |
| 2026-11-07 | 全 Go 原生界面重写(DEC-032)与远端历史清理 | 你决定停止 WebView 返工,改用 `github.com/egoist/mygo/ui` 原生界面重写 M1,持续同步 MyGo 最新版(`v0.8.1`),并保留后端服务层边界以便未来支持远程 VPS 无头录制 + Web 配置;远端 `origin/main` 已按你的指示重置为只留第一个提交 `b208ad6` |
-| 2026-11-07 | ACT-005:订阅、续期检查、弹幕字幕与直播的真实站点检查 | 全部通过,脱敏回执见 `artifacts/site-check/act005.json`(见 [ACT-005](#act-005)) |
+| 2026-11-07 | ACT-005:订阅、续期检查、弹幕字幕与直播的真实站点检查 | 全部通过,额度已记账 |
| 2026-11-07 | Q-002:数据保存在哪里 | 你决定:按用户安装到 `%LOCALAPPDATA%\Programs\trace`(开发版 `trace-dev`),数据在 `%LOCALAPPDATA%\trace`(开发版 `trace-dev`),缓存默认在“文档\trace”(开发版 `trace-dev`)、设置里可改;不用 `%APPDATA%` 和 `~\.trace`(DEC-029) |
| 2026-11-07 | Q-007:粘贴 Cookie 登录要不要自动续期 | 你决定:不续期,设置页说明原因;过期后重新粘贴,或改用扫码登录(DEC-031) |
| 2026-11-07 | Q-006 第 1、2 条、关闭到托盘、ACT-005 | 一个账号只属于一个订阅、删除订阅不删缓存也不取关(DEC-031);关闭窗口最小化到托盘并释放界面内存(DEC-030);授权 ACT-005,直播录制用你指定的直播间 |
| 2026-11-07 | M1 追加需求与文档结构 | 产物只留最新(DEC-025);以“订阅”为入口(DEC-026);M1 追加订阅、检查更新、自动缓存、关注导入、登录续期、弹幕字幕、逐文件进度、直播(DEC-027);文档按参考的开发治理分层重组、仍保持精简(DEC-028,替代 DEC-015) |
-| 2026-11-05 | ACT-004:M1 的真实站点有界检查 | 全部通过,动态列表与 `nav` 额度已用完(见 [ACT-004](#act-004)) |
+| 2026-11-05 | ACT-004:M1 的真实站点有界检查 | 全部通过,动态列表与 `nav` 额度已用完 |
| 2026-11-05 | 界面与缓存方向 | 设置页带分类栏(DEC-019);Q-001 强调色定为粉色和蓝色(DEC-021);主页、解析、媒体库、任务分开入口(DEC-022);主页是已缓存内容的信息流(DEC-023);Q-004 定为最高画质与音质、多 P 全部,并有升级提醒和红绿黄圆点(DEC-024) |
-| 2026-11-04 | ACT-003:动态列表与缓存的真实站点检查 | 全部通过,动态列表额度已用完(见 [ACT-003](#act-003)) |
+| 2026-11-04 | ACT-003:动态列表与缓存的真实站点检查 | 全部通过,动态列表额度已用完 |
| 2026-11-04 | M1 范围 | 只做哔哩哔哩,必须登录,按动态手动缓存并提供媒体库(DEC-018);代码按职责分包(DEC-020) |
-| 2026-11-04 | ACT-002:哔哩哔哩真实站点有界检查 | 第二轮全部通过(见 [ACT-002](#act-002)) |
+| 2026-11-04 | ACT-002:哔哩哔哩真实站点有界检查 | 第二轮全部通过 |
| 2026-11-04 | 界面方向与治理 | 类似 X 的社交网络布局(DEC-014);治理保持精简(DEC-015) |
diff --git a/cmd/trace-server/deploy/README.md b/cmd/trace-server/deploy/README.md
new file mode 100644
index 0000000..163ce41
--- /dev/null
+++ b/cmd/trace-server/deploy/README.md
@@ -0,0 +1,124 @@
+# TRACE 远程版部署说明
+
+`trace-server` 是 TRACE 的远程版,放在 Linux VPS(Debian 12、Ubuntu 22.04 一类,amd64 或 arm64)上运行。它只做四件事:按本地同步过去的订阅检查**启动之后**的新内容、按规则缓存、按规则录制直播、用 rclone 把完成的文件上传到网盘(如 Google Drive)。没有界面,本地 TRACE 在“设置 › 远程”查看状态、同步订阅与 Cookie。
+
+包里有:`trace-server`(程序)、`trace-server.service`(systemd 示例)、本说明、`THIRD-PARTY-NOTICES.txt`、`VERSION.txt`。下面的命令按默认布局写:
+
+| 用途 | 路径 |
+| --- | --- |
+| 程序 | `/opt/trace/trace-server` |
+| 数据目录(设置、证书、凭证、数据库、日志) | `/var/lib/trace/data` |
+| 导出目录(缓存的文件,布局与本地媒体库相同) | `/srv/trace/export` |
+| rclone 配置 | `/var/lib/trace/rclone/rclone.conf` |
+
+## 1. 安装程序与专用用户
+
+```sh
+sudo useradd --system --home-dir /var/lib/trace --shell /usr/sbin/nologin trace
+sudo mkdir -p /opt/trace /var/lib/trace/rclone /srv/trace/export
+sudo tar -xzf trace-server-*-linux-amd64.tar.gz -C /opt/trace --strip-components=1
+sudo chown -R trace:trace /var/lib/trace /srv/trace
+sudo chmod 700 /var/lib/trace /srv/trace/export
+/opt/trace/trace-server version
+```
+
+arm64 的机器换成 `linux-arm64` 的包。解压前可以用包旁边的 `SHA256SUMS` 核对:`sha256sum -c SHA256SUMS --ignore-missing`。
+
+## 2. 初始化,拿到连接码
+
+用 `trace` 用户运行,数据目录才属于它:
+
+```sh
+sudo -u trace /opt/trace/trace-server init \
+ --data /var/lib/trace/data --export /srv/trace/export \
+ --public-address --name 东京VPS
+```
+
+- 打印的**连接码**只显示这一次(令牌只存哈希)。复制到本地 TRACE 的“设置 › 远程”。
+- `--public-address` 写进连接码;不填时用本机第一个非回环地址,VPS 在 NAT 后面时那不是公网地址。默认监听 `:47380`,可用 `--listen` 改。
+- 证书是自签名的,本地按连接码里的 SHA-256 指纹校验,不需要域名和 CA 证书。重新 `init` 会换证书,本地要粘贴新的连接码。
+- 令牌丢了或泄露了:`sudo -u trace /opt/trace/trace-server token --data /var/lib/trace/data` 换新令牌并打印新连接码,旧令牌立即失效。
+
+## 3. 防火墙
+
+只需要放行一个 TCP 端口(默认 47380)。能固定本地出口 IP 时只放行它:
+
+```sh
+sudo ufw allow from <本地出口 IP> to any port 47380 proto tcp # 或:sudo ufw allow 47380/tcp
+```
+
+云服务商的安全组也要放行同一端口。接口要求令牌;1 分钟内失败 5 次的来源 10 分钟内都会被拒绝。
+
+## 4. 配置上传(rclone)
+
+远程自己调用 rclone 上传:条目的文件全部写完后上传,直播每收尾一段就上传该段与更新后的 `item.json`,`item.json` 总在媒体文件之后上传;rclone 确认成功后才删除 VPS 上的文件。没有配置上传时文件留在导出目录。
+
+1. 安装 rclone(官方安装脚本或发行版的包),确认 `rclone version` 可用。
+2. 配置网盘,配置文件放在服务能写的位置(rclone 会刷新令牌并写回):
+
+ ```sh
+ sudo -u trace env RCLONE_CONFIG=/var/lib/trace/rclone/rclone.conf rclone config
+ ```
+
+ Google Drive 建议用自己在 Google Cloud 控制台创建的 OAuth client_id 与 client_secret(rclone 文档的“Making your own client_id”),共用的默认 client_id 速度受限。VPS 没有浏览器时,按 rclone 的提示在有浏览器的电脑上运行它给出的 `rclone authorize` 命令,把结果粘回来。Google Drive 每个账号每天大约能上传 750 GiB,超过后远程状态显示配额错误并按退避重试。
+3. 编辑 `/var/lib/trace/data/server.json` 的 `upload` 部分:
+
+ ```json
+ "upload": {
+ "mode": "rclone",
+ "remote": "gdrive:trace",
+ "deleteAfterUpload": true
+ }
+ ```
+
+ `remote` 是 rclone 的远端路径;`rclone`(程序路径,默认在 PATH 里找)、`config`(配置文件,不填时用环境变量 `RCLONE_CONFIG`)、`extraArgs`(额外参数,如 `["--bwlimit", "8M"]`)可选。
+4. 测试一次(写入并删除一个测试文件):
+
+ ```sh
+ sudo -u trace env RCLONE_CONFIG=/var/lib/trace/rclone/rclone.conf \
+ /opt/trace/trace-server upload-test --data /var/lib/trace/data
+ ```
+
+改完 `server.json` 后重启服务才生效。
+
+**不用内置上传、自己定时运行 rclone 时**,保持 `"mode": "none"`,并且一定排除未写完的文件:
+
+```sh
+rclone move /srv/trace/export gdrive:trace --exclude "*.part" --exclude ".trace-*" --min-age 2m --delete-empty-src-dirs
+```
+
+`trace-server rclone-filter` 会打印这组规则。远程不依赖导出目录里的文件继续存在,文件被搬走不影响缓存和录制。
+
+## 5. systemd 服务
+
+```sh
+sudo cp /opt/trace/trace-server.service /etc/systemd/system/
+sudo systemctl daemon-reload
+sudo systemctl enable --now trace-server
+systemctl status trace-server
+journalctl -u trace-server -f
+```
+
+示例服务用 `trace` 用户运行,`ProtectSystem=strict` 下只有 `/var/lib/trace` 和导出目录可写。改了路径时,`ExecStart`、`ReadWritePaths` 与 `RCLONE_CONFIG` 一起改。`systemctl stop` 发 SIGTERM:远程暂停任务、给录制收尾,最多 30 秒。日志也写在 `/var/lib/trace/data/logs/`,不含 Cookie、令牌和签名地址。
+
+## 6. 连接本地 TRACE
+
+本地“设置 › 远程”粘贴连接码 → 连接 → “同步订阅”,再在每个站点点“同步 Cookie”。之后本地续期、扫码登录或粘贴登录成功时会自动推送 Cookie;远程离线时本地标“Cookie 待同步”,恢复后自动重试。远程只缓存同步之后的新内容,不续期 Cookie,Cookie 失效时状态显示“需要重新同步”。
+
+网盘上的文件下载到本地后,在本地媒体库“⋯ → 导入…”选那个文件夹,按预览确认即可;不需要停下远程。
+
+## 7. 凭证保护的边界
+
+站点 Cookie 用数据目录里的密钥(`credentials/secret.key`,`0600`)加密保存,令牌只存哈希,证书私钥 `0600`。这能防止只拷走数据库或日志就拿到 Cookie,**不能**防止拿到 VPS 的 root 或 `trace` 用户权限的人:他们能读密钥,也就能解密 Cookie。不要在别人能登录的机器上运行;不再使用时在本地“设置 › 远程”点“清除远程登录”,或删除数据目录。
+
+## 8. 升级
+
+两边需要同一协议版本,版本不同时本地显示“两边版本不同”。换包升级:
+
+```sh
+sudo systemctl stop trace-server
+sudo tar -xzf trace-server-<新版本>-linux-amd64.tar.gz -C /opt/trace --strip-components=1
+sudo systemctl start trace-server
+```
+
+数据目录保留不动。新版程序写过的数据,旧版程序会拒绝打开,不要降级。
diff --git a/cmd/trace-server/deploy/trace-server.service b/cmd/trace-server/deploy/trace-server.service
new file mode 100644
index 0000000..665d1be
--- /dev/null
+++ b/cmd/trace-server/deploy/trace-server.service
@@ -0,0 +1,36 @@
+# TRACE 远程版的 systemd 服务示例(部署步骤见同目录 README.md)。
+# 路径按 README 的默认布局:程序 /opt/trace,数据目录 /var/lib/trace/data,
+# 导出目录 /srv/trace/export,rclone 配置 /var/lib/trace/rclone/rclone.conf。
+# 改了路径时,ExecStart、ReadWritePaths 与 RCLONE_CONFIG 一起改。
+
+[Unit]
+Description=TRACE remote (trace-server)
+Wants=network-online.target
+After=network-online.target
+
+[Service]
+Type=simple
+User=trace
+Group=trace
+ExecStart=/opt/trace/trace-server run --data /var/lib/trace/data
+Environment=RCLONE_CONFIG=/var/lib/trace/rclone/rclone.conf
+Restart=on-failure
+RestartSec=10
+# SIGTERM 时暂停任务、给录制收尾,最多 30 秒。
+KillSignal=SIGTERM
+TimeoutStopSec=45
+UMask=0077
+NoNewPrivileges=true
+ProtectSystem=strict
+ProtectHome=true
+PrivateTmp=true
+PrivateDevices=true
+ProtectKernelTunables=true
+ProtectKernelModules=true
+ProtectControlGroups=true
+RestrictSUIDSGID=true
+LockPersonality=true
+ReadWritePaths=/var/lib/trace /srv/trace/export
+
+[Install]
+WantedBy=multi-user.target
diff --git a/cmd/trace-server/main.go b/cmd/trace-server/main.go
new file mode 100644
index 0000000..16799e1
--- /dev/null
+++ b/cmd/trace-server/main.go
@@ -0,0 +1,175 @@
+// Command trace-server is TRACE's headless remote for a Linux VPS
+// (docs/design/remote.md §2): it checks the subscriptions the desktop
+// syncs, caches their new content by rule, records lives and uploads the
+// finished files with rclone. It has no library, parsing or player and
+// never links the desktop UI.
+//
+// trace-server init --data --export [--listen :47380] [--public-address host[:port]] [--name ]
+// trace-server run --data
+// trace-server token --data
+// trace-server upload-test --data
+// trace-server rclone-filter
+// trace-server version
+package main
+
+import (
+ "context"
+ "flag"
+ "fmt"
+ "io"
+ "os"
+ "os/signal"
+ "syscall"
+ "time"
+
+ "github.com/chialecode/trace/internal/appdirs"
+ "github.com/chialecode/trace/internal/remoteserver"
+ "github.com/chialecode/trace/internal/upload"
+)
+
+func main() {
+ os.Exit(run(os.Args[1:], os.Stdout, os.Stderr))
+}
+
+const usage = `trace-server:TRACE 远程版
+
+用法:
+ trace-server init --data <数据目录> --export <导出目录> [--listen :47380] [--public-address 地址[:端口]] [--name 名字]
+ trace-server run --data <数据目录>
+ trace-server token --data <数据目录>
+ trace-server upload-test --data <数据目录>
+ trace-server rclone-filter
+ trace-server version
+`
+
+func run(args []string, stdout, stderr io.Writer) int {
+ if len(args) == 0 {
+ fmt.Fprint(stderr, usage)
+ return 2
+ }
+ cmd, rest := args[0], args[1:]
+ switch cmd {
+ case "version", "-v", "--version":
+ if len(rest) > 0 {
+ fmt.Fprintln(stderr, "version 不接受额外参数")
+ return 2
+ }
+ b := appdirs.BuildInfo()
+ fmt.Fprintf(stdout, "trace-server %s\ncommit %s\nbuilt %s\n", b.Version, orDash(b.Commit), orDash(b.BuildTime))
+ return 0
+ case "rclone-filter":
+ if len(rest) > 0 {
+ fmt.Fprintln(stderr, "rclone-filter 不接受额外参数")
+ return 2
+ }
+ fmt.Fprint(stdout, rcloneFilter)
+ return 0
+ case "help", "-h", "--help":
+ fmt.Fprint(stdout, usage)
+ return 0
+ case "init", "run", "token", "upload-test":
+ default:
+ fmt.Fprint(stderr, usage)
+ return 2
+ }
+ fs := flag.NewFlagSet(cmd, flag.ContinueOnError)
+ fs.SetOutput(stderr)
+ data := fs.String("data", "", "数据目录")
+ var export, listen, public, name *string
+ if cmd == "init" {
+ export = fs.String("export", "", "导出目录(init)")
+ listen = fs.String("listen", "", "监听地址(init,默认 :47380)")
+ public = fs.String("public-address", "", "写进连接码的地址(init,默认本机第一个非回环地址)")
+ name = fs.String("name", "", "名字(init,默认主机名)")
+ }
+ if err := fs.Parse(rest); err != nil {
+ return 2
+ }
+ if fs.NArg() > 0 {
+ fmt.Fprintf(stderr, "多余的参数:%s\n", fs.Arg(0))
+ return 2
+ }
+ if *data == "" {
+ fmt.Fprintln(stderr, "需要 --data <数据目录>")
+ return 2
+ }
+ switch cmd {
+ case "init":
+ res, err := remoteserver.Init(remoteserver.InitOptions{DataDir: *data, ExportDir: *export, Listen: *listen, PublicAddress: *public, Name: *name})
+ if err != nil {
+ fmt.Fprintln(stderr, "init 失败:", err)
+ return 1
+ }
+ printCode(stdout, *data, res, true)
+ return 0
+ case "token":
+ res, err := remoteserver.RotateToken(*data)
+ if err != nil {
+ fmt.Fprintln(stderr, "换令牌失败:", err)
+ return 1
+ }
+ fmt.Fprintln(stdout, "已换新令牌,旧令牌立即失效。")
+ printCode(stdout, *data, res, false)
+ return 0
+ case "upload-test":
+ cfg, err := remoteserver.LoadConfig(*data)
+ if err != nil {
+ fmt.Fprintln(stderr, err)
+ return 1
+ }
+ up, err := upload.New(upload.Options{Config: cfg.Upload, DataDir: *data})
+ if err != nil {
+ fmt.Fprintln(stderr, err)
+ return 1
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
+ defer cancel()
+ if err := up.Test(ctx); err != nil {
+ fmt.Fprintln(stderr, "上传测试失败:", err)
+ return 1
+ }
+ fmt.Fprintf(stdout, "上传测试通过:%s 可以写入并删除。\n", cfg.Upload.Remote)
+ return 0
+ case "run":
+ ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
+ defer stop()
+ err := remoteserver.Run(ctx, remoteserver.RunOptions{DataDir: *data, LogMirror: stderr, Ready: func(addr string) {
+ fmt.Fprintf(stderr, "trace-server 已启动:%s\n", addr)
+ }})
+ if err != nil {
+ fmt.Fprintln(stderr, "trace-server:", err)
+ return 1
+ }
+ return 0
+ }
+ return 2
+}
+
+func printCode(w io.Writer, dataDir string, res remoteserver.InitResult, first bool) {
+ if first {
+ fmt.Fprintf(w, "已初始化:数据目录 %s,导出目录 %s,监听 %s\n\n", dataDir, res.Config.ExportDir, res.Config.Listen)
+ }
+ fmt.Fprintln(w, "连接码(只显示这一次,请复制到本地 TRACE 的“设置 › 远程”):")
+ fmt.Fprintln(w)
+ fmt.Fprintln(w, " "+res.Code)
+ fmt.Fprintln(w)
+ fmt.Fprintf(w, "地址:%s\n证书指纹(SHA-256):%s\n", res.Conn.URL, res.Conn.Fingerprint)
+ fmt.Fprintln(w, "连接码里的地址按本机的网卡生成;VPS 的公网地址不同时,请用 --public-address 重新 init,或在本地分别填写地址、令牌与指纹。")
+ if first {
+ fmt.Fprintln(w)
+ fmt.Fprint(w, rcloneFilter)
+ }
+}
+
+const rcloneFilter = `上传时排除未写完的文件(自己定时运行 rclone 时加上):
+ --exclude "*.part" --exclude ".trace-*" --min-age 2m
+例如:
+ rclone move <导出目录> gdrive:trace --exclude "*.part" --exclude ".trace-*" --min-age 2m --delete-empty-src-dirs
+`
+
+func orDash(s string) string {
+ if s == "" {
+ return "-"
+ }
+ return s
+}
diff --git a/cmd/trace-server/main_test.go b/cmd/trace-server/main_test.go
new file mode 100644
index 0000000..88fc5cb
--- /dev/null
+++ b/cmd/trace-server/main_test.go
@@ -0,0 +1,27 @@
+package main
+
+import (
+ "bytes"
+ "strings"
+ "testing"
+)
+
+func TestCLIScopedFlagsAndExtraArgs(t *testing.T) {
+ var out, errBuf bytes.Buffer
+ if code := run([]string{"run", "--data", t.TempDir(), "--listen", ":9999"}, &out, &errBuf); code != 2 {
+ t.Fatalf("run with init-only --listen = %d, want 2 (stderr=%q)", code, errBuf.String())
+ }
+ errBuf.Reset()
+ if code := run([]string{"run", "--data", t.TempDir(), "extra"}, &out, &errBuf); code != 2 {
+ t.Fatalf("run with extra arg = %d, want 2 (stderr=%q)", code, errBuf.String())
+ }
+ errBuf.Reset()
+ if code := run([]string{"version", "extra"}, &out, &errBuf); code != 2 {
+ t.Fatalf("version with extra arg = %d, want 2 (stderr=%q)", code, errBuf.String())
+ }
+ out.Reset()
+ errBuf.Reset()
+ if code := run([]string{"version"}, &out, &errBuf); code != 0 || !strings.Contains(out.String(), "trace-server ") {
+ t.Fatalf("version = %d out=%q err=%q", code, out.String(), errBuf.String())
+ }
+}
diff --git a/docs/README.md b/docs/README.md
index b78dead..ca312cc 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -7,7 +7,7 @@
| 用户要什么 | [需求](requirements.md)(FR/NFR,状态分已实现、本阶段、待实现) |
| 先做什么、做到什么算基本可用、怎样验收 | [路线与验收](delivery/roadmap.md)(能力范围、MVP 基线、验收场景 AC) |
| 用户决定过什么 | [有效决定](decisions.md) |
-| 系统怎样工作 | 技术设计:[架构、接口与原生界面](design/architecture.md)、[数据、缓存与信息流](design/data-and-cache.md)、[订阅、检查更新与自动缓存](design/subscriptions.md)、[直播](design/live.md) |
+| 系统怎样工作 | 技术设计:[架构、接口与原生界面](design/architecture.md)、[数据、缓存与信息流](design/data-and-cache.md)、[订阅、检查更新与自动缓存](design/subscriptions.md)、[直播](design/live.md)、[远程版、上传与导入导出](design/remote.md) |
| 界面怎样做 | [界面规范](ui.md) |
| 为什么选这套技术 | [技术选型研究](research/2026-11-05-stack.md)、[媒体与存储选型](research/2026-11-05-media.md)、[订阅、弹幕与直播选型](research/2026-11-07-subscriptions-live.md)、[抖音签名与直播录制选型](research/2026-11-12-douyin.md) |
| 站点怎样请求 | [哔哩哔哩协议资料](research/bilibili.md)、[抖音协议资料](research/douyin.md)(静态调研,A 的定稿在 §11) |
diff --git a/docs/decisions.md b/docs/decisions.md
index 3af72e1..093d736 100644
--- a/docs/decisions.md
+++ b/docs/decisions.md
@@ -29,19 +29,22 @@
| DEC-014 | 界面采用类似 X、Instagram 的社交网络页面,侧边栏不做成规整的方块列表 | 用户提供 X 的截图,2026-11-04 | 只借鉴布局,不复制标识和图标;底色按用户偏好以白与灰为主,强调色见 DEC-021。[界面规范](ui.md) |
| DEC-015 | 治理保持精简(已由 [DEC-028](#dec-028) 替代) | 用户,2026-11-04 | 只有根入口、USER-ACTIONS、开发规则三份文件和产品正本;不设文档登记表、需求映射或多脚本门禁 |
| DEC-016 | 桌面应用用 Go + [MyGo](https://github.com/egoist/mygo)(系统 WebView2 显示网页前端)。理由:Go 编译快,而后端的站点逻辑需要经常修改(WebView2 模式与“锁死旧版本”已由 [DEC-032](#dec-032) 替代:改为 MyGo 原生界面 `mygo/ui`,持续同步 MyGo 最新版) | 用户,2026-11-05 | 只有 `main.go`、`internal/shell` 与 `internal/ui` 引用 MyGo。[选型研究](research/2026-11-05-stack.md) |
-| DEC-058 | **订阅一个账号时先问加到哪个订阅**:用户页的“订阅”(哔哩哔哩与抖音)、“我的”里的“加入订阅”与添加订阅里预览的账号,都打开同一个“加入订阅”对话框:可以搜索并加入现有订阅(同一个人的多个账号放在一起),或者新建一个以账号昵称命名的订阅 | 用户,2026-11-17(“添加订阅的时候弹窗,添加到现有订阅中(支持搜索),或者选择新建一个订阅”) | 补上 FR-USER-003 已经要求、此前只实现了“新建”的“加入已有订阅”。已属于别的订阅的账号仍按原来的“移到”流程处理(添加订阅对话框与订阅详情),这个对话框不移动账号。A 已实现([阶段报告 §17](delivery/stage-report.md#a-review-feedback-4-5),[界面规范](ui.md#subscribe-picker)) |
+| DEC-058 | **订阅一个账号时先问加到哪个订阅**:用户页的“订阅”(哔哩哔哩与抖音)、“我的”里的“加入订阅”与添加订阅里预览的账号,都打开同一个“加入订阅”对话框:可以搜索并加入现有订阅(同一个人的多个账号放在一起),或者新建一个以账号昵称命名的订阅 | 用户,2026-11-17(“添加订阅的时候弹窗,添加到现有订阅中(支持搜索),或者选择新建一个订阅”) | 补上 FR-USER-003 已经要求、此前只实现了“新建”的“加入已有订阅”。已属于别的订阅的账号仍按原来的“移到”流程处理(添加订阅对话框与订阅详情),这个对话框不移动账号。A 已实现([阶段报告 §17](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-report.md#a-review-feedback-4-5),[界面规范](ui.md#subscribe-picker)) |
| DEC-059 | 2026-11-18 实机反馈:① **任务页加“检查计划”**:每个订阅账号显示上次检查更新的时间与结果、下一轮定时检查预计何时查到它(每轮每个站点最多查 B 站 30 个、抖音 20 个,上次查得早的先查;退避时排到退避结束后;只手动检查、未登录、定时检查关闭分别说明),开了“开播录制”的订阅再显示上次开播检查的时间与大约间隔;② **抖音开播检查只用抖音每小时额度的一半**(60 次;已由 [DEC-060](#dec-060) ⑤ 取代):每轮只查分到的几个账号,上次查得早的先查、新加的账号最先查;另一半留给定时检查更新、自动缓存和开始录制;③ 直播换段时,上一段在后台转换,录制不停;④ 录制结束后的异常只记在这一场录像上,任务页“录制异常”不再多出一张没有录像的卡片 | 用户,2026-11-18(“新加入已有规则订阅的账号似乎没有自动录制直播,我也无法验证它有没有自动缓存更新”“在任务页面展示未来检查每个账号更新的一个计划时间点”“dev 出现直播录制异常”) | 根因:17 个抖音账号开了开播录制,每 3 分钟每个都查一次,约每小时 340 次,十分钟内用完抖音的 120 次额度,此后定时检查更新(一轮要 34 次)每轮都被推迟,新加的账号从未检查过,查到开播也拿不到开始录制的额度。代价:开播被发现变慢,17 个账号时每个约 18 分钟查一次([Q-020](../USER-ACTIONS.md#q-020))。录制异常:开发版在主页订阅信息流里点头像时闪退(列表状态在构建列表时被重置),重启期间丢了 16 段;3.3 GB 的一段在录制循环里转换约 40 秒,期间直播列表滚过,丢了 12 段;同一批异常又以“直播间状态”显示成第二张卡片。[界面 §3.6](ui.md#library)、[直播 §2、§5](design/live.md)、[订阅 §3](design/subscriptions.md#schedule) |
| DEC-060 | 2026-11-18 第二次实机反馈:① **合并后的视频时长允许差 2 秒或站点标称时长的 3%(取大的)**,原来固定 2 秒;校验失败时原因写明是缺轨、结构不对还是时长相差多少;② **查到开播就开始录制**:订阅开了“开播录制”的账号,不论是巡检、用户在账号页或订阅详情手动刷新开播状态、还是检查更新时在作品列表里看到正在开播,都按规则开始录制(手动停过的这一场除外);手动刷新算作这个账号的一次开播检查;③ **手动检查**:任务页“检查计划”顶部“检查全部”,每个账号一行右侧“检查”只查这一个账号(不论它的规则是否定时检查,未登录的站点除外);④ 设置“开播检查间隔”下写明当前实际间隔,并列出开播检查规则(任务页“检查计划”顶部有摘要);⑤ **抖音开播检查改为按间隔、限速**(取代 DEC-059 ②):每个账号按设置的间隔查,两个请求之间至少隔 6 秒,一轮最多 `间隔 / 6 秒` 个(3 分钟一轮 30 个),超过后轮流查、上次查得早的先查,每多一个账号间隔约多 6 秒;开播相关的请求不占每小时额度(额度留给检查更新与自动缓存),退避与风控停止照旧 | 用户,2026-11-18(BV1tw411t7Pu“MP4 轨道、结构或时长校验失败”;“支持手动触发检查”;“在账户页面手动刷新了直播状态后仍然不会开始录制”;“开播检查抖音为啥不按设置里的时间,我看设置里是3分钟,怎么18分钟才检查一次”) | ① 该分 P 站点标称 129 秒,下载到的视频流与音频流都是 126.5 秒(两轨相差 0.39 秒),转码后的流比标称短一点是正常的;预览片段在下载前已拒绝、流被截断会先在长度校验失败,这项校验只防合并出错。② 原来只有巡检会开始录制,手动刷新与检查更新只更新显示的状态,于是显示“直播中”却不录。④ 抖音没有按人批量查开播的接口([协议 §8.6](research/douyin.md#live)),每个账号每次一请求;17 个账号每 3 分钟各查一次要每小时 340 次,超过抖音每小时 120 次的额度,按 DEC-059 ② 只用一半,所以约 18 分钟轮一次,用户看过对照(参考的多平台录制工具每个直播间各自 30 秒一查、没有总量上限,只靠失败退避)后选了折中,并要求“订阅数量增加后每个用户的检查周期不要放得很大”([Q-020](../USER-ACTIONS.md#q-020)),于是不再给开播检查定小时预算,改为限速:17 个账号每 3 分钟各查一次约每小时 340 次,30 个账号以内间隔不变;代价是请求量随账号数增长(最多每小时 600 次,3 分钟一轮时),都带用户的抖音登录态,风控时整站退避。[数据 §4](design/data-and-cache.md)、[直播 §5](design/live.md)、[订阅 §3](design/subscriptions.md#schedule)、[界面 §3](ui.md) |
| DEC-061 | 2026-11-19 实机反馈:① **缓存规则新增“全部缓存”**:用这条规则的订阅,每个账号每 7 天检查一次全部作品(哔哩哔哩是投稿视频,抖音是全部作品),没缓存的交给 DEC-050 ① 的慢速缓存队列一条一条缓存,已缓存的直接跳过;每个站点一次只开一个这样的队列,站点上还有没结束的缓存队列(包括用户自己点的“全部缓存”)时不开新的,上次检查得早、从没检查过的账号先开;任务页的队列名写“定期全部缓存”;② **“全部账号”与订阅详情“账号”里每个账号显示作品总数与已缓存数**:作品总数是上次解析这个账号时站点给的数(打开它的主页、读它的投稿列表、全部缓存开始时),打开这两个页面不发请求;已缓存数从本机媒体库数(哔哩哔哩算这个账号的视频与为他缓存的合作视频,抖音算视频与图文);③ **为某个账号缓存的合作视频算在这个账号下**:主页与订阅“内容”的信息流按账号筛选时包括为他缓存的合作视频,媒体库作者列表把它列在这个账号下而不是投稿人下;从用户页点开视频再在视频页缓存,也按这个账号存放。直接解析视频链接缓存的仍放在投稿人(第一作者)下 | 用户,2026-11-19(“新增一个全部缓存的设置……”“订阅的全部账号页面和每个订阅的页面里的关联账号新增作品总数和已缓存总数的展示……只有解析过的时候触发”“通过 space.bilibili.com/1382015878 缓存 BV1Ryui6nE4G 的时候被放到 TMT 官方旗舰店下了”) | ③ 的根因:文件夹本来就对(`bilibili/1382015878/videos/BV1Ryui6nE4G`,`via.reason = collab`),但信息流只按投稿人筛选、媒体库作者列表只按投稿人分组,所以显示在投稿人下。数据:`updates.db` 新增表 `account_works`(作品总数、统计时间、上次全部缓存时间),`subscriptions.json` 的规则与 `rules` 新增可选字段 `fullCache`,`cache-queue.json` 的任务新增可选字段 `origin`,结构版本都不变,旧版程序忽略它们。默认值见 [Q-021](../USER-ACTIONS.md#q-021)。A 已实现([订阅 §4](design/subscriptions.md#full-cache)、[数据与缓存 §2.1](design/data-and-cache.md)、[界面 §3.9](ui.md#subscriptions)) |
-| DEC-057 | M4 实机反馈(第五轮)的任务页与界面调整:① **任务页里的记录都能删除**:结束的缓存队列(完成、取消、出错)可以逐个“移除”或“清除已结束”,进行中的要先取消;“最近结束的录制”可以逐条或全部移除(只从这个列表隐藏,录像留在媒体库);结束的录制的“录制异常”可以“删除记录”(录像本身不删);② **缓存队列**:任务侧栏只留一项“缓存队列(进行中的个数)”,点开后页面按卡片列出全部队列,点卡片展开进度与最近缓存的内容(带封面,动态没有图片时用它引用的视频封面);③ 图标栏的按钮整体上移:顶部的 TRACE 标志只是标志,不再占一个按钮位;④ **主页点头像打开订阅**:主页帖子作者已订阅时点头像进入这个订阅,没订阅的仍打开用户页;用户页只在用户主动解析时打开;⑤ **主页切换站点筛选更快**:缩略图按显示大小解码(单图 960 px、九宫格 480 px),解码结果放进按使用时间淘汰的缓存(600 张、320 MiB),读文件时同一文件夹 3 秒内只核对一次没有链接;⑥ **订阅 › 全部账号**:按站点列出全部订阅的账号,每行显示所属订阅,点开进入那个订阅;⑦ 抖音私密账号:不再看到“私密”就不请求作品,当前登录的抖音账号能看到作品时照常列出与缓存 | 用户,2026-11-16(第五轮反馈 1、4~7 条及补充的全部账号、私密账号与任务封面) | 替代 DEC-050 ② 中任务侧栏每个队列一行的做法。删除只改 TRACE 的记录与列表,不删除已缓存的文件。A 已实现([阶段报告 §16](delivery/stage-report.md#feedback-5)) |
-| DEC-056 | **转发与合作视频的存放位置**:① 转发的动态存到**转发者**文件夹的 `forwards/`,转发里带的视频也存在那里(不再进原作者的文件夹,也不和转发者自己的投稿混在一起),条目记 `via`(`reason=forward`、转发者、转发的动态);媒体库新增“转发”筛选,“图片”“视频”只列作者自己的内容,按作者筛选时包括为他缓存的转发;② 哔哩哔哩**合作视频**为订阅或解析的那位成员缓存时,存到这位成员的 `videos/`,记 `via`(`reason=collab`);没有成员上下文(直接解析视频)时仍存在投稿人(第一作者)的文件夹 | 用户,2026-11-16(第五轮反馈 2、3 条,例子:缓存灰泽满Hazel 时 BV1DDpE68E56 进了小柔Channel 的文件夹) | 只影响新缓存的条目:已有条目留在原文件夹,想移动就在媒体库删除后重新缓存。`item.json` 新增可选字段 `via`,结构版本不变;`library.db` 新增表达式索引 `idx_library_items_via`。A 已实现([阶段报告 §16](delivery/stage-report.md#feedback-5),[数据与缓存设计 §2](design/data-and-cache.md)) |
-| DEC-055 | 媒体库加一个“刷新”按钮:用户可能直接在资源管理器里删文件,刷新后弹窗提示哪些文件被删除了 | 用户,2026-11-16 | 刷新只看文件在不在、大小对不对(不算哈希,大库也快),文件夹被删的条目从媒体库移除,删了部分文件的条目标为缺文件;弹窗只列这次新发现的,已标过缺文件的不再重复列出。设置“存储”的“重建索引”不变。A 已实现([阶段报告 §14](delivery/stage-report.md#feedback-4)) |
-| DEC-054 | 缓存规则里有一条不可修改的“默认”规则:所有选项都不开(不定时检查、不自动缓存、不录制直播),新订阅默认使用它 | 用户,2026-11-16 | 替代 DEC-040 ① 中“默认”规则可以编辑、初始为定时检查的说法(仍不能删除,删除别的规则时它的订阅改用“默认”)。已有用“默认”规则的订阅在升级时按原来的设置归到同设置的规则(如“定时检查”),行为不变。A 已实现([阶段报告 §14](delivery/stage-report.md#feedback-4)) |
-| DEC-053 | M4 实机反馈(第四轮)的主页调整:① **主页回到上次阅读的位置**:再次打开 TRACE 时,主页时间线停在上次看到的那条,往上滑继续看新缓存的内容(不显示“N 条更新的内容”提示);“全部 / B 站 / 抖音”三个站点筛选分别记位置,单个订阅的信息流不记;② **主页侧栏列出订阅的更新**:侧栏按哔哩哔哩动态页头像条的样式列出订阅,不加“正在直播”“订阅”之类的分节标题:正在直播的排最前面(头像一圈高亮),然后是未读的(头像右下角一个小圆点),再是已读的(没有圆点),各组按最近更新时间从新到旧。点一个订阅就看它的信息流,圆点立即消失、变为已读,但这次不挪位置,下次进入主页时才移到已读的那一组 | 用户,2026-11-16(附哔哩哔哩动态页头像条截图;同日答复 Q-019) | 替代 DEC-040 ④ 的“每次打开从最新处开始,不恢复位置”(“往上翻过的不再当成未读”“不提示 N 条更新的内容”仍有效),以及 DEC-033 ①、DEC-037 的“有更新”中“不标未读”的部分:主页侧栏订阅的圆点表示该订阅有没点开看过的新缓存内容;侧栏原来单独的“正在直播”分节并入这个列表;仍不做未读数字、单条已读标记,也不在图标栏加未读角标。由 B 实现([当前计划 §14](delivery/stage-plan.md#feedback-4)),默认值见 [Q-019](../USER-ACTIONS.md#q-019) |
+| DEC-062 | **远程版(M5)**:① 单独打包无界面的远程程序 `trace-server`,主要在 Debian 12、Ubuntu 22.04 一类的 Linux VPS 上运行,只做检查更新、按规则缓存启动后的新内容、开播录制和上传,没有媒体库等其他功能;② 本地与远程总是同一版本,导入导出与接口不考虑旧版本兼容;③ **Cookie 只由本地续期**,远程从不续期;本地续期或重新登录后,连着远程就自动推送;④ 远程开 HTTPS 接口(启动时生成自签名证书与令牌,本地用连接码里的证书指纹认证),本地在“设置 › 远程”查看远程状态,手动同步订阅与 Cookie;⑤ **订阅同步时连同缓存规则一起同步**,远程按每个订阅的规则缓存与录制,不执行“全部缓存”与补更早内容;⑥ 订阅列表可导出导入;资源库可导出,也可以从网盘下载后**手动选文件夹导入**,增量导入,有冲突的由用户逐条或批量选择保留本地、用导入的或合并;⑦ 导出目录与媒体库同一布局,文件写完后才出现正式名,`item.json` 带每个文件的大小与 SHA-256,所以不用停下远程也能导入已上传的部分;⑧ 为以后的集群模式(多台机器订阅同一批账号、汇成一个资源库)预留节点 ID 与按条目合并;⑨ **远程内置上传**:调用机器上的 rclone,按条目先传媒体文件、最后传 `item.json`,确认后删除本机文件;用户自己的定时 rclone 方式仍然兼容 | 用户,2026-11-19(“下一个阶段我希望能提供部署到远程 VPS 的版本……”,四个问题选了推荐项:内置 HTTPS + 令牌、只由本地续期、随订阅同步缓存规则、手动选文件夹导入;随后补充“可以在远端软件里内置上传功能,如果你觉得这样更可靠,我主要是会上传到 google drive”) | 内置上传仍用 rclone 而不直接对接 Google Drive 接口:rclone(MIT,2026-11-06 发布 v1.76.0,2026-11-18 仍有提交)已经处理 OAuth、断点续传、每个 client_id 的限速与每天 750 GiB 的上传上限;它的文档说共用的 client_id 会在 2026 年内停用,Google Drive 要用户自己的 client_id,TRACE 自己对接也绕不开(rclone.org/drive,2026-11-19 查询)。远程只能挡住凭证文件被单独拷走,挡不住拿到 VPS root 的人。默认值见 [Q-022](../USER-ACTIONS.md#q-022)。[远程设计](design/remote.md)、需求 [§2.10](requirements.md#remote-scope) |
+| DEC-063 | 2026-11-20 实机反馈:① **抖音共创作品存到为谁缓存的账号下**:从某个账号的作品列表缓存(订阅自动缓存、缓存队列与“全部缓存”、用户页作品的“缓存”)时,作品的发布者不是这个账号,就存到这个账号的 `douyin/<短哈希>/works/<作品 ID>/`,清单记 `via = {reason: "collab", site: "douyin", uid: 这个账号, name}`,作者仍是发布者;信息流按账号筛选、媒体库作者列表、已缓存数都算在这个账号下(与哔哩哔哩合作视频的 DEC-056、DEC-061 ③ 相同)。直接解析作品链接缓存的仍放在发布者下;已经缓存过的条目沿用原来的文件夹,不搬动;② **主页的帖子在账号名后用小一号的强调色文字显示所属订阅的名称**(不加“订阅”二字,与账号名相同时不重复显示),点它打开这个订阅;③ **全部缓存(含定期全部缓存)检查未缓存的作品时也看完整性**:部分完成、有缺失记录或分 P 没有文件的条目和没缓存的一样交给队列再缓存一次(只补缺的部分),完整的、正在缓存的、已暂停的和只是可以升级画质的照常跳过 | 用户,2026-11-20(“为什么会缓存到悠长假期,就算缓存应该是缓存到猫九酱”“信息流不光展示账号名,也用一个稍微小号的蓝色字展示一下订阅名称,不要加订阅两个字”“检查未缓存的时候也应该把完整性纳入范围”) | ① 的根因:抖音的缓存请求没有“为哪个账号缓存”,文件夹总按作品的 `author` 算;作品列表接口会把共创作品列在共创者名下。数据:`download_tasks` 新增可选列 `via_json`(任务重启后仍写对 `via`),结构版本不变,旧版程序忽略它。② 用户给了两种写法,按第一种实现(账号名仍是主标题)。③ 同一个账号永远补不上的内容(例如版权限制的配乐)每次全部缓存都会再请求一次,按 7 天一次的节奏代价可以接受。正本:[数据与缓存 §2.1](design/data-and-cache.md)、[界面 §3.1](ui.md#home)、[订阅 §4](design/subscriptions.md#full-cache) |
+| DEC-064 | 2026-11-21 实机反馈:**订阅详情“内容”标签的每条帖子右上角有“⋯”**,菜单“在资源管理器中显示”与红字“删除”;删除走媒体库同一套删除计划与确认弹窗(只删登记文件;动态独占的引用视频一起删,单独缓存或别的动态也引用的保留),删除后列表重新载入。全部缓存不记住删除过的条目,下次补齐时照常再缓存 | 用户,2026-11-21(“现在没有地方能移除已缓存的动态的,只能针对图片和视频进行移除……右上角三个点可以直接删除每个条目”“全部缓存不跳过已删除的,只是用来清理异常的内容”) | 媒体库按文件列图片与视频,只有文字的动态没有卡片,不能删。确认弹窗顺带修正:动态没有标题时用正文第一行,大小计入一并删除的引用视频,共用视频的说明改成从动态的角度写。不改数据结构。正本:[界面 §3.1、订阅详情](ui.md) |
+| DEC-057 | M4 实机反馈(第五轮)的任务页与界面调整:① **任务页里的记录都能删除**:结束的缓存队列(完成、取消、出错)可以逐个“移除”或“清除已结束”,进行中的要先取消;“最近结束的录制”可以逐条或全部移除(只从这个列表隐藏,录像留在媒体库);结束的录制的“录制异常”可以“删除记录”(录像本身不删);② **缓存队列**:任务侧栏只留一项“缓存队列(进行中的个数)”,点开后页面按卡片列出全部队列,点卡片展开进度与最近缓存的内容(带封面,动态没有图片时用它引用的视频封面);③ 图标栏的按钮整体上移:顶部的 TRACE 标志只是标志,不再占一个按钮位;④ **主页点头像打开订阅**:主页帖子作者已订阅时点头像进入这个订阅,没订阅的仍打开用户页;用户页只在用户主动解析时打开;⑤ **主页切换站点筛选更快**:缩略图按显示大小解码(单图 960 px、九宫格 480 px),解码结果放进按使用时间淘汰的缓存(600 张、320 MiB),读文件时同一文件夹 3 秒内只核对一次没有链接;⑥ **订阅 › 全部账号**:按站点列出全部订阅的账号,每行显示所属订阅,点开进入那个订阅;⑦ 抖音私密账号:不再看到“私密”就不请求作品,当前登录的抖音账号能看到作品时照常列出与缓存 | 用户,2026-11-16(第五轮反馈 1、4~7 条及补充的全部账号、私密账号与任务封面) | 替代 DEC-050 ② 中任务侧栏每个队列一行的做法。删除只改 TRACE 的记录与列表,不删除已缓存的文件。A 已实现([阶段报告 §16](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-report.md#feedback-5)) |
+| DEC-056 | **转发与合作视频的存放位置**:① 转发的动态存到**转发者**文件夹的 `forwards/`,转发里带的视频也存在那里(不再进原作者的文件夹,也不和转发者自己的投稿混在一起),条目记 `via`(`reason=forward`、转发者、转发的动态);媒体库新增“转发”筛选,“图片”“视频”只列作者自己的内容,按作者筛选时包括为他缓存的转发;② 哔哩哔哩**合作视频**为订阅或解析的那位成员缓存时,存到这位成员的 `videos/`,记 `via`(`reason=collab`);没有成员上下文(直接解析视频)时仍存在投稿人(第一作者)的文件夹 | 用户,2026-11-16(第五轮反馈 2、3 条,例子:缓存灰泽满Hazel 时 BV1DDpE68E56 进了小柔Channel 的文件夹) | 只影响新缓存的条目:已有条目留在原文件夹,想移动就在媒体库删除后重新缓存。`item.json` 新增可选字段 `via`,结构版本不变;`library.db` 新增表达式索引 `idx_library_items_via`。A 已实现([阶段报告 §16](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-report.md#feedback-5),[数据与缓存设计 §2](design/data-and-cache.md)) |
+| DEC-055 | 媒体库加一个“刷新”按钮:用户可能直接在资源管理器里删文件,刷新后弹窗提示哪些文件被删除了 | 用户,2026-11-16 | 刷新只看文件在不在、大小对不对(不算哈希,大库也快),文件夹被删的条目从媒体库移除,删了部分文件的条目标为缺文件;弹窗只列这次新发现的,已标过缺文件的不再重复列出。设置“存储”的“重建索引”不变。A 已实现([阶段报告 §14](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-report.md#feedback-4)) |
+| DEC-054 | 缓存规则里有一条不可修改的“默认”规则:所有选项都不开(不定时检查、不自动缓存、不录制直播),新订阅默认使用它 | 用户,2026-11-16 | 替代 DEC-040 ① 中“默认”规则可以编辑、初始为定时检查的说法(仍不能删除,删除别的规则时它的订阅改用“默认”)。已有用“默认”规则的订阅在升级时按原来的设置归到同设置的规则(如“定时检查”),行为不变。A 已实现([阶段报告 §14](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-report.md#feedback-4)) |
+| DEC-053 | M4 实机反馈(第四轮)的主页调整:① **主页回到上次阅读的位置**:再次打开 TRACE 时,主页时间线停在上次看到的那条,往上滑继续看新缓存的内容(不显示“N 条更新的内容”提示);“全部 / B 站 / 抖音”三个站点筛选分别记位置,单个订阅的信息流不记;② **主页侧栏列出订阅的更新**:侧栏按哔哩哔哩动态页头像条的样式列出订阅,不加“正在直播”“订阅”之类的分节标题:正在直播的排最前面(头像一圈高亮),然后是未读的(头像右下角一个小圆点),再是已读的(没有圆点),各组按最近更新时间从新到旧。点一个订阅就看它的信息流,圆点立即消失、变为已读,但这次不挪位置,下次进入主页时才移到已读的那一组 | 用户,2026-11-16(附哔哩哔哩动态页头像条截图;同日答复 Q-019) | 替代 DEC-040 ④ 的“每次打开从最新处开始,不恢复位置”(“往上翻过的不再当成未读”“不提示 N 条更新的内容”仍有效),以及 DEC-033 ①、DEC-037 的“有更新”中“不标未读”的部分:主页侧栏订阅的圆点表示该订阅有没点开看过的新缓存内容;侧栏原来单独的“正在直播”分节并入这个列表;仍不做未读数字、单条已读标记,也不在图标栏加未读角标。由 B 实现([当前计划 §14](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-plan.md#feedback-4)),默认值见 [Q-019](../USER-ACTIONS.md#q-019) |
| DEC-052 | 本机开发版常驻后台:`tools/package -install` 安装开发版时,TRACE Dev 在运行就让它保存并退出(不强杀);**每次安装成功后都以 `--background` 在托盘打开 TRACE Dev**,不论安装前是否在运行、窗口是否打开。在 Agent 命令沙箱(作业对象)里运行时,工具请求新进程脱离作业;不允许脱离时在 `install-dev.json` 记 `inJob=true` 并提示从开始菜单打开一次,不写成已常驻 | 用户,2026-11-15(“dev 版本会常态运行……重装完后需要打开 dev 版本在后台运行”) | 替代 DEC-051 ⑤ 的“原来回到托盘的仍回到托盘”与 DEC-041 ② 的“原来开着就重开”;只对开发版本机安装生效,正式版应用内更新照旧恢复原来的窗口。[工程规则 §2.2](dev-rules/engineering.md#dev-install) |
-| DEC-051 | M4 实机反馈(第二轮,8 条)的产品调整:① **更新页面**:设置里新增“更新”分类,显示当前版本与通道、这个通道怎样更新(正式版每 24 小时自动检查;开发版不自己检查,由本机打包后自动安装并重开)、上次与下次检查的时间和结果、检查记录与更新记录(何时从哪个版本到哪个版本、通过什么方式);② 删除缓存条目后,作者的最后一条也删掉时,同时删除变空的类型文件夹和作者文件夹,不留空文件夹;③ **不限制同时录制数**(去掉设置“同时录制数”与上限检查),并在“任务 › 直播录制”提供**录制异常**记录(断流重连、因网速跟不上丢失的片段及时长、速度低于码率、空间不足、转换失败),按录制列出;④ 图标栏“订阅”上的橙色小点只表示“有订阅正在直播”,悬停提示写明,不是未读;⑤ 更新开发版时,本机正在运行的 TRACE Dev 先保存并退出,装完再打开(原来回到托盘的仍回到托盘);每次反馈时 Agent 检查本机开发版日志;⑥ 订阅头像默认用第一个账号的头像,两个站点都在本机存一份,不再依赖存下的地址;⑦ **订阅详情改为“内容”“账号”两个标签**:“内容”(默认)是这个订阅全部账号已缓存内容的信息流(同主页帖子),“直播”并进“账号”:每个账号一行同时显示直播状态与录制按钮;⑧ 设置“缓存规则”里可以给一条规则**批量选择使用它的订阅**,不用到每个订阅里逐个改 | 用户,2026-11-15(M4 第一轮反馈实现后的实机反馈) | ②④⑤⑥ 已由 A 实现([阶段报告 §10](delivery/stage-report.md#feedback-2));①③⑦⑧ 由 B 实现([当前计划 §13](delivery/stage-plan.md#feedback-2)),理解与默认值见 [Q-018](../USER-ACTIONS.md#q-018)。⑦ 替代 DEC-040 与[界面规范 §3.9](ui.md#subscriptions) 的“直播(默认)/ 账号”标签和“订阅的内容在主页与媒体库里看”;③ 替代 FR-SET-002 与 FR-LIVE-002 的同时录制数 1~4 |
-| DEC-050 | M4 实机反馈(第一轮补充)的产品调整:① **缓存队列**:用户页“⋯”里的“缓存更早的内容(10 / 20 / 50 条)”改为“全部缓存”——不是马上把这个账号以前的内容全部排进下载队列,而是建一个缓存队列任务,在后台以较慢、不规律的速度一条一条缓存(间隔随机,隔一段时间长歇一次,等上一条下载完再排下一条),遇到风控、限流或额度用完就等退避结束再继续,重启后接着做;② **任务页加上下文侧栏**:侧栏直接列出“下载任务”“缓存队列”(每个队列任务一行:头像、名称、进度与状态)和“直播录制”,点哪项页面显示哪项,替代 DEC-049 ① 里任务页顶部的两个标签;③ **托盘右键菜单**只留“打开”和“退出”,在指针处用系统原生菜单打开(字体更小、与图标之间没有空隙),任务与录制数量放到悬停提示 | 用户,2026-11-15(附托盘菜单对比截图) | 替代 DEC-046 ⑥ 与 FR-USER-004 中按条数一次入队的做法、DEC-049 ① 的任务页标签、[界面规范 §3.10](ui.md#tray) 的托盘菜单项(状态行、检查全部订阅)。①② 的实现见[当前计划 §12](delivery/stage-plan.md#feedback-1b),节奏的默认值见 [Q-017](../USER-ACTIONS.md#q-017);③ 已由 A 实现([阶段报告 §7](delivery/stage-report.md#feedback-1)) |
-| DEC-049 | M4 实机反馈(第一轮)的产品调整:① 直播录制不再计入图标栏“任务”的角标;任务页分“缓存”“直播录制”两个标签,“直播录制”里选中一场正在录制的直播,就在页面里实时播放录制中的画面(读正在写入的录像文件,不另开站点连接);实时弹幕要先研究协议并做真实检查,作为下一阶段(FR-LIVE-003);② 解析页改用上下文侧栏:最近解析移到侧栏(每条“⋯”里有删除),主面板只有一个居中的大输入框,像搜索引擎首页;视频与用户页的侧栏是同一份列表;③ 媒体库是独立的离线内容:不再按缓存时间排序(按发布时间,录像按开播时间),点视频或图片就地打开播放层或看图层,“详情”在媒体库自己的本机详情里打开,图标栏仍停在媒体库,不进入解析页、不发网络请求;④ 实况照片在看图层翻到即自动播放动态片段,按钮用来重播 | 用户,2026-11-14(M4 交付后的实机反馈 8 条,其余 4 条是缺陷,见[阶段报告 §7](delivery/stage-report.md#feedback-1)) | 替代 DEC-037 ④ 与[界面规范 §3.2](ui.md#parse) 中“输入框下面是最近解析列表”、§2 中任务角标数录制中的任务、§3.6 的“发布时间 / 缓存时间”排序切换;①~③ 的实现见[当前计划 §11](delivery/stage-plan.md#feedback-1),理解与默认值见 [Q-016](../USER-ACTIONS.md#q-016) |
+| DEC-051 | M4 实机反馈(第二轮,8 条)的产品调整:① **更新页面**:设置里新增“更新”分类,显示当前版本与通道、这个通道怎样更新(正式版每 24 小时自动检查;开发版不自己检查,由本机打包后自动安装并重开)、上次与下次检查的时间和结果、检查记录与更新记录(何时从哪个版本到哪个版本、通过什么方式);② 删除缓存条目后,作者的最后一条也删掉时,同时删除变空的类型文件夹和作者文件夹,不留空文件夹;③ **不限制同时录制数**(去掉设置“同时录制数”与上限检查),并在“任务 › 直播录制”提供**录制异常**记录(断流重连、因网速跟不上丢失的片段及时长、速度低于码率、空间不足、转换失败),按录制列出;④ 图标栏“订阅”上的橙色小点只表示“有订阅正在直播”,悬停提示写明,不是未读;⑤ 更新开发版时,本机正在运行的 TRACE Dev 先保存并退出,装完再打开(原来回到托盘的仍回到托盘);每次反馈时 Agent 检查本机开发版日志;⑥ 订阅头像默认用第一个账号的头像,两个站点都在本机存一份,不再依赖存下的地址;⑦ **订阅详情改为“内容”“账号”两个标签**:“内容”(默认)是这个订阅全部账号已缓存内容的信息流(同主页帖子),“直播”并进“账号”:每个账号一行同时显示直播状态与录制按钮;⑧ 设置“缓存规则”里可以给一条规则**批量选择使用它的订阅**,不用到每个订阅里逐个改 | 用户,2026-11-15(M4 第一轮反馈实现后的实机反馈) | ②④⑤⑥ 已由 A 实现([阶段报告 §10](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-report.md#feedback-2));①③⑦⑧ 由 B 实现([当前计划 §13](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-plan.md#feedback-2)),理解与默认值见 [Q-018](../USER-ACTIONS.md#q-018)。⑦ 替代 DEC-040 与[界面规范 §3.9](ui.md#subscriptions) 的“直播(默认)/ 账号”标签和“订阅的内容在主页与媒体库里看”;③ 替代 FR-SET-002 与 FR-LIVE-002 的同时录制数 1~4 |
+| DEC-050 | M4 实机反馈(第一轮补充)的产品调整:① **缓存队列**:用户页“⋯”里的“缓存更早的内容(10 / 20 / 50 条)”改为“全部缓存”——不是马上把这个账号以前的内容全部排进下载队列,而是建一个缓存队列任务,在后台以较慢、不规律的速度一条一条缓存(间隔随机,隔一段时间长歇一次,等上一条下载完再排下一条),遇到风控、限流或额度用完就等退避结束再继续,重启后接着做;② **任务页加上下文侧栏**:侧栏直接列出“下载任务”“缓存队列”(每个队列任务一行:头像、名称、进度与状态)和“直播录制”,点哪项页面显示哪项,替代 DEC-049 ① 里任务页顶部的两个标签;③ **托盘右键菜单**只留“打开”和“退出”,在指针处用系统原生菜单打开(字体更小、与图标之间没有空隙),任务与录制数量放到悬停提示 | 用户,2026-11-15(附托盘菜单对比截图) | 替代 DEC-046 ⑥ 与 FR-USER-004 中按条数一次入队的做法、DEC-049 ① 的任务页标签、[界面规范 §3.10](ui.md#tray) 的托盘菜单项(状态行、检查全部订阅)。①② 的实现见[当前计划 §12](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-plan.md#feedback-1b),节奏的默认值见 [Q-017](../USER-ACTIONS.md#q-017);③ 已由 A 实现([阶段报告 §7](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-report.md#feedback-1)) |
+| DEC-049 | M4 实机反馈(第一轮)的产品调整:① 直播录制不再计入图标栏“任务”的角标;任务页分“缓存”“直播录制”两个标签,“直播录制”里选中一场正在录制的直播,就在页面里实时播放录制中的画面(读正在写入的录像文件,不另开站点连接);实时弹幕要先研究协议并做真实检查,作为下一阶段(FR-LIVE-003);② 解析页改用上下文侧栏:最近解析移到侧栏(每条“⋯”里有删除),主面板只有一个居中的大输入框,像搜索引擎首页;视频与用户页的侧栏是同一份列表;③ 媒体库是独立的离线内容:不再按缓存时间排序(按发布时间,录像按开播时间),点视频或图片就地打开播放层或看图层,“详情”在媒体库自己的本机详情里打开,图标栏仍停在媒体库,不进入解析页、不发网络请求;④ 实况照片在看图层翻到即自动播放动态片段,按钮用来重播 | 用户,2026-11-14(M4 交付后的实机反馈 8 条,其余 4 条是缺陷,见[阶段报告 §7](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-report.md#feedback-1)) | 替代 DEC-037 ④ 与[界面规范 §3.2](ui.md#parse) 中“输入框下面是最近解析列表”、§2 中任务角标数录制中的任务、§3.6 的“发布时间 / 缓存时间”排序切换;①~③ 的实现见[当前计划 §11](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-plan.md#feedback-1),理解与默认值见 [Q-016](../USER-ACTIONS.md#q-016) |
| DEC-017 | 前端用 React + TypeScript(Vite、Tailwind),包管理用 npm(已由 [DEC-032](#dec-032) 替代:全项目改为 Go + `mygo/ui` 原生界面,不再引入 Node/npm/React/TypeScript) | 用户按推荐选择,2026-11-04;2026-11-05 随 DEC-016 复核后保持 | [选型研究 §3~§4](research/2026-11-05-stack.md#other-choices) |
| DEC-018 | 第一阶段(M1)只做哔哩哔哩:必须登录(扫码或粘贴凭证),没有访客模式;解析视频、用户主页、动态与投稿;按动态手动缓存文字、图片和视频,并提供媒体库。自动缓存以后再做(“自动缓存以后再做”已由 [DEC-027](#dec-027) 替代:按订阅规则的自动缓存并入 M1) | 用户,2026-11-04 | 缓存以动态为单位,视频按 `bvid` 只存一份,投稿列表和动态共用;手动凭证从输入框单向交给后端一次。[需求](requirements.md#scope)、[架构设计 §5](design/architecture.md#credentials)、[数据设计 §2](design/data-and-cache.md#cache) |
| DEC-019 | 设置是单独的页面:左栏左下角的设置按钮进入;设置页有自己的分类栏,以便以后容纳很多设置项;账号管理并入设置页 | 用户,2026-11-04、2026-11-05 | [界面规范 §3.7](ui.md#settings) |
diff --git a/docs/delivery/roadmap.md b/docs/delivery/roadmap.md
index afcca08..4521610 100644
--- a/docs/delivery/roadmap.md
+++ b/docs/delivery/roadmap.md
@@ -32,7 +32,8 @@
| 多站点基础(按站点登录与凭证、站点标记与筛选、按站点的请求额度与退避、数据结构迁移) | FR-AUTH-007、FR-SITE-002、NFR-NET-002、NFR-SEC-003、NFR-DATA-004 | AC-34、35、43、44 | 已实现 |
| 抖音(登录、链接、作品与用户页、缓存视频与图文、订阅与检查更新、开播状态与录制) | FR-DY-001~009、NFR-NET-003 | AC-36~42 | 已实现(真实站点见 ACT-010、ACT-011,实机见 H-001) |
| 直播 FLV 录制(抖音主路线、哔哩哔哩后备) | FR-DY-009、FR-LIVE-004 | AC-41、42 | 已实现(真实直播短录见 ACT-011) |
-| 我的:登录账号的关注、收藏夹、稍后再看、历史记录(哔哩哔哩)与关注、喜欢、收藏(抖音),点击打开详情 | FR-ACCT-001~005 | AC-45~53 | 已实现(M4,DEC-047;抖音喜欢/收藏夹/观看历史见 ACT-020 与 LOOP-014) |
+| 我的:登录账号的关注、收藏夹、稍后再看、历史记录(哔哩哔哩)与关注、喜欢、收藏(抖音),点击打开详情 | FR-ACCT-001~005 | AC-45~53 | 已实现(DEC-047;抖音喜欢/收藏夹/观看历史见 ACT-020 与 LOOP-014) |
+| 远程版(无界面远程程序、HTTPS 接口、订阅与 Cookie 同步、远程状态、内置上传、资源库与订阅的导入导出) | FR-REMOTE-001~008 | AC-56~64 | 已实现(真实 VPS、网盘与站点见 H-003) |
| 在线播放、专栏全文与合集系列(含抖音合集与音乐)、直播弹幕、抖音以外的其他站点、沉浸式标题栏与开机启动、同站多登录账号与抖音扫码 | FR-PLAY-001、FR-FEED-002、FR-LIVE-003、FR-SITE-001、FR-RUN-002、FR-AUTH-006 | 以后定义 | 待实现 |
@@ -53,6 +54,7 @@
| 安装、数据与打包 | 按用户安装到 `%LOCALAPPDATA%\Programs\trace`(开发版 `trace-dev`),数据在 `%LOCALAPPDATA%\trace`、缓存在“文档\trace”,两个通道隔离;接入旧的缓存文件夹;一条命令打包开发版安装包、只留最新产物;门禁一条命令;开发版打包后本机自动更新,正式版一条命令发布并联网更新(设置“更新”页统一显示版本、通道更新方式与检查/更新记录,DEC-051 ①) | Windows 代码签名、winget 与 Microsoft Store、测试版通道、差分包体积优化 |
| 抖音(DEC-043) | 粘贴 Cookie 登录、按站点登录互不影响;分享文本与各类链接解析;作品详情(视频、图文、实况、配乐)与用户作品列表;缓存视频(最高档、无水印、单文件 MP4)与图文;订阅关联抖音账号、检查更新(置顶不打断)、自动缓存;开播状态与 FLV 录制(原画优先、断流重连、换段、收尾);站点小字标记与按站点筛选;抖音与哔哩哔哩的额度、退避与熔断互不影响 | 扫码登录、关注导入、合集与喜欢收藏、直播弹幕、HLS-TS 后备(LOOP-008)、画质升级提醒、评论 |
| 我的(DEC-047) | “我的”页按站点折叠的功能;哔哩哔哩关注(含分组)、收藏夹、稍后再看、历史记录,抖音关注、喜欢、收藏(全部与收藏夹)都能翻页浏览,风控、未登录、失效、网络、空与到底分别说明;视频、作品、用户点开详情并能缓存,用户能加入订阅;返回时列表与位置保留;列表不落盘 | 一键缓存整个收藏夹或稍后再看、收藏的合集与追番、抖音观看历史(ACT-020 确认后)、写操作(取消收藏、删历史) |
+| 远程版(DEC-062) | `trace-server` 在 Linux 上 `init` 与 `run`;本地用连接码连接、看状态、同步订阅与 Cookie;远程只按规则缓存起点之后的新内容与录制,内置 rclone 上传并删除已上传的文件;媒体库从文件夹增量导入(预览、冲突选择、未传完的部分导入后再补)与导出;订阅导出导入 | 集群模式与多个远程、远程网页、本地自动从网盘拉取、导入时转码或去重相似内容 |
每个阶段按“A 制定覆盖整个阶段的计划 → B 连续实现与自测 → A 集中复核 → 用户授权后 push/PR/合并”推进;用户的人工检查、反馈与决定记在 USER-ACTIONS,任何时候处理,不阻塞这条流水线,反馈带来的修复进入当时正在进行的阶段。
@@ -116,5 +118,14 @@
| AC-53 | 隐私:浏览这些列表后,数据目录与缓存目录里没有新增包含列表标题或用户的文件,日志只有功能名、页数与错误类别(哨兵标题测试);退出某个站点后“我的”里该站点的列表立即清空;抖音“观看历史”只有在 ACT-020 确认后才出现,否则不显示入口 | 自动化通过(抖音观看历史未显示) |
| AC-54 | 用户页“⋯ → 全部缓存”建立后台慢速不规律缓存队列(每次只排 1 条,随机间隔与长歇,自动翻页共用站点每小时规则额度与退避,重复点击不建重复队列并可“在缓存队列中查看”);任务页侧栏在“下载任务 / 缓存队列 / 直播录制”间切换,支持队列暂停、继续、取消(取消不删已入库文件)与重启恢复,`cache-queue.json` 不含凭证和签名地址(DEC-050 ①②) | 自动化与 `tools/uishots` 通过(实机见 H-001 第 30 步) |
| AC-55 | 媒体库完全离线:点击卡片播放或看原图、“⋯ → 详情”打开 `/library/item` 本机详情均零网络请求、不跳转到解析页、不写最近解析;只有点详情右上角“⋯ → 在解析页打开”才进入解析页并发网络请求(DEC-049 ③) | 自动化与 `tools/uishots` 通过(实机见 H-001 第 30 步) |
+| AC-56 | `go run ./tools/package -server` 生成 `linux/amd64` 与 `linux/arm64` 的 `trace-server` 包(程序、systemd 示例、部署说明);程序不含 MyGo 与界面代码,体积比桌面版小;`trace-server version` 显示与桌面版同一版本号 | 自动化通过(`-server` 包在 WSL Ubuntu 校验、解包、运行与远程冒烟) |
+| AC-57 | 在 Linux 上 `trace-server init` 打印连接码与 rclone 过滤规则,`run` 提供 HTTPS 接口;不带令牌或令牌错误返回 401,1 分钟失败 5 次后暂时 429;证书指纹不符时本地拒绝连接;日志与状态里没有令牌、连接码与 Cookie(哨兵测试) | 自动化通过(M5-K07~K09,Windows 与 WSL;远程冒烟);真实 VPS `not-run`(H-003) |
+| AC-58 | 本地“设置 › 远程”粘贴连接码后显示远程的版本、运行时长、空间、各站点登录、订阅、检查、缓存、录制、上传与最近错误;远程不在线、证书变了、令牌错、版本不同分别说明 | 自动化与 `tools/uishots` 通过(假远程,M5-K15);真实远程 `not-run`(H-003) |
+| AC-59 | “同步订阅”后远程的订阅、规则与相关设置与本地相同,本地显示已同步;远程第一次检查新账号只建立起点;之后发布的内容按订阅的规则缓存、开播按规则录制;规则开了“全部缓存”的订阅在远程不做全部缓存;从本地移出的账号远程不再检查,已缓存文件不删 | 自动化通过(M5-K05、K11、K17、K22);真实站点 `not-run`(H-003) |
+| AC-60 | 按站点“同步 Cookie”:远程校验后显示登录的账号;无效 Cookie 被拒、原凭证不变;远程从不发续期请求;本地续期或重新登录后自动推送,远程离线时显示“Cookie 待同步”并在恢复后推送;远程判定登录失效后停止这个站点的请求并提示重新同步 | 自动化通过(假站点,M5-K10、K16);真实站点 `not-run`(H-003) |
+| AC-61 | 远程缓存与录制进行时,内置上传按条目先传媒体文件再传 `item.json`,确认后删除本机文件;`.part` 与 `.trace-` 文件从不上传、不删除;rclone 失败时重试并在状态里说明;改用外部定时 `rclone move`(带排除规则)时远程照常继续缓存与录制、不重复下载 | 自动化通过(假 rclone,M5-K11 与远程冒烟);Google Drive `not-run`(H-003) |
+| AC-62 | 媒体库“导入”一个网盘下载的文件夹:预览分出新条目、可补充、相同、冲突、未传完、无法识别;新条目导入后在媒体库与主页可播放;直播只传完一部分时导入已完成的段,下次导入补上其余;冲突按保留本地、用导入的、合并分别得到正确的文件;中途取消后再导入能完成且没有半个文件;来源文件默认不动 | 自动化与 `tools/uishots` 通过(M5-K18~K20) |
+| AC-63 | 媒体库“导出”的文件夹与订阅导出的 `trace-subscriptions.json` 能在另一个数据目录里导入,得到相同的条目、订阅与规则;订阅导入的预览正确区分新订阅、已订阅的账号与不同的规则 | 自动化通过(M5-K21、K22) |
+| AC-64 | 两台远程(不同节点)缓存了同一场直播的不同段,先后导入同一个资源库后合并成一场,`item.json` 记着缓存它们的节点 | 自动化通过(M5-K21) |
-AC-01~04、AC-08~11、AC-15、AC-17、AC-19~22 的哔哩哔哩真实站点部分需要真实请求或人工操作,分别对应 USER-ACTIONS 的 ACT-004、ACT-005 和 H-001;AC-28、29、32 的实机部分对应 H-002;AC-35~38、AC-41 的真实站点部分对应 ACT-010 与 ACT-011;AC-46~51 的真实站点部分对应 ACT-020;合成测试通过不等于这些场景通过。
+AC-01~04、AC-08~11、AC-15、AC-17、AC-19~22 的哔哩哔哩真实站点部分需要真实请求或人工操作,分别对应 USER-ACTIONS 的 ACT-004、ACT-005 和 H-001;AC-28、29、32 的实机部分对应 H-002;AC-35~38、AC-41 的真实站点部分对应 ACT-010 与 ACT-011;AC-46~51 的真实站点部分对应 ACT-020;AC-56~64 在真实 VPS 与网盘上的部分对应 H-003。合成测试通过不等于这些场景通过。
diff --git a/docs/delivery/stage-plan.md b/docs/delivery/stage-plan.md
index 4836623..1861501 100644
--- a/docs/delivery/stage-plan.md
+++ b/docs/delivery/stage-plan.md
@@ -1,436 +1,218 @@
-# 当前阶段计划:M4(我的:登录账号的站点内容)
+# 当前阶段计划:M5(远程版、上传与导入导出)
-- **阶段编号**:M4;计划标识 `TRACE-M4-01`,修订 4(2026-11-15:加第 13 节,第二轮实机反馈;修订 3 的第 11、12 节已由 B 实现、A 审查收敛)。
-- **角色**:A 规划;B 连续实施与自检;A 集中审查([开发流程 §2](../dev-rules/workflow.md#agent-handoff))。给 B 的 prompt:本轮在[第 13.6 节](#prompt-feedback-2)(最初的在[第 10 节](#prompt))。
-- **分支**:`codex/m4-account`,A 已从 `main @ f080483` 创建。本计划所在的提交是阶段提交的起点;B 的实施、A 的审查修复和人工反馈的修复全部 amend 进这一个 DCO 提交。
-- **上一阶段**:M3(抖音视频与直播)经 PR #7 合并为 `main @ f080483`:[M3 计划](https://github.com/chialecode/trace/blob/f080483/docs/delivery/stage-plan.md)、[M3 报告](https://github.com/chialecode/trace/blob/f080483/docs/delivery/stage-report.md)。
-- **决定与需求**:[DEC-047](../decisions.md#dec-047);需求 FR-ACCT-001~005([需求 §2.9](../requirements.md#account-scope));验收 AC-45~AC-53([路线与验收](roadmap.md#acceptance));界面 [§3.11](../ui.md#mine);服务契约 [架构 §3](../design/architecture.md#services) 的 `AccountService`;协议 [哔哩哔哩 §21](../research/bilibili.md#account-lists)、[抖音 §12](../research/douyin.md#account-lists)。实现细节的默认值见 [Q-015](../../USER-ACTIONS.md#q-015),真实站点检查是 [ACT-020](../../USER-ACTIONS.md#act-020)。
+- **阶段编号**:M5;计划标识 `TRACE-M5-01`,修订 1(2026-11-19)。
+- **角色**:A 规划;B 连续实施与自检;A 集中审查([开发流程 §2](../dev-rules/workflow.md#agent-handoff))。给 B 的 prompt 在[第 10 节](#prompt)。
+- **分支**:`codex/m5-remote`,A 已从 `main @ 8327803` 创建。本计划所在的提交是阶段提交的起点;B 的实施、A 的审查修复和人工反馈的修复全部 amend 进这一个 DCO 提交。
+- **上一阶段**:M4(我的)经 PR #8 合并为 `main @ a613735`,合并后的三轮反馈(DEC-059~061)经 PR #10 合并为 `main @ 8327803`:[M4 计划](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-plan.md)、[M4 报告](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-report.md)。
+- **决定与需求**:[DEC-062](../decisions.md#dec-062);需求 FR-REMOTE-001~008([需求 §2.10](../requirements.md#remote-scope));验收 AC-56~AC-64([路线与验收](roadmap.md#acceptance));**设计正本 [远程设计](../design/remote.md)**(本计划只补实现上的指引,不重复设计);默认值 [Q-022](../../USER-ACTIONS.md#q-022);真实 VPS 检查 [H-003](../../USER-ACTIONS.md#h-003)。
-用户 2026-11-14 要求:把哔哩哔哩和抖音提供的账号接口功能做在一个功能页里——左侧图标栏一个图标,点进去每个网站的功能默认折叠,选一个网站展开功能,点功能主面板出现不同内容(关注列表、收藏、稍后再看、历史记录等),里面的视频、图文都能点击跳转到解析页;具体功能参考本机参考与 GitHub 项目。A 理解的目标:登录账号在两个站点上“自己的”列表在 TRACE 里一处浏览,列表本身只读、不落盘,条目接入已有的详情、缓存与订阅流程,不另造旁路。
+用户 2026-11-19 要求:提供部署到远程 VPS 的版本,只获取启动后更新的内容和录制,没有其他功能;VPS 上的内容定时上传到网盘,再从网盘下载到本地导入(假设两边都是最新版);订阅列表与资源库都能导入导出,订阅从本地经 VPS 的 HTTP 接口同步,资源库从网盘下载后增量导入,冲突由用户选保留或合并;为以后的集群模式做准备;可以单独打包远程版减小体积;远程通常运行在 Debian 12、Ubuntu 22 一类的 Linux 上;本地软件可以连接远程查看状态、手动同步订阅与 Cookie;上传时还在增长的视频不会被上传,元数据要一同上传,不需要停下远程就能导入。用户选了四个推荐项(内置 HTTPS + 令牌、只由本地续期、随订阅同步缓存规则、手动选文件夹导入),并补充“可以在远端软件里内置上传功能,如果你觉得这样更可靠,主要上传到 Google Drive”。A 的结论:内置上传,但传输交给 rclone(DEC-062 ⑨ 的理由)。
## 1. 范围与退出条件
| 项目 | 约定 |
| --- | --- |
-| 阶段内容 | 阶段开始的整理(C0);哔哩哔哩账号列表客户端(W1);抖音账号列表客户端与表单 POST 签名(W2);`AccountService` 服务层(W3);“我的”界面(W4);真实检查、截图与隐私测试工具(W5);文档(W6) |
-| 不在本阶段 | 任何写操作(取消收藏、删除历史、移出稍后再看、取消关注、点赞);一键缓存整个收藏夹或稍后再看(Q-015 第 4 条);哔哩哔哩收藏的合集、追番追剧、点赞与投币的视频;抖音收藏的合集与音乐、稍后再看;列表的本机持久化与离线查看;抖音扫码;新增第三方依赖 |
-| 可连续执行 | 本地实现、合成夹具、测试、截图、打包与本机开发版自动安装、冒烟、文档同步、阶段提交与 amend;ACT-020 的 1 次真实只读检查(常设授权内) |
-| 外部操作 | 真实请求只在 [ACT-020](../../USER-ACTIONS.md#act-020) 的对象与额度内,经 `tools/actcheck -act act020` 1 次;Cookie 缺失或失效就记 `not-run` 并写进 USER-ACTIONS 的“待你统一处理”,不阻塞。未授权:push、PR、合并、标签、发布 |
-| 必须保留 | M1~M3 的全部行为与测试:两站点登录、续期、解析、缓存、订阅、检查更新、录制、代理、一键缓存更早内容与筛选;数据结构版本 2 与守卫(本阶段不改任何数据文件结构);按站点的间隔、额度、退避与熔断;凭证隔离与哨兵;安静测试;只删登记文件;`dist/<通道>/` 只留最新一份(DEC-025) |
+| 阶段内容 | 阶段开始的整理与依赖盘点(C0、D1);可写文件与临时名的统一(W1);远程运行配置与 Linux 凭证(W2);`trace-server` 程序、接口与安全(W3);内置上传(W4);本地远程客户端与“设置 › 远程”(W5);资源库导入导出(W6);订阅导出导入与同步快照(W7);打包、门禁与 CI(W8);文档(W9) |
+| 不在本阶段 | 集群调度(多台分担账号)与同时连多个远程(FR-REMOTE-009);远程网页;本地自动从网盘拉取;远程的解析、手动缓存、全部缓存、补更早内容;Windows 版远程程序与 Docker 镜像;远程自我更新(换包重启);导入时转码或识别相似内容;新的站点能力 |
+| 可连续执行 | 本地实现、合成夹具、假 rclone、在回环地址上起真实 HTTPS 服务的端到端测试、截图、打包与本机开发版自动安装、冒烟、文档同步、阶段提交与 amend;本机有 WSL 时在其中运行 Linux 版 `trace-server` 冒烟 |
+| 外部操作 | 本阶段不需要 Agent 发真实站点请求,也不连接任何网盘;远程对真实站点与网盘的行为由用户在 [H-003](../../USER-ACTIONS.md#h-003) 检查。未授权:push、PR、合并、标签、发布 |
+| 必须保留 | M1~M4 与 DEC-059~061 的全部行为与测试;数据结构版本 2 与守卫(本阶段只加可选字段与 `CREATE TABLE IF NOT EXISTS` 新表,不升结构版本);按站点的间隔、额度、退避与熔断;凭证隔离与哨兵;INV-01~14;安静测试(不碰本机安装的应用);只删登记文件;`dist/<通道>/` 只留最新一份(DEC-025) |
**退出条件**
| 条件 | 做法 | 工作包 | 验收 |
| --- | --- | --- | --- |
-| “我的”入口与折叠分组 | 图标栏第三项“我的”;侧栏两组默认折叠、手风琴展开;未登录与失效只给登录入口、不发请求;窄窗在页面里选择 | W3、W4 | AC-45 |
-| 哔哩哔哩关注 | 复用已有关注分组与列表接口;订阅状态与加入订阅;点开用户页 | W1、W3、W4 | AC-46 |
-| 哔哩哔哩收藏夹 | `list-all` + `resource/list`;默认在前、私密标记、失效灰显、非视频只给浏览器 | W1、W3、W4 | AC-47 |
-| 哔哩哔哩稍后再看 | `toview/web`(WBI);进度、“全部 / 未看完” | W1、W3、W4 | AC-48 |
-| 哔哩哔哩历史记录 | `history/cursor` 游标翻页;按日分组;视频、直播可打开,其他只给浏览器;游标不前进时停下 | W1、W3、W4 | AC-49 |
-| 抖音关注 | `following/list` 时间游标;点开抖音用户页;加入订阅 | W2、W3、W4 | AC-50 |
-| 抖音喜欢与收藏 | `favorite`、`listcollection`(POST 表单签名)、`collects/list` + `collects/video/list`;3:4 网格;第 1 页空壳判失效 | W2、W3、W4 | AC-51 |
-| 真实状态 | 风控、限流、网络、失效、格式变化、空、到底分别说明;不自动重试;熔断按站点 | W1~W4 | AC-52 |
-| 隐私与条件入口 | 列表只在内存、不进日志与文件(哨兵);退出登录即清空;抖音观看历史由 ACT-020 的 D-V5 决定 | W2~W5 | AC-53 |
-| 阶段开始的整理 | 见第 6 节 | C0 | 文档检查;报告的整理记录 |
-
-**阶段完成的判定**:B 自检的必测用例(第 7 节)与门禁全部通过,A 集中审查收敛后,才可以请用户授权 push、PR 与合并。ACT-020 与人工检查不是合并的前提;ACT-020 没做时,报告与交付状态必须写明“我的”只经合成验证,AC-46~51 的真实站点部分为 `not-run`。
-
-**阶段完成后,用户可以:** 点图标栏“我的”,展开哔哩哔哩看自己的关注(按分组)、收藏夹、稍后再看、历史记录,展开抖音看自己的关注、喜欢、收藏;点任何视频、作品或用户打开详情,返回时回到原位;在条目的“⋯”里缓存、复制链接、在浏览器中打开,把关注的人加入订阅。
-
-## 2. A 已核对的现场(2026-11-14,`main @ f080483`)
-
-- **Git**:`main` 与 `origin/main` 一致,工作区干净;远端只有 `main`(M3 分支已清理)。
-- **界面骨架**:路由常量在 `internal/ui/app.go:32`(`RouteHome`…`RouteLogin`),图标栏条目 `mainNavItems`(`internal/ui/views.go:25`,五项),图标栏绘制 `renderRail`(`internal/ui/shell.go`),侧栏宽度按路由 `contextPanelWidth`(`shell.go:18`),页面限宽 `pageWidth`。打开详情时图标栏把 `RouteVideo/RouteUser/RouteDouyinWork/RouteDouyinUser` 算作“解析”高亮。返回只有一级 `PreviousRoute`(`app.go:946`、`NavigateBack` `app.go:980`),所以“我的”必须自己在内存里保存列表与滚动位置,不能依赖返回链。
-- **打开详情**:界面 `openLink`(`app.go:1350`)调用 `backend.OpenLink`,后者在 `service/backend.go:1148` 起解析并写最近解析(`history.Record`)与信息流条目。“我的”的条目一律走这条路径(FR-ACCT-003)。
-- **可复用的列表行**:哔哩哔哩投稿紧凑行 `renderUserVideoRow`(`views.go:1361`,目前绑 `bilibili.UserSpace`/`UserVideoItem`)、列表结尾与错误 `renderUserListEnd`/`renderUserListError`(`views.go:1184`、`:1349`)、抖音 3:4 卡片 `renderDouyinWorkGridCard`(`douyin_views.go:1262`,绑 `DouyinUserView`)。W4 要把它们抽成与数据来源无关的版本,用户页与“我的”共用,用户页外观不变。
-- **服务层**:`BackendAPI`(`service/backend.go:275`)由 12 个服务接口组成;已有 `FollowingService.RelationTags/RelationFollowings`(哔哩哔哩关注,`site/bilibili/relation.go`,ACT-005 真实检查过);`HistoryService` 是“最近解析”,“我的”的历史要另起名(如 `WatchHistory`),不要混用。
-- **哔哩哔哩客户端**:`doBiliJSON`(`client.go:479`)、`RequireAuth`(`:255`)、WBI 签名 `SignWBIParams`(`wbi.go:54`)与密钥缓存已有;500 毫秒全局间隔已有。
-- **抖音客户端**:`doAPIRequest`(`client.go:496`)只发 GET,`apiRequestSpec`(`:430`)没有方法与请求体;签名器 `sign.SignInput` 已有 `Body` 字段,`buildABogus` 已对请求体做 SM3(附录 A 的 `db`,`sign.go:203`、`:486`);受保护路径表已含 `favorite`、`listcollection`、`collects/list`、`collects/video/list`([抖音协议 附录 A.7](../research/douyin.md#sign-spec))。登录账号的 `sec_uid` 在凭证状态里(`credential.Status.SecUID`)。
-- **工具**:`tools/actcheck` 已有 `act010`~`act019` 的写法(账本、发出前拒绝超额、程序写回执、脱敏扫描);`tools/uishots` M3 结束时 36 个场景、108 张 PNG;`tools/check` 是唯一门禁入口。
-- **真实站点**:本阶段对两个站点的账号列表接口 0 次请求。`.env.local` 已有两站点测试 Cookie 的路径变量;哔哩哔哩测试 Cookie 上次成功使用是 2026-11-08(ACT-007),是否仍有效未知。
-- **本机参考**:找到索引(仓库外)。“用户视频列表解析”与“抖音签名与访问上下文”两个领域的本地副本(2026-11-09)覆盖抖音的喜欢、收藏、收藏夹、关注;哔哩哔哩的收藏、稍后再看、历史没有登记参考,A 查了 GitHub(第 3 节)并在索引旁 `PROPOSALS.md` 追加了 P-013。
+| 远程程序可打包、在 Linux 上运行 | `cmd/trace-server` 的 `init/run/token/upload-test/version/rclone-filter`;不链接 MyGo;`linux/amd64`、`arm64` 包 | W2、W3、W8 | AC-56、AC-57 |
+| 远程接口安全 | HTTPS 自签名 + 指纹、令牌哈希、失败限流、版本握手、日志无敏感内容 | W3、W5 | AC-57、AC-58 |
+| 订阅同步与远程规则 | 快照整体替换;起点;按规则缓存与录制;不做全部缓存 | W2、W3、W7 | AC-59 |
+| Cookie 推送 | 校验后保存、不续期、本地续期后自动推送与待同步重试、失效停站点 | W2、W3、W5 | AC-60 |
+| 上传 | 按条目先媒体后 `item.json`、确认后删除、重试与说明;兼容外部 `rclone move` | W1、W4 | AC-61 |
+| 远程状态 | “设置 › 远程”的全部状态与错误分类 | W3、W5 | AC-58 |
+| 资源库导入导出 | 预览六类、冲突三种处理、校验、可中断续做、导出 | W6 | AC-62、AC-63 |
+| 订阅导出导入 | `trace-subscriptions.json` 与预览 | W7 | AC-63 |
+| 集群预留 | 节点 ID、`cachedBy`、按条目合并 | W1、W6 | AC-64 |
+| 整理与依赖 | 第 6 节 | C0、D1 | 文档检查;报告的整理记录与盘点结果 |
+
+**阶段完成的判定**:B 自检的必测用例(第 7 节)与门禁全部通过,A 集中审查收敛后,才可以请用户授权 push、PR 与合并。H-003 不是合并的前提;没做时,报告与交付状态必须写明远程版只经本机、CI 与(若有)WSL 验证,真实 VPS、真实站点与 Google Drive 部分为 `not-run`。
+
+**阶段完成后,用户可以:** 在 VPS 上解压 `trace-server`、`init` 拿到连接码、装 systemd 服务;在本地“设置 › 远程”粘贴连接码,看到远程状态,同步订阅与 Cookie;远程按订阅规则缓存新内容与录制,并用 rclone 上传到 Google Drive、删掉 VPS 上已上传的文件;把网盘上的文件夹下载下来,在媒体库“导入”,按预览处理冲突后导入;导出订阅与资源库给另一台 TRACE。
+
+## 2. A 已核对的现场(2026-11-19,`main @ 8327803`)
+
+- **Git**:`main` 与 `origin/main` 一致;远端还有 Dependabot 分支(PR #9,`golang.org/x/image` 0.47.0 → 0.48.0)。
+- **无 GUI 后端**:`go list -deps ./internal/service` 不含 MyGo;`GOOS=linux GOARCH=amd64 go build ./internal/service/ ./internal/library/ ./internal/subscription/ ./internal/live/ ./internal/download/` 成功。合并(`internal/download/mux*.go`,mp4ff)、SQLite(`modernc.org/sqlite`)都是纯 Go。`tools/check` 已在 `main.go:228` 一带检查 MyGo 只出现在允许的包里。
+- **入口**:只有根目录 `main.go`(桌面,`shell.Run()`);没有 `cmd/`。`service.NewBackend(Options)`(`internal/service/backend.go`)一次建好全部组件并启动后台循环:续期 `runRenewalLoop`(`backend.go:772`)、全部缓存 `runFullCacheLoop`(`account_works.go`)等;`Options` 已有 `Locations`、`Desktop`、`DisableBgWorkers` 等注入点。`NewDefaultDesktop` 在非 Windows 上会调用系统程序,远程要注入空实现。
+- **Linux 平台文件**:`appdirs/lock_other.go` 是真正的 `flock` 独占锁;`appdirs/knownfolder_other.go` 用 `~/Documents`,远程不能用它(数据与导出目录由命令行给出);`credential/dpapi_other.go` 用常量派生的固定密钥,只适合测试,远程必须换成随机密钥文件(W2)。
+- **条目清单**:`library.ItemMetadata`(`internal/library/schema.go:17`)的 `media[]` 已有 `path`、`bytes`、`sha256`;直播每段收尾时算 SHA-256([直播 §2 第 6 步](../design/live.md))。`item.json` 可直接当导入清单。
+- **临时文件名**:下载与录制用 `<正式名>.part`;合并用 `.trace-mux-*.part`、`.trace-progressive-*.part`;但 `storage.WriteFileAtomic`(`internal/storage/atomic.go:22`)与 `storage/schema.go:314` 用 `<正式名>.tmp--<随机>`,凭证用 `.tmp-cred-*`,抖音还有 `.raw`、`.imgtmp`、`.audtmp` 等后缀(`internal/download/douyin.go:1486`),这些不满足“`*.part` 或 `.trace-*`”的统一排除规则(W1)。
+- **续期与登录**:续期在服务层 `tryScheduledRenewal`(`backend.go:818`),登录在 `AuthService`;自动推送 Cookie 挂在这两处成功之后(W5)。
+- **CI**:`.github/workflows/ci.yml` 的 `repository-quality` 在 Ubuntu 上运行 `go run ./tools/check`,所以新增的跨平台测试会在真实 Linux 上跑。
+- **本机参考**:索引里“多平台无界面录制(以后 Linux/headless)”一项(GPL,只参考思路,本地副本 2026-11-10):它的上传也放在“录制处理完成之后”,并把上传后删除作为开关,与本设计一致;没有可复用的代码,仓库不写它的名字。
## 3. 依据、查证与选型
-- **不引入依赖**:全部是站点协议与界面工作,复用标准库与已有模块(`mygo/ui`、`site`、`service`)。没有需要选型的通用能力。
-- **哔哩哔哩协议事实**(2026-11-14,GitHub REST):社区接口文档仓库 `SocialSisterYi/bilibili-API-collect` 已归档并清空(默认分支 `deprecated` 只剩 `README.md`),不能再作来源;改按一个活跃的第三方哔哩哔哩客户端(GPL-3.0,2026-11-13 仍有提交,未归档)的请求与模型核对,另参照本机参考里多站点订阅项目的收藏夹与稍后再看路由(AGPL)。结论写在[哔哩哔哩协议 §21](../research/bilibili.md#account-lists)。两者都是 GPL/AGPL:**只取协议事实,不复制代码**。
-- **抖音协议事实**:本机参考里两个抖音项目(MIT 与 Apache-2.0,本地副本 2026-11-09,GitHub 上 2026-11-13、2026-11-09 仍有推送)。按 [DEC-044](../decisions.md#dec-044),事实已写进[抖音协议 §12](../research/douyin.md#account-lists),B **只按文档独立实现**,不照搬参考实现的结构与命名。
-- **未知项**:协议两节的“待真实检查”清单(B-V1~4、D-V1~5)。抖音观看历史只有路径名,没有参数与结构;抖音稍后再看在网页检索与两份参考里都没有接口,不做(DEC-047)。
+- **不引入新的 Go 依赖**:HTTPS、自签名证书、令牌与指纹用标准库 `crypto/tls`、`crypto/x509`、`crypto/ecdsa`、`crypto/sha256`;HTTP 用 `net/http`;调用 rclone 用 `os/exec`。
+- **上传工具 rclone**(2026-11-19 查询):GitHub `rclone/rclone`,MIT,未归档,2026-11-18 仍有推送,最新发行 v1.76.0(2026-11-06)。官方文档:`rclone move` 只在复制没有错误时删除源文件,空目录要 `--delete-empty-src-dirs`(rclone.org/commands/rclone_move);本地后端在上传中发现文件变化会以 “can't copy - source file is being updated” 中止(rclone.org/local);`--min-age` 只作用于文件(rclone.org/filtering);Google Drive 每天 750 GiB 上传上限,共用的 client_id 2026 年内停用、需要用户自己的 client_id,每个 client_id 默认每秒约 10 次请求(rclone.org/drive)。结论:rclone 作为用户机器上的外部程序,TRACE 不打包、不读它的配置;Google Drive 授权完全交给 `rclone config`。
+- **不直接对接 Google Drive 接口**:要自己处理 OAuth(无界面机器上的授权)、令牌保存与续期、断点续传、限速与每日上限;收益只是少装一个 rclone,风险大,不做(DEC-062)。
+- **远程网页不做**:用户只要求本地软件连接远程;[架构 §9](../design/architecture.md#headless-ext)保留以后的选项。
-## 4. 设计要点
+## 4. 实现指引
-### 4.1 站点层(W1、W2)
+设计以[远程设计](../design/remote.md)为准,下面是 A 对实现的约束与建议,B 可以选更好的做法,但要在报告里写明。
-- 新文件 `internal/site/bilibili/account.go` 与 `internal/site/douyin/account.go`,只放请求、解析与错误分类,返回站点自己的结构;不依赖 `service`、`ui`、`library`(`tools/check` 的依赖方向照旧)。
-- **哔哩哔哩**:`FavFolders(ctx, mid)`、`FavResources(ctx, mediaID, pn)`、`ToView(ctx, pn, viewed)`(WBI)、`WatchHistory(ctx, cursor)`;关注复用 `RelationTags/RelationTagUsers/RelationFollowings`。`id`、`media_id`、`oid`、`kid` 按 int64 或字符串解析,不经浮点。失效(`attr` 1/9)、类型(`type` 2/12/24,`business`)、进度(`-1` 看完)在站点层归一。游标与“到底”规则按协议 §21:`has_more=true` 而空列表、历史游标不前进都返回 `schema_changed`。
-- **抖音**:`apiRequestSpec` 加 `method`、`form`(有序参数对)与额外请求头;POST 时把编码后的表单体交给签名器的 `Body`,`Content-Type: application/x-www-form-urlencoded`,查询串照旧签名;GET 行为与字节完全不变(已有签名向量全部通过)。`Followings(ctx, secUID, maxTime)`、`Favorites(ctx, secUID, cursor)`、`Collection(ctx, cursor)`(POST)、`CollectFolders(ctx, cursor)`、`CollectFolderWorks(ctx, collectsID, cursor)`;作品条目复用已有 `aweme` 解析。第 1 页空壳与 `aweme_list: null` 按[抖音协议 §12](../research/douyin.md#account-lists)判为登录失效或被拦截,有 `has_more` 的空列表才算空。`WatchHistory` 只在 ACT-020 的 D-V5 通过后实现(第 4.4 节)。
-- 两站点的这些请求都是**用户操作触发的手动请求**:走各自的全局间隔、登录检查与熔断(熔断打开时直接返回原因),不计规则每小时额度,不自动重试。
+### 4.1 包与依赖方向
-### 4.2 服务层 `AccountService`(W3)
-
-- 新文件 `internal/service/account.go`,接口按[架构 §3](../design/architecture.md#services):`Sections(site)`、`Folders(site, kind)`、`Page(site, kind, folderID, cursor)`,`BackendAPI` 组合它。DTO 放 `dto.go`:`AccountSection{site, kind, label, available, reason}`、`AccountFolder{id, title, count, private, isDefault}`、`AccountPage{items, cursor, hasMore, total}`、`AccountItem`(字段见架构表),视频与作品带 `cacheKey`(与用户页同一个键生成函数,圆点用 `CacheService.States`),用户带 `accountKey` 与所属订阅(`OwnerOfAccount`)。
-- 站点未登录或失效时 `Sections` 只返回一个 `available=false` 的条目与原因,`Page` 在发请求前返回 `auth_required`。
-- **隐私**:服务层不缓存、不写文件、不写信息流与最近解析(打开详情时由 `OpenLink` 照常写);日志只记 `account.. page=N items=M` 与错误类别,不记标题、昵称、ID、游标值。
-- 抖音“观看历史”在 `Sections` 里由一个包内常量开关控制(默认关),D-V5 通过后 B 打开并补实现与测试;不通过就保持关闭并登记 LOOP。
-
-### 4.3 界面(W4)
-
-- 路由 `RouteMine = "/mine"`;`mainNavItems` 在“订阅”后插入 `{RouteMine, "mine", "我的"}`,新线性图标按[界面 §2](../ui.md#nav)的描边规范画(书签或人形,B 选一个与现有图标风格一致的)。`contextPanelWidth` 对 `RouteMine` 与主页同宽;窄窗时页面内显示选择列表([界面 §3.11](../ui.md#mine))。
-- 状态全部在 `App` 内存里:展开的站点、选中的功能,以及每个“站点 + 功能 + 收藏夹/筛选”的列表状态(条目、游标、是否还有、加载中、错误、滚动偏移、请求代号)。同一列表同时只有一个请求;后发的覆盖先发的;离开页面不取消已发的请求,但结果只写回它自己的列表。`auth:changed` 时清空该站点的全部列表与选中项。
-- 行与卡片复用 4.1 节提到的组件(抽出与数据来源无关的版本);“⋯”菜单项与动作复用已有实现(缓存、复制链接、在浏览器中打开、加入订阅对话框)。点击条目调用已有的 `openLink`,从而记入最近解析、按“点开即跳转”显示。
-- 浏览器入口只接受 `https://` 且主机在站点白名单(`bilibili.com`、`b23.tv`、`douyin.com`)内的地址。
-
-### 4.4 抖音观看历史的条件流程
-
-B 完成 W2 的合成测试后先跑 ACT-020(不必等界面)。D-V5 返回 `aweme_list` 与 `has_more`:把参数与字段补进[抖音协议 §12](../research/douyin.md#account-lists),实现 `WatchHistory` 与夹具,打开开关,UI 按“喜欢”的网格显示。否则:保持关闭,协议 §12 写明现象,在[交付状态 LOOP](status.md#loop) 加一条,在 Q-015 第 3 条写结果。两种结果都不影响阶段完成。
-
-## 5. 工作包
-
-| 工作包 | 预期结果与关键失败路径 | 完成证据 |
+| 包 | 内容 | 可以依赖 |
| --- | --- | --- |
-| C0 阶段开始的整理 | 按第 6 节处理 | 报告的整理记录;`go run ./tools/checkdocs` |
-| W1 哔哩哔哩账号列表客户端 | 第 4.1 节四个函数;夹具覆盖:收藏夹默认/私密位、空收藏夹(`data=null`)、失效条目、音频与番剧类型、`bv_id` 别名;稍后再看 WBI 参数与签名、`viewed=2`、`progress=-1`、`is_pgc`;历史游标三元组推进、`business` 各类、游标不前进 → `schema_changed`;`-101` → 失效、`-352/-412` → 风控、HTTP 412、超大响应、非 JSON | `go test ./internal/site/bilibili/...` 中新增的 `TestFav*`、`TestToView*`、`TestWatchHistory*` |
-| W2 抖音账号列表客户端 | `apiRequestSpec` 支持 POST 表单且 GET 字节不变;POST 表单体进入 `a_bogus`(用固定时钟与随机源的向量证明表单体变化会改变签名,GET 向量不变);关注 `min_time`→`max_time` 推进与不前进停下;喜欢/收藏/收藏夹的 `cursor`/`max_cursor` 两种字段;`collects_id_str` 优先;0 字节、`aweme_list:null`、无 `has_more` 的第 1 页判失效或拦截;网关拦截、验证页、HTTP 403/429 分类;请求不带 `x-secsdk-csrf-token`、带协议要求的 `Referer` | `go test ./internal/site/douyin/...` 中新增的 `TestFollowings*`、`TestFavorites*`、`TestCollection*`、`TestCollectFolder*`、`TestPOSTSign*`;已有签名测试不改断言 |
-| W3 `AccountService` | 第 4.2 节;未登录、失效、熔断在发请求前返回;条目归一(可打开/失效/不支持、`browserURL` 白名单、`cacheKey` 与订阅归属);不写文件、不写最近解析;日志不含哨兵标题与昵称;退出登录后再请求返回 `auth_required` | `go test ./internal/service/...` 中新增的 `TestAccount*`(含隐私哨兵:浏览后扫描数据目录与日志) |
-| W4 “我的”界面 | 第 4.3 节与[界面 §3.11](../ui.md#mine);三档宽度无横向溢出;手风琴折叠;首次选择才请求;滚到底加载、同列表不并发;切换功能与从详情返回不重新请求、滚动位置保留;“刷新”从第一页重来;错误与空、到底分开;失效条目不可点;“⋯”动作复用;退出登录清空;输入法与键盘可用(组合输入时回车不提交、Esc 关菜单、焦点可见) | `go test ./internal/ui/...` 中新增的 `TestMine*`;`tools/uishots` 新场景(第 7 节) |
-| W5 工具 | `tools/actcheck -act act020`(账本、额度、停止条件、程序写出的回执、脱敏扫描:回执里没有标题、昵称、ID、Cookie);`tools/uishots` 加“我的”场景并做断言;测试安静、不抢焦点、不碰已安装的 TRACE | `go test ./tools/...`;`artifacts/site-check/act020.json`(或 `not-run` 记录);`artifacts/uishots/` |
-| W6 文档 | 需求 §2.9 状态、路线 AC-45~53 状态、交付状态“已实现能力”、协议两节按真实检查结果改标记(核/未)、Q-015 第 3 条结果、H-001 第 28 步核对、工程规则里的场景数 | `go run ./tools/checkdocs` |
-| D1 依赖盘点与漏洞修复(2026-11-14 B 开工后追加,DEC-048) | 按[依赖盘点](../dev-rules/workflow.md#dependency-inventory)执行。追加时(2026-11-14)`go run ./tools/deps -audit` 失败:`GO-2026-6859`(标准库 `net/http`,代码实际调用)在 Go 1.27.4 修复;盘点满 7 天的有 `go` 行 1.27.3 → 1.27.4、`golang.org/x/sys` v0.49.0 → v0.50.0。把 `go.mod` 的 `go` 行升到 1.27.4、升级 `x/sys` 后 `go mod tidy`,跑 `go run ./tools/check`;`x/sys` 涉及 `appdirs`、`credential`(DPAPI)、`library`(长路径),相关测试必须通过。交付前复跑盘点,届时满 7 天的也升级(追加时未满的有 `mp4ff` v0.63.0、`mygo` v0.9.0、`x/image` v0.48.0);0.x 的次版本升级视同不兼容升级,尤其 `mygo`(界面框架与打包工具)要单独升级并跑 `uishots`、打包与冒烟,失败回退并在报告写明。没升的写原因;不登记漏洞例外,除非确实无法修复 | `go run ./tools/deps -audit` 为 `passed`;`go run ./tools/deps` 的交付前输出与处理结果写进报告 |
-
-注明:连续完成全部范围、自测和修复,不逐包请求继续;需要用户的事写进 USER-ACTIONS,非阻塞的先按默认值实现,真正的阻塞只暂停依赖部分。
-
-## 6. 阶段开始的整理(C0)
-
-| 对象 | 处理 |
-| --- | --- |
-| 上一阶段的计划与报告 | A 已用本计划替换 M3 计划,并把报告换成 M4 的空报告;M3 原文在 `f080483` 的固定链接里。仓库内指向它们锚点的链接 A 已改成固定链接(`decisions.md` 的 DEC-043、DEC-046,`USER-ACTIONS.md`,`status.md`)。B 复查是否还有指向 `stage-plan.md#`/`stage-report.md#` 旧锚点的链接 |
-| 文档里以前阶段的标签 | `docs/research/2026-11-12-douyin.md`(约 26 处)、`docs/research/douyin.md`(约 14 处)、`docs/design/architecture.md`、`docs/dev-rules/engineering.md`、`status.md` 的 LOOP-013,以及 `decisions.md` 里 DEC-027、DEC-034、DEC-041 仍指向“当前计划”的链接:改成直接描述能力或固定链接;决定的“来源”列与研究资料里的日期记录保持原样。USER-ACTIONS 里 H-001 第 26 步的“(M3)”改成“(抖音)” |
-| 生成物 | `artifacts/review/`(2026-11-09 的旧审查日志):删除;`artifacts/release/`:只留最新一份,属于发布工具的产物,不动;`artifacts/site-check/`:回执是真实检查的证据,保留;`artifacts/uishots/`、`artifacts/smoke/`、`artifacts/package/` 由工具覆盖为最新一份;`dist/` 只留两个通道各最新一份 |
-| 代码注释 | 按 LOOP-007,改到的文件里顺手清掉旧的计划与问题编号 |
-| A 的临时草稿 | `.local/m4/`(A 规划时的草稿,Git 忽略):B 开工时删除 |
-
-不得删除:`.env.local`、`.local/site-secrets/`、`.local/site-check/` 的对象与账本、用户数据、许可证与第三方声明。
-
-## 7. 必测用例
-
-| 编号 | 场景 | 证据 |
-| --- | --- | --- |
-| M4-K01 | 哔哩哔哩收藏夹:默认在前、私密标记、空收藏夹为空不是错误、失效条目不可打开、`type=12/24` 只给浏览器、两页无重复 | W1、W3 单测 |
-| M4-K02 | 哔哩哔哩稍后再看:WBI 签名参数正确(固定密钥与时间的向量)、`viewed=2`、进度与“已看完”、`count` 判到底 | W1 单测 |
-| M4-K03 | 哔哩哔哩历史:游标三元组推进、两页无重复、`archive`→视频、`live`→主播用户页、其他→浏览器;游标不前进时 `schema_changed`,最多 1 次额外请求 | W1、W3 单测 |
-| M4-K04 | 哔哩哔哩关注:分组筛选、订阅归属、加入订阅后归属更新 | W3、W4 单测 |
-| M4-K05 | 抖音 POST 表单:签名覆盖表单体;GET 已有向量字节不变;请求头与 `Referer` 正确 | W2 单测 |
-| M4-K06 | 抖音关注:`max_time` 游标推进与不前进停下;`sec_uid` 作为打开与订阅的键 | W2、W3 单测 |
-| M4-K07 | 抖音喜欢与收藏:`cursor`/`max_cursor` 都认、`collects_id_str` 优先、第 1 页空壳判失效而不是空、真正空列表显示空 | W2、W3 单测 |
-| M4-K08 | 风控与错误:两站点的风控、限流、网络、失效、格式变化分别分类;不自动重试;熔断时不发请求;一个站点熔断不影响另一个站点的“我的” | W1~W3 单测 |
-| M4-K09 | 未登录与失效:`Sections` 只给登录入口;`Page` 发请求前拒绝;`auth:changed` 后界面清空该站点列表 | W3、W4 单测 |
-| M4-K10 | 隐私哨兵:用带哨兵标题与昵称的夹具浏览全部功能后,数据目录、缓存目录与日志里没有哨兵;最近解析只在点开详情后出现那一条 | W3 单测 |
-| M4-K11 | 界面:默认折叠、手风琴、首次选择才请求、滚到底加载且不并发、切换与返回不重复请求、滚动位置保留、“刷新”重来 | W4 单测 |
-| M4-K12 | 点开:视频、作品、用户分别走 `OpenLink` 打开正确页面并记入最近解析;失效条目点击无动作 | W4 单测 |
-| M4-K13 | 三档宽度截图与断言:折叠态、B 站收藏夹(含失效行与私密收藏夹下拉)、稍后再看、历史分组、关注、抖音喜欢网格、抖音收藏下拉、未登录、风控错误、窄窗选择列表;无横向溢出 | `tools/uishots` |
-| M4-K14 | ACT-020:1 次只读检查,按停止条件停;回执由程序写出且脱敏扫描干净;结论回写协议两节 | `artifacts/site-check/act020.json` 或 `not-run` 记录 |
-| M4-K15 | 回归:已有全部测试、截图场景与冒烟通过;用户页的投稿行与抖音作品卡片外观不变(截图断言) | `go run ./tools/check`;`tools/uishots`;`tools/smoke` |
-
-## 8. MVP 与 LOOP
-
-- 本阶段贯通[路线 §3](roadmap.md#mvp-loop)“我的”一行的“MVP 必须”。
-- 可以记为 LOOP 的深化:一键缓存整个收藏夹或稍后再看;收藏的合集、追番追剧、抖音收藏的合集与音乐;抖音观看历史(D-V5 不通过时);列表搜索与排序切换;在“我的”里批量加入订阅。
-- 不能记为 LOOP:任何一个功能的翻页、错误分类、空与到底的区分、点开详情、隐私(这些是 MVP 底线)。
-
-## 9. 交付与验证
-
-- 依赖(D1,追加):交付前跑 `go run ./tools/deps` 与 `go run ./tools/deps -audit`,`-audit` 失败不能交付;联网失败记 `not-run`。**A 审查时专门复核 D1**:它是 B 开工后加进计划的,B 可能没读到;没做或没做完时,A 按审查规则直接补做(局部、可自测),并在报告的审查部分写明。
-- 门禁:`go run ./tools/check`(含 `checkdocs`、`go vet`、`go test`、依赖方向);Linux `go vet` 交叉检查;`go run ./tools/uishots -out artifacts/uishots`;`go run ./tools/smoke -pkg dist/trace-dev -out artifacts/smoke`。
-- B 交付整个阶段时执行 `go run ./tools/package -install` 把最新开发版装到本机,版本写进报告与交付消息([工程规则 §2.2](../dev-rules/engineering.md#dev-install))。
-- 报告 `docs/delivery/stage-report.md` 按[交接模板 §2](../templates/agent-handoff.md)写:工作包 → 实现位置 → 实际命令与证据 → 状态与限制;附整理记录、ACT-020 结果、not-run 与限制、给 A 的审查 prompt。
-- 提交:全部 amend 进本计划所在的阶段提交(DCO),收尾时把提交消息改写为对最终结果的描述,例如 `feat(m4): browse the signed-in accounts' lists under 我的`。
-
-
-## 10. 给 Agent B 的交接 Prompt
-
-```text
-你是 TRACE 的 Agent B,负责连续实施 M4(我的:登录账号的站点内容)。
-
-计划:docs/delivery/stage-plan.md(TRACE-M4-01 修订 1)。先按 AGENTS.md 读入口文档,再读计划引用的正本:
-DEC-047、需求 §2.9(FR-ACCT-001~005)、路线 AC-45~53、界面 §3.11、架构 §3 的 AccountService、
-哔哩哔哩协议 §21、抖音协议 §12、USER-ACTIONS 的 Q-015 与 ACT-020。
-
-分支 codex/m4-account,基点 main @ f080483;分支上第一个提交是 A 的计划提交,你的全部实现、文档与修复
-都 amend 进这一个 DCO 提交(git commit --amend -s)。开工时核对一次分支、提交与工作区;.local/m4/ 是 A 的
-草稿,按 C0 删除。
-
-连续完成 C0、W1~W6 与必测用例 M4-K01~K15,不逐包请示:本地实现、合成夹具、测试、截图、打包、冒烟、
-文档同步都在授权内。抖音协议按 DEC-044 只按仓库文档独立实现,不照搬参考代码;GPL/AGPL 参考只读事实。
-W1、W2 的合成测试通过后先跑 ACT-020(常设授权内,1 次,额度见 USER-ACTIONS;Cookie 缺失或失效就记
-not-run 并写进“待你统一处理”),按计划第 4.4 节决定抖音观看历史。
-
-必须保留:M1~M3 的全部行为与测试、数据结构版本 2(本阶段不改数据文件结构)、按站点的间隔/额度/退避/熔断、
-凭证隔离与哨兵、安静测试、只删登记文件。不做任何写操作,不新增第三方依赖。
-
-交付前:go run ./tools/check、Linux go vet、tools/uishots、tools/smoke 全部通过;go run ./tools/package -install
-更新本机 TRACE Dev;按交接模板写 docs/delivery/stage-report.md(含整理记录、ACT-020 结果、not-run 与限制、
-给 A 的审查 prompt),同步需求/路线/交付状态/协议/USER-ACTIONS(H-001 第 28 步、Q-015)。
-未授权:push、PR、合并、标签、发布。最终回复给出交付 SHA、开发版版本号和一个首选下一步。
-```
-
-
-## 11. 修订 2:M4 实机反馈第一轮(2026-11-14)
-
-用户在 M4 交付后给了 8 条反馈。A 已直接修完其中 4 个缺陷和 1 个小调整,并查清了 1 个站点问题([阶段报告 §7](stage-report.md#feedback-1)):缓存规则展开后再缩起闪退(F-003)、直播录像转换失败(F-004)、抖音订阅头像重启后丢失(F-005)、哔哩哔哩实况照片不会动(F-006,改为翻到即播)、抖音“喜欢”空响应让“收藏”也失败(F-007)。剩下 3 条是界面与功能调整([DEC-049](../decisions.md#dec-049) ①~③),由 B 在本阶段内连续实现,交付后 A 再集中审查。理解与默认值见 [Q-016](../../USER-ACTIONS.md#q-016)。
-
-### 11.1 工作包
-
-| 包 | 内容 | 主要位置 |
-| --- | --- | --- |
-| R1 解析页 | 上下文侧栏在解析页也显示(`renderContextPanel` 把 `RouteParse` 和视频、用户页一样交给最近解析侧栏)。侧栏标题“最近解析”,右侧一个“⋯”(全部清空,行内确认);每行是小封面或头像、单行标题、一行“类型 · 站点”,点行打开,悬停出现“⋯”(在浏览器中打开、删除;删除同时清对应缩略图);当前打开的条目高亮。主面板只剩一个**居中的大输入框**(最宽约 640px,高约 52px,全圆角,左侧当前账号头像,右侧强调色“立即解析”),像搜索引擎首页那样在页面竖直方向略偏上居中;识别失败的一句话说明在输入框下面;主面板不再列最近解析。回车、输入法组合时回车不提交、解析中禁用这些行为不变 | `internal/ui/views.go` `renderParseRoute`、`shell.go` `renderHistoryPanel` |
-| R2 媒体库离线 | ① 去掉“发布时间 / 缓存时间”切换,固定按发布时间从新到旧(录像按开播时间);已保存的旧排序偏好忽略,不报错。② 新增媒体库自己的本机详情路由(如 `/library/item`):“⋯ → 详情”在这里打开,内容复用现有本机内容详情的渲染,但图标栏仍高亮“媒体库”,上下文侧栏仍是媒体库侧栏,返回回到媒体库原来的筛选与滚动位置。③ 媒体库里的任何点击(缩略图、标题、详情里的图片和视频、录像分段)都不切到解析的路由,也不发站点请求;详情里需要联网的动作(缓存、补存、升级、刷新元数据)不显示,只在“⋯”里留一个“在解析页打开”作为用户明确选择的联网入口。④ 先复现用户说的“点视频或图片跳到解析页”,把所有从媒体库进入 `RouteVideo` / `RouteDouyinWork` 的路径列出来逐一改掉 | `internal/ui/library_view.go` `openLibraryTile`、`OpenLibraryItemDetail`、`shell.go` 图标栏高亮 |
-| R3 直播录制标签 | ① 图标栏“任务”的角标只数排队和进行中的缓存任务,不数录制(`activeWorkCount`)。② 任务页顶部两个标签“缓存”“直播录制(N)”,原来排在最上面的录制行移到“直播录制”标签;没有录制时写“现在没有直播在录制”。③ 在“直播录制”里点一场正在录制的直播,在页面里**实时播放录制中的画面**:读正在写入的录像文件(哔哩哔哩是 HLS fMP4 追加,抖音是 FLV 转写的 fMP4),**不另开站点连接**,离开标签、停止录制或这一段结束换段时停止或跟到新段;画面落后直播约 10 秒以内可以接受,打开后约 5 秒内出画。先做时限 1 天的技术验证:播放器能否读一个还在增长的 fMP4(例如给 `internal/player` 加一个读到文件末尾就等待新数据的读取方式);两条录制路径写出的 `.part` 是否都是可边写边读的分片 MP4。验证不通过的那条路径,界面照实说明“这场录制暂不支持实时预览”,记 LOOP,不用另开连接绕过。④ 实时弹幕不在本轮,预览区不画弹幕,也不显示弹幕开关 | `internal/ui/views.go` `renderTasksRoute`、`shell.go`、`internal/live`、`internal/player` |
-| R4 文档 | 按实现同步[界面规范](../ui.md) §2(任务角标)、§3.2(解析页)、§3.6(媒体库、任务页标签与实时预览);需求与路线如有新条目一并补;报告追加 B 的交付节 | `docs/` |
-
-### 11.2 必测用例(追加)
-
-| 编号 | 用例 |
-| --- | --- |
-| M4-K16 | 解析页主面板只有输入框(没有最近解析列表);侧栏列出最近解析,点行打开,“⋯ → 删除”删掉条目和它的缩略图;“全部清空”要行内确认 |
-| M4-K17 | 视频页、用户页、解析页三处侧栏是同一份最近解析列表,当前条目高亮 |
-| M4-K18 | 媒体库没有排序切换;带旧的“缓存时间”偏好启动时按发布时间排,不报错 |
-| M4-K19 | 从媒体库点视频、图片、录像分段、“⋯ → 详情”以及详情里的图片和视频,`CurrentRoute` 始终是媒体库的路由、图标栏高亮“媒体库”,假后端记录的站点请求数为 0;返回后筛选与滚动位置不变 |
-| M4-K20 | 只有录制在进行时,“任务”没有角标;有排队或进行中的缓存任务时角标只数这些 |
-| M4-K21 | 任务页两个标签,录制行只在“直播录制”里;点正在录制的直播开始实时预览,录像文件继续增长时画面跟着前进;离开标签或停止录制后预览停止、文件句柄释放(录像能正常转换和改名) |
-| M4-K22 | 实时预览期间站点请求计数不增加(只有录制本身的请求) |
-| M4-K23 | 回归:A 修的 F-003~F-007 的测试(`TestCacheRuleFoldsAgainWithoutCrashing`、`TestFinalizeLivePartTrimsSubFrameFragmentOverlap`、`TestRecoveryConvertsUnconvertedSegmentUnderFinalName`、`TestDouyinSubscriptionKeepsALocalAvatar`、`TestDouyinLikesRefusalLeavesTheSiteRunning`、实况照片自动播放)保持通过 |
-
-### 11.3 不在本轮
+| `internal/remote` | 协议类型(状态、快照、凭证推送、错误)、连接码编码与解码、固定指纹的 HTTPS 客户端 | 标准库、`internal/site`(只用站点 ID) |
+| `internal/remoteserver` | 证书与令牌生成、鉴权与失败限流、路由、把请求转到服务层 | `internal/remote`、`internal/service` |
+| `internal/upload` | 上传队列、调用 rclone、退避、上传记录 | `internal/library`、`internal/storage` |
+| `internal/transfer` | 资源库导入的扫描、判定、执行与导出 | `internal/library`、`internal/storage` |
+| `cmd/trace-server` | 命令行、`server.json`、信号处理、组装 | 上面这些与 `internal/service` |
-- 实时弹幕(哔哩哔哩直播弹幕的 WebSocket 协议、抖音直播弹幕的 protobuf 与签名):A 在下一阶段先写协议资料、选型(WebSocket 客户端优先用已在依赖图里的 `golang.org/x/net/websocket`,要另行查证)并申请真实检查,再交给 B。
-- 抖音“喜欢”的浏览器通道:等用户在 Q-016 第 1 条决定。
+订阅快照的生成与整体替换放在 `internal/subscription`(它拥有这些数据)。全部新包不依赖 MyGo;`tools/check` 增加 `go list -deps ./cmd/trace-server` 不含 MyGo、`internal/player`、`internal/ui`、`internal/shell` 的检查。
-### 11.4 交付
+### 4.2 远程运行配置(W2)
-同第 9 节:门禁、Linux vet、截图(解析页、媒体库详情、任务页两个标签各补一张)、冒烟、`go run ./tools/package -install`;报告追加“B:第一轮反馈的实现”一节和给 A 的审查 prompt;全部 amend 进同一个阶段提交。
+- `service.Options` 增加运行配置(如 `Profile: ProfileRemote`)。远程下:不启动续期循环、全部缓存循环、开发版安装与更新检查、最近解析与头像下载;“定时检查更新”总开关视为开;规则的 `fullCache` 忽略;入队“全部缓存”和手动缓存的服务方法返回明确错误(远程接口本来也不暴露);`Desktop` 注入空实现。
+- 保存位置固定为导出目录,用户设置里的 `cacheDir` 不生效;远程不做 `RebuildIndex` 以外的文件扫描(升级探测、丢失文件刷新、空间页统计不在远程运行)。
+- **文件可能被搬走**:远程判断“已缓存、已排过任务、录到第几段”只看数据库与录制状态(`updates.db` 的 `auto_task_id`、`library.db` 的索引与 `json_data`),不看文件是否还在。录制写新段、重写 `item.json` 之前 `MkdirAll` 条目文件夹。必须有测试:缓存与录制进行中把已完成的文件与 `item.json` 删掉,远程继续工作、不重复下载、下一次 `item.json` 仍列出全部已完成的段。
+- **Linux 凭证**:`dpapi_other.go` 改为用 `credentials/` 下随机生成的 32 字节密钥文件(`0600`,`init` 时生成,缺失时生成新的并让旧凭证读不出而按“没有 Cookie”处理),去掉固定派生密钥;Windows 不变。远程的凭证 `source` 记为 `remote_push`,不续期(`Renewal()` 返回不可用,原因“由本地续期”)。
-
-### 11.5 给 Agent B 的交接 Prompt
+### 4.3 远程程序与接口(W3)
-并入[第 12.5 节](#prompt-feedback-1b):第 11、12 节一起实施。
+- 连接码:`trace-remote:1:` 加 base64url 的 JSON(`url`、`token`、`fingerprint`、`name`);`init` 的 `--listen` 与可选的 `--public-address`(写进连接码的地址,默认用监听端口和本机首个非回环地址,打印时提醒按需改)。
+- 证书:ECDSA P-256 自签名,有效期 10 年;`token` 命令不换证书。本地客户端 `InsecureSkipVerify` 只能与“比较叶证书 SHA-256”的 `VerifyConnection` 一起出现,并有测试证明指纹不符时请求一个字节都不发出。
+- 失败限流按来源 IP 计数(不信任 `X-Forwarded-For`)。请求体上限 1 MiB,读写超时 30 秒。
+- 端点与状态内容见[设计 §3、§7](../design/remote.md#api)。状态由服务层已有的读取方法组装(检查计划、任务、录制、站点退避与登录),不为状态另发站点请求。
+- `run` 收到 `SIGTERM`/`SIGINT` 时走服务层的退出收尾(任务暂停、录制收尾,限时 30 秒)后退出码 0。
-
-## 12. 修订 3:第一轮反馈的补充(2026-11-15)
+### 4.4 上传(W4)
-用户又给了 4 条。A 已修 2 条([阶段报告 §7](stage-report.md#feedback-1)):托盘右键菜单只留“打开”“退出”、在指针处用系统原生菜单打开(F-008,DEC-050 ③);抖音用户页作品多时卡顿、“缓存更早的内容”后更卡(F-009:每帧为全部已加载作品读媒体库状态、每张可见卡片再读一次条目,改为只读可见行并按缓存状态版本缓存)。另外 2 条是 [DEC-050](../decisions.md#dec-050) ①②,和第 11 节一起由 B 实现;节奏的默认值见 [Q-017](../../USER-ACTIONS.md#q-017)。**第 11 节 R3 ② 的“任务页顶部两个标签”由本节 Q2 的侧栏代替**,R3 ①③④ 不变。
+- 数据:`library.db` 新表 `upload_files(item_key, rel_path, bytes, sha256, uploaded_at, PRIMARY KEY(item_key, rel_path))`(`CREATE TABLE IF NOT EXISTS`,结构版本不变)。
+- 触发:条目每次成功 `SaveItem`(包括直播每段收尾)后,把清单里还没上传的正式文件放进上传队列;启动时扫一次索引补上漏掉的。同一时间只有一个 rclone 进程。
+- 一批:`rclone copy <条目文件夹> /<相对路径> --files-from <临时清单> [--config <文件>] `,退出码 0 后再单独传 `item.json`;临时清单放在数据目录,不放导出目录。
+- 删除:开着 `deleteAfterUpload` 时,媒体文件在确认上传后经 library 的登记文件删除路径删除;`item.json`、封面与其他小文件等条目最终完成(不在录制、不在缓存、状态为完成或失败)且最后一版 `item.json` 已上传后再删,然后删空文件夹。索引里的条目保留(远程靠它判断已缓存)。
+- 错误分类:找不到 rclone、配置或远端错误、配额或限流(stderr 里的 `quota`/`rateLimit`/`upload limit` 等关键字)、网络、本地文件没了(不再重试这一个文件,状态说明)。stderr 只保留脱敏后的首行(去掉 URL 查询串与形如令牌的长串)。
+- 测试用假 rclone(测试二进制自身充当,按环境变量决定成功、失败、慢),不访问网络。
-### 12.1 设计要点
+### 4.5 临时文件名统一(W1)
-- **缓存队列任务**(服务层,新文件,如 `internal/service/cache_queue.go`):一个任务 = 一个账号的一个列表(哔哩哔哩“动态”或“投稿”,抖音“作品”)从最新往更早全部缓存。状态:排队中、进行中、等待(下次时间)、等待退避结束、已暂停、已完成(到列表末尾)、已停止(原因)。保存在数据目录的新文件(如 `cache-queue.json`,自带版本号;不改现有数据文件的结构,版本 2 不变),只存站点、账号 ID、名称、列表、翻页游标、计数、状态与时间,不存地址与凭证;重启后接着做。
-- **节奏**(默认值见 Q-017,集中在一处常量,测试可注入时钟与随机源):同一站点同时只跑一个队列任务,其余按加入顺序排队;每次只把 1 条未缓存的条目排进下载队列,**等它下载结束**再随机等一段(默认 40~150 秒),每缓存 15~25 条(随机)长歇 10~25 分钟;需要下一页时翻页(自动请求,计入站点每小时额度、遵守退避与熔断);遇到风控、限流、额度用完或站点退避就停在“等待退避结束”,退避过后再随机等 10~30 分钟继续;登录失效暂停,重新登录后继续;应用退出时停下、启动后随机等 1~5 分钟再继续。复用 `batch_cache.go` 已有的候选与翻页逻辑(已缓存或不能缓存的跳过并计数),不另写一套。
-- **入口**:用户页“⋯”的“缓存更早的内容”子菜单换成一项“全部缓存”(哔哩哔哩按当前标签是动态还是投稿;私密账号没有);这个列表已在队列里时换成“在缓存队列中查看”。点“全部缓存”后顶部提示“已加入缓存队列,会在后台慢慢缓存”,不弹确认框。`CacheOlderUserItems` 与 10 / 20 / 50 条的选项删掉,相应的测试改为覆盖新入口;FR-USER-004 与界面 §3.4 改写。
-- **Q2 任务页侧栏**:`renderContextPanel` 给 `RouteTasks` 一个侧栏:“下载任务(N)”(N = 排队与进行中)、“缓存队列”分组(每个队列任务一行:头像、名称、小字“已缓存 x · 跳过 y”与状态或下次时间,正在进行的高亮)、“直播录制(N)”。点“下载任务”页面显示现在的任务列表(“检查画质更新”“清除已结束”不变);点某个队列任务页面显示它的详情:名称与列表、状态与原因、计数、最近缓存的几条(点开本机内容)、操作“暂停 / 继续”“取消”(取消不删已缓存的内容);点“直播录制”显示第 11 节 R3 的录制与实时预览。窄窗时侧栏退回为页面顶部的分段选择。图标栏“任务”的角标仍只数排队与进行中的下载任务(不数队列任务等待中的条目,也不数录制)。
+- 条目文件夹与导出目录里的全部临时文件改为 `*.part` 或 `.trace-*`:`WriteFileAtomic` 改为同目录下 `.trace-<文件名>.-<随机>.tmp`;`storage/schema.go`、凭证的临时名同样处理(凭证不在导出目录,统一是为了规则简单);抖音的 `.raw`、`.imgtmp`、`.audtmp` 改为以 `.part` 结尾。旧名字的续传与清理识别保留一个版本,避免升级时丢掉进行中的下载。
+- 增加一个测试:在缓存、录制、合并、写清单的各个阶段截取条目文件夹的文件列表,凡不是正式文件的名字都匹配 `*.part` 或 `.trace-*`。
+- `item.json` 增加可选字段 `cachedBy`(`node`、`name`),节点 ID 存 `<数据目录>/node.json`(首次需要时生成);桌面与远程都写。
-### 12.2 工作包
+### 4.6 本地客户端与界面(W5)
-| 包 | 内容 |
-| --- | --- |
-| Q1 缓存队列 | 服务层任务、持久化、节奏与停止规则、事件;`BackendAPI` 增加列出、加入、暂停、继续、取消;用户页入口 |
-| Q2 任务页侧栏 | 侧栏、下载任务页、队列任务详情页、直播录制页(与第 11 节 R3 合并实现) |
-| Q3 文档 | 需求 FR-USER-004 改写、界面 §3.4 §3.6、数据设计(新文件)、订阅设计(与定时检查共用额度的说明)、交付状态 |
-
-### 12.3 必测用例(追加)
-
-| 编号 | 用例 |
-| --- | --- |
-| M4-K24 | 假时钟与固定随机源下,一个 300 条的列表按“入队 1 条 → 等下载结束 → 随机间隔”推进,间隔落在默认范围内、每 15~25 条长歇一次;任何时刻这个任务在下载队列里最多 1 条 |
-| M4-K25 | 翻页计入站点每小时额度;风控、限流、额度用完时进入“等待退避结束”,不再发请求,退避过后继续;另一个站点的队列不受影响 |
-| M4-K26 | 重启后任务与游标恢复,已缓存的不重复入队;登录失效暂停、重新登录后继续;暂停、继续、取消(取消不删已缓存的内容);同一列表重复加入只保留一个 |
-| M4-K27 | 用户页“⋯”只有“全部缓存”(或“在缓存队列中查看”),没有按条数的选项;私密账号没有 |
-| M4-K28 | 任务页侧栏三项与队列任务行;点哪项显示哪项;角标只数排队与进行中的下载任务 |
-| M4-K29 | 隐私:`cache-queue.json`、日志与事件里没有 Cookie、签名地址与查询串(扩展现有哨兵测试) |
-| M4-K30 | 回归:A 修的 F-008、F-009 的测试(`TestTrayMenuOnlyOpensAndQuits`、`TestDouyinWorkGridDoesNotReadTheLibraryEachFrame`)保持通过 |
-| M4-K31 | 冒烟连跑 10 次全部通过;若复现 LOOP-015 的 `StealFocusDetected`,查清是否由托盘原生菜单(F-008)引起并修复,查不清就在报告里写明现象与次数 |
-
-### 12.4 不在本轮
-
-- 队列的速度设置界面(先用 Q-017 的默认值;需要时再加到设置“缓存与下载”)。
-- 订阅的自动缓存改用队列节奏(订阅自动缓存只处理新动态,量小,保持现状)。
+- 服务层新增 `RemoteService`:读写连接(连接码或三项;令牌进凭证库,地址、名字、指纹进 `settings.json` 的 `remote`)、`RemoteStatus`、`SyncSubscriptionsToRemote`、`PushCredentialToRemote(site)`、`RemoveRemote`。错误分类:无法连接、证书变了、令牌错或被暂时拒绝、版本不同、远程拒绝 Cookie(附远程给的原因)。
+- 自动推送:续期成功、扫码或粘贴登录成功后,若配置了远程就异步推送;失败记“Cookie 待同步”(`settings.json` 里只记站点与时间),后台每 10 分钟与每次读远程状态时重试。退出登录不自动清除远程的 Cookie(“设置 › 远程”有“清除远程登录”)。
+- 界面:设置新增分类“远程”(`internal/ui/views.go:1524` 一带的分类表),内容按[设计 §7](../design/remote.md#status)。页面可见时每 30 秒刷新,离开即停;请求在后台执行,不阻塞界面。按[界面规范](../ui.md)的现有控件与文案风格;`docs/ui.md` 增加对应小节。
-
-### 12.5 给 Agent B 的交接 Prompt(修订 3,含第 11、12 节)
+### 4.7 资源库导入导出(W6)
-```text
-你是 TRACE 的 Agent B,继续 M4,实施第一轮实机反馈:计划 docs/delivery/stage-plan.md 第 11 节(修订 2)
-与第 12 节(修订 3),两节一起做;第 11 节 R3 ② 的任务页标签由第 12 节 Q2 的侧栏代替。
-
-先按 AGENTS.md 读入口文档,再读:DEC-049、DEC-050、计划第 11、12 节、阶段报告 §7(A 已修的 F-003~F-009)、
-界面规范 §2、§3.2、§3.4、§3.6、§3.10、需求 FR-USER-004、batch_cache.go、USER-ACTIONS 的 Q-016、Q-017。
-
-分支 codex/m4-account,在现有的阶段提交上继续;你的实现、测试与文档全部 amend 进这一个 DCO 提交
-(git commit --amend -s)。开工时核对一次分支、提交与工作区,保留已有改动。
+- `transfer.Scan(root)` 只读:找 `item.json`(深度与布局按 `<站点>/<作者>/<种类>/<条目>`,也接受选中 `library` 的上一层),解析、校验路径在条目内(INV-08 同样的规则),按[设计 §6.3](../design/remote.md#import)分类;对本地已有的条目只读索引与文件大小,SHA-256 只在需要比较时计算,并有进度与取消。
+- `transfer.Apply(plan, 选择, 选项)` 后台执行:复制到 `.part` → 校验 → 改名 → 合并并写 `item.json` → 更新索引与信息流。“用导入的”替换本地文件前,导入的副本必须已校验落盘;删除本地多余文件走登记文件删除(INV-09)。记录每条的结果,失败的条目不影响其他条目。
+- `item.json` 合并放在 `internal/library`(例如 `MergeItemMetadata(local, imported, mode)`),覆盖:分 P 并集、直播段并集按段号排序、`live.incidents` 去重并集、`media` 以实际存在且校验过的文件为准、状态重新计算(全部文件齐全才是完成,INV-06)。
+- 界面:媒体库“⋯”菜单加“导入…”“导出…”;导入是一个页面(选择文件夹 → 扫描进度 → 预览分组与冲突逐条或批量选择 → 开始);执行进度在任务页侧栏新增“导入”一项(与下载任务、缓存队列并列),结束后有结果摘要。导出:选范围(全部或当前筛选)与文件夹,作为同样的后台任务。
+- 导入不要求远程程序停下:未传完的条目只导入已校验的文件,下一次导入时这条变成“可补充”。
-连续完成 R1~R4、Q1~Q3 与 M4-K16~K31,不逐包请示:本地实现、合成夹具、测试、截图、打包、冒烟、文档同步都在授权内。
-R3 先做时限 1 天的技术验证(播放器能否读还在增长的 fMP4;两条录制路径的 .part 能否边写边读),
-不通过的路径照实说明并记 LOOP,不另开站点连接。缓存队列的节奏用 Q-017 的默认值,集中在一处常量,
-测试注入时钟与随机源,不真的等待。本轮不做实时弹幕,不新增第三方依赖,不发真实站点请求。
-
-必须保留:M1~M4 已有行为与测试(被 DEC-049、DEC-050 替代的除外,相应测试改写而不是删掉)、
-现有数据文件结构版本 2(缓存队列用新文件)、按站点的间隔/额度/退避/熔断、凭证隔离与隐私哨兵、
-安静测试(不抢焦点、不碰已安装的应用)、只删登记文件。
-
-交付前:go run ./tools/check、Linux go vet、tools/uishots(补解析页、媒体库详情、任务页三项的截图)、
-tools/smoke 全部通过;go run ./tools/package -install 更新本机 TRACE Dev;阶段报告追加“B:第一轮反馈的实现”
-(工作包 → 位置 → 命令与证据 → 状态与限制、not-run、给 A 的审查 prompt),同步需求、界面规范、数据设计、
-交付状态与 USER-ACTIONS(H-001 第 30 步)。
-未授权:push、PR、合并、标签、发布。最终回复给出交付 SHA、开发版版本号和一个首选下一步。
-```
+### 4.8 订阅快照、导出导入(W7)
-
-## 13. 修订 4:第二轮实机反馈(2026-11-15)
+- `subscription.Manager` 提供 `Snapshot()`(订阅、规则、设置的一部分,带摘要哈希)与 `ReplaceFromSnapshot()`(一次写入,保留按“站点 + UID”的账号状态);设置的那部分由服务层合并进快照。
+- 文件 `trace-subscriptions.json` 与远程同步用同一结构,`format`、`version` 不对就拒绝。本地导入走预览:新订阅、账号已在某个订阅里(默认跳过,可选合并进那个订阅)、规则同 ID 不同内容(保留本地 / 用导入的);确认后一次写入。导入的订阅不改变已有账号的检查起点。
+- 订阅页([界面 §3.9](../ui.md#subscriptions))的“⋯”加“导出订阅…”“导入订阅…”。
-用户装了 `0.1.2-dev.202611150933` 后给了 8 条反馈([DEC-051](../decisions.md#dec-051))。A 已直接处理 4 条([阶段报告 §10](stage-report.md#feedback-2)):删除作者最后一条后清掉空文件夹(②)、订阅图标橙点的悬停说明(④)、更新开发版时关闭并重开正在运行的 TRACE Dev(⑤,原有流程,本轮实测)与日志检查(下载进度刷屏、崩溃不留痕迹,已修)、订阅头像两站点都存本机副本并修好用户页订阅不带头像(⑥)。剩下 4 条(①③⑦⑧)由 B 在本阶段内连续实现;理解与默认值见 [Q-018](../../USER-ACTIONS.md#q-018)。基点是 A 本轮的阶段提交(见报告 §10)。
+### 4.9 打包与 CI(W8)
-### 13.1 设计要点
+- `go run ./tools/package -server`:交叉编译 `linux/amd64` 与 `linux/arm64`(`CGO_ENABLED=0`、`-trimpath`、与桌面相同的版本注入),输出到 `dist/trace-server/`(只留最新一份),每个架构一个 `trace-server-<版本>-linux-<架构>.tar.gz`,内含 `trace-server`、`trace-server.service`、`README.md`(中文部署说明:目录、用户、防火墙、`init`、systemd、rclone 配置与 client_id、外部定时 rclone 的排除规则、凭证保护的边界、换包升级),另有 `SHA256SUMS`。报告写两个程序与桌面程序的体积。
+- `tools/check`:上面的依赖检查;`GOOS=linux GOARCH=amd64` 与 `arm64` 构建 `./cmd/trace-server`。
+- `tools/smoke` 增加远程冒烟(可以是 `-server` 选项):在临时目录 `init` → 启动 → 用连接码读状态 → 同步一个合成快照 → 假 rclone 上传一个合成条目 → 收到信号后退出;Windows 本机与 Ubuntu CI 都能跑(Linux 下跑交叉编译的真程序,Windows 下跑本机构建)。本机有 WSL 时额外用 Linux 包跑一次,没有就记 `not-run`。
-- **U1 更新页**(DEC-051 ①):设置新增分类“更新”(放在“关于”之前,图标用现有的刷新类图标)。内容自上而下:
- - 当前版本卡片:版本、通道(正式版 / 开发版)、提交与构建时间。
- - 更新方式一句话:正式版“打开 TRACE 时每 24 小时自动检查一次(可在下面关闭),也可以立即检查”;开发版“开发版不会自己联网检查;Agent 打包后会自动安装,正在运行的 TRACE Dev 会先退出,装完在托盘打开”。
- - 正式版:上次检查(时间与结果:已是最新 / 发现 x.y.z / 失败原因)、下次检查时间、“立即检查”与原有的“自动检查更新”“自动下载更新”开关(从“关于”移过来,“关于”只留一行“版本与更新见‘更新’”)。开发版:不显示检查按钮与开关,显示“本机安装的开发版”(卸载项里的版本,与正在运行的版本不同时写“已安装更新的版本,重启 TRACE Dev 后生效”)。
- - **检查记录**(最近 20 次:时间、自动/手动、结果)与**更新记录**(最近 50 次:时间、从 X 到 Y、方式:自动更新 / 本机打包安装 / 手动安装)。
- - 记录存数据目录新文件 `update-history.json`(`version: 1`,原子写,更高版本拒绝、损坏备份后重建;不改现有数据文件结构)。更新记录在启动时由 `DecideStartup` 发现版本变化时写一条(开发版记“本机打包安装”;正式版有自动更新的重启标记时记“自动更新”,否则“手动安装”);检查记录由 `update.Controller` 每次检查结束时写(开发版没有检查记录)。只存版本、时间、方式与结果文字,不存下载地址。
-- **L1 录制不限数与录制异常**(DEC-051 ③):
- - 去掉同时录制数:设置“订阅与直播”里删掉“同时录制数”一行,`live.Manager` 的三处上限检查(手动开始、哔哩哔哩自动录制、抖音录制)删掉;`settings.json` 里的 `maxRecordings` / `live.maxConcurrentRecordings` 继续读入但不再使用(不报错、不改结构)。旧测试中断言上限的改为断言不限。
- - 录制异常事件(录制会话内产生,随录像条目保存在 `item.json` 的 `live.incidents`,可选字段,旧程序忽略;录制中的也在内存里实时可见):`reconnect`(断流后重新取流:断开时刻、恢复用时)、`lost_segments`(HLS 媒体序号跳号:丢了几段、按目标时长估算的秒数;FLV 断开到重连之间的空档秒数)、`slow`(连续 30 秒下载速度低于码率,记开始时刻与持续时长,恢复后结束)、`disk`(空间不足停止)、`convert_failed`(收尾转换失败,沿用 F-004 的原因)。每类相邻 1 分钟内的合并成一条,每场最多 200 条。不另发站点请求。
- - 界面:“任务 › 直播录制”页里每场录制(进行中与最近结束的)行上有异常时显示一个“⚠ N 处异常”小字;任务侧栏在“直播录制(N)”下加一项“录制异常(N)”(N = 最近 7 天有异常的录制场数,为 0 时显示但不带数字),点开页面按场列出(直播间、开始时间、异常列表:时间、类型的中文说明、影响时长),已结束的可点开录像详情(本机路由,同媒体库)。窄窗与侧栏一致退回为顶部分段选择。
-- **S1 订阅详情“内容 / 账号”**(DEC-051 ⑦):
- - 标签改为“内容”(默认)与“账号”。“内容”是这个订阅**全部关联账号**已缓存内容的信息流:与主页时间线同一套帖子渲染、虚拟化与“到底加载更早”,按发布时间从新到旧,只读本机(与主页“有更新”里点进某人的时间线同一数据源,按订阅的全部账号筛选);没有内容时写“还没有缓存这个订阅的内容”,并给“检查更新”(订阅“⋯”里已有)的提示文字,不加新主按钮。
- - “账号”合并原“直播”:每个账号一行,站点小字、头像、昵称、UID/抖音号,下面一行直播状态(未开通直播间 / 未开播 / 直播中“标题 · 清晰度”/ 录制中“已录 时长 · 大小”);行右侧在直播中时是“录制”(强调色)或“停止录制”,其余操作(打开主页、在浏览器中观看、用作头像、解除关联、刷新直播状态)收进行“⋯”。已录制的录像不在这里列(在“内容”里作为录像帖子出现)。底部“关联另一个账号”保持。
- - 旧 `SubDetailTab` 值 `live` 读入时当作 `accounts`。界面规范 §3.9 改写。
-- **S2 缓存规则批量指定订阅**(DEC-051 ⑧):设置“缓存规则”里每条规则展开后,在编辑器下方加“使用这条规则的订阅(N)”一行和“选择订阅…”按钮,弹出对话框:搜索框 + 全部订阅的复选列表(头像、名称,已在用这条规则的预先勾上,在用别的规则的写“当前:规则名”),“全选”“全不选”,底部“应用到 N 个订阅”。应用时一次写入(服务层新增 `SetSubscriptionsRule(ruleID, subIDs)`:把勾上的设为这条规则;原来用这条规则、这次取消勾选的改回“默认”规则),不是逐个调用。默认规则也能这样指定。订阅详情的规则按钮保持。
-
-### 13.2 工作包
+## 5. 工作包
-| 包 | 内容 | 主要位置 |
+| 工作包 | 预期结果与关键失败路径 | 完成证据 |
| --- | --- | --- |
-| U1 更新页 | 13.1 的“更新”分类、`update-history.json`、记录写入点 | `internal/update`、`internal/shell/updates.go`、`internal/service`(新文件读写与 `BackendAPI`)、`internal/ui/views.go` 设置 |
-| L1 录制不限数与异常 | 去掉上限;`live.incidents` 事件采集(HLS 跳号、FLV 重连空档、慢速、空间、转换);任务侧栏“录制异常”与页面 | `internal/live/{recorder,douyin_live,manager}.go`、`internal/library`(可选字段)、`internal/ui/tasks_view.go`、`settings` 界面 |
-| S1 订阅详情 | “内容”信息流与“账号”合并直播 | `internal/ui/subscriptions.go`、`feed.go`(复用按作者筛选的数据源)、`internal/service` 若需按订阅筛选的查询 |
-| S2 规则批量 | 规则编辑器下的批量选择对话框与 `SetSubscriptionsRule` | `internal/ui/rules_view.go`、`internal/subscription`、`internal/service` |
-| D2 文档 | 需求(FR-UPD、FR-SET-002、FR-LIVE-002、订阅详情与规则相关条目)、界面 §3.6 §3.9 设置、数据设计(`update-history.json`、`live.incidents`)、直播设计、交付状态、USER-ACTIONS H-001 第 31 步 | `docs/` |
+| C0 整理 | 第 6 节 | 报告整理记录;`go run ./tools/checkdocs` |
+| D1 依赖 | 处理 PR #9;`tools/deps` 盘点与 `-audit` | 报告的盘点结果 |
+| W1 临时名、节点与清单 | 所有非正式文件匹配 `*.part`/`.trace-*`;旧名可续传;`cachedBy` 与 `node.json` | K01、K02 |
+| W2 远程运行配置与凭证 | 远程不续期、不做全部缓存;文件被搬走后照常工作;Linux 凭证用随机密钥文件 | K03~K06 |
+| W3 `trace-server` 与接口 | 命令、证书、令牌、限流、版本握手、状态、快照替换、凭证推送与校验、信号收尾 | K07~K11 |
+| W4 上传 | 先媒体后清单、确认后删除、最终才删 `item.json`、重试与分类、重启补传 | K12~K14 |
+| W5 本地客户端与“设置 › 远程” | 连接、状态、同步、自动推送与待同步重试、错误分类、截图 | K15~K17 |
+| W6 资源库导入导出 | 扫描与六类判定、三种冲突处理、校验、中断续做、导出可再导入、两节点合并 | K18~K21 |
+| W7 订阅快照与导出导入 | 快照与替换、文件导出导入与预览 | K22 |
+| W8 打包、门禁、冒烟、CI | `-server` 包、依赖与交叉编译检查、远程冒烟 | K23、K24 |
+| W9 文档 | 设计、界面、数据、架构目录、工程规则命令、交付状态、需求状态、USER-ACTIONS(H-003 步骤按实际命令更新) | `checkdocs` |
+
+连续完成全部范围、自测和修复,不逐包请求继续;需要用户的事写进 USER-ACTIONS,非阻塞的按 [Q-022](../../USER-ACTIONS.md#q-022) 的默认值实现。
+
+
+## 6. 阶段开始的整理(C0)与依赖盘点(D1)
-### 13.3 必测用例(追加)
-
-| 编号 | 用例 |
+| 对象 | 处理 |
| --- | --- |
-| M4-K32 | 设置“更新”:正式版显示上次/下次检查与记录,“立即检查”后多一条检查记录;开发版不显示检查按钮,显示更新方式说明;启动时版本变化写一条更新记录(开发版“本机打包安装”,正式版带重启标记“自动更新”);`update-history.json` 版本 1、损坏时备份重建、更高版本拒绝;没有下载地址 |
-| M4-K33 | 同时开始 5 场录制(合成直播源)都能开始,没有“已达到同时录制上限”;设置里没有“同时录制数” |
-| M4-K34 | 合成 HLS 播放列表媒体序号跳 3 段 → 一条 `lost_segments`(3 段、估算秒数);FLV 断开 20 秒后重连 → 一条 `reconnect` 与空档秒数;慢速 30 秒 → 一条 `slow`;事件写进录像 `item.json` 的 `live.incidents`,旧清单(无此字段)照常读;全程没有额外站点请求 |
-| M4-K35 | 任务侧栏“录制异常(N)”与页面按场列出;录制行显示“⚠ N 处异常”;窄窗顶部分段可达 |
-| M4-K36 | 订阅详情默认“内容”,信息流只含该订阅全部账号的已缓存内容(含两个站点的账号),零站点请求;“账号”每行带直播状态,直播中可开始/停止录制;旧 `live` 标签值读成“账号” |
-| M4-K37 | 缓存规则“选择订阅…”勾选 3 个订阅应用后,这 3 个订阅的规则变为该规则、取消勾选的回到默认,`subscriptions.json` 只写一次;订阅详情的规则按钮同步显示 |
-| M4-K38 | 回归:A 本轮的 `TestDeletingTheLastItemRemovesTheEmptyAuthorFolder`、`TestBilibiliUserPageSubscriptionKeepsALocalAvatar`、`TestTaskStatusLogOnlyLogsChanges`、`TestCrashOutputKeepsThePreviousCrashAndPrunes` 与 F-001~F-011 的测试保持通过 |
-
-### 13.4 不在本轮
+| `docs/delivery/stage-report.md`(M4 报告) | 已在合并提交里(上面的固定链接);仍有效的结论确认已在正本(状态、决定、USER-ACTIONS),然后改写为 M5 报告。仓库里指向旧报告与旧计划锚点的链接,A 已改成固定提交链接;B 复查没有遗漏 |
+| USER-ACTIONS 里已完成的 ACT(ACT-001~007、010~021 等) | 按[开发流程 §3](../dev-rules/workflow.md#agent-user)的“结项”,已处理完的移到“最近处理完的”,保留锚点;内容精炼到一两行 |
+| 文档里以前阶段的标签 | `docs/` 中用阶段号或返工轮次描述能力的文字改为能力描述(当前计划与报告除外),例如交付状态、需求、界面里的“第五轮反馈”“M4 起”之类 |
+| `artifacts/`、`dist/`、`tmp/`、根目录 `package.exe` | 确认是忽略的生成物,各只留最新一份;`package.exe` 若是 `go build ./tools/package` 的残留就删除,并确认被 `.gitignore` 覆盖 |
+| 测试名 | 新测试按能力命名,不带阶段号或问题编号 |
-- 实时弹幕(仍按 §11.3)。
-- 开发版自己联网检查更新(开发版没有发布源;更新页只说明方式并显示本机安装的版本)。
-- 录制异常的系统通知(只在任务页显示;需要时再加)。
-
-### 13.5 交付
-
-同第 9 节:门禁、Linux vet、截图(设置“更新”正式版与开发版、任务“录制异常”、订阅详情“内容”“账号”、规则批量选择对话框,各三档宽度)、冒烟、`go run ./tools/package -install`(本机 TRACE Dev 在运行时由工具让它退出、装完再打开);交付前跑 `go run ./tools/deps` 与 `-audit`;报告追加“B:第二轮反馈的实现”与给 A 的审查 prompt;全部 amend 进同一个阶段提交。
-
-
-### 13.6 给 Agent B 的交接 Prompt(修订 4)
-
-```text
-你是 TRACE 的 Agent B,继续 M4,实施第二轮实机反馈:计划 docs/delivery/stage-plan.md 第 13 节(修订 4)。
+**D1**:PR #9(`golang.org/x/image` 0.47.0 → 0.48.0)并入本阶段提交后关闭;运行 `go run ./tools/deps`,满 7 天的版本全部升级,跑 `go run ./tools/check`;`go run ./tools/deps -audit`。失败或跑不起来按[开发流程 §5.5](../dev-rules/workflow.md#dependency-inventory)记录。
-先按 AGENTS.md 读入口文档,再读:DEC-051、计划第 13 节、阶段报告 §9、§10(A 已修的 F-010~F-015 与本轮已处理的 ②④⑤⑥)、
-界面规范 §3.6、§3.9 与设置、需求 FR-UPD、FR-SET-002、FR-LIVE-002、直播设计、USER-ACTIONS 的 Q-018。
-
-分支 codex/m4-account,在现有的阶段提交上继续(基点与 A 交付 SHA 见报告 §10);你的实现、测试与文档全部 amend 进
-这一个 DCO 提交(git commit --amend -s)。开工时核对一次分支、提交与工作区,保留已有改动。
-
-连续完成 U1、L1、S1、S2、D2 与 M4-K32~K38,不逐包请示:本地实现、合成夹具、测试、截图、打包、冒烟、文档同步都在授权内。
-默认值按 Q-018。本轮不新增第三方依赖,不发真实站点请求;录制异常只从录制本身已有的数据推算,不另开连接。
-
-必须保留:M1~M4 已有行为与测试(被 DEC-051 替代的除外,相应测试改写而不是删掉)、现有数据文件结构版本 2
-(更新记录用新文件 update-history.json,录制异常用 item.json 的可选字段)、按站点的间隔/额度/退避/熔断、
-凭证隔离与隐私哨兵、安静测试(不抢焦点、不碰已安装的应用)、只删登记文件、A 本轮的修复与回归测试。
-
-交付前:go run ./tools/deps、go run ./tools/deps -audit、go run ./tools/check、GOOS=linux go vet ./...、
-tools/uishots(补 13.5 列的截图)、tools/smoke 全部通过;go run ./tools/package -install 更新本机 TRACE Dev;
-阶段报告追加“B:第二轮反馈的实现”(工作包 → 位置 → 命令与证据 → 状态与限制、not-run、给 A 的审查 prompt),
-同步需求、界面规范、数据与直播设计、交付状态与 USER-ACTIONS(H-001 第 31 步)。
-未授权:push、PR、合并、标签、发布。最终回复给出交付 SHA、开发版版本号和一个首选下一步。
-```
-
-
-## 14. 修订 5:第四轮实机反馈的主页调整(2026-11-16)
-
-用户 2026-11-16 的反馈:A 已修好直播录制的两个缺陷([阶段报告 §14](stage-report.md#feedback-4));主页的两条要求是产品调整([DEC-053](../decisions.md#dec-053)),由 B 在本阶段内连续实现,按用户对 [Q-019](../../USER-ACTIONS.md#q-019) 的答复。基点是 A 本轮 amend 后的阶段提交(见报告 §14 的交付消息)。
-
-### 14.1 设计要点
-
-- **H1 回到上次阅读的位置**(DEC-053 ①):
- - `ui-state.json` 新增可选字段 `homePositions: {"all"|"bilibili"|"douyin": {key, pubTs, offsetPx}}`:每个站点筛选下主时间线(不含单订阅视图,单订阅不记位置)可见区最上面那条帖子与它顶边的偏移。滚动停下约 1 秒后保存,离开主页与退出前(`--quit-for-update` 也算)再保存一次;内容没变时不写。旧文件没有这个字段时照常读,结构版本保持 2。现有 `anchor`(看过的最新一条)的含义不变。
- - 每次启动后第一次显示某个站点筛选的主时间线时(启动时的筛选,或之后第一次切到另一个筛选):以该筛选的位置为游标,读这条及更早的一页(`direction: older`,包含它本身),列表定位到这条并恢复偏移;`feedMoreBefore = true`,滑到顶附近按现有 `loadFeedEdge(true)` 载入更新的内容,当前看到的条目不跳动。这条已被删掉时,用 `pubTs` 定位到不晚于它的最近一条;没有记录时从最新处开始。同一次运行内切到别的页面再回来,保留当时的列表与位置(现有行为);同一次运行内在筛选之间来回切换,回到每个筛选当时的位置(离开一个筛选前先保存它的位置)。
- - 达到 NFR-PERF-001:5000 条合成数据下 1 秒内回到上次位置。
-- **H2 侧栏“订阅”列表**(DEC-053 ②):
- - 主页侧栏自上而下:“全部动态”、站点筛选,然后直接是订阅列表;**不加任何分节标题**(不写“正在直播”“订阅”“有更新”)。原来单独的“正在直播”分节(`renderLivePanelSection`)与“有更新”都并入这个列表。
- - 每行:头像(现有 `renderAccountAvatar`)加名称,不加状态说明文字。**正在直播**的头像一圈高亮(现有直播圈);**未读**时头像右下角一个强调蓝色小圆点(约 8px,带一圈背景色描边,样式参考哔哩哔哩动态页的头像条)。排序分三组:正在直播的在最前(组内未读在前,再按最近更新时间),然后未读,然后已读;后两组各按该订阅在当前站点筛选下最新一条已缓存内容的发布时间从新到旧。没有已缓存内容的订阅不列出,正在直播的除外。只列订阅;没有订阅的作者(直接缓存的作品)和没订阅的直播间不进这个列表。点任何一行(包括正在直播的)都打开这个订阅的信息流。
- - 未读的判断:`latest > seen`。`latest` 是该订阅全部关联账号在当前站点筛选下最新的已缓存发布时间;`seen` 是 `homeSeen["sub:"]`,没有这一项时用启动时读到的 `anchor.pubTs` 作为初始值(第一次使用、两者都没有时算已读,新装不会满屏圆点)。在主时间线上往下翻不改变某个订阅的已读状态,只有点开它才算看过。
- - 点击一行:用现有 `openHomeActorFeed` 打开这个订阅的信息流,并写 `homeSeen["sub:"] = max(原值, latest)`;圆点立即消失。**排序在进入主页时算一次并保存为快照**:本次停留在主页期间(含点开、返回“全部动态”、切换站点筛选)只更新圆点与直播圈、不改顺序;新缓存的内容只会让圆点出现,开播或下播只改直播圈,都不挪动行。下次进入主页(从别的页面切回来,或重新启动)重新排序,看过的就移到已读组。
- - 订阅很多时列表要虚拟化(同订阅侧栏 `SubPanelListState` 的做法),重绘不逐帧读媒体库(复用现有 `libraryStatistics` 与按条目缓存)。
- - 窄窗(没有侧栏)时,时间线上方的头像行(现在的 `renderHomeUpdatedAvatarsRow`)改成同样的列表横向展示:圆形头像、下面一行名称、未读圆点,与哔哩哔哩的头像条相同;最前面是“全部动态”。
- - 原来按“有更新”打开单个作者(无订阅)的入口去掉;`homeSeen` 里 `mid:` / 作者键的旧值保留不删。
+## 7. 必测用例
-### 14.2 工作包
+全部用合成样本与假站点客户端,测试安静、不碰本机安装的应用、不访问网络(假 rclone 也不访问)。
-| 包 | 内容 | 主要位置 |
+| 编号 | 用例 | 对应 |
| --- | --- | --- |
-| H1 回到阅读位置 | 按站点筛选的 `homePositions` 保存与启动后第一次恢复、删除后按 `pubTs` 回退 | `internal/uistate`(可选字段)、`internal/ui/feed.go`、`internal/ui/views.go` 主页、`internal/shell`(退出前保存) |
-| H2 订阅列表与圆点 | 侧栏订阅列表(并入正在直播、无分节标题)、未读判断与进入主页时的排序快照、窄窗横向头像条 | `internal/ui/feed.go`(替换 `homeUpdatedActors`)、`internal/ui/shell.go` 主页侧栏、`internal/ui/views.go` |
-| D3 文档 | 需求 FR-FEED-001 与 NFR-PERF-001 说明、界面规范 §3.1(主页)与第 66 行附近的“不恢复位置”、数据设计 `ui-state.json`(`homePositions`、`homeSeen` 的新语义)、架构 §主页、订阅设计第 72 行的“有更新”、交付状态、USER-ACTIONS H-001 补一步 | `docs/` |
-
-### 14.3 必测用例(追加)
+| M5-K01 | 缓存视频(多 P、合并)、抖音图文与实况、直播录制换段收尾、写清单、凭证保存的过程中,条目文件夹与导出目录里除正式文件外的名字都匹配 `*.part` 或 `.trace-*`;旧名字的 `.part`/`.raw` 进行中下载升级后能续传 | W1 |
+| M5-K02 | 新缓存的条目 `item.json` 带 `cachedBy`,节点 ID 在重启后不变;没有该字段的旧条目照常读取 | W1、AC-64 |
+| M5-K03 | 远程配置下:没有续期请求(假客户端计数为 0)、开了全部缓存的规则不建队列、入队全部缓存返回明确错误、定时检查总开关为开 | W2、AC-59 |
+| M5-K04 | 远程正在缓存一个多 P 视频和录制一场直播时,删除已完成的文件与 `item.json`(模拟 `rclone move`):缓存继续完成、不重复下载已完成的条目、下一段收尾后的 `item.json` 列出全部已完成的段、没有错误日志 | W2、AC-61 |
+| M5-K05 | 远程第一次检查同步来的新账号只建立起点;之后的新内容按订阅规则自动缓存、开播按规则录制;起点之前的内容从不缓存 | W2、AC-59 |
+| M5-K06 | Linux 凭证:密钥文件 `0600`、凭证文件不含明文哨兵;密钥丢失时凭证按“没有 Cookie”处理且不崩溃;Windows 路径不变 | W2 |
+| M5-K07 | `init` 生成目录权限、证书、令牌哈希与连接码;连接码只打印一次,`server.json` 不含令牌明文;`token` 换令牌后旧令牌 401 | W3、AC-57 |
+| M5-K08 | 没有令牌、错误令牌 401;同一 IP 1 分钟失败 5 次后 429,10 分钟后恢复;超过 1 MiB 的请求体 413;协议版本不同 409 并带两边版本 | W3、AC-57 |
+| M5-K09 | 客户端用错误指纹连接:握手失败、服务端没有收到任何 HTTP 请求;正确指纹成功 | W3、W5、AC-57 |
+| M5-K10 | `PUT credentials`:假站点校验通过才保存、失败时原凭证不变并返回原因;远程站点被判登录失效后状态为“需要重新同步”,该站点不再发请求;推送不含 `refresh_token` | W3、AC-60 |
+| M5-K11 | 端到端:回环地址上起真实 HTTPS 服务与真实后端(临时目录、假站点),本地客户端连接、读状态、同步快照、推送 Cookie;收到退出信号时录制收尾、任务暂停、退出码 0;整个过程的日志、状态与数据文件里没有令牌、连接码、Cookie 哨兵 | W3、AC-57、AC-58 |
+| M5-K12 | 上传顺序:同一条目先媒体文件后 `item.json`(假 rclone 记录调用顺序);成功后删除媒体文件,`item.json` 与封面在条目最终完成并上传最后一版后才删;空文件夹删除;`.part` 文件从不出现在上传清单里 | W4、AC-61 |
+| M5-K13 | 上传失败:找不到 rclone、退出码非 0、stderr 带配额字样分别得到正确分类与退避;文件在上传前被外部删掉时不无限重试;`deleteAfterUpload` 关时不删任何文件 | W4、AC-61 |
+| M5-K14 | 重启后补传:上传进行中退出,重启后从 `upload_files` 与索引补上没传完的,已传的不重复 | W4 |
+| M5-K15 | “设置 › 远程”:粘贴连接码连接;无法连接、证书变了、令牌错、版本不同、远程拒绝 Cookie 分别显示对应文案;页面不可见时不发远程请求 | W5、AC-58 |
+| M5-K16 | 本地续期成功、扫码登录、粘贴登录后自动推送 Cookie;远程离线时标“Cookie 待同步”,恢复后后台重试成功并清除标记 | W5、AC-60 |
+| M5-K17 | 订阅同步后本地显示“已同步”;本地改订阅后显示“有改动未同步”(按快照哈希) | W5、W7、AC-59 |
+| M5-K18 | 导入扫描:合成文件夹含新条目、可补充、相同、冲突(同路径不同内容;不同作者文件夹)、未传完(缺文件、大小不符、SHA-256 不符)、无法识别(无清单、版本不对、`..` 路径)各至少一条,分类全部正确;扫描不写任何文件 | W6、AC-62 |
+| M5-K19 | 导入执行:新条目导入后在媒体库与主页可见并可读取媒体路径;可补充只补缺的文件;冲突的保留本地 / 用导入的 / 合并三种结果的文件与 `item.json` 正确;未传完的直播先导入已校验的段、补齐文件后再导入变成可补充并完成 | W6、AC-62 |
+| M5-K20 | 导入在复制大文件中途取消或进程被杀:没有正式名的半个文件、索引不含未完成的条目;再导入能完成;默认来源不动,勾选删除时只删已导入的文件 | W6、AC-62 |
+| M5-K21 | 本地导出的文件夹在另一个数据目录导入得到相同条目;两个节点各录一部分段的同一场直播先后导入后合并为一场、段号连续、`cachedBy` 保留 | W6、AC-63、AC-64 |
+| M5-K22 | 订阅快照:替换保留账号起点、移出的账号不再检查、文件不删;导出文件不含 Cookie;导入预览区分新订阅、已订阅的账号、不同的规则,确认后一次写入,失败时不变 | W7、AC-59、AC-63 |
+| M5-K23 | `tools/package -server` 产出两个架构的包与 `SHA256SUMS`;`go list -deps ./cmd/trace-server` 不含 MyGo 等界面包;`trace-server version` 与桌面版版本一致 | W8、AC-56 |
+| M5-K24 | 回归:`go run ./tools/check` 全部通过;`tools/uishots` 新增“设置 › 远程”(未连接、已连接、无法连接)、导入预览(含冲突)、任务页“导入”、订阅导入预览的场景,三种宽度无横向滚动;`go run ./tools/smoke`(桌面)与远程冒烟通过;`GOOS=linux go vet ./...` 通过 | 全部 |
-| 编号 | 用例 |
-| --- | --- |
-| M4-K39 | “全部”滚到第 40 条、“B 站”滚到第 10 条后“重启”(重建 `App`,`RestartHomeSession`):两个筛选各自回到自己的那条、偏移相同,“抖音”从最新处开始;往上滑载入更新的条目且当前条目不跳;那条删掉后回到不晚于它的最近一条;单订阅视图不写位置;旧 `ui-state.json` 照常读 |
-| M4-K40 | 侧栏“订阅”:3 个未读订阅带圆点排在上面、按最新发布时间排序,已读的在下面无圆点;点开一个未读订阅后圆点消失、位置不变,`homeSeen` 写入;离开主页再回来,它移到已读组的正确位置;新缓存的内容让已读订阅出现圆点但本次不挪位置 |
-| M4-K41 | 第一次使用(没有 `anchor` 与 `homeSeen`)不显示任何圆点;只有 `anchor` 时比它新的订阅带圆点;站点筛选为“抖音”时只列有抖音内容的订阅,排序与圆点按抖音内容算 |
-| M4-K42 | 正在直播的订阅排最前、头像带直播圈(即使没有已缓存内容),侧栏没有任何分节标题、没有状态说明文字;本次停留中开播不挪位置;1000 个订阅时侧栏滚动不卡顿、重绘不读媒体库;窄窗下时间线上方是横向头像条(“全部动态”在最前、直播圈、未读圆点);三档宽度截图 |
-| M4-K43 | 回归:A 本轮的 `TestRecoveryAcceptsEXTINFDriftAndClearsConvertFailed`、`TestHLSSequenceResetIsNotLostSegments` 与以前各轮的测试保持通过;被 DEC-053 替代的“主页不恢复位置”的测试改写而不是删掉 |
-
-### 14.4 不在本轮
+## 8. MVP 与 LOOP
-- 图标栏“主页”的未读角标或数字(DEC-053 不要)。
-- 按条记已读、把没订阅的作者放进侧栏列表。
+- 本阶段要贯通的 MVP 流程见[路线 §3](roadmap.md#mvp-loop)的“远程版”一行。
+- 可以记为 LOOP 的深化:状态页的图表与历史、上传带宽的时段控制、导入时按作者批量决定冲突以外的更多批量规则、Docker 镜像、远程换包后的本地提示升级。不得记为 LOOP 的:任何会让凭证、令牌出现在日志或文件里的缺口,导入留下半个文件或标错完成状态,上传在确认前删除文件。
-### 14.5 交付
+## 9. 交付与验证
-同第 9 节:门禁、Linux vet、截图(主页侧栏订阅列表有未读与已读、窄窗头像条、恢复位置后的主页,各三档宽度)、冒烟、`go run ./tools/package -install`;报告追加“B:第四轮反馈的实现”与给 A 的审查 prompt;全部 amend 进同一个阶段提交。
+- B 交付前:`go run ./tools/check`、`go run ./tools/deps` 与 `-audit`、`go run ./tools/uishots`、桌面冒烟与远程冒烟、`go run ./tools/package -server`、`go run ./tools/package -install`(把最新开发版装到本机并保持 TRACE Dev 在托盘运行)。
+- 报告(`docs/delivery/stage-report.md`,按[交接模板 §2](../templates/agent-handoff.md))写:每个工作包与用例的实现位置和证据、两个远程包的 SHA-256 与体积、本机开发版版本、WSL 冒烟是否运行、`not-run` 项(真实 VPS、真实站点、Google Drive,见 H-003)。
+- USER-ACTIONS:把 H-003 的步骤按实际的命令、包名与界面文案改准;Q-022 有变化就更新。
-
-### 14.6 给 Agent B 的交接 Prompt(修订 5)
+
+## 10. 给 Agent B 的交接 Prompt
```text
-你是 TRACE 的 Agent B,继续 M4,实施第四轮实机反馈的主页调整:计划 docs/delivery/stage-plan.md 第 14 节(修订 5)。
-
-先按 AGENTS.md 读入口文档,再读:DEC-053(以及被它部分替代的 DEC-040 ④、DEC-033 ①、DEC-037)、计划第 14 节、
-阶段报告 §14、界面规范 §3.1、需求 FR-FEED-001 与 NFR-PERF-001、数据设计 ui-state.json 一节、USER-ACTIONS 的 Q-019(用户已答复)。
-
-分支 codex/m4-account,在现有的阶段提交上继续;你的实现、测试与文档全部 amend 进这一个 DCO 提交
-(git commit --amend -s)。开工时核对一次分支、提交与工作区,保留已有改动。
-
-连续完成 H1、H2、D3 与 M4-K39~K43,不逐包请示:本地实现、合成夹具、测试、截图、打包、冒烟、文档同步都在授权内。
-按用户对 Q-019 的答复实现(站点筛选分别记位置;侧栏无分节标题,正在直播的排最前)。本轮不新增第三方依赖,不发真实站点请求;主页只读本机数据。
-
-必须保留:M1~M4 已有行为与测试(被 DEC-053 替代的除外,相应测试改写而不是删掉)、数据文件结构版本 2
-(homePositions 是 ui-state.json 的可选字段)、主页滚动流畅(重绘不逐帧读媒体库、不在界面线程解码原图)、
-凭证隔离与隐私哨兵、安静测试(不抢焦点、不碰已安装的应用)、A 本轮的录制修复与回归测试。
-
-交付前:go run ./tools/check、GOOS=linux go vet ./...、tools/uishots(补 14.5 的截图)、tools/smoke 全部通过;
-go run ./tools/package -install 更新本机 TRACE Dev(装完它会在托盘打开,确认命令结束后仍在运行);
-阶段报告追加“B:第四轮反馈的实现”(工作包 → 位置 → 命令与证据 → 状态与限制、not-run、给 A 的审查 prompt),
-同步需求、界面规范、数据设计、架构、订阅设计、交付状态与 USER-ACTIONS。
-未授权:push、PR、合并、标签、发布。最终回复给出交付 SHA、开发版版本号和一个首选下一步。
+你是 TRACE 的 Agent B,动作:连续实施 M5(远程版、上传与导入导出)。
+
+- 计划:docs/delivery/stage-plan.md(TRACE-M5-01 修订 1);设计正本 docs/design/remote.md;决定 DEC-062;需求 FR-REMOTE-001~008;验收 AC-56~64;默认值 USER-ACTIONS 的 Q-022;人工检查 H-003。
+- 分支 codex/m5-remote,基点 main @ 8327803;计划所在提交是阶段提交的起点,你的全部改动 amend 进这一个 DCO 提交(git commit --amend -s)。开始时核对一次分支、提交与计划。
+- 范围:C0、D1、W1~W9 与必测用例 M5-K01~K24,连续完成、自测、修复,不逐包请示;非阻塞的按 Q-022 默认值实现并写明。
+- 必须保留:M1~M4 与 DEC-059~061 的行为与测试;数据结构版本 2(只加可选字段与 IF NOT EXISTS 新表);INV-01~14;按站点的额度、退避与熔断;安静测试、不碰本机安装的应用;只删登记文件;dist 只留最新一份。
+- 不发真实站点请求、不连接网盘;远程行为全部用假站点客户端与假 rclone 验证。真实 VPS 与 Google Drive 是 H-003,保持 not-run。
+- 交付:go run ./tools/check、tools/deps 与 -audit、uishots、桌面与远程冒烟、tools/package -server、tools/package -install(装好后 TRACE Dev 保持在托盘运行);按交接模板写 docs/delivery/stage-report.md;更新正本文档与 USER-ACTIONS(H-003 步骤按实际改准)。
+- 未授权:push、PR、合并、标签、发布。
+- 完成后给出交付 SHA、报告入口与给 A 的审查 prompt。
```
diff --git a/docs/delivery/stage-report.md b/docs/delivery/stage-report.md
index fd61d54..b9c3a71 100644
--- a/docs/delivery/stage-report.md
+++ b/docs/delivery/stage-report.md
@@ -1,560 +1,149 @@
-# 阶段报告:M4(我的:登录账号的站点内容)
+# 阶段报告:M5(远程版、上传与导入导出)
-计划:[TRACE-M4-01](stage-plan.md)(修订 4:含 D1、第一轮实机反馈 §11~§12 及第二轮实机反馈 §13)。上一阶段的报告在合并提交里:[M3 报告](https://github.com/chialecode/trace/blob/f080483/docs/delivery/stage-report.md)。
+计划:[TRACE-M5-01](stage-plan.md)(修订 1)。上一阶段的报告在合并提交里:[M4 报告](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-report.md)。
-本报告由 B 按[交接模板 §2](../templates/agent-handoff.md)填写;A 的集中审查写在第 6 节(M4 交付)、第 9 节(第一轮反馈的实现)与第 12 节(第二轮反馈的实现)。
+本报告由 B 按[交接模板 §2](../templates/agent-handoff.md)填写;A 的集中审查追加在后面。
-## 1. B 交付(2026-11-14)
+## 1. B 交付(2026-11-20)
| 信息 | 内容 |
| --- | --- |
-| 执行范围 | C0、W1~W6、D1 与必测用例 M4-K01~K15 全部做完,没有缩减验收。用户新增指示:抖音网页版“稍后再看”的网页搜索(CSDN、知乎等)也没找到,已写进[抖音协议 §12](../research/douyin.md#account-lists)与 Q-015 第 3 条 |
-| 版本与工作区 | 分支 `codex/m4-account`,基点 `main @ f080483`;全部改动 amend 进阶段提交(计划提交 `eec4da2` 之上,DCO),交付 SHA 在交付消息里。工作区里 DEC-048 的文件(`tools/deps/`、`.github/dependabot.yml`、`ci.yml`、`AGENTS.md`、`workflow.md`、`decisions.md`、`engineering.md` 的依赖盘点段)是 B 开工后由另一会话写入的;计划已把它们列为本阶段的 D1,所以一起进了阶段提交,B 没有改动它们的内容。没有 push 或 PR |
-| 可运行产物 | `go run ./tools/package -install`:开发版 `0.1.2-dev.202611140852`,已静默装到本机(从 `0.1.2-dev.202611131858` 升级,安装时 TRACE Dev 没在运行)。`trace-dev-setup-0.1.2-dev.202611140852-amd64.exe` SHA-256 `0b05e3dd8b6256a3650c7f1067dd3f6d99e7c87867235bcf2c68e600f7431dcc`,`trace.exe` `7e941f24d71261c99d16f48189d78291bc83b32b5e61e263e71a937670f1447f`(`dist/trace-dev/SHA256SUMS.txt`)。注意:包是从未提交的工作区构建的,`VERSION.txt` 里的提交是 `eec4da2…-dirty`,源码与交付提交相同 |
-| 关键变更与恢复 | 新服务 `AccountService`,接入 `BackendAPI`;抖音客户端支持表单 POST(只有 `listcollection` 用);新路由 `/mine` 与图标栏第三项“我的”。数据结构仍是版本 2,没有新文件,列表只在内存里。全部只读。没有新增第三方依赖;`go` 行 1.27.3 → 1.27.4、`golang.org/x/sys` v0.49.0 → v0.50.0(D1) |
+| 执行范围 | C0、D1、W1~W9 与必测用例 M5-K01~K24 全部做完,没有缩减验收。用户没有新增指示。非阻塞的问题按 [Q-022](../../USER-ACTIONS.md#q-022) 的默认值实现;B 另定的 4 项写在 Q-022 第 11~14 条和本报告第 4 节 |
+| 版本与工作区 | 分支 `codex/m5-remote`,基点 `main @ 8327803`。全部改动 amend 进阶段提交(计划提交 `ca72b48` 之上,DCO),交付 SHA 在交付消息里。工作区里没有不属于本阶段的未提交文件。`artifacts/backup-20261116` 与 `artifacts/repair-20261115` 是用户真实数据的备份,被忽略也没有动,写进了 USER-ACTIONS 的“本机文件”。没有 push,没有 PR |
+| 可运行产物 | **桌面开发版**:`go run ./tools/package -install` 装成 `0.1.3-dev.202611191746`(从 `0.1.3-dev.202611190516` 升级),已在托盘运行(`artifacts/package/install-dev.json`:relaunched、background 都是 true)。`trace-dev-setup-0.1.3-dev.202611191746-amd64.exe` SHA-256 `c2cc14d10158c99348abd590f185f9622e304b409c307a094d31d92311c7880e`(8.0 MiB),`trace.exe` SHA-256 `1f61e58542dcd87efa7c4ed7929aa0540dce3b1c0c24d36d2dc50615ddee7a41`(25.0 MiB),VERSION 的 commit 是 `ca72b48…-dirty`(包在 amend 之前构建,源码与交付提交相同)。**远程版**:`go run ./tools/package -server` 产出 `dist/trace-server/`:`trace-server-0.1.3-dev.202611191749-linux-amd64.tar.gz` SHA-256 `51a7b1d5b0c473ccb29f633f68fdf5c04ab8b3e461ca648814af73bb8c812123`(包 6.9 MiB,程序 16.1 MiB);`trace-server-0.1.3-dev.202611191749-linux-arm64.tar.gz` SHA-256 `f0d86337db131ba75e0a9ad583acfe4ceb2695110dffa53957b6a34d48010df4`(包 6.4 MiB,程序 15.0 MiB);另有 `SHA256SUMS`。截图在 `artifacts/uishots/`(64 个场景,192 张),冒烟回执在 `artifacts/smoke/`、`artifacts/smoke-server/`、`artifacts/smoke-server-linux/`。样本全部是合成的:假站点客户端、假 rclone(`internal/upload/fakerclone`,冒烟程序在 `TRACE_FAKE_RCLONE=1` 时充当 rclone)、回环地址上的真实 HTTPS |
+| 关键变更与恢复 | 新程序 `cmd/trace-server`(`init`/`run`/`token`/`version`/`upload-test`/`rclone-filter`)。新包:`internal/remote`(协议、连接码、指纹固定的客户端)、`internal/remoteserver`(配置、HTTPS 接口、令牌哈希、失败限流、请求体上限、版本握手、信号收尾)、`internal/upload`(rclone 上传)、`internal/transfer`(扫描、导入、导出)。服务层新增远程运行配置(`remote_profile.go`)、本地远程客户端(`remote_client.go`)、远程接口实现(`remote_server_api.go`)、订阅同步与文件导出导入(`remote_sync.go`)、导入导出任务(`transfer_jobs.go`)。**数据**:结构仍是版本 2,只加了可选字段(`item.json` 的 `cachedBy`、`settings.json` 的 `remote`)、远程数据目录里的新表 `upload_files`(`IF NOT EXISTS`),以及两个新文件 `node.json` 和 Linux 的 `credentials/secret.key`。**临时名**:所有非正式文件都匹配 `*.part` 或 `.trace-*`,DASH 中间文件改名为 `.trace-Pxx.video-<清晰度代码>-<编码 ID>.m4s`,旧名字的进行中下载升级后会被接管续传。**权限**:远程不续期,不做全部缓存,也不能手动缓存(返回 `ErrRemoteUnsupported`);令牌只存哈希;推送的 Cookie 先经站点校验才保存。**界面**:“设置 › 远程”;媒体库“⋯ → 导入… / 导出…”与导入页;任务页“导入导出”分段;订阅“⋯ → 导出订阅… / 导入订阅…”。**恢复**:导入逐个文件校验大小与 SHA-256,用临时名复制后再改名,`item.json` 最后写;取消或中断后重新扫描导入即可,相同的跳过、缺的补上。上传成功确认后才删除文件,`item.json` 最后上传、最后删除;重启后按 `upload_files` 补传 |
| 工作包 / 用例 | 实现位置 | 实际命令与证据 | 状态与限制 |
| --- | --- | --- | --- |
-| C0 整理 | 见第 2 节 | `go run ./tools/checkdocs` OK | passed |
-| W1 哔哩哔哩客户端(K01~K03) | `internal/site/bilibili/account.go`:`FavFolders`、`FavResources`、`ToView`(WBI)、`WatchHistory`(游标三元组);`client.go` 的 `doBiliJSON` 把 `data=null` 当空 | `TestFavFoldersDefaultFirstPrivateAndNullData`、`TestFavResourcesPagingKindsAndInvalid`、`TestToViewWBIViewedAndProgress`、`TestWatchHistoryCursorBusinessesAndStall`、`TestAccountListsErrorClasses` | passed;ACT-020 B-V1~B-V4 真实通过 |
-| W2 抖音客户端(K05~K07) | `internal/site/douyin/client.go` 的 `apiRequestSpec.form`(POST 表单体进入 `a_bogus` 的 `Body`);`account.go`:`Followings`、`Favorites`、`Collection`(POST)、`CollectFolders`、`CollectFolderWorks`、`WatchHistory`(`WatchHistoryEnabled=false`) | `TestPOSTSignFormBodyFeedsABogusAndGETUnchanged`(已有签名测试的断言没改)、`TestFollowingsMaxTimeCursorAndStall`、`TestFavoritesShellVersusEmpty`、`TestFavoritesCursorFieldsAndDedup`、`TestCollectFolderListAndWorks`、`TestAccountListsRequireLogin` | passed;真实站点只有关注通过,其余见第 3 节的 ACT-020 |
-| W3 `AccountService`(K04、K08~K10) | `internal/service/account.go`:`AccountSections`/`AccountFolders`/`AccountPage`;发请求前查登录、功能和站点熔断;风控与限流用 `RecordSiteAutomaticStop` 记到该站点;条目归一成 `AccountItem`;`safeBrowserURL` 只放行 https 的 `bilibili.com`、`b23.tv`、`douyin.com`;日志只写 `account.. page=N items=M more=bool` | `TestAccountSectionsLoginGate`、`TestAccountBilibiliListsMapping`、`TestAccountDouyinListsMapping`、`TestAccountBreakerPerSite`、`TestAccountPrivacySentinels`(浏览全部功能后扫描数据目录、日志与缓存目录,没有哨兵;最近解析只在 `OpenLink` 后出现)、`TestSafeBrowserURL` | passed |
-| W4 “我的”界面(K11、K12) | `internal/ui/mine.go`(`MineState`、`OpenMine`、手风琴侧栏、下拉与“全部 / 未看完”、虚拟列表、按日分组、错误与空/到底分开、“⋯”菜单、`mineOnAccountChanged` 只在退出或换账号时清空);`views.go` 的投稿行抽成 `renderCompactVideoRow`,用户页与“我的”共用;`douyin_views.go` 的网格卡片不再绑 `DouyinUserView`;`theme.go` 新图标 `mine`、`clock`、`history` | `TestMineFoldedPanelAndFirstChoiceRequests`、`TestMineScrollLoadsNextPageOnceAndKeepsPosition`、`TestMineItemsOpenThroughOpenLink`、`TestMineErrorsEmptyAndSignOut`、`TestMineNarrowWindowChooserAndBack`、`TestMineHistoryDateGroups` | passed。“我的”没有文本输入框;菜单用已有的 `MoreMenuButton`,Esc 与焦点沿用它的行为,没有为“我的”另写键盘测试 |
-| W5 工具(K13、K14) | `tools/actcheck/act020.go`(账本、分类额度共 22 次、站点各自的停止条件、未登记的接口拒发、回执不写标题/昵称/ID,扫描密钥);`tools/uishots/mine_fixture.go`,10 个“我的”场景 | `TestAct020ClassifyAndHandles`;`go run ./tools/uishots -out artifacts/uishots`:46 个场景、138 张 PNG 全部通过;`artifacts/site-check/act020.json` | passed(ACT-020 结果见第 3 节) |
-| W6 文档 | 需求 §2.9、路线 AC-45~53、交付状态(已实现能力、LOOP-014)、架构 §3、两份协议、工程规则(场景数与 Go 版本)、USER-ACTIONS(ACT-020、Q-015、H-001 第 28 步、待你统一处理) | `go run ./tools/checkdocs` OK | passed |
-| D1 依赖盘点 | `go.mod`/`go.sum` | 升级前 `go run ./tools/deps -audit` failed(`GO-2026-6859`,`net/http`,代码会调用);把 `go` 行升到 1.27.4、`x/sys` 升到 v0.50.0 后 `-audit` passed(called 0,例外 0,另有 7 条在代码没调用到的模块里)。交付前 `go run ./tools/deps`:已到期 0 项;没到期的有 `mp4ff` v0.63.0(0 天)、`mygo` v0.9.0(2 天)、`x/image` v0.48.0(4 天),都不足 7 天,所以没升 | passed |
-| K15 回归 | — | `go run ./tools/check` ALL CHECKS PASSED(Go 1.27.4,2m48s);`GOOS=linux go vet ./...` OK;`go run ./tools/smoke -pkg dist/trace-dev -out artifacts/smoke` PASSED(托盘专用工作集 0.58 MiB,WebView2 0)。外观不变:在临时工作树里用基点 `eec4da2` 生成 108 张截图,跟本次逐像素比,去掉 52 像素的图标栏(新加了“我的”图标)后,用户页、抖音用户页、作品与视频详情等都一样;只有 `settings` 与 `settings-logs`(临时目录名、时间戳)和 `player*`(视频帧时间)不同,跟本阶段改动无关 | passed |
+| C0 整理 | 见第 2 节 | `go run ./tools/checkdocs` OK(包含在 `tools/check` 里) | passed |
+| D1 依赖 | `go.mod`/`go.sum` | 见第 3 节 | passed;PR #9 要在合并后关闭(未授权操作 GitHub) |
+| W1 临时名、节点与清单(K01、K02) | `internal/storage/atomic.go`(`TempPrefix`、`TempSuffix`、`IsTempName`、`TempSiblingPath`);`internal/download/video.go`、`douyin.go`、`manager.go`(DASH 中间名、旧名接管);`internal/live` 的段文件与收尾;`internal/library/node.go`(`node.json`、`LoadOrCreateNode`)、`library.go`(`cachedBy`)、`files.go` | K01:`watchNames` 在 `TestMuxDASHFilesAndVideoCacheEndToEnd`、`TestDouyinVideoCacheRangeRefreshAndSecretScrub`、`TestDouyinPlainAndMixedNotesMusicAndUnknownPage`、`TestCachingContinuesWhenFinishedFilesAreMovedAway`、`TestRecordingContinuesWhenFinishedSegmentsAreMovedAway` 的整个过程中持续检查文件名;`TestLegacyStreamPartResumesUnderTemporaryName`;凭证与 JSON 写入沿用 `TestWriteMigratedJSONAtomicPreRenameFaultCleansTemp`(断言改为新临时名)。K02:`TestCachedByNodeIsStableAndOldItemsStillLoad` | passed |
+| W2 远程运行配置与凭证(K03~K06) | `internal/service/remote_profile.go`;`internal/credential/secret.go`、`dpapi_other.go`(Linux 用随机密钥文件做 AES-GCM),`dpapi_windows.go` 不变;`internal/subscription/snapshot.go` | K03:`TestRemoteProfileHasNoRenewalNoFullCacheAndChecksOn`(续期与站点请求计数为 0;全部缓存不建队列;入队返回明确错误;定时检查关不掉)。K04:`TestCachingContinuesWhenFinishedFilesAreMovedAway`、`TestRecordingContinuesWhenFinishedSegmentsAreMovedAway`。K05:`TestSnapshotReplaceKeepsStartPointsAndStopsRemovedAccounts`。K06:`TestLinuxCredentialKeyFile`(WSL 下运行) | passed。**K05 只覆盖一部分**:同步来的账号先建起点、起点前的内容不进更新,由该测试在远程的快照路径上验证;“新内容按规则自动缓存、开播按规则录制”沿用 M3 的 `TestScheduledCheckBackoffQuotaAndAutoCache` 等测试,远程走同一个订阅管理器与后端,没有为远程另写一遍 |
+| W3 `trace-server` 与接口(K07~K11) | `cmd/trace-server/main.go`;`internal/remoteserver/config.go`、`server.go`、`run.go`;`internal/remote/client.go`、`code.go`、`protocol.go`;`internal/service/remote_server_api.go` | K07:`TestInitPrivateFilesCodeAndTokenRotation`。K08:`TestAPIAuthFailureLimitBodyLimitAndProtocol`。K09:`TestClientPinsCertificateBeforeAnyRequest`。K10:`TestCredentialPushVerifiesBeforeSaving`、`TestRemoteProfileHasNoRenewalNoFullCacheAndChecksOn`(没有 `refresh_token`)。K11:`TestRunEndToEndWithoutLeakingSecrets`;进程级的 `go run ./tools/smoke -server` | passed。**K11 的录制收尾**:端到端测试用取消停止服务,确认任务暂停与没有泄露;“退出时录制收尾为可播放文件”沿用 `TestStopRecordingWhileLiveFinalizesPlayableFile`(远程与桌面走同一个 `backend.Close`)。SIGTERM 退出码 0 在 WSL 冒烟里验证;Windows 冒烟用 kill 再重启,验证锁会释放(第 5 节) |
+| W4 上传(K12~K14) | `internal/upload/upload.go`(`upload_files` 表、按条目排队、先媒体后清单、确认后删除、错误分类与退避、重启补传、`sanitize`);`internal/upload/fakerclone` | K12:`TestUploadOrderDeleteAndNoPartFiles`、`TestUploadRecordingSegmentsThenFinal`、`TestUploadWaitsForBusyDownload`。K13:`TestUploadFailuresAndKeepFiles`、`TestSanitizeKeepsFirstErrorLineWithoutSecrets`。K14:`TestUploadResumesAfterRestart` | passed(Windows 与 WSL) |
+| W5 本地客户端与“设置 › 远程”(K15~K17) | `internal/service/remote_client.go`;`internal/ui/remote_settings.go`;`internal/ui/theme.go` | K15:`TestDesktopConnectAndErrorKinds`(无法连接、证书变了、令牌错、版本不同、远程拒绝 Cookie 各自的文案;页面不可见时没有远程请求)。K16:`TestDesktopPushesCookieAfterLoginAndRetriesPending`。K17:`TestDesktopSyncStateFollowsSnapshotHash`。截图:`settings-remote-*.png`、`settings-remote-connected-*.png`、`settings-remote-unreachable-*.png` | passed |
+| W6 资源库导入导出(K18~K21) | `internal/transfer/scan.go`、`apply.go`、`export.go`;`internal/library/merge.go`;`internal/service/transfer_jobs.go`;`internal/ui/transfer_view.go`、`library_view.go`、`views.go`、`tasks_view.go`、`shell.go` | K18:`TestScanSortsSixCategoriesWithoutWriting`。K19:`TestApplyNewSupplementConflictsAndIncomplete`。K20:`TestApplyCancelResumeAndDeleteSource`。K21:`TestExportReimportAndTwoNodeLiveMerge`;服务层 `TestTransferJobsExportEverythingAndImportElsewhere`(导出分页 2 条一页、5 个条目,导出 → 扫描 → 导入,丢弃的计划不能再执行)。截图:`library-import-preview-*.png`、`tasks-transfers-*.png` | passed。**K20 只覆盖一部分**:中断用复制大文件中途取消来模拟,没有真的杀进程。被杀时留下的只会是 `.trace-*` 临时名,重新扫描会忽略它们,下一次复制再覆盖 |
+| W7 订阅快照与导出导入(K22) | `internal/subscription/snapshot.go`、`snapshot_import.go`;`internal/service/remote_sync.go`(`ExportSubscriptions`;路径是文件夹时用 `trace-subscriptions.json`);`internal/ui/transfer_view.go` 的订阅导出导入对话框 | `TestSnapshotReplaceKeepsStartPointsAndStopsRemovedAccounts`、`TestSnapshotReplaceFailureKeepsPrevious`、`TestSnapshotImportPreviewAndApply`。截图:`subscriptions-import-preview-*.png` | passed |
+| W8 打包、门禁、冒烟、CI(K23、K24) | `tools/package/server.go`(`-server`)、`main.go`(`devInfo`);`tools/check/main.go`(规则 9:`trace-server` 不得依赖界面包;`checkServerBuild`:linux amd64/arm64 交叉编译加 `GOOS=linux go vet ./...`;gofmt 覆盖 `cmd`);`tools/smoke/server.go`;`cmd/trace-server/deploy/`;`.github/workflows/ci.yml` | K23:`go run ./tools/package -server` 产出两个包与 `SHA256SUMS`;`TestWriteTarGzLayoutModesAndLineEndings`;`tools/check` 规则 9 的 3 个合成用例;WSL 里 `sha256sum -c` OK、`file` 显示静态 ELF、`trace-server version` 与桌面版是同一构建号格式(`0.1.3-dev.<时间>`,两个包分开构建所以分钟不同)。K24:见下一行 | passed |
+| K24 回归 | — | `go run ./tools/check` ALL CHECKS PASSED(Go 1.27.4);`go run ./tools/uishots` 64 个场景、192 张图全部通过,三种宽度没有横向滚动,新增 6 个场景;桌面冒烟 `go run ./tools/smoke -pkg dist/trace-dev -out artifacts/smoke` PASSED(3039 ms,托盘专用工作集 0.61 MiB,WebView2 0);远程冒烟 Windows `go run ./tools/smoke -server` PASSED(kill 后重启,1196 ms),WSL Ubuntu 用 Linux 包里的程序 PASSED(SIGTERM,77 ms,`artifacts/smoke-server-linux/smoke.json`);`GOOS=linux go vet ./...` OK。WSL 里还跑了 credential、remoteserver、upload、transfer、subscription、library、storage、download、live、service 的 Linux 测试程序,全部通过 | passed |
+| W9 文档 | `docs/design/remote.md`、`data-and-cache.md`、`architecture.md`;`docs/ui.md`;`docs/dev-rules/engineering.md`;`docs/requirements.md`(FR-REMOTE-001~008);`docs/delivery/roadmap.md`(AC-56~64)、`status.md`;`USER-ACTIONS.md`(Q-022、H-003);`cmd/trace-server/deploy/README.md` | `go run ./tools/checkdocs` OK | passed |
## 2. 整理记录(C0)
| 对象 | 处理 |
| --- | --- |
-| `.local/m4/`(A 的计划草稿,Git 忽略) | 删除(7 个文件,内容已进计划与正本) |
-| `artifacts/review/`(2026-11-09 的旧审查日志) | 删除 |
-| 指向 `stage-plan.md#`、`stage-report.md#` 旧锚点的链接 | 复查后没有剩下的 |
-| 以前阶段的标签 | `docs/research/douyin.md` 5 处、`docs/research/2026-11-12-douyin.md` 12 处,改成直接描述(“方案 M1/M2”是方案名,`SM3` 是算法名,保留);`engineering.md`“本阶段只用这一把密钥”改成“目前”;`status.md` LOOP-013 去掉“M3 审查 F-004”;`decisions.md` DEC-027、DEC-034、DEC-041 去掉指向“当前计划”的链接(DEC-047 是本阶段的,保留);USER-ACTIONS H-001 第 26 步的“(M3)”改成“(抖音)”。决定的“来源”列和研究资料的日期记录保持原样。`architecture.md` 没有找到阶段标签 |
-| 代码注释(LOOP-007) | 改到的文件里去掉 `C09`、`F-056`、`R3`、`R6`、`M4-K10`、`M4-K13`;DEC、ACT、Q 是正本编号,保留 |
-| 生成物 | `artifacts/uishots`、`smoke`、`package`、`dist/trace-dev` 都被工具覆盖成最新一份;`artifacts/release/`、`artifacts/site-check/` 不动 |
-| 临时文件 | K15 比较用的工作树与截图、仓库外的补丁脚本都在用后删除 |
-
-## 3. ACT-020 结果(2026-11-14,1 次,额度已用完)
-
-`go run ./tools/actcheck -act act020`:账本 `runs=1`,API 15/22,`secretScanClean=true`,`tempDataDeleted=true`,回执 `artifacts/site-check/act020.json`。
-
-| 验证点 | 结果 |
-| --- | --- |
-| 哔哩哔哩登录、B-V0 关注 | pass:3 个分组,第 1 页 20 人,`total` 247 |
-| B-V1 收藏夹列表 | pass:4 个,恰好 1 个默认并排第一;没有私密收藏夹(私密位只有合成覆盖) |
-| B-V2 收藏夹内容 | pass:`ps=20` 被接受,2 页各 20 条,页间 0 重复,1 条失效 |
-| B-V3 稍后再看 | pass:WBI 一次通过,全部 92、未看完 91 |
-| B-V4 历史记录 | pass:2 页游标推进、0 重复;两页全是视频(直播、专栏、番剧只有合成覆盖) |
-| 抖音登录、D-V1 关注 | pass:2 页各 20 人,`max_time` 推进、0 重复,`total` 95 |
-| D-V2 喜欢 | fail:HTTP 200,客户端判 `risk_control`(空壳、非 JSON 验证页或挑战字段之一;回执里的原文被当时的脱敏截断,脱敏已改成按完整 URL 匹配,新增测试覆盖)。按停止条件立即停了抖音,没有重试 |
-| D-V3~D-V5 | not-run(因停止而没有发出) |
-
-结论:抖音“观看历史”不显示(Q-015 第 3 条,LOOP-014)。抖音喜欢、收藏、收藏夹只经合成验证。被判风控的原因不确定:可能是测试账号要求验证,也可能是 `favorite` 需要协议资料里没写的请求头或 Cookie 字段。已在 USER-ACTIONS“待你统一处理”请用户先在浏览器确认,再授权复查 1 次。
-
-## 4. not-run 与限制
-
-- 抖音喜欢、收藏、收藏夹的真实站点部分(AC-51):not-run,见上。
-- 只有合成覆盖、真实账号里没出现的:私密收藏夹;历史里的直播、专栏、番剧;稍后再看“已看完”(本账号 `finished=0`)。
-- 实机(H-001 第 28 步):not-run,等用户。
-- Linux:只跑了 `go vet` 和交叉编译,Linux 测试由 CI 跑,本机没跑;`go test -race` 没有 cgo,not-run。
-- 开发版是从未提交的工作区构建的(`-dirty`),源码与交付提交相同。
-
-## 5. 给 A 的审查 prompt
+| `docs/delivery/stage-report.md`(M4 报告) | 已在合并提交里(固定链接见开头)。仍有效的结论已经在正本里(交付状态、决定、USER-ACTIONS),所以整篇改写为本报告。复查后,仓库里没有指向旧报告或旧计划锚点的相对链接 |
+| USER-ACTIONS 里已完成的 ACT | ACT-001~007、009~012、014~021 移到“最近处理完的”,保留锚点,各精炼成一行。ACT-008 仍有效,留在原处 |
+| 以前阶段的标签 | `roadmap.md` 的“(M4,”改为能力描述;`status.md` 的 LOOP-010 标签改为能力描述。新测试的注释不带 `M5-Kxx` |
+| 根目录 `package.exe` | 是 `go build ./tools/package` 的残留,被误加入了仓库。已 `git rm --cached` 并删除,`.gitignore` 加了 `/*.exe` |
+| `dist/`、`artifacts/`、`tmp/` | `dist/` 按类各留一份:`trace/`(发行版,不动)、`trace-dev/`、`trace-server/`。`artifacts/` 里的 `smoke-server`、`smoke-server-linux` 是新的冒烟回执,各一份。两个用户数据备份没有动(见第 1 节)。`tmp/` 是本次实施用的临时脚本与 WSL 测试程序,被忽略,交付后可以整个删除 |
+| 测试名 | 新测试都按能力命名(第 1 节的表),没有阶段号或问题编号 |
+
+## 3. 依赖盘点(D1)
+
+- PR #9(`golang.org/x/image` 0.47.0 → 0.48.0)的改动已经并入本阶段提交。关闭 PR 要操作 GitHub,没有授权,所以 PR #9 还开着;合并后 Dependabot 会自动关闭它,不会的话由用户关闭。
+- `go run ./tools/deps`:开始时把满 7 天的都升了:`mp4ff` v0.62.0 → v0.62.1、`mygo` v0.8.3 → v0.9.0、`x/image` → v0.48.0、`x/text` v0.43.0 → v0.44.0(间接依赖)。交付前到期 0 个。还在等 7 天的有 2 个:`mp4ff` v0.63.0(第 6 天)、`mygo` v0.10.0(第 1 天)。
+- `mygo` v0.9.0 在 `go.mod` 里带进 6 个间接模块(`go-crypto`、`circl`、`compress`、`xz`、`rpm`、`x/crypto`)。它们只被 `mygo/cmd/mygo` 使用,不会链接进 TRACE 或 `trace-server`(`go list -deps` 已核对)。
+- `go run ./tools/deps -audit` passed:called 0,没有例外,另有 7 条在代码没调用到的模块里。
+- 升级后重新跑了 `tools/check` 与 `uishots`,都通过。
+
+## 4. 实现中的决定(都可逆,没有写成 DEC)
+
+1. **导入选文件夹、导出选目标**:用路径输入框,没有用系统文件对话框(Q-022 第 11 条)。MyGo 没有原生选择器,保留以后换成原生对话框的空间。
+2. **任务页的分段叫“导入导出(N)”**(Q-022 第 12 条)。导入与导出是同一类后台任务,合在一个分段里。
+3. **没选处理方式的冲突在导入时跳过**;“不同作者文件夹”的冲突保留本地的文件夹(Q-022 第 13 条)。导入页可以一次给全部冲突定处理方式。
+4. **导出范围是媒体库当前的整个筛选结果**,不只是已经加载的那一页(Q-022 第 14 条)。实现时发现 `ListItems` 默认最多返回 200 条,导出会截断,已改为按 500 条一页分页导出(`exportPageSize`),有测试覆盖。
+5. **导入的文件校验不过时**,记进条目的“缺失”,条目标为部分完成,不当作完成。
+6. **两个节点各录了一部分的同一场直播**,导入时按开始时间合并为一场,段号重新编为连续的,`cachedBy` 保留。
+7. **DASH 中间文件改名为 `.trace-` 开头**;旧名字的进行中下载会被接管续传(K01)。
+8. 远程不做全部缓存。`startDueFullCacheSweeps` 没有专门判断远程:远程配置下全部缓存的规则不建队列,因此它什么也不会启动,测试断言了这一点。
+
+## 5. not-run 与限制
+
+- **H-003(真实 VPS、真实站点、Google Drive)not-run**:本阶段没有发真实站点请求,也没有连接网盘。步骤已按实际命令、包名和界面文案写进 [H-003](../../USER-ACTIONS.md#h-003),部署说明在 `cmd/trace-server/deploy/README.md`(也随包分发)。
+- **`go test -race` not-run**:本机没有 cgo 工具链,与以前的阶段相同。
+- **Windows 冒烟不发 SIGTERM**:Windows 不能给子进程发 SIGTERM,所以远程冒烟在 Windows 上 kill 后重启,验证锁释放和数据可以重新打开。正常退出(SIGTERM、退出码 0、录制收尾)在 WSL 用 Linux 包里的程序验证过。
+- **导入导出任务只在内存里**:退出 TRACE 后任务列表清空;重新扫描同一个文件夹会继续导入(相同的跳过、缺的补上),不会重复复制。
+- **旧版开发版退出慢**:已查明是抖音录制的死锁,见[第 7 节](#feedback-1)第 1 条,已修复。
+- **体积**:`trace-server` 程序 16.1 MiB(amd64),桌面 `trace.exe` 25.0 MiB。远程版不链接 MyGo、界面、播放器、托盘与语言包,由 `tools/check` 的规则 9 守护。
+
+## 6. 给 A 的审查 prompt
```text
-你是 TRACE 的 Agent A,集中审查 M4(我的:登录账号的站点内容)。
-
-计划 docs/delivery/stage-plan.md(TRACE-M4-01 修订 1 + D1),报告 docs/delivery/stage-report.md(第 1~5 节)。
-分支 codex/m4-account,基点 main @ f080483,交付 SHA 见 B 的交付消息(阶段只有这一个 DCO 提交)。
-
-重点:
-1. AccountService(internal/service/account.go):发请求前查登录、功能与熔断;风控与限流按站点记自动停止;
- 日志与文件不含列表内容(TestAccountPrivacySentinels);safeBrowserURL 白名单。
-2. 抖音表单 POST(internal/site/douyin/client.go 的 form):GET 签名字节不变,表单体进入 a_bogus。
-3. “我的”界面(internal/ui/mine.go):首次选择才请求、翻页不并发、从详情返回不重发、退出或换账号才清空;
- renderCompactVideoRow 抽取后用户页外观不变(报告 K15 的像素对比)。
-4. ACT-020:抖音 D-V2 被判风控,D-V3~D-V5 没发;观看历史隐藏(LOOP-014);复查需要用户新授权,
- 不要再跑 act020。
-5. D1:go 1.27.4、x/sys v0.50.0;tools/deps -audit passed。DEC-048 的文件是另一会话写入、计划列为 D1 的,
- B 没改内容,请确认它们进本阶段提交是对的。
-
-验证:go run ./tools/check、GOOS=linux go vet ./...、go run ./tools/uishots -out artifacts/uishots、
-go run ./tools/smoke -pkg dist/trace-dev -out artifacts/smoke。局部问题直接修并 amend(git commit --amend -s),
-较大缺口按交接模板 §3 一次性交回。未授权:push、PR、合并、标签、发布。
+你是 TRACE 的 Agent A,动作:集中审查 M5(远程版、上传与导入导出)B 的交付。
+- 计划:docs/delivery/stage-plan.md(TRACE-M5-01 修订 1);设计正本 docs/design/remote.md;决定 DEC-062;需求 FR-REMOTE-001~008;验收 AC-56~64;默认值 USER-ACTIONS 的 Q-022(第 11~14 条是 B 另定的);人工检查 H-003。
+- 分支 codex/m5-remote,基点 main @ 8327803;交付 SHA 见 B 的交付消息(计划提交 ca72b48 之上的单个 DCO 提交)。报告 docs/delivery/stage-report.md 第 1~5 节,以及第 7 节(2026-11-20 实机反馈的 5 处修复:抖音开录死锁、抖音共创作品存放位置 DEC-063、图文配乐、主页订阅名、全部缓存补不完整的条目)。
+- 重点:凭证与令牌不进日志、状态和文件(remoteserver、upload.sanitize、remote_client);上传先媒体后 item.json、确认后才删除;导入的临时名、校验与中断恢复(transfer/apply.go);两节点直播合并;“设置 › 远程”、导入页、任务页“导入导出”、订阅导出导入的交互与 docs/ui.md 是否一致;trace-server 的依赖边界(tools/check 规则 9);报告第 1 节里标了“只覆盖一部分”的 K05、K11、K20;第 7 节末尾的补充审查点。
+- 必须保留:M1~M4 与 DEC-059~061 的行为与测试;数据结构版本 2;INV-01~14;按站点的额度、退避与熔断;安静测试、不碰本机安装的应用;只删登记文件;dist 只留最新一份。
+- 验证:go run ./tools/check;需要时跑 go run ./tools/uishots、go run ./tools/smoke -server、go run ./tools/package -server;有 WSL 时可用 Linux 包跑远程冒烟。不发真实站点请求,不连接网盘;H-003 保持 not-run。
+- 直接修复局部问题并 amend 进同一个提交(git commit --amend -s),把审查结论追加到 stage-report.md;较大的缺口按交接模板 §3 列差异清单交回 B。
+- 未授权:push、PR、合并、标签、发布。
```
-
-## 6. A:集中审查(2026-11-14)
-
-**基点与范围**:B 交付 `8f92c12`(`main @ f080483` 之上的一个 DCO 提交,44 个文件)。读了计划、报告与正本(需求 §2.9、界面 §3.11、两份协议的账号列表节),逐个看了 `internal/service/account.go`、`internal/site/bilibili/account.go`、`internal/site/douyin/account.go` 与 `client.go` 的 POST 改动、`internal/ui/mine.go`、`views.go` 的 `renderCompactVideoRow` 抽取、`douyin_views.go` 的卡片参数、`tools/actcheck/act020.go` 与回执、隐私哨兵测试;复核了 D1 和 DEC-048 文件的归属。没有逐行读的:`tools/uishots/mine_fixture.go`、`tools/deps/main.go`(DEC-048 的工具,由测试和本次实跑覆盖)。
-
-**结论**
-
-| 方面 | 结论 |
-| --- | --- |
-| 实现交付 | C0、W1~W6、D1 与 M4-K01~K15 都有实现与证据;ACT-020 的抖音喜欢、收藏、收藏夹为 `not-run`(被判风控后按规则停下),报告与交付状态如实写了 |
-| 技术审查 | 发现 2 个 P2,A 已直接修复并复验(F-001、F-002);没有 P0、P1。修复后收敛 |
-| 产品验收 | 未开始:H-001 第 28 步(实机看“我的”)为 `not-run`;抖音三项没有真实站点证据(LOOP-014) |
-
-**问题**
-
-| 编号 | 严重度 | 位置与触发 | 实际结果与影响 | 依据 | 修复与复验 |
-| --- | --- | --- | --- | --- | --- |
-| F-001 | P2 | `internal/ui/mine.go` `renderMineWorkGrid`:抖音喜欢/收藏里有 TRACE 不支持的作品(直播卡片 `aweme_type=101` 或没有可用视频流,服务层给 `Kind=unsupported`) | 仍用普通作品卡片画:本体可点,打开后详情页报“暂不支持”;“⋯”里有“缓存”(`Uncacheable` 为假),点了只会得到失败的任务 | FR-ACCT-003、界面 §3.11“打不开的条目……本体不可点,只能在‘⋯’里在浏览器中打开” | 新增 `renderMineUnsupportedWorkCard`:灰色 3:4 块写类型,不可点,“⋯”只有“在浏览器中打开”。`TestMineUnsupportedDouyinWorkIsNotClickable`(在 B 的版本上失败:“the unsupported work can be opened”,修复后通过) |
-| F-002 | P2 | `mine.go` `mineLoadFolders`:结果用 `Mine.gen` 判断是否过期,而 `mineEnsureList` 每建一个新列表都会让 `gen` 加一 | 分组或收藏夹列表还在路上时选了别的功能(例如选“关注”后马上点“历史记录”),返回的分组被当成过期丢掉,回到原功能时再请求一次;抖音“收藏”的收藏夹列表最多 5 页、每页至少隔 1 秒,等于多发最多 5 次受保护接口 | FR-ACCT-002“之后切到别的功能再切回来……不重新请求”;NFR-NET-003 少发请求 | 改用只在 `mineClearSite`(退出、失效、换号)时加一的 `clearGen`。`TestMineFoldersSurviveChoosingAnotherFunction`(在 B 的版本上失败:“following groups were dropped”,修复后通过;同时断言清空站点后到达的结果仍被丢弃) |
-
-**文档同步**:界面 §3.11 的 B 站关注“订阅:X(点击进入订阅)”与实现不符——整行本体是打开用户页的按钮,里面再嵌一个按钮会抢点击;改为“整行点击打开用户页,进入订阅用‘⋯ → 打开订阅‘X’’”,与实现和抖音关注一致。
-
-**复核过、没有问题的要点**
-
-- 发请求前的检查:`accountGate` 先查站点、登录、功能是否在 `AccountSections` 里、站点退避,再发请求;未登录时 `AccountSections` 只返回登录条目。风控与限流经 `accountFail` 记到该站点的自动停止,只影响这个站点(`TestAccountBreakerPerSite`)。注意这是计划写明的做法:在“我的”里点一次被判风控的抖音“喜欢”,抖音的定时检查也会按退避暂停,退避期间“我的”的抖音也直接显示退避原因——已在 LOOP-014 写明,复查抖音时一并确认。
-- 隐私:服务层只记 `account.. page/items/more` 与错误类别;`TestAccountPrivacySentinels` 浏览全部功能后扫描数据、日志、缓存目录无哨兵,最近解析只在 `OpenLink` 后多一条;界面状态 `Mine` 不进 `ui-state.json`。抖音账号接口的错误只带不含查询串的接口地址。
-- 抖音 POST:只有 `form != nil` 才改成 POST,表单体同时进入 `a_bogus` 的 `Body` 与请求体,GET 路径不变(已有签名测试断言未改);`strings.Reader` 让重定向可以重放请求体。
-- 翻页:哔哩哔哩历史游标不前进、收藏夹/稍后再看“有下一页却空页”、抖音游标不前进都按 `schema_changed` 停下;界面同一列表的翻页用 `requestGuarded` 的同名请求去重,退出或换号后到达的结果因 `Lists[key] != l` 被丢弃。
-- 浏览器入口 `safeBrowserURL` 只放行 https、443、站点域名后缀、无用户信息的地址(`TestSafeBrowserURL`)。
-- 打开详情走 `OpenVideo`/`OpenUser`/`OpenDouyinWork`/`OpenDouyinUser`,它们都调用 `openLink`,记入最近解析。
-- ACT-020:账本 `runs=1`、15/22,未登记的接口在传输层拒发,回执没有标题、昵称、ID。回执是在 `eec4da2-dirty` 的工作区上跑的,不是最终交付的提交;哔哩哔哩四项只证明站点层当时的写法,此后站点层没有改协议参数。D-V2 的错误原文当时被脱敏截断,B 已改脱敏规则并加测试。
-- D1:A 复跑 `go run ./tools/deps`(满 7 天 0 项;`mp4ff` v0.63.0 0 天、`mygo` v0.9.0 2 天、`x/image` v0.48.0 4 天未到期)与 `go run ./tools/deps -audit`(`passed`,called 0、例外 0、未调用 7);`gh pr list` 没有开着的 Dependabot PR。DEC-048 的文件(`tools/deps/`、`dependabot.yml`、`ci.yml`、`AGENTS.md` 等)是计划 D1 列入本阶段的内容,按“一个阶段一个提交”进本阶段提交是对的。
-
-**建议(不算缺陷)**
-
-- 抖音账号列表对任何一页的 `aweme_list: null` 都按空壳处理,比协议 §12 写的“第 1 页”更严;真实站点在最后一页是否会给 `null` 还不知道,复查抖音时留意(LOOP-014)。
-- 抖音列表里 `status.is_delete` 的作品直接跳过,不显示“已失效”;站点本身多半不返回这类条目,按反馈再定。
-
-**A 的验证**(修复后的工作区):
-
-| 命令 | 结果 |
-| --- | --- |
-| `go test ./internal/ui/ -run TestMine -count=1` | ok(含 2 条新回归测试;在 B 的 `mine.go` 上这 2 条失败) |
-| `go run ./tools/check` | ALL CHECKS PASSED(1m53s;另在 B 的 `8f92c12` 上先跑过一次,1m07s 通过) |
-| `GOOS=linux go vet ./...` | OK |
-| `go run ./tools/uishots -out artifacts/uishots` | 46 个场景、138 张 PNG 全部通过 |
-| `go run ./tools/package -install` | 开发版 `0.1.2-dev.202611140903`(`VERSION.txt` 提交 `c9bfa5b`,不带 `-dirty`),从 `0.1.2-dev.202611140852` 静默升级,安装时 TRACE Dev 没在运行。安装包 SHA-256 `99287ca2944b3d9a9745521fb41d6d48f6052207a68265a4a008fdad462f9c3a`,`trace.exe` `9257df12bf4b3f1dd273d7955a255c62ec65db15367680c64fc988a317bf0a39` |
-| `go run ./tools/smoke -pkg dist/trace-dev -out artifacts/smoke` | 第 1 次 FAILED(12.7 秒,`wait second_instance.json: timed out`,第二实例 8 秒内没写出快照);紧接着第 2 次 PASSED(2.9 秒,托盘专用工作集 0.61 MiB,WebView2 0)。本次只改了“我的”界面,与单实例无关;第 1 次是新构建的程序第一次启动,推测是首次启动变慢(如安全软件扫描),原因未确认。再出现就登记 LOOP 查单实例的等待时间 |
-| `go run ./tools/deps`、`go run ./tools/deps -audit` | 见上 D1 |
-
-修复 amend 进阶段提交后(`c9bfa5b`)打包;之后只把本节的验证结果补进报告、再 amend 一次,代码与开发版相同,最终 SHA 见 A 的交付消息。没有 push 或 PR。
-
-## 7. 实机反馈第一轮(2026-11-14,A 修复与规划)
-
-用户装了 `0.1.2-dev.202611140903` 后给了 8 条反馈,2026-11-15 又补充 4 条。A 直接修了 7 条(F-003~F-009);5 条功能调整记 [DEC-049](../decisions.md#dec-049)、[DEC-050](../decisions.md#dec-050),交给 B 按[计划 §11、§12](stage-plan.md#feedback-1) 实现。
-
-| 编号 | 反馈 | 根因 | 修复与回归测试 |
-| --- | --- | --- | --- |
-| F-003(P1) | 设置“缓存规则”里展开一条规则后再点它缩起,软件闪退 | 点击把 `RuleDraft` 置空后,同一帧里旧的 `editing` 判断仍调用 `renderRuleEditor`,解引用空指针(`rules_view.go`) | 点击后重新读 `RuleDraft` 再决定是否画编辑器,`renderRuleEditor` 对空草稿直接返回。`TestCacheRuleFoldsAgainWithoutCrashing`(展开、缩起各两次;修复前在同一位置 panic) |
-| F-004(P1) | 一场哔哩哔哩直播录像的 `item.json` 记着 `part-001.mp4.part` “转换失败,临时片段已保留” | 哔哩哔哩 HLS fMP4 的音频分片和上一片重叠 32 个时间单位(48 kHz 下不到 1 毫秒),mp4ff 的 `Defragment` 遇到“下一片从上一个采样中间开始”就拒绝。用户的文件(ftyp、moov、382 组 moof/mdat)实测报错 `traf of track 2 … starts at 213381072 inside sample [213380080,213381104)` | 转换前把每条轨道上一片最后一个采样的时长减去重叠(只处理小于一个采样的重叠,`internal/live/overlap.go`);用户的文件修复后转出 95.281 秒、moov 在前、两轨相差 0.008 秒。启动恢复也加固:媒体记录时长为 0 的片段(未转换的原始 fMP4,即使已叫最终文件名)会重新转换,失败就退回原名、不丢文件;运行中的转换失败把原因写进录制的错误信息。`TestFinalizeLivePartTrimsSubFrameFragmentOverlap`、`TestRecoveryConvertsUnconvertedSegmentUnderFinalName`(修复前都失败) |
-| F-005(P2) | 抖音订阅的头像重启后变成名字生成的图 | 抖音头像地址带签名查询串,`sanitizeAccountFace` 按 NFR-SEC-003 不把它写进 `subscriptions.json`,于是重启后没有头像可用 | 头像下载到本机 `/avatars/<站点>-.png`(只存图片,不存地址;7 天内不重取;订阅检查、关联账号、打开用户页时更新;删除订阅或解除关联时清理,只删符合命名的文件)。界面优先用本机头像。`TestDouyinSubscriptionKeepsALocalAvatar`(PNG 出现、订阅文件里没有地址、删除后清理、无关文件保留)。已有的抖音订阅在下一次检查更新或打开用户页后补上头像 |
-| F-006(P2) | 哔哩哔哩实况照片还是不会动(给了动态 `1269437400365400067` 和它的 mp4) | 缓存是对的:这条动态的 `images/01_live.mp4` 就是用户给的片段(AVC、无音轨、2.576 秒),播放器能解码并从 0 播到 2.576 秒。问题在交互:看图层要点底部会自动隐藏的小“播放”按钮才播 | 实况照片翻到这一页就自动播放动态片段,按钮用来重播(DEC-049 ④,界面 §3.5)。`TestBilibiliLivePhotoPlaysInTheViewer` 改为不点按钮也开始播放;`TestDouyinWorkVideoNoteBGMAndViewerInlinePlayback` 改为翻到实况页自动播放、配乐保持暂停 |
-| F-007(P1) | 抖音“喜欢”和“收藏”返回空响应,是否风控 | 用户同意后复查 1 次(测试 Cookie,5 次 API,无挑战与限流,[抖音协议 §12](../research/douyin.md#account-lists) 的“复查”):“喜欢”对三种写法都回 HTTP 200、0 字节;同一会话的“收藏”正常返回 18 条。所以“喜欢”是这个接口不回应非浏览器请求,不是账号风控。用户看到“收藏”也空,是因为“喜欢”的 0 字节被判成风控、打开了抖音的整站退避,之后收藏在发出前就被拒(日志只有两条 `account.douyin.likes error=risk_control`),同时抖音的定时检查也暂停了 | “喜欢”的 0 字节改判为 `unavailable`,提示“抖音只把‘喜欢’列表给浏览器里的抖音网页,TRACE 取不到;其他功能不受影响”,不打开退避;其他接口的 0 字节仍判风控。`TestDouyinLikesRefusalLeavesTheSiteRunning`(修复前打开退避)、`TestFavoritesShellVersusEmpty` 更新。要真正拿到“喜欢”,需要一条浏览器通道,见 Q-016 第 1 条 |
-| F-008(P2,2026-11-15 补充) | 托盘右键菜单离图标太高、中间有空隙,字体偏大,项太多 | MyGo 的托盘菜单按 Windows 11 的做法居中在图标上方、离任务栏 12 DIP,用它自己画的较大字体,没有选项可改 | 托盘不再交给 MyGo 的菜单:右键时在指针处打开系统原生菜单(`TrackPopupMenuEx`,系统菜单字体,Windows 11 圆角),只有“打开 TRACE Dev”“退出”;左键打开窗口;任务与录制数量放到悬停提示(`internal/shell/traymenu_windows.go`,其他系统仍用 MyGo 菜单)。DEC-050 ③。`TestTrayMenuOnlyOpensAndQuits`;菜单的位置与外观只能实机看(H-001 第 29 步) |
-| F-009(P1,2026-11-15 补充) | 解析里打开抖音用户的作品列表很卡,“缓存更早的内容”之后更卡 | 每一帧都为**全部已加载作品**查一次媒体库状态(每条一次 SQLite 读取,外加扫描全部下载任务),每张可见卡片再读一次条目找本机封面;作品越多、下载任务越多越卡,缓存更早的内容会同时让两者变多,任务事件又让界面频繁重画。“我的”的作品网格同样如此 | 卡片的状态与本机封面改为只为可见的行读取,并缓存到任务或媒体库变化为止(`workCardLocals`),未缓存的作品不再读条目。`TestDouyinWorkGridDoesNotReadTheLibraryEachFrame`(300 条作品:修复前两帧读 1200 次状态、之后每帧 600 次;修复后首帧只读排出的行,之后的帧 0 次,状态变化后只重读可见行)。剩余:“未缓存”筛选打开时,状态每变一次仍要查全部已加载作品,下载进行中会较频繁,按反馈再处理 |
-
-**交给 B 的**(DEC-049 ①~③ 与 DEC-050 ①②,计划 §11、§12):缓存队列(“全部缓存”以较慢、不规律的速度在后台缓存一个账号的全部内容)与任务页侧栏(下载任务、缓存队列、直播录制);以及 2026-11-14 的 3 条:直播录制不计入任务角标、任务页单独的“直播录制”标签与实时预览(实时弹幕放下一阶段);解析页用侧栏放最近解析、主面板只留居中的输入框;媒体库是独立的离线内容(不按缓存时间排序,点击和详情都不进解析页)。
-
-**A 的验证**(修复后的工作区):
-
-| 命令 | 结果 |
-| --- | --- |
-| 新增与改动的回归测试(见上表) | 修复前失败、修复后通过(F-006 是行为调整,测试随之改写) |
-| 用户的录像 `part-001.mp4`(离线副本,不进仓库) | 修复前 `Defragment` 报重叠;修复后转出 95.281 秒,moov 在前 |
-| 抖音复查(真实站点,测试 Cookie) | 5 次 API,喜欢 3 次 0 字节、收藏 18 条,无挑战与限流;探针是临时测试文件,跑完已删 |
-| `go run ./tools/check` | ALL CHECKS PASSED(2m0s) |
-| `GOOS=linux go vet ./...` | OK |
-| `go run ./tools/uishots -out artifacts/uishots` | 138 张全部通过 |
-| `go run ./tools/package -install` | 开发版 `0.1.2-dev.202611141406`(提交 `2595b98`),从 `0.1.2-dev.202611140903` 静默升级,安装时 TRACE Dev 没在运行。安装包 SHA-256 `d51af53f034626d1a24be864ac63cac78919013804c21851aca29d0704d0dcd9`,`trace.exe` `9d23463f5ae468edd720f75f3a3d1d9f2f932fd22814d7ce7424cd7aabb27c1e` |
-| `go run ./tools/smoke -pkg dist/trace-dev -out artifacts/smoke` | PASSED(3.0 秒,托盘专用工作集 0.59 MiB,WebView2 0) |
-
-修复 amend 进阶段提交后打包;之后只把本表补进报告、再 amend 一次,代码与开发版相同。没有 push 或 PR。H-001 第 29 步(实机复查)为 `not-run`。
-
-**2026-11-15 补充(F-008、F-009)的验证**:
-
-| 命令 | 结果 |
-| --- | --- |
-| `go test`(`TestTrayMenuOnlyOpensAndQuits`、`TestDouyinWorkGridDoesNotReadTheLibraryEachFrame`) | 通过;后者在修复前的代码上失败(两帧读 1200 次状态) |
-| `go run ./tools/check` | ALL CHECKS PASSED(1m42s) |
-| `GOOS=linux go vet ./...` | OK |
-| `go run ./tools/uishots -out artifacts/uishots` | 138 张全部通过 |
-| `go run ./tools/package -install` | 开发版 `0.1.2-dev.202611150223`(提交 `0a6045c`),从 `0.1.2-dev.202611141406` 静默升级,安装时 TRACE Dev 没在运行。安装包 SHA-256 `f0dc17c96ba617fd97a8d6348298f1b88ed0f46e1e931d84596b9b602ced055e`,`trace.exe` `cef9a874cc56079cda2b4c7d47a5ecf40f01231c7862c36ade5ba167ad981f34` |
-| `go run ./tools/smoke -pkg dist/trace-dev -out artifacts/smoke` | **17 次中 15 次 PASSED、2 次 FAILED**(`StealFocusDetected = true`,打包后最先的几次);改动前的提交 `ab3cd3f` 打的包连跑 8 次全过。原因未确认,记 LOOP-015,交 B 复现 |
-
-托盘菜单的位置、字体与左键打开只能实机看(H-001 第 29 步⑥),为 `not-run`。
-
-
-## 8. B:第一轮反馈的实现(2026-11-15)
-
-按[计划 §11、§12](stage-plan.md#feedback-1)(修订 3)连续完成 R1~R4、Q1~Q3 及必测用例 M4-K16~K31,保留 A 在 §6、§7 的全部修复与回归测试(F-001~F-009),没有新增第三方依赖,没有发起任何真实站点请求。
-
-| 信息 | 内容 |
-| --- | --- |
-| 执行范围 | R1~R4、Q1~Q3 与必测用例 M4-K16~K31 全部完成,无缩减验收;LOOP-015 复现与修复核实见下 |
-| 版本与工作区 | 分支 `codex/m4-account`,基点 `main @ f080483`;全部实现、文档与回归测试均已 amend 进同一个阶段提交(含 DCO `Signed-off-by:`,单阶段单提交),代码提交 `9f8eff8` 打包后仅回填本节验证数值并再次 amend(源码与开发版一致,最终交付 SHA 见交付消息);未执行 push、PR、合并或打标签 |
-| 可运行产物 | `go run ./tools/package -install`:开发版 `0.1.2-dev.202611150644`(`VERSION.txt` 提交 `9f8eff82935a`,`built_at=2026-11-15T06:44:16Z`,干净工作区构建、不带 `-dirty`),已从 `0.1.2-dev.202611150223` 静默自动升级本机 `TRACE Dev`(安装时未在运行,用时 `1401 ms`,`artifacts/package/install-dev.json`)。`trace-dev-setup-0.1.2-dev.202611150644-amd64.exe` SHA-256 `42734b72b19117e5efb3a8d28a6f7402e16cab92fa6410078be4bde9adcb2bbe`,`trace.exe` `f2fbd2e506ab29ef55b137cae53238c4bd968f80966466f7674d45326c6d3d2b`(`dist/trace-dev/SHA256SUMS.txt`) |
-| 关键变更与恢复 | 现有 v2 数据文件(`library.db`、`updates.db`、`subscriptions.json`、`ui-state.json`)结构完全不变;新增独立文件 `/cache-queue.json`(`version: 1`,原子写,遇到更高未知版本拒绝覆盖,不含任何 Cookie 或签名 URL),仍可直接装回上一个开发版。旧 `CacheOlderUserItems`(10/20/50 条立即入队)已由 `EnqueueCacheQueue` 等“全部缓存”慢速不规律队列接口替代 |
-
-| 工作包 / 用例 | 实现位置 | 实际命令与证据 | 状态与限制 |
-| --- | --- | --- | --- |
-| R1 解析页侧栏与居中大输入框(K16、K17) | `internal/ui/shell.go`、`views.go`、`app.go`:`/parse` 接入与 `/video`、`/user` 共用的“最近解析”上下文侧栏并高亮当前打开项,主面板改为全宽留白中央单一大输入框(窄窗 `< 1000` 的“最近解析”入口见 A 审查 F-011),输入法组合态保护不变 | `TestParsePageCenteredInputAndHistorySidebar`、`TestVideoUserAndParseShareSameHistorySidebarWithActiveHighlight`;`tools/uishots` 解析页有历史与空历史三档宽度截图 | passed |
-| R2 媒体库固定排序与纯离线详情(K18、K19) | `internal/ui/library_view.go`、`views.go`、`shell.go`、`app.go`:去掉“缓存时间”排序切换并静默忽略旧 `ui-state.json` 里的 `cached_at` 偏好,固定按发布时间(录像按开播时间)从新到旧排列;点击卡片直接本机播放/看图,“⋯ → 详情”打开纯离线 `/library/item`(零站点请求、不写最近解析,返回保留原筛选与位置),仅右上角“⋯ → 在解析页打开”进入解析页联网 | `TestLibraryHasNoSortToggleAndIgnoresLegacyCachedAtSort`、`TestLibraryOfflineNavigationNeverLeavesLibraryOrRequestsSite`;`tools/uishots` 媒体库与 `/library/item` 本机详情三档宽度截图 | passed |
-| Q1 缓存队列服务与持久化(K24~K27、K29) | `internal/service/cache_queue.go`、`batch_cache.go`、`backend.go`、`browsing.go`、`avatars.go`、`dto.go`、`events.go`:实现 `ListCacheQueue` / `FindCacheQueueTask` / `EnqueueCacheQueue` / `PauseCacheQueue` / `ResumeCacheQueue` / `CancelCacheQueue`,独立持久化 `/cache-queue.json`(`version: 1`);按站点各自串行、每次只排 1 条下载,可注入时钟与随机源驱动两条间 40~150 秒随机等待、每 15~25 条长歇 10~25 分钟、风控退避后加 10~30 分钟缓冲、启动后 1~5 分钟恢复,自动翻页经 `site.WithAutomaticRequests` 共用站点每小时额度与退避;移除旧 `CacheOlderUserItems` 及 10/20/50 选项 | `TestCacheQueue300ItemsPacingAndSingleDownloadConcurrency`、`TestCacheQueuePagingQuotaBackoffAndCrossSiteIsolation`、`TestCacheQueueRestartAuthPauseResumeCancelAndDedupe`、`TestCacheQueuePrivacySentinel`、`TestCacheQueueSkipsCachedDuplicatesAndOrdinaryItemErrors`、`TestEnqueueCacheQueueValidatesRequestAndLoadedList` | passed |
-| Q2 + R3 任务角标、任务页三栏与直播 `.part` 实时预览(K20~K23、K28) | `internal/player/{mf_live_windows,live_fmp4,mf_other,player,synth,video_worker}.go`、`internal/live/{live_preview,recorder,douyin_live,manager}.go`、`internal/service/{backend,browsing,dto}.go`、`internal/ui/{tasks_view,cache_older,views,douyin_views,shell,app}.go`:图标栏“任务”数字角标只数排队与进行中的下载任务;用户页与抖音用户页“⋯”改为“全部缓存 / 在缓存队列中查看”;任务页上下文侧栏切换“下载任务(N)/ 缓存队列 / 直播录制(N)”(窄窗顶部切换);“直播录制”页内只读打开增长中的本机 `.part` 实时预览(HLS fMP4 与 HTTP-FLV 双路径,零额外站点连接、无实时弹幕,离开或停止录制立即同步释放句柄,保留 F-004 子帧重叠裁剪与 `Defragment` 收尾) | `TestTasksBadgeCountsOnlyActiveDownloadTasks`、`TestUserPageCacheAllQueueEntry`、`TestTasksSidebarSectionsAndCacheQueueDetail`、`TestTasksLiveRecordingRealTimePreviewAndHandleRelease`、`TestBilibiliHLSRecordingPreviewStateRolloverAndZeroExtraHTTP`、`TestBilibiliHLSRecordingPreviewSegmentRolloverAdvancesPartIndex`、`TestDouyinHTTPFLVRecordingPreviewAndAudioOnlyUnsupported`、`TestOpenLivePreviewGrowingHLSAndFLVFMP4AndDanmakuSuppressed`、`TestLivePreviewBlockedTailImmediateUnblockAndWindowsRename`、`TestLivePreviewTailWindowJoinsNearLiveEdge`、`TestOpenLivePreviewRejectsUnsupportedContainersAndReleasesHandle`、`TestEndToEndLiveRecorderAndPlayerPreviewFinalizeWithoutHandleConflict`、`TestLiveRecordingPreviewPassthrough`;`go run ./tools/uishots -out artifacts/uishots`:49 个场景、147 张 PNG 全部通过 | passed |
-| LOOP-015 与 10 次连续冒烟(K30、K31) | `internal/shell/shell.go`、`priority_windows.go`、`priority_other.go`、`traymenu_test.go`、`tools/smoke/main.go`、`main_test.go`:安静模式(`s.quiet != ""`)屏蔽托盘点击/原生右键菜单与全屏切换、补 `reuse_window` 与 `second_instance` 焦点核对、新增不含标题的 `StealFocusDetail`(阶段名、HWND 类名、可见性) | `TestTrayMenuOnlyOpensAndQuits`(K30)、`TestQuietModeSuppressesTrayClickAndMenu`、`TestQuietModeTrayIconCloseToTrayAndMemory`、`TestFormatFocusFailure`;开发版 `0.1.2-dev.202611150644` 连跑 10 次 `go run ./tools/smoke -pkg dist/trace-dev -out artifacts/smoke`:**10/10 全部 PASSED**(单次 `2835~2944 ms`,托盘专用工作集 `0.55~0.60 MiB`,`webview2=0`,`stealFocusDetected=false`) | passed(焦点检查未做任何放宽) |
-| R4 + Q3 文档与门禁、D1 复跑 | `docs/requirements.md`、`docs/ui.md`、`docs/design/{architecture,data-and-cache,subscriptions,live}.md`、`docs/delivery/{roadmap,status,stage-report}.md`、`docs/dev-rules/engineering.md`、`USER-ACTIONS.md`(H-001 第 30 步、Q-016/Q-017) | `go run ./tools/deps`(`due=0`)、`go run ./tools/deps -audit`(`passed`,`called=0`)、`go run ./tools/check`(`ALL CHECKS PASSED in 1m0.326s`)、`GOOS=linux go vet ./...`(OK)、`go run ./tools/checkdocs`(OK);F-001~F-009 回归单测全部通过 | passed |
-
-### R3 直播录制页内实时预览技术验证结论
-
-- **路径 A(哔哩哔哩 HLS fMP4,`internal/live/recorder.go`)**:**支持**。实测验证含非零起始 `tfdt`(如数小时开播时间戳)及跨分片子帧音频重叠的 `init + moof+mdat` 增长 `.part` 文件,Windows Media Foundation 双独立 `IMFSourceReader`(视频与音频各自独立读取器)可持续追加解码并推进画面与音频时钟;F-004 收尾子帧重叠裁剪与恢复逻辑原样保留。
-- **路径 B(抖音 / 哔哩哔哩后备 HTTP-FLV 转写 fMP4,`internal/live/douyin_live.go`、`remux.go`)**:**支持**。`ftyp+moov` 与按 GOP 刷盘的多轨 `moof+mdat` `.part` 文件可持续边写边读解码,全程不向站点或直播 CDN 发起任何额外连接。
-- **不支持场景如实说明**:纯音频电台直播(`AudioOnly=true`)或非分片 MP4(无 `mvex`)不绕过、不另开连接,直接返回 `PreviewSupported=false` / `ErrLivePreviewUnsupported`(提示“这场录制暂不支持实时预览”)。
-- **Media Foundation 增长流读取与同步句柄释放**:`internal/player/mf_live_windows.go` 以 `FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE` 打开本机 `.part`,通过纯 Go COM `IMFByteStream`(通告 `PARTIALLY_DOWNLOADED`、录制中未知总长、严格按已落盘完整 `moof+mdat` box 边界映射并在 256 KiB 页缓存边界补齐虚拟 ISO BMFF `free` box、`TailWindow` 贴近最新关键帧起播、PTS 归零且禁止对增长流调用 `SetCurrentPosition`)驱动解码;离开页面、切换预览或停止录制时,`Controller.Close()` 先触发无锁 `abort()`(`< 1 ms` 唤醒阻塞中的 `ReadSample` / `BeginRead`),再同步释放全部 `IMFSourceReader`、D3D11、`IMFByteStream` COM 引用与 `*os.File` 句柄,实测 `Close()` 返回后立即执行 `mp4.Defragment`、`os.Rename` 与 `os.Remove` 无任何 Windows 文件句柄占用冲突。
-
-### D1 交付前依赖盘点复跑结论
-
-- `go run ./tools/deps`(2026-11-15):满 7 天的直接模块与 `go` 行更新为 `0` 项(`due: 0`);未满 7 天冷却期的有 3 项(`github.com/Eyevinn/mp4ff` `v0.62.0 -> v0.63.0` 1 天、`github.com/egoist/mygo` `v0.8.3 -> v0.9.0` 3 天、`golang.org/x/image` `v0.47.0 -> v0.48.0` 5 天),按 DEC-048 与计划 D1 不提前升级。
-- `go run ./tools/deps -audit`(2026-11-15):`passed`(`called: 0`,`excepted: 0`,`open: 0`,`expiredExceptions: 0`;另有 `notCalled: 7` 位于代码未调用到的依赖模块内)。本轮未引入任何新的第三方依赖。
-
-### LOOP-015 与 10 次连续冒烟结论(M4-K31)
-
-- **复现与源码排查**:先对改动前的开发包 `0.1.2-dev.202611150223` 只读连跑 `tools/smoke` 15 次,15/15 全部通过(后台测试会话无活动前台窗口 `GetForegroundWindow()=0`,耗时 `2830~2944 ms`)。逐行核查 `Shell.checkForegroundSafety`(严格仅在 `fgPID != 0 && fgPID == os.Getpid()` 时粘滞置位,不会因外部进程切窗口误报)与 `mygo` 窗口/托盘实现(无 `WS_VISIBLE` 创建、`SWP_NOACTIVATE`、`Shell_NotifyIconW` 均不激活前台),定位到 F-008 引入的唯一安静模式缺口:`Shell` 其余交互入口均检查 `s.quiet == ""`,唯独 `setupTray` 在 `s.quiet != ""` 下仍注册了 `tray.OnClick(s.RestoreFromTray)` 与 `tray.OnRightClick(popUpTrayMenu)`;冒烟第 5 步第二实例 `RequestSingleInstanceLock` 调用 `AllowSetForegroundWindow(ASFW_ANY)` 后进入 2 秒托盘静置期,期间任务栏临时托盘图标一旦收到右键点击,`popUpTrayMenu` 便创建归属 `trace.exe` 的宿主窗口并调用 `SetForegroundWindow` + `TrackPopupMenuEx`,直接使 `tray` 快照首次置位并粘滞带入 `restored` 快照(与第 7 节记录的现象完全吻合)。
-- **加固与验证**:在不削弱任何焦点断言的前提下,改为 `s.quiet != ""` 时不挂载托盘菜单与左/右键回调、屏蔽全屏切换,补齐 `reuse_window` 与 `second_instance` 快照的焦点核对,并增加不含窗口标题与用户数据的 `StealFocusDetail`(记录阶段名、HWND 类名与可见性)。最终合入全部工作包并打包安装开发版 `0.1.2-dev.202611150644`(提交 `9f8eff82935a`)后,连跑 10 次 `go run ./tools/smoke -pkg dist/trace-dev -out artifacts/smoke`:**10/10 全部 PASSED**(各轮 `durationMs` 为 `2944`、`2840`、`2845`、`2890`、`2836`、`2903`、`2835`、`2892`、`2887`、`2886 ms`;`quietMode=hidden`,托盘专用工作集 `0.55~0.60 MiB`、提交内存 `79.52~81.99 MiB`,`webview2ProcessCount=0`,`stealFocusDetected=false`;最新回执保存在 `artifacts/smoke/smoke.json`)。
-
-### not-run 与限制
-
-- **实机体验(H-001 第 28~30 步、H-002)**:`not-run`,本机 `TRACE Dev` 已由打包工具自动静默更新到最新构建,待用户在真实桌面体验解析页布局、媒体库离线详情、用户页“全部缓存”慢速队列、任务页三栏、直播录制实时预览及原生托盘菜单位置。
-- **真实站点部分**:本轮 R1~R4、Q1~Q3 为本机界面、队列调度与本机 `.part` 预览改造,按计划未发真实站点请求;ACT-020 中抖音“收藏夹”与“观看历史”仍无真实站点证据(LOOP-014,“喜欢”已于 2026-11-14 复查确认为只给浏览器网页)。
-- **实时弹幕(FR-LIVE-003,Q-016 第 4 条)**:按 DEC-049 ① 与计划 §11,本阶段只提供直播录制页内实时音画预览,不显示、不抓取实时弹幕,留待后续阶段单独研究协议与选型。
-- **跨平台与竞态**:Linux 仅在本机执行 `GOOS=linux go vet ./...` 交叉静态检查,完整 Linux 测试在授权推送后由 GitHub Actions CI 执行;本机无 cgo 工具链,`go test -race` 为 `not-run`;大于 2 GiB 的 `co64` 大文件门控默认未执行。
-
-### 给 Agent A 的审查 prompt
-
-```text
-你是 TRACE 的 Agent A,集中审查 M4 第一轮实机反馈及补充功能调整(DEC-049 ①~③、DEC-050 ①②)。
-
-计划:docs/delivery/stage-plan.md(TRACE-M4-01 修订 3,重点第 11、12 节)
-报告:docs/delivery/stage-report.md(重点第 8 节,并确认第 6、7 节 F-001~F-009 回归均保留)
-分支:codex/m4-account,基点 main @ f080483(单阶段单个 DCO 提交,最终 SHA 见 B 的交付消息)。
-
-审查重点:
-1. R1 解析页布局(DEC-049 ②):/parse 接入共用的“最近解析”侧栏,主面板仅留居中大输入框,窄窗 <1000 可达最近解析,IME 组合态回车不误触发(M4-K16、K17)。
-2. R2 媒体库纯离线与固定排序(DEC-049 ③):去掉缓存时间排序切换;媒体库点击播放与“⋯ → 详情”(/library/item)全程零网络请求、不跳解析页、不写最近解析,仅右上角“⋯ → 在解析页打开”联网(M4-K18~K20)。
-3. Q1 缓存队列与持久化(DEC-050 ①,internal/service/cache_queue.go):替代旧 10/20/50 批量入队;按站点各自串行、每次只排 1 条下载,两条间 40~150 秒随机等待、每 15~25 条长歇 10~25 分钟,自动翻页经 site.WithAutomaticRequests 共用站点每小时额度与退避;cache-queue.json(v1,现有 v2 数据文件结构未变)不含任何 Cookie 或签名 URL;取消时停止队列并清理未完成下载且绝不删已入库媒体(M4-K25~K29)。
-4. Q2 + R3 任务角标、任务页三栏与直播实时预览(DEC-049 ①、DEC-050 ②):图标栏“任务”数字角标只数排队和进行中的下载任务;任务页侧栏切换“下载任务 / 缓存队列 / 直播录制”;直播录制页内只读打开本机增长中 .part(HLS fMP4 与 HTTP-FLV 重封装两条路径,零额外站点连接、无实时弹幕),离开页面或停止录制立即同步释放句柄,不影响 F-004 分片重叠裁剪、mp4ff Defragment 与改名(M4-K21~K24、K30)。
-5. LOOP-015 与冒烟稳定性(M4-K31):核查 StealFocusDetected 排查结论与 F-008 原生托盘两项菜单(TestTrayMenuOnlyOpensAndQuits),确认连跑冒烟通过、D1 依赖盘点与漏洞审计通过、文档无本机路径或参考项目名泄露。
-
-验证命令:go run ./tools/deps、go run ./tools/deps -audit、go run ./tools/check、GOOS=linux go vet ./...、go run ./tools/uishots -out artifacts/uishots、go run ./tools/smoke -pkg dist/trace-dev -out artifacts/smoke。局部问题直接修复、打包安装(如需)并 amend(git commit --amend -s),较大缺口按交接模板 §3 一次性交回。未授权:push、PR、合并、打标签、发布。
-```
-
-
-## 9. A:集中审查第一轮反馈的实现(2026-11-15)
-
-**基点与范围**:B 交付 `0e748e1`(`main @ f080483` 之上的一个 DCO 提交;相对 A 上次的 `0a6045c`,57 个文件、约 1.2 万行新增)。读了计划 §11、§12 与 B 的 §8,逐个看了 `internal/service/cache_queue.go`(启动恢复、站点循环、下载监视、候选推进、暂停/继续/取消)、`batch_cache.go` 的翻页与候选、`backend.go` 的登录与退出钩子、`internal/ui/views.go` 的解析页与任务角标、`shell.go` 的侧栏与高亮、`library_view.go` 的本机详情与“在解析页打开”、`tasks_view.go` 的实时预览开关与句柄释放、`internal/shell` 的安静模式加固。没有逐行读的:`internal/player/mf_live_windows.go` 与 `live_fmp4.go`(Media Foundation 的 COM 封装与增长文件读取,约 1800 行),由 B 的合成 fMP4 测试和本次全量测试覆盖,实机效果为 `not-run`。
-
-**结论**
-
-| 方面 | 结论 |
-| --- | --- |
-| 实现交付 | R1~R4、Q1~Q3 与 M4-K16~K31 都有实现与测试证据;F-001~F-009 的回归测试都在并通过(K23、K30) |
-| 技术审查 | 发现 2 个 P2,A 已直接修复并复验(F-010、F-011);文档 3 处与实现或证据不符,已改(见下);1 个小问题记 LOOP-016。没有 P0、P1。修复后收敛 |
-| 产品验收 | 未开始:H-001 第 28~30 步为 `not-run`;实时预览、队列节奏与解析页窄窗只有自动化与截图证据 |
-
-**问题**
-
-| 编号 | 严重度 | 位置与触发 | 实际结果与影响 | 依据 | 修复与复验 |
-| --- | --- | --- | --- | --- | --- |
-| F-010 | P2 | `cache_queue.go` `advanceCandidateStep`:一条未缓存的内容入队时失败(视频已删除、详情读取失败等普通错误) | 入队前已经向站点读了详情(哔哩哔哩 `VideoDetail`、抖音作品详情),失败后却不等待就立刻处理下一条。一个列表里连续多条失败时,会变成连着发请求,正是 DEC-050 ① 要避免的“规律、密集”的请求 | DEC-050 ①、计划 §12.1“每次只把 1 条……再随机等一段”;NFR-NET-003 | 普通失败计为跳过后照常随机等待(与下载失败同一路径 `finishItemOutcomeLocked`);已缓存、重复、不能缓存的条目不发请求,仍不等待。`TestCacheQueueSkipsCachedDuplicatesAndOrdinaryItemErrors` 改为断言失败条目后也有一次 40 秒等待(4 次而不是 3 次);在 B 的版本上这个断言失败 |
-| F-011 | P2 | `views.go` `renderParseRoute`:窗口宽度 < 1000(没有上下文侧栏)时打开解析页 | 主面板只有输入框,侧栏又不显示,“最近解析”在解析页完全找不到;视频页、用户页窄窗时同样没有侧栏,于是窄窗下没有任何地方能看最近解析。B 的测试反而断言窄窗时不显示,报告写的“窄窗顶部保留入口”与实现不符 | 界面 §1“窄窗没有侧栏时……退回为页面里的……”、FR-HIST-001;审查要求“窄窗 < 1000 可达最近解析” | 窄窗时输入框靠上放置,下方显示同一份最近解析(复用 `renderHistoryPanel`,含“⋯”与行内确认);宽窗不变。`TestParsePageCenteredInputAndHistorySidebar` 改为断言 720 宽时历史行在输入框下方的中栏里(在 B 的版本上失败)。界面 §1、§3.2 同步 |
-
-**文档修正**:①本节之前的 §8 工作包表把用例编号对错了(R2 写成 K18~K20、Q1 写成 K25~K29、Q2+R3 写成 K21~K24),按计划 §11.2、§12.3 改为 R2 = K18、K19,Q1 = K24~K27、K29,Q2+R3 = K20~K23、K28。②LOOP-015 的结论:B 对旧开发包连跑 15 次、新开发包连跑 10 次都没有复现,“安静模式下托盘回调抢焦点”是代码审查推出的可能原因(冒烟过程中没有人点托盘),不是已确认的根因;交付状态 LOOP-015 改为如实写“未复现、已加固、根因未确认”。加固本身(安静模式不挂托盘交互、补两处焦点核对、`StealFocusDetail`)没有放宽检查,保留。③报告开头“A 的审查写在第 3 节”改为第 6、9 节。
-
-**记为 LOOP 的**:LOOP-016(一个站点登录失效时,另一个仍登录站点的缓存队列被按“应用关闭”暂停,本次运行内不自动继续),见交付状态。
-
-**复核过、没有问题的要点**
-
-- **缓存队列**:同一站点同时只有一个任务处于进行/等待(`selectActiveSiteEntryLocked`),每次只入队 1 条,等下载结束(`completed`/`partial` 且已入库算成功)再随机等 40~150 秒,按 15~25 条长歇 10~25 分钟;翻页和入队都在 `site.WithAutomaticRequests(ctx, "cache_queue")` 下,发出前先查站点退避与每小时额度,命中就进入“等待退避结束”并加 10~30 分钟;风控与限流会登记站点退避;登录失效暂停、重新登录(扫码、导入 Cookie、续期、抖音登录)后只恢复因登录暂停的任务,换号时只恢复换号前已暂停的那些;退出时进行中的任务记“应用关闭”,退避中的保持退避,启动后随机等 1~5 分钟。两个站点各有独立循环,互不阻塞。
-- **取消**:只取消这个任务派生的、尚未完成的下载(`Cancel` 只清理该任务的 `.part`),不删媒体库条目与已缓存文件;完成或取消后同一列表可重新加入,只保留一条记录。
-- **`cache-queue.json`**:版本 1、原子写、`0600`;只有站点、账号 ID、名称、列表、游标、已处理键、计数、状态与时间;读入和写出都过一遍去 URL、去查询串、去凭证键值的清洗,游标与键里有 `?=&;/:` 的直接丢弃;更高版本拒绝启动、损坏时备份后重建。现有版本 2 的数据文件结构没有变。隐私哨兵 `TestCacheQueuePrivacySentinel` 覆盖文件、日志与事件。
-- **媒体库离线**:卡片点击在媒体库内直接播放或看图;“⋯ → 详情”进 `/library/item`,图标栏高亮“媒体库”、侧栏是媒体库侧栏,作者头像与名称不可点、不显示缓存/升级/刷新,图片与封面只用本机文件(详情卡片清空了远程地址),返回回到原筛选与滚动位置;只有“⋯ → 在解析页打开”切到解析页并解析。订阅详情与任务页里录像的“详情”也走这个本机路由。
-- **任务角标与侧栏**:`activeWorkCount` 只数 `queued`/`running` 的下载任务;侧栏三项与窄窗顶部分段选择由测试覆盖。
-- **实时预览**:只读打开本机 `.part`(共享读、写、删除),不发站点或 CDN 请求(`TestBilibiliHLSRecordingPreviewStateRolloverAndZeroExtraHTTP`);离开任务页“直播录制”、录制停止或换段时由 `syncLivePreviewState` 关闭或跟到新段,`Close` 同步释放句柄后录制收尾的 `Defragment`、改名与删除不冲突(`TestEndToEndLiveRecorderAndPlayerPreviewFinalizeWithoutHandleConflict`);F-004 的子帧重叠裁剪保留(`TestFinalizeLivePartTrimsSubFrameFragmentOverlap`)。纯音频直播与非分片 MP4 如实显示“暂不支持实时预览”。不画弹幕。
-- **泄露检查**:仓库里没有本机绝对路径(除说明安装位置的 `%LOCALAPPDATA%` 写法与 CI 示例),没有本机参考索引里的项目名(`tools/checkdocs` 按本机索引的 14 个词检查通过)。
-
-**A 的验证**(修复后的工作区):
-
-| 命令 | 结果 |
-| --- | --- |
-| F-010、F-011 的回归测试 | 在 B 的版本上失败,修复后通过 |
-| `go run ./tools/deps` | `due: 0`;未满 7 天的 3 项(mp4ff v0.63.0、mygo v0.9.0、x/image v0.48.0)按 DEC-048 不升 |
-| `go run ./tools/deps -audit` | `passed`(`called: 0`,`notCalled: 7`) |
-| `go run ./tools/check` | ALL CHECKS PASSED(2m0.9s,在 amend 后的提交上) |
-| `GOOS=linux go vet ./...` | OK |
-| `go run ./tools/uishots -out artifacts/uishots` | 147 张全部通过;`parse-720x860.png` 显示窄窗时输入框下方的最近解析 |
-| `go run ./tools/package -install` | 开发版 `0.1.2-dev.202611150921`(提交 `63af756`,干净工作区),从 `0.1.2-dev.202611150644` 静默升级,安装时 TRACE Dev 没在运行。安装包 SHA-256 `ef750ee1318c3df9d0c1e25ab158cd18bcbe3d4cec1c468e8dd234535bc45e74`,`trace.exe` `b8f2d4449388756f7cf50cc2eb7eb59c2c44bb0db6b13a63bc01ed23cceaf255` |
-| `go run ./tools/smoke -pkg dist/trace-dev -out artifacts/smoke` | 连跑 10 次全部 PASSED(9 次 2.85~2.98 秒、1 次 8.6 秒,托盘专用工作集 0.57~0.62 MiB,WebView2 0,`stealFocusDetected=false`) |
-
-修复 amend 进阶段提交后打包;之后只把本表补进报告、再 amend 一次,代码与开发版相同。没有 push 或 PR。H-001 第 28~30 步为 `not-run`。
-
-
-## 10. 实机反馈第二轮(2026-11-15,A 修复与规划)
+## 7. 实机反馈(2026-11-20,B 修复)
-用户装了 `0.1.2-dev.202611150933` 后给了 8 条反馈([DEC-051](../decisions.md#dec-051))。A 直接处理了 ②④⑤⑥,并按⑤检查了本机开发版日志(只读 `logs/trace.log` 与 `subscriptions.json` 的结构字段,内容不进仓库);①③⑦⑧ 交给 B([计划 §13](stage-plan.md#feedback-2),默认值见 [Q-018](../../USER-ACTIONS.md#q-018))。
+用户在本机 TRACE Dev 上发现三件事,又提了两项要求。B 查明原因后修复,全部 amend 进阶段提交。
-| 编号 | 反馈或发现 | 根因 | 修复与回归测试 |
-| --- | --- | --- | --- |
-| F-012(P2,反馈②) | 删掉一个作者的全部内容后,留下空的作者文件夹 | 删除只自下而上清理条目文件夹本身(`removeEmptyDirsBottomUp`),不向上看类型文件夹与作者文件夹 | 删除后再向上删除因此变空的类型文件夹(`videos/`、`works/` 等)与作者文件夹;只在保存位置内,站点文件夹与保存位置不删,只用 `os.Remove`(不空就失败)(`library.go` `removeEmptyAuthorDirs`)。`TestDeletingTheLastItemRemovesTheEmptyAuthorFolder`:删同一作者第一条时另一条不动,删最后一条后作者文件夹消失、`bilibili/` 保留;有用户文件的条目连同上级文件夹保留 |
-| F-013(P2,反馈⑥) | 订阅头像还会丢 | 本机数据里 11-15 新建的 3 个哔哩哔哩订阅都没有头像地址:用户页“订阅”按钮调用 `UpsertSubscription` 时没传 `Face`,要等第一次检查更新才补;而本机头像副本(F-005)只给抖音存,界面也只给抖音读 | 用户页订阅带上头像;两个站点都存本机头像副本(订阅、关联、检查更新、打开已订阅账号的用户页时,7 天内不重取),界面对两个站点都先用本机副本;订阅头像仍默认是第一个账号(`syncSubFields` 的 `Avatar`,用户可在账号里“用作头像”改)。`TestBilibiliUserPageSubscriptionKeepsALocalAvatar`(修复前没有本机头像);`TestDouyinSubscriptionKeepsALocalAvatar` 保持通过。已有的 3 个订阅在下次检查更新或打开其用户页时补上 |
-| F-014(P3,日志检查) | `trace.log` 412 行里 365 行是下载任务,一个任务 3 分钟写了 115 行相同的“-> running” | 下载进度每秒回调一次,回调里每次都写日志 | 只在任务状态变化时写(`taskStatusLog`)。`TestTaskStatusLogOnlyLogsChanges` |
-| F-015(P2,日志检查) | 11-14 09:19~09:31 之间 4 次启动、只有 1 次正常退出,日志里没有任何崩溃线索(那是 F-003 的闪退,已修) | 程序崩溃时调用栈只写到标准错误,窗口程序没有控制台,什么也留不下 | 启动时用 `runtime/debug.SetCrashOutput` 把崩溃调用栈写进 `logs/crash.log`;下次启动时非空的改名为 `crash-.log`(只留 5 份)并在 `trace.log` 记一行(`internal/shell/crashlog.go`)。`TestCrashOutputKeepsThePreviousCrashAndPrunes` |
-| 反馈④ | 加了新订阅后“订阅”图标上有个小红点,不知道什么意思 | 那是“有订阅正在直播”的橙色点(界面 §2),只有颜色没有说明 | 悬停提示改为“订阅 · 有订阅正在直播”;“任务”角标的提示写“N 个下载排队或进行中”(`railButtonTip`)。是否在直播以站点返回为准,A 没有为此发站点请求 |
-| 反馈⑤ | 常驻后台运行,更新开发版时直接关掉再装、装完重开 | `tools/package -install` 本来就这样做([工程规则 §2.2](../dev-rules/engineering.md#dev-install)):之前几次安装时 TRACE Dev 恰好没在运行(`install-dev.json` 的 `wasRunning=false`) | 本轮安装时 TRACE Dev 正在运行,实测见下表 |
-
-**日志里其余的情况**:没有 `ERROR`;`account.douyin.likes error=risk_control` 两行是 F-007 修复前的旧版本;11-13 以前的版本带 `-dirty`,之后都是干净构建。
-
-**交给 B 的**(DEC-051 ①③⑦⑧,计划 §13):设置“更新”页与检查/更新记录;去掉同时录制数并加“录制异常”;订阅详情改为“内容 / 账号”;缓存规则批量指定订阅。
-
-**A 的验证**(修复后的工作区):
-
-| 命令 | 结果 |
-| --- | --- |
-| 新增的 4 个回归测试 | F-012、F-013 在修复前的代码上失败;F-014、F-015 是新加的能力,测试随之新增 |
-| `go run ./tools/check` | ALL CHECKS PASSED(2m11s,在 amend 后的提交上) |
-| `GOOS=linux go vet ./...` | OK |
-| `go run ./tools/uishots -out artifacts/uishots` | 147 张全部通过 |
-| `go run ./tools/package -install` | 开发版 `0.1.2-dev.202611151001`(提交 `ce8b3f4`,干净工作区)。**安装时 TRACE Dev 正在托盘里运行**:工具让它保存并退出(日志“quitting for update (dev-install, window open: false)”,用时 2.1 秒),静默安装后以 `--background` 重新打开到托盘,总用时 3.5 秒(`install-dev.json`:`wasRunning=true`、`relaunched=true`、`background=true`);新进程启动后 `logs/crash.log` 已建好(空)。安装包 SHA-256 `7bcf18a3d3ee961a1d33aced4fbca629d0831935d0e1ec2f6933335ba48d4ce6`,`trace.exe` `9e68ad3d4e208c614bb819dc1cd41ad3c5403a72a36a9277eda0b8e671ff4c03` |
-| `go run ./tools/smoke -pkg dist/trace-dev -out artifacts/smoke` | 连跑 3 次全部 PASSED(2.9~3.0 秒,托盘专用工作集 0.56~0.59 MiB,WebView2 0);冒烟用临时目录与单独的单实例锁,不影响本机正在运行的 TRACE Dev |
-
-修复 amend 进阶段提交后打包;之后只把本表补进报告、再 amend 一次,代码与开发版相同。没有 push 或 PR。H-001 第 31 步(本轮 A 修复的实机复查)为 `not-run`。
-
-
-## 11. B:第二轮反馈的实现(2026-11-15)
-
-按[计划 §13](stage-plan.md#feedback-2)(修订 4)与 [Q-018](../../USER-ACTIONS.md#q-018) 默认值连续完成 U1、L1、S1、S2、D2 及必测用例 M4-K32~K38,完整保留 A 在 §6、§7、§9、§10 的全部修复与回归测试(F-001~F-015)以及 B 第一轮 §8 的全部实现,没有改动 `go.mod` / `go.sum`,没有新增第三方依赖,没有发起任何真实站点请求。
-
-| 信息 | 内容 |
-| --- | --- |
-| 执行范围 | U1(设置“更新”页与 `update-history.json`)、L1(不限同时录制数与“任务 › 录制异常” `live.incidents`)、S1(订阅详情“内容 / 账号”标签)、S2(缓存规则批量选择订阅 `SetSubscriptionsRule`)、D2(正本文档与截图门禁同步)及必测用例 M4-K32~K38 全部完成,无缩减验收 |
-| 版本与工作区 | 分支 `codex/m4-account`,基点 `main @ f080483`(A 第二轮基点 `7c164c9`);代码与截图通过门禁并 amend 进单个 DCO 提交(`2fe7d2b`)后打包安装,随后仅补写报告与版本号再 amend 一次,源码与已装开发版一致;最终交付 SHA 见 B 的交付消息。工作区干净,未执行 push、PR、合并、打标签或发布 |
-| 可运行产物 | `go run ./tools/package -install`:开发版 `0.1.2-dev.202611151157`(`VERSION.txt` 提交 `2fe7d2b76794`、`built_at=2026-11-15T11:57:41Z`,干净工作区构建、不带 `-dirty`),安装时 `TRACE Dev` 正在托盘里运行,工具经 `--quit-for-update` 让其保存退出(`quitMs=329`)、静默安装并以 `--background` 重新打开到托盘,从 `0.1.2-dev.202611151001` 自动升级,总耗时 `1645 ms`(`artifacts/package/install-dev.json`:`installed=true`、`wasRunning=true`、`relaunched=true`、`background=true`)。`trace-dev-setup-0.1.2-dev.202611151157-amd64.exe` SHA-256 `9dc53c0c1855009497ff72a80beef2749b3f87cce2b8fd389f9813da24c2bb09`,`trace.exe` `3bac049a4811e33c96857e218b60af8d19650f3b65a32252abff7b63516a9983`(`dist/trace-dev/SHA256SUMS.txt`)。`go run ./tools/uishots -out artifacts/uishots`:54 个场景、162 张 PNG 全部通过。`go run ./tools/smoke -pkg dist/trace-dev -out artifacts/smoke`:连跑 3 次全部 PASSED(各轮 `durationMs` 为 `2979`、`2867`、`2990 ms`,`quietMode=hidden`,托盘专用工作集 `0.55~0.57 MiB`、提交内存 `80.55~82.05 MiB`,`webview2ProcessCount=0`,`stealFocusDetected=false`;最新回执见 `artifacts/smoke/smoke.json`) |
-| 关键变更与恢复 | 现有 v2 数据文件(`library.db`、`updates.db`、`subscriptions.json`、`ui-state.json`)与 `cache-queue.json`(v1)结构完全不变;新增独立文件 `/update-history.json`(`version: 1`,原子写 `0600`,遇到更高未知版本拒绝启动并不覆盖原文件,损坏时备份重建,读写双向清洗去 URL、查询串与凭证键值,只保存版本、时间、方式与结果文字);直播录像清单 `item.json` 增加可选字段 `live.incidents`(旧版忽略,无该字段的旧清单照常读取);`ui-state.json` 旧 `SubDetailTab="live"` 读入时归一为 `"accounts"`;`settings.json` 旧 `maxRecordings` / `live.maxConcurrentRecordings` 兼容读取但不再限制并发;服务层新增 `SetSubscriptionsRule(ruleID, subIDs)` 单次原子写 `subscriptions.json`(取消勾选的订阅回退 `default`) |
-
-| 工作包 / 用例 | 实现位置 | 实际命令与证据 | 状态与限制 |
-| --- | --- | --- | --- |
-| U1 设置“更新”页与 `update-history.json`(K32) | `internal/update/{history,controller}.go`、`internal/shell/{updates,shell}.go`、`internal/service/{update_history,dev_install_windows,dev_install_other,backend,dto}.go`、`internal/ui/{updates_view,views}.go`:设置新增“更新”分类(位于“关于”之前,“关于”指向“更新”);正式版展示当前版本、更新方式、上次/下次检查、“立即检查”、自动检查/下载开关及检查记录(≤20 条)与更新记录(≤50 条);开发版展示更新方式说明、读取 HKCU 卸载项显示本机已安装的开发版版本(高于运行版本时提示重启生效)与记录,不显示检查按钮和自动开关;`DecideStartup` 在版本变化时写入更新记录(开发版 `dev_install`,正式版有重启标记 `auto_update`、否则 `manual`) | `TestUpdateHistorySchemaV1AndRetention`、`TestUpdateHistoryRefusesNewerVersionWithoutOverwriting`、`TestUpdateHistoryCorruptBackupAndRebuild`、`TestUpdateHistoryPrivacyScrubbingReadAndWrite`、`TestControllerRecordsChecksAndExposesNextCheck`、`TestDecideStartupRecordsVersionChangeMethods`、`TestBackendUpdateHistoryNewerVersionRefused`、`TestBackendUpdateHistoryCorruptRecoveryAndExistingSchemasUnchanged`、`TestBackendUpdateHistoryPrivacySentinelAndInstalledDevVersion`、`TestReadRegistryDisplayVersionIsolatedKey`、`TestSettingsUpdateCategoryOrderAndAboutNavigation`、`TestSettingsUpdateReleasePageCheckFlowAndHistoryM4K32`、`TestSettingsUpdateDevPageNoCheckControlsAndInstalledVersionPromptM4K32`;截图 `settings-update-{1280,1000,720}x860.png`、`settings-update-dev-{1280,1000,720}x860.png`、`settings-about-{1280,1000,720}x860.png` | passed |
-| L1 不限同时录制数与“录制异常” `live.incidents`(K33~K35) | `internal/library/schema.go`、`internal/live/{incidents,recorder,douyin_live,manager,live_preview}.go`、`internal/site/{types.go,douyin/live.go}`、`internal/settings/settings.go`、`internal/service/{backend,browsing,dto}.go`、`internal/ui/{live_incidents_view,tasks_view,views,app}.go`:移除设置“订阅与直播”里的“同时录制数”行及 `live.Manager` 全部并发上限检查;在会话内存与录像 `item.json` 可选字段 `live.incidents` 采集 5 类异常(`reconnect`、`lost_segments`、`slow`、`disk`、`convert_failed`;相邻 1 分钟同类合并、单场上限 200 条、零额外站点连接);录制行显示“⚠ N 处异常”,任务侧栏新增第 4 项“录制异常(N)”(最近 7 天含进行中有异常场数,0 场不带数字,窄窗顶部分段可达),已结束场次点击进入 `/library/item` 纯离线详情 | `TestConcurrentRecordingsUnlimited_M4K33`、`TestLiveRecordingIncidentsAllFiveKindsCoalesceAndCap_M4K34`、`TestLiveIncidentsBackwardCompatibilityAndSanitization`、`TestSettingsNoRecordingLimitAndTasksLiveIncidentsUI_M4K33_M4K35`;截图 `tasks-incidents-{1280,1000,720}x860.png`、`tasks-live-{1280,1000,720}x860.png` | passed |
-| S1 订阅详情“内容 / 账号”标签(K36) | `internal/uistate/uistate.go`、`internal/ui/{subscriptions,images,app,views}.go`:订阅详情改为“内容”(默认)与“账号”双标签;“内容”复用主页时间线卡片渲染、虚拟化与触底翻页,按发布时间倒序列出该订阅全部关联哔哩哔哩/抖音账号的已缓存内容(纯离线读 `library.db`、零站点请求,0 账号不误调全库查询,空态显示“还没有缓存这个订阅的内容”并提示右上角“⋯ → 检查更新”);“账号”按行合并站点标签、本机头像、昵称、UID/抖音号与直播状态,直播/录制中直接显示“录制 / 停止录制”主操作按钮,其余操作收进行内“⋯”,不重复列历史录像;旧 `live` 标签值归一为 `accounts` | `TestM4K36_SubscriptionDetailContentTabCrossSiteZeroRequestsAndEmptyState`、`TestM4K36_SubscriptionDetailAccountsTabLiveRecordingAndMoreMenu`、`TestM4K36_LegacyLiveTabNormalizesToAccounts`、`TestM4K36_SubscriptionDetailThreeWidthsAndLocalAvatars`、`TestUIStateSubDetailTabNormalization`;截图 `subscription-detail-{1280,1000,720}x860.png`、`subscription-content-empty-{1280,1000,720}x860.png`、`subscription-accounts-{1280,1000,720}x860.png` | passed |
-| S2 缓存规则批量选择订阅(K37) | `internal/subscription/{rules,manager}.go`、`internal/service/backend.go`、`internal/ui/{rules_batch_dialog,rules_view,overlays,app}.go`:服务层与订阅管理器新增 `SetSubscriptionsRule(ruleID, subIDs)`(勾选订阅设为该规则、原属该规则但取消勾选的回退 `default`,单次原子写 `subscriptions.json`,包括默认规则本身);设置“缓存规则”展开任一规则后显示“使用这条规则的订阅(N)”与“选择订阅…”按钮,模态框支持搜索、本机头像、“当前:<规则名>”、“全选 / 全不选”、“应用到 N 个订阅”及 Esc/遮罩关闭 | `TestSetSubscriptionsRuleBatchAtomicAndRollback`、`TestCacheRuleBatchSelectSubscriptionsM4K37`、`TestCacheRuleBatchDialogErrorRetainsSelectionAndDismissShortcuts`;截图 `settings-rules-batch-{1280,1000,720}x860.png`、`settings-rules-{1280,1000,720}x860.png` | passed |
-| D2 正本文档同步、截图门禁、冒烟与全量回归(K38) | `docs/requirements.md`、`docs/ui.md`、`docs/design/{architecture,data-and-cache,subscriptions,live}.md`、`docs/delivery/{roadmap,status,stage-report}.md`、`docs/dev-rules/engineering.md`、`USER-ACTIONS.md`(H-001 第 18/21/24/26/30/31 步、H-002)、`tools/uishots/{main,main_test}.go` | A 本轮回归 `TestDeletingTheLastItemRemovesTheEmptyAuthorFolder`(F-012)、`TestBilibiliUserPageSubscriptionKeepsALocalAvatar`(F-013)、`TestTaskStatusLogOnlyLogsChanges`(F-014)、`TestCrashOutputKeepsThePreviousCrashAndPrunes`(F-015)及 F-001~F-011 全部回归测试通过;`TestUIShotsScenesAndStructuredAssertions` 与 `go run ./tools/uishots -out artifacts/uishots`(54 场景、162 张 PNG 全过);`go run ./tools/deps`(`due=0`)、`go run ./tools/deps -audit`(`passed`、`called=0`)、`go run ./tools/check`(`ALL CHECKS PASSED in 1m16.129s`)、`GOOS=linux go vet ./...`(OK)、`go run ./tools/smoke -pkg dist/trace-dev -out artifacts/smoke`(3/3 PASSED) | passed |
-
-### 交付前依赖盘点与漏洞审计结论
-
-- `go run ./tools/deps`(2026-11-15):`status=reported, due=0, waiting=3`。满 7 天的直接模块与 `go` 行更新为 `0` 项;未满 7 天冷却期的有 3 项(`github.com/Eyevinn/mp4ff` `v0.62.0 -> v0.63.0` 1 天、`github.com/egoist/mygo` `v0.8.3 -> v0.9.1` 0 天、`golang.org/x/image` `v0.47.0 -> v0.48.0` 5 天),按 DEC-048 不提前升级。
-- `go run ./tools/deps -audit`(2026-11-15):`status=passed, called=0, excepted=0, open=0, notCalled=7, expiredExceptions=0`。代码调用路径无已知漏洞,本轮未改动 `go.mod` / `go.sum`、未引入新第三方依赖。
-
-### not-run 与限制
-
-- **实机体验与安装更新检查(H-001 第 28~31 步、H-002)**:`not-run`。本机 `TRACE Dev` 已自动静默更新至 `0.1.2-dev.202611151157` 并在托盘重开,待用户在真实桌面按 H-001 第 28~31 步复查“我的”及第一、二轮全部反馈项。
-- **真实站点部分**:本轮 U1、L1、S1、S2、D2 为本机设置更新记录、录制会话内异常推算、离线订阅信息流与规则批量写入改造,按计划未发任何真实站点请求;ACT-020 中抖音“收藏夹”与“观看历史”仍无真实站点证据(LOOP-014)。
-- **实时弹幕与系统通知**:按 DEC-049 ① 与计划 §11.3、§13.4,实时预览不显示实时弹幕(留待后续阶段单独研究);录制异常仅在任务页展示,不弹系统通知,开发版不联网检查更新。
-- **跨平台、竞态与超大文件门控**:Linux 仅在本机执行 `GOOS=linux go vet ./...` 交叉静态检查,完整 Linux 单测待授权推送后由 GitHub Actions CI 执行;本机无 cgo 工具链,`go test -race` 为 `not-run`;大于 2 GiB 的 `co64` 大文件门控默认未执行。
-
-### 给 Agent A 的审查 prompt
-
-```text
-你是 TRACE 的 Agent A,集中审查 M4 第二轮实机反馈的实现(DEC-051 ①③⑦⑧)。
-
-计划:docs/delivery/stage-plan.md(TRACE-M4-01 修订 4,重点第 13 节)
-报告:docs/delivery/stage-report.md(重点第 11 节,并确认第 6、7、9、10 节 F-001~F-015 修复及第 8 节第一轮实现均完整保留)
-分支:codex/m4-account,基点 main @ f080483(A 第二轮基点 7c164c9;单阶段单个 DCO 提交,代码与截图通过门禁并 amend 为 2fe7d2b 后打包安装开发版 0.1.2-dev.202611151157,再仅补写报告与版本号 amend 一次;最终交付 SHA 见 B 的交付消息,工作区无未提交改动)。
-
-审查重点:
-1. U1 设置“更新”页与 update-history.json(DEC-051 ①,M4-K32):设置新增“更新”(位于“关于”之前,“关于”指向“更新”);正式版显示当前版本、更新方式、上次/下次检查、“立即检查”、自动开关及最近 20 条检查记录与 50 条更新记录;开发版不显示检查按钮与自动开关,说明开发版更新方式并读取 HKCU 卸载项展示本机已安装的开发版版本(高于运行版本时提示重启生效);DecideStartup 在版本变化时写入更新记录(开发版“本机打包安装”,正式版有自动更新标记记“自动更新”、否则“手动安装”);update-history.json(v1,现有 v2 数据文件结构不变)原子写、高版本拒绝、损坏备份重建、无下载地址或凭证泄露。
-2. L1 不限同时录制数与“录制异常” live.incidents(DEC-051 ③,M4-K33~K35):设置“订阅与直播”去掉“同时录制数”,live.Manager 三处上限全部移除,settings.json 旧字段兼容读取;item.json 可选字段 live.incidents 与会话内存记录 reconnect、lost_segments(HLS 序号跳段与估算秒数、FLV 重连空档秒数)、slow(持续 30 秒低于码率)、disk、convert_failed 五类事件(相邻 1 分钟合并、单场上限 200 条、零额外站点请求,旧无此字段清单兼容读取);录制行显示“⚠ N 处异常”,任务侧栏新增“录制异常(N)”(最近 7 天有异常场数,0 场不带数字,窄窗顶部分段可达),已结束场次点开 /library/item 离线详情。
-3. S1 订阅详情“内容 / 账号”标签(DEC-051 ⑦,M4-K36):默认“内容”标签复用主页时间线渲染、虚拟化与触底加载,合并该订阅关联全部哔哩哔哩/抖音账号的已缓存内容(纯离线读本机、零站点请求,0 账号防全库误查,空态文案与“⋯ → 检查更新”提示无多余主按钮);“账号”标签按行合并直播状态与“录制 / 停止录制”及“⋯”菜单,不重复列已录录像,保留底部“关联另一个账号”;旧 SubDetailTab="live" 归一为 "accounts"。
-4. S2 缓存规则批量选择订阅(DEC-051 ⑧,M4-K37):设置“缓存规则”展开规则后显示“使用这条规则的订阅(N)”与“选择订阅…”对话框(搜索、复选框、本机头像、“当前:规则名”、全选/全不选、“应用到 N 个订阅”);SetSubscriptionsRule(ruleID, subIDs) 将勾选订阅设为该规则、取消勾选的原订阅回退 default,subscriptions.json 单次原子写入。
-5. D2 正本文档同步、截图门禁与回归(M4-K38、Q-018、H-001 第 31 步):确认 F-012~F-015 与 F-001~F-011 全部回归测试通过,54 个场景 / 162 张 PNG 截图及 1280/1000/720 三档断言通过,本机 TRACE Dev 自动更新与连续冒烟通过,无本机私有路径或参考项目名泄露。
-
-验证命令:go run ./tools/deps、go run ./tools/deps -audit、go run ./tools/check、GOOS=linux go vet ./...、go run ./tools/uishots -out artifacts/uishots、go run ./tools/smoke -pkg dist/trace-dev -out artifacts/smoke。局部问题直接修复、打包安装(如需)并 amend(git commit --amend -s),较大缺口按交接模板 §3 一次性交回。未授权:push、PR、合并、打标签、发布。
-```
-
-
-## 12. A:集中审查第二轮反馈的实现(2026-11-15)
-
-**基点与范围**:B 交付 `4de8c0f`(`main @ f080483` 之上的单个 DCO 提交;源码与截图在干净构建提交 `2fe7d2b` 生成开发版 `0.1.2-dev.202611151157` 后,仅补写 §11 报告与版本号 amend 一次;相对 A 第二轮基点 `7c164c9`,共 53 个文件变更)。对照[计划 §13](stage-plan.md#feedback-2)(修订 4)、[Q-018](../../USER-ACTIONS.md#q-018) 默认值与 B 的 §11 报告,逐一审查了 `internal/update/{history,controller,source}.go`、`internal/shell/{updates,shell,crashlog}.go`、`internal/service/{update_history,dev_install_windows,dev_install_other,backend,browsing,dto}.go`、`internal/storage/`、`internal/library/{schema.go,author_dir_test.go}`、`internal/live/{incidents,recorder,douyin_live,manager,live_preview}.go`、`internal/site/{types.go,douyin/live.go}`、`internal/settings/settings.go`、`internal/subscription/{rules,manager}.go`、`internal/uistate/uistate.go`、`internal/ui/{updates_view,live_incidents_view,tasks_view,subscriptions,rules_batch_dialog,rules_view,overlays,images,app,views}.go`、`tools/uishots/{main,main_test}.go` 及全部受影响正本文档,抽检核对了 `artifacts/uishots/` 新增与改动的 1280/720 截图,并只读复查了本机开发版 `logs/trace.log`、`logs/crash.log` 与 `update-history.json` 的结构字段。
-
-**结论**
-
-| 方面 | 结论 |
-| --- | --- |
-| 实现交付 | U1、L1、S1、S2、D2 与必测用例 M4-K32~K38 均有完整实现、自动化单测与 54 场景 / 162 张 PNG 三档截图证据;§6、§7、§9、§10 的 F-001~F-015 修复及 §8 第一轮实现均完整保留,未改动 `go.mod` / `go.sum`,无新增第三方依赖,本轮零真实站点请求 |
-| 技术审查 | 发现 1 个局部 P2 问题(F-016),A 已直接修复、补回归测试并完成复验;核实修正 1 处本机打包重开的运行态说明(见下)。无 P0、P1,无需交回 B 返工,审查收敛 |
-| 产品验收 | 未开始:H-001 第 28~31 步与 H-002 仍为 `not-run`;自动化测试、截图门禁与冒烟通过不代表产品验收通过 |
-
-**问题**
-
-| 编号 | 严重度 | 位置与触发 | 实际结果与影响 | 依据 | 修复与复验 |
-| --- | --- | --- | --- | --- | --- |
-| F-016 | P2 | `internal/ui/updates_view.go` `renderDevUpdateSection` 与 `internal/update/source.go` `compareFields`:开发版运行未安装的更新构建或 `go run`(`0.0.0-dev`),而 HKCU 卸载项 `DisplayVersion` 记录的已装版本低于当前运行版本 | 原实现用 `installedVer != runningBuild.Version` 判断重启提示,导致卸载项版本**低于**当前运行版本或运行 `0.0.0-dev` 时误显示“已安装更新的版本,重启 TRACE Dev 后生效”;同时 `update.Compare` 用 `strconv.Atoi` 解析预发布数字段,12 位 UTC 时间戳(如 `202611151230`)在 32 位 `int` 下会溢出 | DEC-051 ①、计划 §13.1 与 M4-K32(“本机卸载项里的开发版版本高于正在运行的版本时,显示‘已安装更新的版本,重启 TRACE Dev 后生效’”) | `renderDevUpdateSection` 改为 `runningVer != appdirs.UnversionedBuild && update.Compare(installedVer, runningVer) > 0`;`compareFields` 改为 `strconv.ParseInt(..., 10, 64)`;同步收紧 `docs/ui.md` §3.7 与 `docs/requirements.md` FR-UPD-002 措辞。`TestVersionCompare` 增加 12 位开发版时间戳比较,`TestSettingsUpdateDevPageNoCheckControlsAndInstalledVersionPromptM4K32` 增加已装旧版与 `0.0.0-dev` 不误提示、已装新版正常提示的断言(在 B 的版本上失败,修复后通过) |
-
-**本机日志只读复查与运行态说明**:`logs/crash.log` 为空(0 字节),`logs/trace.log` 无 `ERROR`。对 §11“已在托盘重开”的核实:在 Agent 单轮命令沙箱内运行 `go run ./tools/package -install` 时,工具会经 `--quit-for-update` 让运行中的 `TRACE Dev` 优雅保存退出(日志 `quitting for update`)、完成静默升级并调用 `LaunchDetached` 拉起新进程(`install-dev.json` 记 `relaunched=true`),但命令沙箱在单轮命令返回关闭 Windows 作业对象时会一并回收其后台子进程,因此命令结束后新进程并未继续常驻(用户在自己的终端直接运行 `go run ./tools/package -install` 时不受沙箱作业回收影响,见 §10)。用户在 `12:40:37Z` 手动打开 `0.1.2-dev.202611151157` 时,本机 `update-history.json`(`version: 1`)已实机写入 `0.1.2-dev.202611151001 -> 0.1.2-dev.202611151157` 的 `dev_install` 记录;A 本轮打包安装 `0.1.2-dev.202611151241` 同样受该命令沙箱回收影响,已在 `USER-ACTIONS.md` 说明如未在桌面或托盘运行可从开始菜单或桌面打开一次。
-
-**复核过、没有问题的要点**
-
-- **U1 设置“更新”页与 `update-history.json`(M4-K32)**:设置左侧分类在“关于”之前新增“更新”,“关于”页说明行可跳转“更新”;正式版完整展示当前版本、更新方式说明、上次与下次检查时间、“立即检查”按钮、“自动检查更新 / 自动下载更新”开关及最近 20 条检查记录、最近 50 条更新记录;开发版隐藏检查按钮与自动开关,说明开发版更新方式并读取 HKCU 卸载项展示已安装版本;`DecideStartupForChannel` 在版本变化时准确区分开发版 `dev_install`(“本机打包安装”)、正式版带有效重启标记 `auto_update`(“自动更新”)与 `manual_install`(“手动安装”);`update.GuardHistorySchema` 在打开 SQLite 前校验 `update-history.json`(v1),遇到更高未知版本拒绝启动且不覆盖原文件,损坏时备份 `.corrupt-<时间戳>` 后重建,原子写 `0600`,读写双向经 `scrubSummaryText` 与 `credential.RedactString` 剥离 URL、域名、查询串和凭证,现有 v2 数据文件与 `cache-queue.json`(v1)结构完全不变。
-- **L1 不限同时录制数与“录制异常” `live.incidents`(M4-K33~K35)**:“设置 › 订阅与直播”已去掉“同时录制数”,`live.Manager` 的 `StartRecording`、`AutoRecord` 与 `UpdateMaxConcurrent` 三处上限全部移除,`settings.json` 旧字段兼容读取;录制会话内存与 `item.json` 可选字段 `live.incidents` 采集 `reconnect`、`lost_segments`(HLS `EXT-X-MEDIA-SEQUENCE` 跳号段数与估算秒数、FLV 重连 ≥ 2 秒空档秒数)、`slow`(滑动窗口持续 ≥ 30 秒低于媒体码率 85%)、`disk`、`convert_failed` 五类事件,按同类相邻 1 分钟合并、单场最多 200 条、全程零额外站点连接,无此字段的旧清单兼容读取;录制行展示橙色“⚠ N 处异常”可直达该场异常,任务侧栏新增第 4 项“录制异常(N)”(最近 7 天含进行中有异常场数,0 场不显示括号数字,`< 1000` 窄窗顶部分段选择器可达),离开“直播录制”立即由 `syncLivePreviewState` 释放 `.part` 预览句柄,已结束场次点击进入 `/library/item` 纯离线详情。
-- **S1 订阅详情“内容 / 账号”标签(M4-K36)**:默认“内容”标签经 `FeedPage(CachedOnly: true, AuthorRefs: refs, Order: "newest")` 合并关联的全部哔哩哔哩与抖音账号已缓存内容,复用主页时间线渲染、虚拟滚动与触底加载,纯离线读 `library.db`、零站点请求,0 关联账号短路返回空页防止全库误查,空态显示“还没有缓存这个订阅的内容”及右上角“⋯ → 检查更新”说明且无多余主按钮;“账号”标签按行合并站点标签、本机头像、昵称、UID/抖音号、直播状态、“录制 / 停止录制”按钮与“⋯”菜单,不重复列已录录像,保留底部“关联另一个账号”;`ui-state.json` 旧 `SubDetailTab="live"` 读入归一为 `"accounts"`。
-- **S2 缓存规则批量选择订阅(M4-K37)**:“设置 › 缓存规则”展开任一规则显示“使用这条规则的订阅(N)”与“选择订阅…”按钮;模态框具备搜索(带输入法 `IsComposing` 保护)、复选框、本机头像、“当前:<规则名>”、“全选 / 全不选”、“应用到 N 个订阅”及 Esc/遮罩关闭;`SetSubscriptionsRule(ruleID, subIDs)` 预先校验规则与全部订阅 ID,勾选订阅设为该规则(自动缓存仍开启时保留已有 `AutoCache.Since`)、原属该规则但取消勾选的回退 `default`、其他规则订阅不动,单次原子写入 `subscriptions.json` 并在写盘失败时完整回滚内存状态。
-- **D2 正本文档同步、截图门禁与回归(M4-K38)**:全部受影响正本文档口径一致;54 个场景 / 162 张 PNG 在 1280/1000/720 三档宽度的结构断言与排版均通过;F-012~F-015 与 F-001~F-011 全部回归测试通过;`tools/checkdocs` 按本机参考索引 14 个词扫描通过,仓库无本机私有路径或参考项目名泄露。
-
-**A 的验证**(修复后的工作区):
-
-| 命令 | 结果 |
-| --- | --- |
-| F-016 回归测试 | `go test -count=1 ./internal/update ./internal/ui -run 'TestVersionCompare\|TestSettingsUpdate'` 通过(在 B 的版本上旧版与 `0.0.0-dev` 断言失败) |
-| `go run ./tools/deps` | `status=reported, due=0, waiting=3`(`mp4ff` `v0.63.0` 2 天、`mygo` `v0.9.1` 0 天、`x/image` `v0.48.0` 5 天,均未满 7 天冷却期,按 DEC-048 不升) |
-| `go run ./tools/deps -audit` | `status=passed, called=0, excepted=0, open=0, notCalled=7, expiredExceptions=0` |
-| `go run ./tools/check` | `ALL CHECKS PASSED in 1m37.933s`(`gofmt`、`go vet`、全量 `go test ./...`、依赖方向、`tools/checkdocs`、`git diff --check HEAD`) |
-| `GOOS=linux go vet ./...` | OK |
-| `go run ./tools/uishots -out artifacts/uishots` | 54 个场景、162 张 PNG 全部通过 |
-| `go run ./tools/package -install` | 开发版 `0.1.2-dev.202611151241`(`VERSION.txt` 提交 `c30601d6f1d5`、`built_at=2026-11-15T12:41:07Z`,干净工作区构建、不带 `-dirty`),安装时 `TRACE Dev`(`0.1.2-dev.202611151157`,窗口打开)正在运行,工具经 `--quit-for-update` 让其保存退出(`quitMs=283`)并静默升级安装(总耗时 `1738 ms`)。安装包 `trace-dev-setup-0.1.2-dev.202611151241-amd64.exe` SHA-256 `62fcb87f5f6239652bbce3e2c088ba9ed1cd4565edb94cb5a60953c755185901`,`trace.exe` `c476bcfdf51b326bb1535c9574642e45ae9602a7dd5f091601a4d7102835947f`(`dist/trace-dev/SHA256SUMS.txt`) |
-| `go run ./tools/smoke -pkg dist/trace-dev -out artifacts/smoke` | 连跑 3 次全部 PASSED(`durationMs` 分别为 `2948`、`2888`、`2884 ms`,`quietMode=hidden`,托盘专用工作集 `0.55~0.59 MiB`、提交内存 `81.41~82.10 MiB`,`webview2ProcessCount=0`,`stealFocusDetected=false`) |
-
-修复 amend 进阶段提交(`c30601d`)后干净构建安装并完成冒烟;之后仅将本节审查记录与交付状态、用户待办中的版本号写回文档,经 `tools/checkdocs` 校验后再 amend 一次,源码与已装开发版 `0.1.2-dev.202611151241` 完全一致。没有 push、PR、合并、打标签或发布。H-001 第 28~31 步与 H-002 仍为 `not-run`。
-
-
-## 13. 实机反馈第三轮(2026-11-15,修复)
-
-| 反馈 | 原因 | 修复 | 回归 |
-| --- | --- | --- | --- |
-| 开发版常驻后台,重装后要在托盘打开([DEC-052](../decisions.md#dec-052)) | `tools/package -install` 只在原来运行时重开,且按退出前的窗口状态决定;在 Agent 命令沙箱(作业对象)里重开的进程会随命令结束 | 每次安装成功后总以 `--background` 在托盘打开;TRACE 遇到“为本机安装而退出”的记录且带 `--background` 时留在托盘;启动时用 `CREATE_BREAKAWAY_FROM_JOB` 脱离作业,不允许时记 `inJob=true` 并提示 | `tools/package` 的 `TestInstallDevWhenNotRunningStartsInTray`、`TestInstallDevQuitsInstallsAndReopensInTray`、`TestInstallDevReportsLaunchInsideJob`;`TestDecideStartupAfterUpdate` 增加开发版与正式版两种重开 |
-| 哔哩哔哩直播录像录制中能在主页看到,结束后“没有已登记的可播放视频” | `live.Manager.StartRecording` 用 `GetItem("live:<房间>:<开播>")` 找已有条目:两个冒号被当成不带站点的完整键,永远找不到 `bilibili:live:…`。录制被打断(本例是 18:01 打包安装退出)后同一场直播再次自动录制时,从空白条目开始、编号回到 `part-001.mp4`,撞上已有文件以 `storage` 停止,并把空白条目写回,原来已登记的 20 分 44 秒录像从清单里消失(文件本身完好) | 改用 `library.CanonicalItemKey("bilibili", "live", …)`;抖音本来就用规范键,不受影响 | `TestStopRecordingWhileLiveFinalizesPlayableFile` 增加“停止后再录同一场”:保留 `part-001`、新文件为 `part-002`、开始时间不变(修复前失败,修复后通过) |
-| 抖音作者页点“全部缓存”后窗口卡死(未响应,CPU 几乎不动) | 死锁:缓存队列在持有 `queue.mu` 时发布事件,外壳的订阅者同步调用 `refreshTrayState` → `tray.SetIcon` 等待主线程;主线程正在画作者页“⋯”菜单,`FindCacheQueueTask` 等 `queue.mu` | 外壳收到后端事件后改为在另一个 goroutine 刷新托盘,并合并连续事件,发布者不再等待主线程;两个站点的全部缓存都受益 | `internal/shell` 的 `TestTrayRefreshDoesNotBlockThePublisher`、`TestTrayRefreshCoalescesBursts` |
-
-本机数据:那场录像的 `part-001.mp4` 完好(1244 秒,`moov` 在前),由 Agent 在 TRACE Dev 关闭时用 `library.SaveItem` 重新登记(改前备份 `item.json` 与 `library.db`,备份放在数据目录外的 `artifacts/`)。卡死的 TRACE Dev 无法响应 `--quit-for-update`,这次按用户“可以关闭后重装”的授权结束了这个进程。
-
-验证:`go run ./tools/check` 全部通过、`GOOS=linux go vet ./...` 通过。`go run ./tools/package` 构建开发版 `0.1.2-dev.202611151300`(提交 `2ff122a`,干净工作区),结束卡死进程并修复录像条目后 `-install-only` 从 `0.1.2-dev.202611151241` 静默升级,安装后以 `--background` 在托盘打开(`install-dev.json`:`relaunched=true`、`background=true`,没有 `inJob`),命令结束后进程仍在运行且响应;安装包 SHA-256 `89a58e0aacb2c5d7b584f7b7e04dad47567f4007e649be589d061579b9678b9a`。修复后的录像条目 `status=complete`、`media` 一条(1280×720、1244 秒)。实机播放与“全部缓存”不再卡死的人工确认:`not-run`。
-
-
-## 14. 实机反馈第四轮(2026-11-16,A 修复与规划)
+| 编号 | 现象与原因 | 修复 | 证据 | 状态 |
+| --- | --- | --- | --- | --- |
+| 1 | **订阅检查停止、退出要等 3 分钟**(交付时以为只是退出慢)。旧版退出时留下的 `logs/crash-20261119T175010Z.log` 显示:`StartDouyinRecording` 持有 `startMu`,在缓存里没有新鲜状态时调用 `CheckAccountLiveStatus`。账号开了自动录制又正在直播时,这个调用经 `autoStartDouyin` 再次进入 `StartDouyinRecording`,又去拿 `startMu`,把自己锁死。之后同一账号的开录、订阅检查结束后的直播检查(订阅定时检查因此从 2026-11-19 14:32Z 后再没完成)和退出时的 `live.Manager.Stop` 都卡在这把锁上。这段代码从 M4 起就存在,本阶段没改它 | `internal/live/douyin_live.go`:`CheckAccountLiveStatus` 改为调用 `checkAccountLiveStatus(…, autoStart)`;`StartDouyinRecording` 内部用 `autoStart=false` 只读状态 | `TestDouyinStartWithoutCachedStatusDoesNotLockItself`:在修复前的代码上 5 秒内 panic(“locked startMu twice”),修复后 0.04 s 通过;`go test ./internal/live` 全部通过 | passed |
+| 2 | **抖音共创作品存到了发布者下**:猫九酱的“全部缓存”(`cq_ec49fbdb50073bbb`,用户手动开的)翻到了 `7229580276903447820`、`7229197081628396832`,它们的作者是“悠长假期”。作品列表接口会把共创作品列在共创者名下(推断,没有发请求核实)。抖音缓存请求里没有“为哪个账号缓存”,文件夹总是按作者算 | [DEC-063](../decisions.md#dec-063) ①:`DouyinWorkEnqueueRequest` 加 `ForUID`/`ForName`;新条目的发布者不是这个账号时,存到这个账号的 `works/` 下,并记 `via` collab;`download_tasks` 加可选列 `via_json`,任务重启后仍能写对;订阅自动缓存、缓存队列(含恢复)、用户页作品的“缓存”(`CacheDouyinWorkFor`)都带上这个账号。媒体库筛选、作者列表、已缓存数原本就按 `via` 计算,不分站点 | `TestDouyinCoCreationIsStoredUnderTheAccountItWasCachedFor`(成员文件夹、`via`、作者不变、按成员筛选能找到、持久化的任务带 `via`;作者自己的作品没有 `via`;已缓存的条目不搬动) | passed;已经缓存的两条不会自动搬动(H-001 第 37 步写了怎么重新放) |
+| 3 | **抖音图文“部分完成”**:本机共 19 条,全是配乐,没有风控。16 条“配乐无可用地址”:`music.play_url` 为空,而图文顶层 `video.play_addr` 里的配乐没有被当作备用地址。3 条“配乐下载失败 (blocked)”:首个地址在 `lf9-music-east.douyinstatic.com`(在允许列表里),失败记录里没有 HTTP 状态;本机 DNS 是代理的 fake-ip(198.18.x.x),不算内网地址,所以推断是跳转离开了允许列表(点播的跳转检查比直播严格) | `internal/site/douyin/work.go` 的 `noteMusicWithFallback`;`internal/download/douyin.go`:下载配乐时 `PublicRedirects=true`,媒体客户端的跳转检查改用 `ValidateRedirectURL`(不允许公网跳转的传输行为不变);缺失原因由 `musicFailureReason` 写出被拦截的原因或域名 | `TestNoteMusicFallsBackToTopLevelPlayAddr`、`TestMediaRedirectsFollowPublicHostsOnlyWhenAllowed`(HTTP、IP、`.local`、非 443 仍拦截)、`TestMusicFailureReasonNamesTheCause` | passed(合成数据);真实站点上能不能补上 not-run,用户在任务页重试时核对(H-001 第 37 步) |
+| 4 | **主页显示订阅名**(用户新增要求) | DEC-063 ②:`internal/ui/components.go` 的 `homePostSubscription`;账号名后面用 13px 强调色显示订阅名,订阅名与账号名相同时不显示,点它打开这个订阅;为订阅账号缓存的共创或合作作品按 `via` 找到订阅。`docs/ui.md` §3.1 | `TestSiteFiltersPersistenceAndSixSiteBadges` 加了“主页订阅名:”断言;`uishots` 192 张全部通过,`home-*.png` 里能看到“技术频道_抖音号 技术频道_Alpha” | passed |
+| 5 | **全部缓存检查未缓存时不看完整性**(用户新增要求):队列把状态点为黄色的条目一律当作已缓存跳过,部分完成或有缺失的条目永远不会被补上;另外抖音的“已缓存数”只按作者计数,第 2 条的共创作品没有算进成员名下 | DEC-063 ③:`internal/service/cache_queue.go` 的 `queueShouldCache`、`internal/library/schema.go` 的 `NeedsCompletion`。部分完成、有缺失记录、分 P 没有文件的条目会再缓存一次(已有的有效文件跳过),完整的、正在缓存的、已暂停的和只是可以升级画质的照常跳过。`internal/library/works.go` 的抖音计数加上 `via` collab | `TestCacheQueueCompletesIncompleteItems`(7 种状态中正好 4 条入队);`TestDouyinCoCreationIsStoredUnderTheAccountItWasCachedFor` 加了已缓存数断言(修复前为 0,失败) | passed |
-本机数据:`文档\trace-dev\bilibili\335144284\lives\` 两场录像(11-15 22:55 与 00:13 开播)显示 23 处异常,10 个 `.part` 留着没转成 MP4(共约 1.95 GB);日志里没有录制相关错误(录制错误只写进录像 `item.json`)。
+**验证**:`go run ./tools/check` ALL CHECKS PASSED(`go test ./...` 1m16s);`go run ./tools/uishots` 192 张全部通过(第 5 条没有改界面);桌面冒烟 PASSED(3034 ms,托盘专用工作集 0.60 MiB,WebView2 0);远程冒烟 Windows PASSED(kill 后重启),WSL Ubuntu 用新 Linux 包 PASSED(SIGTERM,78 ms)。
-| 反馈 | 原因 | 修复 | 回归 |
-| --- | --- | --- | --- |
-| 哔哩哔哩直播录制“收尾转换失败:直播录像轨道或时长校验失败”,录像停在 `.part` | 收尾把转换后的时长与录制时累加的 HLS `EXTINF` 之和比较,误差上限 0.1 秒。`EXTINF` 只是估计:实测 588.33 秒的分段 `EXTINF` 之和为 587.92 秒(差 0.41 秒),越长差得越多,所以长分段全部失败、几秒的短分段通过。10 个失败文件的转换本身全部成功(视频与音频轨、`moov` 在前),没有内容丢失 | `finalizeLivePart` 改为与源分片自身的媒体时间线(首个 `tfdt` 到末样本结束,取最长轨,`fragmentTimelineSec`)比较,误差 ≤ 1 秒(实测都在 0.02 秒内);不再接收 `EXTINF` 时长参数。启动恢复转换成功后删除该段的 `convert_failed` 记录 | `TestRecoveryAcceptsEXTINFDriftAndClearsConvertFailed`;FLV 测试改为自己核对转换后时长与重封装检查点 ≤ 0.1 秒 |
-| “分片丢失”出现 1 亿段、3 亿段 | 断流重连后主播端重新推流,新流的媒体序号从新的基数开始(这两段的时间线也从 0 或 6.7 秒重新开始),却仍和旧流最后的序号相减。其余“丢失 5~19 段”是真的:前一段媒体在 2358.2 秒结束、下一段从 2368.2 秒开始,与报告的 10 段一致 | 记录当前运行里上一个分片的写入时间;按目标时长估算的丢失秒数比距上一分片的时间多出 30 秒以上时,视为新编号,不记丢失(重启后没有这个时间,沿用原判断) | `TestHLSSequenceResetIsNotLostSegments`(新编号 0 段;真实跳号 2 段) |
-| 打开 `space.bilibili.com/702699638` 提示“解析接口数据字段失败”,设置里的运行日志没有记录 | 打开哔哩哔哩用户页时,界面另外查询这位 UP 主的直播状态(`get_status_info_by_uids`)。这位 UP 主没有直播间,接口返回 `"data": []`(站点把空的对象写成空数组),TRACE 按对象解析而失败。用户卡片、动态(4 页)与投稿接口用同一登录各请求一次,都能正常解析。没有日志,是因为界面显示的错误只写进横幅,不写日志;同一页面里获取动态失败也只放在页面上 | `doBiliJSON` 期望对象(map)而收到空数组时按空结果处理(`emptyArrayForMap`,非空数组与期望结构体时仍报格式变化);新增 `LogUserError`:界面显示的每个错误都写一行 `ERROR ui: …`,附接口路径(不含查询串)与字段解析原因,同一行 1 分钟内只写一次;解析用户页时动态失败也写日志 | `TestLiveStatusByUIDsAcceptsEmptyArrayData`、`TestEmptyArrayToleranceOnlyCoversEmptyMaps`、`TestLogUserErrorWritesDetailOnce` |
-| 缓存规则加一条不可修改的默认规则([DEC-054](../decisions.md#dec-054)) | 原来的“默认”规则可以编辑,内置为“定时检查”;新订阅各处都传“定时检查”,用户页订阅与导入还直接开着定时检查 | `default` 改为全关并拒绝修改(`ErrDefaultRuleLocked`);读入时与内置不同就复位,原来用它的订阅自动归到同设置的规则(旧默认改过名就沿用那个名字,否则如“定时检查”),行为不变并立即写回;新建、用户页订阅、抖音订阅、“我的”订阅与导入全部从默认规则开始;设置里“默认”展开后只显示说明与“选择订阅…” | `TestDefaultRuleIsLockedAndAllOffForNewSubscriptions`、`TestEditedDefaultRuleMovesToANamedRule`、`TestDefaultCacheRuleOpensReadOnly`;改写 `TestSharedRuleEditsApplyToAllItsSubscriptions`(删除规则后回到全关的默认)、`TestFullV1DirectoryMigrationIdempotencyAndRetention`(旧默认复位,其订阅归到“定时检查”)与三个界面测试的新订阅设置 |
-| 媒体库加“刷新”,提示在资源管理器里删掉的文件([DEC-055](../decisions.md#dec-055)) | 原来只有设置“存储”里的“重建索引”:它会移除文件夹已删的条目、标出缺文件的条目,但不告诉用户是哪些,而且会对所有文件算哈希 | `library.RefreshIndex`(同一扫描,不算哈希)在报告里列出 `Removed`(文件夹已删)与 `NewlyMissing`(这次才缺文件,附缺少的文件路径,`verifyItemFilesDetail`);`Backend.RefreshLibrary` 记一行日志;媒体库搜索框旁“刷新”在后台运行,完成后弹窗列出结果 | `TestRefreshIndexReportsFilesDeletedOutsideTrace`(第二次刷新不重复报告)、`TestLibraryRefreshListsDeletedFiles` |
-| 抖音视频“分段异常” | 本机日志、`library.db`(下载任务、重试记录、条目状态)、缓存队列与抖音作品清单里都没有找到异常或这句提示;11-15 14:40 暂停的作品 `7678206464992934130` 已在 11-16 继续并完成(10 MB,2160×3840,20 秒) | 未修改;用户答复暂不处理,下次出现再反馈(Q-019 第 3 条) | — |
+**产物**(替换第 1 节的同类产物):
+- 开发版 `0.1.3-dev.202611201130` 已装到本机,在托盘运行;前后两次升级时旧版都很快退出,没有新的崩溃记录。`trace-dev-setup-0.1.3-dev.202611201130-amd64.exe` SHA-256 `cb2b9c6d8ae57d2051380983d97206f5af094061c8b203233392cea64f9907b4`(8.0 MiB)。
+- 远程版:`trace-server-0.1.3-dev.202611201130-linux-amd64.tar.gz` SHA-256 `bb2a352547ddb78a1a9a4426ed33ab3cd52264157bfd933c747ca20525924236`,`trace-server-0.1.3-dev.202611201130-linux-arm64.tar.gz` SHA-256 `e9702bbd79d68d1c3992613075dded08e337a3dab7dd16de6e87f55e90c0158b`。
-修好的本机数据:安装新开发版后启动恢复自动转换了两场录像全部 10 个 `.part`,两场都变成 `complete`(18 段与 2 段),9 条“收尾转换失败”记录被删除;已经写入的两条 1 亿、3 亿段的“分片丢失”是历史记录,未改动。
+**给 A 的补充审查点**:第 1 条的锁顺序,看还有没有别的路径持有 `startMu` 时进入开录;第 2 条新增的 `via_json` 列(只加列,带默认值);第 3 条把配乐的跳转放宽到公网 HTTPS,依据是推断,审查时请判断这个放宽是否可以接受;第 5 条让永远补不上的内容每次全部缓存都再请求一次(7 天一次)。
-主页的两条新要求(恢复上次阅读位置、侧栏按未读与更新时间列订阅)是产品调整,记为 [DEC-053](../decisions.md#dec-053),交给 B([计划 §14](stage-plan.md#feedback-4),按用户对 [Q-019](../../USER-ACTIONS.md#q-019) 的答复)。
+
+## 8. 全仓库代码审查、重构、依赖更新与打包验证(2026-11-21)
-真实站点请求(用户 2026-11-16 要求排查这一个空间页):匿名请求 `x/web-interface/card` 与 `get_status_info_by_uids` 各 1 次;用开发版哔哩哔哩登录的只读副本请求导航、动态 4 页和投稿 1 页(共 6 次,间隔 ≥ 2 秒),没有触发风控。回复只在本机用来定位字段,排查后删除;没有使用客户端自动续期,开发版保存的登录没有变化。
+在 M5 交付基点之上,按七个领域加双验证员完成了全仓库源码、测试、工具与 CI 工作流的全面审查与收敛,所有改动并入同一个 DCO 阶段提交。
-验证:`go run ./tools/check` 全部通过;对两场的 10 个真实 `.part` 跑新的收尾检查全部通过(不写入原目录)。`go run ./tools/package -install` 将本机 TRACE Dev 从 `0.1.2-dev.202611151300` 升级到 `0.1.2-dev.202611160430`,并在托盘重新打开(`relaunched=true`、`background=true`);启动后进程仍在运行,两场录像的清单已核对。加上用户页修复后再次 `-install`,升级到 `0.1.2-dev.202611160441`(提交 `cf45df6`),托盘重开且命令结束后仍在运行。加上默认规则与媒体库“刷新”后再次 `-install`,升级到 `0.1.2-dev.202611160507`,托盘重开且仍在运行;安装前把本机 `subscriptions.json` 备份到 `artifacts/backup-20261116/`。本机原“默认”规则被改名为“自定义”并全部开启(11 个订阅都在用),启动后“默认”复位为全关,11 个订阅改用新规则“自定义”,定时检查、自动缓存(四种类型)与开播录制都与原来相同。媒体库“刷新”与只读的默认规则在实机上的操作:`not-run`。在实机上播放这两场录像:`not-run`。
+### 8.1 重点缺陷修复与代码重构
-
-## 15. B:第四轮反馈的实现(2026-11-16)
+- **安全与边界**:`OSDesktop.OpenExternalURL` 严格限制 `http`/`https` 与非空主机(拒绝 `file://`、UNC、用户信息);`site.GuardedMediaDialer` 接入哔哩哔哩与抖音媒体传输并修补代理切换豁免与内网/CGNAT/NAT64 网段;抖音 `FetchImageLimited`、头像与历史缩略图补齐站点登录校验(INV-07);远程连接码与令牌改为密码框并即刻清空;`SiteError.Endpoint`、`RoomState.LastError`、日志脱敏与 `sitecheck` 统一剥离签名参数、`*url.Error`、远程令牌、`csrf`、`qrcode_key` 及编码变体;Windows 目录联接点(`ModeIrregular`)与写入/删除无缓存严格路径校验覆盖 `library` 与 `transfer`;`tools/smoke` 与 `tools/uishots` 清理目录限定于 `artifacts/`;`tools/actcheck` 与 `sitecheck` 对未授权接口类别默认拒绝。
+- **数据安全与核心管线**:修复 `subscription.Delete` 未命中非数字 ID 时 `mid = 0` 误删纯抖音订阅、解绑/移动原 B 站账号后 `sub_id` 碰撞覆盖他人订阅、`auth_required` 触发退避与自动缓存吞错误;修复 `storage.OpenSQLite` 仅在确认库损坏时才改名恢复与 WAL 页头 schema 守卫;`library.Store` 新增 `SetAllowMovedFiles(true)` 供 `ProfileRemote` 启用,避免远端搬走文件后被降级为 `missing_files`;`upload` 改为 `--files-from-raw`、检查写入错误、修复忙碌/损坏条目 CPU 空转并上报真实 `QueuedBytes`;修复 `MergeItemMetadata` 多节点直播段合并顺序/内容去重/补充字段、`transfer` 导出目录重叠与未传完冲突删除本地文件;修复 `update.Controller` 并发空指针与定时空转;修复下载实况先改名后校验、`t.Status="paused"` 污染、`context.WithCancel` 泄漏与 64 位 `elst`;修复直播封面写入顺序、远端空 `itemDir` 磁盘检查、Enhanced FLV `PacketTypeMetadata = 4`(同步更新 `docs/design/live.md`)、>3s GOP 误判纯音频、跨轨时间线与 `RefreshForAccounts` 房间过滤;修复 Media Foundation 实时预览关闭时 COM 缓冲 UAF、`pendingReads` 提前删除、取消死锁、`splitDecoder` 采样率/声道数未代理、奇数宽高 NV12 越界及字幕重叠匹配。
+- **服务、外壳与界面**:释放锁后再发布同步事件;自动更新 `Relaunch()` 改为在 `mygo.App.OnQuit` 幂等清理后端与释放目录锁;`PauseAllActiveWork` 按站点隔离失效状态(解决 LOOP-016);托盘刷新串行化并持久化窗口尺寸与首次托盘提示;媒体库无封面视频不再整文件读入 `.mp4` 解码;修复远程设置 30 秒刷新负时长空转;`requestGuardedCleanup` 保证关到托盘或丢弃请求时释放 `MediaDecoder`;头像与历史缩略图异步解码与负缓存、媒体库/检查计划/关注导入虚拟化、全切片 FNV 缓存与 IME/对话框统一。
+- **结构拆解与去重**:拆解 `download`、`live`、`library`、`subscription`、`service`、`shell`、`ui`、`tools/uishots`、`tools/actcheck` 等超大文件;提取公共 `site.WrapIdleReadCloser`、`SanitizeEndpoint`、`UnwrapURLError`、`LoopbackTransport`、`visitManifestFiles`、共享 Range 下载与直播会话主循环;全仓补齐 100+ 条回归测试,清零历史阶段/问题编号注释(完成 LOOP-007)。
-按[计划 §14](stage-plan.md#feedback-4)(修订 5)与用户对 [Q-019](../../USER-ACTIONS.md#q-019) 的答复连续完成 H1、H2、D3 及必测用例 M4-K39~K43,保留 A 在 §14 的录制修复与回归测试、DEC-054/055 的实现及以前各轮的全部测试;没有改动 `go.mod` / `go.sum`,没有新增第三方依赖,没有发起真实站点请求,主页只读本机数据。
+### 8.2 依赖更新与清理记录
-| 信息 | 内容 |
+| 类别 | 处理 |
| --- | --- |
-| 执行范围 | H1(各站点筛选的阅读位置)、H2(侧栏订阅列表、未读圆点与窄窗头像条)、D3(正本文档)及 M4-K39~K43 全部完成,无缩减验收 |
-| 版本与工作区 | 分支 `codex/m4-account`,在 A 本轮的阶段提交 `46213c6` 上继续;代码、测试、截图与正本文档 amend 为 `e7966b9` 后打包安装,再只补写本报告、交付状态与 USER-ACTIONS 并 amend 一次,源码与已装开发版一致;最终交付 SHA 见 B 的交付消息。未执行 push、PR、合并、打标签或发布 |
-| 可运行产物 | `go run ./tools/package -install`:开发版 `0.1.2-dev.202611160535`(`VERSION.txt` 提交 `e7966b91da5b`、`built_at=2026-11-16T05:35:48Z`),安装时 TRACE Dev 正在托盘运行,经 `--quit-for-update` 保存退出(`quitMs=325`)、静默安装并以 `--background` 在托盘重开,从 `0.1.2-dev.202611160507` 升级,`1850 ms`(`artifacts/package/install-dev.json`:`installed=true`、`wasRunning=true`、`relaunched=true`、`background=true`);命令结束后 `trace.exe` 仍在运行(`tasklist` 核对)。`trace-dev-setup-0.1.2-dev.202611160535-amd64.exe` SHA-256 `b4db302c29d69b794e2cd3bbd597d66f4fac5e01bcac714a150a412804b267a1`,`trace.exe` `3dbf853898282deb24e2f8a9f1cabcbf39704b82713b75df36f1c1d3ac65a0a0` |
-| 数据结构 | 数据文件结构版本不变:`ui-state.json` 新增可选字段 `homePositions`(`{"all"\|"bilibili"\|"douyin": {key, pubTs, offsetPx}}`,旧文件没有时照常读,规范化只留三个筛选键与有效项);`homeSeen` 只写 `sub:`,旧的 `mid:` 与作者键保留不删;`anchor` 含义不变 |
-
-| 工作包 / 用例 | 实现位置 | 命令与证据 | 状态与限制 |
-| --- | --- | --- | --- |
-| H1 回到阅读位置(M4-K39、NFR-PERF-001) | `internal/uistate/uistate.go`(`HomePosition`、`HomePositions`、规范化与复制);`internal/ui/home_position.go`(`restoreHomePosition` 以 `{key+"\x00", pubTs}` 为游标读 `older` 一页、包含那条本身,删掉时就是不晚于它的最近一条;`stepHomeRestore` 先定位到那条、布局后按偏移滚动,期间不在两端翻页;`noteHomePosition` 用行与列表上一帧的布局框算偏移,静止 1 秒保存;`flushHomePosition` 在离开主页、点开订阅、切换筛选与 `App.Close`(关到托盘、退出、`--quit-for-update`)时保存,相同不写);`internal/ui/feed.go`(`setFeedSiteFilter` 各筛选的条目与位置留在内存,回来时按那条与偏移重新定位)、`internal/ui/app.go`(`loadInitialFeed` 每次运行每个筛选第一次显示时恢复)、`internal/ui/views.go` | `TestHomeRestoresReadingPositionPerSiteFilter`(“全部”第 41 条偏移 37px、“B 站”另一处,重建 `App` 后各回各的、“抖音”从最新处开始,往上滑载入更新的条目且当前条目不跳,那条删除后回到不晚于它的最近一条,单订阅视图不写位置)、`TestHomeRestoresPositionQuicklyWith5000Posts`(5000 条,重建到回到位置 < 1 s)、`TestHomePositionsAreOptionalAndPerSiteFilter`;改写 `TestFeedProgressEventsKeepPositionAndRestartOpensAtNewest`(新会话回到读到的那条) | passed |
-| H2 订阅列表与圆点(M4-K40~K42) | `internal/ui/home_subs.go`(`homeSubscriptionRows`:按 `libraryStatistics` 的作者最新时间聚合到订阅、只算当前筛选的站点,按签名缓存行;进入主页时每个筛选排一次顺序快照:直播(组内未读在前)→ 未读 → 已读,停留期间新符合的追加到末尾;`homeSubUnread`:`homeSeen["sub:"]`,没有时用启动时的 `anchor`,都没有算已读;`renderHomeSubAvatar` 直播圈与约 8px 强调蓝圆点);`internal/ui/shell.go`(`renderHomePanel` 去掉“有更新”“正在直播”分节,订阅列表 `ui.List` 虚拟化);`internal/ui/views.go`(窄窗横向头像条,“全部动态”在最前,只构建滚到的条目);`internal/ui/feed.go`(`markSubscriptionSeen` 写原值与最新时间的较大者) | `TestHomePanelSubscriptionsUnreadOrderAndDots`、`TestHomePanelFirstUseAnchorAndSiteFilter`、`TestHomePanelLiveFirstNoTitlesAndNarrowStrip`、`TestHomePanelThousandSubscriptionsVirtualized`(1000 个订阅只构建可见行,滚动 20 次不读统计与信息流);改写 `TestHomePanelListsLiveRooms`(直播订阅排最前、点开它的信息流,没订阅的直播间不列)与 `TestHomePostsUpdatedRowParseHistoryAndLibraryMenus`(未订阅作者不列、圆点与不挪位置) | passed |
-| D3 文档 | `docs/requirements.md`(FR-FEED-001、NFR-PERF-001、FR-LIVE-001、FR-DY-008)、`docs/ui.md`(§1 侧栏、§3.1 订阅列表与回到位置)、`docs/design/data-and-cache.md`(`ui-state.json` 与 §4 位置、订阅列表)、`docs/design/architecture.md`、`docs/design/subscriptions.md`、`docs/design/live.md`、`docs/delivery/status.md`、`USER-ACTIONS.md`(H-001 第 32 步、Q-019) | `go run ./tools/checkdocs` OK | passed |
-| 截图(§14.5) | `tools/uishots/main.go`:主页场景加两个订阅的本机内容(一新一旧)与固定 `anchor`,断言侧栏 `主页订阅列表`、窄窗 `主页订阅头像条` 与 `主页订阅头像:全部动态`,禁止“正在直播”“有更新”;新场景 `home-restored`(新会话回到第 3 条、偏移 40px,场景可多跑几帧) | `go run ./tools/uishots -out artifacts/uishots`:55 个场景、165 张 PNG 全部通过;`home-{1280,1000,720}x860.png`(直播、未读、已读三组与窄窗头像条)、`home-restored-{1280,1000,720}x860.png` | passed |
-| M4-K43 回归 | A 本轮 `TestRecoveryAcceptsEXTINFDriftAndClearsConvertFailed`、`TestHLSSequenceResetIsNotLostSegments` 及以前各轮测试 | 单独运行两个录制测试通过;`go run ./tools/check`:`ALL CHECKS PASSED in 2m28.041s`(`internal/ui` 50.7 s);`GOOS=linux go vet ./...` OK;`go run ./tools/smoke -pkg dist/trace-dev -out artifacts/smoke`:PASSED(`2933 ms`,`quietMode=hidden`,托盘专用工作集 `0.62 MiB`、提交 `81.36 MiB`,`webview2=0`,`stealFocusDetected=false`);`go run ./tools/deps`:`due=0`、`waiting=3` | passed |
-
-实现中发现并一并处理:原来从单订阅视图返回时把主列表的 `ListState` 原样拷回,单订阅视图滚动过的话主时间线会落到别处(以前的测试没有在单订阅视图里滚动);现在返回与切换筛选都按记下的那条与偏移重新定位,`TestHomeActorReturnRestoresRowAndPixelOffset` 照常通过,`TestHomeRestoresReadingPositionPerSiteFilter` 覆盖了滚动过的情形。
-
-### not-run 与限制
-
-- **实机体验**:`not-run`。本机 TRACE Dev 已更新至 `0.1.2-dev.202611160535` 并在托盘运行,待用户按 [H-001](../../USER-ACTIONS.md#h-001) 第 32 步复查。
-- 偏移按上一帧的布局框计算,滚动停下约 1 秒后才保存;在保存前强制结束进程(不经过关闭或退出)会丢掉最后这段滚动,回到上一次保存的位置。
-- 侧栏的“最新更新时间”按 `library.db` 的条目统计(与媒体库同一来源),只出现在信息流、没有对应媒体库条目的内容不计入。
-- `go test -race` 与完整的 Linux 单测仍为 `not-run`(本机无 cgo 工具链;Linux 只做了 `GOOS=linux go vet`)。
-
-### 给 Agent A 的审查 prompt
-
-```text
-你是 TRACE 的 Agent A,集中审查 M4 第四轮实机反馈的主页调整(DEC-053,计划 docs/delivery/stage-plan.md 第 14 节修订 5)。
+| 依赖盘点(DEC-048) | 远端 PR #9(`golang.org/x/image` 0.47.0 → 0.48.0)已并入本阶段提交,合并后关闭;升级满 7 天的 `github.com/Eyevinn/mp4ff` v0.62.1 → v0.63.0;`go run ./tools/deps` 剩余 `due: 0`、`waiting: 1`(`github.com/egoist/mygo` v0.10.0,第 3 天,未满 7 天);`go run ./tools/deps -audit` 通过(`called: 0`、`open: 0`、`expiredExceptions: 0`) |
+| 清理无用代码 | 删除已被 `trace-subscriptions.json` 取代且零调用的 OPML 子系统(`internal/subscription/opml.go`、`service.BackendAPI` 的 `ExportOPML`/`ImportOPML` 及对应单测);删除 4 个零调用未导出函数(`shell.trayStatusLabel`、`subscription.getSchedulerStateLocked`/`saveSchedulerStateLocked`、`ui.subscriptionLiveOn`、`ui.logoutAccount`) |
+| 清理测试与文档 | 按能力重命名两个遗留反馈测试文件(`feedback5_test.go` → `tasks_and_sub_accounts_test.go`、`home_feedback4_test.go` → `home_position_and_subs_test.go`);更新过时的根目录 `README.md`、`docs/dev-rules/engineering.md`(MyGo v0.9.0 / `mp4ff` v0.63.0 / 任务页六组侧栏)、`docs/design/live.md`(`PacketTypeMetadata = 4`)与 `docs/delivery/status.md`(LOOP-007/016、OSS-003);删除被忽略的 `tmp/` 临时脚本与旧 WSL 测试产物(不动用户备份 `artifacts/backup-20261116` 与 `artifacts/repair-20261115`) |
-报告:docs/delivery/stage-report.md 第 15 节(并确认第 14 节 A 的录制修复、DEC-054/055 与以前各轮实现完整保留)。
-分支:codex/m4-account,单个 DCO 提交;B 的代码与文档 amend 为 e7966b9 后打包安装开发版 0.1.2-dev.202611160535,再只补写报告、交付状态与 USER-ACTIONS 并 amend 一次(最终 SHA 见 B 的交付消息)。
+### 8.3 2026-11-21 开发版下载、媒体库归属与任务卡片反馈修复
-审查重点:
-1. H1 阅读位置(M4-K39、NFR-PERF-001):internal/ui/home_position.go 的恢复(key+"\x00" 游标包含那条本身、删掉时不晚于它的最近一条、先定位再按偏移滚动、期间不翻页)、偏移测量(行与列表上一帧的布局框)、保存时机(静止 1 秒、离开主页、点开订阅、切换筛选、App.Close 覆盖关到托盘与 --quit-for-update,相同不写、失败只报一次);三个筛选分别记位置、同一次运行内来回切换回到各自位置、单订阅视图不写;ui-state.json 结构版本仍为 2,homePositions 可选。
-2. H2 订阅列表(M4-K40~K42):internal/ui/home_subs.go 的未读判断(homeSeen 优先、没有用启动时 anchor、都没有算已读)、进入主页时的顺序快照与停留期间只改圆点与直播圈(新符合的追加末尾)、按站点筛选统计、只列订阅;侧栏无分节标题与状态文字、ui.List 虚拟化、行按签名缓存不逐帧读媒体库;窄窗头像条只构建滚到的条目。
-3. 改写而非删除的旧测试:TestFeedProgressEventsKeepPositionAndRestartOpensAtNewest、TestHomePanelListsLiveRooms、TestHomePostsUpdatedRowParseHistoryAndLibraryMenus;以及从单订阅视图返回改为按那条与偏移重新定位(原来拷回 ListState,单订阅视图滚动过会错位)。
-4. 文档:requirements、ui.md §1/§3.1、data-and-cache(ui-state.json、§4)、architecture、subscriptions、live、status、USER-ACTIONS(H-001 第 32 步、Q-019)。
+针对用户反馈的本机 TRACE Dev 下载“部分完成”、B 站转发视频归属、抖音共创作品详情页入口及任务卡片右侧裁切问题,结合本机只读排障与常设授权内的有界真实站点验证(`internal/sitecheck` 账本,隔离临时目录验证后即删)查明全部根因并完成修复:
-验证命令:go run ./tools/check、GOOS=linux go vet ./...、go run ./tools/uishots -out artifacts/uishots、go run ./tools/smoke -pkg dist/trace-dev -out artifacts/smoke。局部问题直接修复(需要时打包安装)并 amend(git commit --amend -s),较大缺口按交接模板一次性交回。未授权:push、PR、合并、打标签、发布。
-```
-
-
-## 16. 实机反馈第五轮(2026-11-16,A 实现)
-
-用户的 7 条反馈及 3 条补充(全部账号页、抖音私密账号、任务里的封面)。产品调整记为 [DEC-056](../decisions.md#dec-056)(转发与合作视频的存放位置)与 [DEC-057](../decisions.md#dec-057)(任务页、图标栏、主页头像、切换速度、全部账号、抖音私密账号)。没有新增第三方依赖,没有发起真实站点请求。
-
-| 反馈 | 原因 | 修改 | 回归 |
+| 编号 | 现象与根因 | 修复 | 证据 |
| --- | --- | --- | --- |
-| 1. 任务里的记录都能删除(最近结束的录制、取消的缓存队列、录制异常) | 缓存队列只能暂停或取消,结束后一直留在 `cache-queue.json`;“最近结束的录制”由媒体库最近的录像推出,没有隐藏记录;录制异常记在录像 `item.json` 与直播管理器内存里,没有清除入口 | `Backend.RemoveCacheQueue`、`RemoveFinishedCacheQueues`(未结束的拒绝:“缓存队列还在进行,请先取消再移除”);`ui-state.json` 可选字段 `dismissedLiveSessions`(8 天后规范化删除)记移除的“最近结束的录制”,逐条“移除”与“全部移除(N)”;`Backend.ClearLiveIncidents` 清空结束场次的 `live.incidents` 并清掉直播管理器里该房间的记录(`Manager.ClearIdleIncidents`),正在录制的拒绝;录制异常每场“删除记录”。都不删录像与已缓存的文件 | `cache_queue_test.go` 4b、`TestClearLiveIncidentsKeepsTheRecording`、`TestSettingsNoRecordingLimitAndTasksLiveIncidentsUI_M4K33_M4K35` 第 7 段、`TestDismissedLiveSessionsExpire`、`TestTasksSidebarSectionsAndCacheQueueDetail`(移除结束的队列) |
-| 2. 转发的图片、视频不进原作者文件夹,放转发者文件夹但不和他自己的投稿混在一起,媒体库能单独筛选 | 转发里的视频按投稿人建 `ItemDir`,动态本身存在转发者的 `dynamics/` | 转发(有 `orig` 或类型为 `DYNAMIC_TYPE_FORWARD`)存到转发者的 `forwards/`,它带的、投稿人不是转发者的视频存到 `forwards//`,清单记 `via = {reason: forward, uid, name, dynamicId}`;转发与原动态里重复的图片、视频只存一份;媒体库新增“转发”(`FeedFilter.Kind = "forward"`),“图片”“视频”加 `ExcludeForward`;按作者筛选也匹配 `via.uid`(表达式索引 `idx_library_items_via`) | `TestForwardIsStoredInForwarderFolderApartFromOwnPosts`(合成服务端端到端:不建投稿人文件夹、“转发”2 条、“视频”去掉转发后 0 条、按转发者筛选 2 条)、`TestDedupeDynamicMediaKeepsOrder`、`TestLibraryForwardFilter` |
-| 3. 合作视频存在订阅的成员下(例:缓存灰泽满Hazel 时 BV1DDpE68E56 进了小柔Channel 的文件夹) | 视频详情只读 `owner`(投稿人即第一作者),没有读 `staff` | `VideoDetail.Staff` 解析 `data.staff`;`VideoEnqueueRequest.ForMid`:订阅自动缓存、缓存队列与用户页投稿的“缓存”带上为谁缓存,这位成员在 `staff` 里且不是投稿人时存到他的 `videos//`,清单记 `via = {reason: collab}`;没有成员上下文(直接解析视频)仍存在投稿人文件夹 | `TestVideoDetailParsesCollaborationStaff`、`TestCollaborationVideoIsStoredUnderTheMemberItWasCachedFor` |
-| 4. 缓存队列在任务页的布局与其他部分不协调 | 侧栏“缓存队列”分组每个队列占一行,选中后主面板只显示一个队列 | 侧栏只留“缓存队列(未结束数)”;主面板顶部说明与“清除已结束(N)”,每个队列一张卡片(状态、计数、暂停 / 继续 / 取消 / 移除),点开展开进度与最近缓存的内容;“在缓存队列中查看”展开对应卡片 | 改写 `TestTasksSidebarSectionsAndCacheQueueDetail`(侧栏“缓存队列(2)”、展开卡片、移除);`tools/uishots` 的 `tasks`、`tasks-queue` 场景改用新标签 |
-| 补充:任务里“最近缓存的内容”有缓存却没有封面 | 队列只记条目键与标题,任务页画缩略图时没有封面路径;动态常常只有引用的视频,没有自己的图片 | `queueRecentCover` 按条目键读媒体库清单取封面(封面优先,其次第一张图、图文页),动态没有图片时用它引用的视频的封面;结果按缓存状态版本缓存,不逐帧读库;去掉这里多余的“已缓存”圆点 | `TestQueueRecentItemsShowCovers` |
-| 5. 图标栏的按钮往上移 | 顶部的 TRACE 字标是一个 40px 的按钮,另加 8px 间距与标题栏上边距 | 字标改为不可点的标志,去掉多余间距,第一个按钮紧挨标志 | `TestImmersiveTitleBarKeepsControlsClearOfWindowButtons`(第一个按钮的中心与“主页全部动态”相差不超过 6px、在拖动条下方) |
-| 6. 主页点头像打开订阅,不是用户页 | 帖子头像统一打开用户页 | 主页帖子的作者已订阅时(`subscriptionForAuthor` 按站点与 UID / mid 找订阅)点头像打开订阅详情,没订阅的仍进用户页;其他页面不变 | `TestHomeAvatarOpensTheSubscription` |
-| 7. 主页切换站点筛选更快(补充:可以引入数据库或 JSON 索引) | 实测(合成 12 个作者 × 6 条 × 3 张 1600×1200 图)切换后的第一帧 2.4~3.5 秒。分析:① 每张缩略图读文件都对每一级上级目录 `EvalSymlinks`;② 缩略图按 1280 px 解码;③ 解码缓存只有 160 张、先进先出,来回切换就全部重新解码。瓶颈不在 `library.db` 查询,所以没有另加数据库或 JSON 索引 | ① 读取时上级目录 3 秒内核对过就不再逐级核对(`rejectDirectoryLinksRecent`,文件本身与条目文件夹每次都核对,写入与删除不走这个缓存);② 按显示大小解码:单图 960 px、九宫格 480 px;③ 解码缓存改为按最近使用淘汰(600 张、320 MiB,`bitmapCache`)。之后第一次进入约 0.7 秒,切回刚看过的筛选 7~11 ms | `TestHomeSiteSwitchBackReusesDecodedImages`(切回三个筛选都 < 300 ms、解码尺寸不超过 960 px)、`home_and_media_test.go` 的解码尺寸 |
-| 补充:订阅页按站点看全部订阅账号 | 没有这样的页面 | 订阅侧栏“全部账号”(窄窗在搜索框旁):站点筛选、“N 个账号”,每行头像、名称、站点、UID 或抖音号与“订阅 <所属订阅>”,点行打开订阅 | `TestSubscriptionAccountsBySite`;新截图场景 `subscriptions-all-accounts` |
-| 补充:抖音用户 `MS4wLjABAAAA66TI…` 提示私密账号不能浏览,网页上有视频 | 用户资料 `secret == 1` 时 TRACE 不请求作品。私密账号对已关注并被通过的账号公开作品,网页用的是同一登录 | 不论是否私密都请求第一页作品:拿到作品时照常列出(`PrivateVisible`,底部一行“私密账号:当前登录的抖音账号可以看到这些作品”,可以“全部缓存”);拿不到(空或无权限)才显示“这个账号是私密账号,当前登录的抖音账号看不到作品”。用户页与直播横幅两处共用 `firstDouyinUserWorks` | `TestDouyinPrivateAccountShowsWorksVisibleToTheSignedInAccount`(合成服务端:私密且有作品时列出,私密且无作品时不报错) |
-
-已有的条目不搬动:BV1DDpE68E56 已经缓存在小柔Channel 的文件夹里,想移到灰泽满Hazel 下,在媒体库删除这条后从灰泽满Hazel 的订阅或用户页重新缓存。以前缓存的转发也留在原处(转发动态本身仍在 `dynamics/`,媒体库按动态类型把它们算进“转发”;它带的视频在投稿人文件夹里,没有 `via`,不进“转发”)。
-
-验证:`go run ./tools/check`:`ALL CHECKS PASSED`(`internal/ui` 30.3 s);`GOOS=linux go vet ./...` OK;`go run ./tools/uishots -out artifacts/uishots`:168 张全部通过(新增 `subscriptions-all-accounts`);`go run ./tools/checkdocs` OK。`go run ./tools/package -install`:TRACE Dev 从 `0.1.2-dev.202611160535` 升级到 `0.1.2-dev.202611161316`(提交 `b5fab00`,安装包 SHA-256 `83e83cbda7c20a05c4805e820e02bd1ab3529812ba073fa5183ec4151fe0e2a0`),保存退出 289 ms、以 `--background` 在托盘重开(`relaunched=true`、`background=true`),命令结束后 `trace.exe` 仍在运行,日志只有启动一行、没有错误。`go run ./tools/smoke -pkg dist/trace-dev -out artifacts/smoke`:PASSED(3002 ms,`quietMode=hidden`,托盘专用工作集 0.60 MiB,`webview2=0`,`stealFocusDetected=false`)。
-
-### not-run 与限制
-
-- **抖音私密账号在真实站点上**:用户 2026-11-16 在 `0.1.2-dev.202611161316` 上实机打开这位私密用户,作品可以列出(H-001 第 33 步 ⑧ 通过);A 没有对这个账号发请求。如果用户登录的抖音账号看不到这位作者的作品(未关注或未通过),TRACE 仍会说明看不到。
-- 合作视频只有带成员上下文(订阅的自动缓存、缓存队列、用户页投稿的“缓存”)时才存到成员下;直接粘贴视频链接解析后缓存,仍存在投稿人文件夹。同一视频已经缓存过时沿用原文件夹。
-- 转发里带的视频如果以后又从投稿人自己的订阅缓存,条目键相同,仍留在转发者的 `forwards/`(同一视频只存一份)。
-- “最近结束的录制”的移除只是隐藏 8 天,之后那场若仍在最近的录像里会重新出现(录像本身不受影响)。
-- 实机体验:`not-run`,待用户按 [H-001](../../USER-ACTIONS.md#h-001) 第 33 步复查。
-- `go test -race` 与完整的 Linux 单测仍为 `not-run`(本机无 cgo 工具链)。
-
-
-## 17. A:审查第四轮 B 的实现与第五轮(自审),加入订阅对话框(2026-11-17)
-
-审查范围:§15 B 的主页调整(`internal/ui/home_position.go` 阅读位置的保存与恢复、`home_subs.go` 侧栏订阅列表与未读圆点、`feed.go` 站点筛选切换、`uistate` 的 `homePositions`);§16 第五轮全部改动(A 自己实现,这里是**自审**):转发与合作视频的路径、`via` 与表达式索引、读取时的目录核对缓存、缓存队列与录制记录的移除、解码缓存、抖音私密账号。按 [REVIEW](../../REVIEW.md) 的顺序看了实现、需求和证据。
-
-| 编号 | 级别 | 位置 | 问题 | 修复与复验 |
-| --- | --- | --- | --- | --- |
-| F-001 | P2 | 界面各处写 `ui-state.json`(`home_position.go` 阅读位置、`app.go` 路由、`feed.go` 站点筛选与查看时间、`live_incidents_view.go`、`media_controls.go`、`overlays.go`、`subscriptions.go`)与后端 `SaveAnchor` | 都先读出整个状态、改一个字段、再整体写回。更新器在后台用 `MutateUIState` 写 `update.lastCheck` 与“已下载、等重启”的版本;它若在界面读与写之间写入,就被界面写回的旧状态覆盖,正式版下载好的更新不会提示重启。第四轮让阅读位置每停约 1 秒写一次,触发机会大增(以前就有,不是第四轮引入) | `SettingsService` 增加 `MutateUIState`,界面各处与 `SaveAnchor` 改为在锁内只改自己的字段;两个注入写入失败的测试桩在新路径上注入同样的失败。新测试 `TestUIStateWritesKeepTheUpdatersWrite`(界面看到的是后台写入前的状态):修复前失败(`ReadyVersion` 被清空),修复后通过 |
-| F-002 | P2 | `Backend.firstDouyinUserWorks`(§16 第五轮) | 私密账号请求作品遇到风控、限流、登录失效或网络错误时,也显示成“当前登录的抖音账号看不到作品”,没有重试;违反“风控、限流、网络失败要分开表达” | 只有作品为空、“禁止访问”或“不可用”才算看不到;其他错误原样显示并可“重试加载抖音作品”,重试拿到作品就照常列出并显示“私密账号:…可以看到这些作品”。`TestDouyinPrivateAccountShowsWorksVisibleToTheSignedInAccount` 增加限流的私密账号(修复前失败、修复后通过),`TestDouyinParseDispatchAndUserPagePaginationExpiredRetryPrivate` 第 7 段覆盖界面上的错误、重试与可见提示 |
-| F-003 | P2 | `TestHomeSiteSwitchBackReusesDecodedImages`(§16 新增) | 用“切回 < 300 ms”判断,机器忙时可能误报:一次完整检查里 `internal/ui` 失败过一次,失败详情没有留下,之后单独与完整重跑共 6 次都没有复现,不能确定就是它 | 改为比较解码缓存里的图片:先等三个筛选的缩略图都加载完,切回时不能出现之前不在缓存里的图片,也不能有正在加载的缩略图。把缓存临时改为 20 张时这条测试失败(又解码了头像),恢复后通过 |
-
-其余没有发现问题:阅读位置的游标 `key + "\x00"` 与 `library.db` 同一发布时间内按键倒序一致,确实包含那条本身;侧栏行按签名缓存、未读在绘制时判断,签名不变也不会显示旧圆点;已缓存的视频再按合作成员缓存时沿用原文件夹,不重复下载;索引重建与“添加已有的缓存文件夹”都是通用的 `item.json` 扫描,`forwards/` 也会被找到;移除缓存队列在锁内完成、写盘失败会回滚;目录核对缓存只用于读取,文件本身与条目文件夹每次都核对。
-
-**加入订阅对话框([DEC-058](../decisions.md#dec-058),用户 2026-11-17 在审查中途提出)**:FR-USER-003 原本就要求“新建订阅,或加入已有订阅”,此前用户页与“我的”只会新建。新增 `internal/ui/subscribe_dialog.go`:用户页“订阅”(哔哩哔哩与抖音)、“我的 › 加入订阅”与添加订阅里预览账号的“加入现有订阅…”都打开它;可以新建,也可以搜索后加入现有订阅(`LinkSubscriptionAccountRef`),失败时在对话框里说明原因、不关闭。实现中发现,在点“加入”的同一帧里把对话框状态整个清零会让 MyGo 在帧末访问已清空的列表状态而崩溃,改为关闭时只置 `Open=false`、打开时再重置。测试:`TestSubscribeAsksExistingOrNew`(用户页打开对话框、列出全部订阅、搜索缩小列表、加入“未读乙”后账号归它且用户页显示已订阅、已属于别的订阅时报错不关闭、取消关闭);改写 `TestMineItemsOpenThroughOpenLink`(“加入订阅”先打开对话框,再点“新建订阅”);新截图场景 `subscribe-picker`。
-
-验证:`go run ./tools/check`:`ALL CHECKS PASSED in 1m22.979s`;`GOOS=linux go vet ./...` OK;`go run ./tools/uishots -out artifacts/uishots`:171 张全部通过;`go run ./tools/checkdocs` OK。`go run ./tools/package -install`:TRACE Dev 从 `0.1.2-dev.202611161316` 升级到 `0.1.2-dev.202611161744`(提交 `7ea008d`),以 `--background` 在托盘重开(`relaunched=true`、`background=true`),命令结束后 `trace.exe` 仍在运行,日志只有退出与启动行;这次保存退出用了 5.1 秒(上次 0.3 秒),日志里退出前后没有错误,只是在后台缓存队列运行时退出。`go run ./tools/smoke -pkg dist/trace-dev -out artifacts/smoke`:PASSED(3045 ms,`quietMode=hidden`,`webview2=0`,`stealFocusDetected=false`)。
-
-结论:实现交付——第四轮 B 的实现与第五轮完成;技术审查——A 审查第四轮 B 的实现、**自审**第五轮与加入订阅对话框,3 个 P2 已修复并复验,审查收敛;产品验收——`not-run`,等用户按 [H-001](../../USER-ACTIONS.md#h-001) 第 32、33 步实机复查。用户 2026-11-17 授权审查通过后推送、创建 PR,CI 通过后合并([ACT-021](../../USER-ACTIONS.md#act-021))。
-
-### not-run 与限制
-
-- 实机复查第 32、33 步与加入订阅对话框:`not-run`(第 33 步 ⑧ 抖音私密账号用户已确认)。
-- F-003 的那次失败没有留下详情,不能确定是哪条测试;之后 6 次重跑都通过。
-- `go test -race` 与完整的 Linux 单测仍为 `not-run`(本机无 cgo 工具链)。
+| 1 | **抖音图文配乐 `blocked`**(`lf3-static.bytednsdoc.com`):空 `music.play_url` 图文回退到顶层 `video.play_addr` 时,部分音频位于字节静态域名 `*.bytednsdoc.com`,该后缀未列入抖音媒体白名单 | `internal/site/types.go` 将 `bytednsdoc.com` 加入 `DefaultDouyinMediaHosts()`(仍强制 HTTPS 443、`GuardedMediaDialer` 与零 Cookie) | `TestDouyinBytednsdocMusicHostAllowed`;真实站点临时验证 1 条该类图文一次完成(`complete`、`music.mp3` 完整落盘、0 Cookie 泄露) |
+| 2 | **抖音图文视频页/实况片段 HTTP 403**:含 `need_set_token: true`(或 `is_need_set_cookie: true`)的 `v26-web*.douyinvod.com` 直链带 `ply_type=3` 策略参数、直接拉取固定 403;而 `play_addr.url_list` 里的 `www.douyin.com/aweme/v1/play/` 此前被媒体白名单静默丢弃 | `internal/site/douyin/work.go` 透传 `NeedSetToken`;`internal/site/douyin/client.go` 新增 `ResolvePlayRedirect`(仅向主站 `/aweme/v1/play/` 发带 Cookie 且禁止自动跟随的单次请求,校验非水印与登录/验证拦截及公网 HTTPS 443 目标地址);`internal/download/douyin_video.go` 与 `douyin_note.go` 对 `NeedSetToken=true` 先解析无 Cookie CDN 地址再下载,普通作品在直链刷新后仍 403/404 时回退解析 | `TestParseAwemeWorkPropagatesNeedSetToken`、`TestResolvePlayRedirectSecurityAndBehavior`、`TestDouyinNeedSetTokenPlayRedirectFallbackAndPartialReason`;真实站点临时验证 2 条 `need_set_token=true` 图文(混排视频页与 3 页实况照片)全部一次完成(`complete`、0 Cookie 泄露;3 条合共 7 次 API、20 次媒体请求) |
+| 3 | **B 站动态 `code=4101152` 显示“未识别的错误代码”且开播卡片进入动态缓存队列**:`/x/polymer/web-dynamic/v1/detail` 对已失效的 `DYNAMIC_TYPE_LIVE_RCMD` 返回 `code=4101152`(“动态不可见”) | `internal/site/bilibili/errors.go` 将 `4101152` 映射为 `ErrKindUnavailable`(“动态不可见或已删除”);`internal/service/batch_cache.go` 的 `dynamicQueueCandidate` 将 `DYNAMIC_TYPE_LIVE_RCMD` 标为不可缓存跳过 | `TestClassifyBiliCodeDynamicUnavailable4101152`、`TestDynamicQueueCandidateSkipsLiveRcmd` |
+| 4 | **B 站转发动态附带视频在媒体库按原视频作者显示**:磁盘已按 DEC-056 存在转发者的 `forwards/` 目录且带 `via.reason="forward"`,但 `library.Statistics()`、`ListItems()`、`LatestPubByAuthor()` 与 `CountCachedWorks()` 未将 `via.reason="forward"` 归属到转发者,导致原视频作者出现在媒体库作者列表 | `internal/library/statistics.go`、`feed.go`、`works.go` 统一将 `via.reason="forward"` 归入转发者名下,不再为仅因转发缓存的视频生成原上传者作者项或错误统计 | `TestForwardVideoBelongsToForwarderNotUploaderInLibrary`、`TestCollabVideoBelongsToMemberItWasCachedFor` |
+| 5 | **抖音共创作品从用户页点进详情页再缓存时丢失“为该账号缓存”上下文**(另确认用户提到的两条旧条目缓存于 2026-11-19,早于 2026-11-20 DEC-063 改动,按规则不自动搬动旧文件夹) | `internal/ui/app.go`、`navigation.go`、`douyin_user_view.go`、`douyin_work_view.go` 对称补齐 `openDouyinWorkFor` 与 `douyinCacheFor`,在用户页点入作品详情再点“缓存视频/缓存图文”时保留 `ForUID`/`ForName` | `TestDouyinWorkDetailPreservesUserContextForCoCreationCache` |
+| 6 | **任务页长标题挤出右侧进度百分比、且“部分完成”卡片缺少原因**:卡片内层列与标题行缺少 `Shrink(1)`,且 `manager.go` 结束时清空了 `partial` 任务的 `ErrorMessage` | `internal/ui/tasks_downloads_view.go` 为卡片内层列、标题行与原因文本补 `Shrink(1)`,并将 `partial` 进度条与原因条改为醒目黄色提示;`internal/download/manager.go`、`douyin_note.go`、`douyin_video.go`、`dynamic.go` 写入并保留缺失摘要,`task_store.go` 读取旧空原因 `partial` 任务时自动从 `item.Missing` 回填 | `TestTasksDownloadsLongTitleAndPartialReasonDoNotClip`、`TestDouyinNeedSetTokenPlayRedirectFallbackAndPartialReason` 及 `uishots` 192 张截图(`tasks-720x860.png` 实眼确认无裁切) |
+
+### 8.3a 2026-11-21 订阅“内容”里删除已缓存条目(DEC-064)
+
+| 现象 | 修复 | 证据 |
+| --- | --- | --- |
+| 已缓存的动态(尤其只有文字的)没有地方删除:媒体库按文件列图片与视频,订阅详情“内容”的帖子没有“⋯” | [DEC-064](../decisions.md#dec-064):`PostCardData.LocalManage`,订阅“内容”的帖子右上角“⋯”(`renderCachedPostMenu`:“在资源管理器中显示”、红字“删除”),删除走媒体库同一个 `PlanDelete` 与确认弹窗;弹窗标题写“类型:标题”(动态无标题用正文第一行),大小计入一并删除的引用视频,共用视频说明改从动态的角度写 | `TestSubscriptionDetailContentTabCrossSiteZeroRequestsAndEmptyState` 加断言:菜单为“在资源管理器中显示,-,删除”,确认弹窗写“动态:<标题>”,确认后动态离开列表、登记图片从磁盘删除、全程 0 次站点请求 |
+
+### 8.4 最终打包与验证证据(替换第 1、7 节的同类产物)
+
+- **门禁与测试**:`go run ./tools/check` ALL CHECKS PASSED(1m27.34s,含双平台依赖方向检查、Linux amd64/arm64 远程构建与 `GOOS=linux go vet ./...`、`tools/checkdocs` 与 `git diff --check HEAD`);全仓含测试包全通;`go run ./tools/uishots -out artifacts/uishots` 64 场景 / 192 张 PNG 与全部断言通过(0 横向溢出)。
+- **桌面开发版**(基点 `bdff0ea62183`):`go run ./tools/package -install` 将本机 TRACE Dev 从 `0.1.3-dev.202611210535` 静默升级至 `0.1.3-dev.202611210624`(`artifacts/package/install-dev.json`:`installed=true`、`relaunched=true`、`background=true`、`inJob=true`,2184 ms)。`trace-dev-setup-0.1.3-dev.202611210624-amd64.exe` SHA-256 `f26831005f121091dcc181c837fe5c350bf65f8f5e6aedf6c7d00a3c1cc789cf`(8.2 MiB);`trace.exe` SHA-256 `5bfdcc5faa66b4153489fb63690051b2a86daf7410719a741e4aa79ef83df43d`(25.4 MiB)。
+- **远程版**(基点 `bdff0ea62183`):`go run ./tools/package -server` 产出 `trace-server-0.1.3-dev.202611210624-linux-amd64.tar.gz` SHA-256 `44b698727ce7b17b02011e58a634f20be08fd270cd48b85481b026e512c930e8`(程序 16.3 MiB);`trace-server-0.1.3-dev.202611210624-linux-arm64.tar.gz` SHA-256 `36003c7544b00032e3db26829e1a5c846dc1a270d352c7ced49aad9a4ccffef3`(程序 15.2 MiB)。
+- **冒烟**:桌面冒烟 `go run ./tools/smoke -pkg dist/trace-dev -out artifacts/smoke` PASSED(3307 ms,`quietMode=hidden`,托盘专用工作集 `0.61 MiB`,`webview2=0`);远程冒烟 `go run ./tools/smoke -server` PASSED(1339 ms,`kill+restart`);Linux 真进程远程冒烟随 GitHub Actions CI 运行。
+- **仍为 `not-run`**:`go test -race`(本机无 CGO/gcc)、真实 VPS/站点/Google Drive 实机检查(H-003)及桌面实机体验(H-001/H-002)。
diff --git a/docs/delivery/status.md b/docs/delivery/status.md
index d05fa4a..8048506 100644
--- a/docs/delivery/status.md
+++ b/docs/delivery/status.md
@@ -1,17 +1,16 @@
# 交付状态
-更新:2026-11-19(2026-11-19 反馈 [DEC-061](../decisions.md#dec-061):A 实现缓存规则“全部缓存”(每 7 天按慢速缓存队列补齐账号的全部作品)、订阅账号的作品数与已缓存数、为某个账号缓存的合作视频在信息流和媒体库作者列表里算在这个账号下;M4 已经 PR #8 合并为 `main @ a613735`;合并后的实机反馈 [DEC-059](../decisions.md#dec-059):A 修了主页订阅信息流点头像闪退、录制异常重复显示、换段时在录制循环里转换导致丢片段,任务页加“检查计划”;第二次反馈 [DEC-060](../decisions.md#dec-060):合并视频的时长校验放宽到 2 秒或 3%,手动刷新与检查更新查到开播也开始录制,“检查计划”可手动检查全部或单个账号,抖音开播检查改为按间隔限速、不占每小时额度并在软件中说明规则;在本地分支 `codex/m4-feedback-0118`)。此前:2026-11-17(A 审查第四轮 B 的实现并自审第五轮,修复 3 个 P2,新增加入订阅对话框 DEC-058;第五轮反馈:A 实现 DEC-056 转发与合作视频的存放位置、DEC-057 任务页删除与缓存队列卡片、图标栏、主页头像打开订阅、切换站点更快、全部账号、抖音私密账号;第四轮反馈:A 修直播录制收尾与序号重置,B 完成主页调整 DEC-053(回到上次阅读位置、侧栏订阅未读圆点);此前 M4 实机反馈第一轮及补充:A 修复 7 项,B 完成 DEC-049 ①~③ 与 DEC-050 ①② 共 5 项实现,A 集中审查收敛;第二轮反馈 8 条 DEC-051:A 处理 4 项,B 完成 U1/L1/S1/S2/D2 共 4 项功能调整与正本文档同步,A 集中审查收敛)。本页只写已实现的能力、当前阶段、已知限制、LOOP 和开发与上游事项,不按轮次追加。
+更新:2026-11-21(M5 远程版、上传与导入导出及全仓库代码审查、重构与依赖更新在分支 `codex/m5-remote` 全部收敛并通过门禁、截图与双冒烟,待推送并经 CI 合并至 `main`;M4 及合并后的三轮实机反馈已合并为 `main @ 8327803`)。本页只写已实现的能力、当前阶段、已知限制、LOOP 和开发与上游事项,不按轮次追加。
## 当前阶段
-**M4(我的:登录账号的站点内容)**([当前计划 TRACE-M4-01](stage-plan.md),DEC-047):分支 `codex/m4-account`,基点 `main @ f080483`。
+**M5(远程版、上传与导入导出)**([当前计划 TRACE-M5-01](stage-plan.md),DEC-062):分支 `codex/m5-remote`,基点 `main @ 8327803`。
-- **状态**:B 已于 2026-11-14 完成 C0、W1~W6 与必测用例 M4-K01~K15;A 同日集中审查,直接修了 2 个 P2(F-001、F-002),审查收敛([阶段报告 §6](stage-report.md#a-review))。用户随后给了第一轮实机反馈(8 条)与 2026-11-15 补充(4 条):A 直接修了 7 项(缓存规则缩起闪退、直播录像转换失败、抖音订阅头像重启后丢失、实况照片翻到即播、抖音“喜欢”空响应连带“收藏”失败、托盘原生两项菜单、抖音用户页卡顿,F-003~F-009,[阶段报告 §7](stage-report.md#feedback-1));**B 已于 2026-11-15 完成交给 B 的 5 项功能调整**(解析页侧栏“最近解析”与居中大输入框、媒体库固定发布时间排序与纯离线详情、任务角标只数下载任务及任务页侧栏与直播录制实时预览、用户页“全部缓存”慢速不规律队列,DEC-049 ①~③、DEC-050 ①②,M4-K16~K31 全部通过,[阶段报告 §8](stage-report.md#b-feedback-1)),A 同日集中审查,直接修了 2 个 P2(F-010 缓存队列失败条目不等待、F-011 窄窗解析页找不到最近解析),审查收敛([阶段报告 §9](stage-report.md#a-review-feedback-1))。用户随后给了第二轮实机反馈 8 条([DEC-051](../decisions.md#dec-051)):A 直接处理了 4 项(删除后清掉空的作者文件夹、订阅图标橙点的说明、订阅头像两站点存本机、更新开发版时关闭并重开),并检查本机日志修了下载进度刷屏与闪退不留记录(F-012~F-015,[阶段报告 §10](stage-report.md#feedback-2));**B 已于 2026-11-15 完成交给 B 的 4 项功能调整与正本文档同步**(U1 设置“更新”页与 `update-history.json`、L1 不限同时录制数与“录制异常” `live.incidents`、S1 订阅详情“内容 / 账号”标签、S2 缓存规则批量选择订阅 `SetSubscriptionsRule`、D2 正本文档同步,M4-K32~K38,[计划 §13](stage-plan.md#feedback-2),默认值 [Q-018](../../USER-ACTIONS.md#q-018),[阶段报告 §11](stage-report.md#b-feedback-2)),A 同日集中审查,直接修了 1 个 P2(F-016 开发版“设置 › 更新”仅在卸载项版本高于运行版本时提示重启生效,并将预发布数字段比较升为 64 位整数),审查收敛([阶段报告 §12](stage-report.md#a-review-feedback-2))。用户 2026-11-16 第四轮反馈:A 修了哔哩哔哩直播录制的两个缺陷(收尾转换误把 HLS `EXTINF` 之和当时长基准,导致长分段都停在 `.part`;重新推流后的新序号被记成上亿段“分片丢失”),本机两场录像已在启动恢复时转换完成;没有直播间的 UP 主空间页提示“解析接口数据字段失败”(直播状态接口返回空数组),已修复,界面显示的错误也会写进运行日志;缓存规则的“默认”改为内置、全关、不可修改,新订阅都用它([DEC-054](../decisions.md#dec-054));媒体库加“刷新”,弹窗列出在资源管理器里删掉的文件([DEC-055](../decisions.md#dec-055));主页“回到上次阅读的位置”和侧栏订阅列表加未读圆点记为 [DEC-053](../decisions.md#dec-053),**B 已于 2026-11-16 完成**(H1 各站点筛选的阅读位置 `homePositions`、H2 侧栏订阅列表与窄窗头像条、D3 文档,M4-K39~K43 全部通过,[计划 §14](stage-plan.md#feedback-4),按用户对 [Q-019](../../USER-ACTIONS.md#q-019) 的答复:站点筛选分别记位置,侧栏不加分节标题、正在直播的排最前,[阶段报告 §15](stage-report.md#b-feedback-4)),待 A 审查;抖音“分段异常”在本机数据里找不到,用户答复下次出现再反馈([阶段报告 §14](stage-report.md#feedback-4))。第五轮反馈(7 条与 3 条补充)A 已实现:[DEC-056](../decisions.md#dec-056)(转发存到转发者的 `forwards/`、媒体库“转发”筛选,合作视频存到为之缓存的成员下)与 [DEC-057](../decisions.md#dec-057)(任务里的记录都能删除、缓存队列改为卡片并显示封面、图标栏上移、主页头像打开订阅、切换站点筛选从 2.4~3.5 秒降到首次约 0.7 秒与切回 10 ms 左右、订阅“全部账号”、抖音私密账号照常请求作品),[阶段报告 §16](stage-report.md#feedback-5);抖音私密账号用户已实机确认可以列出作品。2026-11-17 A 审查第四轮 B 的实现并自审第五轮,修复 3 个 P2(界面写 `ui-state.json` 会覆盖更新器的写入、私密账号把风控与限流显示成看不到、切换速度测试按耗时判断),按用户要求新增“加入订阅”对话框([DEC-058](../decisions.md#dec-058)),审查收敛([阶段报告 §17](stage-report.md#a-review-feedback-4-5))。本机 TRACE Dev 已更新至 `0.1.2-dev.202611161744`;推送与合并([ACT-021](../../USER-ACTIONS.md#act-021))用户 2026-11-17 已授权:审查收敛后推送、创建 PR,CI 通过后合并。实现细节按 [Q-015](../../USER-ACTIONS.md#q-015)、[Q-016](../../USER-ACTIONS.md#q-016)、[Q-017](../../USER-ACTIONS.md#q-017)、[Q-018](../../USER-ACTIONS.md#q-018) 的默认值。
-- 需求 FR-ACCT-001~005([需求 §2.9](../requirements.md#account-scope))已实现;验收 AC-45~53 自动化与截图通过。[ACT-020](../../USER-ACTIONS.md#act-020) 跑了 1 次:哔哩哔哩四项与抖音关注真实通过;抖音“喜欢”停下。同日按用户反馈复查 1 次:抖音“收藏”真实通过(18 条),“喜欢”对非浏览器请求固定回 0 字节,现在如实提示且不再打开抖音退避;收藏夹没有真实证据,“观看历史”不显示(LOOP-014)。
+- **状态**:M5 全部范围(C0、D1、W1~W9、M5-K01~K24)、2026-11-20 实机反馈修复(DEC-063)及 2026-11-21 全仓库代码审查、缺陷修复、质量重构、依赖更新(`mp4ff` v0.63.0、PR #9 并入)、无用代码/文档清理、开发版下载/归属/任务卡片修复及订阅“内容”里删除已缓存条目(DEC-064)均已收敛,门禁、截图、桌面与远程冒烟、`-server` 打包全部通过([阶段报告](stage-report.md#full-audit-20261121)),本机开发版已更新到 `0.1.3-dev.202611210644`。需求 FR-REMOTE-001~008([需求 §2.10](../requirements.md#remote-scope))已实现;AC-56~64 自动化通过,其中真实 VPS、真实站点 Cookie 与 Google Drive 的部分仍是 `not-run`,等用户做 [H-003](../../USER-ACTIONS.md#h-003)。设计正本是[远程设计](../design/remote.md),默认值见 [Q-022](../../USER-ACTIONS.md#q-022)。
## 上一阶段
-**M3(抖音视频与直播)**:经 PR #7 squash 合并为 `main @ f080483`([M3 计划](https://github.com/chialecode/trace/blob/f080483/docs/delivery/stage-plan.md)、[M3 报告](https://github.com/chialecode/trace/blob/f080483/docs/delivery/stage-report.md),含第六轮实机反馈 DEC-046 与 A 的两次集中审查)。真实站点:ACT-010~ACT-012、ACT-014~ACT-019 各按授权运行(抖音登录对照、纯 Go 签名、置顶翻页、图文、点播下载、直播 FLV 短录、原画优先缓存、哔哩哔哩实况)。M2(安装与更新)合并为 `main @ c17bd87`,第一个正式版 [v0.1.1](https://github.com/chialecode/trace/releases/tag/v0.1.1) 于 2026-11-12 发布。实机体验 [H-001](../../USER-ACTIONS.md#h-001) 与安装更新检查 [H-002](../../USER-ACTIONS.md#h-002) 仍为 `not-run`,产品验收未开始。
+**M4(我的:登录账号的站点内容)**:经 PR #8 squash 合并为 `main @ a613735`,合并后的三轮实机反馈(DEC-059~061)经 PR #10 合并为 `main @ 8327803`([M4 计划](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-plan.md)、[M4 报告](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-report.md),含五轮实机反馈与 A 的各次集中审查)。需求 FR-ACCT-001~005 已实现,AC-45~53 自动化与截图通过;[ACT-020](../../USER-ACTIONS.md#act-020) 真实检查了哔哩哔哩四项与抖音关注、收藏,抖音“喜欢”对非浏览器请求固定回 0 字节,现在如实提示(LOOP-014)。实机检查 H-001 第 28~36 步仍是 not-run。上上阶段 M3 经 PR #7 合并为 `main @ f080483`([M3 计划](https://github.com/chialecode/trace/blob/f080483/docs/delivery/stage-plan.md)、[M3 报告](https://github.com/chialecode/trace/blob/f080483/docs/delivery/stage-report.md))。
## 已实现能力
@@ -32,6 +31,8 @@
- **我的:登录账号的站点内容(FR-ACCT-001~005)**:图标栏第三项“我的”,侧栏“哔哩哔哩”“抖音”两组默认折叠、手风琴展开,窄窗在页面里选择;`AccountService`(`AccountSections`/`AccountFolders`/`AccountPage`)在发请求前检查登录、功能与站点熔断,风控与限流记入该站点的自动停止,列表只在内存里、日志只记功能名、页数与条数;哔哩哔哩关注(分组)、收藏夹(`list-all` + `resource/list`)、稍后再看(WBI,“全部 / 未看完”)、历史记录(游标三元组、按日分组);抖音关注(`max_time`)、喜欢、收藏(`listcollection` 表单 POST 体参与 `a_bogus`,收藏夹 `collects_id_str`),第 1 页空壳判“登录已失效或被拦截”;条目经 `OpenLink` 打开详情,“⋯”提供缓存、复制链接、在浏览器中打开、加入订阅;全部只读。
+- **远程版、上传与导入导出(FR-REMOTE-001~008、DEC-062)**:无界面的 `cmd/trace-server`(`linux/amd64`、`linux/arm64`,`CGO_ENABLED=0`,不链接 MyGo、界面、播放器与外壳)有 `init`、`run`、`token`、`upload-test`、`rclone-filter`、`version`;`go run ./tools/package -server` 打成带 systemd 示例与中文部署说明的 tar.gz。HTTPS(TLS 1.3、自签名证书按连接码里的指纹固定)+ 只存哈希的令牌,同一地址 1 分钟失败 5 次封 10 分钟,请求体上限 1 MiB,协议不同 409。远程用服务层的远程配置运行:不续期、不做全部缓存与补更早内容,Cookie 推送先校验再保存(Linux 上用数据目录里的随机密钥 AES-GCM 加密)。订阅快照整体替换并保留账号起点;内置上传逐条目调用 rclone,先传媒体文件、最后传 `item.json`,确认后只删刚上传的登记文件,失败按 1/5/15/60 分钟退避并分类说明。所有写了一半的文件都是 `*.part` 或 `.trace-*`(含 DASH 分轨)。本地“设置 › 远程”连接、查看状态、同步订阅与 Cookie,本地续期或重新登录后自动推送,推送不了标“Cookie 待同步”并重试。媒体库“⋯ → 导入…”只读扫描后按六类预览、冲突逐条或批量选保留本地 / 用导入的 / 合并,复制先写 `.part` 校验再改名、可中断续做、默认不动来源;“⋯ → 导出…”按全部或当前筛选导出可再导入的文件夹;两台机器各录一部分的直播合并后段号连续;进度在任务页“导入导出”。订阅页可导出、导入 `trace-subscriptions.json`(不含 Cookie),导入先预览。条目清单新增可选的 `cachedBy`,数据结构版本仍是 2。
+
安装与更新:实现、自动化测试与 ptest 演练通过,v0.1.1 已发布,实机未验收(H-002):
- **版本号与设置“更新”页(FR-UPD-001、DEC-051 ①)**:正式版 `0.1.x`(还没有发布时从 `0.1.1` 开始),开发版 `<下一个正式版>-dev.`;版本、通道、提交与构建时间注入程序,“设置 › 更新”(位于“关于”之前,“关于”页指向“更新”)、诊断、日志、文件属性、安装包名、卸载项与 `VERSION.txt` 一致([工程规则 §2.1](../dev-rules/engineering.md#versions))。
@@ -41,7 +42,7 @@
- **发布(AC-31、AC-33)**:`go run ./tools/release` 检查、签名构建、ptest 升级演练后放进 `dist/trace/`,只有授权后才发布;`.github/workflows/release.yml` 每周检查、构建、演练,发布受仓库变量控制([工程规则 §2.3、§4.2](../dev-rules/engineering.md#release))。
- **安装体验(FR-STORE-001)**:两个通道各自的图标、中文安装界面、发布者 `chialecode` 与版权,安装包名带版本。
-已知限制:没有可用 GPU 的电脑走软件解码,界面不会卡死,但高分辨率 60 fps 视频可能掉帧;本机没有 cgo 工具链,`go test -race` 无法运行(记为 `not-run`);大于 2 GiB 的 `co64` 大文件门控默认未执行;抖音直播仅提供 HLS(MPEG-TS)或为纯音频电台模式时不录制并说明原因(见 LOOP-008、LOOP-009);抖音真实直播的 HEVC(`CodecID=12`/`hvc1`)流没在真实站点见到,只由合成测试覆盖(ACT-014 的直播间只给 AVC)。
+已知限制:没有可用 GPU 的电脑走软件解码,界面不会卡死,但高分辨率 60 fps 视频可能掉帧;本机没有 cgo 工具链,`go test -race` 无法运行(记为 `not-run`);大于 2 GiB 的 `co64` 大文件门控默认未执行;抖音直播仅提供 HLS(MPEG-TS)或为纯音频电台模式时不录制并说明原因(见 LOOP-008、LOOP-009);抖音真实直播的 HEVC(`CodecID=12`/`hvc1`)流没在真实站点见到,只由合成测试覆盖(ACT-014 的直播间只给 AVC);远程版只经本机、WSL Ubuntu 与假站点、假 rclone 验证,真实 VPS、真实 Cookie 推送与 Google Drive 是 `not-run`(H-003);本地一次只连一个远程;导入、导出与订阅文件的路径直接输入,没有系统的文件夹选择框;Windows 上的远程冒烟不能发控制台信号,改为结束进程后再启动(`SIGTERM` 收尾在 Linux 上验证)。
## 后续 LOOP(Agent 侧)
@@ -52,27 +53,27 @@
| LOOP-002 | 在线播放(不缓存直接播放:Referer 代理、流式解码) | M1 已实现 FR-LIB-002 的本机播放(抖音图文配乐与混排视频页支持在线预览暂存),完整 FR-PLAY-001 在线播放仍在后续范围 |
| LOOP-003 | 任务详情显示每个文件的进度 | 已实现(FR-CACHE-009) |
| LOOP-004 | 直播录制的 HTTP-FLV 后备(FLV 标签解析、时间戳修正、转 MP4) | 已实现(FR-DY-009、FR-LIVE-004,[直播设计 §2.1](../design/live.md#flv)) |
-| LOOP-005 | 远程服务器(VPS)无头录制模式与轻量 Web 配置界面 | 通过 `INV-05` 与 `service.Backend` 接口保持后端与 `mygo/ui` 解耦([架构设计 §9](../design/architecture.md#headless-ext));需要时直接为 `internal/service` 增加轻量 `net/http` JSON/Web 控制台或 `mygo/ui` WASM 前端 |
+| LOOP-005 | 远程版的网页配置界面 | 无头远程版已实现(FR-REMOTE-001~008,[远程设计](../design/remote.md)),由本地“设置 › 远程”管理;以后需要网页时,在 `internal/remoteserver` 的 HTTPS 接口上加轻量网页或 `mygo/ui` WASM 前端([架构设计 §9](../design/architecture.md#headless-ext)) |
| LOOP-006 | 更新的深化:差分更新的体积、更新说明的排版、Windows 代码签名、winget / Microsoft Store、测试版通道、更新失败时的回退帮助 | 安装与更新已贯通完整流程([M2 计划 §7](https://github.com/chialecode/trace/blob/15e229c/docs/delivery/stage-plan.md));按反馈再排 |
-| LOOP-007 | 代码注释里残留的旧计划与问题编号(如“R8”“F-043”“C22”) | 文档、测试名及 M3 改动的全部 Go 文件已清理为直接描述;未触及的文件在后续改到时顺手清理 |
+| LOOP-007 | 代码注释里残留的旧计划与问题编号(如“R8”“F-043”“C22”) | 已在全仓库代码审查与重构中全部清理为直接描述 |
| LOOP-008 | 抖音直播的 HLS-TS 后备(MPEG-TS 解复用,候选 `github.com/bluenviron/mediacommon/v2`) | 当前只录 HTTP-FLV;直播间只有 HLS 时录制失败并说明原因。真实检查或用户反馈出现这种直播间时再做([选型 §4](../research/2026-11-12-douyin.md#a-review)) |
| LOOP-009 | 纯音频(语音电台)直播录制 | 当前识别语音直播并明确提示暂不支持录制;后续需要时为纯 AAC 直播流补单音频轨 `.m4a` 收尾与播放 |
-| LOOP-010 | 抖音扫码登录与关注列表批量导入 | 当前按 DEC-043 提供粘贴 Cookie 登录;M4 的“我的 › 抖音 › 关注”可以逐个浏览并加入订阅(FR-ACCT-005),像哔哩哔哩那样按分组批量导入仍在后续;扫码按 FR-AUTH-006 单独研究协议与风控成本 |
+| LOOP-010 | 抖音扫码登录与关注列表批量导入 | 当前按 DEC-043 提供粘贴 Cookie 登录;“我的 › 抖音 › 关注”可以逐个浏览并加入订阅(FR-ACCT-005),像哔哩哔哩那样按分组批量导入仍在后续;扫码按 FR-AUTH-006 单独研究协议与风控成本 |
| LOOP-011 | 抖音缓存作者目录可读命名与订阅网格主动查询开播状态 | 当前作者目录采用 `sec_uid` 的 SHA-256 前 12 位防止改名冲突,订阅网格复用最近一次开播结果避免逐人高频请求(Q-014 第 5 条);按实机体验反馈评估 |
| LOOP-012 | 清零 `download`、`live`、`subscription`、`library` 对 `site/bilibili` 的历史直接引用 | `tools/check` 已锁定现有引用者名单、抖音实现全程经 `internal/site` 接口零耦合;后续可平滑收敛旧哔哩哔哩调用点 |
| LOOP-013 | 抖音直播 FLV 的 CDN 302 跳转修复后的真实录制 | ACT-012 确认 FLV 第一跳 `302` 到白名单外的 HTTPS 443 域名,A 已改为“第一跳查白名单、之后只允许 HTTPS 443 公共域名”([直播设计](../design/live.md)读流一节)。已解决:[ACT-014](../../USER-ACTIONS.md#act-014) 真实录制通过(AVC 720p,21.56 秒)。以后如果跳转目标变成 IP 或非 443 端口,录制会报“已拦截”,再按日志评估是否放开 |
| LOOP-014 | 抖音“我的”的真实验证与“观看历史” | ACT-020 与 2026-11-14 的复查([抖音协议 §12](../research/douyin.md#account-lists)):关注、全部收藏真实通过;“喜欢”对非浏览器请求固定回 HTTP 200、0 字节(加网页参数和 `DOWNGRADE` 头都一样),现在提示“只给浏览器里的抖音网页”,不打开退避;要拿到需要浏览器通道(Q-016 第 1 条)。收藏夹(`collects/list`、`collects/video/list`)与 `history/read` 还没有真实证据,观看历史入口按 Q-015 第 3 条隐藏(`douyin.WatchHistoryEnabled=false`);最后一页是否会给 `aweme_list: null` 仍待确认(现在任何一页都按空壳处理) |
-| LOOP-015 | 冒烟偶发“抢焦点” | 2026-11-15 托盘改为原生菜单(F-008)后的开发版 `0.1.2-dev.202611150223` 在 17 次冒烟中有 2 次在 `tray` 与 `restored` 快照报 `StealFocusDetected = true`。B 对同一开发包又连跑 15 次、新开发包连跑 10 次,**都没有复现**,所以根因没有确认。B 做了不放宽检查的加固:安静模式不挂托盘的单击与右键回调、不切全屏(`TestQuietModeSuppressesTrayClickAndMenu`),`reuse_window` 与 `second_instance` 也核对焦点,并新增 `StealFocusDetail`(阶段名、窗口类名与可见性,不含标题)。冒烟中没有人点托盘,所以“托盘回调抢焦点”只是可能的原因之一。下次再出现时按 `StealFocusDetail` 定位具体窗口([阶段报告 §8、§9](stage-report.md#b-feedback-1)) |
-| LOOP-016 | 一个站点登录失效时,另一个站点的缓存队列也停下 | `TriggerAuthExpired` 调用 `PauseAllActiveWork`。对仍登录的站点,缓存队列按 `app_closed` 暂停,显示“已暂停(应用关闭)”,本次运行内不会自动继续(重启后或点“继续”恢复);下载任务按原有逻辑全部 `auth_required` 暂停。影响小(需要先有一个站点登录失效),按反馈再改成只暂停失效的站点(A 审查 2026-11-15,[阶段报告 §9](stage-report.md#a-review-feedback-1)) |
+| LOOP-015 | 冒烟偶发“抢焦点” | 2026-11-15 托盘改为原生菜单(F-008)后的开发版 `0.1.2-dev.202611150223` 在 17 次冒烟中有 2 次在 `tray` 与 `restored` 快照报 `StealFocusDetected = true`。B 对同一开发包又连跑 15 次、新开发包连跑 10 次,**都没有复现**,所以根因没有确认。B 做了不放宽检查的加固:安静模式不挂托盘的单击与右键回调、不切全屏(`TestQuietModeSuppressesTrayClickAndMenu`),`reuse_window` 与 `second_instance` 也核对焦点,并新增 `StealFocusDetail`(阶段名、窗口类名与可见性,不含标题)。冒烟中没有人点托盘,所以“托盘回调抢焦点”只是可能的原因之一。下次再出现时按 `StealFocusDetail` 定位具体窗口([阶段报告 §8、§9](https://github.com/chialecode/trace/blob/8327803/docs/delivery/stage-report.md#b-feedback-1)) |
+| LOOP-016 | 一个站点登录失效时,另一个站点的缓存队列也停下 | 已解决:`PauseAllActiveWork` 现按站点检查活跃凭证,只暂停未登录或已失效的站点,不再暂停仍登录站点的缓存队列、下载任务或直播录制 |
## 开发与上游事项
| 编号 | 内容 | 状态 |
| --- | --- | --- |
-| OSS-001 | MyGo 持续高频迭代(当前 `v0.8.3`) | 按 DEC-032 不保留旧版兼容包袱,持续同步 MyGo 最新版;后端核心包不依赖 MyGo(INV-05),只有 `main.go`、`internal/shell`、`internal/ui`、`internal/player`、`internal/locales`、`tools/uishots` 引用 MyGo。MyGo 的更新签名只覆盖更新包内容、不含版本号,TRACE 在清单里加了版本证明;MyGo 的更新不改卸载项的版本,TRACE 在更新后第一次启动时改;MyGo 自己的“应用正在运行”安装提示仍是英文 |
+| OSS-001 | MyGo 持续高频迭代(当前 `v0.9.0`) | 按 DEC-032 不保留旧版兼容包袱,持续同步 MyGo 最新版;后端核心包不依赖 MyGo(INV-05),只有 `main.go`、`internal/shell`、`internal/ui`、`internal/player`、`internal/locales`、`tools/uishots` 引用 MyGo。MyGo 的更新签名只覆盖更新包内容、不含版本号,TRACE 在清单里加了版本证明;MyGo 的更新不改卸载项的版本,TRACE 在更新后第一次启动时改;MyGo 自己的“应用正在运行”安装提示仍是英文 |
| OSS-002 | Windows Media Foundation(`IMFSourceReader`)纯 Go COM 调用与 `mygo/audio` 音画同步 | 合成 AVC/AAC 与纯音频(WAV/AAC)读取、Seek 与静音测试通过;真实音频设备体验留 H-001 |
-| OSS-003 | `mp4ff` v0.62.0 渐进式 MP4(1 秒交错 + `elst`)、单文件 MP4 流式 `moov` 前置重排及最高音轨后备 | 小样本合并/轨道/时长、尾置 `moov` 磁盘流式前置重排(含 32 位偏移升级 `co64` 合成测试)与失败保留旧文件回归通过;最高 FLAC/杜比另存,主 MP4 用 AAC;真实 FLAC-in-MP4 解码未验证([媒体选型](../research/2026-11-05-media.md#hires-audio)) |
+| OSS-003 | `mp4ff` v0.63.0 渐进式 MP4(1 秒交错 + `elst`)、单文件 MP4 流式 `moov` 前置重排及最高音轨后备 | 小样本合并/轨道/时长、尾置 `moov` 磁盘流式前置重排(含 32 位偏移升级 `co64` 合成测试)与失败保留旧文件回归通过;最高 FLAC/杜比另存,主 MP4 用 AAC;真实 FLAC-in-MP4 解码未验证([媒体选型](../research/2026-11-05-media.md#hires-audio)) |
| OSS-004 | 纯 Go 弹幕排版器与 WebVTT 字幕在 `mygo/ui` 中的叠加性能 | 测试验证:10,000 条弹幕在时间窗二分查找 + 轨道防重叠下单帧耗时远低于 `1 ms` 目标,Seek 无残留 |
| OSS-005 | 直播录像用 `mp4ff` `Defragment` 把 fMP4(含 HLS fMP4 与 HTTP-FLV 按 GOP 重封装的 fMP4)转普通 MP4 | 默认小样本(AVC、`CodecID=12` HEVC、Enhanced FLV `hvc1` + AAC)转换与登记恢复通过;大于 2 GiB 与稀疏 `co64` 门控未执行,不能记为已验证 |
| OSS-006 | `mygo/ui` 窗口关闭到托盘销毁窗口、释放纹理并在同一进程内反复重建 | 托盘测试与最新 `tools/smoke` 通过;真实隐藏窗口、单实例与隔离数据锁/路径检查通过;内存数值见[M3 报告](https://github.com/chialecode/trace/blob/f080483/docs/delivery/stage-report.md)及 `artifacts/smoke/smoke.json` |
diff --git a/docs/design/architecture.md b/docs/design/architecture.md
index c079b12..bd8fea3 100644
--- a/docs/design/architecture.md
+++ b/docs/design/architecture.md
@@ -1,6 +1,6 @@
# 技术设计:架构、接口与原生界面
-技术设计说明系统“应当怎样工作”,按专题分四份:本页(进程与分层、代码目录、服务接口、站点客户端、凭证、原生界面、不变量、窗口与托盘、远程无头扩展边界)、[数据、缓存与信息流](data-and-cache.md)、[订阅、检查更新与自动缓存](subscriptions.md)、[直播](live.md)。与代码不一致时按[冲突规则](../dev-rules/workflow.md#conflicts)处理。选型依据见[技术选型研究](../research/2026-11-05-stack.md)和[媒体与存储选型](../research/2026-11-05-media.md),协议见[哔哩哔哩协议资料](../research/bilibili.md)。
+技术设计说明系统“应当怎样工作”,按专题分五份:本页(进程与分层、代码目录、服务接口、站点客户端、凭证、原生界面、不变量、窗口与托盘、远程版的分层)、[数据、缓存与信息流](data-and-cache.md)、[订阅、检查更新与自动缓存](subscriptions.md)、[直播](live.md)、[远程版、上传与导入导出](remote.md)。与代码不一致时按[冲突规则](../dev-rules/workflow.md#conflicts)处理。选型依据见[技术选型研究](../research/2026-11-05-stack.md)和[媒体与存储选型](../research/2026-11-05-media.md),协议见[哔哩哔哩协议资料](../research/bilibili.md)。
## 1. 进程与分层
@@ -28,6 +28,7 @@ internal/ui(mygo/ui 声明式视图、路由、看图层、播放层) ──
```text
main.go 组装依赖、获取单实例与数据目录锁、启动服务与原生窗口
+cmd/trace-server/ 无界面的远程程序(Linux):init、run、token、upload-test 等命令;deploy/ 放 systemd 示例与中文部署说明
mygo.json MyGo 打包配置:正式版身份、版本线 0.1.0、图标、发布者与版权、中文目录(i18n)、更新公钥与 GitHub 仓库;
打包工具按通道临时改写(开发版 trace-dev、ptest 演练 trace-ptest)
CHANGELOG.md 正式版每个版本的更新内容(Release 说明与“更新内容”)
@@ -38,7 +39,7 @@ internal/
update/ 更新逻辑(纯 Go,不依赖 MyGo):检查与下载的状态机(controller.go)、TRACE 的更新源与校验(source.go)、检查与更新记录(update-history.json)
locales/ 中文目录 zh-Hans.json 与 MyGo 生成的访问代码(安装界面与 MyGo 自带字符串)
ui/ mygo/ui 原生界面:图标栏 + 上下文侧栏 + 页面的自适应布局、路由、登录页、主页信息流、订阅(列表/详情/导入)、
- 我的、解析页、视频详情、用户页、媒体库(含 /library/item 离线详情)、任务页(四组侧栏、直播录制实时预览与录制异常)、设置页(含“更新”分类与规则批量选订阅)、看图层、播放层及界面内存测试(ui.NewTester)
+ 我的、解析页、视频详情、用户页、媒体库(含 /library/item 离线详情与导入页)、任务页(六组侧栏、直播录制实时预览与录制异常、导入导出)、设置页(含“远程”“更新”分类与规则批量选订阅)、看图层、播放层及界面内存测试(ui.NewTester)
player/ 原生媒体播放与叠加:Windows Media Foundation(IMFSourceReader 纯 Go COM 调用,含增长中 fMP4 .part 的只读实时预览)解码 MP4 音视频、
mygo/audio 音频时钟与输出、纯 Go 弹幕排版器(danmaku.go)与 WebVTT 字幕解析匹配(subtitle.go)
appdirs/ 构建信息(版本、通道、提交、构建时间,由 -ldflags 注入);通道(release / dev / ptest / source)与安装、数据、缓存位置的推算,“文档”文件夹的系统登记位置,数据目录独占锁
@@ -61,12 +62,16 @@ internal/
download/ 任务队列与状态机(按站点熔断)、分段下载器(8 MiB 续传、重试、节点轮换)、按站点的执行器与媒体传输规格、选流、合并(mp4ff)、
单文件 MP4 校验与 moov 前置、升级探测(只有哔哩哔哩)、弹幕与字幕保存
settings/、uistate/ 设置(settings.json);界面状态(ui-state.json,主页看过的最新一条、窗口尺寸、最后路由等)
- storage/ 数据目录、原子写、最近解析(history.json)、SQLite 打开与迁移、数据文件的结构版本(schema.go)
+ storage/ 数据目录、原子写、最近解析(history.json)、SQLite 打开与迁移、数据文件的结构版本(schema.go)、临时文件名约定(*.part、.trace-*)
+ remote/ 远程协议:连接码、状态与快照等 JSON 类型、按证书指纹固定的 HTTPS 客户端与错误分类(无法连接、证书变了、令牌错、版本不同、被拒)
+ remoteserver/ trace-server 的服务端:init 与配置(server.json、证书、令牌哈希)、HTTPS 接口与鉴权限流、磁盘空间、Run 的启动与收尾
+ upload/ 远程的内置上传:逐条目调用 rclone、确认后删登记文件、退避与错误分类;fakerclone/ 是测试与冒烟用的假 rclone
+ transfer/ 资源库导入(扫描分六类、校验后复制、合并清单)与导出(可携带的 item.json)
tools/check/ 质量门禁(一条命令)
tools/checkdocs/ 文档、公开内容与依赖方向检查
tools/uishots/ 用 ui.NewTester 渲染全部页面的必测状态与三档宽度,输出 PNG 截图与结构化断言回执 assertions.json
-tools/smoke/ 真实进程端到端冒烟(启动 trace.exe、单实例与数据目录锁、托盘关闭与重建、零杂散目录校验)
-tools/package/ 开发版打包(解包文件 + NSIS 按用户安装包)与本机自动安装(install.go)
+tools/smoke/ 真实进程端到端冒烟(启动 trace.exe、单实例与数据目录锁、托盘关闭与重建、零杂散目录校验);-server 是远程冒烟(server.go)
+tools/package/ 开发版打包(解包文件 + NSIS 按用户安装包)与本机自动安装(install.go);-server 打远程版的 Linux 包(server.go)
tools/release/ 正式版发布:检查、构建签名、ptest 升级演练、可选发布;release.yml 的静态检查
tools/actcheck/ 真实站点有界检查程序(act006 / act007 / act010 / act011,账本门禁与脱敏回执)
tools/icons/ 绘制两个通道的应用图标
@@ -233,11 +238,6 @@ tools/internal/build/ 打包共用:版本号、通道配置、-ldflags
- **数据结构版本**:启动时先核对数据文件的结构版本([数据 §1](data-and-cache.md#schema-versions));遇到比这个版本新的结构就显示“这些数据来自更新的 TRACE 版本,请安装新版”并退出,不写任何文件。
-## 9. 未来远程服务器(VPS)轻量模式与 Web 配置边界(DEC-032)
+## 9. 远程版(DEC-032、DEC-062)
-全项目改为纯 Go 后,架构通过以下约束保证未来可零成本提取出一个部署在 Linux/Windows VPS 上的无头直播录制与自动缓存程序(如 `cmd/trace-server` 或 `trace -headless`),并通过浏览器 Web 界面进行基础配置(添加/删除直播间与订阅、开关自动录制、扫码或粘贴 Cookie 登录、查看录制状态):
-
-1. **后端零 GUI 依赖(INV-05)**:`internal/service` 及所有下层包(`site/bilibili`、`subscription`、`live`、`download`、`library`、`credential`、`storage`、`settings`)全部是 `CGO_ENABLED=0` 的标准 Go 代码,不引用 `mygo` 或 Windows GUI 库(平台相关文件如 `dpapi_other.go`、`lock_other.go`、`disk_other.go` 提供 Linux/跨平台实现)。
-2. **`internal/service` 接口化**:桌面端的 `internal/ui` 只通过 `service.Backend` 接口调用业务方法。未来新增远程模式时,只需提供两种轻量 Web 入口之一(或同时提供),无需重写任何业务逻辑:
- - **路线 A(标准库 `net/http` JSON API + 内嵌单页 Web 控制台)**:用一个很薄的 `internal/webadmin` 包把 `service.Backend` 的方法(如 `AuthService`、`SubscriptionService`、`LiveService`、`SettingsService`)映射为带 Token 鉴权的 HTTP JSON 端点,并用 `embed.FS` 内嵌一个几十 KB 的静态配置页面,编译出约 10 MB 的单文件 Linux 静态二进制即可在 VPS 上通过浏览器添加直播间与管理录制。
- - **路线 B(`mygo/ui` 直接编译为浏览器 WebAssembly)**:MyGo 原生支持 `mygo build -platform web`(`GOOS=js GOARCH=wasm`),可将 `internal/ui` 编译为运行在浏览器 Canvas/WebGL2 中的前端,通过实现一个走 HTTP 的 `service.Backend` 客户端直接复用同一套 Go 界面。
+后端零 GUI 依赖(INV-05)让同一套 `internal/service` 能编译成无界面的远程程序 `cmd/trace-server`(Linux,`CGO_ENABLED=0`):它在服务层用远程配置启动(不续期、不做全部缓存与补更早内容、定时检查总开关常开),由 `internal/remoteserver` 把状态、订阅快照与凭证推送映射为 HTTPS JSON 接口;本地桌面版经 `internal/remote` 客户端连接。远程不提供网页(浏览器控制台与 `mygo/ui` WebAssembly 前端仍是以后的选项)。完整设计见[远程设计](remote.md)。
diff --git a/docs/design/data-and-cache.md b/docs/design/data-and-cache.md
index 3889a75..2f128bc 100644
--- a/docs/design/data-and-cache.md
+++ b/docs/design/data-and-cache.md
@@ -70,10 +70,11 @@
<保存位置>/douyin//lives//item.json、cover.jpg、part-001.mp4…
```
-“添加已有的缓存文件夹”同样扫描 `douyin/*/{works,lives}/*/item.json`。文件名只用 ID 和序号,标题写在清单里,避免非法字符和超长路径。视频条目放在 UP 主自己的目录下,被动态引用;投稿列表和视频页直接缓存的也是同一个视频条目。两种例外(DEC-056),都在清单里记 `via`:
+“添加已有的缓存文件夹”同样扫描 `douyin/*/{works,lives}/*/item.json`。文件名只用 ID 和序号,标题写在清单里,避免非法字符和超长路径。视频条目放在 UP 主自己的目录下,被动态引用;投稿列表和视频页直接缓存的也是同一个视频条目。三种例外(DEC-056、DEC-063),都在清单里记 `via`:
- **转发**:转发的动态存到转发者的 `forwards/`,转发里带的视频(原作者不是转发者)也存到转发者的 `forwards//`,不建原作者的文件夹,也不和转发者自己的 `dynamics/`、`videos/` 混在一起;`via = {reason: "forward", site, uid: 转发者, name, dynamicId}`。
- **合作视频**:为订阅、缓存队列或用户页里的某位成员缓存哔哩哔哩合作视频(视频详情 `staff` 里有这位成员、但他不是投稿人)时,存到这位成员的 `videos//`,`via = {reason: "collab", site, uid: 成员, name}`;没有成员上下文(直接解析视频链接)时仍存在投稿人的文件夹。从用户页点开视频、再在视频页缓存,也带着这个用户页的成员(DEC-061 ③)。为成员缓存的合作视频在信息流里按作者筛选时也算这位成员的(`feed_items.item_key` 属于 `via.reason = collab` 且 `via.uid` 是他的条目),媒体库作者列表(`Statistics`)把它列在这位成员下而不是投稿人下。
+- **抖音共创作品**(DEC-063 ①):从某个账号的作品列表缓存(订阅自动缓存、缓存队列与“全部缓存”、用户页作品的“缓存”)的作品,发布者不是这个账号时,存到这个账号的 `douyin/<短哈希>/works/<作品 ID>/`,`via = {reason: "collab", site: "douyin", uid: 这个账号的 sec_uid, name}`,作者仍记发布者;信息流筛选、媒体库作者列表与已缓存数和哔哩哔哩合作视频一样按 `via` 算在这个账号下。直接解析作品链接缓存的仍存在发布者的文件夹。缓存任务把 `via` 记在 `download_tasks.via_json`,任务暂停或重启后仍写进清单。
同一条目键只有一个文件夹:条目已经缓存过时沿用原来的文件夹,不搬动;想换位置就在媒体库删除后重新缓存。
@@ -88,6 +89,8 @@
可选的 `via`(DEC-056,见 2.1)说明条目为谁缓存、存在谁的文件夹:`reason`(`forward` 或 `collab`)、`site`、`uid`、`name`,转发另记 `dynamicId`;`author` 仍是原作者或投稿人。旧清单没有这个字段时照常读取,结构版本不变。媒体库把 `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))。
+
抖音条目的作者另记 `site`、`uid`(`sec_uid`)与抖音号;视频作品记实际与可选的档位(分辨率、编码、帧率、码率、档位名);图文记配乐(标题、作者、时长、文件)。直播录像条目([直播 §4](live.md#recording-item))的 `live` 对象另含可选字段 `live.incidents`(录制异常事件列表:`reconnect`、`lost_segments`、`slow`、`disk`、`convert_failed`,每场最多 200 条,DEC-051 ③;不改清单结构版本,无此字段的旧清单照常读取)。
只存公开内容;哔哩哔哩的图片原始 URL 可以存(公开 CDN,去掉尺寸后缀),**视频的签名播放地址与直播流地址不存**;抖音的图片与媒体地址都带签名与过期参数,**一律不存**。播放数、点赞数、评论数这类会变的互动数据不缓存(DEC-040)。
@@ -148,6 +151,7 @@
### 2.6 合并、校验与状态圆点
+- **中间流的文件名**:合并前的视频流与音频流写成 `.trace-Pxx.video-<清晰度代码>-<编码 ID>.m4s`、`.trace-Pxx.audio-<代码>.m4s`(下载中再加 `.part`),与其他临时文件一样以 `.trace-` 开头,所以上传与同步工具排除 `*.part`、`.trace-*` 就不会碰到它们([远程 §6.1](remote.md#export-format))。旧版本留下的 `Pxx.video-….m4s` 在续传前先改成新名字,合并成功后旧名字的登记也一起清掉。
- **合并**:用 mp4ff 把视频流和音频流合成一个 MP4(Q-003):`ftyp` + `moov` 在前、音视频约 1 秒一块交错写入、带编辑列表、各轨时长与源流一致(NFR-MEDIA-001)。合并成功后删掉中间流文件;合并失败时保留两个流文件,记为部分缓存“合并失败”。
- **单文件 MP4**(抖音视频、混排图文视频页、抖音与哔哩哔哩的实况片段;哔哩哔哩实况片段不核对预期时长,DEC-046 ①,[ACT-019](../../USER-ACTIONS.md#act-019) 实测站点给的是 `moov` 在前的 AVC MP4):不合并。下载完成后以懒加载模式核对顶层 box 总长与文件长度一致、非分片结构(不含 `moof`)、至少含一条有效非加密视频轨(有音频轨就一起核对,拒绝 `encv`/`enca`/`sinf` 等 CENC 加密样本项)、正时长且与站点给的预期时长误差不超过 2 秒或预期时长的 3%(取大的,DEC-060 ①;不要求 `elst` 编辑列表)。`moov` 已在 `mdat` 之前时直接计算 SHA-256 通过;`moov` 在 `mdat` 之后时用 mp4ff 在磁盘上把 `moov` 移到 `mdat` 之前(按文件区间流式顺序拷贝 `mdat` 载荷、不把整个文件读进内存,平移全部轨道的 `stco`/`co64` 块偏移并在超 32 位上限时自动升级为 `co64`,写同目录临时文件、`fsync` 后原子改名;改写失败清理临时文件、保留原文件不动并记为部分缓存)。图片按文件头与 `Content-Type` 决定扩展名,拒绝 HTML/JSON 伪装的响应。
- **校验**:文件长度与响应一致;合并后的 MP4 能被解析出视频轨(和音频轨),时长与站点给的误差不超过 2 秒或站点时长的 3%(取大的;转码后的流可能比站点标称短几秒,DEC-060 ①),失败原因写明缺轨、结构不对或时长相差多少;记录 SHA-256。全部通过后才把 `*.part` 改为正式名并写清单(INV-06)。
@@ -175,7 +179,7 @@
- 删动态条目删除它自己的文件;它引用的视频条目只在没有其他动态引用、也不是被直接缓存的情况下一起删除,否则保留并告知。
- **只删登记过的文件**:按清单删除媒体文件、`orig.json`、本条目的 `*.part` 临时文件,最后删除 `item.json`;然后自下而上只删除已经变空的文件夹(`images/`、条目文件夹),再向上删除因此变空的类型文件夹(`videos/`、`works/` 等)与作者文件夹(`/`、`/`);只在保存位置内向上,站点文件夹与保存位置本身不删,一律用只能删空文件夹的 `os.Remove`。文件夹里还有未登记的文件(例如用户自己放的)时保留文件夹,界面说明“文件夹里还有 N 个不是 TRACE 创建的文件,已保留”。任何情况下都不对条目文件夹做递归删除(INV-09)。
-- 确认弹窗先调 `PlanDelete(key)`:它与 `Delete` 用同一份删除计划,列出会删除的条目与登记文件、会保留的共用视频(“这个视频还被 N 条动态引用,将保留视频文件”),不改动任何东西。
+- 确认弹窗先调 `PlanDelete(key)`:它与 `Delete` 用同一份删除计划,列出会删除的条目与登记文件、会保留的共用视频(“这条动态引用的 N 个视频单独缓存过或还被别的动态引用,将保留”),不改动任何东西。
- 先改索引并写待清理记录,再删文件;删不掉的(被占用等)留在待清理里,下次启动再删,并跳过已经被重新缓存的条目。
- **改保存位置**:只影响之后的新任务;索引给每个条目记它的保存位置,旧条目照常浏览。
- **可选迁移旧文件**:无进行中/排队缓存任务与录制时才开始;已暂停 worker 完全退出后才能迁移,期间阻止新队列/worker 启动。只复制清单登记的文件,新位置有同名用户文件则停止。副本校验与根登记成功、设置原子落盘成功后才删除登记的原文件;此前失败回滚新副本与根,保留原文件,不搬动整个目录。
diff --git a/docs/design/live.md b/docs/design/live.md
index 5952e36..187bfbe 100644
--- a/docs/design/live.md
+++ b/docs/design/live.md
@@ -35,7 +35,7 @@
选型见[抖音签名与直播录制选型 §2~§4](../research/2026-11-12-douyin.md#live-route)。和 HLS 输入共用第 2 节的段文件、checkpoint、换段、收尾、关闭与空间规则,只有“取到样本”这一步不同:
1. **读流**:一条 HTTP 长连接顺序读取;连接超时 10 秒,15 秒读不到数据按断流处理。请求头按站点(抖音 `Referer`/`Origin: https://live.douyin.com`,哔哩哔哩同 HLS),不带 Cookie。哔哩哔哩每一跳都要在白名单内;抖音的首个拉流地址要在白名单内,之后的跳转会被 CDN 调度到白名单外的厂商域名(ACT-012 实测),所以只要求 HTTPS、443 端口、公共域名(拒绝 IP 字面量、单段与本地主机名、带账号的地址),最多 5 跳,拨号时仍拒绝解析到回环、内网或链路本地的地址。
-2. **解析**:9 字节文件头(跳过扩展头部字节并核对首个 `PreviousTagSize0`)+ 逐个 Tag(11 字节头、`PreviousTagSize == 11 + DataSize` 校验;Tag 边界正常 EOF 收尾已缓冲完整帧,半包截断或长度失配丢弃残尾并保留已落盘分片)。视频支持经典 AVC(`CodecID=7`)、国内常见的 HEVC `CodecID=12`(`0x1c`/`0x2c`)、Enhanced FLV(首字节最高位置位,FourCC `hvc1`/`avc1`,`PacketType=0` 参数集、`1` `CodedFrames` 带 3 字节有符号 `SI24` CTS、`3` `CodedFramesX` 隐式 `CTS=0`、`2` 结束包、`5` 元数据包跳过);音频只支持 AAC(`SoundFormat=10`)。参数集从 `avcC`/`hvcC`/`AudioSpecificConfig` 实解,不依赖 `onMetaData`;兼容 1/2/4 字节长度前缀并统一改写成 4 字节大端 NALU;交给 mp4ff 前校验 AVC 的 SPS/PPS 非空且 SPS 可解、HEVC 的 VPS/SPS/PPS 都非空且 SPS 可解。遇到不支持的编码或无视频的纯音频流结束录制并说明。
+2. **解析**:9 字节文件头(跳过扩展头部字节并核对首个 `PreviousTagSize0`)+ 逐个 Tag(11 字节头、`PreviousTagSize == 11 + DataSize` 校验;Tag 边界正常 EOF 收尾已缓冲完整帧,半包截断或长度失配丢弃残尾并保留已落盘分片)。视频支持经典 AVC(`CodecID=7`)、国内常见的 HEVC `CodecID=12`(`0x1c`/`0x2c`)、Enhanced FLV(首字节最高位置位,FourCC `hvc1`/`avc1`,`PacketType=0` 参数集、`1` `CodedFrames` 带 3 字节有符号 `SI24` CTS、`3` `CodedFramesX` 隐式 `CTS=0`、`2` 结束包、`4` 元数据包跳过);音频只支持 AAC(`SoundFormat=10`)。参数集从 `avcC`/`hvcC`/`AudioSpecificConfig` 实解,不依赖 `onMetaData`;兼容 1/2/4 字节长度前缀并统一改写成 4 字节大端 NALU;交给 mp4ff 前校验 AVC 的 SPS/PPS 非空且 SPS 可解、HEVC 的 VPS/SPS/PPS 都非空且 SPS 可解。遇到不支持的编码或无视频的纯音频流结束录制并说明。
3. **时间戳**:展开无符号 32 位回绕和有符号 31 位编码器溢出回绕;CTS 按有符号 24 位补码展开并折算到视频时间刻度;以首个媒体包为 0;同一轨 `[-1000ms, 0]` 的轻微抖动夹紧为单调递增;正向跳变超过 10 秒或倒退超过 1 秒换新段(第 2 节第 4 步)。视频时间刻度 90000,音频用采样率并通过 128 位乘除换算避免长时溢出。
4. **写入**:先等到第一个视频关键帧和有效参数集(单视频轨启动最多等 3 秒音频参数集与首帧,超时后先按单视频轨写初始化段;若后续音频到达则在下一个视频关键帧换新段),写 `ftyp+moov` 初始化段;之后每到下一个关键帧且距上次写入 ≥ 1 秒(或累积 ≥ 2 秒、≥ 4 MiB)写一个 `moof+mdat` 分片,`fsync` 后保存 checkpoint(记录字节偏移与精确累计时长),与第 2 节第 3 步同一协议,所以启动恢复与收尾不用新增分支。规范化后的参数集内容变化(忽略原样重发)时在关键帧换新段。
5. **断流**:读错误、EOF、403/404/410 时重新取流(抖音重新调用直播间接口,哔哩哔哩同第 2 节第 5 步),**不复用旧地址**;新的连接写新段。
diff --git a/docs/design/remote.md b/docs/design/remote.md
new file mode 100644
index 0000000..dfb4825
--- /dev/null
+++ b/docs/design/remote.md
@@ -0,0 +1,138 @@
+# 技术设计:远程版、上传与导入导出
+
+本页说明远程版(`trace-server`,部署在 Linux VPS 上)应当怎样工作,以及它和本地 TRACE 之间的订阅同步、Cookie 推送、上传和资源库导入导出([DEC-062](../decisions.md#dec-062),需求 [FR-REMOTE-001~008](../requirements.md#remote-scope))。进程分层与凭证见[架构](architecture.md),条目文件夹与 `item.json` 见[数据与缓存](data-and-cache.md),检查更新与规则见[订阅](subscriptions.md),录制见[直播](live.md)。与代码不一致时按[冲突规则](../dev-rules/workflow.md#conflicts)处理。
+
+
+## 1. 角色与数据流
+
+```text
+本地 TRACE(Windows 桌面) 远程 trace-server(Linux,无界面)
+ 订阅、规则、设置 ──HTTPS + 令牌 + 证书指纹──> 只按同步来的订阅检查更新、按规则缓存新内容与录制
+ Cookie(只由本地续期)──────────────────────> 凭证文件(本机密钥加密),从不续期
+ 设置 › 远程:查看状态 <─────────────────────── 状态(登录、检查、缓存、录制、上传、磁盘)
+ 导出目录(与媒体库同样的条目文件夹)
+ │ 内置上传:调用 rclone,按条目上传,成功后删本机文件
+ │ 或用户自己的定时 rclone(兼容)
+ ▼
+ 媒体库 › 导入 <── 用户从网盘下载的文件夹 ──────── 网盘(如 Google Drive)
+```
+
+- 远程只做四件事:按同步来的订阅检查更新、按订阅的缓存规则缓存新内容、按规则录制直播、把完成的文件上传。没有媒体库界面、解析、“我的”、全部缓存、补更早内容、播放和 Web 页面。
+- 本地和远程是同一版本(DEC-062 ②):协议与文件格式只认当前版本,版本不同就拒绝并提示更新,不做旧格式兼容。
+- 为以后的集群模式(多台机器订阅同一批账号、汇成一个资源库)预留:每个安装有节点 ID;条目按条目键合并;导入不关心条目来自哪台机器(第 6 节)。
+
+
+## 2. 程序与部署
+
+- **独立程序**:`cmd/trace-server`,只链接 `internal/service` 及下层包与 `internal/remote*`,不链接 MyGo、`internal/ui`、`internal/player`、`internal/shell`(`tools/check` 检查 `go list -deps ./cmd/trace-server`)。`CGO_ENABLED=0` 静态编译,发行 `linux/amd64` 与 `linux/arm64`;Debian 12、Ubuntu 22.04 及以上不需要额外运行库。上传需要机器上有 `rclone`(TRACE 不打包它)。
+- **命令**:
+ - `trace-server init --data <数据目录> --export <导出目录> [--listen :47380] [--public-address <地址[:端口]>] [--name <名字>]`:建目录(`0700`)、节点 ID、自签名证书、访问令牌与凭证密钥,打印一次**连接码**(地址、令牌、证书 SHA-256 指纹)和推荐的 rclone 过滤规则;令牌只存哈希,之后不能再查看。连接码里的地址取 `--public-address`,不填时取本机第一个非回环地址(VPS 在 NAT 后面时要填公网地址)。
+ - `trace-server run --data <数据目录>`:前台运行(交给 systemd 管理);`SIGTERM` 按托盘“退出”的同一路径收尾(任务暂停、录制收尾,限时 30 秒)。
+ - `trace-server token --data <数据目录>`:换新令牌并打印新的连接码,旧令牌立即失效。
+ - `trace-server upload-test --data <数据目录>`:用当前上传设置传一个小测试文件再删掉,检查 rclone 与网盘配置。
+ - `trace-server version`、`trace-server rclone-filter`。
+- **文件**:数据目录放 `server.json`(监听地址、导出目录、节点 ID 与名字、令牌哈希、上传设置)、`tls/`(证书与私钥 `0600`)、`credentials/`(凭证与密钥 `0600`)、`library.db`、`updates.db`、`subscriptions.json`、`settings.json`、`logs/`;数据目录独占锁同桌面版(INV-14)。导出目录就是远程的缓存保存位置,布局与本地媒体库相同([数据 §1](data-and-cache.md#storage))。
+- **发行包**:`go run ./tools/package -server` 交叉编译两个架构,输出 `dist/trace-server/` 下每个架构一个 `trace-server-<版本>-linux-<架构>.tar.gz` 与 `SHA256SUMS`(只留最新一份)。包内一个顶层文件夹,含 `trace-server`、`trace-server.service`、`README.md`、`THIRD-PARTY-NOTICES.txt`、`VERSION.txt`;`trace-server.service` 与 `README.md` 的正本在 `cmd/trace-server/deploy/`。
+- **systemd**:`trace-server.service` 示例用专用用户 `trace`,`Restart=on-failure`、`NoNewPrivileges`、`ProtectSystem=strict`,`ReadWritePaths` 只放 `/var/lib/trace`(数据目录与 rclone 配置)和导出目录,`RCLONE_CONFIG` 指向服务能写的 rclone 配置,`TimeoutStopSec=45` 留够 30 秒收尾。部署说明(`cmd/trace-server/deploy/README.md`)写目录、用户、防火墙、`init`、systemd、rclone 配置与自己的 client_id、外部定时 rclone 的排除规则、凭证保护的边界与换包升级。
+- **日志**:`<数据目录>/logs/trace.log`,同时写标准错误(由 journald 收集);规则同桌面版,另外不记录令牌、连接码、请求体与 rclone 的输出原文(只记退出码与脱敏后的首行错误)。
+
+
+## 3. 远程接口与安全
+
+- **传输**:HTTPS(TLS 1.3),证书是 `init` 生成的自签名 ECDSA P-256 证书。本地客户端不信任系统证书库,只认连接码里的证书指纹(叶证书 DER 的 SHA-256),不一致就拒绝,并提示“远程证书变了”。连接码经 SSH 终端从 VPS 拿到,所以第一次连接就能确认身份,不需要“首次信任”。
+- **鉴权**:每个请求带 `Authorization: Bearer <令牌>`,令牌 32 字节随机数,服务端只存 SHA-256,并用常数时间比较。同一来源地址 1 分钟内失败 5 次后,10 分钟内一律 `429`。请求体上限 1 MiB(订阅快照与凭证),没有 CORS,不提供网页。
+- **版本**:请求与响应都带 `X-Trace-Protocol`(当前 `1`)和程序版本;协议不同返回 `409`,本地显示两边的版本并提示更新较旧的一边。
+- **端点**(`/api/v1/`,JSON):
+
+| 方法与路径 | 做什么 |
+| --- | --- |
+| `GET status` | 第 7 节的状态 |
+| `GET subscriptions` | 远程当前的订阅快照与它的摘要哈希(本地据此显示“有改动未同步”) |
+| `PUT subscriptions` | 用本地的订阅快照整体替换远程的(第 4 节) |
+| `PUT credentials/{site}` | 推送一个站点的 Cookie(第 5 节) |
+| `DELETE credentials/{site}` | 清除远程这个站点的登录 |
+| `POST upload/retry` | 让失败的上传立即重试 |
+
+- **本地保存**:连接的地址、名字与证书指纹放 `settings.json` 的 `remote`;令牌放凭证库(Windows DPAPI,与站点凭证同样保护),不进设置文件、日志与界面。
+
+
+## 4. 订阅同步与远程的规则
+
+- **订阅快照**(与“导出订阅”文件同一格式,第 6.3 节):订阅(ID、名字、关联账号的站点、UID、名字与头像地址、选用的规则 ID)、共用缓存规则,以及设置的一部分:画质、编码顺序、音质、多 P、并发、弹幕、字幕、AI 字幕、定时检查间隔、开播检查间隔。不同步代理、保存位置、窗口与播放器设置,也不含 Cookie。
+- **整体替换**:远程的订阅、规则与上面这些设置换成快照里的。账号的检查起点、上次检查与已发现的更新按“站点 + UID”保留,移出快照的账号不再检查,已缓存的文件不删(INV-11)。替换在一次写入里完成,失败就保持原样。
+- **只缓存启动之后的新内容**:远程第一次检查一个账号时只建立起点(INV-12),起点之前的内容永远不缓存;远程停机期间发布、起点之后的内容在恢复后照常补上(受每轮页数限制)。远程不执行“全部缓存”(规则里的这一项在远程忽略,状态里注明),也没有补更早内容和手动缓存。
+- **规则照常**:每个订阅按自己的规则决定是否定时检查、自动缓存哪些类型、是否开播录制。远程的总开关“定时检查更新”始终打开(不然它什么也不做),所以选用“默认”规则的订阅在远程不会被检查。每小时额度、退避与熔断与桌面版相同(INV-10),远程与本地各算各的。
+- **本地与远程都缓存同一条**时,导入时这一条按“相同”跳过或按冲突处理(第 6.2 节);不需要本地关掉自动缓存。
+
+
+## 5. Cookie 推送与续期
+
+- **只由本地续期**(DEC-062 ③):哔哩哔哩续期会让旧 Cookie 失效,所以远程从不续期,也不调用任何登录接口。推送内容只有站点 Cookie 和账号摘要(UID、昵称),不推送 `refresh_token`。
+- **推送时机**:用户在“设置 › 远程”点“同步 Cookie”;本地续期成功、重新扫码或粘贴登录后,只要配置了远程,就自动推送一次。推送失败(离线、证书不符、令牌错)时记为“Cookie 待同步”,之后每次刷新远程状态和每 10 分钟后台重试,成功后清除标记。
+- **远程验证**:收到后先用 nav(哔哩哔哩)或 `profile/self`(抖音)校验一次,失败不保存,原凭证保持不变,并把原因返回本地。
+- **失效**:远程请求得到“未登录”时,把这个站点标为“需要重新同步 Cookie”,停止这个站点的全部请求(INV-07),直到收到新 Cookie。
+- **远程的凭证保存**:`credentials/` 下按站点存,用 `init` 生成的随机 32 字节密钥做 AES-GCM 加密,密钥文件 `0600`。这只能挡住把凭证文件单独拷走,挡不住拿到这台机器 root 权限的人;部署说明要写明这一点。不再使用非 Windows 下固定派生密钥的做法。
+
+
+## 6. 导出目录、上传与导入
+
+
+### 6.1 导出格式(远程导出目录、网盘上的副本、本地导出的文件夹都是这一种)
+
+- **布局**:与媒体库相同,`<站点>/<作者>/<种类>/<条目>/`,里面是媒体文件和 `item.json`。`item.json` 就是这个条目的清单:`media` 列出每个文件的相对路径、字节数与 SHA-256(直播的每段同样)。
+- **写入顺序**:先把媒体文件以正式名写完、校验通过,最后原子写 `item.json`。直播每收尾一段就重写一次 `item.json`,列出这一场到此为止的全部正式段(包括已经上传、本机已删掉的段)。
+- **正在写的文件都有标记**:下载与录制中的文件以 `.part` 结尾,原子写入的临时文件以 `.trace-` 开头(`storage.WriteFileAtomic`、合并、图片与音频临时文件统一改成这两种)。DASH 视频的音视频分轨在合并成 `P01.mp4` 之前也用 `.trace-P01.video-….m4s` 这类名字;旧版本留下的 `P01.video-….m4s` 续传时先改成新名字再继续。所以任何上传方式只要排除 `*.part` 和 `.trace-*`,就不会传出写了一半的文件;`trace-server rclone-filter` 打印这两条规则。
+- **可携带的清单**:导出、上传到网盘的 `item.json` 去掉只对本机有意义的字段(本机条目文件夹 `itemDir`、`itemKey`、`rawId`、`totalBytes`),其余与本地相同;导入时按条目内容重新算出这些字段。
+- **节点**:`item.json` 新增可选字段 `cachedBy`(`node`、`name`):缓存它的机器。旧条目没有这个字段;本地缓存的写本机节点 ID(`<数据目录>/node.json`)。
+- **允许文件被搬走**:远程不依赖导出目录里的文件继续存在。是否已缓存、录到第几段只看远程自己的数据库与录制状态;文件夹被搬空后,下次写入时重新建立。远程不对导出目录做升级检查、丢失文件扫描和重建索引。
+
+
+### 6.2 内置上传(推荐,DEC-062 ⑨)
+
+- **方式**:`server.json` 的 `upload`:`mode`(`rclone` 或 `none`)、`remote`(rclone 远端路径,如 `gdrive:trace`)、`rclone`(程序路径,默认在 `PATH` 里找)、`config`(可选的 rclone 配置文件路径)、`deleteAfterUpload`(默认开)、`extraArgs`(追加参数,如带宽限制)。网盘授权由用户用 `rclone config` 完成;TRACE 不读取也不保存 rclone 配置里的令牌。
+- **单位与顺序**:一个条目的一批新完成文件为一次上传。先上传媒体文件(`rclone copy <条目文件夹> <远端>/<相对路径> --files-from <清单>`),成功后再上传 `item.json`。所以网盘上出现某个版本的 `item.json` 时,它列出的文件已经先传过。直播每收尾一段上传一次这一段与新的 `item.json`。
+- **确认与删除**:rclone 退出码为 0 才算成功。成功后记入远程数据库(路径、字节数、SHA-256、时间);`deleteAfterUpload` 开着时,只删除刚确认上传的正式文件,以及变空的文件夹(INV-09)。录制中的 `.part` 与还没写完的条目从不上传、不删除。
+- **失败**:按退避重试(1、5、15、60 分钟,之后每小时);rclone 找不到、配置错误、网盘配额(如 Google Drive 每天 750 GiB 的上传上限)分别在状态里说明。导出目录剩余空间低于 5 GiB 时状态显示警告,低于 1 GiB 时暂停新的缓存任务(录制按直播的磁盘规则)。
+- **外部定时上传**(`mode: none`,兼容用户原来的做法):TRACE 不上传也不删除;用户自己的定时 `rclone copy` 或 `rclone move` 加上 `--exclude "*.part" --exclude ".trace-*"`(建议再加 `--min-age 2m`)。用 `move` 时远程照常工作(第 6.1 节)。
+
+
+### 6.3 资源库导入(本地,DEC-062 ④)
+
+- **入口**:媒体库“⋯ → 导入…”打开媒体库里的导入页(标题“导入”,左上角返回媒体库),填一个文件夹路径(网盘下载下来的、另一台 TRACE 的缓存文件夹或导出文件夹,选它或它的上一层都可以;按 `<站点>/<作者>/<种类>/<条目>` 认出相对路径)。没有系统的文件夹选择框,路径直接输入或粘贴。先扫描、只读,列出预览,用户确认后才写入。
+- **逐条判定**(条目键相同即同一条目,与来自哪台机器无关):
+
+| 分类 | 条件 | 默认处理 |
+| --- | --- | --- |
+| 新条目 | 本地没有这个条目键 | 导入 |
+| 可补充 | 本地已有,导入的多出本地没有的文件(如新录的段、补全的分 P),同名文件内容一致 | 只补多出的文件,合并 `item.json` |
+| 相同 | 文件集合与内容都一致 | 跳过 |
+| 冲突 | 同一路径的文件字节数或 SHA-256 不同,或同一条目在不同的作者文件夹 | 等用户选:保留本地 / 用导入的 / 合并 |
+| 未传完 | `item.json` 列出的文件缺失、字节数不符或 SHA-256 不符 | 能校验通过的文件照常导入(条目标为部分完成,没校验通过的文件记在 `missing`),其余等下次导入补上;一个媒体文件都没有的条目跳过 |
+| 无法识别 | 没有 `item.json`、格式版本不对、路径越出条目文件夹 | 跳过并说明 |
+
+- **冲突的三种处理**:保留本地(只补本地缺的文件)、用导入的(导入的文件校验通过后替换本地的同名文件,再删除本地多余的登记文件)、合并(本地已有的同名文件保留,补上缺的,`parts`、直播段、`live.incidents` 取并集)。可以逐条选,也可以“全部冲突都……”;逐条选的优先,两处都没选的冲突这次跳过。本地条目在另一个作者文件夹时,三种处理都写进本地原来的文件夹,不搬动本地文件。
+- **同一场直播的两部分**:两台机器各录到一部分段时,合并把导入的段接在本地段之后、按顺序重新编号(本地文件从不改名),内容相同的段只留一份;导入的直播已经录完而本地的还标着录制中时,按“可补充”更新清单。
+- **写入**:文件先复制为 `.part`,校验字节数与 SHA-256 后改正式名,`item.json` 最后写入并更新索引与信息流;中途取消或中断不会留下半个文件,再导入一次会从剩下的继续。默认复制,来源不动;勾选“导入后删除来源里已导入的文件”才删,只删校验并导入成功的文件与变空的文件夹。
+- **位置**:导入的条目放在本地当前保存位置的同一相对路径;作者文件夹按 `item.json` 的归属(合作视频的 `via` 等,DEC-056、DEC-061)不变。
+- **进度**:扫描与导入都是后台任务,任务页侧栏“导入导出”列出进度、速度与结果摘要(新增、补充、跳过、冲突处理、未传完的条数,没完成的条目与原因);扫描完等待确认的任务可以从这里“查看预览”回到导入页或“放弃”。任务列表只保留本次运行的。
+
+
+### 6.4 本地导出
+
+- **资源库导出**:媒体库“⋯ → 导出…”选范围(全部,或媒体库当前的筛选:类型、站点、来源或作者、搜索词)和目标文件夹,按第 6.1 节的格式复制已完成的文件与 `item.json`;只复制 `item.json` 登记的文件,正在缓存、录制中的条目只导出已完成的部分。目标里已有内容相同的文件就跳过,所以中断后再导出一次会接着做。作为后台任务列在任务页“导入导出”。导出的文件夹可以被另一台 TRACE 导入。
+- **订阅导出与导入**:订阅页“⋯ → 导出订阅…”写 `trace-subscriptions.json`(填的是文件夹时自动补上这个文件名)(`format: "trace-subscriptions"`、`version: 1`、导出时间、节点、规则、订阅、设置的一部分,与第 4 节的快照相同,不含 Cookie)。“⋯ → 导入订阅…”先预览:新订阅、已在某个订阅里的账号(跳过或合并进已有订阅)、同 ID 但内容不同的规则(保留本地 / 用导入的)。确认后一次写入。
+
+
+## 7. 远程状态与本地的“设置 › 远程”
+
+- **状态内容**(`GET status`):版本与协议、节点名、启动时间、导出目录的剩余与总空间;每个站点的登录状态(有效、需要重新同步、没有 Cookie、退避到某时)、账号昵称、Cookie 同步时间;订阅数、账号数、上次同步时间与快照哈希;每个账号的上次检查时间与结果、下一轮预计时间(同任务页“检查计划”);正在缓存与排队的任务数,最近 20 条完成与失败;正在录制的场次(主播、开始时间、时长、大小、段数、异常数);上传方式、排队与正在上传的条目数与字节数、今日已上传、最近一次失败及原因;最近 20 条错误(类别与脱敏后的说明)。不含任何凭证、签名地址与流地址。
+- **本地页面**:设置新增分类“远程”([界面 §3.7](../ui.md#settings))。没有连接时:粘贴连接码,或分别填地址、令牌、指纹。连接后:状态卡片(在线或无法连接及原因、版本、运行时长、空间);站点行(登录状态,“同步 Cookie”);订阅行(“远程 N 个订阅 · M 个账号 · X 前同步”,本地与远程不同时写“有改动未同步”,“同步订阅”);录制、缓存、上传、检查与错误各一节,可展开。页面打开时每 30 秒刷新一次,另有“刷新”按钮;页面关闭时不请求远程(Cookie 待同步的后台重试除外)。
+- **只连一个远程**:现在只保存一个连接;数据结构按列表设计,以后的集群模式再放开。
+- **验证**:`go run ./tools/smoke -server` 在临时目录跑真程序:`init` → 启动 → 用连接码读状态 → 同步合成快照 → 用假 rclone 上传一个合成条目并确认本机文件已删 → 停止,回执在 `artifacts/smoke-server/`。Linux 上用 `SIGTERM` 停止并确认正常退出、数据目录锁已释放;Windows 上没有控制台信号可发,改为结束进程后再启动一次确认锁已释放。冒烟把代理指向本机的空端口,任何站点请求都出不去。CI(Ubuntu)在 `tools/check` 之后跑同一条命令。
+
+
+## 8. 为集群模式预留
+
+- 节点 ID(每个数据目录一个,随机生成)与名字;`item.json.cachedBy`;状态与快照带节点。
+- 导入按条目键合并、与来源无关,所以多台机器的导出可以先后导入同一个资源库,同一条目的不同部分(如两台机器各录到的段)会合并。
+- 多台机器分担同一批账号(谁检查哪个、避免重复缓存)还没有做(FR-REMOTE-009);现在每台远程都独立检查同步给它的全部账号。
diff --git a/docs/design/subscriptions.md b/docs/design/subscriptions.md
index 038aacb..25ce2d9 100644
--- a/docs/design/subscriptions.md
+++ b/docs/design/subscriptions.md
@@ -93,7 +93,7 @@ TRACE 以订阅为逻辑入口(DEC-026):一个订阅代表一个被追踪
- 这一轮因风控、限流或未登录停止时不建任务。已经缓存过的动态(索引里已有)只记 `auto_task_id` 为已有条目,不重复建任务。
-- **全部缓存(DEC-061 ①)**:规则的 `fullCache` 打开时,后台每 10 分钟看一次哪些账号到期(`updates.db` 的 `account_works.full_cache_at` 为空或早于 7 天前,`FullCacheInterval`),按上次全部缓存时间从早到晚,为它建一个 DEC-050 ① 的缓存队列(哔哩哔哩列表 `videos`,抖音 `works`,`origin = "full_cache"`),并把 `full_cache_at` 记为现在。队列自己从新到旧翻完整个列表,已缓存或正在缓存的直接跳过,没缓存的按慢速、不规律的节奏一条一条缓存,遇到风控、限流或额度用完照常等待。每个站点同时只有一个没结束的缓存队列时才开新的,所以全部缓存的账号一个接一个做,也不和用户自己点的“全部缓存”同时跑。取消的队列不会马上重开,等下一个 7 天。抖音开始前读一次账号资料(自动请求,退避或额度用完时跳过)记下作品总数。
+- **全部缓存(DEC-061 ①)**:规则的 `fullCache` 打开时,后台每 10 分钟看一次哪些账号到期(`updates.db` 的 `account_works.full_cache_at` 为空或早于 7 天前,`FullCacheInterval`),按上次全部缓存时间从早到晚,为它建一个 DEC-050 ① 的缓存队列(哔哩哔哩列表 `videos`,抖音 `works`,`origin = "full_cache"`),并把 `full_cache_at` 记为现在。队列自己从新到旧翻完整个列表,完整缓存了的、正在缓存的、已暂停的(在任务页继续)和只是可以升级画质的直接跳过;没缓存的、失败的和缓存了但不完整的(部分完成、有缺失记录、分 P 没有文件,DEC-063 ③,`library.NeedsCompletion`)按慢速、不规律的节奏一条一条缓存,不完整的再缓存一次时保留已有的有效文件、只补缺的部分;遇到风控、限流或额度用完照常等待。每个站点同时只有一个没结束的缓存队列时才开新的,所以全部缓存的账号一个接一个做,也不和用户自己点的“全部缓存”同时跑。取消的队列不会马上重开,等下一个 7 天。抖音开始前读一次账号资料(自动请求,退避或额度用完时跳过)记下作品总数。
- **作品总数与已缓存数(DEC-061 ②)**:`account_works(site, uid, works_total, works_at, full_cache_at)` 记每个账号上次解析时站点给的作品总数(`-1` 表示还不知道):打开哔哩哔哩用户页(`card` 的 `archive_count`)、读投稿列表第一页(`arc/search` 的总数,包括全部缓存翻的第一页)、打开抖音用户页或全部缓存开始时(资料的 `aweme_count`)。`SubscriptionAccountWorks()` 只读本机:总数来自这张表,已缓存数由 `library.CountCachedWorks` 从 `library_items` 数(哔哩哔哩 `kind = video` 且投稿人是他或 `via` 是为他缓存的合作视频,抖音 `kind` 为 `video` 或 `dynamic`)。
diff --git a/docs/dev-rules/engineering.md b/docs/dev-rules/engineering.md
index 9efef34..2714f3c 100644
--- a/docs/dev-rules/engineering.md
+++ b/docs/dev-rules/engineering.md
@@ -5,13 +5,13 @@
## 1. 环境与版本
-本节只记**实际**安装和锁定的版本。按 DEC-032,全项目使用纯 Go + MyGo 原生界面(`github.com/egoist/mygo/ui`),不引入 Node.js、npm、Vite、React 或 TypeScript,也不依赖客户机 WebView2 运行时;后续开发持续与 MyGo 最新版本(当前 `v0.8.3`)同步改动。
+本节只记**实际**安装和锁定的版本。按 DEC-032,全项目使用纯 Go + MyGo 原生界面(`github.com/egoist/mygo/ui`),不引入 Node.js、npm、Vite、React 或 TypeScript,也不依赖客户机 WebView2 运行时;后续开发持续与 MyGo 最新版本(当前 `v0.9.0`)同步改动。
-| 组件 | 版本 | 锁定方式 | 状态(2026-11-09) |
+| 组件 | 版本 | 锁定方式 | 状态(2026-11-21) |
| --- | --- | --- | --- |
| Go | `go1.27.4 windows/amd64` | `go.mod` 的 `go 1.27.4`(2026-11-14 从 1.27.3 升级,修 GO-2026-6859) | 本机已安装 1.27.3,`GOTOOLCHAIN=auto` 按 `go` 行自动下载 1.27.4 |
-| MyGo 库 / CLI | `v0.8.3` | `go.mod` 的 `tool github.com/egoist/mygo/cmd/mygo` 与 `require github.com/egoist/mygo v0.8.3` | 已锁定并实测(`go tool mygo`、`mygo/ui` 原生窗口/测试器、`mygo.Updater`) |
-| Go 依赖 | `github.com/egoist/mygo v0.8.3`、`modernc.org/sqlite v1.62.0`、`github.com/Eyevinn/mp4ff v0.62.0`、`google.golang.org/protobuf v1.36.12`(`protowire`)、`github.com/yeqown/go-qrcode/v2 v2.3.0`(二维码矩阵)及传递 `github.com/yeqown/reedsolomon v1.0.0`(均 MIT)、`golang.org/x/image v0.47.0`(WebP 与图标绘制,BSD-3-Clause)、`golang.org/x/sys v0.50.0`(Windows API 与注册表) | `go.mod` 与 `go.sum` 精确版本 | 已实际接入并通过门禁;许可随包收录,二维码传递模块的许可补充见下 |
+| MyGo 库 / CLI | `v0.9.0` | `go.mod` 的 `tool github.com/egoist/mygo/cmd/mygo` 与 `require github.com/egoist/mygo v0.9.0` | 已锁定并实测(`go tool mygo`、`mygo/ui` 原生窗口/测试器、`mygo.Updater`) |
+| Go 依赖 | `github.com/egoist/mygo v0.9.0`、`modernc.org/sqlite v1.62.0`、`github.com/Eyevinn/mp4ff v0.63.0`、`google.golang.org/protobuf v1.36.12`(`protowire`)、`github.com/yeqown/go-qrcode/v2 v2.3.0`(二维码矩阵)及传递 `github.com/yeqown/reedsolomon v1.0.0`(均 MIT)、`golang.org/x/image v0.48.0`(WebP 与图标绘制,BSD-3-Clause)、`golang.org/x/sys v0.50.0`(Windows API 与注册表) | `go.mod` 与 `go.sum` 精确版本 | 已实际接入并通过门禁;许可随包收录,二维码传递模块的许可补充见下 |
| NSIS(构建期工具) | `v3.13`(`makensis.exe`) | MyGo 缓存于 `%LOCALAPPDATA%\mygo\nsis-3.13`(zlib/libpng、bzip2、CPL 1.0 许可) | 本机已安装并生成开发版、正式版与 ptest 安装包 |
| Windows Media Foundation | Windows 10/11 系统自带(`mfplat.dll`、`mfreadwrite.dll`、`ole32.dll`) | — | 本机已有,经合成样本解码、拖动与静音测试验证 |
@@ -26,10 +26,12 @@
| `go run ./tools/check` | 全部质量门禁(见第 3 节),任一失败就以非零退出 | 已实现并实测通过;最新范围与用时见[阶段报告](../delivery/stage-report.md) |
| `go run ./tools/deps [-audit]` | [依赖盘点](workflow.md#dependency-inventory):列出直接依赖模块与 `go` 行满 7 天的新版本,只出报告;`-audit` 用固定版本的 `govulncheck` 查代码实际调用到的已知漏洞,未登记在 `tools/deps/exceptions.json` 或例外过了复查日期则退出码 1,跑不起来退出码 2(`not-run`)。阶段开始与 B 交付前各跑一次,要联网 | 已实现;2026-11-14 首次运行:盘点 2 项满龄(`golang.org/x/sys`、`go` 1.27.4),`-audit` 有 1 条被调用的标准库漏洞(升到 Go 1.27.4 可修),7 条在没调用到的依赖模块里 |
| `go run ./tools/package [-install \| -install-only]` | 构建开发版:按[版本号](#versions)算出 `<下一个正式版>-dev.`,临时把 `mygo.json` 换成开发版配置(`trace-dev` 身份、开发版图标、发布者、中文目录,不带更新),经 `MYGO_LDFLAGS` 注入版本、通道、提交与构建时间,运行 `mygo build -platform windows/amd64`;先在 `dist/.staging-<时间>/` 生成安装包 `trace-dev-setup-<版本>-amd64.exe`、解包的 `trace.exe`、`THIRD-PARTY-NOTICES.txt`、`VERSION.txt`、`SHA256SUMS.txt` 并校验,再替换 `dist/trace-dev/` 中登记的文件。只打包,不动本机开发版;`-install` 打包后再[安装到本机](#dev-install),`-install-only` 只安装 `dist/trace-dev/` 里现有的包。许可文件逐字收录 Go 模块和标准库的 LICENSE/NOTICE;精确版本的官方补充见下,其他缺许可模块会停止打包 | 已实现并实测通过;最新产物与安装结果见[阶段报告](../delivery/stage-report.md) |
+| `go run ./tools/package -server` | 构建远程版:版本号同开发版,`CGO_ENABLED=0 GOOS=linux`、`-trimpath -ldflags "-s -w …"` 交叉编译 `./cmd/trace-server` 的 `amd64` 与 `arm64`,每个架构打一个 `trace-server-<版本>-linux-<架构>.tar.gz`(顶层一个同名文件夹,含 `trace-server`、`cmd/trace-server/deploy/` 里的 `trace-server.service` 与 `README.md`、`THIRD-PARTY-NOTICES.txt`、`VERSION.txt`),以 `SHA256SUMS` 登记,先在 `dist/.staging-server-<时间>/` 生成再替换 `dist/trace-server/` 里登记的文件。不能与 `-install` 同用 | 已实现并实测通过;体积与 WSL 解包核对见[阶段报告](../delivery/stage-report.md) |
| `go run ./tools/release [-allow-dirty] [-offline] [-plan] [-publish]` | [发布正式版](#release):检查、构建、签名、ptest 升级演练,产物放进 `dist/trace/` | 已实现;`-allow-dirty -offline` 演练实测通过,没有发布过 |
| `go run ./tools/icons` | 重画 `assets/icon.png`(正式版:深灰底 `#3c4043` 白字 “T”,DEC-046 去掉了点)与 `assets/icon-dev.png`(开发版:同一图标加琥珀色 “DEV” 角标);两个通道底色、字母高度(250–780)与笔画(110)相同,只差角标(2026-11-14 用户要求),1024×1024 | 已实现;图标已入库,只在改图标时运行 |
| `go run ./tools/smoke -pkg dist/trace-dev -out artifacts/smoke` | 包冒烟:在临时的 `LOCALAPPDATA`、`APPDATA`、`USERPROFILE`、“文档”与 `TEMP`/`TMP` 目录下,以[安静模式](#quiet-tests)启动 `trace.exe`,检查进程存活、程序报告的版本、提交与构建时间与 `VERSION.txt` 一致、无 `msedgewebview2.exe` 子进程、`library.db`、`updates.db` 与 `mygo/` 建在数据目录里、临时 `APPDATA` 与用户主目录下没有新文件夹、单实例与数据目录锁生效、托盘关闭与重建正常、日志无凭证;`HTTP(S)_PROXY` 指向本机关闭的端口,保证不访问真实站点 | 已实现并实测通过,`quietMode=hidden`、`webview2=0`;最新内存与用时见[阶段报告](../delivery/stage-report.md) |
-| `go run ./tools/uishots -out artifacts/uishots` | 界面截图与断言:用 `mygo/ui` 的 `ui.NewTester` 在 1280、1000、720 三档宽度下渲染全部必测页面与状态,直接将 `tt.Image()` 编码为 PNG 截图并写出结构化布局/无障碍断言回执 `assertions.json` | 已实现并实测通过:当前 54 个场景、162 张 PNG,覆盖解析页侧栏与居中大输入框(有历史/空历史)、媒体库离线本机详情(`/library/item`)、任务页四组侧栏(下载任务、缓存队列详情、直播录制行内“⚠ N 处异常”与实时预览、录制异常)、“我的”(折叠、哔哩哔哩收藏夹/稍后再看/历史/关注、抖音喜欢/收藏、未登录、风控错误、窄窗选择)、订阅详情(“内容”跨站已缓存信息流与空态、“账号”合并直播状态与录制按钮)、设置“缓存规则”(含展开规则点开批量“选择订阅…”对话框)、“设置 › 更新”(正式版与开发版)及“关于”、更新已就绪的提示、绿色强调色预览(Q-011)、播放选项与音量面板,以及抖音用户页、作品/图文与配乐条、抖音登录分段、多站点账号与退避设置、多站点订阅账号列表和六处站点小字断言;最新断言结果见[阶段报告](../delivery/stage-report.md) |
+| `go run ./tools/smoke -server [-server-bin <程序>]` | 远程冒烟([远程 §7](../design/remote.md#status)):不给 `-server-bin` 时用本机 `go build ./cmd/trace-server`。在临时目录 `init` → `run` → 用连接码读状态 → 同步合成订阅快照 → 冒烟程序自己充当 rclone(`internal/upload/fakerclone`)上传一个合成条目并确认本机文件已删 → 停止;Linux 发 `SIGTERM` 并确认正常退出、数据目录锁已释放,Windows 改为结束进程后再启动一次;检查数据目录文件权限(Linux)与令牌没有出现在任何文件和输出里。`HTTP(S)_PROXY` 指向本机关闭的端口。回执 `artifacts/smoke-server/smoke.json` | 已实现并实测通过(Windows 本机构建;WSL Ubuntu 用 `-server` 包里的 Linux 程序);CI 在 `tools/check` 之后运行 |
+| `go run ./tools/uishots -out artifacts/uishots` | 界面截图与断言:用 `mygo/ui` 的 `ui.NewTester` 在 1280、1000、720 三档宽度下渲染全部必测页面与状态,直接将 `tt.Image()` 编码为 PNG 截图并写出结构化布局/无障碍断言回执 `assertions.json` | 已实现并实测通过:当前 64 个场景、192 张 PNG,覆盖解析页侧栏与居中大输入框(有历史/空历史)、媒体库离线本机详情(`/library/item`)、任务页六组侧栏(下载任务、缓存队列详情、直播录制行内“⚠ N 处异常”与实时预览、录制异常、检查计划、导入导出)、“我的”(折叠、哔哩哔哩收藏夹/稍后再看/历史/关注、抖音喜欢/收藏、未登录、风控错误、窄窗选择)、订阅详情(“内容”跨站已缓存信息流与空态、“账号”合并直播状态与录制按钮)、设置“缓存规则”(含展开规则点开批量“选择订阅…”对话框)、“设置 › 更新”(正式版与开发版)及“关于”、更新已就绪的提示、绿色强调色预览(Q-011)、播放选项与音量面板,以及抖音用户页、作品/图文与配乐条、抖音登录分段、多站点账号与退避设置、多站点订阅账号列表和六处站点小字断言,以及“设置 › 远程”(未连接、已连接、无法连接)、媒体库导入页(含冲突)、任务页“导入导出”与导入订阅预览;最新断言结果见[阶段报告](../delivery/stage-report.md) |
| `go run ./tools/actcheck -act ` | 真实站点有界检查:读取 `.local/site-check/` 的检查对象与持久化账本(发出前超额即拒),在 USER-ACTIONS 写明的额度内串行执行,遇挑战、限流或未登录立即停止,输出脱敏回执 `artifacts/site-check/.json` | 已实现;合成门禁测试在 `tools/actcheck` 内,真实请求只在用户授权对应 ACT 项且账本未满时运行 |
`reedsolomon v1.0.0` 模块归档缺少 LICENSE;官方下一提交只增加 MIT LICENSE、源码未变。其固定来源、SHA-256 与精确版本补充保存在 [tools/internal/build/licenses/README.md](../../tools/internal/build/licenses/README.md),由打包工具嵌入通知,升级到自带许可的模块后移除;打包不依赖在线查许可。
@@ -82,9 +84,10 @@
| 检查 | 内容 |
| --- | --- |
-| Go 格式与静态检查 | `gofmt -l` 输出为空;`go vet ./...` |
+| Go 格式与静态检查 | `gofmt -l main.go cmd internal tools` 输出为空;`go vet ./...` |
| Go 测试 | `go test ./...`:协议夹具与固定向量(含抖音 SM3/`a_bogus`/`x-secsdk-web-signature`)、选流、分段下载与重试、合并与单文件 MP4 `moov` 前置校验、数据结构版本迁移与 `.premigrate-1` 备份、索引重建、安全删除、信息流分页、媒体路径白名单、多站点凭证与哨兵隔离、混合站点订阅与检查更新、按站点退避与每小时额度、关注导入、登录续期、弹幕与字幕、直播 HLS fMP4 与 HTTP-FLV(AVC/HEVC `CodecID=12`/Enhanced FLV `hvc1`)录制转换、安装与数据位置、托盘与单实例、原生界面 `ui.NewTester` 测试、真实检查器账本门禁与文档检查反例 |
-| 依赖方向 | `go list -deps`:`internal/...` 与 `tools/...` 中只有 `internal/shell`、`internal/ui`、`internal/player`、`internal/locales`(MyGo 自带字符串与安装界面的中文目录)、`tools/uishots` 依赖 `github.com/egoist/mygo/...`(INV-05);`internal/site` 只用 Go 标准库(零 `internal/...` 与第三方依赖);`internal/site/bilibili` 与 `internal/site/douyin`(含子包)不依赖 `storage`、`library`、`download`、`subscription`、`live`、`service`、`ui`,且两个站点包互不引用;`internal/site/douyin/sign` 不依赖 `internal/credential` 与 `net/http`;`download`、`live`、`subscription`、`library`、`storage`、`settings`、`uistate` 不依赖 `internal/site/douyin`;直接引用 `internal/site/bilibili` 的内部包名单锁定(`download`、`library`、`live`、`service`、`subscription`、`ui`),`storage`、`settings`、`uistate` 零 `site/bilibili` 依赖,不再新增引用者;`internal/ui` 不直接引用 `internal/site/douyin`(及 `sign`) |
+| 依赖方向 | `go list -deps`:`internal/...` 与 `tools/...` 中只有 `internal/shell`、`internal/ui`、`internal/player`、`internal/locales`(MyGo 自带字符串与安装界面的中文目录)、`tools/uishots` 依赖 `github.com/egoist/mygo/...`(INV-05);`internal/site` 只用 Go 标准库(零 `internal/...` 与第三方依赖);`internal/site/bilibili` 与 `internal/site/douyin`(含子包)不依赖 `storage`、`library`、`download`、`subscription`、`live`、`service`、`ui`,且两个站点包互不引用;`internal/site/douyin/sign` 不依赖 `internal/credential` 与 `net/http`;`download`、`live`、`subscription`、`library`、`storage`、`settings`、`uistate` 不依赖 `internal/site/douyin`;直接引用 `internal/site/bilibili` 的内部包名单锁定(`download`、`library`、`live`、`service`、`subscription`、`ui`),`storage`、`settings`、`uistate` 零 `site/bilibili` 依赖,不再新增引用者;`internal/ui` 不直接引用 `internal/site/douyin`(及 `sign`);`cmd/trace-server` 不依赖 MyGo、`internal/ui`、`internal/player`、`internal/shell`、`internal/locales`(检查范围含 `./cmd/...`) |
+| 远程版构建 | `CGO_ENABLED=0 GOOS=linux` 下 `GOARCH=amd64` 与 `arm64` 各构建一次 `./cmd/trace-server`,再 `GOOS=linux go vet ./...` |
| 文档与公开内容 | `go run ./tools/checkdocs`:相对链接与锚点存在;没有本机绝对路径、哔哩哔哩/抖音 Cookie 或签名参数文本(含 `sessionid=`、`sessionid_ss=`、`sid_guard=`、`msToken=`、带 `a_bogus=` 或 `x-signature` 的地址),也没有本机参考索引里登记的项目名(运行时读取索引,名单不进仓库) |
| 空白 | `git diff --check HEAD`(只看已跟踪的文件:新文件先 `git add` 再跑门禁) |
@@ -132,7 +135,7 @@
GitHub 上 main 的规则集:只能经 PR 写入,禁止强推和删除,保持线性历史,只允许 squash 合并,所有讨论必须解决,必需检查为 `repository-quality`;Actions 只允许固定 SHA 的 `actions/checkout`,token 只读,来自 fork 的 PR 运行 workflow 前须维护者批准(所有外部贡献者)。为防止垃圾内容,外部只开放 Discussions:关闭 Issues、Wiki 和 Projects,PR 仅协作者可创建;安全问题走私密漏洞报告。远端设置以 GitHub 实际回读为准。
-CI 文件 `.github/workflows/ci.yml` 的 job 名必须是 `repository-quality`,在 Ubuntu 上运行文档检查与 `go vet`/`go test ./internal/... ./tools/...`;Go 用 runner 预装版本或 `GOTOOLCHAIN` 自动下载,不引入未许可的 action。CI 不替代本地的 Windows 构建与界面检查:Linux 上 DPAPI 与 Media Foundation 换成非 Windows 桩或合成后端(`internal/credential/dpapi_other.go`、`internal/player/mf_other.go`),依赖 Windows 文件共享锁的测试段落跳过(`internal/library/lock_other_test.go`);没有显示器时,托盘测试里打开真实隐藏窗口的段落跳过(`internal/shell/shell_test.go`,Windows 本机照常运行)。本机没有 cgo 工具链,`go test -race` 无法运行,记为 not-run。本机只完成 Linux `go vet` 与测试包交叉编译,未运行真实 Ubuntu CI;交叉编译的退出成功不等于 Linux 测试通过。
+CI 文件 `.github/workflows/ci.yml` 的 job 名必须是 `repository-quality`,在 Ubuntu 上运行 `go run ./tools/check`,再运行远程冒烟 `go run ./tools/smoke -server`(真实 Linux 进程与 `SIGTERM`);Go 用 runner 预装版本或 `GOTOOLCHAIN` 自动下载,不引入未许可的 action。CI 不替代本地的 Windows 构建与界面检查:Linux 上 DPAPI 与 Media Foundation 换成非 Windows 桩或合成后端(`internal/credential/dpapi_other.go`、`internal/player/mf_other.go`),依赖 Windows 文件共享锁的测试段落跳过(`internal/library/lock_other_test.go`);没有显示器时,托盘测试里打开真实隐藏窗口的段落跳过(`internal/shell/shell_test.go`,Windows 本机照常运行)。本机没有 cgo 工具链,`go test -race` 无法运行,记为 not-run。本机只完成 Linux `go vet` 与测试包交叉编译,未运行真实 Ubuntu CI;交叉编译的退出成功不等于 Linux 测试通过。
**Dependabot**([.github/dependabot.yml](../../.github/dependabot.yml),DEC-048):Go 模块每周、Actions 每月,冷却期 7 天,同主版本更新合为一组(`golang.org/x/*` 单独一组),关闭自动 rebase,不自动合并。版本更新 PR 在阶段开始时集中处理([开发流程 §5.5](workflow.md#dependency-inventory)),所以纯依赖更新不会单独触发每周发布。Dependabot 告警与自动安全修复 PR 已打开(2026-11-14 用户授权,Agent 经 API 打开并核对);安全修复 PR 不受冷却期限制,有就尽快评审合并。
@@ -157,8 +160,8 @@ Action 一律固定完整 SHA(`actions/checkout` v7.0.1、`actions/upload-arti
| 位置 | 内容与去留 |
| --- | --- |
| `build/`、`tmp/` | 构建缓存与开发数据,随时可删,由构建重建 |
-| `dist/<通道>/`(`dist/trace-dev/`、`dist/trace/`) | 每个通道只有最新一份(DEC-025、DEC-029)。`dist/trace-dev/`(`tools/package`):安装包 `trace-dev-setup-<版本>-amd64.exe`,以及解包的 `trace.exe`(冒烟用)、`THIRD-PARTY-NOTICES.txt`、`VERSION.txt`、`SHA256SUMS.txt`。`dist/trace/`(`tools/release`):Release 上传的全部文件——安装包 `trace-setup-<版本>-amd64.exe`、更新包与清单、差分包、`install.ps1`、`VERSION.txt`、`THIRD-PARTY-NOTICES.txt`,以 `SHA256SUMS` 登记。工具先在 `dist/.staging-<时间>/`(发布为 `dist/.release-*`、演练为 `dist/.rehearsal-*`,用完删除)生成并校验,再替换上一份登记的文件,目录里其他文件不动。数据不在包旁(DEC-029),替换包不会碰到用户数据。安装包由 MyGo 用 NSIS(`v3.13`,见第 1 节)生成:各通道的 `windows.installerInclude`(`assets/installer/<通道>.nsh` + `shortcuts.nsh`,由 `ChannelConfig` 设置)按 FR-STORE-001 处理快捷方式;按用户安装到 `%LOCALAPPDATA%\Programs\<目录名>`、开始菜单快捷方式、中文安装界面、可在“设置 > 应用”卸载;卸载只删安装目录。旧的带日期的包目录(`dist/trace-<版本>-windows-x64-<日期>[-序号]/`)里可能有用户数据,工具不删,按 USER-ACTIONS 的[本机文件](../../USER-ACTIONS.md#local-files)处理 |
-| `artifacts/<类别>/` | 一次性脚本、截图、日志和测量结果,每类只留最近一次(DEC-025):类别为 `smoke`、`uishots`、`package`(`install-dev.json`)、`release`(`release.json`、`rehearsal.json`、`notes.md`)、`site-check`、`review`;写新一次前,工具只清空该类别目录里的内容(确认路径在 `artifacts/<类别>/` 内、不是链接,不跨目录通配)。阶段报告引用的证据就是这一份 |
+| `dist/<通道>/`(`dist/trace-dev/`、`dist/trace/`、`dist/trace-server/`) | 每个通道只有最新一份(DEC-025、DEC-029)。`dist/trace-server/`(`tools/package -server`):两个架构的 `trace-server-<版本>-linux-<架构>.tar.gz` 与 `SHA256SUMS`。`dist/trace-dev/`(`tools/package`):安装包 `trace-dev-setup-<版本>-amd64.exe`,以及解包的 `trace.exe`(冒烟用)、`THIRD-PARTY-NOTICES.txt`、`VERSION.txt`、`SHA256SUMS.txt`。`dist/trace/`(`tools/release`):Release 上传的全部文件——安装包 `trace-setup-<版本>-amd64.exe`、更新包与清单、差分包、`install.ps1`、`VERSION.txt`、`THIRD-PARTY-NOTICES.txt`,以 `SHA256SUMS` 登记。工具先在 `dist/.staging-<时间>/`(发布为 `dist/.release-*`、演练为 `dist/.rehearsal-*`,用完删除)生成并校验,再替换上一份登记的文件,目录里其他文件不动。数据不在包旁(DEC-029),替换包不会碰到用户数据。安装包由 MyGo 用 NSIS(`v3.13`,见第 1 节)生成:各通道的 `windows.installerInclude`(`assets/installer/<通道>.nsh` + `shortcuts.nsh`,由 `ChannelConfig` 设置)按 FR-STORE-001 处理快捷方式;按用户安装到 `%LOCALAPPDATA%\Programs\<目录名>`、开始菜单快捷方式、中文安装界面、可在“设置 > 应用”卸载;卸载只删安装目录。旧的带日期的包目录(`dist/trace-<版本>-windows-x64-<日期>[-序号]/`)里可能有用户数据,工具不删,按 USER-ACTIONS 的[本机文件](../../USER-ACTIONS.md#local-files)处理 |
+| `artifacts/<类别>/` | 一次性脚本、截图、日志和测量结果,每类只留最近一次(DEC-025):类别为 `smoke`、`smoke-server`(远程冒烟;WSL 里用 Linux 包跑的那次另放 `smoke-server-linux`)、`uishots`、`package`(`install-dev.json`)、`release`(`release.json`、`rehearsal.json`、`notes.md`)、`site-check`、`review`;写新一次前,工具只清空该类别目录里的内容(确认路径在 `artifacts/<类别>/` 内、不是链接,不跨目录通配)。阶段报告引用的证据就是这一份 |
| `.local/site-secrets/`、`.local/site-check/` | 本机 Cookie 与真实检查记录;不删,不入库 |
一次性命令的输出写进所属跑次目录,不散落在仓库根。入库的只有可公开、经审阅的最终摘要,写在阶段报告里。
diff --git a/docs/requirements.md b/docs/requirements.md
index ae31735..f46f136 100644
--- a/docs/requirements.md
+++ b/docs/requirements.md
@@ -153,6 +153,23 @@ TRACE 是 Windows 桌面应用,以“订阅”(被追踪的人)为入口
| FR-ACCT-005 | 抖音:**关注**(头像、昵称、抖音号、签名,已在订阅里的显示所属订阅,其余在“⋯”里加入订阅);**喜欢**(我点过赞的作品);**收藏**(“全部收藏”与各收藏夹,选一个看里面的作品)。作品用抖音用户页同样的 3:4 网格。抖音“观看历史”只在真实检查确认接口可用后显示([Q-015](../USER-ACTIONS.md#q-015) 第 3 条);抖音网页版没有“稍后再看”,不做 | 已实现(抖音“观看历史”未显示,LOOP-014) |
| FR-ACCT-006 | 批量操作与更多账号内容:整个收藏夹或稍后再看一键缓存、收藏的合集与追番追剧、抖音收藏的合集与音乐、写操作(取消收藏、删除历史等) | 待实现 |
+
+### 2.10 远程版、上传与导入导出(DEC-062)
+
+单独打包的无界面远程程序在 Linux VPS 上只缓存启动后的新内容与录制直播,把完成的文件上传到网盘;本地 TRACE 连接它查看状态、同步订阅与 Cookie,并把网盘下载下来的文件夹增量导入媒体库([远程设计](design/remote.md))。
+
+| 编号 | 需求 | 状态 |
+| --- | --- | --- |
+| FR-REMOTE-001 | 远程程序 `trace-server`:单独打包(不含界面),`linux/amd64` 与 `linux/arm64`,Debian 12、Ubuntu 22.04 及以上直接运行;`init` 生成数据目录、证书、令牌与连接码,`run` 交给 systemd 运行;只检查更新、按规则缓存新内容、开播录制与上传,没有媒体库、解析、全部缓存、补更早内容与网页 | 已实现;真实 VPS、网盘与站点未验收(H-003) |
+| FR-REMOTE-002 | 远程接口:HTTPS(自签名证书,本地按连接码里的指纹认证)+ 令牌;失败多次暂时拒绝;两边版本不同时拒绝并说明 | 已实现;真实 VPS、网盘与站点未验收(H-003) |
+| FR-REMOTE-003 | 订阅同步:本地“同步订阅”把订阅、共用缓存规则与相关设置整体替换到远程;远程第一次检查账号只建立起点,之后按每个订阅的规则缓存与录制 | 已实现;真实 VPS、网盘与站点未验收(H-003) |
+| FR-REMOTE-004 | Cookie 推送:本地按站点推送 Cookie,远程校验后保存、从不续期;本地续期或重新登录后自动推送,推送不了时记为待同步并重试;远程登录失效时停止这个站点的请求并提示重新同步 | 已实现;真实 VPS、网盘与站点未验收(H-003) |
+| FR-REMOTE-005 | 远程状态:本地“设置 › 远程”显示远程的版本、运行时长、空间、各站点登录、订阅同步情况、检查计划、缓存、录制、上传与最近错误 | 已实现;真实 VPS、网盘与站点未验收(H-003) |
+| FR-REMOTE-006 | 上传:远程内置上传(调用 rclone,按条目先传媒体文件、最后传 `item.json`,确认后删除本机文件,失败重试并说明原因);也兼容用户自己的定时 rclone(正在写的文件都带 `.part` 或 `.trace-` 标记) | 已实现;真实 VPS、网盘与站点未验收(H-003) |
+| FR-REMOTE-007 | 资源库导入导出:媒体库“导入”选文件夹,预览新条目、可补充、相同、冲突、未传完与无法识别;冲突逐条或批量选保留本地、用导入的或合并;校验大小与 SHA-256 后写入,中断后可继续;“导出”把全部或筛选的条目按同一格式复制到文件夹 | 已实现;真实 VPS、网盘与站点未验收(H-003) |
+| FR-REMOTE-008 | 订阅导出导入:订阅页导出 `trace-subscriptions.json`(不含 Cookie),导入时预览新订阅、已订阅的账号与不同的规则后一次写入 | 已实现;真实 VPS、网盘与站点未验收(H-003) |
+| FR-REMOTE-009 | 集群模式:多台机器分担同一批账号的检查与缓存,汇成一个资源库;同时连接多个远程 | 待实现 |
+
## 3. 非功能需求
diff --git a/docs/research/bilibili.md b/docs/research/bilibili.md
index 0ed701a..a9b9358 100644
--- a/docs/research/bilibili.md
+++ b/docs/research/bilibili.md
@@ -35,7 +35,7 @@ TRACE 只在登录状态下请求(DEC-018),所有内容接口都附带凭
| -101 | 未登录 | `auth_required`(nav 例外,见第 4 节) |
| -352 | 风控校验失败,`data` 里可能有 `v_voucher` | `risk_control`:停止,不自动重试,提示用户稍后重试或登录 |
| -412 / HTTP 412 | 请求被拦截 | `rate_limited`:停止,不自动重试 |
-| -404、62002(稿件不可见)、62004(审核中)、62012(仅 UP 主自己可见) | 内容不可得 | `unavailable`,带具体原因 |
+| -404、62002(稿件不可见)、62004(审核中)、62012(仅 UP 主自己可见)、4101152(动态不可见) | 内容不可得 | `unavailable`,带具体原因 |
| -400 | 参数错误 | `bad_request`(多半是 TRACE 的缺陷) |
| -403 | 权限不足 | `forbidden` |
| 超时、连接失败、DNS | 网络问题 | `network`:可以手动重试 |
diff --git a/docs/research/douyin.md b/docs/research/douyin.md
index 1a79058..86ad0e3 100644
--- a/docs/research/douyin.md
+++ b/docs/research/douyin.md
@@ -339,7 +339,7 @@ TRACE 登录确认判定式(缺一不可;精确未登录错误码在 [ACT-01
| `images[i].download_url_list[]` | **带抖音水印图地址**(URL 模板常含 `tplv-dy-water` 或 `watermark` 字样),TRACE 选流时**跳过不用** |
| **`images[i].live_photo_type`** 与 **`images[i].clip_type`** | **实况照片(Live Photo)标识**:普通静态图无 `video`(或 `video: null`);实况照片单页携带 `live_photo_type == 1`(常见伴随 `clip_type == 5`,其他循环模式可能有不同非零 `clip_type`),且同级带非空 `images[i].video` 对象(仅在 PC Web `aid=6383` 接口完整返回,移动端分享 HTML 常缺失该字段) |
| **`images[i].video.play_addr.url_list[]`**(及 `images[i].video.bit_rate[]`) | **实况照片对应的无水印动态短片**(通常为 3~5 秒、带声音的 H.264/H.265 MP4 单文件,含 `width`、`height`、`duration`、`data_size`)。若声明 `live_photo_type == 1` 但缺失 `video.play_addr.url_list`,应视为结构异常而非静默退化为静态图 |
-| `music.play_url.url_list[]` 与 `music.is_original_sound` | 图集配乐/原声 MP3/M4A 地址(可能为空——部分受版权保护曲目 `play_url` 下无 `url_list`)。注意:**判断是否为作者原声应读布尔值 `music.is_original_sound`(而非 `music.is_original`,后者表示音乐人发行曲目)** |
+| `music.play_url.url_list[]` 与 `music.is_original_sound` | 图集配乐/原声 MP3/M4A 地址(可能为空——部分受版权保护曲目 `play_url` 下无 `url_list`)。注意:**判断是否为作者原声应读布尔值 `music.is_original_sound`(而非 `music.is_original`,后者表示音乐人发行曲目)**。`url_list` 为空时 TRACE 改用顶层 `video.play_addr` 的地址(下一行:图文上它装的就是配乐),下载后仍按字节判断是不是音频;2026-11-21 实测确认部分空 `play_url` 图文的顶层 `video.play_addr` 指向字节静态域 `*.bytednsdoc.com`(返回有效 MP3 音频),已将 `bytednsdoc.com` 加入抖音媒体域名白名单,且配乐跳转与直播一样允许任意公网 HTTPS 443 域名(IP、本地主机名与 HTTP 仍拦截),失败原因写出具体错误分类与说明 |
| **视频页(图文里混排的视频,`实测(ACT-010 V-04,2026-11-13)`)** | 抖音图文支持把静态图、实况照片、独立视频页与配乐混排在同一条 `images[]` 作品中:单页含非空 `images[i].video.play_addr`(或 `bit_rate[]`)且 `live_photo_type != 1` 时,按**视频页**解析(按 §6.5 同等规则选无水印单文件 MP4 流,以 `images[i].url_list` 作该页封面;实测混排样本在 `aweme/detail` 与无 Cookie CDN 拉取/容器校验中一次通过)。未知形态单页不报错,保底保存 `images[i].url_list` 图片并标记 `unknownKind` |
| **外层 `aweme.video.play_addr`(必防陷阱!)** | 在图文作品上,顶层 `aweme.video.play_addr` 依然存在,但它里面装的是**背景音乐音频文件**(如 `.mp3` / 音频流),**绝不是视频画面**!解析器必须先判 `len(images) > 0` 走图文分支,绝不能先看 `video.play_addr != nil` 把图文误当成普通视频下载 |
@@ -395,8 +395,8 @@ TRACE 登录确认判定式(缺一不可;精确未登录错误码在 [ACT-01
- **抖音常规点播视频(含实况照片动态短片)直接返回音视频已交错封装好的完整单文件 MP4**(含视频轨 H.264/HEVC 与音频轨 AAC),下载校验字节长度一致后直接原子落盘即可播放,**无需二次混流合并**!(唯独图文作品若同时保存多张静态图、实况短片与独立配乐音频,按条目目录内多文件组织)。
2. **必要请求头与凭证隔离铁律**:
- 必带 `User-Agent`(与 API 相同的桌面 Chrome UA)与 `Referer: https://www.douyin.com/`;
- - **禁止向媒体 CDN 域名发送用户登录 Cookie**(常见官方点播与图片 CDN 后缀:`*.douyinvod.com`、`*.zjcdn.com`、`*.douyinpic.com`、`*.byteimg.com`、`*.douyinstatic.com`、`*.bdxiguaimg.com`、`*.snssdk.com`)。CDN 鉴权完全依靠 URL 查询串或路径中的签名参数,不带 Cookie 既防止会话凭证跨边缘节点泄露,也避免异常会话绑定限速。
- - 特例:极少数作品标记 `video.is_need_set_cookie == true` 且仅能走 `www.douyin.com/aweme/v1/play/` 302 跳转时,只有发往 `www.douyin.com` 的首跳属于主站域,302 落到 CDN 域名后的拉流请求仍**绝不转发 Cookie**。
+ - **禁止向媒体 CDN 域名发送用户登录 Cookie**(常见官方点播、配乐与图片 CDN 后缀:`*.douyinvod.com`、`*.zjcdn.com`、`*.douyinpic.com`、`*.byteimg.com`、`*.douyinstatic.com`、`*.bytednsdoc.com`、`*.bdxiguaimg.com`、`*.snssdk.com`)。CDN 鉴权完全依靠 URL 查询串或路径中的签名参数,不带 Cookie 既防止会话凭证跨边缘节点泄露,也避免异常会话绑定限速。
+ - 特例(2026-11-21 实测证实):部分图文视频页、实况片段或视频的 `video` 节点标记 `need_set_token == true` 或 `is_need_set_cookie == true`,其直链 `v26-web*.douyinvod.com` 携带 `ply_type=3` 策略参数、直接拉取固定返回 HTTP 403;此时 TRACE 先由已登录的 `Client.ResolvePlayRedirect` 向 `www.douyin.com/aweme/v1/play/` 发带 Cookie 且禁止自动重定向(`noRedirect`)的单次首跳,校验响应 `Location` 为合法公网 HTTPS 443 媒体地址后,再走无 Cookie 的分段下载器拉取(后续 CDN 边缘 302 仍严格要求公网 HTTPS 443,且**绝不向任何 CDN 域名发送 Cookie**)。普通未标 `need_set_token` 的作品仍优先走直链 CDN,仅在直链刷新后仍持续 403/404 时再回退该首跳解析。
3. **`Range` 分段拉取与断点续传**:
- 抖音点播 CDN(`*.douyinvod.com` 等)标准支持 `Range: bytes=-` 并返回 `HTTP 206 Partial Content` 与 `Content-Range`(`源码阅读(本机参考索引中的用户视频列表解析实现、抖音签名与访问上下文实现,2026-11-12)`;具体 8 MiB 分段表现将在 [ACT-010](#act-010) 实测核对)。
- TRACE 可直接复用[媒体与存储选型 §5](2026-11-05-media.md#download)的分段 `Range` 下载器与 `.part` 续传机制,并根据 `play_addr.data_size` 或首个 `206` 的 `Content-Range` 总长度做严格完整性校验(防提前断连残缺文件入库)。
diff --git a/docs/ui.md b/docs/ui.md
index 937a5f3..2f3f5f8 100644
--- a/docs/ui.md
+++ b/docs/ui.md
@@ -19,7 +19,7 @@
- **媒体库**(含媒体库本机详情 `/library/item`):类型(全部 / 视频 / 图片 / 直播录像 / 转发;“图片”“视频”只列作者自己的内容,转发的动态与它带的图片、视频在“转发”里,DEC-056);“来源”(全部来源、各订阅、不属于订阅的 UP 主);底部一行“N 项 · 占用大小”。
- **解析页、视频页与用户页**:“最近解析”,在解析过的对象之间切换,当前对象高亮(DEC-049 ②)。
- **我的**:按站点折叠的两组功能(哔哩哔哩、抖音),默认折叠,见[第 3.11 节](#mine)。
- - **任务**:“下载任务(N)”、“缓存队列(N)”(N 为未结束的队列数,DEC-057 ②)、“直播录制(N)”、“录制异常(N)”(N 为最近 7 天有异常的录制场数,为 0 时不带数字;DEC-050 ②、DEC-051 ③)、“检查计划”(DEC-059 ①),见[第 3.6 节](#library)。
+ - **任务**:“下载任务(N)”、“缓存队列(N)”(N 为未结束的队列数,DEC-057 ②)、“直播录制(N)”、“录制异常(N)”(N 为最近 7 天有异常的录制场数,为 0 时不带数字;DEC-050 ②、DEC-051 ③)、“检查计划”(DEC-059 ①)、“导入导出(N)”(N 为进行中与等待确认的导入导出数,为 0 时不带数字,DEC-062),见[第 3.6 节](#library)。
- **设置**:设置分类(含“更新”与“关于”等),见[第 3.7 节](#settings)。
- 登录页没有上下文侧栏。
- **页面**:白底。顶部栏(不随内容滚动)左边是返回箭头(需要时)与页面标题(18px,600),右边是**快速解析框**(链接图标 + “粘贴链接或 UID 解析”,在任何页面都能用,结果在页面里打开)和该页的操作;页面较窄时快速解析框换到标题下一行。解析页、设置页、登录页不显示快速解析框。帖子、视频与用户详情及媒体库本机详情限宽 680px 居中;解析页主面板全宽居中承载一个最宽约 640px 的大输入框;媒体库网格、任务列表、订阅头像网格用满宽度;设置限宽 860px。
@@ -38,7 +38,7 @@
3. **我的**:登录账号在站点上的关注、收藏、稍后再看、历史等([第 3.11 节](#mine),DEC-047)。
4. **解析**:粘贴链接或 UID。
5. **媒体库**:已缓存的图片、视频和直播录像。
- 6. **任务**:下载任务、缓存队列、直播录制、录制异常与检查计划;只有存在排队或进行中的下载任务时,右上角显示强调色小数字(只数这两种下载任务,不数直播录制,也不数缓存队列里等待中的条目,DEC-049 ①、DEC-050 ②)。
+ 6. **任务**:下载任务、缓存队列、直播录制、录制异常、检查计划与导入导出;只有存在排队或进行中的下载任务时,右上角显示强调色小数字(只数这两种下载任务,不数直播录制,也不数缓存队列里等待中的条目,DEC-049 ①、DEC-050 ②)。
- 底部固定当前账号的小头像(悬停显示昵称和 `UID`,点击进入账号设置,未登录时进入登录页)和**设置**(齿轮图标)。
- 不显示做不了的功能入口。
@@ -52,7 +52,7 @@
- **点开即跳转**(DEC-038):从帖子、投稿、头像、最近解析打开视频或用户页时,立刻切换到目标页面,先显示卡片上已有的标题、作者和封面,并显示“正在打开…”;读取完成后填入完整内容。失败时在该页面显示原因和“重试”。后点的覆盖先点的,已经离开的页面不会被迟到的结果拉回。
- **顶部栏**:返回箭头、页面标题、快速解析框与页面操作,不随内容滚动;页面里的标签选中项下方是一条强调色粗短线。
- **帖子**(主页信息流、订阅详情、用户页动态共用 `PostCard`,DEC-037):左边圆形头像(点击进入用户页),右边第一行“昵称 · 发布时间 · 类型”和右上角的[状态圆点](#status-dot)(主页不画,DEC-046 ⑦);正文(超过 6 行折叠,可展开);图片像站点上那样尽量完整显示(DEC-040):1 张时按原比例完整显示(竖图高 360px、宽按比例,横图最宽 480px,比例限制在 1:2 到 2.4:1 之间),2 张或 4 张排两列、其他排三列的正方形格子(最多显示 9 张,多出的在最后一格写“+N”),实况照片左上角标“实况”,图片没加载出来时是浅灰底块,不写文字;点击图片打开[看图层](#viewer)。视频是一张横向卡片:左边 200px 宽的 16:9 封面(右下角时长),右边标题(最多两行)、简介(最多两行)和清晰度规格;不显示播放数、评论数这类会变的数字,也不缓存它们;点卡片任意位置播放(已缓存时在播放层播放本机文件);转发在白底细线圆角框里显示原动态摘要;不支持的类型显示类型名说明。
- - **在主页信息流(含单个订阅视图)与订阅详情“内容”标签中**:帖子下方**不放任何文字按钮**(不显示“内置播放”“查看图片”“补存弹幕和字幕”“浏览器打开”“复制链接”“查看封面”等),直接点视频画面播放、点图片看图、点头像或昵称进用户页(DEC-037、DEC-051 ⑦)。**主页**里作者已订阅时,点头像进入这个订阅的详情,没订阅的才进用户页(DEC-057 ④);用户页(解析页)只在用户主动解析或从别处明确打开时出现。
+ - **在主页信息流(含单个订阅视图)与订阅详情“内容”标签中**:帖子下方**不放任何文字按钮**(不显示“内置播放”“查看图片”“补存弹幕和字幕”“浏览器打开”“复制链接”“查看封面”等),直接点视频画面播放、点图片看图、点头像或昵称进用户页(DEC-037、DEC-051 ⑦)。订阅详情“内容”标签的每条帖子右上角另有一个“⋯”,菜单是“在资源管理器中显示”,分隔线后红字“删除”(打开与媒体库相同的删除确认,DEC-064);主页帖子没有“⋯”。**主页**里作者已订阅时,点头像进入这个订阅的详情,没订阅的才进用户页(DEC-057 ④);用户页(解析页)只在用户主动解析或从别处明确打开时出现。
- **在用户页与动态详情中**:帖子同样**没有文字按钮**;右上角状态圆点旁一个“⋯”,菜单依次是“缓存”(仅未缓存时)、“在浏览器中打开”“复制链接”(DEC-038)。点未缓存视频的画面打开视频详情。条目之间用细线分隔,不用卡片阴影。
@@ -67,6 +67,7 @@
- 内容是所有已缓存的动态、直接缓存的视频和直播录像,不分作者,按发布时间(录像按开播时间)从新到旧排列,每条是一个帖子;录像帖子显示“直播录像”与清晰度编码规格。已缓存的视频卡片点击后在播放层播放本机文件;图片点击打开看图层看本机原图。
- **回到上次阅读的位置**(DEC-053 ①,替代 DEC-040 的“每次从最新处开始”):“全部 / B 站 / 抖音”分别记下主时间线可见区最上面那条与它顶边的偏移(滚动停下约 1 秒后、离开主页、切换筛选与关闭窗口或退出时保存)。每次启动后第一次显示某个筛选时停在那条与偏移,往上滑载入之后缓存的内容,当前看到的条目不跳动;那条被删掉时停在不晚于它的最近一条;没有记录时从最新处开始。同一次运行内切到别的页面或别的筛选再回来,回到当时的位置。单个订阅的信息流不记位置。不提示“N 条更新的内容”,往上翻过的就是看过了(DEC-040);看过的最新一条仍记为 `anchor`,作为没有 `homeSeen` 的订阅的初始已读基准。
- 抖音的作品同样是帖子(DEC-043):视频作品按视频卡片(竖版封面在左、文案在右),图文作品按图文帖子显示图片,并在图片下方显示配乐条([§3.4](#douyin-pages));作者行带站点小字。主页上下文侧栏“全部动态”下面有站点筛选“全部 / B 站 / 抖音”(窄窗时是时间线上方的三段式切换),默认“全部”,记在 `ui-state.json`(FR-SITE-002)。
+- **作者行的订阅名**(DEC-063 ②):帖子的账号名后面用小一号(13px)的强调色文字显示它所属订阅的名称,不加“订阅”二字;订阅名与账号名相同时不重复显示;点账号名或订阅名打开这个订阅。为订阅账号缓存的共创或合作作品按这个账号的订阅显示。
- 底部到头时显示“已经到最早的缓存了”。
- 分页读取失败保留帖子并显示“重试”,等待用户重试;查看时间保存失败显示原因,“看最新”失败仍停在原位置。主页缺少本机图片时使用占位图,不自动补发远程图片请求。
- 空状态:“还没有缓存的内容。到‘解析’里打开一位 UP 主或抖音作者,在动态或作品上点‘缓存’”,带一个去解析页的按钮。
@@ -122,12 +123,14 @@
### 3.6 媒体库与任务
-- **媒体库**(图标栏“媒体库”,DEC-037、DEC-039、DEC-049 ③):独立的离线浏览页面。顶部栏标题“媒体库”(“重建索引”在设置“存储”);搜索框右侧一个“刷新”按钮(DEC-055):在后台重新检查保存位置里的文件(只看文件在不在、大小对不对,不算哈希、不联网,进行中显示“正在刷新…”),完成后弹窗列出这次发现的变化——“文件夹已删除,已从媒体库移除(N)”(标题与文件夹路径)和“缺少文件(N)”(标题与缺少的文件名,最多列 6 个),没有变化时写“检查了 N 个条目,没有发现被删除的文件。”,底部“知道了”;类型与来源在上下文侧栏(窄窗时退回为页面里的标签“全部 / 图片 / 视频 / 直播录像 / 转发”和“作者筛选”);页面里一行搜索框,**固定按发布时间从新到旧排序**(直播录像按开播时间;不再提供“发布时间 / 缓存时间”切换,已保存的旧缓存时间排序偏好静默忽略)。来源分组里加站点筛选“全部 / B 站 / 抖音”,与类型、作者筛选叠加(FR-SITE-002)。
+- **媒体库**(图标栏“媒体库”,DEC-037、DEC-039、DEC-049 ③):独立的离线浏览页面。顶部栏标题“媒体库”(“重建索引”在设置“存储”);搜索框右侧一个“刷新”按钮(DEC-055):在后台重新检查保存位置里的文件(只看文件在不在、大小对不对,不算哈希、不联网,进行中显示“正在刷新…”),完成后弹窗列出这次发现的变化——“文件夹已删除,已从媒体库移除(N)”(标题与文件夹路径)和“缺少文件(N)”(标题与缺少的文件名,最多列 6 个),没有变化时写“检查了 N 个条目,没有发现被删除的文件。”,底部“知道了”;类型与来源在上下文侧栏(窄窗时退回为页面里的标签“全部 / 图片 / 视频 / 直播录像 / 转发”和“作者筛选”);页面里一行搜索框,**固定按发布时间从新到旧排序**(直播录像按开播时间;不再提供“发布时间 / 缓存时间”切换,已保存的旧缓存时间排序偏好静默忽略)。来源分组里加站点筛选“全部 / B 站 / 抖音”,与类型、作者筛选叠加(FR-SITE-002)。顶部栏右侧一个“⋯”(菜单“导入…”“导出…”,DEC-062)。
+ - **导入页**(“⋯ → 导入…”,[远程 §6.3](design/remote.md#import)):在媒体库里打开,标题“导入”,左上角返回箭头回到媒体库,上下文侧栏仍是媒体库侧栏,内容宽度最多约 760px。上方“选择要导入的文件夹”、一行说明(网盘下载的文件夹、另一台 TRACE 的缓存或导出文件夹都可以;先只读扫描,确认后才写入)、路径输入框与强调色“扫描”(扫描中“正在扫描…”,下面一行“正在扫描:已检查 N 个条目”与“取消”)。扫描完成后:一行摘要“扫描到 N 个条目:M 个会导入(约 X),K 个冲突等你决定”;一排可点的分类胶囊“全部 N · 新条目 · 可补充 · 相同 · 冲突 · 未传完 · 无法识别”(各带条数,点了只看这一类);有冲突时一行“全部冲突都:[暂不处理 / 保留本地 / 用导入的 / 合并]”与小字“逐条选的优先”;下面每个条目一张细边框卡片:分类小标签、标题,冲突条目右侧一个同样的下拉框,一行小字(作者、“来自 <节点名>”、要复制的文件数与大小、缺失或不一致的文件数、内容不同的文件名、“本地在另一个作者文件夹”、无法识别的原因),一行来源文件夹路径;最多列 200 条,超出时说明“只显示前 200 条;导入会处理全部条目”。底部固定一条操作栏:开关“导入后删除来源里已导入的文件”(说明只删校验通过并已导入的文件和变空的文件夹,默认关),右侧“放弃”与强调色“开始导入”;开始后跳到任务页“导入导出”。扫描失败、取消时在原处说明。
+ - **导出**(“⋯ → 导出…”,[远程 §6.4](design/remote.md#export-local)):对话框,标题“导出媒体库”、一行说明、“范围”下拉(“全部”;媒体库当前有类型、站点、来源或搜索筛选时另有“当前筛选”)、目标文件夹输入框,“取消”与强调色“开始导出”;目标为空、范围内没有内容时在框下说明原因;开始后跳到任务页“导入导出”。
- 网格:卡片约 240px 宽,按页面宽度每行 2~6 个;**16:9 圆角缩略图**(圆角 14px),视频右下角显示时长、正中播放图标;**不显示状态圆点**(媒体库里都是已缓存的内容,DEC-039);缩略图下方是**最多两行的标题**(14px,600)、一行元信息(作者名,直播录像附清晰度与编码如“原画 · AVC”)和右侧一个“⋯”按钮。虚拟滚动,滚到底继续加载。
- 点击缩略图或标题直接在原地打开对应文件的看图层或**播放层**(DEC-033、DEC-037、DEC-049 ③),不按网格位置猜测分 P、不跳转到解析路由、不发任何站点网络请求;点击右下角“⋯”展开菜单:**详情**(在媒体库自己的本机详情路由 `/library/item` 打开所属动态、视频、作品或直播录像,保持“媒体库”图标高亮与媒体库侧栏,返回时保留原筛选与滚动位置,只读本机数据,仅在详情“⋯”里留“在解析页打开”作为明确联网入口)、**在资源管理器中显示**、**删除**。播放层和看图层一样是浮在应用上方的深色圆角面板(点面板外关闭;全屏时铺满窗口),**打开即自动播放**(DEC-040),底部悬浮条只保留圆形**播放/暂停**、**进度条**、**音量**、**全屏**,右上角保留圆形**“⋯”更多菜单**与**关闭**。音量按钮展开 0~100% 滑块与静音开关;全屏作用于原生窗口,切分段保持全屏,关闭播放或登录失效时恢复。**弹幕**(开关、透明度滑块 20%~100%、显示区域上方 1/4 / 上半屏 / 全屏、密度低/中/高/不限)、**字幕**(语言选择与关闭)、**分段切换**(多 P 或多段直播录像的“上一段 / 下一段”)、**在文件夹中显示**、**用系统播放器打开**统一收进“⋯”菜单。鼠标静止约 2 秒后悬浮控件自动隐藏,鼠标移动或任意按键时重新出现;菜单打开时保持控件可见。音量、静音、弹幕与字幕偏好记住并沿用,保存失败显示原因。
- - 每个条目的“删除”打开确认弹窗:写明预计清理的已登记缓存文件数与大小;共用视频时说明“这个视频还被 N 条动态引用,将保留视频文件”;删除后文件夹里还有非 TRACE 文件时提示“已保留 N 个不是 TRACE 创建的文件”。
+ - 每个条目的“删除”打开确认弹窗:写明预计清理的已登记缓存文件数与大小;标题行写“类型:标题”(动态没有标题时用正文第一行);删除动态时说明一并删除的引用视频数,以及“这条动态引用的 N 个视频单独缓存过或还被别的动态引用,将保留”;删除后文件夹里还有非 TRACE 文件时提示“已保留 N 个不是 TRACE 创建的文件”。
- 空状态:“还没有符合筛选的媒体。缓存图片、视频或直播录像后,它们会出现在这里”。
-- **任务**(图标栏“任务”,DEC-049 ①、DEC-050 ②、DEC-051 ③):通过上下文侧栏(≥ 1000 宽;窄窗 `< 1000` 时退回为页面顶部的分段选择)组织五部分内容,点哪一项主面板显示哪一项:
+- **任务**(图标栏“任务”,DEC-049 ①、DEC-050 ②、DEC-051 ③):通过上下文侧栏(≥ 1000 宽;窄窗 `< 1000` 时退回为页面顶部的分段选择)组织六部分内容,点哪一项主面板显示哪一项:
1. **下载任务(N)**(N 为排队与进行中的下载任务数,与图标栏“任务”角标一致):顶部栏右侧提供“检查画质更新”按钮(执行时显示“检查 M / N · 取消”),存在已结束(已完成 / 已取消)的任务时提供“清除已结束(N)”按钮。每行是对象缩略图、标题、站点小字、进度条与“已下载 / 总大小”、状态文字和操作(进行中/排队可暂停或取消;已暂停可继续;失败/部分完成可重试或移除;已完成/已取消可移除,不能取消;DEC-033)。失败原因(`LastError`)直接显示在任务行内;移除失败或部分完成的任务前,行内弹出确认提示“确认移除该任务?会删除未完成的临时文件,已缓存完成的文件会保留”。点“展开详情”(FR-CACHE-009)显示逐文件进度清单与脱敏后的分段重试记录。
2. **缓存队列(N)**(DEC-057 ②,替代每个队列占侧栏一行;N 为未结束的队列数):主面板顶部一行小字“取消或移除队列不会删除已缓存到媒体库的内容”,有结束的队列时右侧“清除已结束(N)”;下面每个队列一张卡片:头像、“账号名称 · 列表类型”、站点小字、状态(或下次时间)与“已缓存 x · 跳过 y”,右侧展开箭头与操作(进行中“暂停”“取消”,已暂停“继续”“取消”,已结束“移除”)。点卡片展开:当前正在缓存的条目、暂停或等待的原因、“最近缓存的内容”(本机封面——动态没有图片时用它引用的视频封面——、标题与缓存时间,点击直接打开本机内容)。从用户页“在缓存队列中查看”进入时展开对应的卡片。
3. **直播录制(N)**(N 为正在录制的场数):列出正在录制的直播行与最近结束的录制行(主播头像、直播标题、站点小字、橙色“录制中”标记、已录时长、大小、速度、段数与清晰度编码如“原画 · AVC”,进行中右侧“停止录制”);有录制异常的场次在行上显示“⚠ N 处异常”小字(可点开查看异常);没有录制在进行时显示“现在没有直播在录制”。
@@ -135,6 +138,7 @@
- **页内实时预览**(DEC-049 ①):在“直播录制”里点击一场正在录制的直播,在页面内直接实时播放正在写入的 `.part` 分片 MP4 画面(边写边读本机录制文件并等待新分片,**不另开任何站点连接**;画面落后直播约 10 秒以内;预览区不渲染弹幕、也不显示弹幕开关,实时弹幕留待下一阶段 FR-LIVE-003)。离开“直播录制”视图(含切到“录制异常”等其他组)或任务页、切换预览对象或停止录制时立即停止预览并同步释放文件句柄,换段时跟随新段或平滑结束,不影响 `.part` 的收尾转换与改名;若某条录制路径不支持实时预览,页面如实说明“这场录制暂不支持实时预览”。
4. **录制异常(N)**(DEC-051 ③;N 为最近 7 天含进行中有异常的录制场数,为 0 时显示“录制异常”不带数字):按录制场次列出(主播/直播间、站点小字、开始时间,以及该场的异常列表:发生时间、类型的中文说明——断流重连、因网速跟不上丢失片段及估算秒数或重连空档秒数、连续 30 秒速度低于码率及持续时长、空间不足、收尾转换失败——与影响时长或段数);已结束的场次点击可打开本机离线录像详情(`/library/item`,同媒体库,不发网络请求),右侧红色描边按钮“删除记录”删除这一场的异常记录(录像不删,正在录制的场次没有这个按钮,DEC-057 ①);没有异常记录时显示空状态说明。
5. **检查计划**(DEC-059 ①):顶部一行“下一轮定时检查:今天 21:07”(定时检查关闭时说明),下面两行小字:更新检查每轮每个站点最多检查的账号数、上次查得早的先查、额度不足或退避时顺延;开播检查的规则摘要(B 站每轮查全部,抖音两次至少隔 6 秒、一轮最多几个、超过后轮流查、不占每小时额度,完整规则见设置 › 订阅与直播,DEC-060 ⑤)。每个订阅账号一张卡片:头像、昵称、站点小字、所属订阅名;“更新检查:上次 今天 20:07 · 正常”(从未检查时“还没有检查过”,失败时红字写原因,如“本小时额度用完,已顺延”);开了“开播录制”的订阅再加一行“开播检查:上次 今天 20:51 · 约每 3 分钟”;右侧“下次 今天 21:07”(退避时“退避后 …”),或“只手动检查”“定时检查已关闭”“未登录,不检查”。按下次检查时间排列,不发站点请求,每 20 秒重读一次本机状态。顶部右侧“检查全部”,检查进行中换成“正在检查 x / y”与“取消”;每张卡片最右“检查”只查这一个账号,查的时候显示“检查中…”,其他卡片的按钮暂不可用,未登录站点的账号按钮不可用(DEC-060 ③)。
+ 6. **导入导出(N)**(DEC-062):本次运行里的导入与导出,新的在上。每个一张卡片:上传图标、“导入 · <来源文件夹>”或“导出 · <目标文件夹>”、右侧状态(正在扫描 / 等待确认 / 正在导入 / 正在导出 / 已完成 / 失败 / 已取消);进行中有进度条、“已复制 / 总大小 · 速度”(扫描时“已检查 / 总数”)、“取消”与当前条目名;扫描完等待确认的写各分类条数,右侧“放弃”与强调色“查看预览”(回到导入页);结束后一行摘要(导入:“新增 · 补充 · 跳过 · 处理冲突 · 未传完 · 复制 N 个文件(大小)”,勾了删除来源时附删除的文件数;导出:“导出 N 个条目 · M 个文件(大小)”及本地已缺失的文件数),失败原因与没完成的条目红字列出。没有任务时空状态“还没有导入或导出”,说明从媒体库右上角“⋯”开始。
### 3.7 设置页(DEC-019)
@@ -155,6 +159,7 @@
- **存储**:安装位置、数据目录、缓存位置(只读路径 + “打开文件夹”、“重建索引”,缓存位置的修改也在本页);显示当前是正式版还是开发版;媒体库占用空间;“添加已有的缓存文件夹”(选择文件夹后显示“接入了 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` 后把连接码粘贴到这里)、“远程连接码”输入框(或切换为分别填写地址、令牌、证书指纹三个输入框)、强调色“连接”(连接中“正在连接…”)与“分别填写地址、令牌与指纹 / 粘贴连接码”切换;失败时红字写原因(无法连接、证书变了、令牌错、版本不同各自的文案);底部小字说明只连接指纹一致的远程、令牌存本机凭证。连接后:顶部一张浅灰卡片(名字、地址 · 版本 · 已运行时长、证书指纹缩写,右侧“刷新”与红色描边“断开”,断开前行内确认);有错误时一条红底提示;下面按细线分节——**订阅**(“已同步”绿点或“有改动未同步”、远程订阅与账号数、上次同步时间,右侧强调色“同步订阅”,一行说明远程只缓存同步之后的新内容、“全部缓存”不在远程执行);**登录**(每个站点一行:状态圆点与“有效 · 昵称 · Cookie 同步于 …”/“需要重新同步”/“未登录”/“退避到 …”,本地标了“Cookie 待同步”时写出来,右侧“同步 Cookie”,有登录时另有红色描边“清除远程登录”;一行说明自动推送与远程不续期);**检查与缓存**(定时检查的账号数与下次时间、缓存中与排队数、录制中的场次、最近完成与失败);**上传与空间**(上传方式与目标、待上传条目与大小、今天已传、正在上传的条目、最近一次失败的原因与下次重试,rclone 找不到等按类别说明;导出目录剩余 / 总空间,低于 5 GiB 警告、低于 1 GiB 写“已暂停新的缓存”);**最近错误**(时间、类别、脱敏说明)。页面显示时每 30 秒刷新一次,离开页面不请求远程。
- **日志**(终端/日志图标,DEC-033):上方“后台状态”卡片显示索引重建、检查更新、自动缓存、直播录制的当前情况;下方“最近运行日志”卡片以等宽字体显示脱敏后的最近运行日志(最多 500 行,经服务层接口读取,不含任何 Cookie 或签名 URL),右上角提供“打开日志文件夹”和“复制”按钮。
- **更新**(刷新图标 `refresh`,放在“关于”之前,路径 `/settings/update`,DEC-051 ①,FR-UPD-001~003):按细线分隔自上而下展示:① 当前版本区域:应用名(TRACE / TRACE Dev)、版本与通道(“正式版”或“开发版”)、“提交 1a2b3c4d5e6f · 构建于 2026-11-09 15:30 UTC”;② 更新方式一句话:正式版显示“打开 TRACE 时每 24 小时自动检查一次(可在下面关闭),也可以立即检查”,开发版显示“开发版不会自己联网检查;Agent 打包后会自动安装,正在运行的 TRACE Dev 会先退出,装完在托盘打开”;③ 通道专属区:正式版展示上次检查(时间与结果:已是最新 / 发现 `x.y.z` / 失败原因;没检查过写“还没有检查过”)、下次检查时间、右侧按钮(平时“立即检查”,检查中“正在检查…”不可点,有新版本未下载时“下载并安装”,已就绪时“重启以更新”)以及两行开关“自动检查更新”“自动下载更新”(默认开,改动立即保存;没有联网更新的构建写“这个构建没有联网更新”);开发版不显示检查按钮与开关,显示“本机安装的开发版”(读取卸载项版本,未安装时如实说明;已安装版本高于正在运行的版本时提示“已安装更新的版本,重启 TRACE Dev 后生效”);④ **检查记录**(最近 20 次:时间、自动/手动、结果;开发版说明不联网检查)与**更新记录**(最近 50 次:时间、从哪个版本到哪个版本、方式:自动更新 / 本机打包安装 / 手动安装)。
- **关于**(FR-UPD-001、DEC-051 ①):应用名(TRACE / TRACE Dev)、版本与通道、提交与构建时间;一行“版本与更新见‘更新’”(点击跳转到设置“更新”分类,不再重复放检查按钮与开关);下方是诊断概览与第三方开源许可说明。
@@ -179,7 +184,8 @@
**订阅列表** `/subscriptions`:
-- 顶部栏标题“订阅”,右侧只放一个强调色主按钮“添加订阅”和一个“⋯”(菜单“检查全部”“从 B 站关注列表导入”;检查进行中时顶部显示“正在检查 M / N”和“取消”按钮)。
+- 顶部栏标题“订阅”,右侧只放一个强调色主按钮“添加订阅”和一个“⋯”(菜单“检查全部”“从 B 站关注列表导入”“导出订阅…”“导入订阅…”;检查进行中时顶部显示“正在检查 M / N”和“取消”按钮)。
+- **导出订阅 / 导入订阅**(DEC-062,[远程 §6.4](design/remote.md#export-local)):都是对话框。导出:标题“导出订阅”、一行说明(订阅、关联账号、缓存规则和部分设置,不含 Cookie;填文件夹时自动补上文件名)、路径输入框、“取消”与强调色“导出”,成功后顶部提示“订阅已导出到 <文件>”。导入:标题“导入订阅”、路径输入框(文件或它所在的文件夹)与“预览”;预览一行摘要“新订阅 N 个 · 已订阅的账号 N 个 · 新规则 N 个 · 规则不同 N 个 · 已全部订阅 N 个”,下面分节列出新订阅(名称、账号数、规则名)、已在订阅里的账号(昵称、站点、本地在哪个订阅)与开关“把导入订阅里的新账号合并进这些已有订阅”(默认关:跳过已订阅的账号,其余账号建成新订阅)、内容不同的规则(每条一个开关“用导入的“<规则名>””,说明两边的摘要,默认保留本地);底部“取消”与强调色“确认导入”(有预览后才出现),成功后关闭并提示新增的订阅数,失败在框内说明、什么都不改。
- 顶部栏下面一个搜索框(按订阅名、备注和账号昵称过滤,只在本机过滤)。
- 主体是**较大的圆形头像网格**(头像约 92px,下方一行订阅名称,过长自动省略),按可用宽度自动排列列数(3~5 列),按行虚拟化滚动(NFR-UI-002)。
- 正在直播的订阅头像外有橙色直播圆环,头像下沿带橙色胶囊小标“直播”(正在录制时带红点与“录制中”);点击该直播/录制小标即可一键开始或停止录制,点击头像或名称进入订阅详情 `/subscriptions/:id`。
@@ -194,7 +200,7 @@
- 顶部返回箭头与订阅名。详情头部(不套卡片)只有大头像、订阅名(及备注说明)、一个**规则按钮**“规则:<规则名> ▾”和一个“⋯”(菜单“检查更新”“改名”“备注”“更换头像”,分隔线后红字“删除订阅”;检查中头部附“取消检查”)。规则按钮弹出全部缓存规则(名称与摘要,当前规则打勾),选一条立即生效,最后一项“管理缓存规则”进入设置的“缓存规则”(DEC-040)。
- 标签栏只有两个:**内容**(默认,`tab=content`)、**账号**(`tab=accounts`;旧保存状态或路由里的 `live` 读入时自动归到“账号”,DEC-051 ⑦,替代 DEC-040 的“直播 / 账号”标签;不再有“更新”“已缓存”“规则”标签):
- - **内容**(默认):这个订阅**全部关联账号**(含同时关联的哔哩哔哩与抖音账号)已缓存内容的信息流(动态、视频、作品与已录制的直播录像帖子),与主页时间线(及主页“有更新”点进单订阅视图)共用同一套帖子渲染、虚拟化列表与滚到底自动加载更早内容,固定按发布时间(录像按开播时间)从新到旧排列,全程只读本机索引与清单、零站点网络请求;没有已缓存内容时显示“还没有缓存这个订阅的内容”,并提示可在右上角“⋯”菜单点“检查更新”,不加额外强调色主按钮。
+ - **内容**(默认):这个订阅**全部关联账号**(含同时关联的哔哩哔哩与抖音账号)已缓存内容的信息流(动态、视频、作品与已录制的直播录像帖子),与主页时间线(及主页“有更新”点进单订阅视图)共用同一套帖子渲染、虚拟化列表与滚到底自动加载更早内容,固定按发布时间(录像按开播时间)从新到旧排列,全程只读本机索引与清单、零站点网络请求;每条帖子右上角的“⋯”可“在资源管理器中显示”与“删除”,用来清理异常的缓存(含只有文字或图片的动态,DEC-064),删除后列表从最新处重新载入;没有已缓存内容时显示“还没有缓存这个订阅的内容”,并提示可在右上角“⋯”菜单点“检查更新”,不加额外强调色主按钮。
- **账号**(合并原“直播”):每个关联账号一行——第一行显示头像(优先使用本机头像副本,DEC-051 ⑥)、昵称、站点小字(“B 站”/“抖音”)、UID 或抖音号;第三行是与“全部账号”相同的作品数(DEC-061 ②,打开页面不发请求);第二行显示直播状态(未开通直播间 / 未开播 / 直播中“标题 · 清晰度与编码,如 原画 · AVC” / 录制中“已录 时长 · 大小”及清晰度编码)。行右侧在直播中或录制中时放置“录制”(强调色主按钮)或“停止录制”按钮;其余操作收进该行的“⋯”菜单(“打开主页”、“在浏览器中观看”、“用作头像”、“解除关联”、“刷新直播状态”)。已录制的录像不再在这里重复列出(在“内容”标签里作为直播录像帖子出现)。底部保留“关联另一个账号:粘贴主页链接或 UID”输入框与预览确认卡片(未直播时确认按钮为该标签页唯一的强调色主按钮)。
- 删除订阅确认框:“删除订阅‘X’?只删除这个订阅和它的账号关联,不删除已缓存的内容,也不会在站点上取消关注。”按钮“确认删除订阅”与“取消”。
diff --git a/go.mod b/go.mod
index 0f95083..5345159 100644
--- a/go.mod
+++ b/go.mod
@@ -3,26 +3,32 @@ module github.com/chialecode/trace
go 1.27.4
require (
- github.com/Eyevinn/mp4ff v0.62.0
- github.com/egoist/mygo v0.8.3
+ github.com/Eyevinn/mp4ff v0.63.0
+ github.com/egoist/mygo v0.9.0
github.com/yeqown/go-qrcode/v2 v2.3.0
- golang.org/x/image v0.47.0
+ golang.org/x/image v0.48.0
golang.org/x/sys v0.50.0
google.golang.org/protobuf v1.36.12
modernc.org/sqlite v1.62.0
)
require (
+ github.com/ProtonMail/go-crypto v1.4.1 // indirect
+ github.com/cloudflare/circl v1.6.2 // indirect
github.com/dustin/go-humanize v1.1.0 // indirect
github.com/ebitengine/purego v0.11.1 // indirect
github.com/go-text/typesetting v0.3.5 // indirect
github.com/google/uuid v1.6.0 // indirect
+ github.com/klauspost/compress v1.18.6 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/ncruces/go-strftime v1.1.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
+ github.com/ulikunitz/xz v0.5.15 // indirect
github.com/yeqown/reedsolomon v1.0.0 // indirect
+ go.digitalxero.dev/rpm v0.3.4 // indirect
+ golang.org/x/crypto v0.57.0 // indirect
golang.org/x/net v0.59.0 // indirect
- golang.org/x/text v0.43.0 // indirect
+ golang.org/x/text v0.44.0 // indirect
modernc.org/libc v1.80.1 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.12.1 // indirect
diff --git a/go.sum b/go.sum
index 99dde4e..af722a0 100644
--- a/go.sum
+++ b/go.sum
@@ -1,13 +1,17 @@
-github.com/Eyevinn/mp4ff v0.62.0 h1:Vx4U0xUfSdcwEgw1wBbTZ53+yZhlJpT7eIAkLUDaxmM=
-github.com/Eyevinn/mp4ff v0.62.0/go.mod h1:97zsDIJUiDTYqKpqq/b1K9foamxXmvsgE4GdPrPK3ks=
+github.com/Eyevinn/mp4ff v0.63.0 h1:u5ys+KWdmLAifmNeXrW3AUKkYQ1JDD9e4tVqtja2NKw=
+github.com/Eyevinn/mp4ff v0.63.0/go.mod h1:97zsDIJUiDTYqKpqq/b1K9foamxXmvsgE4GdPrPK3ks=
+github.com/ProtonMail/go-crypto v1.4.1 h1:9RfcZHqEQUvP8RzecWEUafnZVtEvrBVL9BiF67IQOfM=
+github.com/ProtonMail/go-crypto v1.4.1/go.mod h1:e1OaTyu5SYVrO9gKOEhTc+5UcXtTUa+P3uLudwcgPqo=
+github.com/cloudflare/circl v1.6.2 h1:hL7VBpHHKzrV5WTfHCaBsgx/HGbBYlgrwvNXEVDYYsQ=
+github.com/cloudflare/circl v1.6.2/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/ebitengine/purego v0.11.1 h1:2zpWRSQNVKN4eKsKO9eM1ILDgWfYMY9GwqRmK6XeQ/0=
github.com/ebitengine/purego v0.11.1/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ=
-github.com/egoist/mygo v0.8.3 h1:aTLEhS221YhsX+gKGNLQ5xEKMLCcYYr3pH9AkTwIRs4=
-github.com/egoist/mygo v0.8.3/go.mod h1:dVav53PwF2xEotjf4oA5lTY2Jp2exgzyjLhbSXhbMwE=
+github.com/egoist/mygo v0.9.0 h1:zGeZTskZ7HNTrKdkh/uEX+OOg+7YTjFMNjiTdie7XU4=
+github.com/egoist/mygo v0.9.0/go.mod h1:Hw9sxdSQ4tHuehHw5Q6alR1qTS8kgv3oSFxEejg+7qo=
github.com/go-test/deep v1.1.0 h1:WOcxcdHcvdgThNXjw0t76K42FXTU7HpNQWHpA2HHNlg=
github.com/go-test/deep v1.1.0/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
github.com/go-text/typesetting v0.3.5 h1:XZPUooClHY0Vf/rFyUyuPRNEkawARaFzLMQcXLSEyPk=
@@ -20,6 +24,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
+github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
+github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
@@ -30,22 +36,28 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
+github.com/ulikunitz/xz v0.5.15 h1:9DNdB5s+SgV3bQ2ApL10xRc35ck0DuIX/isZvIk+ubY=
+github.com/ulikunitz/xz v0.5.15/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
github.com/yeqown/go-qrcode/v2 v2.3.0 h1:MMsNJgZrG95g8SOGGGaGcEZkOt1ByHjeCLSaymGm9aY=
github.com/yeqown/go-qrcode/v2 v2.3.0/go.mod h1:WBrb4qHlVtggZtquxDyMq+Uv+R4xtUaz4laG2iqG34s=
github.com/yeqown/reedsolomon v1.0.0 h1:x1h/Ej/uJnNu8jaX7GLHBWmZKCAWjEJTetkqaabr4B0=
github.com/yeqown/reedsolomon v1.0.0/go.mod h1:P76zpcn2TCuL0ul1Fso373qHRc69LKwAw/Iy6g1WiiM=
-golang.org/x/image v0.47.0 h1:za/8gVz++PPZqmZJBNSISICN5Rrj5zixP/8K++fgmqo=
-golang.org/x/image v0.47.0/go.mod h1:IkN5o4A7vq55vXN8FWjjnhg9Rs2GOtffqsSi9mWAKYE=
+go.digitalxero.dev/rpm v0.3.4 h1:iq+rx7zB6wQeNhLQ1mcvW92v9ZqNaxCvuu0+nPVit4w=
+go.digitalxero.dev/rpm v0.3.4/go.mod h1:45EsEzHamzqInyWQx9vpj7OYpL0BrkbQF87VdrLn5wo=
+golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
+golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
+golang.org/x/image v0.48.0 h1:1AvuPcuoOTJpA7s4VZ5umrb90T3So0rkB/bSGmxkxik=
+golang.org/x/image v0.48.0/go.mod h1:mmtg64iqJKGqEgy+r13dfybl85tmxUd2lMnmaiSdWYY=
golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
-golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
-golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
+golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
+golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
-golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
-golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
+golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
+golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
diff --git a/internal/appdirs/appdirs.go b/internal/appdirs/appdirs.go
index b4f15e9..d373680 100644
--- a/internal/appdirs/appdirs.go
+++ b/internal/appdirs/appdirs.go
@@ -240,11 +240,16 @@ func ResolveWithOptions(opts Options) (Locations, error) {
var err error
docsDir, err = resolveDocumentsDir()
if err != nil || docsDir == "" {
- home, _ := os.UserHomeDir()
- docsDir = filepath.Join(home, "Documents")
+ if home, hErr := os.UserHomeDir(); hErr == nil && strings.TrimSpace(home) != "" {
+ docsDir = filepath.Join(home, "Documents")
+ }
}
}
- defaultCacheDir = filepath.Join(docsDir, appName)
+ if docsDir != "" {
+ defaultCacheDir = filepath.Join(docsDir, appName)
+ } else {
+ defaultCacheDir = filepath.Join(dataDir, "library")
+ }
}
}
defaultCacheDir = filepath.Clean(defaultCacheDir)
diff --git a/internal/appdirs/appdirs_test.go b/internal/appdirs/appdirs_test.go
index 1f33990..00b6072 100644
--- a/internal/appdirs/appdirs_test.go
+++ b/internal/appdirs/appdirs_test.go
@@ -136,10 +136,6 @@ func TestLockDataDirExclusive(t *testing.T) {
_ = lock2.Release()
}
-func TestLocationsByChannel(t *testing.T) {
- TestResolvePortableAndInstalledPaths(t)
-}
-
func TestDocumentsKnownFolderRedirect(t *testing.T) {
tmp := t.TempDir()
redirectedDocs := filepath.Join(tmp, "OneDrive", "Documents")
@@ -158,14 +154,6 @@ func TestDocumentsKnownFolderRedirect(t *testing.T) {
}
}
-func TestAllTracePathsLowercase(t *testing.T) {
- TestResolvePortableAndInstalledPaths(t)
-}
-
-func TestDataDirExclusiveLock(t *testing.T) {
- TestLockDataDirExclusive(t)
-}
-
func assertRelativeLowercase(t *testing.T, base, target string) {
t.Helper()
rel, err := filepath.Rel(base, target)
diff --git a/internal/appdirs/lock_other.go b/internal/appdirs/lock_other.go
index 3f3d0c8..660ea09 100644
--- a/internal/appdirs/lock_other.go
+++ b/internal/appdirs/lock_other.go
@@ -3,6 +3,7 @@
package appdirs
import (
+ "errors"
"fmt"
"os"
"path/filepath"
@@ -28,7 +29,10 @@ func LockDataDir(dataDir string) (*Lock, error) {
if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
_ = f.Close()
- return nil, ErrAlreadyLocked
+ if errors.Is(err, syscall.EWOULDBLOCK) || errors.Is(err, syscall.EAGAIN) {
+ return nil, ErrAlreadyLocked
+ }
+ return nil, fmt.Errorf("appdirs: lock %s: %w", lockPath, err)
}
return &Lock{
@@ -37,14 +41,6 @@ func LockDataDir(dataDir string) (*Lock, error) {
}, nil
}
-// Path returns the locked file path.
-func (l *Lock) Path() string {
- if l == nil {
- return ""
- }
- return l.path
-}
-
// Release unlocks and closes the lock file.
func (l *Lock) Release() error {
if l == nil || l.file == nil {
diff --git a/internal/appdirs/lock_windows.go b/internal/appdirs/lock_windows.go
index 8ed1746..7f62192 100644
--- a/internal/appdirs/lock_windows.go
+++ b/internal/appdirs/lock_windows.go
@@ -42,7 +42,7 @@ func LockDataDir(dataDir string) (*Lock, error) {
if errors.Is(err, windows.ERROR_LOCK_VIOLATION) || errors.Is(err, windows.ERROR_IO_PENDING) {
return nil, ErrAlreadyLocked
}
- return nil, fmt.Errorf("%w: %v", ErrAlreadyLocked, err)
+ return nil, fmt.Errorf("appdirs: lock %s: %w", lockPath, err)
}
return &Lock{
diff --git a/internal/appdirs/proc_windows.go b/internal/appdirs/proc_windows.go
index 9deacf3..5c5c990 100644
--- a/internal/appdirs/proc_windows.go
+++ b/internal/appdirs/proc_windows.go
@@ -15,13 +15,13 @@ var (
const belowNormalPriorityClass = 0x00004000
-// LowerCurrentProcessPriority sets the current process priority to BELOW_NORMAL_PRIORITY_CLASS (§6).
+// LowerCurrentProcessPriority sets the current process priority to BELOW_NORMAL_PRIORITY_CLASS.
func LowerCurrentProcessPriority() {
h, _, _ := procGetCurrentProc.Call()
_, _, _ = procSetPriorityClassW.Call(h, uintptr(belowNormalPriorityClass))
}
-// SetSubprocessQuiet configures cmd so it hides console windows and runs at BELOW_NORMAL_PRIORITY_CLASS (§6).
+// SetSubprocessQuiet configures cmd so it hides console windows and runs at BELOW_NORMAL_PRIORITY_CLASS.
func SetSubprocessQuiet(cmd *exec.Cmd) {
if cmd == nil {
return
diff --git a/internal/credential/credential.go b/internal/credential/credential.go
index c2e1f7b..539f4ba 100644
--- a/internal/credential/credential.go
+++ b/internal/credential/credential.go
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"net/http"
+ "net/url"
"os"
"path/filepath"
"sort"
@@ -179,12 +180,17 @@ func parseRawCookieHeader(rawCookie string) map[string]string {
return pairs
}
-// FilterCookieMap filters a map of cookies down to the 5 whitelisted Bilibili keys.
+func isSafeCookieValue(v string) bool {
+ return v != "" && !strings.ContainsAny(v, "\r\n;")
+}
+
+// FilterCookieMap filters a map of cookies down to the 5 whitelisted Bilibili keys,
+// rejecting empty values and values containing CR/LF/semicolon header delimiters.
func FilterCookieMap(in map[string]string) map[string]string {
out := make(map[string]string)
for k, v := range in {
v = strings.TrimSpace(v)
- if v == "" {
+ if !isSafeCookieValue(v) {
continue
}
if canonicalKey, ok := allowedKeyLookup[strings.ToLower(strings.TrimSpace(k))]; ok {
@@ -248,7 +254,7 @@ func openWithConfig(siteID string, entropy []byte, path string) (*Store, string,
return nil, "", err
}
- plain, err := decryptBytesWithEntropy(raw, s.entropy)
+ plain, err := unprotectFor(path, raw, s.entropy)
if err != nil {
backup, bErr := backupCorruptFile(path)
if bErr != nil {
@@ -352,14 +358,25 @@ func (s *Store) Status() Status {
return s.buildStatus(s.rec)
}
+func (s *Store) isActiveRecordLocked() bool {
+ if s == nil || s.rec == nil {
+ return false
+ }
+ return s.rec.State != "expired" && s.rec.State != "logged_out" && s.rec.State != "decrypt_failed"
+}
+
+func (s *Store) requireSite(want string) error {
+ if s.Site() != want {
+ return fmt.Errorf("credential: store site %q cannot accept %q operation", s.Site(), want)
+ }
+ return nil
+}
+
// HasActiveCredential reports whether usable cookies are present.
func (s *Store) HasActiveCredential() bool {
s.mu.RLock()
defer s.mu.RUnlock()
- if s.rec == nil {
- return false
- }
- if s.rec.State == "expired" || s.rec.State == "logged_out" || s.rec.State == "decrypt_failed" {
+ if !s.isActiveRecordLocked() {
return false
}
return s.hasRequiredCookies(s.rec.Cookies)
@@ -370,7 +387,7 @@ func (s *Store) HasActiveCredential() bool {
func (s *Store) CookieHeader() string {
s.mu.RLock()
defer s.mu.RUnlock()
- if s.rec == nil || s.rec.State == "expired" || s.rec.State == "logged_out" || s.rec.State == "decrypt_failed" {
+ if !s.isActiveRecordLocked() {
return ""
}
var pairs []string
@@ -386,17 +403,17 @@ func (s *Store) CookieHeader() string {
func (s *Store) CookieValue(name string) string {
s.mu.RLock()
defer s.mu.RUnlock()
- if s.rec == nil || s.rec.State == "expired" || s.rec.State == "logged_out" || s.rec.State == "decrypt_failed" {
+ if !s.isActiveRecordLocked() {
return ""
}
return s.rec.Cookies[name]
}
-// Cookies returns a copy of the stored whitelisted cookies, or nil if not logged in.
+// Cookies returns a copy of the stored whitelisted cookies when active, or nil if not logged in or expired.
func (s *Store) Cookies() map[string]string {
s.mu.RLock()
defer s.mu.RUnlock()
- if s.rec == nil {
+ if !s.isActiveRecordLocked() {
return nil
}
out := make(map[string]string, len(s.rec.Cookies))
@@ -406,11 +423,11 @@ func (s *Store) Cookies() map[string]string {
return out
}
-// CSRF returns the current bili_jct token if logged in.
+// CSRF returns the current bili_jct token when active, or empty string if not logged in or expired.
func (s *Store) CSRF() string {
s.mu.RLock()
defer s.mu.RUnlock()
- if s.rec == nil {
+ if !s.isActiveRecordLocked() {
return ""
}
return s.rec.Cookies["bili_jct"]
@@ -437,6 +454,9 @@ func (s *Store) SaveManual(rawCookie, rawRefreshToken string) (Status, error) {
// SaveVerifiedManual saves already-validated manual Bilibili cookies and profile metadata.
func (s *Store) SaveVerifiedManual(cookies map[string]string, refreshToken string, mid int64, uname, face string) (Status, error) {
+ if err := s.requireSite(SiteBilibili); err != nil {
+ return Status{}, err
+ }
filtered := FilterCookieMap(cookies)
if filtered["SESSDATA"] == "" {
return Status{}, ErrMissingRequiredKeys
@@ -478,6 +498,9 @@ func (s *Store) MarkChecked() (Status, error) {
// SaveQR saves Bilibili credentials obtained from QR code login.
func (s *Store) SaveQR(cookies map[string]string, refreshToken string, mid int64, uname, face string) (Status, error) {
+ if err := s.requireSite(SiteBilibili); err != nil {
+ return Status{}, err
+ }
filtered := FilterCookieMap(cookies)
if filtered["SESSDATA"] == "" || filtered["bili_jct"] == "" {
return Status{}, ErrMissingRequiredKeys
@@ -552,6 +575,26 @@ func (s *Store) MarkState(state, message string) (Status, error) {
return s.buildStatus(s.rec), nil
}
+// MarkPushed records that the credential was pushed by the desktop to the
+// remote (source "remote_push"): it keeps no refresh token and is never
+// renewed there (DEC-062 ③).
+func (s *Store) MarkPushed(source string) (Status, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.rec == nil {
+ return s.lastStatus, ErrNotLoggedIn
+ }
+ next := s.cloneRecord(s.rec)
+ next.Source = source
+ next.RefreshToken = ""
+ next.ConfirmPending = false
+ next.PendingOldRefreshToken = ""
+ if err := s.persistRecordLocked(next); err != nil {
+ return s.buildStatus(s.rec), err
+ }
+ return s.buildStatus(s.rec), nil
+}
+
// CommitRefreshStep4 atomically saves new cookies and newRefreshToken after cookie/refresh succeeds,
// while recording confirmPending=true and pendingOldRefreshToken=oldRefreshToken until confirm/refresh completes.
func (s *Store) CommitRefreshStep4(newCookies map[string]string, newRefreshToken, oldRefreshToken string) error {
@@ -625,6 +668,20 @@ func ExtractSetCookies(headers []*http.Cookie) map[string]string {
return FilterCookieMap(raw)
}
+func appendSecretVariants(dst []string, raw string) []string {
+ if len(raw) < 4 {
+ return dst
+ }
+ dst = append(dst, raw)
+ if esc := url.QueryEscape(raw); esc != raw && len(esc) >= 4 {
+ dst = append(dst, esc)
+ }
+ if unesc, err := url.QueryUnescape(raw); err == nil && unesc != raw && len(unesc) >= 4 {
+ dst = append(dst, unesc)
+ }
+ return dst
+}
+
func (s *Store) collectSecrets() []string {
if s == nil {
return nil
@@ -637,15 +694,11 @@ func (s *Store) collectSecrets() []string {
var secrets []string
for k, v := range s.rec.Cookies {
if len(v) >= 4 && !isNonSecretCookieValue(k, v) {
- secrets = append(secrets, v)
+ secrets = appendSecretVariants(secrets, v)
}
}
- if len(s.rec.RefreshToken) >= 4 {
- secrets = append(secrets, s.rec.RefreshToken)
- }
- if len(s.rec.PendingOldRefreshToken) >= 4 {
- secrets = append(secrets, s.rec.PendingOldRefreshToken)
- }
+ secrets = appendSecretVariants(secrets, s.rec.RefreshToken)
+ secrets = appendSecretVariants(secrets, s.rec.PendingOldRefreshToken)
return secrets
}
@@ -707,7 +760,7 @@ func (s *Store) persistRecordLocked(next *Record) error {
if len(entropy) == 0 {
entropy = []byte(BilibiliEntropy)
}
- cipherData, err := encryptBytesWithEntropy(plain, entropy)
+ cipherData, err := protectFor(s.path, plain, entropy)
for i := range plain {
plain[i] = 0
}
@@ -727,7 +780,7 @@ func writeFileAtomic(path string, data []byte, perm os.FileMode) error {
if err := os.MkdirAll(dir, 0o700); err != nil {
return err
}
- tmp, err := os.CreateTemp(dir, ".tmp-cred-*")
+ tmp, err := os.CreateTemp(dir, ".trace-cred-*.tmp")
if err != nil {
return err
}
@@ -755,7 +808,14 @@ func writeFileAtomic(path string, data []byte, perm os.FileMode) error {
}
func backupCorruptFile(path string) (string, error) {
- backup := fmt.Sprintf("%s.corrupt-%s", path, time.Now().UTC().Format("20060102T150405Z"))
+ ts := time.Now().UTC().Format("20060102T150405.000Z")
+ backup := fmt.Sprintf("%s.corrupt-%s", path, ts)
+ for i := 1; i < 100; i++ {
+ if _, err := os.Stat(backup); os.IsNotExist(err) {
+ break
+ }
+ backup = fmt.Sprintf("%s.corrupt-%s-%d", path, ts, i)
+ }
if err := os.Rename(path, backup); err != nil {
return "", err
}
diff --git a/internal/credential/credential_test.go b/internal/credential/credential_test.go
index bbd92e7..e51ee56 100644
--- a/internal/credential/credential_test.go
+++ b/internal/credential/credential_test.go
@@ -148,14 +148,6 @@ func TestDPAPIStoreRoundTripCorruptAndConfirmState(t *testing.T) {
}
}
-func TestManualCookieParseWhitelistAndLimit(t *testing.T) {
- TestManualCookieParserWhitelistAndBounds(t)
-}
-
-func TestDPAPIRoundTripAndCorruptBackup(t *testing.T) {
- TestDPAPIStoreRoundTripCorruptAndConfirmState(t)
-}
-
func TestAtomicReplaceCredential(t *testing.T) {
path := filepath.Join(t.TempDir(), "credentials", "bilibili.bin")
store, _, err := Open(path)
@@ -220,4 +212,48 @@ func TestExpiredCredentialIsBlockedWhenStatusCannotPersist(t *testing.T) {
if err != nil || !bytes.Equal(before, after) {
t.Fatalf("expiration damaged encrypted credential: %v", err)
}
+ if store.Cookies() != nil || store.CSRF() != "" {
+ t.Fatalf("expired store still returned Cookies=%v CSRF=%q", store.Cookies(), store.CSRF())
+ }
+}
+
+func TestRedactEncodedSecretsAndCookieInjectionGuard(t *testing.T) {
+ dir := t.TempDir()
+ biliStore, _, err := Open(filepath.Join(dir, "bilibili.bin"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ rawSess := "abc,def%2Cxyz|123"
+ rawCSRF := "csrf_token_9999"
+ if _, err := biliStore.SaveVerifiedManual(map[string]string{
+ "SESSDATA": rawSess,
+ "bili_jct": rawCSRF,
+ "sid": "bad\r\nInjected: 1",
+ "DedeUserID": "123;evil=1",
+ }, "", 1, "u", ""); err != nil {
+ t.Fatal(err)
+ }
+ gotCookies := biliStore.Cookies()
+ if gotCookies["sid"] != "" || gotCookies["DedeUserID"] != "" {
+ t.Fatalf("CR/LF/semicolon cookie values were not rejected: %+v", gotCookies)
+ }
+ logLine := "raw=" + rawSess + " enc=abc%2Cdef%252Cxyz%7C123 dec=abc,def,xyz|123 csrf=" + rawCSRF
+ redacted := biliStore.RedactString(logLine)
+ for _, leak := range []string{"abc,def", "abc%2Cdef", "csrf_token_9999"} {
+ if strings.Contains(redacted, leak) {
+ t.Fatalf("RedactString leaked %q in %q", leak, redacted)
+ }
+ }
+
+ // Cross-site save must be rejected.
+ if _, err := biliStore.SaveVerifiedDouyinManual(map[string]string{"sessionid": "synth_dy"}, DouyinProfile{}); err == nil {
+ t.Fatal("expected Bilibili store to reject SaveVerifiedDouyinManual")
+ }
+ dyStore, _, err := OpenDouyin(filepath.Join(dir, "douyin.bin"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := dyStore.SaveVerifiedManual(map[string]string{"SESSDATA": "synth_bili"}, "", 1, "u", ""); err == nil {
+ t.Fatal("expected Douyin store to reject SaveVerifiedManual")
+ }
}
diff --git a/internal/credential/douyin.go b/internal/credential/douyin.go
index 9f4a41f..f04864f 100644
--- a/internal/credential/douyin.go
+++ b/internal/credential/douyin.go
@@ -124,7 +124,7 @@ func CleanDouyinCookieMap(in map[string]string) map[string]string {
// First apply case-folded matches, then exact-case matches so UIFID and uifid never clobber each other.
for k, v := range in {
v = strings.TrimSpace(strings.Trim(strings.TrimSpace(v), `"'`))
- if v == "" {
+ if !isSafeCookieValue(v) {
continue
}
trimmedKey := strings.TrimSpace(k)
@@ -137,7 +137,7 @@ func CleanDouyinCookieMap(in map[string]string) map[string]string {
}
for k, v := range in {
v = strings.TrimSpace(strings.Trim(strings.TrimSpace(v), `"'`))
- if v == "" {
+ if !isSafeCookieValue(v) {
continue
}
trimmedKey := strings.TrimSpace(k)
@@ -171,6 +171,9 @@ func (s *Store) SaveDouyinManual(rawCookie string) (Status, error) {
// SaveVerifiedDouyinManual persists cleaned Douyin cookies and verified profile metadata.
func (s *Store) SaveVerifiedDouyinManual(cookies map[string]string, profile DouyinProfile) (Status, error) {
+ if err := s.requireSite(SiteDouyin); err != nil {
+ return Status{}, err
+ }
cleaned := CleanDouyinCookieMap(cookies)
if !hasDouyinSession(cleaned) {
return Status{}, ErrMissingDouyinSession
@@ -199,6 +202,9 @@ func (s *Store) SaveVerifiedDouyinManual(cookies map[string]string, profile Douy
// UpdateDouyinProfile updates cached Douyin profile metadata (uid, sec_uid, unique_id, nickname, avatar) and marks state logged_in.
func (s *Store) UpdateDouyinProfile(profile DouyinProfile) (Status, error) {
+ if err := s.requireSite(SiteDouyin); err != nil {
+ return Status{}, err
+ }
s.mu.Lock()
defer s.mu.Unlock()
if s.rec == nil {
@@ -233,13 +239,16 @@ func (s *Store) UpdateDouyinProfile(profile DouyinProfile) (Status, error) {
// MergeContextCookies merges non-identity context cookies (ttwid, msToken, UIFID, __ac_*)
// received from response Set-Cookie headers into an active Douyin credential.
func (s *Store) MergeContextCookies(cookies map[string]string) error {
+ if err := s.requireSite(SiteDouyin); err != nil {
+ return err
+ }
cleaned := CleanDouyinCookieMap(cookies)
if len(cleaned) == 0 {
return nil
}
s.mu.Lock()
defer s.mu.Unlock()
- if s.rec == nil || s.rec.State == "expired" || s.rec.State == "logged_out" || s.rec.State == "decrypt_failed" {
+ if !s.isActiveRecordLocked() {
return ErrNotLoggedIn
}
next := s.cloneRecord(s.rec)
diff --git a/internal/credential/douyin_test.go b/internal/credential/douyin_test.go
index 70017b8..410538b 100644
--- a/internal/credential/douyin_test.go
+++ b/internal/credential/douyin_test.go
@@ -35,11 +35,11 @@ func TestV011BilibiliFixtureCompatibilityAndEntropyIsolation(t *testing.T) {
"uname": "SyntheticV011User",
"state": "logged_in"
}`)
- biliCipher, err := encryptBytesWithEntropy(v011JSON, []byte("trace:bilibili:credential:v1"))
+ biliPath := filepath.Join(credDir, BilibiliFileName)
+ biliCipher, err := protectFor(biliPath, v011JSON, []byte("trace:bilibili:credential:v1"))
if err != nil {
t.Fatalf("encrypt v0.1.1 synthetic fixture: %v", err)
}
- biliPath := filepath.Join(credDir, BilibiliFileName)
if err := os.WriteFile(biliPath, biliCipher, 0o600); err != nil {
t.Fatal(err)
}
diff --git a/internal/credential/dpapi_other.go b/internal/credential/dpapi_other.go
index eb3c106..d0a915a 100644
--- a/internal/credential/dpapi_other.go
+++ b/internal/credential/dpapi_other.go
@@ -7,34 +7,135 @@ import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
- "crypto/sha256"
+ "errors"
"fmt"
"io"
+ "os"
+ "path/filepath"
+ "sync"
)
-var defaultEntropy = []byte(BilibiliEntropy)
+// On Linux and other systems there is no DPAPI. Credentials are sealed with
+// AES-256-GCM under a random 32-byte key kept next to them in KeyFileName
+// (0600), created the first time one is written. This only stops a
+// credential file copied away on its own; whoever can read the key file (the
+// same user or root) can read the credentials (docs/design/remote.md §5).
-func deriveFallbackKey(entropy []byte) [32]byte {
- if len(entropy) == 0 {
- entropy = defaultEntropy
- }
- buf := make([]byte, 0, len(entropy)+len(":fallback"))
- buf = append(buf, entropy...)
- buf = append(buf, ":fallback"...)
- return sha256.Sum256(buf)
+var cipherHeader = []byte("TRACEK1")
+
+var keyMu sync.Mutex
+
+// errNoKey means the key file is gone: what it sealed cannot be read and is
+// treated as no credential.
+var errNoKey = errors.New("credential: key file missing")
+
+// EnsureKeyFile creates the key file of dir when it is missing.
+func EnsureKeyFile(dir string) error {
+ key, err := loadKey(dir, true)
+ clear(key)
+ return err
}
-func encryptBytes(plain []byte) ([]byte, error) {
- return encryptBytesWithEntropy(plain, defaultEntropy)
+func readExistingKeyFile(path string) ([]byte, error) {
+ info, err := os.Lstat(path)
+ if err != nil {
+ return nil, err
+ }
+ if info.Mode()&os.ModeSymlink != 0 {
+ return nil, fmt.Errorf("credential: key file %s must not be a symlink", KeyFileName)
+ }
+ if !info.Mode().IsRegular() {
+ return nil, fmt.Errorf("credential: key file %s is not a regular file", KeyFileName)
+ }
+ if info.Mode().Perm() != 0o600 {
+ if err := os.Chmod(path, 0o600); err != nil {
+ return nil, fmt.Errorf("credential: chmod key file: %w", err)
+ }
+ }
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ return nil, err
+ }
+ if len(raw) != 32 {
+ clear(raw)
+ return nil, fmt.Errorf("credential: key file has the wrong size")
+ }
+ return raw, nil
}
-func decryptBytes(cipherData []byte) ([]byte, error) {
- return decryptBytesWithEntropy(cipherData, defaultEntropy)
+func loadKey(dir string, create bool) ([]byte, error) {
+ keyMu.Lock()
+ defer keyMu.Unlock()
+ path := filepath.Join(dir, KeyFileName)
+ raw, err := readExistingKeyFile(path)
+ if err == nil {
+ return raw, nil
+ }
+ if !errors.Is(err, os.ErrNotExist) {
+ return nil, err
+ }
+ if !create {
+ return nil, errNoKey
+ }
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ return nil, err
+ }
+ key := make([]byte, 32)
+ if _, err := io.ReadFull(rand.Reader, key); err != nil {
+ clear(key)
+ return nil, err
+ }
+ tmp, err := os.CreateTemp(dir, ".trace-key-*.tmp")
+ if err != nil {
+ clear(key)
+ return nil, err
+ }
+ tmpPath := tmp.Name()
+ cleanupTmp := func() { _ = os.Remove(tmpPath) }
+ if err := tmp.Chmod(0o600); err != nil {
+ _ = tmp.Close()
+ cleanupTmp()
+ clear(key)
+ return nil, err
+ }
+ if _, err := tmp.Write(key); err != nil {
+ _ = tmp.Close()
+ cleanupTmp()
+ clear(key)
+ return nil, err
+ }
+ if err := tmp.Sync(); err != nil {
+ _ = tmp.Close()
+ cleanupTmp()
+ clear(key)
+ return nil, err
+ }
+ if err := tmp.Close(); err != nil {
+ cleanupTmp()
+ clear(key)
+ return nil, err
+ }
+ linkErr := os.Link(tmpPath, path)
+ cleanupTmp()
+ if linkErr != nil {
+ clear(key)
+ if errors.Is(linkErr, os.ErrExist) {
+ return readExistingKeyFile(path)
+ }
+ return nil, linkErr
+ }
+ return key, nil
}
-func encryptBytesWithEntropy(plain []byte, entropy []byte) ([]byte, error) {
- key := deriveFallbackKey(entropy)
- block, err := aes.NewCipher(key[:])
+// protectFor seals plain for the file at path; entropy binds it to its site
+// (sealed data of one site never opens as another's).
+func protectFor(path string, plain, entropy []byte) ([]byte, error) {
+ key, err := loadKey(filepath.Dir(path), true)
+ if err != nil {
+ return nil, err
+ }
+ defer clear(key)
+ block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
@@ -46,17 +147,20 @@ func encryptBytesWithEntropy(plain []byte, entropy []byte) ([]byte, error) {
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
- out := gcm.Seal(nonce, nonce, plain, nil)
- return append([]byte("DPAPI1"), out...), nil
+ out := append(append([]byte{}, cipherHeader...), nonce...)
+ return gcm.Seal(out, nonce, plain, entropy), nil
}
-func decryptBytesWithEntropy(cipherData []byte, entropy []byte) ([]byte, error) {
- if !bytes.HasPrefix(cipherData, []byte("DPAPI1")) {
+func unprotectFor(path string, data, entropy []byte) ([]byte, error) {
+ if !bytes.HasPrefix(data, cipherHeader) {
return nil, fmt.Errorf("credential: invalid cipher header")
}
- raw := cipherData[6:]
- key := deriveFallbackKey(entropy)
- block, err := aes.NewCipher(key[:])
+ key, err := loadKey(filepath.Dir(path), false)
+ if err != nil {
+ return nil, err
+ }
+ defer clear(key)
+ block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
@@ -64,10 +168,9 @@ func decryptBytesWithEntropy(cipherData []byte, entropy []byte) ([]byte, error)
if err != nil {
return nil, err
}
+ raw := data[len(cipherHeader):]
if len(raw) < gcm.NonceSize() {
return nil, fmt.Errorf("credential: cipher too short")
}
- nonce := raw[:gcm.NonceSize()]
- ct := raw[gcm.NonceSize():]
- return gcm.Open(nil, nonce, ct, nil)
+ return gcm.Open(nil, raw[:gcm.NonceSize()], raw[gcm.NonceSize():], entropy)
}
diff --git a/internal/credential/dpapi_windows.go b/internal/credential/dpapi_windows.go
index 3f26ca9..43a022e 100644
--- a/internal/credential/dpapi_windows.go
+++ b/internal/credential/dpapi_windows.go
@@ -21,14 +21,6 @@ func makeBlob(b []byte) windows.DataBlob {
}
}
-func encryptBytes(plain []byte) ([]byte, error) {
- return encryptBytesWithEntropy(plain, dpapiEntropy)
-}
-
-func decryptBytes(cipher []byte) ([]byte, error) {
- return decryptBytesWithEntropy(cipher, dpapiEntropy)
-}
-
func encryptBytesWithEntropy(plain []byte, entropy []byte) ([]byte, error) {
if len(entropy) == 0 {
entropy = dpapiEntropy
@@ -98,3 +90,14 @@ func decryptBytesWithEntropy(cipher []byte, entropy []byte) ([]byte, error) {
copy(out, unsafe.Slice(outBlob.Data, outBlob.Size))
return out, nil
}
+
+// EnsureKeyFile has nothing to do on Windows: DPAPI keeps the key.
+func EnsureKeyFile(string) error { return nil }
+
+func protectFor(_ string, plain, entropy []byte) ([]byte, error) {
+ return encryptBytesWithEntropy(plain, entropy)
+}
+
+func unprotectFor(_ string, data, entropy []byte) ([]byte, error) {
+ return decryptBytesWithEntropy(data, entropy)
+}
diff --git a/internal/credential/keyfile_other_test.go b/internal/credential/keyfile_other_test.go
new file mode 100644
index 0000000..b1432e9
--- /dev/null
+++ b/internal/credential/keyfile_other_test.go
@@ -0,0 +1,90 @@
+//go:build !windows
+
+package credential
+
+import (
+ "bytes"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+// On Linux the credential file is sealed under a random key file
+// (0600); the file holds no plain sentinel; a lost key file means "no
+// Cookie" without a crash, and a new login works again.
+func TestLinuxCredentialKeyFile(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "bilibili.bin")
+ store, _, err := Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ const sess = "SENTINEL_LINUX_SESS_5d2e"
+ if _, err := store.SaveManual("SESSDATA="+sess+"; bili_jct=SENTINEL_LINUX_CSRF", "SENTINEL_LINUX_RT"); err != nil {
+ t.Fatal(err)
+ }
+ st, err := os.Stat(filepath.Join(dir, KeyFileName))
+ if err != nil || st.Mode().Perm() != 0o600 || st.Size() != 32 {
+ t.Fatalf("key file = %v %v", st, err)
+ }
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, s := range []string{sess, "SENTINEL_LINUX_CSRF", "SENTINEL_LINUX_RT"} {
+ if bytes.Contains(raw, []byte(s)) {
+ t.Fatalf("the credential file holds %s in plain text", s)
+ }
+ }
+ again, _, err := Open(path)
+ if err != nil || !again.Status().LoggedIn || !bytes.Contains([]byte(again.CookieHeader()), []byte(sess)) {
+ t.Fatalf("reopen = %+v %v", again.Status(), err)
+ }
+
+ // The same key with another site's entropy does not open it.
+ if _, err := unprotectFor(path, raw, []byte("other-site")); err == nil {
+ t.Fatal("sealed data opened with another site's entropy")
+ }
+
+ if err := os.Remove(filepath.Join(dir, KeyFileName)); err != nil {
+ t.Fatal(err)
+ }
+ lost, _, err := Open(path)
+ if err != nil {
+ t.Fatalf("Open after the key file was lost: %v", err)
+ }
+ if lost.Status().LoggedIn || lost.CookieHeader() != "" {
+ t.Fatalf("a credential was read without its key: %+v", lost.Status())
+ }
+ if _, err := lost.SaveManual("SESSDATA=fresh; bili_jct=x", ""); err != nil {
+ t.Fatalf("a new login after the key was lost: %v", err)
+ }
+ if st, err := os.Stat(filepath.Join(dir, KeyFileName)); err != nil || st.Mode().Perm() != 0o600 {
+ t.Fatalf("new key file = %v %v", st, err)
+ }
+
+ // The remote's token is sealed the same way.
+ tok := filepath.Join(dir, "remote-x.bin")
+ if err := SaveSecret(tok, RemoteTokenEntropy, []byte("SENTINEL_TOKEN_77")); err != nil {
+ t.Fatal(err)
+ }
+ if b, _ := os.ReadFile(tok); bytes.Contains(b, []byte("SENTINEL_TOKEN_77")) {
+ t.Fatal("the token file holds the token in plain text")
+ }
+ if got, ok, err := LoadSecret(tok, RemoteTokenEntropy); err != nil || !ok || string(got) != "SENTINEL_TOKEN_77" {
+ t.Fatalf("LoadSecret = %q %v %v", got, ok, err)
+ }
+
+ // Symlink keyfile must be rejected.
+ symDir := t.TempDir()
+ target := filepath.Join(symDir, "other.key")
+ if err := os.WriteFile(target, bytes.Repeat([]byte("a"), 32), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(target, filepath.Join(symDir, KeyFileName)); err != nil {
+ t.Fatal(err)
+ }
+ if err := EnsureKeyFile(symDir); err == nil {
+ t.Fatal("EnsureKeyFile accepted symlink key file")
+ }
+}
diff --git a/internal/credential/secret.go b/internal/credential/secret.go
new file mode 100644
index 0000000..2642061
--- /dev/null
+++ b/internal/credential/secret.go
@@ -0,0 +1,52 @@
+package credential
+
+import (
+ "errors"
+ "os"
+)
+
+// KeyFileName is the key file of the credentials folder on Linux (unused
+// on Windows, where DPAPI holds the key).
+const KeyFileName = "secret.key"
+
+// Secrets other than site Cookies (the remote's access token) are kept with
+// the same protection as the site credentials: DPAPI on Windows, the key file
+// elsewhere. The entropy keeps each kind apart.
+const RemoteTokenEntropy = "trace:remote:token:v1"
+
+// SaveSecret seals data into path (0600).
+func SaveSecret(path, entropy string, data []byte) error {
+ sealed, err := protectFor(path, data, []byte(entropy))
+ if err != nil {
+ return err
+ }
+ return writeFileAtomic(path, sealed, 0o600)
+}
+
+// LoadSecret opens a secret written by SaveSecret; ok is false when there is
+// none or it cannot be opened any more.
+func LoadSecret(path, entropy string) (data []byte, ok bool, err error) {
+ raw, err := os.ReadFile(path)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil, false, nil
+ }
+ if err != nil {
+ return nil, false, err
+ }
+ plain, err := unprotectFor(path, raw, []byte(entropy))
+ if err != nil {
+ if errors.Is(err, os.ErrPermission) {
+ return nil, false, err
+ }
+ return nil, false, nil
+ }
+ return plain, true, nil
+}
+
+// DeleteSecret removes a secret; a missing one is not an error.
+func DeleteSecret(path string) error {
+ if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return err
+ }
+ return nil
+}
diff --git a/internal/download/cover.go b/internal/download/cover.go
index 2e96aa8..d3e097b 100644
--- a/internal/download/cover.go
+++ b/internal/download/cover.go
@@ -2,6 +2,7 @@ package download
import (
"context"
+ "os"
"path/filepath"
"github.com/chialecode/trace/internal/library"
@@ -20,7 +21,7 @@ func (m *Manager) saveVideoCover(ctx context.Context, task *Task, meta *library.
continue
}
rel = file.Path
- if mediaIsValid(*meta, rel) {
+ if m.mediaAlreadyCompleted(*meta, file) {
clearMissing(meta, "cover")
return nil
}
@@ -40,3 +41,22 @@ func (m *Manager) saveVideoCover(ctx context.Context, task *Task, meta *library.
clearMissing(meta, "cover")
return m.saveVideoManifest(task, meta)
}
+
+// mediaAlreadyCompleted reports whether a registered manifest file is valid on
+// disk, or was already completed and later moved away in remote/export mode.
+func (m *Manager) mediaAlreadyCompleted(meta library.ItemMetadata, file library.MediaFile) bool {
+ if file.Path == "" {
+ return false
+ }
+ if library.VerifyMediaFile(meta.ItemDir, file, true) {
+ return true
+ }
+ if m.lib != nil && m.lib.AllowMovedFiles() && file.Bytes > 0 && file.SHA256 != "" {
+ if full, err := library.ResolveItemPath(meta.ItemDir, file.Path); err == nil {
+ if _, statErr := os.Stat(full); os.IsNotExist(statErr) {
+ return true
+ }
+ }
+ }
+ return false
+}
diff --git a/internal/download/douyin.go b/internal/download/douyin.go
deleted file mode 100644
index c266150..0000000
--- a/internal/download/douyin.go
+++ /dev/null
@@ -1,2238 +0,0 @@
-package download
-
-import (
- "bytes"
- "context"
- "errors"
- "fmt"
- "io"
- "math"
- jitterrand "math/rand/v2"
- "mime"
- "net"
- "net/http"
- "net/url"
- "os"
- "path/filepath"
- "strings"
- "time"
-
- "github.com/chialecode/trace/internal/library"
- "github.com/chialecode/trace/internal/site"
-)
-
-// WorkPlanOptions carries user quality and codec preferences when planning a site download.
-type WorkPlanOptions struct {
- VideoQuality string
- CodecOrder []string
-}
-
-// PlannedNotePage describes one 1-based page in a Douyin image or mixed note.
-type PlannedNotePage struct {
- Index int
- Kind string // "image", "live_photo", "video", "unknown"
- UnknownKind string
- UnknownReason string
- Width int
- Height int
- DurationSec int
- ImageURLs []string
- VideoURLs []string
- Gear string
- QualityName string
- Codec string
- FPS int
- Bitrate int64
-}
-
-// PlannedMusic describes background music metadata and candidate URLs on a Douyin note.
-type PlannedMusic struct {
- ID string
- Title string
- Author string
- DurationSec int
- Original bool
- CoverURLs []string
- PlayURLs []string
-}
-
-// WorkDownloadPlan holds rich metadata and ephemeral CDN URLs for caching a Douyin video or note.
-type WorkDownloadPlan struct {
- Site site.ID
- Kind string // "video" or "dynamic" ("note" / "image_note" normalized to "dynamic")
- TargetID string
- Title string
- Desc string
- CanonicalURL string
- PubTs int64
- DurationSec int
- AuthorUID string
- AuthorUniqueID string
- AuthorName string
- AuthorFace string
- CoverURLs []string
- VideoURLs []string
- OriginalURLs []string // untranscoded source (原画), tried before VideoURLs
- VideoGear string
- QualityName string
- Codec string
- Width int
- Height int
- FPS int
- Bitrate int64
- AvailableGears []string
- DowngradeHint string
- Pages []PlannedNotePage
- Music *PlannedMusic
- Transport site.MediaTransportSpec
-}
-
-// WorkPlanner plans rich work downloads for a site without exposing site-private packages to download.
-type WorkPlanner interface {
- SiteID() site.ID
- PlanWorkDownload(ctx context.Context, targetID string, opts WorkPlanOptions) (WorkDownloadPlan, error)
-}
-
-// SiteAuthChecker is an optional interface implemented by planners that enforce login before enqueueing.
-type SiteAuthChecker interface {
- RequireAuth(action string) error
-}
-
-// SiteErrorReporter is an optional interface implemented by planners that track automatic-request errors.
-type SiteErrorReporter interface {
- ReportAutomaticError(ctx context.Context, err error)
-}
-
-// DouyinWorkEnqueueRequest specifies a Douyin video or image/mixed note to enqueue for local caching.
-type DouyinWorkEnqueueRequest struct {
- AwemeID string `json:"awemeId"`
- Kind string `json:"kind,omitempty"` // optional hint: "video" or "dynamic"/"note"
- Source string `json:"source,omitempty"` // "manual" or "auto"
- Plan *WorkDownloadPlan `json:"-"`
-}
-
-// RegisterSitePlanner registers a cross-site DownloadPlanner (upgrading automatically if it also implements WorkPlanner).
-func (m *Manager) RegisterSitePlanner(planner site.DownloadPlanner) {
- if planner == nil {
- return
- }
- if wp, ok := planner.(WorkPlanner); ok {
- m.RegisterWorkPlanner(wp)
- return
- }
- m.RegisterWorkPlanner(&basicSitePlannerAdapter{inner: planner})
-}
-
-// RegisterWorkPlanner registers a rich WorkPlanner for its SiteID.
-func (m *Manager) RegisterWorkPlanner(planner WorkPlanner) {
- if planner == nil {
- return
- }
- m.mu.Lock()
- m.planners[planner.SiteID()] = planner
- m.mu.Unlock()
-}
-
-func (m *Manager) getWorkPlanner(siteID site.ID) (WorkPlanner, bool) {
- m.mu.Lock()
- defer m.mu.Unlock()
- p, ok := m.planners[siteID]
- return p, ok
-}
-
-type basicSitePlannerAdapter struct {
- inner site.DownloadPlanner
-}
-
-func (a *basicSitePlannerAdapter) SiteID() site.ID {
- return a.inner.SiteID()
-}
-
-func (a *basicSitePlannerAdapter) RequireAuth(action string) error {
- if checker, ok := a.inner.(SiteAuthChecker); ok {
- return checker.RequireAuth(action)
- }
- return nil
-}
-
-func (a *basicSitePlannerAdapter) ReportAutomaticError(ctx context.Context, err error) {
- if rep, ok := a.inner.(SiteErrorReporter); ok {
- rep.ReportAutomaticError(ctx, err)
- }
-}
-
-func (a *basicSitePlannerAdapter) PlanWorkDownload(ctx context.Context, targetID string, _ WorkPlanOptions) (WorkDownloadPlan, error) {
- p, err := a.inner.PlanDownload(ctx, targetID, 1)
- if err != nil {
- return WorkDownloadPlan{}, err
- }
- return convertSiteDownloadPlan(p), nil
-}
-
-func convertSiteDownloadPlan(p site.DownloadPlan) WorkDownloadPlan {
- kind := "video"
- if p.Kind == "image_note" || p.Kind == "note" || p.Kind == "dynamic" || len(p.Images) > 0 {
- kind = "dynamic"
- }
- canonicalURL := ""
- if p.Site == site.Douyin && p.TargetID != "" {
- if kind == "dynamic" {
- canonicalURL = "https://www.douyin.com/note/" + p.TargetID
- } else {
- canonicalURL = "https://www.douyin.com/video/" + p.TargetID
- }
- }
- pages := make([]PlannedNotePage, 0, len(p.Images))
- for i, img := range p.Images {
- idx := img.Index
- if idx <= 0 {
- idx = i + 1
- }
- pageKind := "image"
- if len(img.VideoURLs) > 0 {
- pageKind = "live_photo"
- }
- pages = append(pages, PlannedNotePage{
- Index: idx,
- Kind: pageKind,
- Width: img.Width,
- Height: img.Height,
- ImageURLs: append([]string(nil), img.ImageURLs...),
- VideoURLs: append([]string(nil), img.VideoURLs...),
- })
- }
- var music *PlannedMusic
- if len(p.MusicURLs) > 0 {
- music = &PlannedMusic{
- PlayURLs: append([]string(nil), p.MusicURLs...),
- }
- }
- transport := p.Media
- if len(transport.AllowedDomains) == 0 && p.Site == site.Douyin {
- transport = site.DouyinVODTransport("", false)
- }
- return WorkDownloadPlan{
- Site: p.Site,
- Kind: kind,
- TargetID: p.TargetID,
- Title: p.Title,
- Desc: p.Desc,
- CanonicalURL: canonicalURL,
- PubTs: p.PubTs,
- DurationSec: p.DurationSec,
- AuthorUID: p.AuthorUID,
- AuthorName: p.AuthorName,
- CoverURLs: append([]string(nil), p.CoverURLs...),
- VideoURLs: append([]string(nil), p.VideoURLs...),
- OriginalURLs: append([]string(nil), p.OriginalURLs...),
- QualityName: p.QualityLabel,
- Codec: p.VideoCodec,
- Width: p.Width,
- Height: p.Height,
- Pages: pages,
- Music: music,
- Transport: transport,
- }
-}
-
-// EnqueueDouyinWork resolves (or accepts a pre-planned) Douyin video or note and enqueues a download task.
-func (m *Manager) EnqueueDouyinWork(ctx context.Context, req DouyinWorkEnqueueRequest) (Task, error) {
- awemeID := strings.TrimSpace(req.AwemeID)
- if awemeID == "" && req.Plan != nil {
- awemeID = strings.TrimSpace(req.Plan.TargetID)
- }
- if awemeID == "" || library.SanitizeFileName(awemeID) != awemeID {
- return Task{}, &site.Error{
- Site: site.Douyin,
- Kind: site.ErrKindBadRequest,
- Message: "无效的抖音作品 ID",
- }
- }
-
- planner, hasPlanner := m.getWorkPlanner(site.Douyin)
- if checker, ok := planner.(SiteAuthChecker); ok {
- if err := checker.RequireAuth("download:douyin"); err != nil {
- return Task{}, err
- }
- }
-
- var plan WorkDownloadPlan
- if req.Plan != nil {
- plan = *req.Plan
- } else {
- if !hasPlanner {
- return Task{}, &site.Error{
- Site: site.Douyin,
- Kind: site.ErrKindUnavailable,
- Message: "抖音下载规划器尚未初始化",
- }
- }
- m.mu.Lock()
- opts := WorkPlanOptions{
- VideoQuality: m.dlSettings.VideoQuality,
- CodecOrder: append([]string(nil), m.dlSettings.CodecOrder...),
- }
- m.mu.Unlock()
- fetched, err := planner.PlanWorkDownload(ctx, awemeID, opts)
- if err != nil {
- return Task{}, err
- }
- plan = fetched
- }
-
- plan.Site = site.Douyin
- if plan.TargetID == "" {
- plan.TargetID = awemeID
- }
- kind := normalizeDouyinTaskKind(firstNonEmptyStr(plan.Kind, req.Kind), len(plan.Pages) > 0)
- plan.Kind = kind
-
- normUID, err := site.NormalizeUID(site.Douyin, plan.AuthorUID)
- if err != nil {
- return Task{}, &site.Error{
- Site: site.Douyin,
- Kind: site.ErrKindSchemaChanged,
- Message: "抖音作品缺少有效作者标识",
- }
- }
- plan.AuthorUID = normUID
- if len(plan.Transport.AllowedDomains) == 0 {
- plan.Transport = site.DouyinVODTransport("", false)
- }
-
- cacheRoot := m.lib.CacheDir()
- itemDir, err := library.EnsureWithinRoot(cacheRoot, filepath.Join(cacheRoot, "douyin", site.DouyinAuthorDir(normUID), "works", plan.TargetID))
- if err != nil {
- return Task{}, err
- }
- itemKey := library.CanonicalItemKey("douyin", kind, plan.TargetID)
- if existing, exists, gErr := m.lib.GetItem(itemKey); gErr == nil && exists && existing.ItemDir != "" {
- itemDir = existing.ItemDir
- }
-
- source := strings.TrimSpace(req.Source)
- if source == "" {
- source = "manual"
- }
- coverDisplay := ""
- if len(plan.CoverURLs) > 0 {
- coverDisplay = sanitizeStoredURL(plan.CoverURLs[0])
- }
-
- title := strings.TrimSpace(plan.Title)
- if title == "" {
- title = strings.TrimSpace(plan.Desc)
- }
- if title == "" {
- title = "抖音作品 " + plan.TargetID
- }
-
- t, err := m.enqueueSingleTask(Task{
- Site: string(site.Douyin),
- Kind: kind,
- Source: source,
- TargetID: plan.TargetID,
- Page: 1,
- Title: title,
- AuthorUID: normUID,
- AuthorName: plan.AuthorName,
- AuthorFace: sanitizeStoredURL(plan.AuthorFace),
- CoverURL: coverDisplay,
- QualityHint: plan.DowngradeHint,
- ItemKey: itemKey,
- ItemDir: itemDir,
- })
- if err != nil {
- return Task{}, err
- }
-
- m.mu.Lock()
- if t.Status == "queued" {
- m.initialPlans[t.TaskID] = plan
- }
- m.mu.Unlock()
-
- m.notifyWake()
- return t, nil
-}
-
-func normalizeDouyinTaskKind(raw string, hasPages bool) string {
- switch strings.ToLower(strings.TrimSpace(raw)) {
- case "dynamic", "note", "image_note", "images":
- return "dynamic"
- case "video", "single_mp4":
- if hasPages {
- return "dynamic"
- }
- return "video"
- default:
- if hasPages {
- return "dynamic"
- }
- return "video"
- }
-}
-
-func classifyDownloadError(err error) string {
- if err == nil {
- return ""
- }
- var pathErr *os.PathError
- if errors.As(err, &pathErr) {
- return site.ErrKindStorage
- }
- var encErr *EncryptedMediaError
- if errors.As(err, &encErr) {
- return site.ErrKindBlocked
- }
- var mp4Err *SingleMP4ValidationError
- if errors.As(err, &mp4Err) {
- return site.ErrKindSchemaChanged
- }
- return site.KindOf(err)
-}
-
-func (m *Manager) reportSiteAutomaticError(ctx context.Context, siteStr string, err error) {
- if err == nil {
- return
- }
- if siteStr == "" || siteStr == string(site.Bilibili) {
- if m.client != nil {
- m.client.ReportAutomaticError(ctx, err)
- }
- return
- }
- if planner, ok := m.getWorkPlanner(site.ID(siteStr)); ok {
- if rep, ok := planner.(SiteErrorReporter); ok {
- rep.ReportAutomaticError(ctx, err)
- }
- }
-}
-
-func (m *Manager) consumeInitialOrFetchDouyinPlan(ctx context.Context, taskID, targetID string) (WorkDownloadPlan, WorkPlanner, error) {
- m.mu.Lock()
- initial, hasInitial := m.initialPlans[taskID]
- if hasInitial {
- delete(m.initialPlans, taskID)
- }
- planner := m.planners[site.Douyin]
- opts := WorkPlanOptions{
- VideoQuality: m.dlSettings.VideoQuality,
- CodecOrder: append([]string(nil), m.dlSettings.CodecOrder...),
- }
- m.mu.Unlock()
-
- if hasInitial {
- return initial, planner, nil
- }
- if planner == nil {
- return WorkDownloadPlan{}, nil, &site.Error{
- Site: site.Douyin,
- Kind: site.ErrKindUnavailable,
- Message: "抖音下载规划器尚未初始化",
- }
- }
- if checker, ok := planner.(SiteAuthChecker); ok {
- if err := checker.RequireAuth("download:douyin"); err != nil {
- return WorkDownloadPlan{}, planner, err
- }
- }
- plan, err := planner.PlanWorkDownload(ctx, targetID, opts)
- if err != nil {
- return WorkDownloadPlan{}, planner, err
- }
- if len(plan.Transport.AllowedDomains) == 0 {
- plan.Transport = site.DouyinVODTransport("", false)
- }
- return plan, planner, nil
-}
-
-func (m *Manager) executeDouyinTask(ctx context.Context, t *Task) error {
- unlock := m.lockVideo("douyin:" + t.TargetID)
- defer unlock()
- if err := ctx.Err(); err != nil {
- return err
- }
-
- plan, planner, err := m.consumeInitialOrFetchDouyinPlan(ctx, t.TaskID, t.TargetID)
- if err != nil {
- return err
- }
- normUID, err := site.NormalizeUID(site.Douyin, firstNonEmptyStr(plan.AuthorUID, t.AuthorUID))
- if err != nil {
- return &site.Error{
- Site: site.Douyin,
- Kind: site.ErrKindSchemaChanged,
- Message: "抖音作品缺少有效作者标识",
- }
- }
- plan.AuthorUID = normUID
- t.AuthorUID = normUID
-
- kind := normalizeDouyinTaskKind(firstNonEmptyStr(plan.Kind, t.Kind), len(plan.Pages) > 0)
- t.Kind = kind
- if kind == "dynamic" {
- return m.executeDouyinNoteTask(ctx, t, plan, planner)
- }
- return m.executeDouyinVideoTask(ctx, t, plan, planner)
-}
-
-func (m *Manager) resolveDouyinItemDir(t *Task, kind, normUID, awemeID string) (library.ItemMetadata, bool, string, error) {
- itemKey := library.CanonicalItemKey("douyin", kind, awemeID)
- previous, exists, err := m.lib.GetItem(itemKey)
- if err != nil {
- return library.ItemMetadata{}, false, "", err
- }
- cacheRoot := m.lib.CacheDir()
- itemDir, err := library.EnsureWithinRoot(cacheRoot, filepath.Join(cacheRoot, "douyin", site.DouyinAuthorDir(normUID), "works", awemeID))
- if err != nil {
- return library.ItemMetadata{}, false, "", err
- }
- if exists && previous.ItemDir != "" {
- itemDir = previous.ItemDir
- } else if t.ItemDir != "" {
- if checked, cErr := library.EnsureWithinRoot(cacheRoot, t.ItemDir); cErr == nil {
- itemDir = checked
- }
- }
- if err := os.MkdirAll(itemDir, 0o700); err != nil {
- return library.ItemMetadata{}, false, "", err
- }
- t.ItemKey = itemKey
- t.ItemDir = itemDir
- return previous, exists, itemDir, nil
-}
-
-func (m *Manager) executeDouyinVideoTask(ctx context.Context, t *Task, plan WorkDownloadPlan, planner WorkPlanner) (result error) {
- previous, exists, itemDir, err := m.resolveDouyinItemDir(t, "video", plan.AuthorUID, t.TargetID)
- if err != nil {
- return err
- }
-
- m.mu.Lock()
- cfg := m.dlSettings
- m.mu.Unlock()
-
- title := firstNonEmptyStr(plan.Title, plan.Desc, t.Title, "抖音视频 "+t.TargetID)
- canonicalURL := firstNonEmptyStr(sanitizeStoredURL(plan.CanonicalURL), "https://www.douyin.com/video/"+t.TargetID)
- t.Title = title
- t.AuthorName = firstNonEmptyStr(plan.AuthorName, t.AuthorName)
- t.AuthorFace = sanitizeStoredURL(firstNonEmptyStr(plan.AuthorFace, t.AuthorFace))
- if len(plan.CoverURLs) > 0 {
- t.CoverURL = sanitizeStoredURL(plan.CoverURLs[0])
- }
- if plan.DowngradeHint != "" {
- t.QualityHint = plan.DowngradeHint
- }
-
- meta := library.ItemMetadata{
- Version: 1,
- ID: "video:" + t.TargetID,
- Site: "douyin",
- Kind: "video",
- Status: "partial",
- Title: title,
- Desc: plan.Desc,
- URL: canonicalURL,
- PubTs: plan.PubTs,
- CachedAt: previous.CachedAt,
- Duration: plan.DurationSec,
- Author: library.ItemAuthor{
- Site: "douyin",
- UID: plan.AuthorUID,
- UniqueID: plan.AuthorUniqueID,
- Name: t.AuthorName,
- Face: t.AuthorFace,
- },
- Media: append([]library.MediaFile(nil), previous.Media...),
- Missing: append([]library.MissingRecord(nil), previous.Missing...),
- DirectCached: true,
- }
-
- finalSaved := false
- defer func() {
- if result == nil || finalSaved {
- return
- }
- if !isSiteStopError(result) && !mediaIsValid(meta, "video.mp4") {
- addMissing(&meta, "video.mp4", "视频尚未完成 ("+classifyDownloadError(result)+")")
- }
- meta.Status = "partial"
- if saved, sErr := m.lib.SaveItem(itemDir, meta); sErr == nil {
- t.ItemKey = saved.ItemKey
- }
- }()
-
- refreshOncePlan := m.makeSinglePlanRefresher(ctx, t.TargetID, planner)
-
- // 1. Save cover. when enabled.
- if cfg.SaveCover && len(plan.CoverURLs) > 0 {
- if coverMedia, cErr := m.cacheDouyinSniffedImage(ctx, t, itemDir, previous, exists, "cover", "cover", plan.CoverURLs, 0, 0, plan.Transport, func() ([]string, error) {
- fresh, rErr := refreshOncePlan()
- if rErr != nil {
- return nil, rErr
- }
- return fresh.CoverURLs, nil
- }); cErr != nil {
- if isSiteStopError(cErr) || isStorageError(cErr) || ctx.Err() != nil {
- return cErr
- }
- addMissing(&meta, "cover", "封面保存失败 ("+classifyDownloadError(cErr)+")")
- } else if coverMedia != nil {
- meta.Media = replaceRoleMedia(meta.Media, "cover", *coverMedia)
- clearMissing(&meta, "cover")
- }
- }
-
- // 2. Download & validate single-file video.mp4 (including bounded-memory moov relocation).
- videoRel := "video.mp4"
- videoPath, err := library.ResolveItemPath(itemDir, videoRel)
- if err != nil {
- return err
- }
- if exists && mediaIsValid(previous, videoRel) {
- for _, mf := range previous.Media {
- if mf.Path == videoRel {
- m.setFileProgress(t, "video", videoRel, "completed", mf.Bytes, mf.Bytes, 0)
- meta.Media = mergeMediaFiles(meta.Media, []library.MediaFile{mf})
- clearMissing(&meta, videoRel)
- break
- }
- }
- } else {
- if err := m.claimTaskFile(t, itemDir, videoRel, videoPath); err != nil {
- return err
- }
- m.setFileProgress(t, "video", videoRel, "downloading", 0, 0, 0)
- refreshVideoURLs := m.makePerFileURLRefresher(ctx, t.TargetID, planner, func(fresh WorkDownloadPlan) ([]string, error) {
- if plan.Codec != "" && fresh.Codec != "" && !strings.EqualFold(plan.Codec, fresh.Codec) {
- return nil, &site.Error{Site: site.Douyin, Kind: site.ErrKindUnavailable, Message: "续传地址的视频编码发生变化,已保留断点"}
- }
- if plan.VideoGear != "" && fresh.VideoGear != "" && plan.VideoGear != fresh.VideoGear {
- return nil, &site.Error{Site: site.Douyin, Kind: site.ErrKindUnavailable, Message: "续传地址的清晰度档位发生变化,已保留断点"}
- }
- return fresh.VideoURLs, nil
- })
- rawRel := videoRel + ".raw"
- stagingPath := videoPath + ".raw"
- var summary MuxTrackSummary
- original := false
- if len(plan.OriginalURLs) > 0 {
- origSummary, oErr := m.cacheDouyinOriginal(ctx, t, plan, planner, videoRel, videoPath)
- switch {
- case oErr == nil:
- summary, original = origSummary, true
- // A transcoded attempt from an earlier run is no longer needed.
- _ = os.Remove(stagingPath)
- _ = os.Remove(stagingPath + ".part")
- m.removeTempTaskProgress(t, rawRel)
- case ctx.Err() != nil || site.IsRoundStop(oErr) || isStorageError(oErr):
- m.setFileProgress(t, "video", videoRel, "failed", t.BytesDownloaded, t.TotalBytes, 0)
- return oErr
- }
- // Any other failure falls back to the best transcoded stream below.
- }
- if !original {
- _, _, dlErr := m.downloadWithTransportRefresh(ctx, plan.Transport, plan.VideoURLs, stagingPath, "video", t, refreshVideoURLs)
- if dlErr != nil {
- if ctx.Err() == nil && !fileOrPartExists(stagingPath) {
- m.removeTempTaskProgress(t, rawRel)
- }
- m.setFileProgress(t, "video", videoRel, "failed", t.BytesDownloaded, t.TotalBytes, 0)
- return dlErr
- }
-
- m.setFileProgress(t, "video", videoRel, "verifying", t.BytesDownloaded, t.TotalBytes, 0)
- var vErr error
- summary, vErr = EnsureSingleMP4Context(ctx, stagingPath, float64(plan.DurationSec))
- if vErr != nil {
- _ = os.Remove(stagingPath)
- if ctx.Err() == nil {
- m.removeTempTaskProgress(t, rawRel)
- }
- m.setFileProgress(t, "video", videoRel, "failed", 0, 0, 0)
- return vErr
- }
- if err := ctx.Err(); err != nil {
- _ = os.Remove(stagingPath)
- return err
- }
- if err := os.Rename(stagingPath, videoPath); err != nil {
- return err
- }
- m.removeTempTaskProgress(t, rawRel)
- }
- durSec := int(math.Round(summary.DurationSec))
- if durSec <= 0 {
- durSec = plan.DurationSec
- }
- meta.Duration = durSec
- width, height := summary.Width, summary.Height
- if width <= 0 {
- width = plan.Width
- }
- if height <= 0 {
- height = plan.Height
- }
- videoMedia := library.MediaFile{
- Role: "video",
- Path: videoRel,
- Bytes: summary.FileBytes,
- SHA256: summary.SHA256,
- Width: width,
- Height: height,
- Duration: durSec,
- }
- m.setFileProgress(t, "video", videoRel, "completed", summary.FileBytes, summary.FileBytes, 0)
- meta.Media = mergeMediaFiles(meta.Media, []library.MediaFile{videoMedia})
- clearMissing(&meta, videoRel)
- meta.DouyinVideo = &library.DouyinVideoInfo{
- File: videoRel,
- Gear: plan.VideoGear,
- QualityName: plan.QualityName,
- Codec: firstNonEmptyStr(plan.Codec, summaryPrimaryVideoCodec(summary)),
- Width: width,
- Height: height,
- FPS: plan.FPS,
- Bitrate: plan.Bitrate,
- AvailableGears: append([]string(nil), plan.AvailableGears...),
- }
- if original {
- info := meta.DouyinVideo
- info.Gear, info.QualityName = douyinOriginalGear, douyinOriginalQuality
- info.Codec = firstNonEmptyStr(summaryPrimaryVideoCodec(summary), plan.Codec)
- info.FPS = 0
- info.Bitrate = 0
- if summary.DurationSec > 0 {
- info.Bitrate = int64(float64(summary.FileBytes*8) / summary.DurationSec)
- }
- info.AvailableGears = append([]string{douyinOriginalQuality}, plan.AvailableGears...)
- }
- }
-
- if meta.DouyinVideo == nil && previous.DouyinVideo != nil {
- cp := *previous.DouyinVideo
- meta.DouyinVideo = &cp
- }
-
- meta.Status = "complete"
- if len(meta.Missing) > 0 {
- meta.Status = "partial"
- t.Status = "partial"
- }
- saved, err := m.lib.SaveItem(itemDir, meta)
- if err != nil {
- return err
- }
- t.ItemKey = saved.ItemKey
- finalSaved = true
- return nil
-}
-
-func (m *Manager) executeDouyinNoteTask(ctx context.Context, t *Task, plan WorkDownloadPlan, planner WorkPlanner) (result error) {
- previous, exists, itemDir, err := m.resolveDouyinItemDir(t, "dynamic", plan.AuthorUID, t.TargetID)
- if err != nil {
- return err
- }
-
- m.mu.Lock()
- cfg := m.dlSettings
- m.mu.Unlock()
-
- title := firstNonEmptyStr(plan.Title, plan.Desc, t.Title, "抖音图文 "+t.TargetID)
- canonicalURL := firstNonEmptyStr(sanitizeStoredURL(plan.CanonicalURL), "https://www.douyin.com/note/"+t.TargetID)
- t.Title = title
- t.AuthorName = firstNonEmptyStr(plan.AuthorName, t.AuthorName)
- t.AuthorFace = sanitizeStoredURL(firstNonEmptyStr(plan.AuthorFace, t.AuthorFace))
- if len(plan.CoverURLs) > 0 {
- t.CoverURL = sanitizeStoredURL(plan.CoverURLs[0])
- }
-
- var mediaFiles []library.MediaFile
- var notePages []library.NotePageRecord
- var missing []library.MissingRecord
- var partialErrors []string
- finalSaved := false
-
- defer func() {
- if result == nil || finalSaved {
- return
- }
- if !isSiteStopError(result) {
- missing = append(missing, library.MissingRecord{
- Item: "note",
- Reason: "图文缓存尚未完成 (" + classifyDownloadError(result) + ")",
- })
- }
- partialMeta := library.ItemMetadata{
- Version: 1,
- ID: "dynamic:" + t.TargetID,
- Site: "douyin",
- Kind: "dynamic",
- Status: "partial",
- Title: title,
- Desc: plan.Desc,
- Text: firstNonEmptyStr(plan.Desc, plan.Title),
- DynamicType: "draw",
- TypeLabel: "图文",
- URL: canonicalURL,
- PubTs: plan.PubTs,
- CachedAt: previous.CachedAt,
- Author: library.ItemAuthor{
- Site: "douyin",
- UID: plan.AuthorUID,
- UniqueID: plan.AuthorUniqueID,
- Name: t.AuthorName,
- Face: t.AuthorFace,
- },
- Media: mergeMediaFiles(previous.Media, mediaFiles),
- NotePages: notePages,
- Missing: missing,
- }
- if saved, sErr := m.lib.SaveItem(itemDir, partialMeta); sErr == nil {
- t.ItemKey = saved.ItemKey
- }
- }()
-
- // Optional cover. when explicitly provided.
- if cfg.SaveCover && len(plan.CoverURLs) > 0 {
- refreshCover := m.makePerFileURLRefresher(ctx, t.TargetID, planner, func(fresh WorkDownloadPlan) ([]string, error) {
- return fresh.CoverURLs, nil
- })
- if coverMedia, cErr := m.cacheDouyinSniffedImage(ctx, t, itemDir, previous, exists, "cover", "cover", plan.CoverURLs, 0, 0, plan.Transport, refreshCover); cErr == nil && coverMedia != nil {
- mediaFiles = append(mediaFiles, *coverMedia)
- }
- }
-
- // Process ordered pages 1..N.
- for i, page := range plan.Pages {
- pageIdx := page.Index
- if pageIdx <= 0 {
- pageIdx = i + 1
- }
- prefix := fmt.Sprintf("images/%02d", pageIdx)
- pageKind := strings.ToLower(strings.TrimSpace(page.Kind))
- if pageKind == "" {
- if len(page.VideoURLs) > 0 {
- pageKind = "live_photo"
- } else {
- pageKind = "image"
- }
- }
-
- switch pageKind {
- case "image":
- refreshImg := m.makePerFileURLRefresher(ctx, t.TargetID, planner, func(fresh WorkDownloadPlan) ([]string, error) {
- if p, ok := findPlannedPage(fresh.Pages, pageIdx, i); ok {
- return p.ImageURLs, nil
- }
- return nil, nil
- })
- imgMedia, imgErr := m.cacheDouyinSniffedImage(ctx, t, itemDir, previous, exists, "image", prefix, page.ImageURLs, page.Width, page.Height, plan.Transport, refreshImg)
- if imgErr != nil {
- if isSiteStopError(imgErr) || isStorageError(imgErr) || ctx.Err() != nil {
- return imgErr
- }
- reason := fmt.Sprintf("第 %02d 页图片下载失败 (%s)", pageIdx, classifyDownloadError(imgErr))
- missing = append(missing, library.MissingRecord{Item: fmt.Sprintf("page_%02d", pageIdx), Reason: reason})
- partialErrors = append(partialErrors, reason)
- notePages = append(notePages, library.NotePageRecord{Index: pageIdx, Kind: "image", Width: page.Width, Height: page.Height})
- continue
- }
- mediaFiles = append(mediaFiles, *imgMedia)
- notePages = append(notePages, library.NotePageRecord{
- Index: pageIdx,
- Kind: "image",
- Image: imgMedia.Path,
- Width: page.Width,
- Height: page.Height,
- })
-
- case "live_photo", "motion":
- refreshImg := m.makePerFileURLRefresher(ctx, t.TargetID, planner, func(fresh WorkDownloadPlan) ([]string, error) {
- if p, ok := findPlannedPage(fresh.Pages, pageIdx, i); ok {
- return p.ImageURLs, nil
- }
- return nil, nil
- })
- imgMedia, imgErr := m.cacheDouyinSniffedImage(ctx, t, itemDir, previous, exists, "image", prefix, page.ImageURLs, page.Width, page.Height, plan.Transport, refreshImg)
- if imgErr != nil {
- if isSiteStopError(imgErr) || isStorageError(imgErr) || ctx.Err() != nil {
- return imgErr
- }
- reason := fmt.Sprintf("第 %02d 页实况静帧下载失败 (%s)", pageIdx, classifyDownloadError(imgErr))
- missing = append(missing, library.MissingRecord{Item: fmt.Sprintf("page_%02d", pageIdx), Reason: reason})
- partialErrors = append(partialErrors, reason)
- notePages = append(notePages, library.NotePageRecord{Index: pageIdx, Kind: "motion", Width: page.Width, Height: page.Height, Duration: page.DurationSec})
- continue
- }
-
- motionRel := fmt.Sprintf("images/%02d_live.mp4", pageIdx)
- refreshMotion := m.makePerFileURLRefresher(ctx, t.TargetID, planner, func(fresh WorkDownloadPlan) ([]string, error) {
- if p, ok := findPlannedPage(fresh.Pages, pageIdx, i); ok {
- return p.VideoURLs, nil
- }
- return nil, nil
- })
- motionMedia, mErr := m.cacheDouyinSingleMP4(ctx, t, itemDir, previous, exists, "motion", motionRel, page.VideoURLs, page.DurationSec, page.Width, page.Height, plan.Transport, refreshMotion)
- rec := library.NotePageRecord{
- Index: pageIdx,
- Kind: "motion",
- Image: imgMedia.Path,
- Width: page.Width,
- Height: page.Height,
- Duration: page.DurationSec,
- }
- if mErr != nil {
- if isSiteStopError(mErr) || isStorageError(mErr) || ctx.Err() != nil {
- return mErr
- }
- reason := fmt.Sprintf("第 %02d 页实况视频下载失败 (%s)", pageIdx, classifyDownloadError(mErr))
- missing = append(missing, library.MissingRecord{Item: motionRel, Reason: reason})
- partialErrors = append(partialErrors, reason)
- } else if motionMedia != nil {
- imgMedia.Motion = motionMedia.Path
- rec.Motion = motionMedia.Path
- if motionMedia.Duration > 0 {
- rec.Duration = motionMedia.Duration
- }
- mediaFiles = append(mediaFiles, *motionMedia)
- }
- mediaFiles = append(mediaFiles, *imgMedia)
- notePages = append(notePages, rec)
-
- case "video":
- var coverRel string
- if len(page.ImageURLs) > 0 {
- refreshPageCover := m.makePerFileURLRefresher(ctx, t.TargetID, planner, func(fresh WorkDownloadPlan) ([]string, error) {
- if p, ok := findPlannedPage(fresh.Pages, pageIdx, i); ok {
- return p.ImageURLs, nil
- }
- return nil, nil
- })
- coverMedia, cErr := m.cacheDouyinSniffedImage(ctx, t, itemDir, previous, exists, "image", prefix, page.ImageURLs, page.Width, page.Height, plan.Transport, refreshPageCover)
- if cErr != nil {
- if isSiteStopError(cErr) || isStorageError(cErr) || ctx.Err() != nil {
- return cErr
- }
- reason := fmt.Sprintf("第 %02d 页视频封面下载失败 (%s)", pageIdx, classifyDownloadError(cErr))
- missing = append(missing, library.MissingRecord{Item: fmt.Sprintf("page_%02d.cover", pageIdx), Reason: reason})
- partialErrors = append(partialErrors, reason)
- } else if coverMedia != nil {
- coverRel = coverMedia.Path
- mediaFiles = append(mediaFiles, *coverMedia)
- }
- }
-
- videoRel := fmt.Sprintf("images/%02d.mp4", pageIdx)
- refreshPageVideo := m.makePerFileURLRefresher(ctx, t.TargetID, planner, func(fresh WorkDownloadPlan) ([]string, error) {
- if p, ok := findPlannedPage(fresh.Pages, pageIdx, i); ok {
- return p.VideoURLs, nil
- }
- return nil, nil
- })
- vidMedia, vErr := m.cacheDouyinSingleMP4(ctx, t, itemDir, previous, exists, "video", videoRel, page.VideoURLs, page.DurationSec, page.Width, page.Height, plan.Transport, refreshPageVideo)
- rec := library.NotePageRecord{
- Index: pageIdx,
- Kind: "video",
- Cover: coverRel,
- Width: page.Width,
- Height: page.Height,
- Duration: page.DurationSec,
- }
- if vErr != nil {
- if isSiteStopError(vErr) || isStorageError(vErr) || ctx.Err() != nil {
- return vErr
- }
- reason := fmt.Sprintf("第 %02d 页视频下载失败 (%s)", pageIdx, classifyDownloadError(vErr))
- missing = append(missing, library.MissingRecord{Item: videoRel, Reason: reason})
- partialErrors = append(partialErrors, reason)
- } else if vidMedia != nil {
- rec.Video = vidMedia.Path
- if vidMedia.Duration > 0 {
- rec.Duration = vidMedia.Duration
- }
- if vidMedia.Width > 0 {
- rec.Width = vidMedia.Width
- }
- if vidMedia.Height > 0 {
- rec.Height = vidMedia.Height
- }
- rec.VideoInfo = &library.DouyinVideoInfo{
- File: vidMedia.Path,
- Gear: page.Gear,
- QualityName: page.QualityName,
- Codec: page.Codec,
- Width: rec.Width,
- Height: rec.Height,
- FPS: page.FPS,
- Bitrate: page.Bitrate,
- }
- mediaFiles = append(mediaFiles, *vidMedia)
- }
- notePages = append(notePages, rec)
-
- default:
- // Unrecognized page kind ("unknown"): keep available image, record unknownKind + missing, never fail whole item.
- var savedImg string
- if len(page.ImageURLs) > 0 {
- refreshUnknownImg := m.makePerFileURLRefresher(ctx, t.TargetID, planner, func(fresh WorkDownloadPlan) ([]string, error) {
- if p, ok := findPlannedPage(fresh.Pages, pageIdx, i); ok {
- return p.ImageURLs, nil
- }
- return nil, nil
- })
- if imgMedia, imgErr := m.cacheDouyinSniffedImage(ctx, t, itemDir, previous, exists, "image", prefix, page.ImageURLs, page.Width, page.Height, plan.Transport, refreshUnknownImg); imgErr != nil {
- if isSiteStopError(imgErr) || isStorageError(imgErr) || ctx.Err() != nil {
- return imgErr
- }
- } else if imgMedia != nil {
- savedImg = imgMedia.Path
- mediaFiles = append(mediaFiles, *imgMedia)
- }
- }
- unkTag := firstNonEmptyStr(page.UnknownKind, pageKind, "unknown")
- reason := firstNonEmptyStr(page.UnknownReason, fmt.Sprintf("第 %02d 页包含暂未识别的页面类型 (%s),已保留可用图片", pageIdx, unkTag))
- missing = append(missing, library.MissingRecord{
- Item: fmt.Sprintf("page_%02d", pageIdx),
- Reason: reason,
- })
- notePages = append(notePages, library.NotePageRecord{
- Index: pageIdx,
- Kind: "unknown",
- UnknownKind: unkTag,
- Image: savedImg,
- Width: page.Width,
- Height: page.Height,
- })
- }
- }
-
- // Process background music if present on the note.
- var musicInfo *library.MusicInfo
- if plan.Music != nil {
- musicCover := ""
- if len(plan.Music.CoverURLs) > 0 {
- musicCover = sanitizeStoredURL(plan.Music.CoverURLs[0])
- }
- musicInfo = &library.MusicInfo{
- ID: plan.Music.ID,
- Title: plan.Music.Title,
- Author: plan.Music.Author,
- Duration: plan.Music.DurationSec,
- Cover: musicCover,
- Original: plan.Music.Original,
- }
- if len(plan.Music.PlayURLs) == 0 {
- missing = append(missing, library.MissingRecord{
- Item: "music",
- Reason: "配乐无可用地址(版权或地区限制)",
- })
- } else {
- refreshMusic := m.makePerFileURLRefresher(ctx, t.TargetID, planner, func(fresh WorkDownloadPlan) ([]string, error) {
- if fresh.Music != nil {
- return fresh.Music.PlayURLs, nil
- }
- return nil, nil
- })
- musicMedia, mErr := m.cacheDouyinSniffedAudio(ctx, t, itemDir, previous, exists, "music", plan.Music.PlayURLs, plan.Music.DurationSec, plan.Transport, refreshMusic)
- if mErr != nil {
- if isSiteStopError(mErr) || isStorageError(mErr) || ctx.Err() != nil {
- return mErr
- }
- reason := fmt.Sprintf("配乐下载失败 (%s)", classifyDownloadError(mErr))
- missing = append(missing, library.MissingRecord{
- Item: "music",
- Reason: reason,
- })
- partialErrors = append(partialErrors, reason)
- } else if musicMedia != nil {
- musicInfo.File = musicMedia.Path
- mediaFiles = append(mediaFiles, *musicMedia)
- }
- }
- }
-
- status := "complete"
- if len(missing) > 0 || len(partialErrors) > 0 {
- status = "partial"
- t.Status = "partial"
- }
-
- meta := library.ItemMetadata{
- Version: 1,
- ID: "dynamic:" + t.TargetID,
- Site: "douyin",
- Kind: "dynamic",
- Status: status,
- Title: title,
- Desc: plan.Desc,
- Text: firstNonEmptyStr(plan.Desc, plan.Title),
- DynamicType: "draw",
- TypeLabel: "图文",
- URL: canonicalURL,
- PubTs: plan.PubTs,
- CachedAt: previous.CachedAt,
- Author: library.ItemAuthor{
- Site: "douyin",
- UID: plan.AuthorUID,
- UniqueID: plan.AuthorUniqueID,
- Name: t.AuthorName,
- Face: t.AuthorFace,
- },
- Media: mediaFiles,
- NotePages: notePages,
- Music: musicInfo,
- Missing: missing,
- DirectCached: true,
- }
-
- saved, saveErr := m.lib.SaveItem(itemDir, meta)
- if saveErr != nil {
- return saveErr
- }
- t.ItemKey = saved.ItemKey
- finalSaved = true
- return nil
-}
-
-func findPlannedPage(pages []PlannedNotePage, index, fallbackPos int) (PlannedNotePage, bool) {
- for _, p := range pages {
- if p.Index == index {
- return p, true
- }
- }
- if fallbackPos >= 0 && fallbackPos < len(pages) {
- return pages[fallbackPos], true
- }
- return PlannedNotePage{}, false
-}
-
-func replaceRoleMedia(existing []library.MediaFile, role string, added library.MediaFile) []library.MediaFile {
- var filtered []library.MediaFile
- for _, mf := range existing {
- if mf.Role != role {
- filtered = append(filtered, mf)
- }
- }
- return append(filtered, added)
-}
-
-func (m *Manager) makeSinglePlanRefresher(ctx context.Context, targetID string, planner WorkPlanner) func() (WorkDownloadPlan, error) {
- var called bool
- var cached WorkDownloadPlan
- var cachedErr error
- return func() (WorkDownloadPlan, error) {
- if called {
- return cached, cachedErr
- }
- called = true
- if planner == nil {
- cachedErr = &site.Error{Site: site.Douyin, Kind: site.ErrKindUnavailable, Message: "无法刷新过期的媒体地址"}
- return WorkDownloadPlan{}, cachedErr
- }
- m.mu.Lock()
- opts := WorkPlanOptions{
- VideoQuality: m.dlSettings.VideoQuality,
- CodecOrder: append([]string(nil), m.dlSettings.CodecOrder...),
- }
- m.mu.Unlock()
- cached, cachedErr = planner.PlanWorkDownload(ctx, targetID, opts)
- return cached, cachedErr
- }
-}
-
-// makePerFileURLRefresher ensures each file re-fetches work detail at most once on 403/404/410.
-func (m *Manager) makePerFileURLRefresher(
- ctx context.Context,
- targetID string,
- planner WorkPlanner,
- extract func(WorkDownloadPlan) ([]string, error),
-) func() ([]string, error) {
- refreshPlan := m.makeSinglePlanRefresher(ctx, targetID, planner)
- var used bool
- return func() ([]string, error) {
- if used {
- return nil, nil
- }
- used = true
- fresh, err := refreshPlan()
- if err != nil {
- return nil, err
- }
- return extract(fresh)
- }
-}
-
-func (m *Manager) cacheDouyinSingleMP4(
- ctx context.Context,
- t *Task,
- itemDir string,
- previous library.ItemMetadata,
- exists bool,
- role string,
- relPath string,
- urls []string,
- expectedDuration int,
- fallbackW, fallbackH int,
- transport site.MediaTransportSpec,
- refreshURLs func() ([]string, error),
-) (*library.MediaFile, error) {
- if exists && mediaIsValid(previous, relPath) {
- for _, mf := range previous.Media {
- if mf.Path == relPath {
- m.setFileProgress(t, role, relPath, "completed", mf.Bytes, mf.Bytes, 0)
- cp := mf
- return &cp, nil
- }
- }
- }
- fullPath, err := library.ResolveItemPath(itemDir, relPath)
- if err != nil {
- return nil, err
- }
- if err := m.claimTaskFile(t, itemDir, relPath, fullPath); err != nil {
- return nil, err
- }
- m.setFileProgress(t, role, relPath, "downloading", 0, 0, 0)
- rawRel := relPath + ".raw"
- stagingPath := fullPath + ".raw"
- if _, _, err := m.downloadWithTransportRefresh(ctx, transport, urls, stagingPath, role, t, refreshURLs); err != nil {
- if ctx.Err() == nil && !fileOrPartExists(stagingPath) {
- m.removeTempTaskProgress(t, rawRel)
- }
- m.setFileProgress(t, role, relPath, "failed", 0, 0, 0)
- return nil, err
- }
- m.setFileProgress(t, role, relPath, "verifying", 0, 0, 0)
- summary, err := EnsureSingleMP4Context(ctx, stagingPath, float64(expectedDuration))
- if err != nil {
- _ = os.Remove(stagingPath)
- if ctx.Err() == nil {
- m.removeTempTaskProgress(t, rawRel)
- }
- m.setFileProgress(t, role, relPath, "failed", 0, 0, 0)
- return nil, err
- }
- if err := ctx.Err(); err != nil {
- _ = os.Remove(stagingPath)
- return nil, err
- }
- if err := os.Rename(stagingPath, fullPath); err != nil {
- return nil, err
- }
- m.removeTempTaskProgress(t, rawRel)
- dur := int(math.Round(summary.DurationSec))
- if dur <= 0 {
- dur = expectedDuration
- }
- w, h := summary.Width, summary.Height
- if w <= 0 {
- w = fallbackW
- }
- if h <= 0 {
- h = fallbackH
- }
- m.setFileProgress(t, role, relPath, "completed", summary.FileBytes, summary.FileBytes, 0)
- return &library.MediaFile{
- Role: role,
- Path: relPath,
- Bytes: summary.FileBytes,
- SHA256: summary.SHA256,
- Width: w,
- Height: h,
- Duration: dur,
- }, nil
-}
-
-func (m *Manager) cacheDouyinSniffedImage(
- ctx context.Context,
- t *Task,
- itemDir string,
- previous library.ItemMetadata,
- exists bool,
- role string,
- relStem string,
- urls []string,
- width, height int,
- transport site.MediaTransportSpec,
- refreshURLs func() ([]string, error),
-) (*library.MediaFile, error) {
- if exists {
- for _, mf := range previous.Media {
- if mf.Role == role && strings.HasPrefix(mf.Path, relStem+".") && mediaIsValid(previous, mf.Path) {
- m.setFileProgress(t, role, mf.Path, "completed", mf.Bytes, mf.Bytes, 0)
- cp := mf
- return &cp, nil
- }
- }
- }
-
- tempRel := relStem + ".imgtmp"
- tempFull, err := library.ResolveItemPath(itemDir, tempRel)
- if err != nil {
- return nil, err
- }
- if err := m.claimTaskFile(t, itemDir, 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
- }
- n, sha, ct, err := m.downloadWithTransportRefreshCT(ctx, transport, urls, tempFull, role, t, refreshURLs)
- if err != nil {
- _ = os.Remove(tempFull)
- if ctx.Err() == nil && !fileOrPartExists(tempFull) {
- m.removeTempTaskProgress(t, tempRel)
- }
- return nil, err
- }
- ext, err := sniffImageExtension(tempFull, ct)
- if err != nil {
- _ = os.Remove(tempFull)
- if ctx.Err() == nil {
- m.removeTempTaskProgress(t, tempRel)
- }
- return nil, &site.Error{Site: transport.Site, Kind: site.ErrKindSchemaChanged, Message: err.Error()}
- }
- finalRel := relStem + ext
- finalFull, err := library.ResolveItemPath(itemDir, finalRel)
- if err != nil {
- _ = os.Remove(tempFull)
- if ctx.Err() == nil {
- m.removeTempTaskProgress(t, tempRel)
- }
- return nil, err
- }
- if err := m.claimTaskFile(t, itemDir, finalRel, finalFull); err != nil {
- _ = os.Remove(tempFull)
- if ctx.Err() == nil {
- m.removeTempTaskProgress(t, tempRel)
- }
- return nil, err
- }
- if err := ctx.Err(); err != nil {
- _ = os.Remove(tempFull)
- return nil, err
- }
- if err := os.Rename(tempFull, finalFull); err != nil {
- _ = os.Remove(tempFull)
- if ctx.Err() == nil {
- m.removeTempTaskProgress(t, tempRel)
- }
- return nil, err
- }
- m.removeTempTaskProgress(t, tempRel)
- m.setFileProgress(t, role, finalRel, "completed", n, n, 0)
- return &library.MediaFile{
- Role: role,
- Path: finalRel,
- Bytes: n,
- SHA256: sha,
- Width: width,
- Height: height,
- }, nil
-}
-
-func (m *Manager) cacheDouyinSniffedAudio(
- ctx context.Context,
- t *Task,
- itemDir string,
- previous library.ItemMetadata,
- exists bool,
- relStem string,
- urls []string,
- durationSec int,
- transport site.MediaTransportSpec,
- refreshURLs func() ([]string, error),
-) (*library.MediaFile, error) {
- if exists {
- for _, mf := range previous.Media {
- if mf.Role == "audio" && strings.HasPrefix(mf.Path, relStem+".") && mediaIsValid(previous, mf.Path) {
- m.setFileProgress(t, "audio", mf.Path, "completed", mf.Bytes, mf.Bytes, 0)
- cp := mf
- return &cp, nil
- }
- }
- }
-
- tempRel := relStem + ".audtmp"
- tempFull, err := library.ResolveItemPath(itemDir, tempRel)
- if err != nil {
- return nil, err
- }
- if err := m.claimTaskFile(t, itemDir, tempRel, tempFull); err != nil {
- return nil, err
- }
- if err := ctx.Err(); err != nil {
- return nil, err
- }
- n, sha, ct, err := m.downloadWithTransportRefreshCT(ctx, transport, urls, tempFull, "audio", t, refreshURLs)
- if err != nil {
- _ = os.Remove(tempFull)
- if ctx.Err() == nil && !fileOrPartExists(tempFull) {
- m.removeTempTaskProgress(t, tempRel)
- }
- return nil, err
- }
- ext, err := sniffAudioExtension(tempFull, ct)
- if err != nil {
- _ = os.Remove(tempFull)
- if ctx.Err() == nil {
- m.removeTempTaskProgress(t, tempRel)
- }
- return nil, &site.Error{Site: transport.Site, Kind: site.ErrKindSchemaChanged, Message: err.Error()}
- }
- finalRel := relStem + ext
- finalFull, err := library.ResolveItemPath(itemDir, finalRel)
- if err != nil {
- _ = os.Remove(tempFull)
- if ctx.Err() == nil {
- m.removeTempTaskProgress(t, tempRel)
- }
- return nil, err
- }
- if err := m.claimTaskFile(t, itemDir, finalRel, finalFull); err != nil {
- _ = os.Remove(tempFull)
- if ctx.Err() == nil {
- m.removeTempTaskProgress(t, tempRel)
- }
- return nil, err
- }
- if err := ctx.Err(); err != nil {
- _ = os.Remove(tempFull)
- return nil, err
- }
- if err := os.Rename(tempFull, finalFull); err != nil {
- _ = os.Remove(tempFull)
- if ctx.Err() == nil {
- m.removeTempTaskProgress(t, tempRel)
- }
- return nil, err
- }
- m.removeTempTaskProgress(t, tempRel)
- m.setFileProgress(t, "audio", finalRel, "completed", n, n, 0)
- return &library.MediaFile{
- Role: "audio",
- Path: finalRel,
- Bytes: n,
- SHA256: sha,
- Duration: durationSec,
- }, nil
-}
-
-func fileOrPartExists(path string) bool {
- if _, err := os.Stat(path); err == nil {
- return true
- }
- if _, err := os.Stat(path + ".part"); err == nil {
- return true
- }
- return false
-}
-
-const (
- douyinOriginalGear = "original"
- douyinOriginalQuality = "原画"
-)
-
-// cacheDouyinOriginal downloads the untranscoded source (原画) into its own staging
-// file and validates it as a single progressive MP4, then moves it to videoPath.
-// On a failure the caller falls back to the transcoded stream, so the staging file
-// is removed unless the task was cancelled or paused (kept for resume).
-func (m *Manager) cacheDouyinOriginal(ctx context.Context, t *Task, plan WorkDownloadPlan, planner WorkPlanner, videoRel, videoPath string) (MuxTrackSummary, error) {
- origRel := videoRel + ".orig.raw"
- origPath := videoPath + ".orig.raw"
- discard := func() {
- if ctx.Err() == nil {
- _ = os.Remove(origPath)
- _ = os.Remove(origPath + ".part")
- m.removeTempTaskProgress(t, origRel)
- }
- }
- refresh := m.makePerFileURLRefresher(ctx, t.TargetID, planner, func(fresh WorkDownloadPlan) ([]string, error) {
- if len(fresh.OriginalURLs) == 0 {
- return nil, &site.Error{Site: site.Douyin, Kind: site.ErrKindUnavailable, Message: "原画地址已不可用"}
- }
- return fresh.OriginalURLs, nil
- })
- if _, _, err := m.downloadWithTransportRefresh(ctx, plan.Transport, plan.OriginalURLs, origPath, "video", t, refresh); err != nil {
- discard()
- return MuxTrackSummary{}, err
- }
- m.setFileProgress(t, "video", videoRel, "verifying", t.BytesDownloaded, t.TotalBytes, 0)
- summary, err := EnsureSingleMP4Context(ctx, origPath, float64(plan.DurationSec))
- if err == nil && summaryPrimaryVideoCodec(summary) == "" {
- err = &site.Error{Site: site.Douyin, Kind: site.ErrKindSchemaChanged, Message: "原画文件没有视频轨"}
- }
- if err == nil {
- err = ctx.Err()
- }
- if err == nil {
- err = os.Rename(origPath, videoPath)
- }
- if err != nil {
- discard()
- return MuxTrackSummary{}, err
- }
- m.removeTempTaskProgress(t, origRel)
- return summary, nil
-}
-
-func trimStagingSuffixes(p string) string {
- for _, suf := range []string{".part", ".raw", ".imgtmp", ".audtmp"} {
- p = strings.TrimSuffix(p, suf)
- }
- return p
-}
-
-func (m *Manager) removeTempTaskProgress(t *Task, tempRel string) {
- filtered := t.Files[:0]
- for _, f := range t.Files {
- if taskFileIdentity(f.Path) != taskFileIdentity(tempRel) {
- filtered = append(filtered, f)
- }
- }
- t.Files = filtered
-}
-
-func (m *Manager) downloadWithTransportRefresh(
- ctx context.Context,
- transport site.MediaTransportSpec,
- urls []string,
- finalPath string,
- role string,
- t *Task,
- refreshURLs func() ([]string, error),
-) (int64, string, error) {
- n, sha, _, err := m.downloadWithTransportRefreshCT(ctx, transport, urls, finalPath, role, t, refreshURLs)
- return n, sha, err
-}
-
-func (m *Manager) downloadWithTransportRefreshCT(
- ctx context.Context,
- transport site.MediaTransportSpec,
- urls []string,
- finalPath string,
- role string,
- t *Task,
- refreshURLs func() ([]string, error),
-) (int64, string, string, error) {
- n, sha, ct, err := m.downloadWithTransportRange(ctx, transport, urls, finalPath, role, t)
- if err == nil {
- return n, sha, ct, nil
- }
- if refreshURLs != nil && (site.IsKind(err, site.ErrKindForbidden) || site.IsKind(err, site.ErrKindUnavailable)) {
- freshURLs, rErr := refreshURLs()
- if rErr != nil {
- if site.IsKind(rErr, site.ErrKindRiskControl) || site.IsKind(rErr, site.ErrKindRateLimited) || site.IsKind(rErr, site.ErrKindAuthRequired) {
- return 0, "", "", rErr
- }
- return 0, "", "", err
- }
- if len(freshURLs) > 0 {
- return m.downloadWithTransportRange(ctx, transport, freshURLs, finalPath, role, t)
- }
- }
- return 0, "", "", err
-}
-
-func (m *Manager) downloadWithTransportRange(
- ctx context.Context,
- transport site.MediaTransportSpec,
- urls []string,
- finalPath string,
- role string,
- t *Task,
-) (int64, string, string, error) {
- var cleanURLs []string
- var lastValidateErr error
- for _, u := range urls {
- u = strings.TrimSpace(u)
- if u == "" {
- continue
- }
- if vErr := transport.ValidateURL(u); vErr != nil {
- lastValidateErr = vErr
- continue
- }
- cleanURLs = append(cleanURLs, u)
- }
- if len(cleanURLs) == 0 {
- if lastValidateErr != nil {
- return 0, "", "", lastValidateErr
- }
- return 0, "", "", &site.Error{
- Site: transport.Site,
- Kind: site.ErrKindUnavailable,
- Message: "下载地址列表为空",
- }
- }
-
- root, rel := filepath.Dir(finalPath), filepath.Base(finalPath)
- if t.ItemDir != "" {
- root = t.ItemDir
- r, err := filepath.Rel(root, finalPath)
- if err != nil {
- return 0, "", "", err
- }
- rel = filepath.ToSlash(r)
- }
- if _, err := library.ResolveItemPath(root, rel); err != nil {
- return 0, "", "", err
- }
- if _, err := library.ResolveItemPath(root, rel+".part"); err != nil {
- return 0, "", "", err
- }
- if err := m.claimTaskFile(t, root, rel, finalPath); err != nil {
- return 0, "", "", err
- }
- if err := ctx.Err(); err != nil {
- return 0, "", "", err
- }
- if err := os.MkdirAll(filepath.Dir(finalPath), 0o700); err != nil {
- return 0, "", "", err
- }
-
- m.mu.Lock()
- chunkSize := m.chunkSize
- if chunkSize <= 0 {
- chunkSize = DefaultRangeChunkSize
- }
- backoffScale := m.backoffScale
- if backoffScale <= 0 {
- backoffScale = time.Second
- }
- mediaWrap := m.mediaWrap
- m.mu.Unlock()
-
- httpClient := newTransportHTTPClient(transport)
- if mediaWrap != nil {
- httpClient.Transport = mediaWrap(httpClient.Transport)
- }
- partPath := finalPath + ".part"
- relFile := taskRelativePath(t, trimStagingSuffixes(finalPath))
-
- var offset int64
- if info, err := os.Stat(partPath); err == nil && !info.IsDir() {
- offset = info.Size()
- }
-
- var totalSize int64 = -1
- var contentType string
- urlIdx := 0
- segRetries := 0
- fullResets := 0
- var lastErr error
-
- for {
- if ctx.Err() != nil {
- return offset, "", "", ctx.Err()
- }
- if totalSize > 0 && offset == totalSize {
- break
- }
-
- targetURL := cleanURLs[urlIdx%len(cleanURLs)]
- endByte := offset + chunkSize - 1
- if totalSize > 0 && endByte >= totalSize {
- endByte = totalSize - 1
- }
-
- res, ct, err := m.fetchTransportSegment(ctx, httpClient, transport, targetURL, partPath, offset, endByte, totalSize, role, t)
- if err == nil {
- if ct != "" {
- contentType = ct
- }
- offset = res.newOffset
- if res.totalSize > 0 {
- totalSize = res.totalSize
- }
- segRetries = 0
- if res.done || (totalSize > 0 && offset >= totalSize) {
- break
- }
- continue
- }
-
- lastErr = err
- errKind := classifyDownloadError(err)
- httpStatus := 0
- var se *site.Error
- if errors.As(err, &se) {
- httpStatus = se.HTTPStatus
- }
-
- if errKind == site.ErrKindRiskControl || errKind == site.ErrKindRateLimited || errKind == site.ErrKindAuthRequired || errKind == site.ErrKindBlocked || errKind == site.ErrKindSchemaChanged || isStorageError(err) {
- m.recordAttempt(t, relFile, offset, targetURL, segRetries+1, errKind, httpStatus)
- return offset, "", "", err
- }
-
- if res.truncatedToZero {
- offset = 0
- totalSize = -1
- fullResets++
- urlIdx++
- m.recordAttempt(t, relFile, offset, targetURL, fullResets, site.ErrKindNetwork, http.StatusOK)
- if fullResets >= 5 {
- t.Status = "paused"
- t.PauseReason = "network"
- t.ErrorKind = site.ErrKindNetwork
- t.ErrorMessage = "已暂停(网络):节点不支持分段续传且重试已达上限"
- return offset, "", "", lastErr
- }
- continue
- }
-
- if errKind == site.ErrKindForbidden || errKind == site.ErrKindUnavailable {
- segRetries++
- urlIdx++
- m.recordAttempt(t, relFile, offset, targetURL, segRetries, errKind, httpStatus)
- if segRetries >= len(cleanURLs) {
- return offset, "", "", lastErr
- }
- continue
- }
-
- offset = res.newOffset
- if res.totalSize > 0 {
- totalSize = res.totalSize
- }
- segRetries++
- urlIdx++
- m.recordAttempt(t, relFile, offset, targetURL, segRetries, errKind, httpStatus)
- if segRetries >= 5 {
- t.Status = "paused"
- t.PauseReason = "network"
- t.ErrorKind = site.ErrKindNetwork
- t.ErrorMessage = "已暂停(网络):分段重试已达上限"
- return offset, "", "", lastErr
- }
-
- backoffUnits := int64(1 << (segRetries - 1))
- if backoffUnits > 16 {
- backoffUnits = 16
- }
- sleepDur := time.Duration(backoffUnits) * backoffScale
- sleepDur = time.Duration(float64(sleepDur) * (0.8 + 0.4*jitterrand.Float64()))
- select {
- case <-ctx.Done():
- return offset, "", "", ctx.Err()
- case <-time.After(sleepDur):
- }
- }
-
- shaHex, actualSize, err := hashFileSHA256(partPath)
- if err != nil {
- return offset, "", "", err
- }
- if totalSize > 0 && actualSize != totalSize {
- return actualSize, "", "", &site.Error{
- Site: transport.Site,
- Kind: site.ErrKindNetwork,
- Message: fmt.Sprintf("文件大小校验不一致: 实际 %d != 预期 %d", actualSize, totalSize),
- }
- }
- if err := os.Rename(partPath, finalPath); err != nil {
- return actualSize, "", "", err
- }
- return actualSize, shaHex, contentType, nil
-}
-
-func (m *Manager) fetchTransportSegment(
- ctx context.Context,
- httpClient *http.Client,
- transport site.MediaTransportSpec,
- targetURL string,
- partPath string,
- offset int64,
- endByte int64,
- knownTotal int64,
- role string,
- t *Task,
-) (segmentResult, string, error) {
- if err := transport.ValidateURL(targetURL); err != nil {
- return segmentResult{newOffset: offset}, "", err
- }
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil)
- if err != nil {
- return segmentResult{newOffset: offset}, "", err
- }
- transport.ApplyHeaders(req)
- req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, endByte))
-
- resp, err := httpClient.Do(req)
- if err != nil {
- var se *site.Error
- if errors.As(err, &se) {
- return segmentResult{newOffset: offset}, "", se
- }
- return segmentResult{newOffset: offset}, "", &site.Error{
- Site: transport.Site,
- Kind: site.ErrKindNetwork,
- Message: "媒体下载连接失败",
- Err: err,
- }
- }
- defer resp.Body.Close()
-
- if resp.StatusCode == http.StatusRequestedRangeNotSatisfiable && offset > 0 {
- _ = os.Truncate(partPath, 0)
- return segmentResult{newOffset: 0, truncatedToZero: true}, "", &site.Error{
- Site: transport.Site,
- Kind: site.ErrKindNetwork,
- HTTPStatus: resp.StatusCode,
- Message: "Range 416,重置分段文件",
- }
- }
- if resp.StatusCode >= 400 {
- mapped := mapMediaHTTPStatus(resp.StatusCode, "")
- mapped.Site = transport.Site
- return segmentResult{newOffset: offset}, "", mapped
- }
-
- rawCT := strings.TrimSpace(resp.Header.Get("Content-Type"))
- if err := rejectDisguisedMediaContentType(transport.Site, rawCT, role, resp.StatusCode); err != nil {
- return segmentResult{newOffset: offset}, rawCT, err
- }
-
- isImage := role == "image" || role == "cover"
- var f *os.File
- var expectedSegLen int64 = -1
- totalSize := knownTotal
- doneAfterThis := false
-
- switch resp.StatusCode {
- case http.StatusPartialContent:
- cr := strings.TrimSpace(resp.Header.Get("Content-Range"))
- if cr == "" {
- return segmentResult{newOffset: offset}, rawCT, &site.Error{Site: transport.Site, Kind: site.ErrKindNetwork, Message: "206 响应缺少 Content-Range"}
- }
- start, end, total, ok := parseContentRange(cr)
- if !ok || start != offset || end < start || end > endByte || total <= end || (knownTotal > 0 && total != knownTotal) {
- return segmentResult{newOffset: offset}, rawCT, &site.Error{
- Site: transport.Site,
- Kind: site.ErrKindNetwork,
- Message: fmt.Sprintf("Content-Range 校验失败: %q", cr),
- }
- }
- if total > 0 {
- totalSize = total
- }
- expectedSegLen = end - start + 1
- if resp.ContentLength >= 0 && resp.ContentLength != expectedSegLen {
- return segmentResult{newOffset: offset}, rawCT, &site.Error{Site: transport.Site, Kind: site.ErrKindNetwork, Message: "分段 Content-Length 与区间长度不一致"}
- }
- if totalSize > 0 && end+1 >= totalSize {
- doneAfterThis = true
- }
- f, err = os.OpenFile(partPath, os.O_CREATE|os.O_WRONLY, 0o600)
- if err == nil {
- _, err = f.Seek(offset, io.SeekStart)
- }
-
- case http.StatusOK:
- if offset > 0 {
- _ = os.Remove(partPath)
- return segmentResult{newOffset: 0, truncatedToZero: true}, rawCT, &site.Error{
- Site: transport.Site,
- Kind: site.ErrKindNetwork,
- HTTPStatus: http.StatusOK,
- Message: "节点未返回 206 Partial Content,已截断从头重试",
- }
- }
- if resp.ContentLength <= 0 {
- return segmentResult{newOffset: offset}, rawCT, &site.Error{Site: transport.Site, Kind: site.ErrKindNetwork, Message: "完整响应缺少有效的 Content-Length"}
- }
- expectedSegLen = resp.ContentLength
- totalSize = resp.ContentLength
- doneAfterThis = true
- f, err = os.OpenFile(partPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
-
- default:
- mapped := mapMediaHTTPStatus(resp.StatusCode, "")
- mapped.Site = transport.Site
- return segmentResult{newOffset: offset}, rawCT, mapped
- }
-
- if isImage && totalSize > MaxImageFileBytes {
- if f != nil {
- _ = f.Close()
- }
- return segmentResult{newOffset: offset}, rawCT, &site.Error{Site: transport.Site, Kind: site.ErrKindSchemaChanged, Message: "图片超过 50 MiB"}
- }
- if err != nil {
- return segmentResult{newOffset: offset}, rawCT, err
- }
-
- idleBody := newMediaIdleReader(resp.Body, 20*time.Second)
- defer idleBody.Close()
- reader := io.LimitReader(idleBody, expectedSegLen+1)
-
- buf := make([]byte, 64*1024)
- var segWritten int64
- written := offset
- checkedHead := offset > 0
- if totalSize > 0 {
- t.TotalBytes = totalSize
- } else if resp.ContentLength > 0 {
- t.TotalBytes = offset + resp.ContentLength
- }
-
- relFile := taskRelativePath(t, strings.TrimSuffix(strings.TrimSuffix(partPath, ".part"), ".raw"))
- progressAt := time.Now()
- progressBytes := offset
-
- for {
- nr, rErr := reader.Read(buf)
- if nr > 0 {
- if !checkedHead {
- checkedHead = true
- if looksLikeDisguisedTextBody(buf[:nr]) {
- _ = f.Close()
- _ = os.Remove(partPath)
- return segmentResult{newOffset: 0}, rawCT, &site.Error{
- Site: transport.Site,
- Kind: site.ErrKindSchemaChanged,
- HTTPStatus: resp.StatusCode,
- Message: "媒体响应正文为 HTML 或 JSON 文本,已拒绝写入",
- }
- }
- }
- if segWritten+int64(nr) > expectedSegLen {
- _ = f.Close()
- _ = os.Truncate(partPath, offset)
- return segmentResult{newOffset: offset, totalSize: totalSize}, rawCT, &site.Error{Site: transport.Site, Kind: site.ErrKindNetwork, Message: "分段正文超出声明区间"}
- }
- nw, wErr := f.Write(buf[:nr])
- if wErr != nil {
- _ = f.Close()
- return segmentResult{newOffset: written, totalSize: totalSize}, rawCT, wErr
- }
- segWritten += int64(nw)
- written += int64(nw)
- t.BytesDownloaded = written
- if t.TotalBytes > 0 {
- t.Progress = float64(written) / float64(t.TotalBytes)
- if t.Progress > 0.99 {
- t.Progress = 0.99
- }
- }
- }
- if elapsed := time.Since(progressAt); elapsed >= 250*time.Millisecond {
- speed := int64(float64(written-progressBytes) / elapsed.Seconds())
- for i := range t.Files {
- if taskFileIdentity(t.Files[i].Path) == taskFileIdentity(relFile) {
- t.Files[i].DownloadedBytes = written
- t.Files[i].TotalBytes = t.TotalBytes
- t.Files[i].SpeedBps = speed
- t.Files[i].Status = "downloading"
- }
- }
- m.persistTaskProgress(*t)
- progressAt = time.Now()
- progressBytes = written
- }
- if rErr != nil {
- if rErr == io.EOF {
- break
- }
- _ = f.Sync()
- _ = f.Close()
- return segmentResult{newOffset: written, totalSize: totalSize}, rawCT, &site.Error{
- Site: transport.Site,
- Kind: site.ErrKindNetwork,
- Message: "媒体分段读取中断",
- Err: rErr,
- }
- }
- }
-
- if err := f.Sync(); err != nil {
- _ = f.Close()
- return segmentResult{newOffset: written, totalSize: totalSize}, rawCT, err
- }
- if err := f.Close(); err != nil {
- return segmentResult{newOffset: written, totalSize: totalSize}, rawCT, err
- }
- if expectedSegLen >= 0 && segWritten != expectedSegLen {
- return segmentResult{newOffset: written, totalSize: totalSize}, rawCT, &site.Error{
- Site: transport.Site,
- Kind: site.ErrKindNetwork,
- Message: fmt.Sprintf("分段字节未读满: 实读 %d < 预期 %d", segWritten, expectedSegLen),
- }
- }
- return segmentResult{
- newOffset: written,
- totalSize: totalSize,
- done: doneAfterThis,
- }, rawCT, nil
-}
-
-func newTransportHTTPClient(spec site.MediaTransportSpec) *http.Client {
- dialer := &net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}
- guard := site.NewGuardedMediaDialer(spec.Site, spec.AllowLocalhost, dialer, "已拦截内网或回环媒体节点地址")
- tr := &http.Transport{
- Proxy: guard.Proxy,
- MaxIdleConns: 16,
- IdleConnTimeout: 60 * time.Second,
- TLSHandshakeTimeout: 10 * time.Second,
- ResponseHeaderTimeout: 10 * time.Second,
- ExpectContinueTimeout: 1 * time.Second,
- DialContext: guard.DialContext,
- }
- return &http.Client{
- Transport: tr,
- CheckRedirect: func(req *http.Request, via []*http.Request) error {
- if len(via) >= 5 {
- return &site.Error{
- Site: spec.Site,
- Kind: site.ErrKindBlocked,
- Message: "媒体重定向超过 5 跳上限",
- }
- }
- if err := spec.ValidateURL(req.URL.String()); err != nil {
- return err
- }
- spec.ApplyHeaders(req)
- return nil
- },
- }
-}
-
-func rejectDisguisedMediaContentType(siteID site.ID, rawCT, role string, statusCode int) error {
- mediaType, _, err := mime.ParseMediaType(rawCT)
- if err != nil {
- mediaType = strings.ToLower(strings.TrimSpace(strings.SplitN(rawCT, ";", 2)[0]))
- }
- mediaType = strings.ToLower(strings.TrimSpace(mediaType))
- switch mediaType {
- case "text/html", "application/xhtml+xml", "application/json", "text/json", "text/plain", "text/xml", "application/xml", "application/javascript", "text/javascript":
- return &site.Error{
- Site: siteID,
- Kind: site.ErrKindSchemaChanged,
- HTTPStatus: statusCode,
- Message: fmt.Sprintf("媒体请求返回了非媒体类型 (%s)", mediaType),
- }
- }
- if (role == "image" || role == "cover") && mediaType != "" &&
- !strings.HasPrefix(mediaType, "image/") && mediaType != "application/octet-stream" {
- return &site.Error{
- Site: siteID,
- Kind: site.ErrKindSchemaChanged,
- HTTPStatus: statusCode,
- Message: fmt.Sprintf("图片响应不是有效的图片类型 (%s)", mediaType),
- }
- }
- return nil
-}
-
-func looksLikeDisguisedTextBody(head []byte) bool {
- trimmed := bytes.TrimLeft(head, " \t\r\n")
- if len(trimmed) == 0 {
- return false
- }
- lower := bytes.ToLower(trimmed[:min(len(trimmed), 32)])
- if bytes.HasPrefix(lower, []byte("= 3 && b[0] == 0xFF && b[1] == 0xD8 && b[2] == 0xFF:
- return ".jpg", nil
- case len(b) >= 8 && bytes.Equal(b[:8], []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1A, '\n'}):
- return ".png", nil
- case len(b) >= 12 && bytes.Equal(b[:4], []byte("RIFF")) && bytes.Equal(b[8:12], []byte("WEBP")):
- return ".webp", nil
- case len(b) >= 6 && (bytes.Equal(b[:6], []byte("GIF87a")) || bytes.Equal(b[:6], []byte("GIF89a"))):
- return ".gif", nil
- case len(b) >= 12 && bytes.Equal(b[4:8], []byte("ftyp")):
- brand := string(b[8:12])
- switch brand {
- case "avif", "avis":
- return ".avif", nil
- case "heic", "heix", "hevc", "hevx", "mif1", "msf1":
- return ".heic", nil
- }
- }
-
- mt, _, _ := mime.ParseMediaType(contentType)
- switch strings.ToLower(strings.TrimSpace(mt)) {
- case "image/jpeg", "image/jpg":
- if len(b) >= 4 && !looksLikeDisguisedTextBody(b) {
- return ".jpg", nil
- }
- case "image/png":
- if len(b) >= 4 && !looksLikeDisguisedTextBody(b) {
- return ".png", nil
- }
- case "image/webp":
- if len(b) >= 4 && !looksLikeDisguisedTextBody(b) {
- return ".webp", nil
- }
- case "image/gif":
- if len(b) >= 4 && !looksLikeDisguisedTextBody(b) {
- return ".gif", nil
- }
- case "image/avif":
- if len(b) >= 4 && !looksLikeDisguisedTextBody(b) {
- return ".avif", nil
- }
- case "image/heic", "image/heif":
- if len(b) >= 4 && !looksLikeDisguisedTextBody(b) {
- return ".heic", nil
- }
- }
- return "", errors.New("文件头不是受支持的图片格式")
-}
-
-func sniffAudioExtension(filePath, contentType string) (string, error) {
- f, err := os.Open(filePath)
- if err != nil {
- return "", err
- }
- defer f.Close()
- var head [32]byte
- n, _ := io.ReadFull(f, head[:])
- b := head[:n]
- if len(b) == 0 || looksLikeDisguisedTextBody(b) {
- return "", errors.New("配乐文件不是有效的音频格式")
- }
-
- switch {
- case len(b) >= 3 && bytes.Equal(b[:3], []byte("ID3")):
- return ".mp3", nil
- case len(b) >= 2 && b[0] == 0xFF && (b[1]&0xF6) == 0xF0:
- return ".aac", nil
- case len(b) >= 2 && b[0] == 0xFF && (b[1]&0xE0) == 0xE0 && ((b[1]>>1)&0x03) != 0:
- return ".mp3", nil
- case len(b) >= 12 && bytes.Equal(b[4:8], []byte("ftyp")):
- return ".m4a", nil
- case len(b) >= 4 && bytes.Equal(b[:4], []byte("OggS")):
- return ".ogg", nil
- case len(b) >= 4 && bytes.Equal(b[:4], []byte("fLaC")):
- return ".flac", nil
- case len(b) >= 12 && bytes.Equal(b[:4], []byte("RIFF")) && bytes.Equal(b[8:12], []byte("WAVE")):
- return ".wav", nil
- }
-
- mt, _, _ := mime.ParseMediaType(contentType)
- switch strings.ToLower(strings.TrimSpace(mt)) {
- case "audio/mpeg", "audio/mp3":
- return ".mp3", nil
- case "audio/mp4", "audio/x-m4a", "audio/m4a", "video/mp4":
- return ".m4a", nil
- case "audio/aac", "audio/aacp":
- return ".aac", nil
- case "audio/ogg", "application/ogg":
- return ".ogg", nil
- case "audio/flac":
- return ".flac", nil
- case "audio/wav", "audio/x-wav", "audio/wave":
- return ".wav", nil
- }
- return ".m4a", nil
-}
-
-type mediaIdleReader struct {
- r io.ReadCloser
- timeout time.Duration
-}
-
-func newMediaIdleReader(r io.ReadCloser, timeout time.Duration) io.ReadCloser {
- if timeout <= 0 {
- return r
- }
- return &mediaIdleReader{r: r, timeout: timeout}
-}
-
-func (m *mediaIdleReader) Read(p []byte) (int, error) {
- type res struct {
- n int
- err error
- }
- ch := make(chan res, 1)
- go func() {
- n, err := m.r.Read(p)
- ch <- res{n: n, err: err}
- }()
- timer := time.NewTimer(m.timeout)
- defer timer.Stop()
- select {
- case out := <-ch:
- return out.n, out.err
- case <-timer.C:
- _ = m.r.Close()
- return 0, errors.New("media read idle timeout")
- }
-}
-
-func (m *mediaIdleReader) Close() error {
- return m.r.Close()
-}
-
-func isSiteStopError(err error) bool {
- k := classifyDownloadError(err)
- return k == site.ErrKindRiskControl || k == site.ErrKindRateLimited || k == site.ErrKindAuthRequired
-}
-
-func firstNonEmptyStr(vals ...string) string {
- for _, v := range vals {
- if s := strings.TrimSpace(v); s != "" {
- return s
- }
- }
- return ""
-}
-
-func sanitizeStoredURL(raw string) string {
- raw = strings.TrimSpace(raw)
- if raw == "" {
- return ""
- }
- u, err := url.Parse(raw)
- if err != nil || u.Scheme == "" || u.Host == "" {
- return ""
- }
- u.User = nil
- u.RawQuery = ""
- u.Fragment = ""
- return u.String()
-}
-
-func summaryPrimaryVideoCodec(s MuxTrackSummary) string {
- for i, h := range s.Handlers {
- if h == "vide" && i < len(s.Codecs) {
- switch s.Codecs[i] {
- case "avc1", "avc3":
- return "avc"
- case "hvc1", "hev1":
- return "hevc"
- default:
- return s.Codecs[i]
- }
- }
- }
- return ""
-}
diff --git a/internal/download/douyin_collab_test.go b/internal/download/douyin_collab_test.go
new file mode 100644
index 0000000..7896cda
--- /dev/null
+++ b/internal/download/douyin_collab_test.go
@@ -0,0 +1,107 @@
+package download
+
+import (
+ "context"
+ "net/http"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/site"
+)
+
+// A work by someone else found in an account's works list (a co-creation)
+// is stored under that account's folder with via collab, keeps its real
+// author, is listed under the account in the library and keeps the via on
+// the persisted task; the author's own works and works already cached stay
+// where they are (DEC-063).
+func TestDouyinCoCreationIsStoredUnderTheAccountItWasCachedFor(t *testing.T) {
+ const (
+ author = "MS4wLjABAAAA_cocreation_author_000001"
+ member = "MS4wLjABAAAA_cocreation_member_000002"
+ collab = "7300000000000000031"
+ ownWork = "7300000000000000032"
+ )
+ videoMP4 := buildProgressiveWithoutElst(t, true, false, 0)
+ mux := http.NewServeMux()
+ mux.HandleFunc("/cdn/v.mp4", func(w http.ResponseWriter, r *http.Request) {
+ serveRangeBytes(w, r, videoMP4, "video/mp4", 0, nil)
+ })
+ mgr, libStore, srv, _, _ := setupDouyinDownloadTestEnv(t, mux, 1)
+ planner := newFakeDouyinWorkPlanner()
+ mgr.RegisterWorkPlanner(planner)
+ plan := func(id string) func(int) (WorkDownloadPlan, error) {
+ return func(int) (WorkDownloadPlan, error) {
+ return WorkDownloadPlan{
+ Site: site.Douyin, Kind: "video", TargetID: id, Title: "共创", DurationSec: 2,
+ AuthorUID: author, AuthorName: "发布者",
+ VideoURLs: []string{srv.URL + "/cdn/v.mp4"}, VideoGear: "adapt_lowest_4_1", QualityName: "720P", Codec: "avc", Width: 640, Height: 360,
+ Transport: site.DouyinVODTransport("Mozilla/5.0 Test", true),
+ }, nil
+ }
+ }
+ planner.setPlan(collab, plan(collab))
+ planner.setPlan(ownWork, plan(ownWork))
+ root := libStore.CacheDir()
+ folder := func(uid, id string) string {
+ return filepath.Join(root, "douyin", site.DouyinAuthorDir(uid), "works", id)
+ }
+ cache := func(id, forUID string) library.ItemMetadata {
+ t.Helper()
+ task, err := mgr.EnqueueDouyinWork(context.Background(), DouyinWorkEnqueueRequest{AwemeID: id, Source: "queue", ForUID: forUID, ForName: "共创成员"})
+ if err != nil {
+ t.Fatalf("EnqueueDouyinWork(%s): %v", id, err)
+ }
+ waitForTaskStatus(t, mgr, task.TaskID, "completed", 8*time.Second)
+ item, ok, err := libStore.GetItem("douyin:video:" + id)
+ if err != nil || !ok {
+ t.Fatalf("%s not indexed: %v %v", id, ok, err)
+ }
+ return item
+ }
+
+ item := cache(collab, member)
+ if !strings.EqualFold(filepath.Clean(item.ItemDir), filepath.Clean(folder(member, collab))) {
+ t.Fatalf("co-creation stored in %s, want the member's folder %s", item.ItemDir, folder(member, collab))
+ }
+ if item.Via == nil || item.Via.Reason != library.ViaCollab || item.Via.Site != "douyin" || item.Via.UID != member || item.Via.Name != "共创成员" {
+ t.Fatalf("via = %+v", item.Via)
+ }
+ if item.Author.UID != author {
+ t.Fatalf("author = %+v, want the real author kept", item.Author)
+ }
+ listed, err := libStore.ListItems(library.FeedFilter{Site: "douyin", AuthorUID: member})
+ if err != nil || len(listed) != 1 || listed[0].ItemKey != item.ItemKey {
+ t.Fatalf("library filtered by the member = %d items %v", len(listed), err)
+ }
+ counts, err := libStore.CountCachedWorks([]library.AuthorRef{{Site: "douyin", UID: member}})
+ if err != nil || counts["douyin:"+member] != 1 {
+ t.Fatalf("cached works of the member = %v %v, want the co-creation counted", counts, err)
+ }
+ tasks, err := mgr.ListTasks()
+ if err != nil {
+ t.Fatal(err)
+ }
+ var persisted *library.ItemVia
+ for _, tk := range tasks {
+ if tk.TargetID == collab {
+ persisted = tk.Via
+ }
+ }
+ if persisted == nil || persisted.UID != member {
+ t.Fatalf("persisted task via = %+v", persisted)
+ }
+
+ // The author's own work, cached for the author, has no via.
+ own := cache(ownWork, author)
+ if own.Via != nil || !strings.EqualFold(filepath.Clean(own.ItemDir), filepath.Clean(folder(author, ownWork))) {
+ t.Fatalf("own work: dir %s via %+v", own.ItemDir, own.Via)
+ }
+ // An item already cached keeps its folder when cached again for another account.
+ again := cache(ownWork, member)
+ if again.Via != nil || !strings.EqualFold(filepath.Clean(again.ItemDir), filepath.Clean(folder(author, ownWork))) {
+ t.Fatalf("re-cached work moved: dir %s via %+v", again.ItemDir, again.Via)
+ }
+}
diff --git a/internal/download/douyin_download_test.go b/internal/download/douyin_download_test.go
index 13c7662..542c5c4 100644
--- a/internal/download/douyin_download_test.go
+++ b/internal/download/douyin_download_test.go
@@ -284,6 +284,7 @@ func TestDouyinVideoCacheRangeRefreshAndSecretScrub(t *testing.T) {
})
mgr, libStore, srv, dbPath, logBuf := setupDouyinDownloadTestEnv(t, mux, 1)
+ checkNames := watchNames(t, libStore.CacheDir())
planner := newFakeDouyinWorkPlanner()
mgr.RegisterWorkPlanner(planner)
@@ -324,6 +325,7 @@ func TestDouyinVideoCacheRangeRefreshAndSecretScrub(t *testing.T) {
t.Fatalf("EnqueueDouyinWork(awemeOK): %v", err)
}
doneOK := waitForTaskStatus(t, mgr, taskOK.TaskID, "completed", 8*time.Second)
+ checkNames()
if sawCookieLeak.Load() {
t.Fatal("CDN media request leaked Cookie header")
}
@@ -496,6 +498,7 @@ func TestDouyinPlainAndMixedNotesMusicAndUnknownPage(t *testing.T) {
})
mgr, libStore, srv, _, _ := setupDouyinDownloadTestEnv(t, mux, 2)
+ checkNames := watchNames(t, libStore.CacheDir())
planner := newFakeDouyinWorkPlanner()
mgr.RegisterWorkPlanner(planner)
transport := site.DouyinVODTransport("Mozilla/5.0 Test", true)
@@ -600,6 +603,7 @@ func TestDouyinPlainAndMixedNotesMusicAndUnknownPage(t *testing.T) {
t.Fatalf("EnqueueDouyinWork(mixed): %v", err)
}
doneMixed := waitForTaskStatus(t, mgr, tMixed.TaskID, "partial", 8*time.Second)
+ checkNames()
for _, rel := range []string{
"images/01.png",
diff --git a/internal/download/douyin_note.go b/internal/download/douyin_note.go
new file mode 100644
index 0000000..ad38273
--- /dev/null
+++ b/internal/download/douyin_note.go
@@ -0,0 +1,608 @@
+package download
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/site"
+)
+
+func (m *Manager) executeDouyinNoteTask(ctx context.Context, t *Task, plan WorkDownloadPlan, planner WorkPlanner) (result error) {
+ previous, exists, itemDir, err := m.resolveDouyinItemDir(t, "dynamic", plan.AuthorUID, t.TargetID)
+ if err != nil {
+ return err
+ }
+
+ m.mu.Lock()
+ cfg := m.dlSettings
+ m.mu.Unlock()
+
+ title := firstNonEmptyStr(plan.Title, plan.Desc, t.Title, "抖音图文 "+t.TargetID)
+ canonicalURL := firstNonEmptyStr(sanitizeStoredURL(plan.CanonicalURL), "https://www.douyin.com/note/"+t.TargetID)
+ t.Title = title
+ t.AuthorName = firstNonEmptyStr(plan.AuthorName, t.AuthorName)
+ t.AuthorFace = sanitizeStoredURL(firstNonEmptyStr(plan.AuthorFace, t.AuthorFace))
+ if len(plan.CoverURLs) > 0 {
+ t.CoverURL = sanitizeStoredURL(plan.CoverURLs[0])
+ }
+
+ var mediaFiles []library.MediaFile
+ var notePages []library.NotePageRecord
+ var missing []library.MissingRecord
+ var partialErrors []string
+ finalSaved := false
+
+ defer func() {
+ if result == nil || finalSaved {
+ return
+ }
+ if !isSiteStopError(result) {
+ missing = append(missing, library.MissingRecord{
+ Item: "note",
+ Reason: "图文缓存尚未完成 (" + classifyDownloadError(result) + ")",
+ })
+ }
+ partialMeta := library.ItemMetadata{
+ Version: 1,
+ ID: "dynamic:" + t.TargetID,
+ Site: "douyin",
+ Kind: "dynamic",
+ Status: "partial",
+ Title: title,
+ Desc: plan.Desc,
+ Text: firstNonEmptyStr(plan.Desc, plan.Title),
+ DynamicType: "draw",
+ TypeLabel: "图文",
+ URL: canonicalURL,
+ PubTs: plan.PubTs,
+ CachedAt: previous.CachedAt,
+ Author: library.ItemAuthor{
+ Site: "douyin",
+ UID: plan.AuthorUID,
+ UniqueID: plan.AuthorUniqueID,
+ Name: t.AuthorName,
+ Face: t.AuthorFace,
+ },
+ Media: mergeMediaFiles(previous.Media, mediaFiles),
+ NotePages: notePages,
+ Missing: missing,
+ Via: m.douyinItemVia(t, previous, exists, itemDir),
+ }
+ saved, sErr := m.lib.SaveItem(itemDir, partialMeta)
+ if sErr != nil {
+ if !isSiteStopError(result) && ctx.Err() == nil {
+ result = sErr
+ }
+ return
+ }
+ t.ItemKey = saved.ItemKey
+ }()
+
+ // Share a single plan refresh across every file in this note so expiring URLs
+ // trigger at most one PlanWorkDownload API call for the whole note.
+ refreshOncePlan := m.makeSinglePlanRefresher(ctx, t.TargetID, planner)
+
+ // Optional cover. when explicitly provided.
+ if cfg.SaveCover && len(plan.CoverURLs) > 0 {
+ refreshCover := makeOnceURLRefresher(refreshOncePlan, func(fresh WorkDownloadPlan) ([]string, error) {
+ return fresh.CoverURLs, nil
+ })
+ if coverMedia, cErr := m.cacheDouyinSniffedImage(ctx, t, itemDir, previous, exists, "cover", "cover", plan.CoverURLs, 0, 0, plan.Transport, refreshCover); cErr != nil {
+ if isSiteStopError(cErr) || isStorageError(cErr) || ctx.Err() != nil {
+ return cErr
+ }
+ missing = append(missing, library.MissingRecord{
+ Item: "cover",
+ Reason: "封面保存失败 (" + classifyDownloadError(cErr) + ")",
+ })
+ } else if coverMedia != nil {
+ mediaFiles = append(mediaFiles, *coverMedia)
+ }
+ }
+
+ // Process ordered pages 1..N.
+ for i, page := range plan.Pages {
+ pageIdx := page.Index
+ if pageIdx <= 0 {
+ pageIdx = i + 1
+ }
+ prefix := fmt.Sprintf("images/%02d", pageIdx)
+ pageKind := strings.ToLower(strings.TrimSpace(page.Kind))
+ if pageKind == "" {
+ if len(page.VideoURLs) > 0 {
+ pageKind = "live_photo"
+ } else {
+ pageKind = "image"
+ }
+ }
+
+ switch pageKind {
+ case "image":
+ refreshImg := makeOnceURLRefresher(refreshOncePlan, func(fresh WorkDownloadPlan) ([]string, error) {
+ if p, ok := findPlannedPage(fresh.Pages, pageIdx, i); ok {
+ return p.ImageURLs, nil
+ }
+ return nil, nil
+ })
+ imgMedia, imgErr := m.cacheDouyinSniffedImage(ctx, t, itemDir, previous, exists, "image", prefix, page.ImageURLs, page.Width, page.Height, plan.Transport, refreshImg)
+ if imgErr != nil {
+ if isSiteStopError(imgErr) || isStorageError(imgErr) || ctx.Err() != nil {
+ return imgErr
+ }
+ reason := fmt.Sprintf("第 %02d 页图片下载失败 (%s)", pageIdx, classifyDownloadError(imgErr))
+ missing = append(missing, library.MissingRecord{Item: fmt.Sprintf("page_%02d", pageIdx), Reason: reason})
+ partialErrors = append(partialErrors, reason)
+ notePages = append(notePages, library.NotePageRecord{Index: pageIdx, Kind: "image", Width: page.Width, Height: page.Height})
+ continue
+ }
+ mediaFiles = append(mediaFiles, *imgMedia)
+ notePages = append(notePages, library.NotePageRecord{
+ Index: pageIdx,
+ Kind: "image",
+ Image: imgMedia.Path,
+ Width: page.Width,
+ Height: page.Height,
+ })
+
+ case "live_photo", "motion":
+ refreshImg := makeOnceURLRefresher(refreshOncePlan, func(fresh WorkDownloadPlan) ([]string, error) {
+ if p, ok := findPlannedPage(fresh.Pages, pageIdx, i); ok {
+ return p.ImageURLs, nil
+ }
+ return nil, nil
+ })
+ imgMedia, imgErr := m.cacheDouyinSniffedImage(ctx, t, itemDir, previous, exists, "image", prefix, page.ImageURLs, page.Width, page.Height, plan.Transport, refreshImg)
+ if imgErr != nil {
+ if isSiteStopError(imgErr) || isStorageError(imgErr) || ctx.Err() != nil {
+ return imgErr
+ }
+ reason := fmt.Sprintf("第 %02d 页实况静帧下载失败 (%s)", pageIdx, classifyDownloadError(imgErr))
+ missing = append(missing, library.MissingRecord{Item: fmt.Sprintf("page_%02d", pageIdx), Reason: reason})
+ partialErrors = append(partialErrors, reason)
+ notePages = append(notePages, library.NotePageRecord{Index: pageIdx, Kind: "motion", Width: page.Width, Height: page.Height, Duration: page.DurationSec})
+ continue
+ }
+
+ motionRel := fmt.Sprintf("images/%02d_live.mp4", pageIdx)
+ refreshMotion := makeOnceURLRefresher(refreshOncePlan, func(fresh WorkDownloadPlan) ([]string, error) {
+ if p, ok := findPlannedPage(fresh.Pages, pageIdx, i); ok {
+ return p.VideoURLs, nil
+ }
+ return nil, nil
+ })
+ motionMedia, mErr := m.cacheDouyinSingleMP4(ctx, t, itemDir, previous, exists, "motion", motionRel, page.VideoURLs, page.NeedSetToken, page.DurationSec, page.Width, page.Height, plan.Transport, planner, refreshMotion)
+ rec := library.NotePageRecord{
+ Index: pageIdx,
+ Kind: "motion",
+ Image: imgMedia.Path,
+ Width: page.Width,
+ Height: page.Height,
+ Duration: page.DurationSec,
+ }
+ if mErr != nil {
+ if isSiteStopError(mErr) || isStorageError(mErr) || ctx.Err() != nil {
+ return mErr
+ }
+ reason := fmt.Sprintf("第 %02d 页实况视频下载失败 (%s)", pageIdx, classifyDownloadError(mErr))
+ missing = append(missing, library.MissingRecord{Item: motionRel, Reason: reason})
+ partialErrors = append(partialErrors, reason)
+ } else if motionMedia != nil {
+ imgMedia.Motion = motionMedia.Path
+ rec.Motion = motionMedia.Path
+ if motionMedia.Duration > 0 {
+ rec.Duration = motionMedia.Duration
+ }
+ mediaFiles = append(mediaFiles, *motionMedia)
+ }
+ mediaFiles = append(mediaFiles, *imgMedia)
+ notePages = append(notePages, rec)
+
+ case "video":
+ var coverRel string
+ if len(page.ImageURLs) > 0 {
+ refreshPageCover := makeOnceURLRefresher(refreshOncePlan, func(fresh WorkDownloadPlan) ([]string, error) {
+ if p, ok := findPlannedPage(fresh.Pages, pageIdx, i); ok {
+ return p.ImageURLs, nil
+ }
+ return nil, nil
+ })
+ coverMedia, cErr := m.cacheDouyinSniffedImage(ctx, t, itemDir, previous, exists, "image", prefix, page.ImageURLs, page.Width, page.Height, plan.Transport, refreshPageCover)
+ if cErr != nil {
+ if isSiteStopError(cErr) || isStorageError(cErr) || ctx.Err() != nil {
+ return cErr
+ }
+ reason := fmt.Sprintf("第 %02d 页视频封面下载失败 (%s)", pageIdx, classifyDownloadError(cErr))
+ missing = append(missing, library.MissingRecord{Item: fmt.Sprintf("page_%02d.cover", pageIdx), Reason: reason})
+ partialErrors = append(partialErrors, reason)
+ } else if coverMedia != nil {
+ coverRel = coverMedia.Path
+ mediaFiles = append(mediaFiles, *coverMedia)
+ }
+ }
+
+ videoRel := fmt.Sprintf("images/%02d.mp4", pageIdx)
+ refreshPageVideo := makeOnceURLRefresher(refreshOncePlan, func(fresh WorkDownloadPlan) ([]string, error) {
+ if p, ok := findPlannedPage(fresh.Pages, pageIdx, i); ok {
+ return p.VideoURLs, nil
+ }
+ return nil, nil
+ })
+ vidMedia, vErr := m.cacheDouyinSingleMP4(ctx, t, itemDir, previous, exists, "video", videoRel, page.VideoURLs, page.NeedSetToken, page.DurationSec, page.Width, page.Height, plan.Transport, planner, refreshPageVideo)
+ rec := library.NotePageRecord{
+ Index: pageIdx,
+ Kind: "video",
+ Cover: coverRel,
+ Width: page.Width,
+ Height: page.Height,
+ Duration: page.DurationSec,
+ }
+ if vErr != nil {
+ if isSiteStopError(vErr) || isStorageError(vErr) || ctx.Err() != nil {
+ return vErr
+ }
+ reason := fmt.Sprintf("第 %02d 页视频下载失败 (%s)", pageIdx, classifyDownloadError(vErr))
+ missing = append(missing, library.MissingRecord{Item: videoRel, Reason: reason})
+ partialErrors = append(partialErrors, reason)
+ } else if vidMedia != nil {
+ rec.Video = vidMedia.Path
+ if vidMedia.Duration > 0 {
+ rec.Duration = vidMedia.Duration
+ }
+ if vidMedia.Width > 0 {
+ rec.Width = vidMedia.Width
+ }
+ if vidMedia.Height > 0 {
+ rec.Height = vidMedia.Height
+ }
+ rec.VideoInfo = &library.DouyinVideoInfo{
+ File: vidMedia.Path,
+ Gear: page.Gear,
+ QualityName: page.QualityName,
+ Codec: page.Codec,
+ Width: rec.Width,
+ Height: rec.Height,
+ FPS: page.FPS,
+ Bitrate: page.Bitrate,
+ }
+ mediaFiles = append(mediaFiles, *vidMedia)
+ }
+ notePages = append(notePages, rec)
+
+ default:
+ // Unrecognized page kind ("unknown"): keep available image, record unknownKind + missing, never fail whole item.
+ var savedImg string
+ if len(page.ImageURLs) > 0 {
+ refreshUnknownImg := makeOnceURLRefresher(refreshOncePlan, func(fresh WorkDownloadPlan) ([]string, error) {
+ if p, ok := findPlannedPage(fresh.Pages, pageIdx, i); ok {
+ return p.ImageURLs, nil
+ }
+ return nil, nil
+ })
+ if imgMedia, imgErr := m.cacheDouyinSniffedImage(ctx, t, itemDir, previous, exists, "image", prefix, page.ImageURLs, page.Width, page.Height, plan.Transport, refreshUnknownImg); imgErr != nil {
+ if isSiteStopError(imgErr) || isStorageError(imgErr) || ctx.Err() != nil {
+ return imgErr
+ }
+ } else if imgMedia != nil {
+ savedImg = imgMedia.Path
+ mediaFiles = append(mediaFiles, *imgMedia)
+ }
+ }
+ unkTag := firstNonEmptyStr(page.UnknownKind, pageKind, "unknown")
+ reason := firstNonEmptyStr(page.UnknownReason, fmt.Sprintf("第 %02d 页包含暂未识别的页面类型 (%s),已保留可用图片", pageIdx, unkTag))
+ missing = append(missing, library.MissingRecord{
+ Item: fmt.Sprintf("page_%02d", pageIdx),
+ Reason: reason,
+ })
+ notePages = append(notePages, library.NotePageRecord{
+ Index: pageIdx,
+ Kind: "unknown",
+ UnknownKind: unkTag,
+ Image: savedImg,
+ Width: page.Width,
+ Height: page.Height,
+ })
+ }
+ }
+
+ // Process background music if present on the note.
+ var musicInfo *library.MusicInfo
+ if plan.Music != nil {
+ musicCover := ""
+ if len(plan.Music.CoverURLs) > 0 {
+ musicCover = sanitizeStoredURL(plan.Music.CoverURLs[0])
+ }
+ musicInfo = &library.MusicInfo{
+ ID: plan.Music.ID,
+ Title: plan.Music.Title,
+ Author: plan.Music.Author,
+ Duration: plan.Music.DurationSec,
+ Cover: musicCover,
+ Original: plan.Music.Original,
+ }
+ if len(plan.Music.PlayURLs) == 0 {
+ missing = append(missing, library.MissingRecord{
+ Item: "music",
+ Reason: "配乐无可用地址(版权或地区限制)",
+ })
+ } else {
+ refreshMusic := makeOnceURLRefresher(refreshOncePlan, func(fresh WorkDownloadPlan) ([]string, error) {
+ if fresh.Music != nil {
+ return fresh.Music.PlayURLs, nil
+ }
+ return nil, nil
+ })
+ // Music CDN hosts redirect to public edge domains outside the static
+ // allowlist; allow public HTTPS redirects while blocking IP/local hosts.
+ musicTransport := plan.Transport
+ musicTransport.PublicRedirects = true
+ musicMedia, mErr := m.cacheDouyinSniffedAudio(ctx, t, itemDir, previous, exists, "music", plan.Music.PlayURLs, plan.Music.DurationSec, musicTransport, refreshMusic)
+ if mErr != nil {
+ if isSiteStopError(mErr) || isStorageError(mErr) || ctx.Err() != nil {
+ return mErr
+ }
+ reason := musicFailureReason(mErr)
+ missing = append(missing, library.MissingRecord{
+ Item: "music",
+ Reason: reason,
+ })
+ partialErrors = append(partialErrors, reason)
+ } else if musicMedia != nil {
+ musicInfo.File = musicMedia.Path
+ mediaFiles = append(mediaFiles, *musicMedia)
+ }
+ }
+ }
+
+ status := "complete"
+ if len(missing) > 0 || len(partialErrors) > 0 {
+ status = "partial"
+ t.Status = "partial"
+ t.ErrorMessage = summarizeMissingReasons(missing)
+ }
+
+ meta := library.ItemMetadata{
+ Version: 1,
+ ID: "dynamic:" + t.TargetID,
+ Site: "douyin",
+ Kind: "dynamic",
+ Status: status,
+ Title: title,
+ Desc: plan.Desc,
+ Text: firstNonEmptyStr(plan.Desc, plan.Title),
+ DynamicType: "draw",
+ TypeLabel: "图文",
+ URL: canonicalURL,
+ PubTs: plan.PubTs,
+ CachedAt: previous.CachedAt,
+ Author: library.ItemAuthor{
+ Site: "douyin",
+ UID: plan.AuthorUID,
+ UniqueID: plan.AuthorUniqueID,
+ Name: t.AuthorName,
+ Face: t.AuthorFace,
+ },
+ Media: mediaFiles,
+ NotePages: notePages,
+ Music: musicInfo,
+ Missing: missing,
+ DirectCached: true,
+ Via: m.douyinItemVia(t, previous, exists, itemDir),
+ }
+
+ saved, saveErr := m.lib.SaveItem(itemDir, meta)
+ if saveErr != nil {
+ return saveErr
+ }
+ t.ItemKey = saved.ItemKey
+ finalSaved = true
+ return nil
+}
+
+func (m *Manager) cacheDouyinSniffedImage(
+ ctx context.Context,
+ t *Task,
+ itemDir string,
+ previous library.ItemMetadata,
+ exists bool,
+ role string,
+ relStem string,
+ urls []string,
+ width, height int,
+ transport site.MediaTransportSpec,
+ refreshURLs func() ([]string, error),
+) (*library.MediaFile, error) {
+ if exists {
+ for _, mf := range previous.Media {
+ if mf.Role == role && strings.HasPrefix(mf.Path, relStem+".") && m.mediaAlreadyCompleted(previous, mf) {
+ m.setFileProgress(t, role, mf.Path, "completed", mf.Bytes, mf.Bytes, 0)
+ cp := mf
+ return &cp, nil
+ }
+ }
+ }
+
+ tempRel := relStem + imgSuffix
+ m.adoptLegacyStaging(t, itemDir, relStem, ".imgtmp", imgSuffix)
+ tempFull, err := library.ResolveItemPath(itemDir, tempRel)
+ if err != nil {
+ return nil, err
+ }
+ if err := m.claimTaskFile(t, itemDir, 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
+ }
+ n, sha, ct, err := m.downloadWithTransportRefreshCT(ctx, transport, urls, tempFull, role, t, refreshURLs)
+ if err != nil {
+ if ctx.Err() == nil {
+ _ = os.Remove(tempFull)
+ if !fileOrPartExists(tempFull) {
+ m.removeTempTaskProgress(t, tempRel)
+ }
+ }
+ return nil, err
+ }
+ ext, err := sniffImageExtension(tempFull, ct)
+ if err != nil {
+ if ctx.Err() == nil {
+ _ = os.Remove(tempFull)
+ m.removeTempTaskProgress(t, tempRel)
+ }
+ return nil, &site.Error{Site: transport.Site, Kind: site.ErrKindSchemaChanged, Message: err.Error()}
+ }
+ finalRel := relStem + ext
+ finalFull, err := library.ResolveItemPath(itemDir, finalRel)
+ if err != nil {
+ if ctx.Err() == nil {
+ _ = os.Remove(tempFull)
+ m.removeTempTaskProgress(t, tempRel)
+ }
+ return nil, err
+ }
+ if err := m.claimTaskFile(t, itemDir, finalRel, finalFull); err != nil {
+ if ctx.Err() == nil {
+ _ = os.Remove(tempFull)
+ m.removeTempTaskProgress(t, tempRel)
+ }
+ return nil, err
+ }
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ if err := os.Rename(tempFull, finalFull); err != nil {
+ if ctx.Err() == nil {
+ _ = os.Remove(tempFull)
+ m.removeTempTaskProgress(t, tempRel)
+ }
+ return nil, err
+ }
+ m.removeTempTaskProgress(t, tempRel)
+ m.setFileProgress(t, role, finalRel, "completed", n, n, 0)
+ return &library.MediaFile{
+ Role: role,
+ Path: finalRel,
+ Bytes: n,
+ SHA256: sha,
+ Width: width,
+ Height: height,
+ }, nil
+}
+
+func (m *Manager) cacheDouyinSniffedAudio(
+ ctx context.Context,
+ t *Task,
+ itemDir string,
+ previous library.ItemMetadata,
+ exists bool,
+ relStem string,
+ urls []string,
+ durationSec int,
+ transport site.MediaTransportSpec,
+ refreshURLs func() ([]string, error),
+) (*library.MediaFile, error) {
+ if exists {
+ for _, mf := range previous.Media {
+ if mf.Role == "audio" && strings.HasPrefix(mf.Path, relStem+".") && m.mediaAlreadyCompleted(previous, mf) {
+ m.setFileProgress(t, "audio", mf.Path, "completed", mf.Bytes, mf.Bytes, 0)
+ cp := mf
+ return &cp, nil
+ }
+ }
+ }
+
+ tempRel := relStem + audSuffix
+ m.adoptLegacyStaging(t, itemDir, relStem, ".audtmp", audSuffix)
+ tempFull, err := library.ResolveItemPath(itemDir, tempRel)
+ if err != nil {
+ return nil, err
+ }
+ if err := m.claimTaskFile(t, itemDir, tempRel, tempFull); err != nil {
+ return nil, err
+ }
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ n, sha, ct, err := m.downloadWithTransportRefreshCT(ctx, transport, urls, tempFull, "audio", t, refreshURLs)
+ if err != nil {
+ if ctx.Err() == nil {
+ _ = os.Remove(tempFull)
+ if !fileOrPartExists(tempFull) {
+ m.removeTempTaskProgress(t, tempRel)
+ }
+ }
+ return nil, err
+ }
+ ext, err := sniffAudioExtension(tempFull, ct)
+ if err != nil {
+ if ctx.Err() == nil {
+ _ = os.Remove(tempFull)
+ m.removeTempTaskProgress(t, tempRel)
+ }
+ return nil, &site.Error{Site: transport.Site, Kind: site.ErrKindSchemaChanged, Message: err.Error()}
+ }
+ finalRel := relStem + ext
+ finalFull, err := library.ResolveItemPath(itemDir, finalRel)
+ if err != nil {
+ if ctx.Err() == nil {
+ _ = os.Remove(tempFull)
+ m.removeTempTaskProgress(t, tempRel)
+ }
+ return nil, err
+ }
+ if err := m.claimTaskFile(t, itemDir, finalRel, finalFull); err != nil {
+ if ctx.Err() == nil {
+ _ = os.Remove(tempFull)
+ m.removeTempTaskProgress(t, tempRel)
+ }
+ return nil, err
+ }
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ if err := os.Rename(tempFull, finalFull); err != nil {
+ if ctx.Err() == nil {
+ _ = os.Remove(tempFull)
+ m.removeTempTaskProgress(t, tempRel)
+ }
+ return nil, err
+ }
+ m.removeTempTaskProgress(t, tempRel)
+ m.setFileProgress(t, "audio", finalRel, "completed", n, n, 0)
+ return &library.MediaFile{
+ Role: "audio",
+ Path: finalRel,
+ Bytes: n,
+ SHA256: sha,
+ Duration: durationSec,
+ }, nil
+}
+
+func findPlannedPage(pages []PlannedNotePage, index, fallbackPos int) (PlannedNotePage, bool) {
+ for _, p := range pages {
+ if p.Index == index {
+ return p, true
+ }
+ }
+ if fallbackPos >= 0 && fallbackPos < len(pages) {
+ return pages[fallbackPos], true
+ }
+ return PlannedNotePage{}, false
+}
+
+func replaceRoleMedia(existing []library.MediaFile, role string, added library.MediaFile) []library.MediaFile {
+ var filtered []library.MediaFile
+ for _, mf := range existing {
+ if mf.Role != role {
+ filtered = append(filtered, mf)
+ }
+ }
+ return append(filtered, added)
+}
diff --git a/internal/download/douyin_plan.go b/internal/download/douyin_plan.go
new file mode 100644
index 0000000..77b35ee
--- /dev/null
+++ b/internal/download/douyin_plan.go
@@ -0,0 +1,713 @@
+package download
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/site"
+)
+
+// WorkPlanOptions carries user quality and codec preferences when planning a site download.
+type WorkPlanOptions struct {
+ VideoQuality string
+ CodecOrder []string
+}
+
+// PlannedNotePage describes one 1-based page in a Douyin image or mixed note.
+type PlannedNotePage struct {
+ Index int
+ Kind string // "image", "live_photo", "video", "unknown"
+ 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
+}
+
+// PlannedMusic describes background music metadata and candidate URLs on a Douyin note.
+type PlannedMusic struct {
+ ID string
+ Title string
+ Author string
+ DurationSec int
+ Original bool
+ CoverURLs []string
+ PlayURLs []string
+}
+
+// WorkDownloadPlan holds rich metadata and ephemeral CDN URLs for caching a Douyin video or note.
+type WorkDownloadPlan struct {
+ Site site.ID
+ Kind string // "video" or "dynamic" ("note" / "image_note" normalized to "dynamic")
+ TargetID string
+ Title string
+ Desc string
+ CanonicalURL string
+ PubTs int64
+ DurationSec int
+ AuthorUID string
+ AuthorUniqueID string
+ AuthorName string
+ AuthorFace string
+ CoverURLs []string
+ VideoURLs []string
+ NeedSetToken bool
+ OriginalURLs []string // untranscoded source (原画), tried before VideoURLs
+ VideoGear string
+ QualityName string
+ Codec string
+ Width int
+ Height int
+ FPS int
+ Bitrate int64
+ AvailableGears []string
+ DowngradeHint string
+ Pages []PlannedNotePage
+ Music *PlannedMusic
+ Transport site.MediaTransportSpec
+}
+
+// WorkPlanner plans rich work downloads for a site without exposing site-private packages to download.
+type WorkPlanner interface {
+ SiteID() site.ID
+ PlanWorkDownload(ctx context.Context, targetID string, opts WorkPlanOptions) (WorkDownloadPlan, error)
+}
+
+// SiteAuthChecker is an optional interface implemented by planners that enforce login before enqueueing.
+type SiteAuthChecker interface {
+ RequireAuth(action string) error
+}
+
+// SiteErrorReporter is an optional interface implemented by planners that track automatic-request errors.
+type SiteErrorReporter interface {
+ ReportAutomaticError(ctx context.Context, err error)
+}
+
+// PlayURLResolver is an optional interface implemented by planners that can
+// resolve an authenticated main-site play redirector URL (e.g.
+// www.douyin.com/aweme/v1/play/) into a cookieless CDN media URL.
+type PlayURLResolver interface {
+ ResolvePlayRedirect(ctx context.Context, playURL string) (string, error)
+}
+
+// DouyinWorkEnqueueRequest specifies a Douyin video or image/mixed note to enqueue for local caching.
+type DouyinWorkEnqueueRequest struct {
+ AwemeID string `json:"awemeId"`
+ Kind string `json:"kind,omitempty"` // optional hint: "video" or "dynamic"/"note"
+ Source string `json:"source,omitempty"` // "manual" or "auto"
+ Plan *WorkDownloadPlan `json:"-"`
+ // ForUID and ForName are the account the work is cached for when it
+ // came from that account's works list (subscription, cache queue, user
+ // page). A work by someone else there is a co-creation: a new item goes
+ // to this account's folder with via collab (DEC-063).
+ ForUID string `json:"forUid,omitempty"`
+ ForName string `json:"forName,omitempty"`
+}
+
+// RegisterSitePlanner registers a cross-site DownloadPlanner (upgrading automatically if it also implements WorkPlanner).
+func (m *Manager) RegisterSitePlanner(planner site.DownloadPlanner) {
+ if planner == nil {
+ return
+ }
+ if wp, ok := planner.(WorkPlanner); ok {
+ m.RegisterWorkPlanner(wp)
+ return
+ }
+ m.RegisterWorkPlanner(&basicSitePlannerAdapter{inner: planner})
+}
+
+// RegisterWorkPlanner registers a rich WorkPlanner for its SiteID.
+func (m *Manager) RegisterWorkPlanner(planner WorkPlanner) {
+ if planner == nil {
+ return
+ }
+ m.mu.Lock()
+ m.planners[planner.SiteID()] = planner
+ m.mu.Unlock()
+}
+
+func (m *Manager) getWorkPlanner(siteID site.ID) (WorkPlanner, bool) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ p, ok := m.planners[siteID]
+ return p, ok
+}
+
+type basicSitePlannerAdapter struct {
+ inner site.DownloadPlanner
+}
+
+func (a *basicSitePlannerAdapter) SiteID() site.ID {
+ return a.inner.SiteID()
+}
+
+func (a *basicSitePlannerAdapter) RequireAuth(action string) error {
+ if checker, ok := a.inner.(SiteAuthChecker); ok {
+ return checker.RequireAuth(action)
+ }
+ return nil
+}
+
+func (a *basicSitePlannerAdapter) ReportAutomaticError(ctx context.Context, err error) {
+ if rep, ok := a.inner.(SiteErrorReporter); ok {
+ rep.ReportAutomaticError(ctx, err)
+ }
+}
+
+func (a *basicSitePlannerAdapter) ResolvePlayRedirect(ctx context.Context, playURL string) (string, error) {
+ if res, ok := a.inner.(PlayURLResolver); ok {
+ return res.ResolvePlayRedirect(ctx, playURL)
+ }
+ return "", &site.Error{Site: a.inner.SiteID(), Kind: site.ErrKindUnavailable, Message: "不支持解析播放跳转地址"}
+}
+
+func (a *basicSitePlannerAdapter) PlanWorkDownload(ctx context.Context, targetID string, _ WorkPlanOptions) (WorkDownloadPlan, error) {
+ p, err := a.inner.PlanDownload(ctx, targetID, 1)
+ if err != nil {
+ return WorkDownloadPlan{}, err
+ }
+ return convertSiteDownloadPlan(p), nil
+}
+
+func convertSiteDownloadPlan(p site.DownloadPlan) WorkDownloadPlan {
+ kind := "video"
+ if p.Kind == "image_note" || p.Kind == "note" || p.Kind == "dynamic" || len(p.Images) > 0 {
+ kind = "dynamic"
+ }
+ canonicalURL := ""
+ if p.Site == site.Douyin && p.TargetID != "" {
+ if kind == "dynamic" {
+ canonicalURL = "https://www.douyin.com/note/" + p.TargetID
+ } else {
+ canonicalURL = "https://www.douyin.com/video/" + p.TargetID
+ }
+ }
+ pages := make([]PlannedNotePage, 0, len(p.Images))
+ for i, img := range p.Images {
+ idx := img.Index
+ if idx <= 0 {
+ idx = i + 1
+ }
+ pageKind := "image"
+ if len(img.VideoURLs) > 0 {
+ pageKind = "live_photo"
+ }
+ pages = append(pages, PlannedNotePage{
+ Index: idx,
+ Kind: pageKind,
+ Width: img.Width,
+ Height: img.Height,
+ ImageURLs: append([]string(nil), img.ImageURLs...),
+ VideoURLs: append([]string(nil), img.VideoURLs...),
+ })
+ }
+ var music *PlannedMusic
+ if len(p.MusicURLs) > 0 {
+ music = &PlannedMusic{
+ PlayURLs: append([]string(nil), p.MusicURLs...),
+ }
+ }
+ transport := p.Media
+ if len(transport.AllowedDomains) == 0 && p.Site == site.Douyin {
+ transport = site.DouyinVODTransport("", false)
+ }
+ return WorkDownloadPlan{
+ Site: p.Site,
+ Kind: kind,
+ TargetID: p.TargetID,
+ Title: p.Title,
+ Desc: p.Desc,
+ CanonicalURL: canonicalURL,
+ PubTs: p.PubTs,
+ DurationSec: p.DurationSec,
+ AuthorUID: p.AuthorUID,
+ AuthorName: p.AuthorName,
+ CoverURLs: append([]string(nil), p.CoverURLs...),
+ VideoURLs: append([]string(nil), p.VideoURLs...),
+ OriginalURLs: append([]string(nil), p.OriginalURLs...),
+ QualityName: p.QualityLabel,
+ Codec: p.VideoCodec,
+ Width: p.Width,
+ Height: p.Height,
+ Pages: pages,
+ Music: music,
+ Transport: transport,
+ }
+}
+
+// EnqueueDouyinWork resolves (or accepts a pre-planned) Douyin video or note and enqueues a download task.
+func (m *Manager) EnqueueDouyinWork(ctx context.Context, req DouyinWorkEnqueueRequest) (Task, error) {
+ awemeID := strings.TrimSpace(req.AwemeID)
+ if awemeID == "" && req.Plan != nil {
+ awemeID = strings.TrimSpace(req.Plan.TargetID)
+ }
+ if awemeID == "" || library.SanitizeFileName(awemeID) != awemeID {
+ return Task{}, &site.Error{
+ Site: site.Douyin,
+ Kind: site.ErrKindBadRequest,
+ Message: "无效的抖音作品 ID",
+ }
+ }
+
+ planner, hasPlanner := m.getWorkPlanner(site.Douyin)
+ if checker, ok := planner.(SiteAuthChecker); ok {
+ if err := checker.RequireAuth("download:douyin"); err != nil {
+ return Task{}, err
+ }
+ }
+
+ var plan WorkDownloadPlan
+ if req.Plan != nil {
+ plan = *req.Plan
+ } else {
+ if !hasPlanner {
+ return Task{}, &site.Error{
+ Site: site.Douyin,
+ Kind: site.ErrKindUnavailable,
+ Message: "抖音下载规划器尚未初始化",
+ }
+ }
+ m.mu.Lock()
+ opts := WorkPlanOptions{
+ VideoQuality: m.dlSettings.VideoQuality,
+ CodecOrder: append([]string(nil), m.dlSettings.CodecOrder...),
+ }
+ m.mu.Unlock()
+ fetched, err := planner.PlanWorkDownload(ctx, awemeID, opts)
+ if err != nil {
+ return Task{}, err
+ }
+ plan = fetched
+ }
+
+ plan.Site = site.Douyin
+ if plan.TargetID == "" {
+ plan.TargetID = awemeID
+ }
+ kind := normalizeDouyinTaskKind(firstNonEmptyStr(plan.Kind, req.Kind), len(plan.Pages) > 0)
+ plan.Kind = kind
+
+ normUID, err := site.NormalizeUID(site.Douyin, plan.AuthorUID)
+ if err != nil {
+ return Task{}, &site.Error{
+ Site: site.Douyin,
+ Kind: site.ErrKindSchemaChanged,
+ Message: "抖音作品缺少有效作者标识",
+ }
+ }
+ plan.AuthorUID = normUID
+ if len(plan.Transport.AllowedDomains) == 0 {
+ plan.Transport = site.DouyinVODTransport("", false)
+ }
+
+ cacheRoot := m.lib.CacheDir()
+ itemDir, err := library.EnsureWithinRoot(cacheRoot, filepath.Join(cacheRoot, "douyin", site.DouyinAuthorDir(normUID), "works", plan.TargetID))
+ if err != nil {
+ return Task{}, err
+ }
+ itemKey := library.CanonicalItemKey("douyin", kind, plan.TargetID)
+ var via *library.ItemVia
+ if existing, exists, gErr := m.lib.GetItem(itemKey); gErr == nil && exists && existing.ItemDir != "" {
+ itemDir = existing.ItemDir
+ } else if forUID, fErr := site.NormalizeUID(site.Douyin, req.ForUID); fErr == nil && forUID != normUID {
+ if dir, dErr := library.EnsureWithinRoot(cacheRoot, filepath.Join(cacheRoot, "douyin", site.DouyinAuthorDir(forUID), "works", plan.TargetID)); dErr == nil {
+ itemDir = dir
+ via = &library.ItemVia{Reason: library.ViaCollab, Site: string(site.Douyin), UID: forUID, Name: strings.TrimSpace(req.ForName)}
+ }
+ }
+
+ source := strings.TrimSpace(req.Source)
+ if source == "" {
+ source = "manual"
+ }
+ coverDisplay := ""
+ if len(plan.CoverURLs) > 0 {
+ coverDisplay = sanitizeStoredURL(plan.CoverURLs[0])
+ }
+
+ title := strings.TrimSpace(plan.Title)
+ if title == "" {
+ title = strings.TrimSpace(plan.Desc)
+ }
+ if title == "" {
+ title = "抖音作品 " + plan.TargetID
+ }
+
+ t, err := m.enqueueSingleTaskWithPlan(Task{
+ Site: string(site.Douyin),
+ Kind: kind,
+ Source: source,
+ TargetID: plan.TargetID,
+ Page: 1,
+ Title: title,
+ AuthorUID: normUID,
+ AuthorName: plan.AuthorName,
+ AuthorFace: sanitizeStoredURL(plan.AuthorFace),
+ CoverURL: coverDisplay,
+ QualityHint: plan.DowngradeHint,
+ ItemKey: itemKey,
+ ItemDir: itemDir,
+ Via: via,
+ }, &plan)
+ if err != nil {
+ return Task{}, err
+ }
+
+ m.notifyWake()
+ return t, nil
+}
+
+func normalizeDouyinTaskKind(raw string, hasPages bool) string {
+ switch strings.ToLower(strings.TrimSpace(raw)) {
+ case "dynamic", "note", "image_note", "images":
+ return "dynamic"
+ case "video", "single_mp4":
+ if hasPages {
+ return "dynamic"
+ }
+ return "video"
+ default:
+ if hasPages {
+ return "dynamic"
+ }
+ return "video"
+ }
+}
+
+// musicFailureReason is the missing-music reason: the error class plus the
+// site error's own words (a refused host, a status), which name no signed
+// URL, so a partial note says why its music failed.
+func musicFailureReason(err error) string {
+ reason := fmt.Sprintf("配乐下载失败 (%s)", classifyDownloadError(err))
+ var se *site.Error
+ if errors.As(err, &se) {
+ if msg := strings.TrimSpace(se.Message); msg != "" {
+ reason += ":" + msg
+ }
+ }
+ return reason
+}
+
+func summarizeMissingReasons(missing []library.MissingRecord) string {
+ var reasons []string
+ seen := make(map[string]bool, len(missing))
+ for _, m := range missing {
+ r := strings.TrimSpace(m.Reason)
+ if r != "" && !seen[r] {
+ seen[r] = true
+ reasons = append(reasons, r)
+ }
+ }
+ switch len(reasons) {
+ case 0:
+ return ""
+ case 1:
+ if len(missing) > 1 {
+ return fmt.Sprintf("%s(共 %d 项未完成)", reasons[0], len(missing))
+ }
+ return reasons[0]
+ default:
+ return fmt.Sprintf("%s 等 %d 项未完成", reasons[0], len(missing))
+ }
+}
+
+func classifyDownloadError(err error) string {
+ if err == nil {
+ return ""
+ }
+ var pathErr *os.PathError
+ if errors.As(err, &pathErr) {
+ return site.ErrKindStorage
+ }
+ var encErr *EncryptedMediaError
+ if errors.As(err, &encErr) {
+ return site.ErrKindBlocked
+ }
+ var mp4Err *SingleMP4ValidationError
+ if errors.As(err, &mp4Err) {
+ return site.ErrKindSchemaChanged
+ }
+ return site.KindOf(err)
+}
+
+func (m *Manager) reportSiteAutomaticError(ctx context.Context, siteStr string, err error) {
+ if err == nil {
+ return
+ }
+ if siteStr == "" || siteStr == string(site.Bilibili) {
+ if m.client != nil {
+ m.client.ReportAutomaticError(ctx, err)
+ }
+ return
+ }
+ if planner, ok := m.getWorkPlanner(site.ID(siteStr)); ok {
+ if rep, ok := planner.(SiteErrorReporter); ok {
+ rep.ReportAutomaticError(ctx, err)
+ }
+ }
+}
+
+func (m *Manager) consumeInitialOrFetchDouyinPlan(ctx context.Context, taskID, targetID string) (WorkDownloadPlan, WorkPlanner, error) {
+ m.mu.Lock()
+ initial, hasInitial := m.initialPlans[taskID]
+ if hasInitial {
+ delete(m.initialPlans, taskID)
+ }
+ planner := m.planners[site.Douyin]
+ opts := WorkPlanOptions{
+ VideoQuality: m.dlSettings.VideoQuality,
+ CodecOrder: append([]string(nil), m.dlSettings.CodecOrder...),
+ }
+ m.mu.Unlock()
+
+ if hasInitial {
+ return initial, planner, nil
+ }
+ if planner == nil {
+ return WorkDownloadPlan{}, nil, &site.Error{
+ Site: site.Douyin,
+ Kind: site.ErrKindUnavailable,
+ Message: "抖音下载规划器尚未初始化",
+ }
+ }
+ if checker, ok := planner.(SiteAuthChecker); ok {
+ if err := checker.RequireAuth("download:douyin"); err != nil {
+ return WorkDownloadPlan{}, planner, err
+ }
+ }
+ plan, err := planner.PlanWorkDownload(ctx, targetID, opts)
+ if err != nil {
+ return WorkDownloadPlan{}, planner, err
+ }
+ if len(plan.Transport.AllowedDomains) == 0 {
+ plan.Transport = site.DouyinVODTransport("", false)
+ }
+ return plan, planner, nil
+}
+
+func (m *Manager) executeDouyinTask(ctx context.Context, t *Task) error {
+ unlock, err := m.lockItem(ctx, "douyin:"+t.TargetID)
+ if err != nil {
+ return err
+ }
+ defer unlock()
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+
+ plan, planner, err := m.consumeInitialOrFetchDouyinPlan(ctx, t.TaskID, t.TargetID)
+ if err != nil {
+ return err
+ }
+ normUID, err := site.NormalizeUID(site.Douyin, firstNonEmptyStr(plan.AuthorUID, t.AuthorUID))
+ if err != nil {
+ return &site.Error{
+ Site: site.Douyin,
+ Kind: site.ErrKindSchemaChanged,
+ Message: "抖音作品缺少有效作者标识",
+ }
+ }
+ plan.AuthorUID = normUID
+ t.AuthorUID = normUID
+
+ kind := normalizeDouyinTaskKind(firstNonEmptyStr(plan.Kind, t.Kind), len(plan.Pages) > 0)
+ t.Kind = kind
+ if kind == "dynamic" {
+ return m.executeDouyinNoteTask(ctx, t, plan, planner)
+ }
+ return m.executeDouyinVideoTask(ctx, t, plan, planner)
+}
+
+// douyinItemVia is the via of a Douyin item: an existing item keeps its own;
+// a new one stored under the folder of the account it was cached for
+// (Task.Via) records that account as a co-creator.
+func (m *Manager) douyinItemVia(t *Task, previous library.ItemMetadata, exists bool, itemDir string) *library.ItemVia {
+ if exists && previous.Via != nil {
+ return previous.Via
+ }
+ if t.Via == nil || t.Via.UID == "" {
+ return nil
+ }
+ root := m.lib.CacheDir()
+ want, err := library.EnsureWithinRoot(root, filepath.Join(root, "douyin", site.DouyinAuthorDir(t.Via.UID), "works", t.TargetID))
+ if err != nil || !strings.EqualFold(filepath.Clean(want), filepath.Clean(itemDir)) {
+ return nil
+ }
+ v := *t.Via
+ return &v
+}
+
+func (m *Manager) resolveDouyinItemDir(t *Task, kind, normUID, awemeID string) (library.ItemMetadata, bool, string, error) {
+ itemKey := library.CanonicalItemKey("douyin", kind, awemeID)
+ previous, exists, err := m.lib.GetItem(itemKey)
+ if err != nil {
+ return library.ItemMetadata{}, false, "", err
+ }
+ cacheRoot := m.lib.CacheDir()
+ itemDir, err := library.EnsureWithinRoot(cacheRoot, filepath.Join(cacheRoot, "douyin", site.DouyinAuthorDir(normUID), "works", awemeID))
+ if err != nil {
+ return library.ItemMetadata{}, false, "", err
+ }
+ if exists && previous.ItemDir != "" {
+ itemDir = previous.ItemDir
+ } else if t.ItemDir != "" {
+ if checked, cErr := library.EnsureWithinRoot(cacheRoot, t.ItemDir); cErr == nil {
+ itemDir = checked
+ }
+ }
+ if err := os.MkdirAll(itemDir, 0o700); err != nil {
+ return library.ItemMetadata{}, false, "", err
+ }
+ t.ItemKey = itemKey
+ t.ItemDir = itemDir
+ return previous, exists, itemDir, nil
+}
+
+func (m *Manager) makeSinglePlanRefresher(ctx context.Context, targetID string, planner WorkPlanner) func() (WorkDownloadPlan, error) {
+ var once sync.Once
+ var cached WorkDownloadPlan
+ var cachedErr error
+ return func() (WorkDownloadPlan, error) {
+ once.Do(func() {
+ if planner == nil {
+ cachedErr = &site.Error{Site: site.Douyin, Kind: site.ErrKindUnavailable, Message: "无法刷新过期的媒体地址"}
+ return
+ }
+ m.mu.Lock()
+ opts := WorkPlanOptions{
+ VideoQuality: m.dlSettings.VideoQuality,
+ CodecOrder: append([]string(nil), m.dlSettings.CodecOrder...),
+ }
+ m.mu.Unlock()
+ cached, cachedErr = planner.PlanWorkDownload(ctx, targetID, opts)
+ })
+ return cached, cachedErr
+ }
+}
+
+// makeOnceURLRefresher shares one refreshed plan across a task's files while
+// limiting each individual file to at most one URL refresh attempt.
+func makeOnceURLRefresher(
+ refreshPlan func() (WorkDownloadPlan, error),
+ extract func(WorkDownloadPlan) ([]string, error),
+) func() ([]string, error) {
+ var used bool
+ return func() ([]string, error) {
+ if used {
+ return nil, nil
+ }
+ used = true
+ fresh, err := refreshPlan()
+ if err != nil {
+ return nil, err
+ }
+ return extract(fresh)
+ }
+}
+
+func isSiteStopError(err error) bool {
+ k := classifyDownloadError(err)
+ return k == site.ErrKindRiskControl || k == site.ErrKindRateLimited || k == site.ErrKindAuthRequired
+}
+
+func fileOrPartExists(path string) bool {
+ if _, err := os.Stat(path); err == nil {
+ return true
+ }
+ if _, err := os.Stat(path + ".part"); err == nil {
+ return true
+ }
+ return false
+}
+
+// Staging names of media that is downloaded first and checked or converted
+// afterwards. They all end in ".part", so nothing that copies an item folder
+// takes them for finished files (docs/design/remote.md §6.1).
+const (
+ stageSuffix = ".stage.part" // transcoded stream before it is checked
+ origSuffix = ".orig.part" // untranscoded source before it is checked
+ imgSuffix = ".img.part" // image before its type is known
+ audSuffix = ".aud.part" // audio before its type is known
+)
+
+// stagingMarkers are the staging suffixes without the trailing ".part",
+// with the names earlier builds used (kept so their downloads resume).
+var stagingMarkers = []string{".stage", ".orig", ".img", ".aud", ".orig.raw", ".raw", ".imgtmp", ".audtmp"}
+
+// trimStagingSuffixes maps a download or staging path back to its final name.
+func trimStagingSuffixes(p string) string {
+ p = strings.TrimSuffix(p, ".part")
+ p = strings.TrimSuffix(p, ".part")
+ for _, suf := range stagingMarkers {
+ if strings.HasSuffix(p, suf) {
+ return strings.TrimSuffix(p, suf)
+ }
+ }
+ return p
+}
+
+// adoptLegacyStaging renames the staging files an earlier build left for
+// base (base+legacy and its ".part") to the current names, so a download
+// that was in progress during an upgrade resumes. Only files this task
+// registered are renamed; its progress record follows the new name.
+func (m *Manager) adoptLegacyStaging(t *Task, itemDir, base, legacy, current string) {
+ m.adoptLegacyName(t, itemDir, base+legacy, base+current)
+}
+
+// adoptLegacyName moves a file this task owns from the name an older
+// version used (oldRel, and its .part) to newRel, so a download paused
+// before the upgrade resumes instead of starting over.
+func (m *Manager) adoptLegacyName(t *Task, itemDir, oldRel, newRel string) {
+ if t == nil || itemDir == "" || oldRel == newRel {
+ return
+ }
+ idx := -1
+ for i := range t.Files {
+ if taskFileIdentity(t.Files[i].Path) == taskFileIdentity(oldRel) && taskFileOwned(t.Files[i]) {
+ idx = i
+ break
+ }
+ }
+ if idx < 0 {
+ return
+ }
+ for _, pair := range [][2]string{{oldRel, newRel}, {oldRel + ".part", newRel + ".part"}} {
+ from, err1 := library.ResolveItemPath(itemDir, pair[0])
+ to, err2 := library.ResolveItemPath(itemDir, pair[1])
+ if err1 != nil || err2 != nil {
+ continue
+ }
+ if _, err := os.Lstat(to); err == nil {
+ continue
+ }
+ if _, err := os.Lstat(from); err == nil {
+ _ = os.Rename(from, to)
+ }
+ }
+ t.Files[idx].Path = newRel
+ _ = m.saveTaskProgress(*t)
+}
+
+func (m *Manager) removeTempTaskProgress(t *Task, tempRel string) {
+ filtered := t.Files[:0]
+ for _, f := range t.Files {
+ if taskFileIdentity(f.Path) != taskFileIdentity(tempRel) {
+ filtered = append(filtered, f)
+ }
+ }
+ t.Files = filtered
+}
diff --git a/internal/download/douyin_video.go b/internal/download/douyin_video.go
new file mode 100644
index 0000000..c36c717
--- /dev/null
+++ b/internal/download/douyin_video.go
@@ -0,0 +1,593 @@
+package download
+
+import (
+ "context"
+ "math"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/site"
+)
+
+const (
+ douyinOriginalGear = "original"
+ douyinOriginalQuality = "原画"
+)
+
+func (m *Manager) executeDouyinVideoTask(ctx context.Context, t *Task, plan WorkDownloadPlan, planner WorkPlanner) (result error) {
+ previous, exists, itemDir, err := m.resolveDouyinItemDir(t, "video", plan.AuthorUID, t.TargetID)
+ if err != nil {
+ return err
+ }
+
+ m.mu.Lock()
+ cfg := m.dlSettings
+ m.mu.Unlock()
+
+ title := firstNonEmptyStr(plan.Title, plan.Desc, t.Title, "抖音视频 "+t.TargetID)
+ canonicalURL := firstNonEmptyStr(sanitizeStoredURL(plan.CanonicalURL), "https://www.douyin.com/video/"+t.TargetID)
+ t.Title = title
+ t.AuthorName = firstNonEmptyStr(plan.AuthorName, t.AuthorName)
+ t.AuthorFace = sanitizeStoredURL(firstNonEmptyStr(plan.AuthorFace, t.AuthorFace))
+ if len(plan.CoverURLs) > 0 {
+ t.CoverURL = sanitizeStoredURL(plan.CoverURLs[0])
+ }
+ if plan.DowngradeHint != "" {
+ t.QualityHint = plan.DowngradeHint
+ }
+
+ meta := library.ItemMetadata{
+ Version: 1,
+ ID: "video:" + t.TargetID,
+ Site: "douyin",
+ Kind: "video",
+ Status: "partial",
+ Title: title,
+ Desc: plan.Desc,
+ URL: canonicalURL,
+ PubTs: plan.PubTs,
+ CachedAt: previous.CachedAt,
+ Duration: plan.DurationSec,
+ Author: library.ItemAuthor{
+ Site: "douyin",
+ UID: plan.AuthorUID,
+ UniqueID: plan.AuthorUniqueID,
+ Name: t.AuthorName,
+ Face: t.AuthorFace,
+ },
+ Media: append([]library.MediaFile(nil), previous.Media...),
+ Missing: append([]library.MissingRecord(nil), previous.Missing...),
+ DirectCached: true,
+ Via: m.douyinItemVia(t, previous, exists, itemDir),
+ }
+
+ finalSaved := false
+ defer func() {
+ if result == nil || finalSaved {
+ return
+ }
+ if !isSiteStopError(result) && !mediaIsValid(meta, "video.mp4") {
+ addMissing(&meta, "video.mp4", "视频尚未完成 ("+classifyDownloadError(result)+")")
+ }
+ meta.Status = "partial"
+ saved, sErr := m.lib.SaveItem(itemDir, meta)
+ if sErr != nil {
+ if !isSiteStopError(result) && ctx.Err() == nil {
+ result = sErr
+ }
+ return
+ }
+ t.ItemKey = saved.ItemKey
+ }()
+
+ refreshOncePlan := m.makeSinglePlanRefresher(ctx, t.TargetID, planner)
+
+ // 1. Save cover. when enabled.
+ if cfg.SaveCover && len(plan.CoverURLs) > 0 {
+ refreshCover := makeOnceURLRefresher(refreshOncePlan, func(fresh WorkDownloadPlan) ([]string, error) {
+ return fresh.CoverURLs, nil
+ })
+ if coverMedia, cErr := m.cacheDouyinSniffedImage(ctx, t, itemDir, previous, exists, "cover", "cover", plan.CoverURLs, 0, 0, plan.Transport, refreshCover); cErr != nil {
+ if isSiteStopError(cErr) || isStorageError(cErr) || ctx.Err() != nil {
+ return cErr
+ }
+ addMissing(&meta, "cover", "封面保存失败 ("+classifyDownloadError(cErr)+")")
+ } else if coverMedia != nil {
+ meta.Media = replaceRoleMedia(meta.Media, "cover", *coverMedia)
+ clearMissing(&meta, "cover")
+ }
+ }
+
+ // 2. Download & validate single-file video.mp4 (including bounded-memory moov relocation).
+ videoRel := "video.mp4"
+ videoPath, err := library.ResolveItemPath(itemDir, videoRel)
+ if err != nil {
+ return err
+ }
+ if exists && mediaIsValid(previous, videoRel) {
+ for _, mf := range previous.Media {
+ if mf.Path == videoRel {
+ m.setFileProgress(t, "video", videoRel, "completed", mf.Bytes, mf.Bytes, 0)
+ meta.Media = mergeMediaFiles(meta.Media, []library.MediaFile{mf})
+ clearMissing(&meta, videoRel)
+ break
+ }
+ }
+ } else {
+ if err := m.claimTaskFile(t, itemDir, videoRel, videoPath); err != nil {
+ return err
+ }
+ m.setFileProgress(t, "video", videoRel, "downloading", 0, 0, 0)
+ refreshVideoURLs := makeOnceURLRefresher(refreshOncePlan, func(fresh WorkDownloadPlan) ([]string, error) {
+ if plan.Codec != "" && fresh.Codec != "" && !strings.EqualFold(plan.Codec, fresh.Codec) {
+ return nil, &site.Error{Site: site.Douyin, Kind: site.ErrKindUnavailable, Message: "续传地址的视频编码发生变化,已保留断点"}
+ }
+ if plan.VideoGear != "" && fresh.VideoGear != "" && plan.VideoGear != fresh.VideoGear {
+ return nil, &site.Error{Site: site.Douyin, Kind: site.ErrKindUnavailable, Message: "续传地址的清晰度档位发生变化,已保留断点"}
+ }
+ return fresh.VideoURLs, nil
+ })
+ rawRel := videoRel + stageSuffix
+ stagingPath := videoPath + stageSuffix
+ m.adoptLegacyStaging(t, itemDir, videoRel, ".raw", stageSuffix)
+ var summary MuxTrackSummary
+ original := false
+ if len(plan.OriginalURLs) > 0 {
+ origSummary, oErr := m.cacheDouyinOriginal(ctx, t, plan, refreshOncePlan, videoRel, videoPath)
+ switch {
+ case oErr == nil:
+ summary, original = origSummary, true
+ // A transcoded attempt from an earlier run is no longer needed.
+ _ = os.Remove(stagingPath)
+ _ = os.Remove(stagingPath + ".part")
+ m.removeTempTaskProgress(t, rawRel)
+ case ctx.Err() != nil || site.IsRoundStop(oErr) || isStorageError(oErr):
+ m.setFileProgress(t, "video", videoRel, "failed", t.BytesDownloaded, t.TotalBytes, 0)
+ return oErr
+ }
+ // Any other failure (including networkPauseError on OriginalURLs) falls back to VideoURLs below.
+ }
+ if !original {
+ _, _, dlErr := m.downloadDouyinMP4WithFallback(ctx, plan.Transport, plan.VideoURLs, plan.NeedSetToken, stagingPath, "video", t, planner, refreshVideoURLs)
+ if dlErr != nil {
+ if ctx.Err() == nil && !fileOrPartExists(stagingPath) {
+ m.removeTempTaskProgress(t, rawRel)
+ }
+ m.setFileProgress(t, "video", videoRel, "failed", t.BytesDownloaded, t.TotalBytes, 0)
+ return dlErr
+ }
+
+ m.setFileProgress(t, "video", videoRel, "verifying", t.BytesDownloaded, t.TotalBytes, 0)
+ var vErr error
+ summary, vErr = EnsureSingleMP4Context(ctx, stagingPath, float64(plan.DurationSec))
+ if vErr != nil {
+ if ctx.Err() == nil {
+ _ = os.Remove(stagingPath)
+ m.removeTempTaskProgress(t, rawRel)
+ m.setFileProgress(t, "video", videoRel, "failed", 0, 0, 0)
+ }
+ return vErr
+ }
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if err := os.Rename(stagingPath, videoPath); err != nil {
+ return err
+ }
+ m.removeTempTaskProgress(t, rawRel)
+ }
+ durSec := int(math.Round(summary.DurationSec))
+ if durSec <= 0 {
+ durSec = plan.DurationSec
+ }
+ meta.Duration = durSec
+ width, height := summary.Width, summary.Height
+ if width <= 0 {
+ width = plan.Width
+ }
+ if height <= 0 {
+ height = plan.Height
+ }
+ videoMedia := library.MediaFile{
+ Role: "video",
+ Path: videoRel,
+ Bytes: summary.FileBytes,
+ SHA256: summary.SHA256,
+ Width: width,
+ Height: height,
+ Duration: durSec,
+ }
+ m.setFileProgress(t, "video", videoRel, "completed", summary.FileBytes, summary.FileBytes, 0)
+ meta.Media = mergeMediaFiles(meta.Media, []library.MediaFile{videoMedia})
+ clearMissing(&meta, videoRel)
+ meta.DouyinVideo = &library.DouyinVideoInfo{
+ File: videoRel,
+ Gear: plan.VideoGear,
+ QualityName: plan.QualityName,
+ Codec: firstNonEmptyStr(plan.Codec, summaryPrimaryVideoCodec(summary)),
+ Width: width,
+ Height: height,
+ FPS: plan.FPS,
+ Bitrate: plan.Bitrate,
+ AvailableGears: append([]string(nil), plan.AvailableGears...),
+ }
+ if original {
+ info := meta.DouyinVideo
+ info.Gear, info.QualityName = douyinOriginalGear, douyinOriginalQuality
+ info.Codec = firstNonEmptyStr(summaryPrimaryVideoCodec(summary), plan.Codec)
+ info.FPS = 0
+ info.Bitrate = 0
+ if summary.DurationSec > 0 {
+ info.Bitrate = int64(float64(summary.FileBytes*8) / summary.DurationSec)
+ }
+ info.AvailableGears = append([]string{douyinOriginalQuality}, plan.AvailableGears...)
+ }
+ }
+
+ if meta.DouyinVideo == nil && previous.DouyinVideo != nil {
+ cp := *previous.DouyinVideo
+ meta.DouyinVideo = &cp
+ }
+
+ meta.Status = "complete"
+ if len(meta.Missing) > 0 {
+ meta.Status = "partial"
+ t.Status = "partial"
+ t.ErrorMessage = summarizeMissingReasons(meta.Missing)
+ }
+ saved, err := m.lib.SaveItem(itemDir, meta)
+ if err != nil {
+ return err
+ }
+ t.ItemKey = saved.ItemKey
+ finalSaved = true
+ return nil
+}
+
+// cacheDouyinOriginal downloads the untranscoded source (原画) into its own staging
+// file and validates it as a single progressive MP4, then moves it to videoPath.
+// On a failure the caller falls back to the transcoded stream, so the staging file
+// is removed unless the task was cancelled or paused (kept for resume).
+func (m *Manager) cacheDouyinOriginal(
+ ctx context.Context,
+ t *Task,
+ plan WorkDownloadPlan,
+ refreshPlan func() (WorkDownloadPlan, error),
+ videoRel, videoPath string,
+) (MuxTrackSummary, error) {
+ origRel := videoRel + origSuffix
+ origPath := videoPath + origSuffix
+ m.adoptLegacyStaging(t, filepath.Dir(videoPath), videoRel, ".orig.raw", origSuffix)
+ discard := func() {
+ if ctx.Err() == nil {
+ _ = os.Remove(origPath)
+ _ = os.Remove(origPath + ".part")
+ m.removeTempTaskProgress(t, origRel)
+ }
+ }
+ refresh := makeOnceURLRefresher(refreshPlan, func(fresh WorkDownloadPlan) ([]string, error) {
+ if len(fresh.OriginalURLs) == 0 {
+ return nil, &site.Error{Site: site.Douyin, Kind: site.ErrKindUnavailable, Message: "原画地址已不可用"}
+ }
+ return fresh.OriginalURLs, nil
+ })
+ if _, _, err := m.downloadWithTransportRefresh(ctx, plan.Transport, plan.OriginalURLs, origPath, "video", t, refresh); err != nil {
+ discard()
+ return MuxTrackSummary{}, err
+ }
+ m.setFileProgress(t, "video", videoRel, "verifying", t.BytesDownloaded, t.TotalBytes, 0)
+ summary, err := EnsureSingleMP4Context(ctx, origPath, float64(plan.DurationSec))
+ if err == nil && summaryPrimaryVideoCodec(summary) == "" {
+ err = &site.Error{Site: site.Douyin, Kind: site.ErrKindSchemaChanged, Message: "原画文件没有视频轨"}
+ }
+ if err == nil {
+ err = ctx.Err()
+ }
+ if err == nil {
+ err = os.Rename(origPath, videoPath)
+ }
+ if err != nil {
+ discard()
+ return MuxTrackSummary{}, err
+ }
+ m.removeTempTaskProgress(t, origRel)
+ return summary, nil
+}
+
+func (m *Manager) cacheDouyinSingleMP4(
+ ctx context.Context,
+ t *Task,
+ itemDir string,
+ previous library.ItemMetadata,
+ exists bool,
+ role string,
+ relPath string,
+ urls []string,
+ needSetToken bool,
+ expectedDuration int,
+ fallbackW, fallbackH int,
+ transport site.MediaTransportSpec,
+ planner WorkPlanner,
+ refreshURLs func() ([]string, error),
+) (*library.MediaFile, error) {
+ if exists && mediaIsValid(previous, relPath) {
+ for _, mf := range previous.Media {
+ if mf.Path == relPath {
+ m.setFileProgress(t, role, relPath, "completed", mf.Bytes, mf.Bytes, 0)
+ cp := mf
+ return &cp, nil
+ }
+ }
+ }
+ fullPath, err := library.ResolveItemPath(itemDir, relPath)
+ if err != nil {
+ return nil, err
+ }
+ if err := m.claimTaskFile(t, itemDir, relPath, fullPath); err != nil {
+ return nil, err
+ }
+ m.setFileProgress(t, role, relPath, "downloading", 0, 0, 0)
+ rawRel := relPath + stageSuffix
+ stagingPath := fullPath + stageSuffix
+ m.adoptLegacyStaging(t, itemDir, relPath, ".raw", stageSuffix)
+ if _, _, err := m.downloadDouyinMP4WithFallback(ctx, transport, urls, needSetToken, stagingPath, role, t, planner, refreshURLs); err != nil {
+ if ctx.Err() == nil && !fileOrPartExists(stagingPath) {
+ m.removeTempTaskProgress(t, rawRel)
+ }
+ m.setFileProgress(t, role, relPath, "failed", 0, 0, 0)
+ return nil, err
+ }
+ m.setFileProgress(t, role, relPath, "verifying", 0, 0, 0)
+ summary, err := EnsureSingleMP4Context(ctx, stagingPath, float64(expectedDuration))
+ if err != nil {
+ if ctx.Err() == nil {
+ _ = os.Remove(stagingPath)
+ m.removeTempTaskProgress(t, rawRel)
+ m.setFileProgress(t, role, relPath, "failed", 0, 0, 0)
+ }
+ return nil, err
+ }
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ if err := os.Rename(stagingPath, fullPath); err != nil {
+ return nil, err
+ }
+ m.removeTempTaskProgress(t, rawRel)
+ dur := int(math.Round(summary.DurationSec))
+ if dur <= 0 {
+ dur = expectedDuration
+ }
+ w, h := summary.Width, summary.Height
+ if w <= 0 {
+ w = fallbackW
+ }
+ if h <= 0 {
+ h = fallbackH
+ }
+ m.setFileProgress(t, role, relPath, "completed", summary.FileBytes, summary.FileBytes, 0)
+ return &library.MediaFile{
+ Role: role,
+ Path: relPath,
+ Bytes: summary.FileBytes,
+ SHA256: summary.SHA256,
+ Width: w,
+ Height: h,
+ Duration: dur,
+ }, nil
+}
+
+func playURLResolverOf(planner WorkPlanner) PlayURLResolver {
+ if planner == nil {
+ return nil
+ }
+ if bsa, ok := planner.(*basicSitePlannerAdapter); ok {
+ r, _ := bsa.inner.(PlayURLResolver)
+ return r
+ }
+ r, _ := planner.(PlayURLResolver)
+ return r
+}
+
+func splitDouyinPlayRedirectURLs(urls []string, allowLocalhost bool) (direct, play []string) {
+ for _, raw := range urls {
+ uStr := strings.TrimSpace(raw)
+ if uStr == "" {
+ continue
+ }
+ u, err := url.Parse(uStr)
+ if err != nil || u.Host == "" {
+ direct = append(direct, uStr)
+ continue
+ }
+ host := strings.ToLower(u.Hostname())
+ cleanPath := strings.TrimSuffix(strings.ToLower(u.Path), "/")
+ isPlayHost := site.MatchDomainSuffix(host, []string{"douyin.com", "iesdouyin.com", "amemv.com"}) ||
+ (allowLocalhost && site.IsLoopbackHost(host))
+ if isPlayHost && cleanPath == "/aweme/v1/play" {
+ play = append(play, uStr)
+ } else {
+ direct = append(direct, uStr)
+ }
+ }
+ return direct, play
+}
+
+func (m *Manager) resolveAndDownloadPlayRedirect(
+ ctx context.Context,
+ transport site.MediaTransportSpec,
+ playURLs []string,
+ stagingPath string,
+ role string,
+ t *Task,
+ resolver PlayURLResolver,
+) (int64, string, error) {
+ if resolver == nil || len(playURLs) == 0 {
+ return 0, "", &site.Error{Site: site.Douyin, Kind: site.ErrKindUnavailable, Message: "无可用播放跳转地址"}
+ }
+ const maxDraws = 2
+ var lastErr error
+ for draw := 0; draw < maxDraws; draw++ {
+ if ctx.Err() != nil {
+ return 0, "", ctx.Err()
+ }
+ playURL := playURLs[draw%len(playURLs)]
+ resolvedURL, rErr := resolver.ResolvePlayRedirect(ctx, playURL)
+ if rErr != nil {
+ if ctx.Err() != nil || isSiteStopError(rErr) || isStorageError(rErr) {
+ return 0, "", rErr
+ }
+ lastErr = rErr
+ if draw+1 >= len(playURLs) {
+ break
+ }
+ continue
+ }
+
+ // The authenticated first hop on www.douyin.com already resolved into a
+ // cookieless CDN URL; allow subsequent public HTTPS 443 edge redirects
+ // (matching live FLV and music policies) while blocking IP/local/non-443.
+ playTransport := transport
+ playTransport.PublicRedirects = true
+ if playTransport.ValidateURL(resolvedURL) != nil && playTransport.ValidateRedirectURL(resolvedURL) == nil {
+ if parsed, pErr := url.Parse(resolvedURL); pErr == nil && parsed.Hostname() != "" {
+ allowed := append([]string(nil), playTransport.AllowedDomains...)
+ allowed = append(allowed, strings.ToLower(parsed.Hostname()))
+ playTransport.AllowedDomains = allowed
+ }
+ }
+
+ n, sha, _, dlErr := m.downloadRange(ctx, m.transportRangeSpec(playTransport, role, true), []string{resolvedURL}, stagingPath, t)
+ if dlErr == nil {
+ return n, sha, nil
+ }
+ if ctx.Err() != nil || isSiteStopError(dlErr) || isStorageError(dlErr) {
+ return 0, "", dlErr
+ }
+ lastErr = dlErr
+ }
+ return 0, "", lastErr
+}
+
+// downloadDouyinMP4WithFallback downloads a Douyin single-file MP4 (video, note
+// video page, or live-photo motion clip). When needSetToken is true (e.g. direct
+// v26-web CDN links require a session token and answer HTTP 403), it resolves the
+// authenticated www.douyin.com/aweme/v1/play/ redirector first into a cookieless
+// CDN URL. For normal works it tries direct CDN URLs first and only uses the play
+// redirector if direct CDN URLs still fail with 403/404 after refresh.
+func (m *Manager) downloadDouyinMP4WithFallback(
+ ctx context.Context,
+ transport site.MediaTransportSpec,
+ urls []string,
+ needSetToken bool,
+ stagingPath string,
+ role string,
+ t *Task,
+ planner WorkPlanner,
+ refreshURLs func() ([]string, error),
+) (int64, string, error) {
+ resolver := playURLResolverOf(planner)
+ directURLs, playURLs := splitDouyinPlayRedirectURLs(urls, transport.AllowLocalhost)
+
+ var (
+ refreshed bool
+ freshDirect []string
+ freshPlay []string
+ refreshError error
+ )
+ refreshOnce := func() ([]string, []string, error) {
+ if refreshed {
+ return freshDirect, freshPlay, refreshError
+ }
+ refreshed = true
+ if refreshURLs == nil {
+ return nil, nil, nil
+ }
+ freshAll, rErr := refreshURLs()
+ refreshError = rErr
+ if rErr != nil {
+ return nil, nil, rErr
+ }
+ freshDirect, freshPlay = splitDouyinPlayRedirectURLs(freshAll, transport.AllowLocalhost)
+ return freshDirect, freshPlay, nil
+ }
+ refreshDirectOnly := func() ([]string, error) {
+ d, _, rErr := refreshOnce()
+ return d, rErr
+ }
+
+ if needSetToken && len(playURLs) > 0 && resolver != nil {
+ n, sha, err := m.resolveAndDownloadPlayRedirect(ctx, transport, playURLs, stagingPath, role, t, resolver)
+ if err == nil || ctx.Err() != nil || isSiteStopError(err) || isStorageError(err) {
+ return n, sha, err
+ }
+ if refreshURLs != nil && (site.IsKind(err, site.ErrKindForbidden) || site.IsKind(err, site.ErrKindUnavailable)) {
+ fDirect, fPlay, rErr := refreshOnce()
+ if rErr != nil {
+ if ctx.Err() != nil || isSiteStopError(rErr) || isStorageError(rErr) || site.IsKind(rErr, site.ErrKindUnavailable) {
+ return 0, "", rErr
+ }
+ } else {
+ if len(fPlay) > 0 {
+ n2, sha2, err2 := m.resolveAndDownloadPlayRedirect(ctx, transport, fPlay, stagingPath, role, t, resolver)
+ if err2 == nil || ctx.Err() != nil || isSiteStopError(err2) || isStorageError(err2) {
+ return n2, sha2, err2
+ }
+ err = err2
+ }
+ if len(fDirect) > 0 {
+ n3, sha3, _, err3 := m.downloadRange(ctx, m.transportRangeSpec(transport, role, true), fDirect, stagingPath, t)
+ if err3 == nil || ctx.Err() != nil || isSiteStopError(err3) || isStorageError(err3) {
+ return n3, sha3, err3
+ }
+ return 0, "", err3
+ }
+ }
+ }
+ if len(directURLs) > 0 && !refreshed {
+ if n2, sha2, _, err2 := m.downloadRange(ctx, m.transportRangeSpec(transport, role, true), directURLs, stagingPath, t); err2 == nil || ctx.Err() != nil || isSiteStopError(err2) || isStorageError(err2) {
+ return n2, sha2, err2
+ }
+ }
+ return 0, "", err
+ }
+
+ if len(directURLs) > 0 {
+ n, sha, err := m.downloadWithTransportRefresh(ctx, transport, directURLs, stagingPath, role, t, refreshDirectOnly)
+ if err == nil || ctx.Err() != nil || isSiteStopError(err) || isStorageError(err) {
+ return n, sha, err
+ }
+ if resolver != nil && (site.IsKind(err, site.ErrKindForbidden) || site.IsKind(err, site.ErrKindUnavailable)) {
+ candPlay := playURLs
+ if len(freshPlay) > 0 {
+ candPlay = freshPlay
+ }
+ if len(candPlay) > 0 {
+ n2, sha2, err2 := m.resolveAndDownloadPlayRedirect(ctx, transport, candPlay, stagingPath, role, t, resolver)
+ if err2 == nil || ctx.Err() != nil || isSiteStopError(err2) || isStorageError(err2) {
+ return n2, sha2, err2
+ }
+ }
+ }
+ return 0, "", err
+ }
+
+ if len(playURLs) > 0 && resolver != nil {
+ n, sha, err := m.resolveAndDownloadPlayRedirect(ctx, transport, playURLs, stagingPath, role, t, resolver)
+ if err == nil || ctx.Err() != nil || isSiteStopError(err) || isStorageError(err) {
+ return n, sha, err
+ }
+ if refreshURLs != nil && (site.IsKind(err, site.ErrKindForbidden) || site.IsKind(err, site.ErrKindUnavailable)) {
+ _, fPlay, rErr := refreshOnce()
+ if rErr == nil && len(fPlay) > 0 {
+ return m.resolveAndDownloadPlayRedirect(ctx, transport, fPlay, stagingPath, role, t, resolver)
+ }
+ }
+ return 0, "", err
+ }
+
+ return m.downloadWithTransportRefresh(ctx, transport, urls, stagingPath, role, t, refreshURLs)
+}
diff --git a/internal/download/download_test.go b/internal/download/download_test.go
index 3d2a999..babb21d 100644
--- a/internal/download/download_test.go
+++ b/internal/download/download_test.go
@@ -74,7 +74,7 @@ func setupDownloadEnv(t *testing.T, handler http.Handler, maxConc int) (*Manager
return mgr, libStore, srv
}
-// PR-2 & C17: Pure-Go DASH video.m4s + audio.m4s muxing via mp4ff, elst verification, Dolby/FLAC sidecar + AAC fallback, and complete video part caching.
+// Pure-Go DASH video.m4s + audio.m4s muxing via mp4ff, elst verification, Dolby/FLAC sidecar + AAC fallback, and complete video part caching.
func TestMuxDASHFilesAndVideoCacheEndToEnd(t *testing.T) {
// Generate 2 seconds (60 video frames @ 30fps, 94 audio frames @ 48kHz) so 1s chunk interleaving produces multiple chunks per track.
vBytes, err := BuildSyntheticVideoM4S(60, 30)
@@ -189,6 +189,7 @@ func TestMuxDASHFilesAndVideoCacheEndToEnd(t *testing.T) {
mgr, libStore, srv := setupDownloadEnv(t, mux, 2)
srvURL = srv.URL
+ checkNames := watchNames(t, libStore.CacheDir())
// High-quality DASH audio retains its MP4 container name, with AAC in the main MP4.
dlCfg := mgr.dlSettings
@@ -209,6 +210,7 @@ func TestMuxDASHFilesAndVideoCacheEndToEnd(t *testing.T) {
// Wait for task completion.
doneTask := waitForTaskStatus(t, mgr, tasks[0].TaskID, "completed", 5*time.Second)
+ checkNames()
mp4Path := filepath.Join(doneTask.ItemDir, "P01.mp4")
summary, err := InspectMP4File(mp4Path)
if err != nil {
@@ -259,7 +261,7 @@ func TestMuxDASHFilesAndVideoCacheEndToEnd(t *testing.T) {
}
}
-// C18 & R-06: Closed-interval 8 MiB Range resume, Content-Range verification, 200 fallback, per-segment retry + URL rotation, and 403 PlayURL refresh.
+// Closed-interval 8 MiB Range resume, Content-Range verification, 200 fallback, per-segment retry + URL rotation, and 403 PlayURL refresh.
func TestRangeResume206AndFallback200(t *testing.T) {
fullPayload := bytes.Repeat([]byte("0123456789abcdef"), 1024) // 16 KiB
wantSum := sha256.Sum256(fullPayload)
@@ -345,7 +347,7 @@ func TestRangeResume206AndFallback200(t *testing.T) {
}
}
-// C19 & C23: Dynamic caching with linked video and partial image failure + retry recovery.
+// Dynamic caching with linked video and partial image failure + retry recovery.
func TestDynamicCacheLinkedVideosAndPartialRetry(t *testing.T) {
vBytes, _ := BuildSyntheticVideoM4S(10, 30)
aBytes, _ := BuildSyntheticAudioM4S(15)
@@ -480,16 +482,7 @@ func TestDynamicCacheLinkedVideosAndPartialRetry(t *testing.T) {
}
}
-// Aliases for stage-report C19 & C23 references.
-func TestDynamicCacheAndLinkedVideos(t *testing.T) {
- TestDynamicCacheLinkedVideosAndPartialRetry(t)
-}
-
-func TestPartialFailureAndRetrySkipsCompleted(t *testing.T) {
- TestDynamicCacheLinkedVideosAndPartialRetry(t)
-}
-
-// C15, C20, R-05: Queue concurrency limit, deduplication, startup pause ("已暂停(应用关闭)"), and risk_control circuit breaker.
+// Queue concurrency limit, deduplication, startup pause ("已暂停(应用关闭)"), and risk_control circuit breaker.
func TestQueueConcurrencyDedupStartupRecoveryAndCircuitBreaker(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/x/web-interface/wbi/view", func(w http.ResponseWriter, r *http.Request) {
@@ -518,7 +511,7 @@ func TestQueueConcurrencyDedupStartupRecoveryAndCircuitBreaker(t *testing.T) {
mgr, _, _ := setupDownloadEnv(t, mux, 1)
ctx := context.Background()
- // 1. Test task deduplication before starting workers (C15).
+ // 1. Test task deduplication before starting workers.
detail := &bilibili.VideoDetail{
BVID: "BV1dedup0001",
Title: "Dedup Video",
@@ -534,7 +527,7 @@ func TestQueueConcurrencyDedupStartupRecoveryAndCircuitBreaker(t *testing.T) {
t.Fatalf("expected duplicate EnqueueVideo to return same task ID %q, got %+v", t1[0].TaskID, t2)
}
- // Simulate an interrupted "running" task in SQLite and verify Start() transitions it to "paused" ("已暂停(应用关闭)") without auto-running (R-05, C15).
+ // Simulate an interrupted "running" task in SQLite and verify Start() transitions it to "paused" ("已暂停(应用关闭)") without auto-running.
_, _ = mgr.db.Exec(`UPDATE download_tasks SET status = 'running' WHERE task_id = ?`, t1[0].TaskID)
_ = mgr.Start(ctx)
mgr.Stop()
@@ -544,7 +537,7 @@ func TestQueueConcurrencyDedupStartupRecoveryAndCircuitBreaker(t *testing.T) {
}
_, _ = mgr.Cancel(t1[0].TaskID)
- // 2. Test risk_control circuit breaker (C20):
+ // 2. Test risk_control circuit breaker:
// Start manager first, then enqueue a task that triggers -412 risk_control and a second queued task.
runCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
@@ -576,15 +569,6 @@ func TestQueueConcurrencyDedupStartupRecoveryAndCircuitBreaker(t *testing.T) {
}
}
-// Aliases for stage-report C15 & C20 references.
-func TestTaskQueueConcurrencyAndStartupPause(t *testing.T) {
- TestQueueConcurrencyDedupStartupRecoveryAndCircuitBreaker(t)
-}
-
-func TestRiskControlCircuitBreakerPausesQueued(t *testing.T) {
- TestQueueConcurrencyDedupStartupRecoveryAndCircuitBreaker(t)
-}
-
func waitForTaskStatus(t *testing.T, mgr *Manager, taskID string, wantStatus string, timeout time.Duration) Task {
t.Helper()
deadline := time.Now().Add(timeout)
diff --git a/internal/download/dynamic.go b/internal/download/dynamic.go
new file mode 100644
index 0000000..629b496
--- /dev/null
+++ b/internal/download/dynamic.go
@@ -0,0 +1,451 @@
+package download
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "math"
+ "net/url"
+ "os"
+ "path"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/site/bilibili"
+ "github.com/chialecode/trace/internal/storage"
+)
+
+func (m *Manager) executeDynamicTask(ctx context.Context, t *Task) (result error) {
+ dyn, err := m.client.DynamicDetail(ctx, t.TargetID)
+ if err != nil {
+ return err
+ }
+
+ forward := dyn.Origin != nil || strings.EqualFold(dyn.Type, "DYNAMIC_TYPE_FORWARD")
+ for origin := dyn.Origin; origin != nil; origin = origin.Origin {
+ dyn.Images = append(dyn.Images, origin.Images...)
+ dyn.Videos = append(dyn.Videos, origin.Videos...)
+ }
+ // A forward's parse already copies the origin's media when the forward has
+ // none of its own; keep each image and video once.
+ dyn.Images = dedupeDynamicImages(dyn.Images)
+ dyn.Videos = dedupeDynamicVideos(dyn.Videos)
+ t.Title = dyn.Title
+ t.Mid = dyn.Author.Mid
+ t.AuthorName = dyn.Author.Name
+ t.AuthorFace = dyn.Author.Face
+
+ m.mu.Lock()
+ multiPart := m.dlSettings.MultiPart
+ m.mu.Unlock()
+
+ cacheRoot := m.lib.CacheDir()
+ // Forwards and what they carry live in the forwarder's own forwards/
+ // folder, apart from their own posts (DEC-056).
+ typeDir := "dynamics"
+ if forward {
+ typeDir = "forwards"
+ }
+ authorDir := filepath.Join(cacheRoot, "bilibili", strconv.FormatInt(dyn.Author.Mid, 10))
+ itemDir, err := library.EnsureWithinRoot(cacheRoot, filepath.Join(authorDir, typeDir, dyn.ID))
+ if err != nil {
+ return err
+ }
+ previous, exists, err := m.lib.GetItem("dynamic:" + dyn.ID)
+ if err != nil {
+ return err
+ }
+ if exists {
+ itemDir = previous.ItemDir
+ } else if t.ItemDir != "" {
+ checked, dirErr := library.EnsureWithinRoot(cacheRoot, t.ItemDir)
+ if dirErr != nil {
+ return dirErr
+ }
+ itemDir = checked
+ }
+ if err := os.MkdirAll(itemDir, 0o700); err != nil {
+ return err
+ }
+ t.ItemDir = itemDir
+
+ for idx, img := range dyn.Images {
+ ext := guessImageExt(img.URL)
+ relName := fmt.Sprintf("images/%02d%s", idx+1, ext)
+ m.setFileProgress(t, "image", relName, "waiting", 0, 0, 0)
+ if img.LiveURL != "" {
+ m.setFileProgress(t, "motion", motionRelName(idx, img.LiveURL), "waiting", 0, 0, 0)
+ }
+ }
+ m.persistTaskProgress(*t)
+
+ var mediaFiles []library.MediaFile
+ var partialErrors []string
+ var videoRefs []string
+ finalSaved := false
+ for _, video := range dyn.Videos {
+ if video.BVID != "" {
+ videoRefs = append(videoRefs, "video:"+video.BVID)
+ }
+ }
+ t.ItemKey = library.CanonicalItemKey("bilibili", "dynamic", dyn.ID)
+ defer func() {
+ if result == nil || finalSaved {
+ return
+ }
+ // An interruption must retain already completed files and their hashes.
+ missing := []library.MissingRecord{{Item: "dynamic", Reason: "动态缓存尚未完成 (" + bilibili.KindOf(result) + ")"}}
+ meta := library.ItemMetadata{Version: 1, ID: "dynamic:" + dyn.ID, Site: "bilibili", Kind: "dynamic", Status: "partial", Title: dyn.Title, Text: dyn.Text, DynamicType: dyn.Type, TypeLabel: dyn.TypeLabel, URL: dyn.CanonicalURL, PubTs: dyn.PubTs, CachedAt: previous.CachedAt, Author: library.ItemAuthor{Mid: dyn.Author.Mid, Name: dyn.Author.Name, Face: dyn.Author.Face}, Media: mergeMediaFiles(previous.Media, mediaFiles), Videos: videoRefs, Missing: missing}
+ if _, err := m.lib.SaveItem(itemDir, meta); err != nil {
+ result = err
+ }
+ }()
+
+ // Save orig.json snapshot if this dynamic is a forward post (data-and-cache.md §2.1 & §2.3).
+ if dyn.Origin != nil {
+ origBytes, mErr := json.MarshalIndent(dyn.Origin, "", " ")
+ if mErr != nil {
+ return mErr
+ }
+ origPath := filepath.Join(itemDir, "orig.json")
+ if err := m.claimTaskFile(t, itemDir, "orig.json", origPath); err != nil {
+ return err
+ }
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if err := storage.WriteFileAtomic(origPath, origBytes, 0o600); err != nil {
+ return err
+ }
+ sum := sha256.Sum256(origBytes)
+ mediaFiles = append(mediaFiles, library.MediaFile{
+ Role: "snapshot",
+ Path: "orig.json",
+ Bytes: int64(len(origBytes)),
+ SHA256: hex.EncodeToString(sum[:]),
+ })
+ }
+
+ for idx, img := range dyn.Images {
+ ext := guessImageExt(img.URL)
+ relName := fmt.Sprintf("images/%02d%s", idx+1, ext)
+ // Existing manifests retain their registered names and location.
+ if exists {
+ for _, media := range previous.Media {
+ if media.Role == "image" && media.Source == img.URL {
+ relName = media.Path
+ break
+ }
+ }
+ }
+ fullPath := filepath.Join(itemDir, relName)
+
+ // If image already exists on disk from an earlier partial attempt, reuse it without re-downloading.
+ if mediaIsValid(previous, relName) {
+ info, statErr := os.Stat(fullPath)
+ if statErr != nil {
+ return statErr
+ }
+ m.setFileProgress(t, "image", relName, "completed", info.Size(), info.Size(), 0)
+ for _, media := range previous.Media {
+ if media.Path == relName {
+ still := media
+ motion, err := m.cacheLiveMotion(ctx, t, itemDir, previous, exists, idx, img.LiveURL, &partialErrors)
+ if err != nil {
+ return err
+ }
+ if motion != nil {
+ still.Motion = motion.Path
+ mediaFiles = append(mediaFiles, *motion)
+ }
+ mediaFiles = append(mediaFiles, still)
+ break
+ }
+ }
+ continue
+ }
+
+ m.setFileProgress(t, "image", relName, "downloading", 0, 0, 0)
+ n, sha, dlErr := m.downloadFileWithRange(ctx, []string{img.URL}, fullPath, t)
+ if dlErr != nil {
+ m.setFileProgress(t, "image", relName, "failed", 0, 0, 0)
+ if isStopError(dlErr) || isStorageError(dlErr) || ctx.Err() != nil {
+ return dlErr
+ }
+ partialErrors = append(partialErrors, fmt.Sprintf("img_%02d: %v", idx+1, dlErr))
+ continue
+ }
+ m.setFileProgress(t, "image", relName, "completed", n, n, 0)
+ still := library.MediaFile{
+ Role: "image",
+ Path: relName,
+ Bytes: n,
+ SHA256: sha,
+ Source: img.URL,
+ Width: img.Width,
+ Height: img.Height,
+ }
+ motion, err := m.cacheLiveMotion(ctx, t, itemDir, previous, exists, idx, img.LiveURL, &partialErrors)
+ if err != nil {
+ return err
+ }
+ if motion != nil {
+ still.Motion = motion.Path
+ mediaFiles = append(mediaFiles, *motion)
+ }
+ mediaFiles = append(mediaFiles, still)
+ }
+
+ for _, v := range dyn.Videos {
+ if v.BVID == "" || !t.CacheLinkedVideos {
+ continue
+ }
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ detail, err := m.client.VideoDetail(ctx, v.BVID)
+ if err != nil {
+ return err
+ }
+ for _, page := range detail.Pages {
+ if multiPart == "first" && page.Page != 1 {
+ continue
+ }
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ vidTask := Task{Site: "bilibili", Kind: "video", TargetID: v.BVID, CID: page.CID, Page: page.Page, Source: t.Source, LinkedVideo: true, ProgressOwner: t, ProgressPrefix: "videos/" + v.BVID + "/", Attempts: t.Attempts}
+ switch {
+ case detail.Author.Mid == dyn.Author.Mid:
+ case forward:
+ if dir, dirErr := library.EnsureWithinRoot(cacheRoot, filepath.Join(authorDir, "forwards", detail.BVID)); dirErr == nil {
+ vidTask.ItemDir, vidTask.ViaName, vidTask.ViaDynamicID = dir, dyn.Author.Name, dyn.ID
+ }
+ case detail.HasStaffMember(dyn.Author.Mid):
+ // A collaboration video posted by a member who is not the uploader.
+ if dir, dirErr := library.EnsureWithinRoot(cacheRoot, filepath.Join(authorDir, "videos", detail.BVID)); dirErr == nil {
+ vidTask.ItemDir = dir
+ }
+ }
+ if err := m.executeVideoTask(ctx, &vidTask); err != nil {
+ t.Attempts = vidTask.Attempts
+ if isStopError(err) || isStorageError(err) || ctx.Err() != nil {
+ return err
+ }
+ partialErrors = append(partialErrors, fmt.Sprintf("video %s P%d: %v", v.BVID, page.Page, err))
+ } else {
+ t.Attempts = vidTask.Attempts
+ }
+ if vidTask.Status == "partial" {
+ partialErrors = append(partialErrors, fmt.Sprintf("video %s P%d: 部分缓存", v.BVID, page.Page))
+ }
+ }
+ }
+
+ status := "complete"
+ var missing []library.MissingRecord
+ if dyn.Degraded {
+ status = "partial"
+ t.Status = "partial"
+ missing = append(missing, library.MissingRecord{Item: "dynamic", Reason: fmt.Sprintf("类型不支持 (%s)", dyn.TypeLabel)})
+ t.ErrorMessage = summarizeMissingReasons(missing)
+ }
+ if len(partialErrors) > 0 {
+ status = "partial"
+ t.Status = "partial"
+ for _, pe := range partialErrors {
+ missing = append(missing, library.MissingRecord{Item: "media", Reason: pe})
+ }
+ }
+
+ meta := library.ItemMetadata{
+ Version: 1,
+ ID: "dynamic:" + dyn.ID,
+ Site: "bilibili",
+ Kind: "dynamic",
+ Status: status,
+ Title: dyn.Title,
+ Text: dyn.Text,
+ DynamicType: dyn.Type,
+ TypeLabel: dyn.TypeLabel,
+ URL: dyn.CanonicalURL,
+ PubTs: dyn.PubTs,
+ CachedAt: previous.CachedAt,
+ Author: library.ItemAuthor{
+ Mid: dyn.Author.Mid,
+ Name: dyn.Author.Name,
+ Face: dyn.Author.Face,
+ },
+ Media: mediaFiles,
+ Videos: videoRefs,
+ Missing: missing,
+ }
+
+ savedMeta, saveErr := m.lib.SaveItem(itemDir, meta)
+ if saveErr != nil {
+ return saveErr
+ }
+ t.ItemKey = savedMeta.ItemKey
+ finalSaved = true
+
+ if len(partialErrors) > 0 {
+ return fmt.Errorf("部分媒体下载失败 (%s)", strings.Join(partialErrors, "; "))
+ }
+ return nil
+}
+
+// motionRelName is where the motion clip of a dynamic's idx-th live photo
+// (实况) is kept, next to its still.
+func motionRelName(idx int, rawURL string) string {
+ ext := ".mp4"
+ if u, err := url.Parse(rawURL); err == nil {
+ switch e := strings.ToLower(path.Ext(u.Path)); e {
+ case ".mp4", ".mov", ".m4v":
+ ext = e
+ }
+ }
+ return fmt.Sprintf("images/%02d_live%s", idx+1, ext)
+}
+
+// cacheLiveMotion keeps the motion clip of a live photo with its still. Clips
+// that require MP4 validation/moov relocation are downloaded to a *.stage.part
+// staging path and atomically renamed to their final name only after validation
+// passes (remote.md §6.1).
+func (m *Manager) cacheLiveMotion(ctx context.Context, t *Task, itemDir string, previous library.ItemMetadata, exists bool, idx int, liveURL string, partialErrors *[]string) (*library.MediaFile, error) {
+ if liveURL == "" {
+ return nil, nil
+ }
+ relName := motionRelName(idx, liveURL)
+ if exists {
+ for _, media := range previous.Media {
+ if media.Role == "motion" && media.Source == liveURL {
+ relName = media.Path
+ break
+ }
+ }
+ }
+ if mediaIsValid(previous, relName) {
+ for _, media := range previous.Media {
+ if media.Path == relName {
+ m.setFileProgress(t, "motion", relName, "completed", media.Bytes, media.Bytes, 0)
+ file := media
+ return &file, nil
+ }
+ }
+ }
+ fullPath, err := library.ResolveItemPath(itemDir, relName)
+ if err != nil {
+ return nil, err
+ }
+ if err := m.claimTaskFile(t, itemDir, relName, fullPath); err != nil {
+ return nil, err
+ }
+
+ needsMP4Check := strings.EqualFold(path.Ext(relName), ".mp4") || strings.EqualFold(path.Ext(relName), ".m4v")
+ if !needsMP4Check {
+ m.setFileProgress(t, "motion", relName, "downloading", 0, 0, 0)
+ n, sha, dlErr := m.downloadFileWithRange(ctx, []string{liveURL}, fullPath, t)
+ if dlErr != nil {
+ m.setFileProgress(t, "motion", relName, "failed", 0, 0, 0)
+ if isStopError(dlErr) || isStorageError(dlErr) || ctx.Err() != nil {
+ return nil, dlErr
+ }
+ *partialErrors = append(*partialErrors, fmt.Sprintf("img_%02d 实况: %v", idx+1, dlErr))
+ return nil, nil
+ }
+ m.setFileProgress(t, "motion", relName, "completed", n, n, 0)
+ return &library.MediaFile{Role: "motion", Path: relName, Bytes: n, SHA256: sha, Source: liveURL}, nil
+ }
+
+ stageRel := relName + stageSuffix
+ stagePath := fullPath + stageSuffix
+ m.setFileProgress(t, "motion", relName, "downloading", 0, 0, 0)
+ _, _, err = m.downloadFileWithRange(ctx, []string{liveURL}, stagePath, t)
+ if err != nil {
+ if ctx.Err() == nil && !fileOrPartExists(stagePath) {
+ m.removeTempTaskProgress(t, stageRel)
+ }
+ m.setFileProgress(t, "motion", relName, "failed", 0, 0, 0)
+ if isStopError(err) || isStorageError(err) || ctx.Err() != nil {
+ return nil, err
+ }
+ *partialErrors = append(*partialErrors, fmt.Sprintf("img_%02d 实况: %v", idx+1, err))
+ return nil, nil
+ }
+
+ // Keep the clip a plain progressive MP4 with moov ahead of mdat, so system
+ // players preview it too (DEC-046 ①); a fragmented or broken clip is
+ // removed while still under the temporary staging name.
+ m.setFileProgress(t, "motion", relName, "verifying", 0, 0, 0)
+ summary, vErr := EnsureSingleMP4Context(ctx, stagePath, 0)
+ if vErr != nil {
+ if ctx.Err() != nil {
+ return nil, ctx.Err()
+ }
+ _ = os.Remove(stagePath)
+ m.removeTempTaskProgress(t, stageRel)
+ m.setFileProgress(t, "motion", relName, "failed", 0, 0, 0)
+ *partialErrors = append(*partialErrors, fmt.Sprintf("img_%02d 实况: %v", idx+1, vErr))
+ return nil, nil
+ }
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ if err := os.Rename(stagePath, fullPath); err != nil {
+ return nil, err
+ }
+ m.removeTempTaskProgress(t, stageRel)
+ m.setFileProgress(t, "motion", relName, "completed", summary.FileBytes, summary.FileBytes, 0)
+ return &library.MediaFile{
+ Role: "motion",
+ Path: relName,
+ Bytes: summary.FileBytes,
+ SHA256: summary.SHA256,
+ Source: liveURL,
+ Width: summary.Width,
+ Height: summary.Height,
+ Duration: int(math.Round(summary.DurationSec)),
+ }, nil
+}
+
+func guessImageExt(rawURL string) string {
+ u, err := url.Parse(rawURL)
+ if err == nil && u.Path != "" {
+ ext := strings.ToLower(path.Ext(u.Path))
+ switch ext {
+ case ".jpg", ".jpeg", ".png", ".webp", ".gif", ".avif":
+ return ext
+ }
+ }
+ return ".jpg"
+}
+
+func dedupeDynamicImages(in []bilibili.DynamicMedia) []bilibili.DynamicMedia {
+ seen := make(map[string]bool, len(in))
+ out := in[:0:0]
+ for _, img := range in {
+ if img.URL != "" && seen[img.URL] {
+ continue
+ }
+ seen[img.URL] = true
+ out = append(out, img)
+ }
+ return out
+}
+
+func dedupeDynamicVideos(in []bilibili.DynamicVideoRef) []bilibili.DynamicVideoRef {
+ seen := make(map[string]bool, len(in))
+ out := in[:0:0]
+ for _, v := range in {
+ if v.BVID != "" && seen[v.BVID] {
+ continue
+ }
+ seen[v.BVID] = true
+ out = append(out, v)
+ }
+ return out
+}
diff --git a/internal/download/fixes_regression_test.go b/internal/download/fixes_regression_test.go
new file mode 100644
index 0000000..50ac475
--- /dev/null
+++ b/internal/download/fixes_regression_test.go
@@ -0,0 +1,800 @@
+package download
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "math"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/Eyevinn/mp4ff/mp4"
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/site"
+ "github.com/chialecode/trace/internal/site/bilibili"
+)
+
+// Live-photo motion clips must stay under a temporary *.part name until
+// EnsureSingleMP4Context succeeds; a broken clip must never appear as final
+// images/01_live.mp4 on disk, and a valid trailing-moov clip is relocated
+// before atomic rename.
+func TestLivePhotoMotionStagedBeforeFinalRename(t *testing.T) {
+ validTrailingMoov := buildProgressiveWithoutElst(t, true, false, 0)
+ jpegBytes := append([]byte{0xFF, 0xD8, 0xFF, 0xE0}, bytes.Repeat([]byte("j"), 256)...)
+
+ var serveBroken atomic.Bool
+ var srvURL string
+ mux := http.NewServeMux()
+ mux.HandleFunc("/x/polymer/web-dynamic/v1/detail", func(w http.ResponseWriter, r *http.Request) {
+ id := r.URL.Query().Get("id")
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": 0,
+ "data": map[string]any{
+ "item": map[string]any{
+ "id_str": id,
+ "type": "DYNAMIC_TYPE_DRAW",
+ "modules": map[string]any{
+ "module_author": map[string]any{"mid": 777, "name": "LivePhotoAuthor", "pub_ts": 1700000001},
+ "module_dynamic": map[string]any{
+ "desc": map[string]any{"text": "实况动态测试"},
+ "major": map[string]any{
+ "type": "MAJOR_TYPE_OPUS",
+ "opus": map[string]any{
+ "title": "实况动态",
+ "pics": []map[string]any{
+ {"url": srvURL + "/media/pic.jpg", "live_url": srvURL + "/media/clip.mp4", "width": 16, "height": 16},
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ })
+ })
+ mux.HandleFunc("/media/pic.jpg", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "image/jpeg")
+ w.Header().Set("Content-Length", strconv.Itoa(len(jpegBytes)))
+ _, _ = w.Write(jpegBytes)
+ })
+ mux.HandleFunc("/media/clip.mp4", func(w http.ResponseWriter, r *http.Request) {
+ body := validTrailingMoov
+ if serveBroken.Load() {
+ body = []byte("not-a-valid-mp4-motion-clip")
+ }
+ w.Header().Set("Content-Type", "video/mp4")
+ w.Header().Set("Content-Length", strconv.Itoa(len(body)))
+ _, _ = w.Write(body)
+ })
+
+ mgr, lib, srv := setupDownloadEnv(t, mux, 1)
+ srvURL = srv.URL
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ if err := mgr.Start(ctx); err != nil {
+ t.Fatal(err)
+ }
+ defer mgr.Stop()
+
+ // 1. Broken motion clip must never materialize as final images/01_live.mp4.
+ serveBroken.Store(true)
+ checkNames := watchNames(t, lib.CacheDir())
+ tBroken, err := mgr.EnqueueDynamic(ctx, DynamicEnqueueRequest{DynamicID: "900000001"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ waitForTaskStatus(t, mgr, tBroken.TaskID, "partial", 5*time.Second)
+ checkNames()
+ if meta, ok, err := lib.GetItem("dynamic:900000001"); err != nil || !ok {
+ t.Fatalf("GetItem broken dynamic: ok=%v err=%v", ok, err)
+ } else if _, statErr := os.Stat(filepath.Join(meta.ItemDir, "images", "01_live.mp4")); !os.IsNotExist(statErr) {
+ t.Fatalf("broken motion clip left final file on disk: %v", statErr)
+ }
+
+ // 2. Valid trailing-moov motion clip is validated/relocated before final rename.
+ serveBroken.Store(false)
+ checkValidNames := watchNames(t, lib.CacheDir())
+ tOK, err := mgr.EnqueueDynamic(ctx, DynamicEnqueueRequest{DynamicID: "900000002"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ waitForTaskStatus(t, mgr, tOK.TaskID, "completed", 5*time.Second)
+ checkValidNames()
+ meta, ok, err := lib.GetItem("dynamic:900000002")
+ if err != nil || !ok || meta.Status != "complete" {
+ t.Fatalf("expected complete live-photo dynamic, got ok=%v err=%v meta=%+v", ok, err, meta)
+ }
+ summary, err := InspectMP4File(filepath.Join(meta.ItemDir, "images", "01_live.mp4"))
+ if err != nil || !summary.MoovBeforeMdat {
+ t.Fatalf("expected relocated moov-before-mdat motion clip, got summary=%+v err=%v", summary, err)
+ }
+}
+
+// When Douyin OriginalURLs exhausts its 5 network retries and falls back to
+// VideoURLs, Task.Status must NOT be poisoned to "paused" in SQLite; the task
+// must finish as "completed" and deliver the completion notification.
+func TestOriginalURLsNetworkFailureDoesNotPoisonTaskStatus(t *testing.T) {
+ videoBytes := buildProgressiveWithoutElst(t, true, false, 0)
+ var origHits atomic.Int32
+ mux := http.NewServeMux()
+ mux.HandleFunc("/cdn/orig-500.mp4", func(w http.ResponseWriter, r *http.Request) {
+ origHits.Add(1)
+ w.WriteHeader(http.StatusInternalServerError)
+ })
+ mux.HandleFunc("/cdn/transcoded.mp4", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "video/mp4")
+ w.Header().Set("Content-Length", strconv.Itoa(len(videoBytes)))
+ _, _ = w.Write(videoBytes)
+ })
+
+ mgr, lib, srv := setupDownloadEnv(t, mux, 1)
+ var notifyMu sync.Mutex
+ var statuses []string
+ mgr.onTaskUpdate = func(tk Task) {
+ notifyMu.Lock()
+ statuses = append(statuses, tk.Status)
+ notifyMu.Unlock()
+ }
+
+ const (
+ secUID = "MS4wLjABAAAA_orig_net_fallback_0001"
+ awemeID = "7399000000000000101"
+ )
+ transport := site.DouyinVODTransport("Mozilla/5.0 Test", true)
+ planner := newFakeDouyinWorkPlanner()
+ planner.setPlan(awemeID, func(_ int) (WorkDownloadPlan, error) {
+ return WorkDownloadPlan{
+ Site: site.Douyin,
+ Kind: "video",
+ TargetID: awemeID,
+ Title: "原画网络失败回退测试",
+ DurationSec: 2,
+ AuthorUID: secUID,
+ AuthorName: "测试创作者",
+ OriginalURLs: []string{srv.URL + "/cdn/orig-500.mp4?sign=secret_orig"},
+ VideoURLs: []string{srv.URL + "/cdn/transcoded.mp4?sign=secret_vid"},
+ VideoGear: "normal_1080_0",
+ QualityName: "1080P",
+ Codec: "avc",
+ Transport: transport,
+ }, nil
+ })
+ mgr.RegisterWorkPlanner(planner)
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ if err := mgr.Start(ctx); err != nil {
+ t.Fatal(err)
+ }
+ defer mgr.Stop()
+
+ task, err := mgr.EnqueueDouyinWork(ctx, DouyinWorkEnqueueRequest{AwemeID: awemeID})
+ if err != nil {
+ t.Fatal(err)
+ }
+ done := waitForTaskStatus(t, mgr, task.TaskID, "completed", 8*time.Second)
+ if origHits.Load() < 5 {
+ t.Fatalf("expected OriginalURLs to exhaust 5 retries, got %d hits", origHits.Load())
+ }
+ if done.PauseReason != "" || done.ErrorKind != "" {
+ t.Fatalf("completed task kept stale pause/error fields: %+v", done)
+ }
+ meta, ok, err := lib.GetItem("douyin:video:" + awemeID)
+ if err != nil || !ok || meta.Status != "complete" {
+ t.Fatalf("expected complete library item, got ok=%v err=%v meta=%+v", ok, err, meta)
+ }
+ notifyMu.Lock()
+ sawCompleted := false
+ for _, st := range statuses {
+ if st == "completed" {
+ sawCompleted = true
+ }
+ }
+ notifyMu.Unlock()
+ if !sawCompleted {
+ t.Fatalf("onTaskUpdate never received completed status: %v", statuses)
+ }
+}
+
+// When a 403 media stream refreshes PlayURL and receives -101 (AuthRequired),
+// downloadStreamWithRefresh must propagate ErrKindAuthRequired (not the stale
+// 403), pause both the triggering task and other running/queued same-site
+// tasks, and emit onTaskUpdate for the paused sibling tasks.
+func TestDownloadStreamRefreshPropagatesAuthRequiredAndPausesConcurrentSiteTasks(t *testing.T) {
+ var playHits atomic.Int32
+ var srvURL string
+ siblingStarted := make(chan struct{})
+ siblingRelease := make(chan struct{})
+ var siblingOnce sync.Once
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/x/web-interface/wbi/view", func(w http.ResponseWriter, r *http.Request) {
+ bvid := r.URL.Query().Get("bvid")
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": 0,
+ "data": map[string]any{
+ "bvid": bvid, "aid": 200, "title": "Auth " + bvid,
+ "owner": map[string]any{"mid": 200, "name": "UP"},
+ "pages": []map[string]any{{"cid": 2001, "page": 1, "part": "P1", "duration": 1}},
+ },
+ })
+ })
+ mux.HandleFunc("/x/player/wbi/playurl", func(w http.ResponseWriter, r *http.Request) {
+ bvid := r.URL.Query().Get("bvid")
+ if bvid == "BV1authSib01" {
+ _ = 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": 1,
+ "video": []map[string]any{{"id": 80, "baseUrl": srvURL + "/media/sibling.m4s", "codecid": 7, "codecs": "avc1"}},
+ },
+ },
+ })
+ return
+ }
+ if playHits.Add(1) >= 2 {
+ _ = json.NewEncoder(w).Encode(map[string]any{"code": -101, "message": "账号未登录"})
+ return
+ }
+ _ = 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": 1,
+ "video": []map[string]any{{"id": 80, "baseUrl": srvURL + "/media/expired.m4s?sign=secret_tok", "codecid": 7, "codecs": "avc1"}},
+ },
+ },
+ })
+ })
+ mux.HandleFunc("/media/sibling.m4s", func(w http.ResponseWriter, r *http.Request) {
+ siblingOnce.Do(func() { close(siblingStarted) })
+ w.Header().Set("Content-Range", "bytes 0-1023/1024")
+ w.Header().Set("Content-Length", "1024")
+ w.WriteHeader(http.StatusPartialContent)
+ _, _ = w.Write([]byte("0123456789abcdef"))
+ if fl, ok := w.(http.Flusher); ok {
+ fl.Flush()
+ }
+ select {
+ case <-r.Context().Done():
+ case <-siblingRelease:
+ }
+ })
+ mux.HandleFunc("/media/expired.m4s", func(w http.ResponseWriter, r *http.Request) {
+ // Wait until sibling worker is also actively running so we verify running-sibling cancellation.
+ select {
+ case <-siblingStarted:
+ case <-time.After(3 * time.Second):
+ }
+ w.WriteHeader(http.StatusForbidden)
+ })
+
+ mgr, _, srv := setupDownloadEnv(t, mux, 2)
+ srvURL = srv.URL
+ cfg := mgr.dlSettings
+ cfg.SaveCover, cfg.SaveDanmaku, cfg.SaveSubtitles = false, false, false
+ mgr.UpdateSettings(cfg)
+
+ var notifyMu sync.Mutex
+ pausedEvents := make(map[string]string)
+ mgr.onTaskUpdate = func(tk Task) {
+ if tk.Status == "paused" {
+ notifyMu.Lock()
+ pausedEvents[tk.TaskID] = tk.PauseReason
+ notifyMu.Unlock()
+ }
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ defer close(siblingRelease)
+ if err := mgr.Start(ctx); err != nil {
+ t.Fatal(err)
+ }
+ defer mgr.Stop()
+
+ detail := func(bvid string) *bilibili.VideoDetail {
+ return &bilibili.VideoDetail{
+ BVID: bvid, Title: "Auth " + bvid,
+ Author: bilibili.AuthorInfo{Mid: 200, Name: "UP"},
+ Pages: []bilibili.VideoPage{{CID: 2001, Page: 1, Title: "P1", Duration: 1}},
+ }
+ }
+ t1, err := mgr.EnqueueVideo(ctx, VideoEnqueueRequest{BVID: "BV1authSib01", Detail: detail("BV1authSib01")})
+ if err != nil {
+ t.Fatal(err)
+ }
+ t2, err := mgr.EnqueueVideo(ctx, VideoEnqueueRequest{BVID: "BV1authExp02", Detail: detail("BV1authExp02")})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ done2 := waitForTaskStatus(t, mgr, t2[0].TaskID, "paused", 6*time.Second)
+ if done2.PauseReason != "auth_required" || done2.ErrorKind != site.ErrKindAuthRequired {
+ t.Fatalf("expected triggering task paused(auth_required), got %+v", done2)
+ }
+ done1 := waitForTaskStatus(t, mgr, t1[0].TaskID, "paused", 6*time.Second)
+ if done1.PauseReason != "auth_required" {
+ t.Fatalf("expected concurrent running sibling task paused(auth_required), got %+v", done1)
+ }
+ notifyMu.Lock()
+ defer notifyMu.Unlock()
+ if pausedEvents[t1[0].TaskID] != "auth_required" || pausedEvents[t2[0].TaskID] != "auth_required" {
+ t.Fatalf("expected onTaskUpdate paused(auth_required) for both tasks, got %+v", pausedEvents)
+ }
+}
+
+// Douyin note tasks must: (a) stop immediately on 412 risk control during cover
+// download, (b) mark the item partial when cover fails with a non-stop error,
+// and (c) share one PlanWorkDownload refresh across all expired pages in a note.
+func TestDouyinNoteCoverErrorsNotSwallowedAndSharedPlanRefresh(t *testing.T) {
+ jpgBytes := append([]byte{0xFF, 0xD8, 0xFF, 0xE0}, bytes.Repeat([]byte("j"), 128)...)
+ var pageHitsAfterRisk atomic.Int32
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/cdn/cover-412.jpg", func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusPreconditionFailed)
+ })
+ mux.HandleFunc("/cdn/cover-404.jpg", func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusNotFound)
+ })
+ mux.HandleFunc("/cdn/risk-page.jpg", func(w http.ResponseWriter, r *http.Request) {
+ pageHitsAfterRisk.Add(1)
+ w.Header().Set("Content-Type", "image/jpeg")
+ w.Header().Set("Content-Length", strconv.Itoa(len(jpgBytes)))
+ _, _ = w.Write(jpgBytes)
+ })
+ mux.HandleFunc("/cdn/expired/", func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusForbidden)
+ })
+ mux.HandleFunc("/cdn/fresh/", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "image/jpeg")
+ w.Header().Set("Content-Length", strconv.Itoa(len(jpgBytes)))
+ _, _ = w.Write(jpgBytes)
+ })
+
+ mgr, lib, srv := setupDownloadEnv(t, mux, 1)
+ transport := site.DouyinVODTransport("Mozilla/5.0 Test", true)
+ const secUID = "MS4wLjABAAAA_note_cover_refresh_001"
+ planner := newFakeDouyinWorkPlanner()
+
+ // Case A: Cover 412 stops immediately without fetching page 1.
+ const noteRisk = "7399000000000000201"
+ planner.setPlan(noteRisk, func(_ int) (WorkDownloadPlan, error) {
+ return WorkDownloadPlan{
+ Site: site.Douyin, Kind: "dynamic", TargetID: noteRisk, Title: "封面风控图文",
+ AuthorUID: secUID, AuthorName: "创作者",
+ CoverURLs: []string{srv.URL + "/cdn/cover-412.jpg"},
+ Pages: []PlannedNotePage{{Index: 1, Kind: "image", ImageURLs: []string{srv.URL + "/cdn/risk-page.jpg"}}},
+ Transport: transport,
+ }, nil
+ })
+
+ // Case B: Cover 404 records missing cover -> item is partial (not falsely complete).
+ const noteMissingCover = "7399000000000000202"
+ planner.setPlan(noteMissingCover, func(_ int) (WorkDownloadPlan, error) {
+ return WorkDownloadPlan{
+ Site: site.Douyin, Kind: "dynamic", TargetID: noteMissingCover, Title: "封面缺失图文",
+ AuthorUID: secUID, AuthorName: "创作者",
+ CoverURLs: []string{srv.URL + "/cdn/cover-404.jpg"},
+ Pages: []PlannedNotePage{{Index: 1, Kind: "image", ImageURLs: []string{srv.URL + "/cdn/fresh/p1.jpg"}}},
+ Transport: transport,
+ }, nil
+ })
+
+ // Case C: 3-page note with expired URLs calls PlanWorkDownload at most once on refresh.
+ const noteSharedRefresh = "7399000000000000203"
+ planner.setPlan(noteSharedRefresh, func(call int) (WorkDownloadPlan, error) {
+ prefix := "/cdn/expired/"
+ if call >= 2 {
+ prefix = "/cdn/fresh/"
+ }
+ return WorkDownloadPlan{
+ Site: site.Douyin, Kind: "dynamic", TargetID: noteSharedRefresh, Title: "共享刷新三图",
+ AuthorUID: secUID, AuthorName: "创作者",
+ Pages: []PlannedNotePage{
+ {Index: 1, Kind: "image", ImageURLs: []string{srv.URL + prefix + "1.jpg"}},
+ {Index: 2, Kind: "image", ImageURLs: []string{srv.URL + prefix + "2.jpg"}},
+ {Index: 3, Kind: "image", ImageURLs: []string{srv.URL + prefix + "3.jpg"}},
+ },
+ Transport: transport,
+ }, nil
+ })
+ mgr.RegisterWorkPlanner(planner)
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ if err := mgr.Start(ctx); err != nil {
+ t.Fatal(err)
+ }
+ defer mgr.Stop()
+
+ // Run Case A.
+ tRisk, err := mgr.EnqueueDouyinWork(ctx, DouyinWorkEnqueueRequest{AwemeID: noteRisk})
+ if err != nil {
+ t.Fatal(err)
+ }
+ stRisk := waitForTaskStatus(t, mgr, tRisk.TaskID, "paused", 5*time.Second)
+ if stRisk.PauseReason != "risk_control" || pageHitsAfterRisk.Load() != 0 {
+ t.Fatalf("cover 412 did not stop note immediately: status=%+v pageHits=%d", stRisk, pageHitsAfterRisk.Load())
+ }
+
+ // Run Case B.
+ tCov, err := mgr.EnqueueDouyinWork(ctx, DouyinWorkEnqueueRequest{AwemeID: noteMissingCover})
+ if err != nil {
+ t.Fatal(err)
+ }
+ waitForTaskStatus(t, mgr, tCov.TaskID, "partial", 5*time.Second)
+ metaCov, ok, err := lib.GetItem("douyin:dynamic:" + noteMissingCover)
+ if err != nil || !ok || metaCov.Status != "partial" {
+ t.Fatalf("expected partial item when cover missing, got ok=%v err=%v meta=%+v", ok, err, metaCov)
+ }
+ hasCoverMissing := false
+ for _, m := range metaCov.Missing {
+ if m.Item == "cover" {
+ hasCoverMissing = true
+ }
+ }
+ if !hasCoverMissing {
+ t.Fatalf("expected missing cover record, got %+v", metaCov.Missing)
+ }
+
+ // Run Case C.
+ tRef, err := mgr.EnqueueDouyinWork(ctx, DouyinWorkEnqueueRequest{AwemeID: noteSharedRefresh})
+ if err != nil {
+ t.Fatal(err)
+ }
+ waitForTaskStatus(t, mgr, tRef.TaskID, "completed", 5*time.Second)
+ if got := planner.callCount(noteSharedRefresh); got != 2 {
+ t.Fatalf("expected 1 enqueue + 1 shared refresh (total 2 calls), got %d", got)
+ }
+}
+
+// lockItem must honor context cancellation while waiting and evict keys once
+// all waiters/holders release so the lock map never grows unbounded.
+func TestLockItemIsContextCancellableAndEvictsUnusedKeys(t *testing.T) {
+ mgr, _, _ := setupDownloadEnv(t, http.NewServeMux(), 1)
+
+ unlock1, err := mgr.lockItem(context.Background(), "BV1lock0001")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ cancelCtx, cancel := context.WithCancel(context.Background())
+ errCh := make(chan error, 1)
+ go func() {
+ _, lErr := mgr.lockItem(cancelCtx, "BV1lock0001")
+ errCh <- lErr
+ }()
+ time.Sleep(20 * time.Millisecond)
+ cancel()
+
+ select {
+ case gotErr := <-errCh:
+ if !errors.Is(gotErr, context.Canceled) {
+ t.Fatalf("expected context.Canceled, got %v", gotErr)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("lockItem did not unblock on context cancellation")
+ }
+
+ unlock1()
+
+ mgr.itemLockMu.Lock()
+ remaining := len(mgr.itemLocks)
+ mgr.itemLockMu.Unlock()
+ if remaining != 0 {
+ t.Fatalf("expected itemLocks map to be empty after unlock, got %d entries", remaining)
+ }
+}
+
+// ensureTrackElst must select elst Version 1 for 64-bit values without 32-bit
+// truncation and must never overwrite an existing non-trivial edit list.
+func TestEnsureTrackElstVersion1AndPreservesExistingElst(t *testing.T) {
+ moov := &mp4.MoovBox{Mvhd: &mp4.MvhdBox{Timescale: 1000}}
+ trak := &mp4.TrakBox{
+ Tkhd: &mp4.TkhdBox{TrackID: 1},
+ Mdia: &mp4.MdiaBox{Mdhd: &mp4.MdhdBox{Timescale: 90000}},
+ }
+ trak.Children = []mp4.Box{trak.Tkhd, trak.Mdia}
+
+ largeMediaTime := int64(math.MaxInt32) + 5000
+ largeDur := uint64(math.MaxUint32) * 100
+ if !ensureTrackElst(moov, trak, largeDur, largeMediaTime) {
+ t.Fatal("expected ensureTrackElst to synthesize elst on track without one")
+ }
+ if trak.Edts == nil || len(trak.Edts.Elst) != 1 {
+ t.Fatalf("expected 1 elst box, got %+v", trak.Edts)
+ }
+ elst := trak.Edts.Elst[0]
+ if elst.Version != 1 {
+ t.Fatalf("expected elst Version 1 for >32-bit values, got %d", elst.Version)
+ }
+ if elst.Entries[0].MediaTime != largeMediaTime {
+ t.Fatalf("MediaTime = %d, want %d", elst.Entries[0].MediaTime, largeMediaTime)
+ }
+ if elst.Entries[0].SegmentDuration <= math.MaxUint32 {
+ t.Fatalf("SegmentDuration truncated to %d", elst.Entries[0].SegmentDuration)
+ }
+
+ // Calling again on a track that already has an elst must NOT clobber MediaTime.
+ if ensureTrackElst(moov, trak, 90000, 12345) {
+ t.Fatal("expected ensureTrackElst to return false when elst already exists")
+ }
+ if elst.Entries[0].MediaTime != largeMediaTime {
+ t.Fatalf("existing MediaTime was clobbered: got %d, want %d", elst.Entries[0].MediaTime, largeMediaTime)
+ }
+}
+
+// cleanTaskPartFiles must delete owned temporary staging files (.trace-*.m4s,
+// *.stage.part) even if they reached "completed" before cancel/failure, while
+// never deleting completed final outputs.
+func TestCleanTaskPartFilesRemovesCompletedTempStagingOnly(t *testing.T) {
+ dir := t.TempDir()
+ tempStream := filepath.Join(dir, ".trace-P01.video-80-7.m4s")
+ finalMP4 := filepath.Join(dir, "P01.mp4")
+ if err := os.WriteFile(tempStream, []byte("temp-m4s"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(finalMP4, []byte("final-mp4"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ cleanTaskPartFiles(Task{
+ ItemDir: dir,
+ Files: []TaskFileProgress{
+ {Owned: true, Role: "video_stream", Path: ".trace-P01.video-80-7.m4s", Status: "completed"},
+ {Owned: true, Role: "video", Path: "P01.mp4", Status: "completed"},
+ },
+ })
+
+ if _, err := os.Stat(tempStream); !os.IsNotExist(err) {
+ t.Fatalf("expected completed temp staging stream to be removed, stat err=%v", err)
+ }
+ if _, err := os.Stat(finalMP4); err != nil {
+ t.Fatalf("completed final output should not be removed: %v", err)
+ }
+}
+
+// PauseForSite and PauseAll must emit onTaskUpdate notifications for every
+// affected task so service/UI listeners observe the state change.
+func TestPauseForSiteAndPauseAllEmitTaskUpdates(t *testing.T) {
+ mgr, _, _ := setupDownloadEnv(t, http.NewServeMux(), 1)
+ var mu sync.Mutex
+ seen := make(map[string]Task)
+ mgr.onTaskUpdate = func(tk Task) {
+ mu.Lock()
+ seen[tk.TaskID] = tk
+ mu.Unlock()
+ }
+
+ bTask, err := mgr.enqueueSingleTask(Task{Site: "bilibili", Kind: "video", TargetID: "BV1emit0001", Page: 1})
+ if err != nil {
+ t.Fatal(err)
+ }
+ dTask, err := mgr.enqueueSingleTask(Task{Site: "douyin", Kind: "video", TargetID: "7399000000000000301", Page: 1})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ mgr.PauseForSite(site.Bilibili, "auth_required", "已暂停")
+ mu.Lock()
+ bEvt, bOK := seen[bTask.TaskID]
+ _, dOK := seen[dTask.TaskID]
+ mu.Unlock()
+ if !bOK || bEvt.Status != "paused" {
+ t.Fatalf("expected PauseForSite to emit paused update for bilibili task, got ok=%v task=%+v", bOK, bEvt)
+ }
+ if dOK {
+ t.Fatalf("PauseForSite(bilibili) should not emit pause for douyin task")
+ }
+
+ mgr.PauseAll("user", "全部暂停")
+ mu.Lock()
+ dEvt, dOK := seen[dTask.TaskID]
+ mu.Unlock()
+ if !dOK || dEvt.Status != "paused" {
+ t.Fatalf("expected PauseAll to emit paused update for douyin task, got ok=%v task=%+v", dOK, dEvt)
+ }
+}
+
+// Signed CDN query strings must be stripped from SiteError.Endpoint, and
+// sniffAudioExtension must reject unknown binary/error payloads instead of
+// blindly defaulting to .m4a.
+func TestSanitizeMediaEndpointAndRejectUnknownAudio(t *testing.T) {
+ rawURL := "https://cdn.example.com/media/clip.m4s?sign=super_secret_token&expires=1999999999"
+ se := mapMediaHTTPStatus(site.Bilibili, http.StatusForbidden, rawURL)
+ if strings.Contains(se.Endpoint, "super_secret_token") || strings.Contains(se.Endpoint, "?") {
+ t.Fatalf("SiteError.Endpoint leaked signed query: %q", se.Endpoint)
+ }
+ if se.Endpoint != "https://cdn.example.com/media/clip.m4s" {
+ t.Fatalf("unexpected sanitized endpoint: %q", se.Endpoint)
+ }
+
+ badPath := filepath.Join(t.TempDir(), "unknown.bin")
+ if err := os.WriteFile(badPath, []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if ext, err := sniffAudioExtension(badPath, "application/octet-stream"); err == nil {
+ t.Fatalf("expected unknown binary audio payload to be rejected, got ext=%q", ext)
+ }
+}
+
+// In remote allow-moved-files mode, an already-completed cover moved away
+// between multi-part downloads must not be re-downloaded on P2.
+func TestMovedCoverNotRedownloadedWhenAllowMovedFilesEnabled(t *testing.T) {
+ var coverHits atomic.Int32
+ jpegBytes := append([]byte{0xFF, 0xD8, 0xFF, 0xE0}, bytes.Repeat([]byte("c"), 128)...)
+ mux := http.NewServeMux()
+ mux.HandleFunc("/media/cover.jpg", func(w http.ResponseWriter, r *http.Request) {
+ coverHits.Add(1)
+ w.Header().Set("Content-Type", "image/jpeg")
+ w.Header().Set("Content-Length", strconv.Itoa(len(jpegBytes)))
+ _, _ = w.Write(jpegBytes)
+ })
+
+ mgr, lib, srv := setupDownloadEnv(t, mux, 1)
+ lib.SetAllowMovedFiles(true)
+
+ itemDir := filepath.Join(lib.CacheDir(), "bilibili", "999", "videos", "BV1CovMv001")
+ if err := os.MkdirAll(itemDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ meta := library.ItemMetadata{
+ Version: 1, Site: "bilibili", Kind: "video", ID: "video:BV1CovMv001",
+ Status: "partial", Title: "Moved Cover", ItemDir: itemDir,
+ Author: library.ItemAuthor{Mid: 999, Name: "UP"},
+ }
+ cfg := mgr.dlSettings
+ cfg.SaveCover = true
+ task := Task{TaskID: "t-cov", Site: "bilibili", Kind: "video", TargetID: "BV1CovMv001", ItemDir: itemDir, Status: "running"}
+
+ // P1 downloads cover.jpg once.
+ if err := mgr.saveVideoCover(context.Background(), &task, &meta, srv.URL+"/media/cover.jpg", cfg); err != nil {
+ t.Fatalf("P1 saveVideoCover: %v", err)
+ }
+ if coverHits.Load() != 1 {
+ t.Fatalf("coverHits after P1 = %d, want 1", coverHits.Load())
+ }
+
+ // Simulate remote rclone move removing cover.jpg from local disk.
+ if err := os.Remove(filepath.Join(itemDir, "cover.jpg")); err != nil {
+ t.Fatal(err)
+ }
+
+ // P2 must recognize cover.jpg was already completed and moved away.
+ if err := mgr.saveVideoCover(context.Background(), &task, &meta, srv.URL+"/media/cover.jpg", cfg); err != nil {
+ t.Fatalf("P2 saveVideoCover: %v", err)
+ }
+ if coverHits.Load() != 1 {
+ t.Fatalf("moved cover was re-downloaded on P2: hits=%d, want 1", coverHits.Load())
+ }
+}
+
+// Verify that oversized image responses are rejected before creating a .part file.
+func TestOversizedImageRejectedBeforeCreatingPartFile(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("/media/huge.jpg", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "image/jpeg")
+ w.Header().Set("Content-Range", fmt.Sprintf("bytes 0-1023/%d", MaxImageFileBytes+1024))
+ w.Header().Set("Content-Length", "1024")
+ w.WriteHeader(http.StatusPartialContent)
+ _, _ = w.Write(bytes.Repeat([]byte("x"), 1024))
+ })
+
+ mgr, _, srv := setupDownloadEnv(t, mux, 1)
+ dir := t.TempDir()
+ dest := filepath.Join(dir, "huge.jpg")
+ task := Task{
+ TaskID: "t-huge",
+ ItemDir: dir,
+ Files: []TaskFileProgress{{Owned: true, Role: "image", Path: "huge.jpg", Status: "downloading"}},
+ }
+ _, _, err := mgr.downloadFileWithRange(context.Background(), []string{srv.URL + "/media/huge.jpg"}, dest, &task)
+ if !site.IsKind(err, site.ErrKindSchemaChanged) {
+ t.Fatalf("expected schema_changed for >50MiB image, got %v", err)
+ }
+ if _, statErr := os.Stat(dest + ".part"); !os.IsNotExist(statErr) {
+ t.Fatalf("expected no .part file created for oversized image, stat err=%v", statErr)
+ }
+}
+
+// executeUpgradeTask must propagate network pause exhaustion as paused(network)
+// (not failed) and preserve child attempt records on the parent task.
+func TestUpgradeNetworkExhaustionPausesAndRecordsAttempts(t *testing.T) {
+ var srvURL string
+ mux := http.NewServeMux()
+ mux.HandleFunc("/x/web-interface/wbi/view", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": 0,
+ "data": map[string]any{
+ "bvid": "BV1upgNet001", "aid": 300, "title": "Upgrade Net Pause",
+ "owner": map[string]any{"mid": 300, "name": "UP"},
+ "pages": []map[string]any{{"cid": 3001, "page": 1, "part": "P1", "duration": 1}},
+ },
+ })
+ })
+ mux.HandleFunc("/x/player/wbi/playurl", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": 0,
+ "data": map[string]any{
+ "quality": 112, "accept_format": "dash", "accept_quality": []int{112, 80},
+ "dash": map[string]any{
+ "duration": 1,
+ "video": []map[string]any{{"id": 112, "baseUrl": srvURL + "/media/always500.m4s", "codecid": 7, "codecs": "avc1"}},
+ },
+ },
+ })
+ })
+ mux.HandleFunc("/media/always500.m4s", func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusInternalServerError)
+ })
+
+ mgr, lib, srv := setupDownloadEnv(t, mux, 1)
+ srvURL = srv.URL
+ cfg := mgr.dlSettings
+ cfg.SaveCover, cfg.SaveDanmaku, cfg.SaveSubtitles = false, false, false
+ mgr.UpdateSettings(cfg)
+
+ itemDir := filepath.Join(lib.CacheDir(), "bilibili", "300", "videos", "BV1upgNet001")
+ if err := os.MkdirAll(itemDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ vBytes, err := BuildSyntheticVideoM4S(30, 30)
+ if err != nil {
+ t.Fatal(err)
+ }
+ p1Path := filepath.Join(itemDir, "P01.mp4")
+ sum, err := DefragmentFMP4Bytes(vBytes, p1Path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := lib.SaveItem(itemDir, library.ItemMetadata{
+ Version: 1, Site: "bilibili", Kind: "video", ID: "video:BV1upgNet001", Status: "complete",
+ Title: "Upgrade Net Pause", ItemDir: itemDir, Author: library.ItemAuthor{Mid: 300, Name: "UP"},
+ ExpectedPages: []int{1},
+ Media: []library.MediaFile{{Role: "video", Path: "P01.mp4", Bytes: sum.FileBytes, SHA256: sum.SHA256}},
+ Parts: []library.VideoPartRecord{{CID: 3001, Page: 1, File: "P01.mp4", Video: library.PartVideoInfo{Quality: 80}}},
+ }); err != nil {
+ t.Fatal(err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ if err := mgr.Start(ctx); err != nil {
+ t.Fatal(err)
+ }
+ defer mgr.Stop()
+
+ upgTask, err := mgr.Upgrade(ctx, "BV1upgNet001")
+ if err != nil {
+ t.Fatal(err)
+ }
+ paused := waitForTaskStatus(t, mgr, upgTask.TaskID, "paused", 6*time.Second)
+ if paused.PauseReason != "network" {
+ t.Fatalf("expected upgrade task paused(network), got %+v", paused)
+ }
+ if len(paused.Attempts) < 5 {
+ t.Fatalf("expected child retry attempts propagated to parent task, got %d", len(paused.Attempts))
+ }
+ var dbAttempts int
+ if err := mgr.db.QueryRow(`SELECT COUNT(*) FROM task_attempts WHERE task_id = ?`, upgTask.TaskID).Scan(&dbAttempts); err != nil {
+ t.Fatal(err)
+ }
+ if dbAttempts < 5 {
+ t.Fatalf("expected >=5 rows in task_attempts for parent upgrade task, got %d", dbAttempts)
+ }
+}
diff --git a/internal/download/manager.go b/internal/download/manager.go
index 9893efc..c5b3684 100644
--- a/internal/download/manager.go
+++ b/internal/download/manager.go
@@ -2,19 +2,10 @@ package download
import (
"context"
- "crypto/rand"
- "crypto/sha256"
"database/sql"
- "encoding/hex"
- "encoding/json"
"errors"
"fmt"
- "io"
- jitterrand "math/rand/v2"
"net/http"
- "net/url"
- "os"
- "path"
"path/filepath"
"strconv"
"strings"
@@ -25,7 +16,6 @@ import (
"github.com/chialecode/trace/internal/settings"
"github.com/chialecode/trace/internal/site"
"github.com/chialecode/trace/internal/site/bilibili"
- "github.com/chialecode/trace/internal/storage"
)
// DefaultRangeChunkSize is the 8 MiB closed-interval segment size required by data-and-cache.md §2.4.
@@ -67,41 +57,46 @@ type TaskDetail struct {
// Task represents a persistent download/cache task stored in SQLite.
type Task struct {
- TaskID string `json:"taskId"`
- Site string `json:"site"`
- Kind string `json:"kind"` // "video", "dynamic", "supplement", "upgrade"
- Source string `json:"source,omitempty"` // "manual" or "auto"
- TargetID string `json:"targetId"`
- CID int64 `json:"cid,omitempty"`
- Page int `json:"page,omitempty"`
- Title string `json:"title"`
- PartTitle string `json:"partTitle,omitempty"`
- Mid int64 `json:"mid,omitempty"`
- AuthorUID string `json:"authorUid,omitempty"`
- AuthorName string `json:"authorName,omitempty"`
- AuthorFace string `json:"authorFace,omitempty"`
- CoverURL string `json:"coverUrl,omitempty"`
- CacheLinkedVideos bool `json:"cacheLinkedVideos,omitempty"`
- LinkedVideo bool `json:"-"` // a video cached as part of a dynamic
- ViaName string `json:"-"` // forwarder name for a video cached from a forward (DEC-056)
- ViaDynamicID string `json:"-"` // forwarding dynamic for such a video
- ProgressOwner *Task `json:"-"`
- ProgressPrefix string `json:"-"`
- Status string `json:"status"` // "queued", "running", "paused", "completed", "failed", "canceled", "partial"
- PauseReason string `json:"pauseReason,omitempty"`
- ErrorKind string `json:"errorKind,omitempty"`
- ErrorMessage string `json:"errorMessage,omitempty"`
- LastError string `json:"lastError,omitempty"`
- QualityHint string `json:"qualityHint,omitempty"`
- BytesDownloaded int64 `json:"bytesDownloaded"`
- TotalBytes int64 `json:"totalBytes"`
- Progress float64 `json:"progress"`
- ItemKey string `json:"itemKey,omitempty"`
- ItemDir string `json:"itemDir,omitempty"`
- Files []TaskFileProgress `json:"files,omitempty"`
- Attempts []TaskAttempt `json:"attempts,omitempty"`
- CreatedAt string `json:"createdAt"`
- UpdatedAt string `json:"updatedAt"`
+ TaskID string `json:"taskId"`
+ Site string `json:"site"`
+ Kind string `json:"kind"` // "video", "dynamic", "supplement", "upgrade"
+ Source string `json:"source,omitempty"` // "manual" or "auto"
+ TargetID string `json:"targetId"`
+ CID int64 `json:"cid,omitempty"`
+ Page int `json:"page,omitempty"`
+ Title string `json:"title"`
+ PartTitle string `json:"partTitle,omitempty"`
+ Mid int64 `json:"mid,omitempty"`
+ AuthorUID string `json:"authorUid,omitempty"`
+ AuthorName string `json:"authorName,omitempty"`
+ AuthorFace string `json:"authorFace,omitempty"`
+ CoverURL string `json:"coverUrl,omitempty"`
+ CacheLinkedVideos bool `json:"cacheLinkedVideos,omitempty"`
+ LinkedVideo bool `json:"-"` // a video cached as part of a dynamic
+ ViaName string `json:"-"` // forwarder name for a video cached from a forward (DEC-056)
+ ViaDynamicID string `json:"-"` // forwarding dynamic for such a video
+ // Via is the creator a Douyin work is cached for when they are not its
+ // author (a co-creation found in their works list): the item goes to
+ // their folder with this via. Kept in via_json so a resumed task still
+ // writes it.
+ Via *library.ItemVia `json:"via,omitempty"`
+ ProgressOwner *Task `json:"-"`
+ ProgressPrefix string `json:"-"`
+ Status string `json:"status"` // "queued", "running", "paused", "completed", "failed", "canceled", "partial"
+ PauseReason string `json:"pauseReason,omitempty"`
+ ErrorKind string `json:"errorKind,omitempty"`
+ ErrorMessage string `json:"errorMessage,omitempty"`
+ LastError string `json:"lastError,omitempty"`
+ QualityHint string `json:"qualityHint,omitempty"`
+ BytesDownloaded int64 `json:"bytesDownloaded"`
+ TotalBytes int64 `json:"totalBytes"`
+ Progress float64 `json:"progress"`
+ ItemKey string `json:"itemKey,omitempty"`
+ ItemDir string `json:"itemDir,omitempty"`
+ Files []TaskFileProgress `json:"files,omitempty"`
+ Attempts []TaskAttempt `json:"attempts,omitempty"`
+ CreatedAt string `json:"createdAt"`
+ UpdatedAt string `json:"updatedAt"`
}
// VideoEnqueueRequest specifies a video (and optional page subset) to cache.
@@ -124,10 +119,16 @@ type DynamicEnqueueRequest struct {
Item *bilibili.DynamicItem `json:"-"`
}
+type keyedLock struct {
+ ch chan struct{}
+ refs int
+}
+
// Manager coordinates queued and active download tasks with concurrency limits and circuit breaking.
type Manager struct {
mu sync.Mutex
- videoLocks sync.Map
+ itemLockMu sync.Mutex
+ itemLocks map[string]*keyedLock
db *sql.DB
lib *library.Store
client *bilibili.Client
@@ -140,6 +141,7 @@ type Manager struct {
chunkSize int64
backoffScale time.Duration
mediaWrap func(http.RoundTripper) http.RoundTripper
+ transports map[mediaTransportKey]*http.Transport
planners map[site.ID]WorkPlanner
initialPlans map[string]WorkDownloadPlan
@@ -164,6 +166,7 @@ func NewManager(
dlSettings.MaxConcurrentTasks = 2
}
m := &Manager{
+ itemLocks: make(map[string]*keyedLock),
db: db,
lib: lib,
client: client,
@@ -172,6 +175,7 @@ func NewManager(
lastNotify: make(map[string]taskNotification),
chunkSize: DefaultRangeChunkSize,
backoffScale: time.Second,
+ transports: make(map[mediaTransportKey]*http.Transport),
planners: make(map[site.ID]WorkPlanner),
initialPlans: make(map[string]WorkDownloadPlan),
wakeCh: make(chan struct{}, 1),
@@ -184,6 +188,46 @@ func NewManager(
return m, nil
}
+// lockItem acquires a context-cancellable per-item lock so concurrent tasks
+// targeting the same manifest do not overwrite each other while remaining
+// immediately cancellable on Pause/Cancel/Stop and never leaking map entries.
+func (m *Manager) lockItem(ctx context.Context, key string) (func(), error) {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ m.itemLockMu.Lock()
+ if m.itemLocks == nil {
+ m.itemLocks = make(map[string]*keyedLock)
+ }
+ kl, ok := m.itemLocks[key]
+ if !ok {
+ kl = &keyedLock{ch: make(chan struct{}, 1)}
+ m.itemLocks[key] = kl
+ }
+ kl.refs++
+ m.itemLockMu.Unlock()
+
+ releaseRef := func() {
+ m.itemLockMu.Lock()
+ kl.refs--
+ if kl.refs == 0 && m.itemLocks[key] == kl {
+ delete(m.itemLocks, key)
+ }
+ m.itemLockMu.Unlock()
+ }
+
+ select {
+ case kl.ch <- struct{}{}:
+ return func() {
+ <-kl.ch
+ releaseRef()
+ }, nil
+ case <-ctx.Done():
+ releaseRef()
+ return nil, ctx.Err()
+ }
+}
+
// SetBackoffScale overrides the 1s base retry backoff unit (used by unit tests for fast deterministic retries).
func (m *Manager) SetBackoffScale(scale time.Duration) {
m.mu.Lock()
@@ -209,69 +253,6 @@ func (m *Manager) SetChunkSize(bytes int64) {
m.mu.Unlock()
}
-func (m *Manager) initSchema() error {
- stmts := []string{
- `CREATE TABLE IF NOT EXISTS download_tasks (
- task_id TEXT PRIMARY KEY,
- site TEXT NOT NULL,
- kind TEXT NOT NULL,
- source TEXT NOT NULL DEFAULT 'manual',
- target_id TEXT NOT NULL,
- cid INTEGER NOT NULL DEFAULT 0,
- page INTEGER NOT NULL DEFAULT 1,
- title TEXT NOT NULL DEFAULT '',
- part_title TEXT NOT NULL DEFAULT '',
- mid INTEGER NOT NULL DEFAULT 0,
- author_uid TEXT NOT NULL DEFAULT '',
- author_name TEXT NOT NULL DEFAULT '',
- author_face TEXT NOT NULL DEFAULT '',
- cover_url TEXT NOT NULL DEFAULT '',
- cache_linked_videos INTEGER NOT NULL DEFAULT 0,
- status TEXT NOT NULL DEFAULT 'queued',
- pause_reason TEXT NOT NULL DEFAULT '',
- error_kind TEXT NOT NULL DEFAULT '',
- error_message TEXT NOT NULL DEFAULT '',
- quality_hint TEXT NOT NULL DEFAULT '',
- bytes_downloaded INTEGER NOT NULL DEFAULT 0,
- total_bytes INTEGER NOT NULL DEFAULT 0,
- progress REAL NOT NULL DEFAULT 0,
- item_key TEXT NOT NULL DEFAULT '',
- item_dir TEXT NOT NULL DEFAULT '',
- files_json TEXT NOT NULL DEFAULT '[]',
- attempts_json TEXT NOT NULL DEFAULT '[]',
- created_at TEXT NOT NULL,
- updated_at TEXT NOT NULL
- );`,
- `CREATE TABLE IF NOT EXISTS task_attempts (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- task_id TEXT NOT NULL,
- attempt_time TEXT NOT NULL,
- file_path TEXT NOT NULL,
- offset_bytes INTEGER NOT NULL DEFAULT 0,
- host TEXT NOT NULL DEFAULT '',
- attempt_num INTEGER NOT NULL DEFAULT 1,
- error_kind TEXT NOT NULL DEFAULT '',
- http_status INTEGER NOT NULL DEFAULT 0
- );`,
- }
- for _, q := range stmts {
- if _, err := m.db.Exec(q); err != nil {
- return err
- }
- }
- // Ensure columns exist on databases created before schema additions.
- for _, alter := range []string{
- `ALTER TABLE download_tasks ADD COLUMN source TEXT NOT NULL DEFAULT 'manual'`,
- `ALTER TABLE download_tasks ADD COLUMN author_uid TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE download_tasks ADD COLUMN pause_reason TEXT NOT NULL DEFAULT ''`,
- `ALTER TABLE download_tasks ADD COLUMN files_json TEXT NOT NULL DEFAULT '[]'`,
- `ALTER TABLE download_tasks ADD COLUMN attempts_json TEXT NOT NULL DEFAULT '[]'`,
- } {
- _, _ = m.db.Exec(alter)
- }
- return nil
-}
-
// Start marks any leftover "queued" or "running" tasks from a previous session as
// "paused" ("已暂停(应用关闭)") per data-and-cache.md §2.4, and launches the worker loop.
func (m *Manager) Start(parentCtx context.Context) error {
@@ -299,7 +280,8 @@ func (m *Manager) Start(parentCtx context.Context) error {
return nil
}
-// Stop cancels all active downloads and waits for background workers to exit.
+// Stop cancels all active downloads, waits for background workers to exit, and
+// releases idle connections on pooled media transports.
func (m *Manager) Stop() {
m.PauseAll("app_closed", "已暂停(应用关闭)")
m.mu.Lock()
@@ -314,6 +296,63 @@ func (m *Manager) Stop() {
cancel()
}
m.wg.Wait()
+
+ m.mu.Lock()
+ transports := make([]*http.Transport, 0, len(m.transports))
+ for _, tr := range m.transports {
+ transports = append(transports, tr)
+ }
+ clear(m.transports)
+ m.mu.Unlock()
+ for _, tr := range transports {
+ tr.CloseIdleConnections()
+ }
+}
+
+func (m *Manager) pauseTasksWhereLocked(reason, errKind, message, whereClause string, whereArgs ...any) ([]string, error) {
+ rows, err := m.db.Query(`SELECT task_id FROM download_tasks WHERE `+whereClause, whereArgs...)
+ if err != nil {
+ return nil, err
+ }
+ var ids []string
+ for rows.Next() {
+ var id string
+ if scanErr := rows.Scan(&id); scanErr != nil {
+ _ = rows.Close()
+ return nil, scanErr
+ }
+ ids = append(ids, id)
+ }
+ if err := errors.Join(rows.Err(), rows.Close()); err != nil {
+ return nil, err
+ }
+ if len(ids) == 0 {
+ return nil, nil
+ }
+ now := time.Now().UTC().Format(time.RFC3339)
+ args := make([]any, 0, 5+len(whereArgs))
+ args = append(args, reason, errKind, errKind, message, now)
+ args = append(args, whereArgs...)
+ _, err = m.db.Exec(`
+ UPDATE download_tasks
+ SET status = 'paused',
+ pause_reason = ?,
+ error_kind = CASE WHEN ? != '' THEN ? ELSE error_kind END,
+ error_message = ?,
+ updated_at = ?
+ WHERE `+whereClause, args...)
+ if err != nil {
+ return nil, err
+ }
+ return ids, nil
+}
+
+func (m *Manager) emitTasksByID(ids []string) {
+ for _, id := range ids {
+ if t, ok, err := m.GetTask(id); err == nil && ok {
+ m.emitUpdate(t)
+ }
+ }
}
// PauseAll pauses all currently running and queued tasks across all sites with the specified reason.
@@ -330,16 +369,14 @@ func (m *Manager) PauseAll(reason, message string) {
if message == "" {
message = "已暂停"
}
- now := time.Now().UTC().Format(time.RFC3339)
- _, err := m.db.Exec(`
- UPDATE download_tasks
- SET status = 'paused', pause_reason = ?, error_message = ?, updated_at = ?
- WHERE status IN ('queued', 'running')
- `, reason, message, now)
+ ids, err := m.pauseTasksWhereLocked(reason, "", message, `status IN ('queued', 'running')`)
if err == nil {
m.taskFaults.Range(func(key, _ any) bool { m.taskFaults.Delete(key); return true })
}
m.mu.Unlock()
+ if err == nil {
+ m.emitTasksByID(ids)
+ }
}
// PauseForSite pauses only running and queued tasks belonging to siteID without interrupting other sites.
@@ -368,18 +405,16 @@ func (m *Manager) PauseForSite(siteID site.ID, reason, message string) {
if message == "" {
message = "已暂停"
}
- now := time.Now().UTC().Format(time.RFC3339)
- _, err := m.db.Exec(`
- UPDATE download_tasks
- SET status = 'paused', pause_reason = ?, error_message = ?, updated_at = ?
- WHERE site = ? AND status IN ('queued', 'running')
- `, reason, message, now, targetSite)
+ ids, err := m.pauseTasksWhereLocked(reason, "", message, `site = ? AND status IN ('queued', 'running')`, targetSite)
if err == nil {
for _, id := range pausedIDs {
m.taskFaults.Delete(id)
}
}
m.mu.Unlock()
+ if err == nil {
+ m.emitTasksByID(ids)
+ }
m.notifyWake()
}
@@ -566,116 +601,6 @@ func (m *Manager) Upgrade(ctx context.Context, keyOrBVID string) (Task, error) {
return t, nil
}
-func (m *Manager) enqueueSingleTask(in Task) (Task, error) {
- m.mu.Lock()
- defer m.mu.Unlock()
-
- if in.Site == "" {
- in.Site = "bilibili"
- }
- if in.AuthorUID == "" && in.Mid > 0 && in.Site == "bilibili" {
- in.AuthorUID = strconv.FormatInt(in.Mid, 10)
- }
-
- // Deduplicate if an identical task for the same site is already queued or running.
- existing, ok, err := m.findActiveOrQueuedLocked(in.Site, in.Kind, in.TargetID, in.CID)
- if err != nil {
- return Task{}, err
- }
- if ok {
- return existing, nil
- }
-
- now := time.Now().UTC().Format(time.RFC3339)
- var rnd [6]byte
- _, _ = rand.Read(rnd[:])
- in.TaskID = "dl-" + hex.EncodeToString(rnd[:])
- in.Status = "queued"
- if in.Source == "" {
- in.Source = "manual"
- }
- in.CreatedAt = now
- in.UpdatedAt = now
-
- linkedInt := 0
- if in.CacheLinkedVideos {
- linkedInt = 1
- }
-
- filesJSON, _ := json.Marshal(in.Files)
- attemptsJSON, _ := json.Marshal(in.Attempts)
-
- _, err = m.db.Exec(`
- INSERT INTO download_tasks (
- task_id, site, kind, source, target_id, cid, page, title, part_title,
- mid, author_uid, author_name, author_face, cover_url, cache_linked_videos,
- status, pause_reason, error_kind, error_message, quality_hint,
- bytes_downloaded, total_bytes, progress, item_key, item_dir,
- files_json, attempts_json, created_at, updated_at
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '', '', '', '', 0, 0, 0, ?, ?, ?, ?, ?, ?)
- `,
- in.TaskID, in.Site, in.Kind, in.Source, in.TargetID, in.CID, in.Page, in.Title, in.PartTitle,
- in.Mid, in.AuthorUID, in.AuthorName, in.AuthorFace, in.CoverURL, linkedInt,
- in.Status, in.ItemKey, in.ItemDir, string(filesJSON), string(attemptsJSON), in.CreatedAt, in.UpdatedAt,
- )
- if err != nil {
- return Task{}, err
- }
- return in, nil
-}
-
-func (m *Manager) findActiveOrQueuedLocked(siteID, kind, targetID string, cid int64) (Task, bool, error) {
- row := m.db.QueryRow(`
- SELECT
- task_id, site, kind, source, target_id, cid, page, title, part_title,
- mid, author_uid, author_name, author_face, cover_url, cache_linked_videos,
- status, pause_reason, error_kind, error_message, quality_hint,
- bytes_downloaded, total_bytes, progress, item_key, item_dir,
- files_json, attempts_json, created_at, updated_at
- FROM download_tasks
- WHERE site = ? AND kind = ? AND target_id = ? AND cid = ? AND status IN ('queued', 'running')
- LIMIT 1
- `, siteID, kind, targetID, cid)
- t, err := scanTask(row)
- if err != nil {
- if err == sql.ErrNoRows {
- return Task{}, false, nil
- }
- return Task{}, false, err
- }
- return t, true, nil
-}
-
-// ListTasks returns active tasks first, then tasks needing action, then finished
-// tasks, with the most recently updated task first within each group.
-func (m *Manager) ListTasks() ([]Task, error) {
- rows, err := m.db.Query(`
- SELECT
- task_id, site, kind, source, target_id, cid, page, title, part_title,
- mid, author_uid, author_name, author_face, cover_url, cache_linked_videos,
- status, pause_reason, error_kind, error_message, quality_hint,
- bytes_downloaded, total_bytes, progress, item_key, item_dir,
- files_json, attempts_json, created_at, updated_at
- FROM download_tasks
- ORDER BY CASE WHEN status IN ('running', 'queued') THEN 0 WHEN status IN ('paused', 'failed', 'partial') THEN 1 ELSE 2 END,
- julianday(updated_at) DESC, rowid DESC
- `)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- var out []Task
- for rows.Next() {
- t, err := scanTask(rows)
- if err != nil {
- return nil, err
- }
- out = append(out, m.withTaskFault(t))
- }
- return out, rows.Err()
-}
-
// WithIdleTasks keeps cache migration from overlapping a worker that is still
// exiting after Pause, or an enqueue/start while registered files are moved.
// work must not call back into Manager.
@@ -695,41 +620,6 @@ func (m *Manager) WithIdleTasks(work func() error) error {
return work()
}
-// GetTask retrieves a single task by taskID.
-func (m *Manager) GetTask(taskID string) (Task, bool, error) {
- row := m.db.QueryRow(`
- SELECT
- task_id, site, kind, source, target_id, cid, page, title, part_title,
- mid, author_uid, author_name, author_face, cover_url, cache_linked_videos,
- status, pause_reason, error_kind, error_message, quality_hint,
- bytes_downloaded, total_bytes, progress, item_key, item_dir,
- files_json, attempts_json, created_at, updated_at
- FROM download_tasks
- WHERE task_id = ?
- `, taskID)
- t, err := scanTask(row)
- if err != nil {
- if err == sql.ErrNoRows {
- return Task{}, false, nil
- }
- return Task{}, false, err
- }
- return m.withTaskFault(t), true, nil
-}
-
-// TaskDetail returns the task along with its per-file progress manifest and desensitized attempt log.
-func (m *Manager) TaskDetail(taskID string) (TaskDetail, bool, error) {
- t, ok, err := m.GetTask(taskID)
- if err != nil || !ok {
- return TaskDetail{}, ok, err
- }
- return TaskDetail{
- Task: t,
- Files: t.Files,
- Attempts: t.Attempts,
- }, true, nil
-}
-
// Pause transitions a queued or running task to "paused".
func (m *Manager) Pause(taskID string) (Task, error) {
m.mu.Lock()
@@ -855,7 +745,11 @@ func (m *Manager) Remove(taskID string) error {
if err := tx.Commit(); err != nil {
return err
}
+ delete(m.initialPlans, taskID)
m.taskFaults.Delete(taskID)
+ m.notifyMu.Lock()
+ delete(m.lastNotify, taskID)
+ m.notifyMu.Unlock()
return nil
}
@@ -938,8 +832,9 @@ func (m *Manager) launchAvailableWorkers() {
m.mu.Unlock()
m.emitUpdate(nextTask)
- go func(t Task, ctx context.Context) {
+ go func(t Task, ctx context.Context, cancel context.CancelFunc) {
defer m.wg.Done()
+ defer cancel()
m.runTask(ctx, t)
if latest, ok, err := m.GetTask(t.TaskID); err == nil && ok && latest.Status == "canceled" {
cleanTaskPartFiles(latest)
@@ -947,45 +842,13 @@ func (m *Manager) launchAvailableWorkers() {
m.mu.Lock()
delete(m.activeRun, t.TaskID)
delete(m.activeSite, t.TaskID)
+ delete(m.initialPlans, t.TaskID)
m.mu.Unlock()
m.notifyWake()
- }(nextTask, taskCtx)
+ }(nextTask, taskCtx, taskCancel)
}
}
-func (m *Manager) claimNextQueuedLocked() (Task, bool) {
- query := `
- SELECT
- task_id, site, kind, source, target_id, cid, page, title, part_title,
- mid, author_uid, author_name, author_face, cover_url, cache_linked_videos,
- status, pause_reason, error_kind, error_message, quality_hint,
- bytes_downloaded, total_bytes, progress, item_key, item_dir,
- files_json, attempts_json, created_at, updated_at
- FROM download_tasks
- WHERE status = 'queued'`
- var args []any
- if len(m.activeRun) > 0 {
- query += " AND task_id NOT IN (" + strings.TrimSuffix(strings.Repeat("?,", len(m.activeRun)), ",") + ")"
- for id := range m.activeRun {
- args = append(args, id)
- }
- }
- query += " ORDER BY rowid ASC LIMIT 1"
- row := m.db.QueryRow(query, args...)
- t, err := scanTask(row)
- if err != nil {
- return Task{}, false
- }
- now := time.Now().UTC().Format(time.RFC3339)
- t.Status = "running"
- t.PauseReason = ""
- t.ErrorKind = ""
- t.ErrorMessage = ""
- t.UpdatedAt = now
- _, _ = m.db.Exec(`UPDATE download_tasks SET status = 'running', pause_reason = '', error_kind = '', error_message = '', updated_at = ? WHERE task_id = ?`, now, t.TaskID)
- return t, true
-}
-
func (m *Manager) runTask(ctx context.Context, t Task) {
if t.Source == "auto" {
ctx = bilibili.WithAutomaticRequests(ctx, "download")
@@ -1015,13 +878,22 @@ func (m *Manager) runTask(ctx context.Context, t Task) {
if err != nil {
m.reportSiteAutomaticError(ctx, t.Site, err)
+ var netPause *networkPauseError
+ if errors.As(err, &netPause) {
+ t.Status = "paused"
+ t.PauseReason = "network"
+ t.ErrorKind = site.ErrKindNetwork
+ t.ErrorMessage = netPause.Error()
+ m.persistTaskProgress(t)
+ return
+ }
errKind := classifyDownloadError(err)
if errKind == bilibili.ErrKindAuthRequired {
t.Status, t.PauseReason = "paused", "auth_required"
t.ErrorKind = errKind
t.ErrorMessage = "已暂停(登录已失效):" + err.Error()
m.persistTaskProgress(t)
- m.pauseQueuedForSite(t.Site, "auth_required", errKind, "已暂停(登录已失效):"+err.Error())
+ m.pauseSitePeers(t.Site, t.TaskID, "auth_required", errKind, "已暂停(登录已失效):"+err.Error())
return
}
if errKind == bilibili.ErrKindQuota || errKind == bilibili.ErrKindBackoff {
@@ -1030,14 +902,15 @@ func (m *Manager) runTask(ctx context.Context, t Task) {
if (errKind == bilibili.ErrKindUnavailable || errKind == bilibili.ErrKindBlocked) && t.Site != string(site.Douyin) {
t.Status = "partial"
}
- // Risk control or rate limit pauses this task and queued tasks of the same site only (data-and-cache.md §2.4).
+ // Risk control or rate limit pauses this task and queued/running tasks of the same site only (data-and-cache.md §2.4).
if errKind == bilibili.ErrKindRiskControl || errKind == bilibili.ErrKindRateLimited {
t.Status = "paused"
t.PauseReason = "risk_control"
t.ErrorKind = errKind
t.ErrorMessage = "已暂停(风控):" + err.Error()
m.persistTaskProgress(t)
- m.tripSiteCircuitBreaker(t.Site, t.TaskID, errKind, err.Error())
+ msg := fmt.Sprintf("检测到站点风控或频率限制 (%s),已自动暂停同站点排队任务: %s", errKind, err.Error())
+ m.pauseSitePeers(t.Site, t.TaskID, "risk_control", errKind, msg)
return
}
if t.Status == "paused" {
@@ -1061,1285 +934,34 @@ func (m *Manager) runTask(ctx context.Context, t Task) {
if t.Status != "partial" {
t.Status = "completed"
+ t.ErrorKind = ""
+ t.ErrorMessage = ""
}
t.PauseReason = ""
t.Progress = 1.0
- t.ErrorKind = ""
- t.ErrorMessage = ""
m.persistTaskProgress(t)
}
-func (m *Manager) tripSiteCircuitBreaker(siteID, triggeringTaskID, errKind, reason string) {
+func (m *Manager) pauseSitePeers(siteID, triggeringTaskID, pauseReason, errKind, msg string) {
if siteID == "" {
siteID = string(site.Bilibili)
}
m.mu.Lock()
- now := time.Now().UTC().Format(time.RFC3339)
- msg := fmt.Sprintf("检测到站点风控或频率限制 (%s),已自动暂停同站点排队任务: %s", errKind, reason)
for id, fn := range m.activeRun {
if id != triggeringTaskID && m.activeSite[id] == siteID {
delete(m.initialPlans, id)
fn()
}
}
- _, _ = m.db.Exec(`
- UPDATE download_tasks
- SET status = 'paused', pause_reason = 'risk_control', error_kind = ?, error_message = ?, updated_at = ?
- WHERE site = ? AND (status = 'queued' OR (status = 'running' AND task_id != ?))
- `, errKind, msg, now, siteID, triggeringTaskID)
- m.mu.Unlock()
-}
-
-func (m *Manager) pauseQueuedForSite(siteID, pauseReason, errKind, msg string) {
- if siteID == "" {
- siteID = string(site.Bilibili)
- }
- m.mu.Lock()
- now := time.Now().UTC().Format(time.RFC3339)
- _, _ = m.db.Exec(`
- UPDATE download_tasks
- SET status = 'paused', pause_reason = ?, error_kind = ?, error_message = ?, updated_at = ?
- WHERE site = ? AND status = 'queued'
- `, pauseReason, errKind, msg, now, siteID)
+ ids, err := m.pauseTasksWhereLocked(
+ pauseReason,
+ errKind,
+ msg,
+ `site = ? AND (status = 'queued' OR (status = 'running' AND task_id != ?))`,
+ siteID, triggeringTaskID,
+ )
m.mu.Unlock()
-}
-
-func (m *Manager) setFileProgress(t *Task, role, relPath, status string, downloaded, total, speed int64) {
- found := false
- for i := range t.Files {
- if t.Files[i].Path == relPath {
- t.Files[i].Role = role
- t.Files[i].Status = status
- t.Files[i].DownloadedBytes = downloaded
- if total > 0 {
- t.Files[i].TotalBytes = total
- }
- t.Files[i].SpeedBps = speed
- found = true
- break
- }
- }
- if !found {
- t.Files = append(t.Files, TaskFileProgress{
- Role: role,
- Path: relPath,
- Status: status,
- DownloadedBytes: downloaded,
- TotalBytes: total,
- SpeedBps: speed,
- })
- }
-}
-
-func (m *Manager) recordAttempt(t *Task, relFile string, offset int64, rawURL string, attempt int, errKind string, httpStatus int) {
- host := ""
- if u, err := url.Parse(rawURL); err == nil {
- host = u.Hostname()
- }
- entry := TaskAttempt{
- Time: time.Now().UTC().Format(time.RFC3339),
- File: relFile,
- Offset: offset,
- Host: host,
- Attempt: attempt,
- ErrorKind: errKind,
- HTTPStatus: httpStatus,
- }
- t.Attempts = append(t.Attempts, entry)
- if len(t.Attempts) > 200 {
- t.Attempts = t.Attempts[len(t.Attempts)-200:]
- }
- if t.TaskID != "" {
- _, _ = m.db.Exec(`
- INSERT INTO task_attempts (task_id, attempt_time, file_path, offset_bytes, host, attempt_num, error_kind, http_status)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
- `, t.TaskID, entry.Time, entry.File, entry.Offset, entry.Host, entry.Attempt, entry.ErrorKind, entry.HTTPStatus)
- }
-}
-
-func (m *Manager) executeDynamicTask(ctx context.Context, t *Task) (result error) {
- dyn, err := m.client.DynamicDetail(ctx, t.TargetID)
- if err != nil {
- return err
- }
-
- forward := dyn.Origin != nil || strings.EqualFold(dyn.Type, "DYNAMIC_TYPE_FORWARD")
- for origin := dyn.Origin; origin != nil; origin = origin.Origin {
- dyn.Images = append(dyn.Images, origin.Images...)
- dyn.Videos = append(dyn.Videos, origin.Videos...)
- }
- // A forward's parse already copies the origin's media when the forward has
- // none of its own; keep each image and video once.
- dyn.Images = dedupeDynamicImages(dyn.Images)
- dyn.Videos = dedupeDynamicVideos(dyn.Videos)
- t.Title = dyn.Title
- t.Mid = dyn.Author.Mid
- t.AuthorName = dyn.Author.Name
- t.AuthorFace = dyn.Author.Face
-
- cacheRoot := m.lib.CacheDir()
- // Forwards and what they carry live in the forwarder's own forwards/
- // folder, apart from their own posts (DEC-056).
- typeDir := "dynamics"
- if forward {
- typeDir = "forwards"
- }
- authorDir := filepath.Join(cacheRoot, "bilibili", strconv.FormatInt(dyn.Author.Mid, 10))
- itemDir, err := library.EnsureWithinRoot(cacheRoot, filepath.Join(authorDir, typeDir, dyn.ID))
- if err != nil {
- return err
- }
- previous, exists, err := m.lib.GetItem("dynamic:" + dyn.ID)
- if err != nil {
- return err
- }
- if exists {
- itemDir = previous.ItemDir
- } else if t.ItemDir != "" {
- itemDir = t.ItemDir
- }
- if err := os.MkdirAll(itemDir, 0o700); err != nil {
- return err
- }
- t.ItemDir = itemDir
-
- for idx, img := range dyn.Images {
- ext := guessImageExt(img.URL)
- relName := fmt.Sprintf("images/%02d%s", idx+1, ext)
- m.setFileProgress(t, "image", relName, "waiting", 0, 0, 0)
- if img.LiveURL != "" {
- m.setFileProgress(t, "motion", motionRelName(idx, img.LiveURL), "waiting", 0, 0, 0)
- }
- }
- m.persistTaskProgress(*t)
-
- var mediaFiles []library.MediaFile
- var partialErrors []string
- var videoRefs []string
- finalSaved := false
- for _, video := range dyn.Videos {
- if video.BVID != "" {
- videoRefs = append(videoRefs, "video:"+video.BVID)
- }
- }
- t.ItemKey = library.CanonicalItemKey("bilibili", "dynamic", dyn.ID)
- defer func() {
- if result == nil || finalSaved {
- return
- }
- // An interruption must retain already completed files and their hashes.
- missing := []library.MissingRecord{{Item: "dynamic", Reason: "动态缓存尚未完成 (" + bilibili.KindOf(result) + ")"}}
- meta := library.ItemMetadata{Version: 1, ID: "dynamic:" + dyn.ID, Site: "bilibili", Kind: "dynamic", Status: "partial", Title: dyn.Title, Text: dyn.Text, DynamicType: dyn.Type, TypeLabel: dyn.TypeLabel, URL: dyn.CanonicalURL, PubTs: dyn.PubTs, CachedAt: previous.CachedAt, Author: library.ItemAuthor{Mid: dyn.Author.Mid, Name: dyn.Author.Name, Face: dyn.Author.Face}, Media: mergeMediaFiles(previous.Media, mediaFiles), Videos: videoRefs, Missing: missing}
- if _, err := m.lib.SaveItem(itemDir, meta); err != nil {
- result = err
- }
- }()
-
- // Save orig.json snapshot if this dynamic is a forward post (data-and-cache.md §2.1 & §2.3).
- if dyn.Origin != nil {
- if origBytes, mErr := json.MarshalIndent(dyn.Origin, "", " "); mErr == nil {
- if err := m.claimTaskFile(t, itemDir, "orig.json", filepath.Join(itemDir, "orig.json")); err != nil {
- return err
- }
- if err := storage.WriteFileAtomic(filepath.Join(itemDir, "orig.json"), origBytes, 0o600); err != nil {
- return err
- }
- mediaFiles = append(mediaFiles, library.MediaFile{Role: "snapshot", Path: "orig.json", Bytes: int64(len(origBytes))})
- }
- }
-
- for idx, img := range dyn.Images {
- ext := guessImageExt(img.URL)
- relName := fmt.Sprintf("images/%02d%s", idx+1, ext)
- // Existing manifests retain their registered names and location.
- if exists {
- for _, media := range previous.Media {
- if media.Role == "image" && media.Source == img.URL {
- relName = media.Path
- break
- }
- }
- }
- fullPath := filepath.Join(itemDir, relName)
-
- // If image already exists on disk from an earlier partial attempt, reuse it without re-downloading.
- if mediaIsValid(previous, relName) {
- info, statErr := os.Stat(fullPath)
- if statErr != nil {
- return statErr
- }
- m.setFileProgress(t, "image", relName, "completed", info.Size(), info.Size(), 0)
- for _, media := range previous.Media {
- if media.Path == relName {
- still := media
- motion, err := m.cacheLiveMotion(ctx, t, itemDir, previous, exists, idx, img.LiveURL, &partialErrors)
- if err != nil {
- return err
- }
- if motion != nil {
- still.Motion = motion.Path
- mediaFiles = append(mediaFiles, *motion)
- }
- mediaFiles = append(mediaFiles, still)
- break
- }
- }
- continue
- }
-
- m.setFileProgress(t, "image", relName, "downloading", 0, 0, 0)
- n, sha, dlErr := m.downloadFileWithRange(ctx, []string{img.URL}, fullPath, t)
- if dlErr != nil {
- m.setFileProgress(t, "image", relName, "failed", 0, 0, 0)
- if isStopError(dlErr) || isStorageError(dlErr) || ctx.Err() != nil {
- return dlErr
- }
- partialErrors = append(partialErrors, fmt.Sprintf("img_%02d: %v", idx+1, dlErr))
- continue
- }
- m.setFileProgress(t, "image", relName, "completed", n, n, 0)
- still := library.MediaFile{
- Role: "image",
- Path: relName,
- Bytes: n,
- SHA256: sha,
- Source: img.URL,
- Width: img.Width,
- Height: img.Height,
- }
- motion, err := m.cacheLiveMotion(ctx, t, itemDir, previous, exists, idx, img.LiveURL, &partialErrors)
- if err != nil {
- return err
- }
- if motion != nil {
- still.Motion = motion.Path
- mediaFiles = append(mediaFiles, *motion)
- }
- mediaFiles = append(mediaFiles, still)
- }
-
- for _, v := range dyn.Videos {
- if v.BVID != "" {
- if t.CacheLinkedVideos {
- detail, err := m.client.VideoDetail(ctx, v.BVID)
- if err != nil {
- return err
- }
- for _, page := range detail.Pages {
- vidTask := Task{Site: "bilibili", Kind: "video", TargetID: v.BVID, CID: page.CID, Page: page.Page, Source: t.Source, LinkedVideo: true, ProgressOwner: t, ProgressPrefix: "videos/" + v.BVID + "/", Attempts: t.Attempts}
- switch {
- case detail.Author.Mid == dyn.Author.Mid:
- case forward:
- if dir, dirErr := library.EnsureWithinRoot(cacheRoot, filepath.Join(authorDir, "forwards", detail.BVID)); dirErr == nil {
- vidTask.ItemDir, vidTask.ViaName, vidTask.ViaDynamicID = dir, dyn.Author.Name, dyn.ID
- }
- case detail.HasStaffMember(dyn.Author.Mid):
- // A collaboration video posted by a member who is not the uploader.
- if dir, dirErr := library.EnsureWithinRoot(cacheRoot, filepath.Join(authorDir, "videos", detail.BVID)); dirErr == nil {
- vidTask.ItemDir = dir
- }
- }
- if err := m.executeVideoTask(ctx, &vidTask); err != nil {
- if bilibili.IsKind(err, bilibili.ErrKindRiskControl) || bilibili.IsKind(err, bilibili.ErrKindRateLimited) || bilibili.IsKind(err, bilibili.ErrKindAuthRequired) {
- return err
- }
- partialErrors = append(partialErrors, fmt.Sprintf("video %s P%d: %v", v.BVID, page.Page, err))
- }
- if vidTask.Status == "partial" {
- partialErrors = append(partialErrors, fmt.Sprintf("video %s P%d: 部分缓存", v.BVID, page.Page))
- }
- }
- }
- }
- }
-
- status := "complete"
- var missing []library.MissingRecord
- if dyn.Degraded {
- status = "partial"
- t.Status = "partial"
- missing = append(missing, library.MissingRecord{Item: "dynamic", Reason: fmt.Sprintf("类型不支持 (%s)", dyn.TypeLabel)})
- }
- if len(partialErrors) > 0 {
- status = "partial"
- t.Status = "partial"
- for _, pe := range partialErrors {
- missing = append(missing, library.MissingRecord{Item: "media", Reason: pe})
- }
- }
-
- meta := library.ItemMetadata{
- Version: 1,
- ID: "dynamic:" + dyn.ID,
- Site: "bilibili",
- Kind: "dynamic",
- Status: status,
- Title: dyn.Title,
- Text: dyn.Text,
- DynamicType: dyn.Type,
- TypeLabel: dyn.TypeLabel,
- URL: dyn.CanonicalURL,
- PubTs: dyn.PubTs,
- CachedAt: previous.CachedAt,
- Author: library.ItemAuthor{
- Mid: dyn.Author.Mid,
- Name: dyn.Author.Name,
- Face: dyn.Author.Face,
- },
- Media: mediaFiles,
- Videos: videoRefs,
- Missing: missing,
- }
-
- savedMeta, saveErr := m.lib.SaveItem(itemDir, meta)
- if saveErr != nil {
- return saveErr
- }
- t.ItemKey = savedMeta.ItemKey
- finalSaved = true
-
- if len(partialErrors) > 0 {
- return fmt.Errorf("部分媒体下载失败 (%s)", strings.Join(partialErrors, "; "))
- }
- return nil
-}
-
-func (m *Manager) downloadStreamWithRefresh(
- ctx context.Context,
- urls []string,
- finalPath string,
- t *Task,
- refreshURLs func() ([]string, error),
-) (int64, string, error) {
- n, sha, err := m.downloadFileWithRange(ctx, urls, finalPath, t)
if err == nil {
- return n, sha, nil
- }
- // If all URLs expired (403, 404, 410), refresh PlayURL at most once and resume from byte offset (data-and-cache.md §2.4).
- if refreshURLs != nil && (bilibili.IsKind(err, bilibili.ErrKindForbidden) || bilibili.IsKind(err, bilibili.ErrKindUnavailable)) {
- freshURLs, rErr := refreshURLs()
- if rErr != nil {
- if bilibili.IsKind(rErr, bilibili.ErrKindRiskControl) || bilibili.IsKind(rErr, bilibili.ErrKindRateLimited) {
- return 0, "", rErr
- }
- return 0, "", err
- }
- if len(freshURLs) > 0 {
- return m.downloadFileWithRange(ctx, freshURLs, finalPath, t)
- }
- }
- return 0, "", err
-}
-
-// downloadFileWithRange downloads from candidate URLs into finalPath via .part,
-// using 8 MiB closed-interval Range requests, per-segment retry with exponential backoff + URL rotation,
-// and Content-Range verification (data-and-cache.md §2.4).
-func (m *Manager) downloadFileWithRange(ctx context.Context, urls []string, finalPath string, t *Task) (int64, string, error) {
- var cleanURLs []string
- rejectedNodes := 0
- for _, u := range urls {
- if u = strings.TrimSpace(u); u == "" {
- continue
- }
- // Third-party MCDN/PCDN nodes outside the media allowlist are skipped
- // up front instead of being recorded as failed attempts.
- if m.client != nil && m.client.ValidateMediaURL(u) != nil {
- rejectedNodes++
- continue
- }
- cleanURLs = append(cleanURLs, u)
- }
- if len(cleanURLs) == 0 && rejectedNodes > 0 {
- return 0, "", &bilibili.SiteError{
- Kind: bilibili.ErrKindUnavailable,
- Message: "站点只返回了不受支持的第三方媒体节点,请稍后重试",
- }
- }
- if len(cleanURLs) == 0 {
- return 0, "", &bilibili.SiteError{
- Kind: bilibili.ErrKindUnavailable,
- Message: "下载地址列表为空",
- }
- }
-
- root, rel := filepath.Dir(finalPath), filepath.Base(finalPath)
- if t.ItemDir != "" {
- root = t.ItemDir
- var err error
- rel, err = filepath.Rel(root, finalPath)
- if err != nil {
- return 0, "", err
- }
- rel = filepath.ToSlash(rel)
- }
- if _, err := library.ResolveItemPath(root, rel); err != nil {
- return 0, "", err
- }
- if _, err := library.ResolveItemPath(root, rel+".part"); err != nil {
- return 0, "", err
- }
- if err := m.claimTaskFile(t, root, rel, finalPath); err != nil {
- return 0, "", err
- }
- // A nonempty file alone is not proof of completion. Reuse only a verified
- // checkpoint with its original length (and hash, when available).
- for _, file := range t.Files {
- if taskFileIdentity(file.Path) == taskFileIdentity(rel) && file.TotalBytes > 0 && library.VerifyMediaFile(root, library.MediaFile{Path: rel, Bytes: file.TotalBytes, SHA256: file.SHA256}, true) {
- sha, sz, err := hashFileSHA256(finalPath)
- return sz, sha, err
- }
- }
-
- if err := os.MkdirAll(filepath.Dir(finalPath), 0o700); err != nil {
- return 0, "", err
- }
-
- m.mu.Lock()
- chunkSize := m.chunkSize
- if chunkSize <= 0 {
- chunkSize = DefaultRangeChunkSize
- }
- backoffScale := m.backoffScale
- if backoffScale <= 0 {
- backoffScale = time.Second
- }
- m.mu.Unlock()
-
- partPath := finalPath + ".part"
- relFile := filepath.Base(finalPath)
- var offset int64
- if info, err := os.Stat(partPath); err == nil && !info.IsDir() {
- offset = info.Size()
- }
-
- var totalSize int64 = -1
- for _, file := range t.Files {
- if taskFileIdentity(file.Path) == taskFileIdentity(rel) && file.TotalBytes > 0 {
- totalSize = file.TotalBytes
- break
- }
- }
- if totalSize > 0 && offset > totalSize {
- if err := os.Truncate(partPath, 0); err != nil {
- return 0, "", err
- }
- offset = 0
- }
- urlIdx := 0
- segRetries := 0
- fullResets := 0
- var lastErr error
-
- for {
- if ctx.Err() != nil {
- return offset, "", ctx.Err()
- }
- if totalSize > 0 && offset == totalSize {
- break
- }
-
- targetURL := cleanURLs[urlIdx%len(cleanURLs)]
- endByte := offset + chunkSize - 1
- if totalSize > 0 && endByte >= totalSize {
- endByte = totalSize - 1
- }
-
- res, err := m.fetchSingleSegment(ctx, targetURL, partPath, offset, endByte, totalSize, t)
- if err == nil {
- offset = res.newOffset
- if res.totalSize > 0 {
- totalSize = res.totalSize
- }
- segRetries = 0
- if res.done || (totalSize > 0 && offset >= totalSize) {
- break
- }
- continue
- }
-
- lastErr = err
- errKind := bilibili.KindOf(err)
- httpStatus := 0
- if se, ok := err.(*bilibili.SiteError); ok {
- httpStatus = se.HTTPStatus
- }
-
- // Risk control (412 / -352 / -412) or rate limit (429): pause immediately without retry!
- if errKind == bilibili.ErrKindRiskControl || errKind == bilibili.ErrKindRateLimited || errKind == bilibili.ErrKindAuthRequired || errKind == bilibili.ErrKindSchemaChanged || isStorageError(err) {
- m.recordAttempt(t, relFile, offset, targetURL, segRetries+1, errKind, httpStatus)
- return offset, "", err
- }
-
- // Subsequent segment returned 200 OK instead of 206: truncate .part, rotate URL, and count towards 5-reset limit.
- if res.truncatedToZero {
- offset = 0
- totalSize = -1
- fullResets++
- urlIdx++
- m.recordAttempt(t, relFile, offset, targetURL, fullResets, bilibili.ErrKindNetwork, http.StatusOK)
- if fullResets >= 5 {
- t.Status = "paused"
- t.PauseReason = "network"
- t.ErrorKind = bilibili.ErrKindNetwork
- t.ErrorMessage = "已暂停(网络):节点不支持分段续传且重试已达上限"
- return offset, "", lastErr
- }
- continue
- }
-
- // Expired/forbidden URL (403, 404, 410): rotate through remaining candidate URLs once without sleeping.
- if errKind == bilibili.ErrKindForbidden || errKind == bilibili.ErrKindUnavailable {
- segRetries++
- urlIdx++
- m.recordAttempt(t, relFile, offset, targetURL, segRetries, errKind, httpStatus)
- if segRetries >= len(cleanURLs) {
- return offset, "", lastErr
- }
- continue
- }
-
- // Transport error (premature EOF, timeout, reset, 5xx): keep written bytes, retry up to 5 times with exponential backoff and URL rotation.
- offset = res.newOffset
- if res.totalSize > 0 {
- totalSize = res.totalSize
- }
- segRetries++
- urlIdx++
- m.recordAttempt(t, relFile, offset, targetURL, segRetries, errKind, httpStatus)
- if segRetries >= 5 {
- t.Status = "paused"
- t.PauseReason = "network"
- t.ErrorKind = bilibili.ErrKindNetwork
- t.ErrorMessage = "已暂停(网络):分段重试已达上限"
- return offset, "", lastErr
- }
-
- // Exponential backoff: 1, 2, 4, 8, 16 units
- backoffUnits := int64(1 << (segRetries - 1))
- if backoffUnits > 16 {
- backoffUnits = 16
- }
- sleepDur := time.Duration(backoffUnits) * backoffScale
- sleepDur = time.Duration(float64(sleepDur) * (0.8 + 0.4*jitterrand.Float64()))
- select {
- case <-ctx.Done():
- return offset, "", ctx.Err()
- case <-time.After(sleepDur):
- }
- }
-
- shaHex, actualSize, err := hashFileSHA256(partPath)
- if err != nil {
- return offset, "", err
- }
- if totalSize > 0 && actualSize != totalSize {
- return actualSize, "", &bilibili.SiteError{
- Kind: bilibili.ErrKindNetwork,
- Message: fmt.Sprintf("文件大小校验不一致: 实际 %d != 预期 %d", actualSize, totalSize),
- }
- }
-
- if err := os.Rename(partPath, finalPath); err != nil {
- return actualSize, "", err
- }
- for i := range t.Files {
- if taskFileIdentity(t.Files[i].Path) == taskFileIdentity(rel) {
- t.Files[i].DownloadedBytes, t.Files[i].TotalBytes = actualSize, actualSize
- t.Files[i].SHA256, t.Files[i].Status = shaHex, "completed"
- }
- }
- m.persistTaskProgress(*t)
- return actualSize, shaHex, nil
-}
-
-type segmentResult struct {
- newOffset int64
- totalSize int64
- done bool
- truncatedToZero bool
-}
-
-func (m *Manager) fetchSingleSegment(
- ctx context.Context,
- targetURL string,
- partPath string,
- offset int64,
- endByte int64,
- knownTotal int64,
- t *Task,
-) (segmentResult, error) {
- if err := m.client.ValidateMediaURL(targetURL); err != nil {
- return segmentResult{newOffset: offset}, err
- }
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil)
- if err != nil {
- return segmentResult{newOffset: offset}, err
- }
- req.Header.Set("User-Agent", bilibili.DefaultUserAgent)
- req.Header.Set("Referer", bilibili.DefaultReferer)
- req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, endByte))
-
- mediaClient, _ := m.client.MediaHTTPClient()
- resp, err := mediaClient.Do(req)
- if err != nil {
- return segmentResult{newOffset: offset}, &bilibili.SiteError{
- Kind: bilibili.ErrKindNetwork,
- Endpoint: targetURL,
- Message: "媒体下载连接失败",
- Err: err,
- }
- }
- defer resp.Body.Close()
-
- // Handle 416 Range Not Satisfiable when offset > 0 by truncating .part and restarting.
- if resp.StatusCode == http.StatusRequestedRangeNotSatisfiable && offset > 0 {
- _ = os.Truncate(partPath, 0)
- return segmentResult{newOffset: 0, truncatedToZero: true}, &bilibili.SiteError{
- Kind: bilibili.ErrKindNetwork,
- HTTPStatus: resp.StatusCode,
- Message: "Range 416,重置分段文件",
- }
- }
-
- if resp.StatusCode >= 400 {
- return segmentResult{newOffset: offset}, mapMediaHTTPStatus(resp.StatusCode, targetURL)
- }
- isImage := false
- relFile := taskRelativePath(t, strings.TrimSuffix(partPath, ".part"))
- for _, file := range t.Files {
- if taskFileIdentity(file.Path) == taskFileIdentity(relFile) && (file.Role == "image" || file.Role == "cover") {
- isImage = true
- break
- }
- }
- if isImage && !strings.HasPrefix(strings.ToLower(resp.Header.Get("Content-Type")), "image/") {
- return segmentResult{newOffset: offset}, &bilibili.SiteError{Kind: bilibili.ErrKindSchemaChanged, Message: "图片响应不是 image/*"}
- }
-
- var f *os.File
- var expectedSegLen int64 = -1
- totalSize := knownTotal
- doneAfterThis := false
-
- switch resp.StatusCode {
- case http.StatusPartialContent:
- cr := strings.TrimSpace(resp.Header.Get("Content-Range"))
- if cr != "" {
- start, end, total, ok := parseContentRange(cr)
- if !ok || start != offset || end < start || end > endByte || total <= end || (knownTotal > 0 && total != knownTotal) {
- return segmentResult{newOffset: offset}, &bilibili.SiteError{
- Kind: bilibili.ErrKindNetwork,
- Message: fmt.Sprintf("Content-Range 校验失败: %q (offset=%d, knownTotal=%d)", cr, offset, knownTotal),
- }
- }
- if total > 0 {
- totalSize = total
- }
- if end >= start {
- expectedSegLen = end - start + 1
- }
- if resp.ContentLength >= 0 && resp.ContentLength != expectedSegLen {
- return segmentResult{newOffset: offset}, &bilibili.SiteError{Kind: bilibili.ErrKindNetwork, Message: "分段 Content-Length 与区间长度不一致"}
- }
- if totalSize > 0 && end+1 >= totalSize {
- doneAfterThis = true
- }
- } else {
- return segmentResult{newOffset: offset}, &bilibili.SiteError{Kind: bilibili.ErrKindNetwork, Message: "206 响应缺少 Content-Range"}
- }
- f, err = os.OpenFile(partPath, os.O_CREATE|os.O_WRONLY, 0o600)
- if err == nil {
- _, err = f.Seek(offset, io.SeekStart)
- }
- case http.StatusOK:
- if offset > 0 {
- // Subsequent segment returned 200 OK instead of 206: truncate .part, rotate node, and retry from 0 (data-and-cache.md §2.4).
- _ = os.Remove(partPath)
- return segmentResult{newOffset: 0, truncatedToZero: true}, &bilibili.SiteError{
- Kind: bilibili.ErrKindNetwork,
- HTTPStatus: http.StatusOK,
- Message: "节点未返回 206 Partial Content,已截断从头重试",
- }
- }
- if resp.ContentLength <= 0 {
- return segmentResult{newOffset: offset}, &bilibili.SiteError{Kind: bilibili.ErrKindNetwork, Message: "完整响应缺少有效的 Content-Length"}
- }
- if resp.ContentLength > 0 {
- expectedSegLen = resp.ContentLength
- totalSize = resp.ContentLength
- }
- doneAfterThis = true
- f, err = os.OpenFile(partPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
- default:
- return segmentResult{newOffset: offset}, mapMediaHTTPStatus(resp.StatusCode, targetURL)
- }
- if isImage && totalSize > MaxImageFileBytes {
- if f != nil {
- _ = f.Close()
- }
- return segmentResult{newOffset: offset}, &bilibili.SiteError{Kind: bilibili.ErrKindSchemaChanged, Message: "图片超过 50 MiB"}
- }
- if err != nil {
- return segmentResult{newOffset: offset}, err
- }
-
- wrapped := m.client.WrapMediaReader(resp.Body)
- defer wrapped.Close()
- reader := io.LimitReader(wrapped, expectedSegLen+1)
-
- buf := make([]byte, 64*1024)
- var segWritten int64
- written := offset
- if totalSize > 0 {
- t.TotalBytes = totalSize
- } else if resp.ContentLength > 0 {
- t.TotalBytes = offset + resp.ContentLength
- }
-
- progressAt := time.Now()
- progressBytes := offset
- for {
- nr, rErr := reader.Read(buf)
- if nr > 0 {
- if segWritten+int64(nr) > expectedSegLen {
- _ = f.Close()
- if err := os.Truncate(partPath, offset); err != nil {
- return segmentResult{newOffset: offset}, err
- }
- return segmentResult{newOffset: offset, totalSize: totalSize}, &bilibili.SiteError{Kind: bilibili.ErrKindNetwork, Message: "分段正文超出声明区间"}
- }
- nw, wErr := f.Write(buf[:nr])
- if wErr != nil {
- _ = f.Close()
- return segmentResult{newOffset: written, totalSize: totalSize}, wErr
- }
- segWritten += int64(nw)
- written += int64(nw)
- t.BytesDownloaded = written
- if t.TotalBytes > 0 {
- t.Progress = float64(written) / float64(t.TotalBytes)
- if t.Progress > 0.99 {
- t.Progress = 0.99
- }
- }
- }
- if elapsed := time.Since(progressAt); elapsed >= 250*time.Millisecond {
- speed := int64(float64(written-progressBytes) / elapsed.Seconds())
- for i := range t.Files {
- if taskFileIdentity(t.Files[i].Path) == taskFileIdentity(relFile) {
- t.Files[i].DownloadedBytes = written
- t.Files[i].TotalBytes = t.TotalBytes
- t.Files[i].SpeedBps = speed
- t.Files[i].Status = "downloading"
- }
- }
- m.persistTaskProgress(*t)
- progressAt = time.Now()
- progressBytes = written
- }
-
- if rErr != nil {
- if rErr == io.EOF {
- break
- }
- _ = f.Sync()
- _ = f.Close()
- return segmentResult{newOffset: written, totalSize: totalSize}, &bilibili.SiteError{
- Kind: bilibili.ErrKindNetwork,
- Endpoint: targetURL,
- Message: "媒体分段读取中断",
- Err: rErr,
- }
- }
- }
-
- if err := f.Sync(); err != nil {
- _ = f.Close()
- return segmentResult{newOffset: written, totalSize: totalSize}, err
- }
- if err := f.Close(); err != nil {
- return segmentResult{newOffset: written, totalSize: totalSize}, err
- }
-
- if expectedSegLen >= 0 && segWritten != expectedSegLen {
- return segmentResult{newOffset: written, totalSize: totalSize}, &bilibili.SiteError{
- Kind: bilibili.ErrKindNetwork,
- Endpoint: targetURL,
- Message: fmt.Sprintf("分段字节未读满: 实读 %d < 预期 %d", segWritten, expectedSegLen),
- }
- }
-
- return segmentResult{
- newOffset: written,
- totalSize: totalSize,
- done: doneAfterThis,
- }, nil
-}
-
-func parseContentRange(cr string) (start, end, total int64, ok bool) {
- cr = strings.TrimSpace(cr)
- if !strings.HasPrefix(strings.ToLower(cr), "bytes ") {
- return 0, 0, 0, false
- }
- rest := strings.TrimSpace(cr[6:])
- slashIdx := strings.IndexByte(rest, '/')
- if slashIdx <= 0 {
- return 0, 0, 0, false
- }
- rangePart := rest[:slashIdx]
- totalPart := rest[slashIdx+1:]
- dashIdx := strings.IndexByte(rangePart, '-')
- if dashIdx <= 0 {
- return 0, 0, 0, false
- }
- sVal, err1 := strconv.ParseInt(strings.TrimSpace(rangePart[:dashIdx]), 10, 64)
- eVal, err2 := strconv.ParseInt(strings.TrimSpace(rangePart[dashIdx+1:]), 10, 64)
- if err1 != nil || err2 != nil || sVal < 0 || eVal < sVal {
- return 0, 0, 0, false
- }
- var tVal int64 = -1
- if totalPart != "*" {
- parsedTotal, err3 := strconv.ParseInt(strings.TrimSpace(totalPart), 10, 64)
- if err3 != nil || parsedTotal <= 0 {
- return 0, 0, 0, false
- }
- tVal = parsedTotal
- }
- return sVal, eVal, tVal, true
-}
-
-func mapMediaHTTPStatus(status int, endpoint string) *bilibili.SiteError {
- switch status {
- case 401:
- return &bilibili.SiteError{Kind: bilibili.ErrKindAuthRequired, HTTPStatus: status, Endpoint: endpoint, Message: "媒体需要登录凭证 (401)"}
- case 403:
- return &bilibili.SiteError{Kind: bilibili.ErrKindForbidden, HTTPStatus: status, Endpoint: endpoint, Message: "媒体访问被拒绝 (403)"}
- case 404, 410:
- return &bilibili.SiteError{Kind: bilibili.ErrKindUnavailable, HTTPStatus: status, Endpoint: endpoint, Message: fmt.Sprintf("媒体资源已失效 (%d)", status)}
- case 412:
- return &bilibili.SiteError{Kind: bilibili.ErrKindRiskControl, HTTPStatus: status, Endpoint: endpoint, Message: "媒体请求触发风控 (412)"}
- case 429:
- return &bilibili.SiteError{Kind: bilibili.ErrKindRateLimited, HTTPStatus: status, Endpoint: endpoint, Message: "媒体请求触发限流 (429)"}
- default:
- return &bilibili.SiteError{Kind: bilibili.ErrKindNetwork, HTTPStatus: status, Endpoint: endpoint, Message: fmt.Sprintf("媒体 HTTP 状态异常 (%d)", status)}
- }
-}
-
-func (m *Manager) saveTaskProgress(t Task) error {
- if t.ProgressOwner != nil {
- owner := t.ProgressOwner
- for _, file := range t.Files {
- file.Path = t.ProgressPrefix + file.Path
- file.ItemDir = t.ItemDir
- found := false
- for i := range owner.Files {
- if owner.Files[i].Path == file.Path {
- owner.Files[i], found = file, true
- break
- }
- }
- if !found {
- owner.Files = append(owner.Files, file)
- }
- }
- owner.Attempts = t.Attempts
- return m.saveTaskProgress(*owner)
- }
- now := time.Now().UTC().Format(time.RFC3339)
- t.UpdatedAt = now
- if t.ErrorMessage == "" && t.LastError != "" {
- t.ErrorMessage = t.LastError
- }
- t.LastError = t.ErrorMessage
- filesJSON, _ := json.Marshal(t.Files)
- attemptsJSON, _ := json.Marshal(t.Attempts)
- res, err := m.db.Exec(`
- UPDATE download_tasks
- SET
- cid = ?, page = ?, title = ?, part_title = ?,
- mid = ?, author_uid = ?, author_name = ?, author_face = ?, cover_url = ?,
- status = ?, pause_reason = ?, error_kind = ?, error_message = ?, quality_hint = ?,
- bytes_downloaded = ?, total_bytes = ?, progress = ?,
- item_key = ?, item_dir = ?, files_json = ?, attempts_json = ?, updated_at = ?
- WHERE task_id = ? AND status = 'running'
- `,
- t.CID, t.Page, t.Title, t.PartTitle,
- t.Mid, t.AuthorUID, t.AuthorName, t.AuthorFace, t.CoverURL,
- t.Status, t.PauseReason, t.ErrorKind, t.ErrorMessage, t.QualityHint,
- t.BytesDownloaded, t.TotalBytes, t.Progress,
- t.ItemKey, t.ItemDir, string(filesJSON), string(attemptsJSON), t.UpdatedAt,
- t.TaskID,
- )
- if err != nil {
- return err
- }
- if changed, _ := res.RowsAffected(); changed == 0 {
- return nil
- }
- m.taskFaults.Delete(t.TaskID)
- m.emitUpdate(t)
- return nil
-}
-
-func (m *Manager) emitUpdate(t Task) {
- if t.ErrorMessage == "" && t.LastError != "" {
- t.ErrorMessage = t.LastError
- }
- t.LastError = t.ErrorMessage
- if m.onTaskUpdate != nil && t.TaskID != "" {
- m.notifyMu.Lock()
- if m.lastNotify == nil {
- m.lastNotify = make(map[string]taskNotification)
- }
- previous := m.lastNotify[t.TaskID]
- if previous.status == t.Status && t.Status == "running" && time.Since(previous.at) < time.Second {
- m.notifyMu.Unlock()
- return
- }
- m.lastNotify[t.TaskID] = taskNotification{status: t.Status, at: time.Now()}
- m.notifyMu.Unlock()
- m.onTaskUpdate(t)
- }
-}
-
-type taskNotification struct {
- status string
- at time.Time
-}
-
-func (m *Manager) persistTaskProgress(task Task) {
- if err := m.saveTaskProgress(task); err != nil {
- task.Status, task.ErrorKind, task.ErrorMessage = "failed", "storage", "任务状态写入失败,请检查存储后重试"
- m.taskFaults.Store(task.TaskID, task)
- m.emitUpdate(task)
- }
-}
-
-func (m *Manager) withTaskFault(task Task) Task {
- if fault, exists := m.taskFaults.Load(task.TaskID); exists {
- return fault.(Task)
- }
- return task
-}
-
-// Register task ownership before creating any file. A pre-existing name with
-// no task checkpoint or manifest is a user file, and must never be replaced.
-func (m *Manager) claimTaskFile(t *Task, root, rel, finalPath string) error {
- owned := false
- for _, file := range t.Files {
- if taskFileIdentity(file.Path) == taskFileIdentity(rel) && taskFileOwned(file) {
- owned = true
- }
- }
- if t.ProgressOwner != nil {
- for _, file := range t.ProgressOwner.Files {
- if taskFileIdentity(file.Path) == taskFileIdentity(t.ProgressPrefix+rel) && strings.EqualFold(file.ItemDir, root) && taskFileOwned(file) {
- owned = true
- }
- }
- }
- if m.lib != nil {
- if meta, ok, err := m.lib.GetItem(t.ItemKey); err != nil {
- return err
- } else if ok && strings.EqualFold(meta.ItemDir, root) {
- for _, file := range meta.Media {
- if taskFileIdentity(file.Path) == taskFileIdentity(rel) {
- owned = true
- }
- }
- }
- }
- if !owned {
- for _, path := range []string{finalPath, finalPath + ".part"} {
- if _, err := os.Lstat(path); err == nil {
- return &bilibili.SiteError{Kind: "storage", Message: "目标文件已存在且未由本任务登记,已保留原文件"}
- } else if !os.IsNotExist(err) {
- return err
- }
- }
- }
- found := false
- for i := range t.Files {
- if taskFileIdentity(t.Files[i].Path) == taskFileIdentity(rel) {
- t.Files[i].Owned = true
- found = true
- }
- }
- if !found {
- t.Files = append(t.Files, TaskFileProgress{Path: rel, Status: "waiting", Owned: true})
- }
- return m.saveTaskProgress(*t)
-}
-
-func taskFileIdentity(rel string) string {
- return strings.TrimSuffix(filepath.ToSlash(rel), ".part")
-}
-
-func taskFileOwned(file TaskFileProgress) bool {
- // Pre-ownership task records can prove a written file through a durable
- // length checkpoint or hash. A waiting filename alone grants no ownership.
- return file.Owned || file.SHA256 != "" || file.DownloadedBytes > 0 && file.TotalBytes >= file.DownloadedBytes
-}
-
-func taskRelativePath(task *Task, filePath string) string {
- if task.ItemDir != "" {
- if rel, err := filepath.Rel(task.ItemDir, filePath); err == nil {
- return filepath.ToSlash(rel)
- }
- }
- return filepath.Base(filePath)
-}
-
-type rowScanner interface {
- Scan(dest ...any) error
-}
-
-func scanTask(r rowScanner) (Task, error) {
- var t Task
- var linkedInt int
- var filesRaw, attemptsRaw string
- err := r.Scan(
- &t.TaskID, &t.Site, &t.Kind, &t.Source, &t.TargetID, &t.CID, &t.Page, &t.Title, &t.PartTitle,
- &t.Mid, &t.AuthorUID, &t.AuthorName, &t.AuthorFace, &t.CoverURL, &linkedInt,
- &t.Status, &t.PauseReason, &t.ErrorKind, &t.ErrorMessage, &t.QualityHint,
- &t.BytesDownloaded, &t.TotalBytes, &t.Progress, &t.ItemKey, &t.ItemDir,
- &filesRaw, &attemptsRaw, &t.CreatedAt, &t.UpdatedAt,
- )
- t.LastError = t.ErrorMessage
- t.CacheLinkedVideos = linkedInt == 1
- if filesRaw != "" {
- _ = json.Unmarshal([]byte(filesRaw), &t.Files)
- }
- if attemptsRaw != "" {
- _ = json.Unmarshal([]byte(attemptsRaw), &t.Attempts)
- }
- return t, err
-}
-
-func hashFileSHA256(filePath string) (string, int64, error) {
- f, err := os.Open(filePath)
- if err != nil {
- return "", 0, err
- }
- defer f.Close()
- h := sha256.New()
- n, err := io.Copy(h, f)
- if err != nil {
- return "", 0, err
- }
- return hex.EncodeToString(h.Sum(nil)), n, nil
-}
-
-// motionRelName is where the motion clip of a dynamic's idx-th live photo
-// (实况) is kept, next to its still.
-func motionRelName(idx int, rawURL string) string {
- ext := ".mp4"
- if u, err := url.Parse(rawURL); err == nil {
- switch e := strings.ToLower(path.Ext(u.Path)); e {
- case ".mp4", ".mov", ".m4v":
- ext = e
- }
- }
- return fmt.Sprintf("images/%02d_live%s", idx+1, ext)
-}
-
-// cacheLiveMotion keeps the motion clip of a live photo with its still. A
-// clip that fails to download leaves the post partial, as any other missing
-// file does; stop, storage and cancel errors end the task.
-func (m *Manager) cacheLiveMotion(ctx context.Context, t *Task, itemDir string, previous library.ItemMetadata, exists bool, idx int, liveURL string, partialErrors *[]string) (*library.MediaFile, error) {
- if liveURL == "" {
- return nil, nil
- }
- relName := motionRelName(idx, liveURL)
- if exists {
- for _, media := range previous.Media {
- if media.Role == "motion" && media.Source == liveURL {
- relName = media.Path
- break
- }
- }
- }
- if mediaIsValid(previous, relName) {
- for _, media := range previous.Media {
- if media.Path == relName {
- m.setFileProgress(t, "motion", relName, "completed", media.Bytes, media.Bytes, 0)
- file := media
- return &file, nil
- }
- }
- }
- m.setFileProgress(t, "motion", relName, "downloading", 0, 0, 0)
- n, sha, err := m.downloadFileWithRange(ctx, []string{liveURL}, filepath.Join(itemDir, relName), t)
- if err != nil {
- m.setFileProgress(t, "motion", relName, "failed", 0, 0, 0)
- if isStopError(err) || isStorageError(err) || ctx.Err() != nil {
- return nil, err
- }
- *partialErrors = append(*partialErrors, fmt.Sprintf("img_%02d 实况: %v", idx+1, err))
- return nil, nil
- }
- // Keep the clip a plain progressive MP4 with moov ahead of mdat, so system
- // players preview it too (DEC-046 ①); a fragmented or broken clip is
- // removed and leaves the post partial.
- if strings.EqualFold(path.Ext(relName), ".mp4") || strings.EqualFold(path.Ext(relName), ".m4v") {
- full := filepath.Join(itemDir, relName)
- summary, vErr := EnsureSingleMP4Context(ctx, full, 0)
- if vErr != nil {
- if ctx.Err() != nil {
- return nil, ctx.Err()
- }
- _ = os.Remove(full)
- m.setFileProgress(t, "motion", relName, "failed", 0, 0, 0)
- *partialErrors = append(*partialErrors, fmt.Sprintf("img_%02d 实况: %v", idx+1, vErr))
- return nil, nil
- }
- n, sha = summary.FileBytes, summary.SHA256
- m.setFileProgress(t, "motion", relName, "completed", n, n, 0)
- return &library.MediaFile{Role: "motion", Path: relName, Bytes: n, SHA256: sha, Source: liveURL,
- Width: summary.Width, Height: summary.Height, Duration: int(summary.DurationSec + 0.5)}, nil
- }
- m.setFileProgress(t, "motion", relName, "completed", n, n, 0)
- return &library.MediaFile{Role: "motion", Path: relName, Bytes: n, SHA256: sha, Source: liveURL}, nil
-}
-
-func guessImageExt(rawURL string) string {
- u, err := url.Parse(rawURL)
- if err == nil && u.Path != "" {
- ext := strings.ToLower(path.Ext(u.Path))
- switch ext {
- case ".jpg", ".jpeg", ".png", ".webp", ".gif", ".avif":
- return ext
- }
- }
- return ".jpg"
-}
-
-func isTempStagingPath(rel string) bool {
- return strings.HasSuffix(rel, ".raw") || strings.HasSuffix(rel, ".imgtmp") || strings.HasSuffix(rel, ".audtmp")
-}
-
-func cleanTaskPartFiles(t Task) {
- if t.ItemDir == "" {
- return
- }
- for _, file := range t.Files {
- if !taskFileOwned(file) || file.Status == "completed" || file.Status == "skipped" {
- continue
- }
- root, rel := t.ItemDir, file.Path
- if file.ItemDir != "" {
- root, rel = file.ItemDir, filepath.Base(file.Path)
- }
- rel = taskFileIdentity(rel)
- candidates := []string{rel + ".part", rel + ".part.part", rel + ".raw", rel + ".raw.part"}
- if isTempStagingPath(rel) {
- candidates = append(candidates, rel)
- }
- for _, pending := range candidates {
- partPath, err := library.ResolveItemPath(root, pending)
- if err == nil {
- _ = os.Remove(partPath)
- }
- }
- }
-}
-
-func mergePartRecords(existing []library.VideoPartRecord, added library.VideoPartRecord) []library.VideoPartRecord {
- out := make([]library.VideoPartRecord, 0, len(existing)+1)
- replaced := false
- for _, p := range existing {
- if p.Page == added.Page || (p.CID > 0 && p.CID == added.CID) {
- out = append(out, added)
- replaced = true
- } else {
- out = append(out, p)
- }
- }
- if !replaced {
- out = append(out, added)
- }
- return out
-}
-
-func mergeMediaFiles(existing []library.MediaFile, added []library.MediaFile) []library.MediaFile {
- byPath := make(map[string]library.MediaFile, len(existing)+len(added))
- var order []string
- for _, m := range existing {
- byPath[m.Path] = m
- order = append(order, m.Path)
- }
- for _, m := range added {
- if _, seen := byPath[m.Path]; !seen {
- order = append(order, m.Path)
- }
- byPath[m.Path] = m
- }
- out := make([]library.MediaFile, 0, len(order))
- for _, p := range order {
- out = append(out, byPath[p])
- }
- return out
-}
-
-func audioRank(id int) int {
- switch id {
- case 30251:
- return 5
- case 30250:
- return 4
- case 30280:
- return 3
- case 30232:
- return 2
- case 30216:
- return 1
- }
- return 0
-}
-
-func isStopError(err error) bool {
- return bilibili.IsKind(err, bilibili.ErrKindRiskControl) || bilibili.IsKind(err, bilibili.ErrKindRateLimited) || bilibili.IsKind(err, bilibili.ErrKindAuthRequired)
-}
-
-func isStorageError(err error) bool {
- var pathErr *os.PathError
- return errors.As(err, &pathErr) || bilibili.IsKind(err, "storage")
-}
-
-func targetQuality(quality string) int {
- switch quality {
- case "2160":
- return 120
- case "1080":
- return 112
- case "720":
- return 74
- }
- return 127
-}
-
-func dedupeDynamicImages(in []bilibili.DynamicMedia) []bilibili.DynamicMedia {
- seen := make(map[string]bool, len(in))
- out := in[:0:0]
- for _, img := range in {
- if img.URL != "" && seen[img.URL] {
- continue
- }
- seen[img.URL] = true
- out = append(out, img)
- }
- return out
-}
-
-func dedupeDynamicVideos(in []bilibili.DynamicVideoRef) []bilibili.DynamicVideoRef {
- seen := make(map[string]bool, len(in))
- out := in[:0:0]
- for _, v := range in {
- if v.BVID != "" && seen[v.BVID] {
- continue
- }
- seen[v.BVID] = true
- out = append(out, v)
+ m.emitTasksByID(ids)
}
- return out
}
diff --git a/internal/download/moved_files_test.go b/internal/download/moved_files_test.go
new file mode 100644
index 0000000..5c7b292
--- /dev/null
+++ b/internal/download/moved_files_test.go
@@ -0,0 +1,278 @@
+package download
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// The user's own `rclone move` takes a finished part and
+// item.json away while the next part is still downloading. The task still
+// completes, the moved part is not downloaded again, and the final
+// item.json lists every part.
+func TestCachingContinuesWhenFinishedFilesAreMovedAway(t *testing.T) {
+ vBytes, err := BuildSyntheticVideoM4S(30, 30)
+ if err != nil {
+ t.Fatal(err)
+ }
+ aBytes, err := BuildSyntheticAudioM4S(47)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var srvURL string
+ var firstTask atomic.Value // func() string: P1's item folder
+ var videoHits [3]atomic.Int32
+ var moved atomic.Bool
+ mux := http.NewServeMux()
+ mux.HandleFunc("/x/web-interface/wbi/view", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
+ "bvid": "BV1Mv411w7KC", "aid": 170002, "title": "两P合成视频", "pic": srvURL + "/media/cover.jpg", "pubdate": 1700000000, "duration": 2,
+ "owner": map[string]any{"mid": 888, "name": "Creator888"},
+ "pages": []map[string]any{
+ {"cid": 6001, "page": 1, "part": "P1", "duration": 1, "dimension": map[string]any{"width": 16, "height": 16}},
+ {"cid": 6002, "page": 2, "part": "P2", "duration": 1, "dimension": map[string]any{"width": 16, "height": 16}},
+ },
+ }})
+ })
+ mux.HandleFunc("/x/player/wbi/playurl", func(w http.ResponseWriter, r *http.Request) {
+ cid := r.URL.Query().Get("cid")
+ if cid == "6002" && !moved.Load() {
+ // P1 is finished: move it and item.json away like rclone move.
+ if fn, ok := firstTask.Load().(func() string); ok && fn() != "" {
+ dir := fn()
+ _ = os.Remove(filepath.Join(dir, "P01.mp4"))
+ _ = os.Remove(filepath.Join(dir, "item.json"))
+ moved.Store(true)
+ }
+ }
+ _ = 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": 1,
+ "video": []map[string]any{{"id": 80, "baseUrl": srvURL + "/media/video.m4s?cid=" + cid, "codecid": 7, "codecs": "avc1.42c00a", "width": 16, "height": 16, "frameRate": "30.0", "bandwidth": 500000}},
+ "audio": []map[string]any{{"id": 30280, "baseUrl": srvURL + "/media/audio.m4s", "codecs": "mp4a.40.2", "bandwidth": 192000}},
+ },
+ }})
+ })
+ mux.HandleFunc("/media/cover.jpg", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "image/jpeg")
+ _, _ = w.Write([]byte("fake-jpeg-cover-bytes"))
+ })
+ mux.HandleFunc("/media/video.m4s", func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Query().Get("cid") {
+ case "6001":
+ videoHits[1].Add(1)
+ case "6002":
+ videoHits[2].Add(1)
+ }
+ w.Header().Set("Content-Length", strconv.Itoa(len(vBytes)))
+ _, _ = w.Write(vBytes)
+ })
+ mux.HandleFunc("/media/audio.m4s", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Length", strconv.Itoa(len(aBytes)))
+ _, _ = w.Write(aBytes)
+ })
+
+ mgr, lib, srv := setupDownloadEnv(t, mux, 1)
+ srvURL = srv.URL
+ checkNames := watchNames(t, lib.CacheDir())
+ cfg := mgr.dlSettings
+ cfg.SaveDanmaku, cfg.SaveSubtitles = false, false
+ mgr.UpdateSettings(cfg)
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+ if err := mgr.Start(ctx); err != nil {
+ t.Fatal(err)
+ }
+ defer mgr.Stop()
+ tasks, err := mgr.EnqueueVideo(ctx, VideoEnqueueRequest{BVID: "BV1Mv411w7KC"})
+ if err != nil || len(tasks) != 2 {
+ t.Fatalf("EnqueueVideo = %+v, %v", tasks, err)
+ }
+ firstTask.Store(func() string {
+ if tk, ok, _ := mgr.GetTask(tasks[0].TaskID); ok && tk.Status == "completed" {
+ return tk.ItemDir
+ }
+ return ""
+ })
+ waitForTaskStatus(t, mgr, tasks[0].TaskID, "completed", 10*time.Second)
+ done := waitForTaskStatus(t, mgr, tasks[1].TaskID, "completed", 10*time.Second)
+ if !moved.Load() {
+ t.Fatal("the test did not move P01 away during the download")
+ }
+ checkNames("P01.mp4", "item.json")
+ if n := videoHits[1].Load(); n != 1 {
+ t.Fatalf("P01 was downloaded %d times, want 1", n)
+ }
+ if _, err := os.Stat(filepath.Join(done.ItemDir, "P02.mp4")); err != nil {
+ t.Fatalf("P02.mp4: %v", err)
+ }
+ raw, err := os.ReadFile(filepath.Join(done.ItemDir, "item.json"))
+ if err != nil {
+ t.Fatalf("item.json was not written again after the move: %v", err)
+ }
+ var meta struct {
+ Parts []struct {
+ Page int `json:"page"`
+ File string `json:"file"`
+ } `json:"parts"`
+ }
+ _ = json.Unmarshal(raw, &meta)
+ if len(meta.Parts) != 2 {
+ t.Fatalf("item.json parts = %+v, want both parts listed", meta.Parts)
+ }
+}
+
+// A DASH stream paused by an older version under its old
+// name (P01.video-….m4s.part) resumes from its offset under the temporary
+// name, and no old name is left.
+func TestLegacyStreamPartResumesUnderTemporaryName(t *testing.T) {
+ vBytes, err := BuildSyntheticVideoM4S(60, 30)
+ if err != nil {
+ t.Fatal(err)
+ }
+ aBytes, err := BuildSyntheticAudioM4S(94)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var srvURL string
+ var hold atomic.Bool
+ hold.Store(true)
+ release := make(chan struct{})
+ var resumedFrom atomic.Int64
+ resumedFrom.Store(-1)
+ mux := http.NewServeMux()
+ mux.HandleFunc("/x/web-interface/wbi/view", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
+ "bvid": "BV1Lg411w7KC", "aid": 170003, "title": "旧名续传", "pic": srvURL + "/media/cover.jpg", "pubdate": 1700000000, "duration": 2,
+ "owner": map[string]any{"mid": 888, "name": "Creator888"},
+ "pages": []map[string]any{{"cid": 7001, "page": 1, "part": "P1", "duration": 2, "dimension": map[string]any{"width": 16, "height": 16}}},
+ }})
+ })
+ mux.HandleFunc("/x/player/wbi/playurl", func(w http.ResponseWriter, r *http.Request) {
+ _ = 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": 2,
+ "video": []map[string]any{{"id": 80, "baseUrl": srvURL + "/media/video.m4s", "codecid": 7, "codecs": "avc1.42c00a", "width": 16, "height": 16, "frameRate": "30.0", "bandwidth": 500000}},
+ "audio": []map[string]any{{"id": 30280, "baseUrl": srvURL + "/media/audio.m4s", "codecs": "mp4a.40.2", "bandwidth": 192000}},
+ },
+ }})
+ })
+ mux.HandleFunc("/media/cover.jpg", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "image/jpeg")
+ _, _ = w.Write([]byte("fake-jpeg-cover-bytes"))
+ })
+ half := len(vBytes) / 2
+ mux.HandleFunc("/media/video.m4s", func(w http.ResponseWriter, r *http.Request) {
+ start := 0
+ if rh := r.Header.Get("Range"); rh != "" {
+ _, _ = fmt.Sscanf(rh, "bytes=%d-", &start)
+ }
+ if hold.Load() {
+ // Serve the first half, then stall until the test pauses.
+ w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, len(vBytes)-1, len(vBytes)))
+ w.Header().Set("Content-Length", strconv.Itoa(len(vBytes)-start))
+ w.WriteHeader(http.StatusPartialContent)
+ _, _ = w.Write(vBytes[start:half])
+ if fl, ok := w.(http.Flusher); ok {
+ fl.Flush()
+ }
+ select {
+ case <-release:
+ case <-r.Context().Done():
+ }
+ return
+ }
+ resumedFrom.CompareAndSwap(-1, int64(start))
+ w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, len(vBytes)-1, len(vBytes)))
+ w.Header().Set("Content-Length", strconv.Itoa(len(vBytes)-start))
+ w.WriteHeader(http.StatusPartialContent)
+ _, _ = w.Write(vBytes[start:])
+ })
+ mux.HandleFunc("/media/audio.m4s", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Length", strconv.Itoa(len(aBytes)))
+ _, _ = w.Write(aBytes)
+ })
+ mgr, _, srv := setupDownloadEnv(t, mux, 1)
+ srvURL = srv.URL
+ cfg := mgr.dlSettings
+ cfg.SaveDanmaku, cfg.SaveSubtitles = false, false
+ mgr.UpdateSettings(cfg)
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+ if err := mgr.Start(ctx); err != nil {
+ t.Fatal(err)
+ }
+ defer mgr.Stop()
+ defer close(release)
+ tasks, err := mgr.EnqueueVideo(ctx, VideoEnqueueRequest{BVID: "BV1Lg411w7KC"})
+ if err != nil || len(tasks) != 1 {
+ t.Fatalf("EnqueueVideo = %+v, %v", tasks, err)
+ }
+ const newRel = ".trace-P01.video-80-7.m4s"
+ const oldRel = "P01.video-80-7.m4s"
+ var itemDir string
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ tk, _, _ := mgr.GetTask(tasks[0].TaskID)
+ if tk.ItemDir != "" {
+ if st, err := os.Stat(filepath.Join(tk.ItemDir, newRel+".part")); err == nil && st.Size() >= int64(half) {
+ itemDir = tk.ItemDir
+ break
+ }
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("the stream never reached half")
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ if _, err := mgr.Pause(tasks[0].TaskID); err != nil {
+ t.Fatal(err)
+ }
+ waitForTaskStatus(t, mgr, tasks[0].TaskID, "paused", 5*time.Second)
+
+ // Turn the paused state into what an older version left behind.
+ // (Windows: the paused download may close the file a moment later.)
+ for i := 0; ; i++ {
+ err := os.Rename(filepath.Join(itemDir, newRel+".part"), filepath.Join(itemDir, oldRel+".part"))
+ if err == nil {
+ break
+ }
+ if i > 200 {
+ t.Fatal(err)
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ tk, _, _ := mgr.GetTask(tasks[0].TaskID)
+ for i := range tk.Files {
+ if taskFileIdentity(tk.Files[i].Path) == newRel {
+ tk.Files[i].Path = oldRel
+ }
+ }
+ filesJSON, _ := json.Marshal(tk.Files)
+ if _, err := mgr.db.Exec(`UPDATE download_tasks SET files_json = ? WHERE task_id = ?`, string(filesJSON), tk.TaskID); err != nil {
+ t.Fatal(err)
+ }
+
+ hold.Store(false)
+ if _, err := mgr.Resume(tasks[0].TaskID); err != nil {
+ t.Fatal(err)
+ }
+ waitForTaskStatus(t, mgr, tasks[0].TaskID, "completed", 10*time.Second)
+ if got := resumedFrom.Load(); got < int64(half) {
+ t.Fatalf("resumed from byte %d, want at least %d (the old .part was not adopted)", got, half)
+ }
+ entries, _ := os.ReadDir(itemDir)
+ for _, e := range entries {
+ if strings.Contains(e.Name(), ".m4s") {
+ t.Fatalf("a stream file is left after the MP4: %s", e.Name())
+ }
+ }
+}
diff --git a/internal/download/music_redirect_test.go b/internal/download/music_redirect_test.go
new file mode 100644
index 0000000..c621672
--- /dev/null
+++ b/internal/download/music_redirect_test.go
@@ -0,0 +1,297 @@
+package download
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/chialecode/trace/internal/site"
+)
+
+// A media redirect leaves the allowed domains only when the transport
+// allows public redirects (Douyin music): then any public HTTPS name on
+// port 443 is followed, while plain HTTP, IP literals and local names stay
+// refused. Other media keep the allow list.
+func TestMediaRedirectsFollowPublicHostsOnlyWhenAllowed(t *testing.T) {
+ hop := func(spec site.MediaTransportSpec, target string) error {
+ t.Helper()
+ client := newTransportHTTPClient(spec)
+ first, _ := http.NewRequest(http.MethodGet, "https://lf9-music-east.douyinstatic.com/obj/ies-music/synthetic.mp3", nil)
+ next, err := http.NewRequest(http.MethodGet, target, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return client.CheckRedirect(next, []*http.Request{first})
+ }
+ vod := site.DouyinVODTransport("", false)
+ music := vod
+ music.PublicRedirects = true
+
+ if err := hop(vod, "https://edge.example-cdn.net/a.mp3"); site.KindOf(err) != site.ErrKindBlocked {
+ t.Fatalf("VOD redirect off the allow list = %v, want blocked", err)
+ }
+ if err := hop(music, "https://edge.example-cdn.net/a.mp3"); err != nil {
+ t.Fatalf("music redirect to a public HTTPS host = %v, want followed", err)
+ }
+ for _, target := range []string{"http://edge.example-cdn.net/a.mp3", "https://203.0.113.7/a.mp3", "https://cdn.local/a.mp3", "https://edge.example-cdn.net:8443/a.mp3"} {
+ if err := hop(music, target); site.KindOf(err) != site.ErrKindBlocked {
+ t.Errorf("music redirect to %s = %v, want blocked", target, err)
+ }
+ }
+}
+
+// The missing-music reason names the class and the site error's words.
+func TestMusicFailureReasonNamesTheCause(t *testing.T) {
+ err := &site.Error{Site: site.Douyin, Kind: site.ErrKindBlocked, Message: "媒体域名不在允许列表中: edge.example-cdn.net"}
+ got := musicFailureReason(err)
+ if got != "配乐下载失败 (blocked):媒体域名不在允许列表中: edge.example-cdn.net" {
+ t.Fatalf("reason = %q", got)
+ }
+ if got := musicFailureReason(errors.New("plain")); strings.Contains(got, ":") {
+ t.Fatalf("reason for a plain error = %q", got)
+ }
+}
+
+func TestDouyinBytednsdocMusicHostAllowed(t *testing.T) {
+ vod := site.DouyinVODTransport("", false)
+ if err := vod.ValidateURL("https://lf3-static.bytednsdoc.com/obj/eden-cn/synthetic/no_sound.mp3"); err != nil {
+ t.Fatalf("bytednsdoc.com HTTPS music URL rejected: %v", err)
+ }
+ for _, bad := range []string{
+ "http://lf3-static.bytednsdoc.com/obj/eden-cn/no_sound.mp3",
+ "https://lf3-static.bytednsdoc.com:8443/obj/eden-cn/no_sound.mp3",
+ "https://203.0.113.10/no_sound.mp3",
+ "https://unlisted.example.net/no_sound.mp3",
+ } {
+ if err := vod.ValidateURL(bad); site.KindOf(err) != site.ErrKindBlocked {
+ t.Errorf("ValidateURL(%q) = %v, want blocked", bad, err)
+ }
+ }
+}
+
+type playRedirectingPlanner struct {
+ *fakeDouyinWorkPlanner
+ resolve func(ctx context.Context, playURL string) (string, error)
+}
+
+func (p *playRedirectingPlanner) ResolvePlayRedirect(ctx context.Context, playURL string) (string, error) {
+ return p.resolve(ctx, playURL)
+}
+
+func TestDouyinNeedSetTokenPlayRedirectFallbackAndPartialReason(t *testing.T) {
+ mp4Bytes := buildProgressiveWithoutElst(t, true, true, 0)
+ coverJPEG := syntheticJPEGMini()
+ musicMP3 := syntheticMP3Mini()
+
+ var direct403Hits atomic.Int32
+ var resolverHits atomic.Int32
+ var cdnCookieLeaks atomic.Int32
+ var edgeRedirectHits atomic.Int32
+
+ mux := http.NewServeMux()
+ checkNoCookie := func(r *http.Request) {
+ if r.Header.Get("Cookie") != "" {
+ cdnCookieLeaks.Add(1)
+ }
+ }
+ mux.HandleFunc("/cdn/cover.jpg", func(w http.ResponseWriter, r *http.Request) {
+ checkNoCookie(r)
+ w.Header().Set("Content-Type", "image/jpeg")
+ _, _ = w.Write(coverJPEG)
+ })
+ mux.HandleFunc("/cdn/music.mp3", func(w http.ResponseWriter, r *http.Request) {
+ checkNoCookie(r)
+ w.Header().Set("Content-Type", "audio/mpeg")
+ serveRangeBytes(w, r, musicMP3, "audio/mpeg", 0, nil)
+ })
+ mux.HandleFunc("/cdn/music-missing.mp3", func(w http.ResponseWriter, r *http.Request) {
+ checkNoCookie(r)
+ w.WriteHeader(http.StatusNotFound)
+ })
+ mux.HandleFunc("/cdn/direct-403.mp4", func(w http.ResponseWriter, r *http.Request) {
+ checkNoCookie(r)
+ direct403Hits.Add(1)
+ w.WriteHeader(http.StatusForbidden)
+ })
+ mux.HandleFunc("/cdn/resolved-first.mp4", func(w http.ResponseWriter, r *http.Request) {
+ checkNoCookie(r)
+ edgeRedirectHits.Add(1)
+ w.Header().Set("Location", "/cdn/edge-final.mp4")
+ w.WriteHeader(http.StatusFound)
+ })
+ mux.HandleFunc("/cdn/edge-final.mp4", func(w http.ResponseWriter, r *http.Request) {
+ checkNoCookie(r)
+ serveRangeBytes(w, r, mp4Bytes, "video/mp4", 0, nil)
+ })
+
+ mgr, libStore, srv, _, _ := setupDouyinDownloadTestEnv(t, mux, 2)
+ planner := &playRedirectingPlanner{
+ fakeDouyinWorkPlanner: newFakeDouyinWorkPlanner(),
+ resolve: func(_ context.Context, playURL string) (string, error) {
+ resolverHits.Add(1)
+ u, err := url.Parse(playURL)
+ if err != nil || strings.TrimSuffix(u.Path, "/") != "/aweme/v1/play" {
+ return "", &site.Error{Site: site.Douyin, Kind: site.ErrKindBlocked, Message: "unexpected play URL"}
+ }
+ return srv.URL + "/cdn/resolved-first.mp4", nil
+ },
+ }
+ mgr.RegisterWorkPlanner(planner)
+
+ transport := site.DouyinVODTransport("", true)
+ const secUID = "MS4wLjABAAAA_need_set_token_author"
+
+ // 1. Mixed note with need_set_token=true on both a video page and a live-photo page:
+ // must go straight to PlayURLResolver (0 direct 403 hits), follow CDN edge redirect with 0 Cookie, and complete.
+ planner.setPlan("7600000000000000101", func(_ int) (WorkDownloadPlan, error) {
+ return WorkDownloadPlan{
+ Site: site.Douyin,
+ Kind: "dynamic",
+ TargetID: "7600000000000000101",
+ Title: "需要跳转的混合图文",
+ AuthorUID: secUID,
+ AuthorName: "测试作者",
+ CoverURLs: []string{srv.URL + "/cdn/cover.jpg"},
+ Music: &PlannedMusic{
+ Title: "背景音乐",
+ PlayURLs: []string{srv.URL + "/cdn/music.mp3"},
+ },
+ Transport: transport,
+ Pages: []PlannedNotePage{
+ {
+ Index: 1,
+ Kind: "video",
+ ImageURLs: []string{srv.URL + "/cdn/cover.jpg"},
+ VideoURLs: []string{srv.URL + "/cdn/direct-403.mp4", srv.URL + "/aweme/v1/play/?video_id=p1&line=0"},
+ NeedSetToken: true,
+ DurationSec: 2,
+ },
+ {
+ Index: 2,
+ Kind: "live_photo",
+ ImageURLs: []string{srv.URL + "/cdn/cover.jpg"},
+ VideoURLs: []string{srv.URL + "/cdn/direct-403.mp4", srv.URL + "/aweme/v1/play/?video_id=p2&line=0"},
+ NeedSetToken: true,
+ DurationSec: 2,
+ },
+ },
+ }, nil
+ })
+
+ tk1, err := mgr.EnqueueDouyinWork(context.Background(), DouyinWorkEnqueueRequest{
+ AwemeID: "7600000000000000101",
+ Source: "manual",
+ })
+ if err != nil {
+ t.Fatalf("EnqueueDouyinWork note: %v", err)
+ }
+ done1 := waitForTaskStatus(t, mgr, tk1.TaskID, "completed", 10*time.Second)
+ if done1.Status != "completed" || done1.ErrorMessage != "" {
+ t.Fatalf("need_set_token note task = %+v, want completed with empty error", done1)
+ }
+ if direct403Hits.Load() != 0 {
+ t.Fatalf("need_set_token=true hit direct 403 URL %d times, want 0", direct403Hits.Load())
+ }
+ if resolverHits.Load() != 2 || edgeRedirectHits.Load() != 2 {
+ t.Fatalf("resolverHits=%d edgeRedirectHits=%d, want 2/2", resolverHits.Load(), edgeRedirectHits.Load())
+ }
+ item1, ok, err := libStore.GetItem(done1.ItemKey)
+ if err != nil || !ok || item1.Status != "complete" || len(item1.Missing) != 0 || item1.Music == nil || item1.Music.File == "" {
+ t.Fatalf("saved note item1 = %+v ok=%v err=%v", item1, ok, err)
+ }
+
+ // 2. Normal video (!need_set_token) whose direct CDN returns persistent 403 falls back to PlayURLResolver and completes.
+ planner.setPlan("7600000000000000102", func(_ int) (WorkDownloadPlan, error) {
+ return WorkDownloadPlan{
+ Site: site.Douyin,
+ Kind: "video",
+ TargetID: "7600000000000000102",
+ Title: "直链403回退视频",
+ AuthorUID: secUID,
+ AuthorName: "测试作者",
+ CoverURLs: []string{srv.URL + "/cdn/cover.jpg"},
+ VideoURLs: []string{srv.URL + "/cdn/direct-403.mp4", srv.URL + "/aweme/v1/play/?video_id=v2&line=0"},
+ DurationSec: 2,
+ Transport: transport,
+ }, nil
+ })
+ tk2, err := mgr.EnqueueDouyinWork(context.Background(), DouyinWorkEnqueueRequest{
+ AwemeID: "7600000000000000102",
+ Source: "manual",
+ })
+ if err != nil {
+ t.Fatalf("EnqueueDouyinWork video: %v", err)
+ }
+ done2 := waitForTaskStatus(t, mgr, tk2.TaskID, "completed", 10*time.Second)
+ if done2.Status != "completed" {
+ t.Fatalf("fallback video task = %+v, want completed", done2)
+ }
+ if direct403Hits.Load() == 0 {
+ t.Fatalf("expected normal video to try direct CDN before falling back")
+ }
+ if cdnCookieLeaks.Load() != 0 {
+ t.Fatalf("detected %d Cookie leaks to CDN", cdnCookieLeaks.Load())
+ }
+
+ // 3. Partial note preserves concise missing reason on Task.ErrorMessage, and ListTasks backfills legacy empty partial reasons.
+ planner.setPlan("7600000000000000103", func(_ int) (WorkDownloadPlan, error) {
+ return WorkDownloadPlan{
+ Site: site.Douyin,
+ Kind: "dynamic",
+ TargetID: "7600000000000000103",
+ Title: "缺配乐的部分完成图文",
+ AuthorUID: secUID,
+ AuthorName: "测试作者",
+ CoverURLs: []string{srv.URL + "/cdn/cover.jpg"},
+ Music: &PlannedMusic{
+ Title: "缺失配乐",
+ PlayURLs: []string{srv.URL + "/cdn/music-missing.mp3"},
+ },
+ Transport: transport,
+ Pages: []PlannedNotePage{
+ {
+ Index: 1,
+ Kind: "image",
+ ImageURLs: []string{srv.URL + "/cdn/cover.jpg"},
+ },
+ },
+ }, nil
+ })
+ tk3, err := mgr.EnqueueDouyinWork(context.Background(), DouyinWorkEnqueueRequest{
+ AwemeID: "7600000000000000103",
+ Source: "manual",
+ })
+ if err != nil {
+ t.Fatalf("EnqueueDouyinWork partial note: %v", err)
+ }
+ done3 := waitForTaskStatus(t, mgr, tk3.TaskID, "partial", 10*time.Second)
+ if done3.ErrorMessage == "" || !strings.Contains(done3.ErrorMessage, "配乐下载失败") {
+ t.Fatalf("partial task ErrorMessage = %q, want missing music reason preserved", done3.ErrorMessage)
+ }
+ // Simulate a legacy DB row whose error_message was cleared; ListTasks and GetTask must backfill it from item.Missing.
+ if _, err := mgr.db.Exec(`UPDATE download_tasks SET error_message = '' WHERE task_id = ?`, done3.TaskID); err != nil {
+ t.Fatalf("clear error_message: %v", err)
+ }
+ got3, ok, err := mgr.GetTask(done3.TaskID)
+ if err != nil || !ok || !strings.Contains(got3.ErrorMessage, "配乐下载失败") {
+ t.Fatalf("GetTask backfilled ErrorMessage = %q (ok=%v err=%v), want missing music reason", got3.ErrorMessage, ok, err)
+ }
+ listed, err := mgr.ListTasks()
+ if err != nil {
+ t.Fatalf("ListTasks: %v", err)
+ }
+ foundBackfilled := false
+ for _, tk := range listed {
+ if tk.TaskID == done3.TaskID && strings.Contains(tk.ErrorMessage, "配乐下载失败") {
+ foundBackfilled = true
+ }
+ }
+ if !foundBackfilled {
+ t.Fatalf("ListTasks did not backfill missing reason for partial task %s", done3.TaskID)
+ }
+}
diff --git a/internal/download/mux.go b/internal/download/mux.go
index dca5aeb..07dd019 100644
--- a/internal/download/mux.go
+++ b/internal/download/mux.go
@@ -1,20 +1,20 @@
package download
import (
- "bytes"
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"math"
+ "math/bits"
"os"
+ "path/filepath"
"github.com/Eyevinn/mp4ff/mp4"
- "github.com/chialecode/trace/internal/storage"
)
-// MuxTrackSummary describes the tracks and structural invariants inside a muxed MP4 file (C17, PR-2).
+// MuxTrackSummary describes the tracks and structural invariants inside a muxed MP4 file.
type MuxTrackSummary struct {
TrackCount int `json:"trackCount"`
Handlers []string `json:"handlers"`
@@ -31,7 +31,7 @@ type MuxTrackSummary struct {
}
// MuxDASHFiles remuxes a Bilibili DASH video .m4s file and an optional audio .m4s file
-// into a standard progressive (moov-before-mdat) MP4 file at outPath using pure-Go mp4ff (C17, PR-2).
+// into a standard progressive (moov-before-mdat) MP4 file at outPath using pure-Go mp4ff.
func MuxDASHFiles(videoPath, audioPath, outPath string) (MuxTrackSummary, error) {
return MuxDASHFilesContext(context.Background(), videoPath, audioPath, outPath)
}
@@ -39,15 +39,31 @@ func MuxDASHFiles(videoPath, audioPath, outPath string) (MuxTrackSummary, error)
// DefragmentFMP4Bytes converts a fragmented MP4 byte slice into a progressive MP4 file at outPath.
// Returns an error if defragmentation fails (never silently writes fragmented bytes).
func DefragmentFMP4Bytes(raw []byte, outPath string) (MuxTrackSummary, error) {
- return writeDefragmentedOutput(raw, outPath)
+ if err := os.MkdirAll(filepath.Dir(outPath), 0o700); err != nil {
+ return MuxTrackSummary{}, err
+ }
+ tmp, err := os.CreateTemp(filepath.Dir(outPath), ".trace-defrag-*.part")
+ if err != nil {
+ return MuxTrackSummary{}, err
+ }
+ tmpPath := tmp.Name()
+ if _, err := tmp.Write(raw); err != nil {
+ _ = tmp.Close()
+ _ = os.Remove(tmpPath)
+ return MuxTrackSummary{}, err
+ }
+ return writeProgressiveDisk(context.Background(), tmp, tmpPath, outPath)
}
-func ensureTrackElst(moov *mp4.MoovBox, trak *mp4.TrakBox, mediaDur uint64) {
+// ensureTrackElst adds a single-entry edit list when trak does not already carry one.
+// It uses elst version 1 (64-bit) whenever SegmentDuration or MediaTime exceeds 32-bit bounds
+// and never overwrites an existing edit list (e.g. B-frame CTS delay or empty edit).
+func ensureTrackElst(moov *mp4.MoovBox, trak *mp4.TrakBox, mediaDur uint64, mediaTime int64) bool {
if trak == nil {
- return
+ return false
}
if trak.Edts != nil && len(trak.Edts.Elst) > 0 {
- return
+ return false
}
movieTS := uint32(1000)
if moov != nil && moov.Mvhd != nil && moov.Mvhd.Timescale > 0 {
@@ -59,20 +75,29 @@ func ensureTrackElst(moov *mp4.MoovBox, trak *mp4.TrakBox, mediaDur uint64) {
}
segDur := mediaDur
if trackTS > 0 && movieTS > 0 && trackTS != movieTS {
- segDur = (mediaDur * uint64(movieTS)) / uint64(trackTS)
+ hi, lo := bits.Mul64(mediaDur, uint64(movieTS))
+ if hi < uint64(trackTS) {
+ segDur, _ = bits.Div64(hi, lo, uint64(trackTS))
+ } else {
+ segDur = math.MaxUint64
+ }
+ }
+ var version byte
+ if segDur > math.MaxUint32 || mediaTime > math.MaxInt32 || mediaTime < math.MinInt32 {
+ version = 1
}
- edts := &mp4.EdtsBox{}
elst := &mp4.ElstBox{
- Version: 0,
+ Version: version,
Entries: []mp4.ElstEntry{
{
SegmentDuration: segDur,
- MediaTime: 0,
+ MediaTime: mediaTime,
MediaRateInteger: 1,
MediaRateFraction: 0,
},
},
}
+ edts := &mp4.EdtsBox{Elst: []*mp4.ElstBox{elst}}
edts.AddChild(elst)
// Insert EdtsBox into trak (preserving Tkhd first).
trak.Edts = edts
@@ -89,6 +114,7 @@ func ensureTrackElst(moov *mp4.MoovBox, trak *mp4.TrakBox, mediaDur uint64) {
newChildren = append([]mp4.Box{edts}, newChildren...)
}
trak.Children = newChildren
+ return true
}
func setSingleTrackID(f *mp4.File, trackID uint32) {
@@ -117,89 +143,6 @@ func setSingleTrackID(f *mp4.File, trackID uint32) {
}
}
-func writeDefragmentedOutput(combinedFragmented []byte, outPath string) (MuxTrackSummary, error) {
- rs := bytes.NewReader(combinedFragmented)
- lazyFile, err := mp4.DecodeFile(rs, mp4.WithDecodeMode(mp4.DecModeLazyMdat), mp4.WithDecodeFlags(mp4.DecStartOnMoof))
- if err != nil {
- return MuxTrackSummary{}, fmt.Errorf("download: decode combined fragmented stream: %w", err)
- }
-
- var outBuf bytes.Buffer
- if dErr := mp4.Defragment(lazyFile, rs, &outBuf); dErr != nil {
- return MuxTrackSummary{}, fmt.Errorf("download: defragment fmp4: %w", dErr)
- }
-
- finalBytes, err := injectElstIntoProgressiveMP4(outBuf.Bytes())
- if err != nil {
- finalBytes = outBuf.Bytes()
- }
-
- if err := storage.WriteFileAtomic(outPath, finalBytes, 0o600); err != nil {
- return MuxTrackSummary{}, err
- }
- summary, err := InspectMP4File(outPath)
- if err != nil {
- return MuxTrackSummary{}, err
- }
- if !summary.MoovBeforeMdat {
- return summary, fmt.Errorf("download: output mp4 moov is not before mdat")
- }
- if summary.MaxTrackDiffSec > 2.0 {
- return summary, fmt.Errorf("download: output mp4 track duration mismatch %.2fs > 2s", summary.MaxTrackDiffSec)
- }
- return summary, nil
-}
-
-func injectElstIntoProgressiveMP4(defragBytes []byte) ([]byte, error) {
- progFile, err := mp4.DecodeFile(bytes.NewReader(defragBytes))
- if err != nil {
- return nil, err
- }
- if progFile.Moov == nil {
- return defragBytes, nil
- }
- oldMoovSize := progFile.Moov.Size()
- modified := false
- for _, trak := range progFile.Moov.Traks {
- if trak.Edts == nil || len(trak.Edts.Elst) == 0 {
- var mediaDur uint64
- if trak.Mdia != nil && trak.Mdia.Mdhd != nil {
- mediaDur = trak.Mdia.Mdhd.Duration
- }
- ensureTrackElst(progFile.Moov, trak, mediaDur)
- modified = true
- }
- }
- if !modified {
- return defragBytes, nil
- }
- newMoovSize := progFile.Moov.Size()
- delta := int64(newMoovSize) - int64(oldMoovSize)
- if delta != 0 {
- for _, trak := range progFile.Moov.Traks {
- if trak.Mdia == nil || trak.Mdia.Minf == nil || trak.Mdia.Minf.Stbl == nil {
- continue
- }
- stbl := trak.Mdia.Minf.Stbl
- if stbl.Stco != nil {
- for i := range stbl.Stco.ChunkOffset {
- stbl.Stco.ChunkOffset[i] = uint32(int64(stbl.Stco.ChunkOffset[i]) + delta)
- }
- }
- if stbl.Co64 != nil {
- for i := range stbl.Co64.ChunkOffset {
- stbl.Co64.ChunkOffset[i] = uint64(int64(stbl.Co64.ChunkOffset[i]) + delta)
- }
- }
- }
- }
- var finalBuf bytes.Buffer
- if err := progFile.Encode(&finalBuf); err != nil {
- return nil, err
- }
- return finalBuf.Bytes(), nil
-}
-
// InspectMP4File parses an MP4 file on disk and returns its track count, handlers, codecs, dimensions, and box layout invariants.
func InspectMP4File(path string) (MuxTrackSummary, error) {
return InspectMP4FileContext(context.Background(), path)
@@ -224,9 +167,12 @@ func InspectMP4FileContext(ctx context.Context, path string) (MuxTrackSummary, e
return MuxTrackSummary{}, err
}
parsed, err := mp4.DecodeFile(contextIO{File: f, ctx: ctx}, mp4.WithDecodeMode(mp4.DecModeLazyMdat), mp4.WithDecodeFlags(mp4.DecStartOnMoof))
- if err != nil || parsed == nil {
+ if err != nil {
return MuxTrackSummary{}, err
}
+ if parsed == nil {
+ return MuxTrackSummary{}, fmt.Errorf("download: mp4 file %s decoded to nil", path)
+ }
var declared uint64
for _, box := range parsed.Children {
declared += box.Size()
diff --git a/internal/download/mux_disk.go b/internal/download/mux_disk.go
index d4b383e..227afb0 100644
--- a/internal/download/mux_disk.go
+++ b/internal/download/mux_disk.go
@@ -76,11 +76,9 @@ func MuxDASHFilesContext(ctx context.Context, videoPath, audioPath, outPath stri
var chunks []diskChunk
for i, track := range tracks {
trak := track.file.Init.Moov.Traks[0]
- ensureTrackElst(init.Moov, trak, track.duration)
- // Defragment shifts the media edit by the first tfdt; preserve that origin.
- if trak.Edts != nil && len(trak.Edts.Elst) > 0 && len(trak.Edts.Elst[0].Entries) > 0 {
- trak.Edts.Elst[0].Entries[0].MediaTime = int64(track.origin)
- }
+ // Defragment shifts the media edit by the first tfdt; preserve that origin
+ // when synthesizing a new edit list without clobbering an existing elst.
+ ensureTrackElst(init.Moov, trak, track.duration, int64(track.origin))
if i > 0 {
init.Moov.AddChild(trak)
init.Moov.Mvex.AddChild(track.file.Init.Moov.Mvex.Trexs[0])
@@ -103,16 +101,19 @@ func MuxDASHFilesContext(ctx context.Context, videoPath, audioPath, outPath stri
if err != nil {
return MuxTrackSummary{}, err
}
- defer os.Remove(combined.Name())
- defer combined.Close()
+ combinedPath := combined.Name()
writer := contextIO{File: combined, ctx: ctx}
if err := init.Encode(writer); err != nil {
+ _ = combined.Close()
+ _ = os.Remove(combinedPath)
return MuxTrackSummary{}, err
}
copyBuffer := make([]byte, 64*1024)
for i, chunk := range chunks {
fragment, err := mp4.CreateFragment(uint32(i+1), chunk.id)
if err != nil {
+ _ = combined.Close()
+ _ = os.Remove(combinedPath)
return MuxTrackSummary{}, err
}
var payload uint64
@@ -122,21 +123,29 @@ func MuxDASHFilesContext(ctx context.Context, videoPath, audioPath, outPath stri
}
fragment.Mdat.SetLazyDataSize(payload)
if err := fragment.Encode(writer); err != nil {
+ _ = combined.Close()
+ _ = os.Remove(combinedPath)
return MuxTrackSummary{}, err
}
for _, sample := range chunk.track.samples[chunk.first:chunk.end] {
if err := ctx.Err(); err != nil {
+ _ = combined.Close()
+ _ = os.Remove(combinedPath)
return MuxTrackSummary{}, err
}
if _, err := io.CopyBuffer(writer, io.NewSectionReader(chunk.track.source, sample.offset, int64(sample.sample.Size)), copyBuffer); err != nil {
+ _ = combined.Close()
+ _ = os.Remove(combinedPath)
return MuxTrackSummary{}, err
}
}
}
if err := combined.Sync(); err != nil {
+ _ = combined.Close()
+ _ = os.Remove(combinedPath)
return MuxTrackSummary{}, err
}
- return writeProgressiveDisk(ctx, combined, outPath)
+ return writeProgressiveDisk(ctx, combined, combinedPath, outPath)
}
func readDiskTrack(ctx context.Context, path, handler string, id uint32) (*diskTrack, error) {
@@ -206,7 +215,22 @@ func readDiskTrack(ctx context.Context, path, handler string, id uint32) (*diskT
return result, nil
}
-func writeProgressiveDisk(ctx context.Context, source *os.File, outPath string) (MuxTrackSummary, error) {
+// writeProgressiveDisk defragments source into outPath and takes ownership of
+// closing and removing sourcePath as soon as defragmentation finishes so peak
+// disk usage stays bounded before optional edit-list rewriting.
+func writeProgressiveDisk(ctx context.Context, source *os.File, sourcePath, outPath string) (MuxTrackSummary, error) {
+ cleanupSource := func() {
+ if source != nil {
+ _ = source.Close()
+ source = nil
+ }
+ if sourcePath != "" {
+ _ = os.Remove(sourcePath)
+ sourcePath = ""
+ }
+ }
+ defer cleanupSource()
+
if _, err := source.Seek(0, io.SeekStart); err != nil {
return MuxTrackSummary{}, err
}
@@ -221,11 +245,15 @@ func writeProgressiveDisk(ctx context.Context, source *os.File, outPath string)
}
defer os.Remove(out.Name())
if err := mp4.Defragment(file, reader, contextIO{File: out, ctx: ctx}); err != nil {
- out.Close()
+ _ = out.Close()
return MuxTrackSummary{}, err
}
+ // Release the combined fragmented staging file before addProgressiveEdits
+ // so at most two copies exist on disk instead of three.
+ cleanupSource()
+
if err := out.Sync(); err != nil {
- out.Close()
+ _ = out.Close()
return MuxTrackSummary{}, err
}
if err := out.Close(); err != nil {
@@ -257,17 +285,32 @@ func addProgressiveEdits(ctx context.Context, path string) error {
reader := contextIO{File: source, ctx: ctx}
file, err := mp4.DecodeFile(reader, mp4.WithDecodeMode(mp4.DecModeLazyMdat))
if err != nil {
- source.Close()
+ _ = source.Close()
return err
}
if file.Moov == nil || file.Mdat == nil {
- source.Close()
+ _ = source.Close()
return fmt.Errorf("download: 合并后缺少 moov/mdat")
}
oldSize := file.Moov.Size()
+ needsRewrite := false
for _, track := range file.Moov.Traks {
if track.Edts == nil || len(track.Edts.Elst) == 0 {
- ensureTrackElst(file.Moov, track, track.Mdia.Mdhd.Duration)
+ var mediaDur uint64
+ if track.Mdia != nil && track.Mdia.Mdhd != nil {
+ mediaDur = track.Mdia.Mdhd.Duration
+ }
+ if ensureTrackElst(file.Moov, track, mediaDur, 0) {
+ needsRewrite = true
+ }
+ }
+ }
+ if !needsRewrite {
+ return source.Close()
+ }
+ for _, track := range file.Moov.Traks {
+ if track.Mdia == nil || track.Mdia.Minf == nil || track.Mdia.Minf.Stbl == nil {
+ continue
}
stbl := track.Mdia.Minf.Stbl
if stbl.Stco != nil {
@@ -285,6 +328,9 @@ func addProgressiveEdits(ctx context.Context, path string) error {
}
delta := file.Moov.Size() - oldSize
for _, track := range file.Moov.Traks {
+ if track.Mdia == nil || track.Mdia.Minf == nil || track.Mdia.Minf.Stbl == nil {
+ continue
+ }
if offsets := track.Mdia.Minf.Stbl.Co64; offsets != nil {
for i := range offsets.ChunkOffset {
offsets.ChunkOffset[i] += delta
@@ -293,7 +339,7 @@ func addProgressiveEdits(ctx context.Context, path string) error {
}
out, err := os.CreateTemp(filepath.Dir(path), ".trace-edits-*.part")
if err != nil {
- source.Close()
+ _ = source.Close()
return err
}
defer os.Remove(out.Name())
diff --git a/internal/download/range_download.go b/internal/download/range_download.go
new file mode 100644
index 0000000..c43a832
--- /dev/null
+++ b/internal/download/range_download.go
@@ -0,0 +1,851 @@
+package download
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ jitterrand "math/rand/v2"
+ "net"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/site"
+ "github.com/chialecode/trace/internal/site/bilibili"
+)
+
+// networkPauseError signals that segmented range retries or full resets reached
+// their upper bound and the task should pause with reason "network" if the
+// caller does not recover via a fallback stream. Returning this typed error
+// instead of mutating Task.Status mid-task prevents SQLite status poisoning
+// when a caller recovers (e.g. Douyin OriginalURLs falling back to VideoURLs
+// or a non-fatal cover/page failure).
+type networkPauseError struct {
+ message string
+ err error
+}
+
+func (e *networkPauseError) Error() string {
+ if e.message != "" {
+ return e.message
+ }
+ if e.err != nil {
+ return e.err.Error()
+ }
+ return "已暂停(网络)"
+}
+
+func (e *networkPauseError) Unwrap() error {
+ return e.err
+}
+
+type mediaTransportKey struct {
+ site site.ID
+ allowLocalhost bool
+}
+
+type segmentResult struct {
+ newOffset int64
+ totalSize int64
+ done bool
+ truncatedToZero bool
+}
+
+type rangeDownloadSpec struct {
+ site site.ID
+ role string
+ validateURL func(string) error
+ applyHeaders func(*http.Request)
+ doRequest func(*http.Request) (*http.Response, error)
+ wrapBody func(io.ReadCloser) io.ReadCloser
+ checkDisguised bool
+ reuseVerified bool
+ updateFinalRow bool
+ allRejectedMsg string
+}
+
+func (m *Manager) bilibiliRangeSpec() rangeDownloadSpec {
+ mediaClient, _ := m.client.MediaHTTPClient()
+ return rangeDownloadSpec{
+ site: site.Bilibili,
+ validateURL: func(raw string) error {
+ if m.client != nil {
+ return m.client.ValidateMediaURL(raw)
+ }
+ return nil
+ },
+ applyHeaders: func(req *http.Request) {
+ req.Header.Set("User-Agent", bilibili.DefaultUserAgent)
+ req.Header.Set("Referer", bilibili.DefaultReferer)
+ },
+ doRequest: mediaClient.Do,
+ wrapBody: func(rc io.ReadCloser) io.ReadCloser {
+ if m.client != nil {
+ return m.client.WrapMediaReader(rc)
+ }
+ return rc
+ },
+ reuseVerified: true,
+ updateFinalRow: true,
+ allRejectedMsg: "站点只返回了不受支持的第三方媒体节点,请稍后重试",
+ }
+}
+
+func (m *Manager) transportRangeSpec(transport site.MediaTransportSpec, role string, reuseVerified bool) rangeDownloadSpec {
+ httpClient := m.transportHTTPClient(transport)
+ return rangeDownloadSpec{
+ site: transport.Site,
+ role: role,
+ validateURL: transport.ValidateURL,
+ applyHeaders: transport.ApplyHeaders,
+ doRequest: httpClient.Do,
+ wrapBody: func(rc io.ReadCloser) io.ReadCloser {
+ return site.WrapIdleReadCloser(rc, 20*time.Second, func() error {
+ return errors.New("media read idle timeout")
+ })
+ },
+ checkDisguised: true,
+ reuseVerified: reuseVerified,
+ }
+}
+
+func (m *Manager) downloadStreamWithRefresh(
+ ctx context.Context,
+ urls []string,
+ finalPath string,
+ t *Task,
+ refreshURLs func() ([]string, error),
+) (int64, string, error) {
+ n, sha, _, err := m.downloadRangeWithRefresh(ctx, m.bilibiliRangeSpec(), urls, finalPath, t, refreshURLs)
+ return n, sha, err
+}
+
+// downloadFileWithRange downloads from candidate URLs into finalPath via .part,
+// using 8 MiB closed-interval Range requests, per-segment retry with exponential backoff + URL rotation,
+// and Content-Range verification (data-and-cache.md §2.4).
+func (m *Manager) downloadFileWithRange(ctx context.Context, urls []string, finalPath string, t *Task) (int64, string, error) {
+ n, sha, _, err := m.downloadRange(ctx, m.bilibiliRangeSpec(), urls, finalPath, t)
+ return n, sha, err
+}
+
+func (m *Manager) fetchSingleSegment(
+ ctx context.Context,
+ targetURL string,
+ partPath string,
+ offset int64,
+ endByte int64,
+ knownTotal int64,
+ t *Task,
+) (segmentResult, error) {
+ relFile := taskRelativePath(t, strings.TrimSuffix(partPath, ".part"))
+ relID := taskFileIdentity(relFile)
+ res, _, err := m.fetchRangeSegment(ctx, m.bilibiliRangeSpec(), targetURL, partPath, relID, "", offset, endByte, knownTotal, t)
+ return res, err
+}
+
+func (m *Manager) downloadWithTransportRefresh(
+ ctx context.Context,
+ transport site.MediaTransportSpec,
+ urls []string,
+ finalPath string,
+ role string,
+ t *Task,
+ refreshURLs func() ([]string, error),
+) (int64, string, error) {
+ n, sha, _, err := m.downloadRangeWithRefresh(ctx, m.transportRangeSpec(transport, role, true), urls, finalPath, t, refreshURLs)
+ return n, sha, err
+}
+
+func (m *Manager) downloadWithTransportRefreshCT(
+ ctx context.Context,
+ transport site.MediaTransportSpec,
+ urls []string,
+ finalPath string,
+ role string,
+ t *Task,
+ refreshURLs func() ([]string, error),
+) (int64, string, string, error) {
+ return m.downloadRangeWithRefresh(ctx, m.transportRangeSpec(transport, role, false), urls, finalPath, t, refreshURLs)
+}
+
+func (m *Manager) downloadRangeWithRefresh(
+ ctx context.Context,
+ spec rangeDownloadSpec,
+ urls []string,
+ finalPath string,
+ t *Task,
+ refreshURLs func() ([]string, error),
+) (int64, string, string, error) {
+ n, sha, ct, err := m.downloadRange(ctx, spec, urls, finalPath, t)
+ if err == nil {
+ return n, sha, ct, nil
+ }
+ // If all URLs expired (403, 404, 410), refresh at most once and resume from byte offset (data-and-cache.md §2.4).
+ if refreshURLs != nil && (site.IsKind(err, site.ErrKindForbidden) || site.IsKind(err, site.ErrKindUnavailable)) {
+ freshURLs, rErr := refreshURLs()
+ if rErr != nil {
+ if ctx.Err() != nil {
+ return 0, "", "", ctx.Err()
+ }
+ if isSiteStopError(rErr) || isStorageError(rErr) || site.IsKind(rErr, site.ErrKindUnavailable) {
+ return 0, "", "", rErr
+ }
+ return 0, "", "", err
+ }
+ if len(freshURLs) > 0 {
+ return m.downloadRange(ctx, spec, freshURLs, finalPath, t)
+ }
+ }
+ return 0, "", "", err
+}
+
+func (m *Manager) downloadRange(
+ ctx context.Context,
+ spec rangeDownloadSpec,
+ urls []string,
+ finalPath string,
+ t *Task,
+) (int64, string, string, error) {
+ var cleanURLs []string
+ var lastValidateErr error
+ rejectedNodes := 0
+ for _, u := range urls {
+ u = strings.TrimSpace(u)
+ if u == "" {
+ continue
+ }
+ if spec.validateURL != nil {
+ if vErr := spec.validateURL(u); vErr != nil {
+ lastValidateErr = vErr
+ rejectedNodes++
+ continue
+ }
+ }
+ cleanURLs = append(cleanURLs, u)
+ }
+ if len(cleanURLs) == 0 {
+ if rejectedNodes > 0 {
+ if spec.allRejectedMsg != "" {
+ return 0, "", "", &site.Error{
+ Site: spec.site,
+ Kind: site.ErrKindUnavailable,
+ Message: spec.allRejectedMsg,
+ }
+ }
+ if lastValidateErr != nil {
+ return 0, "", "", lastValidateErr
+ }
+ }
+ return 0, "", "", &site.Error{
+ Site: spec.site,
+ Kind: site.ErrKindUnavailable,
+ Message: "下载地址列表为空",
+ }
+ }
+
+ root, rel := filepath.Dir(finalPath), filepath.Base(finalPath)
+ if t.ItemDir != "" {
+ root = t.ItemDir
+ r, err := filepath.Rel(root, finalPath)
+ if err != nil {
+ return 0, "", "", err
+ }
+ rel = filepath.ToSlash(r)
+ }
+ if _, err := library.ResolveItemPath(root, rel); err != nil {
+ return 0, "", "", err
+ }
+ if _, err := library.ResolveItemPath(root, rel+".part"); err != nil {
+ return 0, "", "", err
+ }
+ if err := m.claimTaskFile(t, root, rel, finalPath); err != nil {
+ return 0, "", "", err
+ }
+ if err := ctx.Err(); err != nil {
+ return 0, "", "", err
+ }
+
+ relID := taskFileIdentity(rel)
+ trimmedRel := taskRelativePath(t, trimStagingSuffixes(finalPath))
+ trimmedID := taskFileIdentity(trimmedRel)
+
+ // A nonempty file alone is not proof of completion. Reuse only a verified
+ // checkpoint with its original length (and hash, when available).
+ if spec.reuseVerified {
+ for _, file := range t.Files {
+ if taskFileIdentity(file.Path) == relID && file.TotalBytes > 0 && library.VerifyMediaFile(root, library.MediaFile{Path: rel, Bytes: file.TotalBytes, SHA256: file.SHA256}, true) {
+ sha, sz, err := hashFileSHA256(finalPath)
+ return sz, sha, "", err
+ }
+ }
+ }
+
+ if err := os.MkdirAll(filepath.Dir(finalPath), 0o700); err != nil {
+ return 0, "", "", err
+ }
+
+ m.mu.Lock()
+ chunkSize := m.chunkSize
+ if chunkSize <= 0 {
+ chunkSize = DefaultRangeChunkSize
+ }
+ backoffScale := m.backoffScale
+ if backoffScale <= 0 {
+ backoffScale = time.Second
+ }
+ m.mu.Unlock()
+
+ partPath := finalPath + ".part"
+ attemptFile := filepath.Base(finalPath)
+ if spec.checkDisguised {
+ attemptFile = trimmedRel
+ }
+
+ var offset int64
+ if info, err := os.Stat(partPath); err == nil && !info.IsDir() {
+ offset = info.Size()
+ }
+
+ var totalSize int64 = -1
+ for _, file := range t.Files {
+ fid := taskFileIdentity(file.Path)
+ if (fid == relID || (trimmedID != "" && fid == trimmedID)) && file.TotalBytes > 0 {
+ totalSize = file.TotalBytes
+ break
+ }
+ }
+ if totalSize > 0 && offset > totalSize {
+ if err := os.Truncate(partPath, 0); err != nil {
+ return 0, "", "", err
+ }
+ offset = 0
+ }
+
+ var contentType string
+ urlIdx := 0
+ segRetries := 0
+ fullResets := 0
+ var lastErr error
+
+ for {
+ if ctx.Err() != nil {
+ return offset, "", "", ctx.Err()
+ }
+ if totalSize > 0 && offset == totalSize {
+ break
+ }
+
+ targetURL := cleanURLs[urlIdx%len(cleanURLs)]
+ endByte := offset + chunkSize - 1
+ if totalSize > 0 && endByte >= totalSize {
+ endByte = totalSize - 1
+ }
+
+ res, ct, err := m.fetchRangeSegment(ctx, spec, targetURL, partPath, relID, trimmedID, offset, endByte, totalSize, t)
+ if err == nil {
+ if ct != "" {
+ contentType = ct
+ }
+ offset = res.newOffset
+ if res.totalSize > 0 {
+ totalSize = res.totalSize
+ }
+ segRetries = 0
+ if res.done || (totalSize > 0 && offset >= totalSize) {
+ break
+ }
+ continue
+ }
+
+ lastErr = err
+ errKind := classifyDownloadError(err)
+ httpStatus := 0
+ var se *site.Error
+ if errors.As(err, &se) {
+ httpStatus = se.HTTPStatus
+ }
+
+ // Risk control (412 / -352 / -412), rate limit (429), auth required (401), blocked, schema changed, or storage: stop immediately without retry.
+ if errKind == site.ErrKindRiskControl || errKind == site.ErrKindRateLimited || errKind == site.ErrKindAuthRequired || errKind == site.ErrKindBlocked || errKind == site.ErrKindSchemaChanged || isStorageError(err) {
+ m.recordAttempt(t, attemptFile, offset, targetURL, segRetries+1, errKind, httpStatus)
+ return offset, "", "", err
+ }
+
+ // Subsequent segment returned 200 OK instead of 206 or 416: truncate .part, rotate URL, and count towards 5-reset limit.
+ if res.truncatedToZero {
+ offset = 0
+ totalSize = -1
+ fullResets++
+ urlIdx++
+ m.recordAttempt(t, attemptFile, offset, targetURL, fullResets, site.ErrKindNetwork, http.StatusOK)
+ if fullResets >= 5 {
+ return offset, "", "", &networkPauseError{
+ message: "已暂停(网络):节点不支持分段续传且重试已达上限",
+ err: lastErr,
+ }
+ }
+ continue
+ }
+
+ // Expired/forbidden URL (403, 404, 410): rotate through remaining candidate URLs once without sleeping.
+ if errKind == site.ErrKindForbidden || errKind == site.ErrKindUnavailable {
+ segRetries++
+ urlIdx++
+ m.recordAttempt(t, attemptFile, offset, targetURL, segRetries, errKind, httpStatus)
+ if segRetries >= len(cleanURLs) {
+ return offset, "", "", lastErr
+ }
+ continue
+ }
+
+ // Transport error (premature EOF, timeout, reset, 5xx): keep written bytes, retry up to 5 times with exponential backoff and URL rotation.
+ offset = res.newOffset
+ if res.totalSize > 0 {
+ totalSize = res.totalSize
+ }
+ segRetries++
+ urlIdx++
+ m.recordAttempt(t, attemptFile, offset, targetURL, segRetries, errKind, httpStatus)
+ if segRetries >= 5 {
+ return offset, "", "", &networkPauseError{
+ message: "已暂停(网络):分段重试已达上限",
+ err: lastErr,
+ }
+ }
+
+ // Exponential backoff: 1, 2, 4, 8, 16 units
+ backoffUnits := int64(1 << (segRetries - 1))
+ if backoffUnits > 16 {
+ backoffUnits = 16
+ }
+ sleepDur := time.Duration(backoffUnits) * backoffScale
+ sleepDur = time.Duration(float64(sleepDur) * (0.8 + 0.4*jitterrand.Float64()))
+ select {
+ case <-ctx.Done():
+ return offset, "", "", ctx.Err()
+ case <-time.After(sleepDur):
+ }
+ }
+
+ shaHex, actualSize, err := hashFileSHA256(partPath)
+ if err != nil {
+ return offset, "", "", err
+ }
+ if totalSize > 0 && actualSize != totalSize {
+ return actualSize, "", "", &site.Error{
+ Site: spec.site,
+ Kind: site.ErrKindNetwork,
+ Message: fmt.Sprintf("文件大小校验不一致: 实际 %d != 预期 %d", actualSize, totalSize),
+ }
+ }
+
+ if err := os.Rename(partPath, finalPath); err != nil {
+ return actualSize, "", "", err
+ }
+ for i := range t.Files {
+ if taskFileIdentity(t.Files[i].Path) == relID {
+ t.Files[i].DownloadedBytes, t.Files[i].TotalBytes = actualSize, actualSize
+ t.Files[i].SHA256 = shaHex
+ if spec.updateFinalRow {
+ t.Files[i].Status = "completed"
+ }
+ }
+ }
+ if spec.updateFinalRow || spec.reuseVerified {
+ m.persistTaskProgress(*t)
+ }
+ return actualSize, shaHex, contentType, nil
+}
+
+func (m *Manager) fetchRangeSegment(
+ ctx context.Context,
+ spec rangeDownloadSpec,
+ targetURL string,
+ partPath string,
+ relID string,
+ trimmedID string,
+ offset int64,
+ endByte int64,
+ knownTotal int64,
+ t *Task,
+) (segmentResult, string, error) {
+ if spec.validateURL != nil {
+ if err := spec.validateURL(targetURL); err != nil {
+ return segmentResult{newOffset: offset}, "", err
+ }
+ }
+ safeEndpoint := site.SanitizeEndpoint(targetURL)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil)
+ if err != nil {
+ return segmentResult{newOffset: offset}, "", &site.Error{
+ Site: spec.site,
+ Kind: site.ErrKindBadRequest,
+ Endpoint: safeEndpoint,
+ Message: "媒体请求构造失败",
+ Err: site.UnwrapURLError(err),
+ }
+ }
+ if spec.applyHeaders != nil {
+ spec.applyHeaders(req)
+ }
+ req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, endByte))
+
+ resp, err := spec.doRequest(req)
+ if err != nil {
+ var se *site.Error
+ if errors.As(err, &se) {
+ return segmentResult{newOffset: offset}, "", se
+ }
+ return segmentResult{newOffset: offset}, "", &site.Error{
+ Site: spec.site,
+ Kind: site.ErrKindNetwork,
+ Endpoint: safeEndpoint,
+ Message: "媒体下载连接失败",
+ Err: site.UnwrapURLError(err),
+ }
+ }
+ defer resp.Body.Close()
+
+ // Handle 416 Range Not Satisfiable when offset > 0 by truncating .part and restarting.
+ if resp.StatusCode == http.StatusRequestedRangeNotSatisfiable && offset > 0 {
+ _ = os.Truncate(partPath, 0)
+ return segmentResult{newOffset: 0, truncatedToZero: true}, "", &site.Error{
+ Site: spec.site,
+ Kind: site.ErrKindNetwork,
+ HTTPStatus: resp.StatusCode,
+ Endpoint: safeEndpoint,
+ Message: "Range 416,重置分段文件",
+ }
+ }
+ if resp.StatusCode >= 400 {
+ return segmentResult{newOffset: offset}, "", mapMediaHTTPStatus(spec.site, resp.StatusCode, safeEndpoint)
+ }
+
+ rawCT := strings.TrimSpace(resp.Header.Get("Content-Type"))
+ role := spec.role
+ if role == "" {
+ for _, file := range t.Files {
+ fid := taskFileIdentity(file.Path)
+ if (fid == relID || (trimmedID != "" && fid == trimmedID)) && file.Role != "" {
+ role = file.Role
+ break
+ }
+ }
+ }
+ isImage := role == "image" || role == "cover"
+ if spec.checkDisguised {
+ if err := rejectDisguisedMediaContentType(spec.site, rawCT, role, resp.StatusCode); err != nil {
+ return segmentResult{newOffset: offset}, rawCT, err
+ }
+ } else if isImage && !strings.HasPrefix(strings.ToLower(rawCT), "image/") {
+ return segmentResult{newOffset: offset}, rawCT, &site.Error{
+ Site: spec.site,
+ Kind: site.ErrKindSchemaChanged,
+ Message: "图片响应不是 image/*",
+ }
+ }
+
+ var expectedSegLen int64 = -1
+ totalSize := knownTotal
+ doneAfterThis := false
+ openFlags := os.O_CREATE | os.O_WRONLY
+ seekToOffset := false
+
+ switch resp.StatusCode {
+ case http.StatusPartialContent:
+ cr := strings.TrimSpace(resp.Header.Get("Content-Range"))
+ if cr == "" {
+ return segmentResult{newOffset: offset}, rawCT, &site.Error{Site: spec.site, Kind: site.ErrKindNetwork, Message: "206 响应缺少 Content-Range"}
+ }
+ start, end, total, ok := parseContentRange(cr)
+ if !ok || start != offset || end < start || end > endByte || total <= end || (knownTotal > 0 && total != knownTotal) {
+ return segmentResult{newOffset: offset}, rawCT, &site.Error{
+ Site: spec.site,
+ Kind: site.ErrKindNetwork,
+ Message: fmt.Sprintf("Content-Range 校验失败: %q (offset=%d, knownTotal=%d)", cr, offset, knownTotal),
+ }
+ }
+ if total > 0 {
+ totalSize = total
+ }
+ expectedSegLen = end - start + 1
+ if resp.ContentLength >= 0 && resp.ContentLength != expectedSegLen {
+ return segmentResult{newOffset: offset}, rawCT, &site.Error{Site: spec.site, Kind: site.ErrKindNetwork, Message: "分段 Content-Length 与区间长度不一致"}
+ }
+ if totalSize > 0 && end+1 >= totalSize {
+ doneAfterThis = true
+ }
+ seekToOffset = true
+
+ case http.StatusOK:
+ if offset > 0 {
+ // Subsequent segment returned 200 OK instead of 206: truncate .part, rotate node, and retry from 0 (data-and-cache.md §2.4).
+ _ = os.Remove(partPath)
+ return segmentResult{newOffset: 0, truncatedToZero: true}, rawCT, &site.Error{
+ Site: spec.site,
+ Kind: site.ErrKindNetwork,
+ HTTPStatus: http.StatusOK,
+ Message: "节点未返回 206 Partial Content,已截断从头重试",
+ }
+ }
+ if resp.ContentLength <= 0 {
+ return segmentResult{newOffset: offset}, rawCT, &site.Error{Site: spec.site, Kind: site.ErrKindNetwork, Message: "完整响应缺少有效的 Content-Length"}
+ }
+ expectedSegLen = resp.ContentLength
+ totalSize = resp.ContentLength
+ doneAfterThis = true
+ openFlags = os.O_CREATE | os.O_WRONLY | os.O_TRUNC
+
+ default:
+ return segmentResult{newOffset: offset}, rawCT, mapMediaHTTPStatus(spec.site, resp.StatusCode, safeEndpoint)
+ }
+
+ // Reject oversized images before opening or truncating .part on disk.
+ if isImage && totalSize > MaxImageFileBytes {
+ return segmentResult{newOffset: offset}, rawCT, &site.Error{
+ Site: spec.site,
+ Kind: site.ErrKindSchemaChanged,
+ Message: "图片超过 50 MiB",
+ }
+ }
+
+ f, err := os.OpenFile(partPath, openFlags, 0o600)
+ if err != nil {
+ return segmentResult{newOffset: offset}, rawCT, err
+ }
+ if seekToOffset {
+ if _, err := f.Seek(offset, io.SeekStart); err != nil {
+ _ = f.Close()
+ return segmentResult{newOffset: offset}, rawCT, err
+ }
+ }
+
+ wrapped := resp.Body
+ if spec.wrapBody != nil {
+ wrapped = spec.wrapBody(resp.Body)
+ }
+ defer wrapped.Close()
+ reader := io.LimitReader(wrapped, expectedSegLen+1)
+
+ buf := make([]byte, 64*1024)
+ var segWritten int64
+ written := offset
+ checkedHead := !spec.checkDisguised || offset > 0
+ if totalSize > 0 {
+ t.TotalBytes = totalSize
+ } else if resp.ContentLength > 0 {
+ t.TotalBytes = offset + resp.ContentLength
+ }
+
+ progressAt := time.Now()
+ progressBytes := offset
+ for {
+ nr, rErr := reader.Read(buf)
+ if nr > 0 {
+ if !checkedHead {
+ checkedHead = true
+ if looksLikeDisguisedTextBody(buf[:nr]) {
+ _ = f.Close()
+ _ = os.Remove(partPath)
+ return segmentResult{newOffset: 0}, rawCT, &site.Error{
+ Site: spec.site,
+ Kind: site.ErrKindSchemaChanged,
+ HTTPStatus: resp.StatusCode,
+ Message: "媒体响应正文为 HTML 或 JSON 文本,已拒绝写入",
+ }
+ }
+ }
+ if segWritten+int64(nr) > expectedSegLen {
+ _ = f.Close()
+ if tErr := os.Truncate(partPath, offset); tErr != nil {
+ return segmentResult{newOffset: offset}, rawCT, tErr
+ }
+ return segmentResult{newOffset: offset, totalSize: totalSize}, rawCT, &site.Error{Site: spec.site, Kind: site.ErrKindNetwork, Message: "分段正文超出声明区间"}
+ }
+ nw, wErr := f.Write(buf[:nr])
+ if wErr != nil {
+ _ = f.Close()
+ return segmentResult{newOffset: written, totalSize: totalSize}, rawCT, wErr
+ }
+ segWritten += int64(nw)
+ written += int64(nw)
+ t.BytesDownloaded = written
+ if t.TotalBytes > 0 {
+ t.Progress = float64(written) / float64(t.TotalBytes)
+ if t.Progress > 0.99 {
+ t.Progress = 0.99
+ }
+ }
+ }
+ if elapsed := time.Since(progressAt); elapsed >= time.Second {
+ speed := int64(float64(written-progressBytes) / elapsed.Seconds())
+ for i := range t.Files {
+ fid := taskFileIdentity(t.Files[i].Path)
+ if fid == relID || (trimmedID != "" && fid == trimmedID) {
+ t.Files[i].DownloadedBytes = written
+ t.Files[i].TotalBytes = t.TotalBytes
+ t.Files[i].SpeedBps = speed
+ t.Files[i].Status = "downloading"
+ }
+ }
+ m.persistTaskProgress(*t)
+ progressAt = time.Now()
+ progressBytes = written
+ }
+
+ if rErr != nil {
+ if rErr == io.EOF {
+ break
+ }
+ _ = f.Sync()
+ _ = f.Close()
+ return segmentResult{newOffset: written, totalSize: totalSize}, rawCT, &site.Error{
+ Site: spec.site,
+ Kind: site.ErrKindNetwork,
+ Endpoint: safeEndpoint,
+ Message: "媒体分段读取中断",
+ Err: site.UnwrapURLError(rErr),
+ }
+ }
+ }
+
+ if err := f.Sync(); err != nil {
+ _ = f.Close()
+ return segmentResult{newOffset: written, totalSize: totalSize}, rawCT, err
+ }
+ if err := f.Close(); err != nil {
+ return segmentResult{newOffset: written, totalSize: totalSize}, rawCT, err
+ }
+
+ if expectedSegLen >= 0 && segWritten != expectedSegLen {
+ return segmentResult{newOffset: written, totalSize: totalSize}, rawCT, &site.Error{
+ Site: spec.site,
+ Kind: site.ErrKindNetwork,
+ Endpoint: safeEndpoint,
+ Message: fmt.Sprintf("分段字节未读满: 实读 %d < 预期 %d", segWritten, expectedSegLen),
+ }
+ }
+
+ return segmentResult{
+ newOffset: written,
+ totalSize: totalSize,
+ done: doneAfterThis,
+ }, rawCT, nil
+}
+
+func newGuardedMediaTransport(siteID site.ID, allowLocalhost bool) *http.Transport {
+ dialer := &net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}
+ guard := site.NewGuardedMediaDialer(siteID, allowLocalhost, dialer, "已拦截内网或回环媒体节点地址")
+ return &http.Transport{
+ Proxy: guard.Proxy,
+ MaxIdleConns: 16,
+ IdleConnTimeout: 60 * time.Second,
+ TLSHandshakeTimeout: 10 * time.Second,
+ ResponseHeaderTimeout: 10 * time.Second,
+ ExpectContinueTimeout: 1 * time.Second,
+ DialContext: guard.DialContext,
+ }
+}
+
+func makeMediaRedirectCheck(spec site.MediaTransportSpec) func(req *http.Request, via []*http.Request) error {
+ return func(req *http.Request, via []*http.Request) error {
+ if len(via) >= 5 {
+ return &site.Error{
+ Site: spec.Site,
+ Kind: site.ErrKindBlocked,
+ Message: "媒体重定向超过 5 跳上限",
+ }
+ }
+ if err := spec.ValidateRedirectURL(req.URL.String()); err != nil {
+ return err
+ }
+ spec.ApplyHeaders(req)
+ return nil
+ }
+}
+
+func newTransportHTTPClient(spec site.MediaTransportSpec) *http.Client {
+ return &http.Client{
+ Transport: newGuardedMediaTransport(spec.Site, spec.AllowLocalhost),
+ CheckRedirect: makeMediaRedirectCheck(spec),
+ }
+}
+
+func (m *Manager) transportHTTPClient(spec site.MediaTransportSpec) *http.Client {
+ key := mediaTransportKey{site: spec.Site, allowLocalhost: spec.AllowLocalhost}
+ m.mu.Lock()
+ if m.transports == nil {
+ m.transports = make(map[mediaTransportKey]*http.Transport)
+ }
+ tr, ok := m.transports[key]
+ if !ok {
+ tr = newGuardedMediaTransport(spec.Site, spec.AllowLocalhost)
+ m.transports[key] = tr
+ }
+ mediaWrap := m.mediaWrap
+ m.mu.Unlock()
+
+ var rt http.RoundTripper = tr
+ if mediaWrap != nil {
+ rt = mediaWrap(tr)
+ }
+ return &http.Client{
+ Transport: rt,
+ CheckRedirect: makeMediaRedirectCheck(spec),
+ }
+}
+
+func parseContentRange(cr string) (start, end, total int64, ok bool) {
+ cr = strings.TrimSpace(cr)
+ if !strings.HasPrefix(strings.ToLower(cr), "bytes ") {
+ return 0, 0, 0, false
+ }
+ rest := strings.TrimSpace(cr[6:])
+ slashIdx := strings.IndexByte(rest, '/')
+ if slashIdx <= 0 {
+ return 0, 0, 0, false
+ }
+ rangePart := rest[:slashIdx]
+ totalPart := rest[slashIdx+1:]
+ dashIdx := strings.IndexByte(rangePart, '-')
+ if dashIdx <= 0 {
+ return 0, 0, 0, false
+ }
+ sVal, err1 := strconv.ParseInt(strings.TrimSpace(rangePart[:dashIdx]), 10, 64)
+ eVal, err2 := strconv.ParseInt(strings.TrimSpace(rangePart[dashIdx+1:]), 10, 64)
+ if err1 != nil || err2 != nil || sVal < 0 || eVal < sVal {
+ return 0, 0, 0, false
+ }
+ var tVal int64 = -1
+ if totalPart != "*" {
+ parsedTotal, err3 := strconv.ParseInt(strings.TrimSpace(totalPart), 10, 64)
+ if err3 != nil || parsedTotal <= 0 {
+ return 0, 0, 0, false
+ }
+ tVal = parsedTotal
+ }
+ return sVal, eVal, tVal, true
+}
+
+func mapMediaHTTPStatus(siteID site.ID, status int, endpoint string) *site.Error {
+ endpoint = site.SanitizeEndpoint(endpoint)
+ switch status {
+ case 401:
+ return &site.Error{Site: siteID, Kind: site.ErrKindAuthRequired, HTTPStatus: status, Endpoint: endpoint, Message: "媒体需要登录凭证 (401)"}
+ case 403:
+ return &site.Error{Site: siteID, Kind: site.ErrKindForbidden, HTTPStatus: status, Endpoint: endpoint, Message: "媒体访问被拒绝 (403)"}
+ case 404, 410:
+ return &site.Error{Site: siteID, Kind: site.ErrKindUnavailable, HTTPStatus: status, Endpoint: endpoint, Message: fmt.Sprintf("媒体资源已失效 (%d)", status)}
+ case 412:
+ return &site.Error{Site: siteID, Kind: site.ErrKindRiskControl, HTTPStatus: status, Endpoint: endpoint, Message: "媒体请求触发风控 (412)"}
+ case 429:
+ return &site.Error{Site: siteID, Kind: site.ErrKindRateLimited, HTTPStatus: status, Endpoint: endpoint, Message: "媒体请求触发限流 (429)"}
+ default:
+ return &site.Error{Site: siteID, Kind: site.ErrKindNetwork, HTTPStatus: status, Endpoint: endpoint, Message: fmt.Sprintf("媒体 HTTP 状态异常 (%d)", status)}
+ }
+}
diff --git a/internal/download/single_mp4.go b/internal/download/single_mp4.go
index 6833dd1..33e0a84 100644
--- a/internal/download/single_mp4.go
+++ b/internal/download/single_mp4.go
@@ -82,8 +82,8 @@ type singleMP4Inspection struct {
}
// EnsureSingleMP4 validates a progressive single-file MP4 on disk (without requiring elst),
-// rejects CENC-encrypted tracks and >2s duration mismatches, and relocates moov before mdat
-// on disk with bounded memory when moov trails mdat.
+// rejects CENC-encrypted tracks and duration mismatches exceeding max(2s, 3%), and relocates
+// moov before mdat on disk with bounded memory when moov trails mdat.
func EnsureSingleMP4(path string, expectedDurationSec float64) (MuxTrackSummary, error) {
return EnsureSingleMP4Context(context.Background(), path, expectedDurationSec)
}
diff --git a/internal/download/slow_media_test.go b/internal/download/slow_media_test.go
index 5124e10..8742b6d 100644
--- a/internal/download/slow_media_test.go
+++ b/internal/download/slow_media_test.go
@@ -23,7 +23,7 @@ import (
"github.com/chialecode/trace/internal/storage"
)
-// C17 (scaled): media reads have only an idle timeout, never a total timeout.
+// Media reads have only an idle timeout, never a total timeout.
// A segment that trickles in far longer than the idle timeout must complete,
// and a stall longer than the idle timeout must resume from the breakpoint.
func TestSlowMediaUsesIdleTimeoutNotTotalTimeout(t *testing.T) {
diff --git a/internal/download/sniff.go b/internal/download/sniff.go
new file mode 100644
index 0000000..f106f73
--- /dev/null
+++ b/internal/download/sniff.go
@@ -0,0 +1,210 @@
+package download
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "mime"
+ "net/url"
+ "os"
+ "strings"
+
+ "github.com/chialecode/trace/internal/site"
+)
+
+func rejectDisguisedMediaContentType(siteID site.ID, rawCT, role string, statusCode int) error {
+ mediaType, _, err := mime.ParseMediaType(rawCT)
+ if err != nil {
+ mediaType = strings.ToLower(strings.TrimSpace(strings.SplitN(rawCT, ";", 2)[0]))
+ }
+ mediaType = strings.ToLower(strings.TrimSpace(mediaType))
+ switch mediaType {
+ case "text/html", "application/xhtml+xml", "application/json", "text/json", "text/plain", "text/xml", "application/xml", "application/javascript", "text/javascript":
+ return &site.Error{
+ Site: siteID,
+ Kind: site.ErrKindSchemaChanged,
+ HTTPStatus: statusCode,
+ Message: fmt.Sprintf("媒体请求返回了非媒体类型 (%s)", mediaType),
+ }
+ }
+ if (role == "image" || role == "cover") && mediaType != "" &&
+ !strings.HasPrefix(mediaType, "image/") && mediaType != "application/octet-stream" {
+ return &site.Error{
+ Site: siteID,
+ Kind: site.ErrKindSchemaChanged,
+ HTTPStatus: statusCode,
+ Message: fmt.Sprintf("图片响应不是有效的图片类型 (%s)", mediaType),
+ }
+ }
+ return nil
+}
+
+func looksLikeDisguisedTextBody(head []byte) bool {
+ trimmed := bytes.TrimLeft(head, " \t\r\n")
+ if len(trimmed) == 0 {
+ return false
+ }
+ lower := bytes.ToLower(trimmed[:min(len(trimmed), 32)])
+ if bytes.HasPrefix(lower, []byte("= 3 && b[0] == 0xFF && b[1] == 0xD8 && b[2] == 0xFF:
+ return ".jpg", nil
+ case len(b) >= 8 && bytes.Equal(b[:8], []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1A, '\n'}):
+ return ".png", nil
+ case len(b) >= 12 && bytes.Equal(b[:4], []byte("RIFF")) && bytes.Equal(b[8:12], []byte("WEBP")):
+ return ".webp", nil
+ case len(b) >= 6 && (bytes.Equal(b[:6], []byte("GIF87a")) || bytes.Equal(b[:6], []byte("GIF89a"))):
+ return ".gif", nil
+ case len(b) >= 12 && bytes.Equal(b[4:8], []byte("ftyp")):
+ brand := string(b[8:12])
+ switch brand {
+ case "avif", "avis":
+ return ".avif", nil
+ case "heic", "heix", "hevc", "hevx", "mif1", "msf1":
+ return ".heic", nil
+ }
+ }
+
+ mt, _, _ := mime.ParseMediaType(contentType)
+ switch strings.ToLower(strings.TrimSpace(mt)) {
+ case "image/jpeg", "image/jpg":
+ if len(b) >= 4 && !looksLikeDisguisedTextBody(b) {
+ return ".jpg", nil
+ }
+ case "image/png":
+ if len(b) >= 4 && !looksLikeDisguisedTextBody(b) {
+ return ".png", nil
+ }
+ case "image/webp":
+ if len(b) >= 4 && !looksLikeDisguisedTextBody(b) {
+ return ".webp", nil
+ }
+ case "image/gif":
+ if len(b) >= 4 && !looksLikeDisguisedTextBody(b) {
+ return ".gif", nil
+ }
+ case "image/avif":
+ if len(b) >= 4 && !looksLikeDisguisedTextBody(b) {
+ return ".avif", nil
+ }
+ case "image/heic", "image/heif":
+ if len(b) >= 4 && !looksLikeDisguisedTextBody(b) {
+ return ".heic", nil
+ }
+ }
+ return "", errors.New("文件头不是受支持的图片格式")
+}
+
+func sniffAudioExtension(filePath, contentType string) (string, error) {
+ f, err := os.Open(filePath)
+ if err != nil {
+ return "", err
+ }
+ defer f.Close()
+ var head [32]byte
+ n, _ := io.ReadFull(f, head[:])
+ b := head[:n]
+ if len(b) == 0 || looksLikeDisguisedTextBody(b) {
+ return "", errors.New("配乐文件不是有效的音频格式")
+ }
+
+ switch {
+ case len(b) >= 3 && bytes.Equal(b[:3], []byte("ID3")):
+ return ".mp3", nil
+ case len(b) >= 2 && b[0] == 0xFF && (b[1]&0xF6) == 0xF0:
+ return ".aac", nil
+ case len(b) >= 2 && b[0] == 0xFF && (b[1]&0xE0) == 0xE0 && ((b[1]>>1)&0x03) != 0:
+ return ".mp3", nil
+ case len(b) >= 12 && bytes.Equal(b[4:8], []byte("ftyp")):
+ return ".m4a", nil
+ case len(b) >= 4 && bytes.Equal(b[:4], []byte("OggS")):
+ return ".ogg", nil
+ case len(b) >= 4 && bytes.Equal(b[:4], []byte("fLaC")):
+ return ".flac", nil
+ case len(b) >= 12 && bytes.Equal(b[:4], []byte("RIFF")) && bytes.Equal(b[8:12], []byte("WAVE")):
+ return ".wav", nil
+ case len(b) >= 4 && bytes.Equal(b[:4], []byte{0x1A, 0x45, 0xDF, 0xA3}):
+ return ".webm", nil
+ }
+
+ mt, _, _ := mime.ParseMediaType(contentType)
+ switch strings.ToLower(strings.TrimSpace(mt)) {
+ case "audio/mpeg", "audio/mp3":
+ return ".mp3", nil
+ case "audio/mp4", "audio/x-m4a", "audio/m4a", "video/mp4":
+ return ".m4a", nil
+ case "audio/aac", "audio/aacp":
+ return ".aac", nil
+ case "audio/ogg", "application/ogg":
+ return ".ogg", nil
+ case "audio/flac":
+ return ".flac", nil
+ case "audio/wav", "audio/x-wav", "audio/wave":
+ return ".wav", nil
+ case "audio/webm":
+ return ".webm", nil
+ }
+ return "", errors.New("配乐文件不是受支持的音频格式")
+}
+
+func firstNonEmptyStr(vals ...string) string {
+ for _, v := range vals {
+ if s := strings.TrimSpace(v); s != "" {
+ return s
+ }
+ }
+ return ""
+}
+
+func sanitizeStoredURL(raw string) string {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return ""
+ }
+ u, err := url.Parse(raw)
+ if err != nil || u.Scheme == "" || u.Host == "" {
+ return ""
+ }
+ u.User = nil
+ u.RawQuery = ""
+ u.Fragment = ""
+ return u.String()
+}
+
+func summaryPrimaryVideoCodec(s MuxTrackSummary) string {
+ for i, h := range s.Handlers {
+ if h == "vide" && i < len(s.Codecs) {
+ switch s.Codecs[i] {
+ case "avc1", "avc3":
+ return "avc"
+ case "hvc1", "hev1":
+ return "hevc"
+ default:
+ return s.Codecs[i]
+ }
+ }
+ }
+ return ""
+}
diff --git a/internal/download/task_store.go b/internal/download/task_store.go
new file mode 100644
index 0000000..69fc0d6
--- /dev/null
+++ b/internal/download/task_store.go
@@ -0,0 +1,696 @@
+package download
+
+import (
+ "crypto/rand"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/url"
+ "os"
+ "path"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/site/bilibili"
+ "github.com/chialecode/trace/internal/storage"
+)
+
+const taskSelectColumns = `
+ task_id, site, kind, source, target_id, cid, page, title, part_title,
+ mid, author_uid, author_name, author_face, cover_url, cache_linked_videos,
+ status, pause_reason, error_kind, error_message, quality_hint,
+ bytes_downloaded, total_bytes, progress, item_key, item_dir,
+ files_json, attempts_json, created_at, updated_at, via_json`
+
+func (m *Manager) initSchema() error {
+ stmts := []string{
+ `CREATE TABLE IF NOT EXISTS download_tasks (
+ task_id TEXT PRIMARY KEY,
+ site TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ source TEXT NOT NULL DEFAULT 'manual',
+ target_id TEXT NOT NULL,
+ cid INTEGER NOT NULL DEFAULT 0,
+ page INTEGER NOT NULL DEFAULT 1,
+ title TEXT NOT NULL DEFAULT '',
+ part_title TEXT NOT NULL DEFAULT '',
+ mid INTEGER NOT NULL DEFAULT 0,
+ author_uid TEXT NOT NULL DEFAULT '',
+ author_name TEXT NOT NULL DEFAULT '',
+ author_face TEXT NOT NULL DEFAULT '',
+ cover_url TEXT NOT NULL DEFAULT '',
+ cache_linked_videos INTEGER NOT NULL DEFAULT 0,
+ status TEXT NOT NULL DEFAULT 'queued',
+ pause_reason TEXT NOT NULL DEFAULT '',
+ error_kind TEXT NOT NULL DEFAULT '',
+ error_message TEXT NOT NULL DEFAULT '',
+ quality_hint TEXT NOT NULL DEFAULT '',
+ bytes_downloaded INTEGER NOT NULL DEFAULT 0,
+ total_bytes INTEGER NOT NULL DEFAULT 0,
+ progress REAL NOT NULL DEFAULT 0,
+ item_key TEXT NOT NULL DEFAULT '',
+ item_dir TEXT NOT NULL DEFAULT '',
+ files_json TEXT NOT NULL DEFAULT '[]',
+ attempts_json TEXT NOT NULL DEFAULT '[]',
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+ );`,
+ `CREATE TABLE IF NOT EXISTS task_attempts (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ task_id TEXT NOT NULL,
+ attempt_time TEXT NOT NULL,
+ file_path TEXT NOT NULL,
+ offset_bytes INTEGER NOT NULL DEFAULT 0,
+ host TEXT NOT NULL DEFAULT '',
+ attempt_num INTEGER NOT NULL DEFAULT 1,
+ error_kind TEXT NOT NULL DEFAULT '',
+ http_status INTEGER NOT NULL DEFAULT 0
+ );`,
+ }
+ for _, q := range stmts {
+ if _, err := m.db.Exec(q); err != nil {
+ return err
+ }
+ }
+ // Ensure columns exist on databases created before schema additions.
+ for _, alter := range []string{
+ `ALTER TABLE download_tasks ADD COLUMN source TEXT NOT NULL DEFAULT 'manual'`,
+ `ALTER TABLE download_tasks ADD COLUMN author_uid TEXT NOT NULL DEFAULT ''`,
+ `ALTER TABLE download_tasks ADD COLUMN pause_reason TEXT NOT NULL DEFAULT ''`,
+ `ALTER TABLE download_tasks ADD COLUMN files_json TEXT NOT NULL DEFAULT '[]'`,
+ `ALTER TABLE download_tasks ADD COLUMN attempts_json TEXT NOT NULL DEFAULT '[]'`,
+ `ALTER TABLE download_tasks ADD COLUMN via_json TEXT NOT NULL DEFAULT ''`,
+ } {
+ _, _ = m.db.Exec(alter)
+ }
+ return nil
+}
+
+func (m *Manager) enqueueSingleTask(in Task) (Task, error) {
+ return m.enqueueSingleTaskWithPlan(in, nil)
+}
+
+func (m *Manager) enqueueSingleTaskWithPlan(in Task, initialPlan *WorkDownloadPlan) (Task, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ if in.Site == "" {
+ in.Site = "bilibili"
+ }
+ if in.AuthorUID == "" && in.Mid > 0 && in.Site == "bilibili" {
+ in.AuthorUID = strconv.FormatInt(in.Mid, 10)
+ }
+
+ // Deduplicate if an identical task for the same site is already queued or running.
+ existing, ok, err := m.findActiveOrQueuedLocked(in.Site, in.Kind, in.TargetID, in.CID)
+ if err != nil {
+ return Task{}, err
+ }
+ if ok {
+ if initialPlan != nil && existing.Status == "queued" {
+ if _, has := m.initialPlans[existing.TaskID]; !has {
+ m.initialPlans[existing.TaskID] = *initialPlan
+ }
+ }
+ return existing, nil
+ }
+
+ now := time.Now().UTC().Format(time.RFC3339)
+ var rnd [6]byte
+ _, _ = rand.Read(rnd[:])
+ in.TaskID = "dl-" + hex.EncodeToString(rnd[:])
+ in.Status = "queued"
+ if in.Source == "" {
+ in.Source = "manual"
+ }
+ in.CreatedAt = now
+ in.UpdatedAt = now
+
+ linkedInt := 0
+ if in.CacheLinkedVideos {
+ linkedInt = 1
+ }
+
+ filesJSON, _ := json.Marshal(in.Files)
+ attemptsJSON, _ := json.Marshal(in.Attempts)
+
+ _, err = m.db.Exec(`
+ INSERT INTO download_tasks (
+ task_id, site, kind, source, target_id, cid, page, title, part_title,
+ mid, author_uid, author_name, author_face, cover_url, cache_linked_videos,
+ status, pause_reason, error_kind, error_message, quality_hint,
+ bytes_downloaded, total_bytes, progress, item_key, item_dir,
+ files_json, attempts_json, created_at, updated_at, via_json
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '', '', '', '', 0, 0, 0, ?, ?, ?, ?, ?, ?, ?)
+ `,
+ in.TaskID, in.Site, in.Kind, in.Source, in.TargetID, in.CID, in.Page, in.Title, in.PartTitle,
+ in.Mid, in.AuthorUID, in.AuthorName, in.AuthorFace, in.CoverURL, linkedInt,
+ in.Status, in.ItemKey, in.ItemDir, string(filesJSON), string(attemptsJSON), in.CreatedAt, in.UpdatedAt, viaJSON(in.Via),
+ )
+ if err != nil {
+ return Task{}, err
+ }
+ if initialPlan != nil {
+ m.initialPlans[in.TaskID] = *initialPlan
+ }
+ return in, nil
+}
+
+func (m *Manager) findActiveOrQueuedLocked(siteID, kind, targetID string, cid int64) (Task, bool, error) {
+ row := m.db.QueryRow(`SELECT`+taskSelectColumns+`
+ FROM download_tasks
+ WHERE site = ? AND kind = ? AND target_id = ? AND cid = ? AND status IN ('queued', 'running')
+ LIMIT 1
+ `, siteID, kind, targetID, cid)
+ t, err := scanTask(row)
+ if err != nil {
+ if err == sql.ErrNoRows {
+ return Task{}, false, nil
+ }
+ return Task{}, false, err
+ }
+ return t, true, nil
+}
+
+// ListTasks returns active tasks first, then tasks needing action, then finished
+// tasks, with the most recently updated task first within each group.
+func (m *Manager) ListTasks() ([]Task, error) {
+ rows, err := m.db.Query(`SELECT` + taskSelectColumns + `
+ FROM download_tasks
+ ORDER BY CASE WHEN status IN ('running', 'queued') THEN 0 WHEN status IN ('paused', 'failed', 'partial') THEN 1 ELSE 2 END,
+ julianday(updated_at) DESC, rowid DESC
+ `)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var out []Task
+ for rows.Next() {
+ t, err := scanTask(rows)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, m.withTaskFault(t))
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ rows.Close()
+ for i := range out {
+ m.fillPartialReason(&out[i])
+ }
+ return out, nil
+}
+
+// GetTask retrieves a single task by taskID.
+func (m *Manager) GetTask(taskID string) (Task, bool, error) {
+ row := m.db.QueryRow(`SELECT`+taskSelectColumns+`
+ FROM download_tasks
+ WHERE task_id = ?
+ `, taskID)
+ t, err := scanTask(row)
+ if err != nil {
+ if err == sql.ErrNoRows {
+ return Task{}, false, nil
+ }
+ return Task{}, false, err
+ }
+ t = m.withTaskFault(t)
+ m.fillPartialReason(&t)
+ return t, true, nil
+}
+
+// TaskDetail returns the task along with its per-file progress manifest and desensitized attempt log.
+func (m *Manager) TaskDetail(taskID string) (TaskDetail, bool, error) {
+ t, ok, err := m.GetTask(taskID)
+ if err != nil || !ok {
+ return TaskDetail{}, ok, err
+ }
+ return TaskDetail{
+ Task: t,
+ Files: t.Files,
+ Attempts: t.Attempts,
+ }, true, nil
+}
+
+func (m *Manager) claimNextQueuedLocked() (Task, bool) {
+ query := `SELECT` + taskSelectColumns + `
+ FROM download_tasks
+ WHERE status = 'queued'`
+ var args []any
+ if len(m.activeRun) > 0 {
+ query += " AND task_id NOT IN (" + strings.TrimSuffix(strings.Repeat("?,", len(m.activeRun)), ",") + ")"
+ for id := range m.activeRun {
+ args = append(args, id)
+ }
+ }
+ query += " ORDER BY rowid ASC LIMIT 1"
+ row := m.db.QueryRow(query, args...)
+ t, err := scanTask(row)
+ if err != nil {
+ return Task{}, false
+ }
+ now := time.Now().UTC().Format(time.RFC3339)
+ res, err := m.db.Exec(`
+ UPDATE download_tasks
+ SET status = 'running', pause_reason = '', error_kind = '', error_message = '', updated_at = ?
+ WHERE task_id = ? AND status = 'queued'
+ `, now, t.TaskID)
+ if err != nil {
+ return Task{}, false
+ }
+ if n, _ := res.RowsAffected(); n == 0 {
+ return Task{}, false
+ }
+ t.Status = "running"
+ t.PauseReason = ""
+ t.ErrorKind = ""
+ t.ErrorMessage = ""
+ t.UpdatedAt = now
+ return t, true
+}
+
+func (m *Manager) setFileProgress(t *Task, role, relPath, status string, downloaded, total, speed int64) {
+ found := false
+ for i := range t.Files {
+ if t.Files[i].Path == relPath {
+ t.Files[i].Role = role
+ t.Files[i].Status = status
+ t.Files[i].DownloadedBytes = downloaded
+ if total > 0 {
+ t.Files[i].TotalBytes = total
+ }
+ t.Files[i].SpeedBps = speed
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Files = append(t.Files, TaskFileProgress{
+ Role: role,
+ Path: relPath,
+ Status: status,
+ DownloadedBytes: downloaded,
+ TotalBytes: total,
+ SpeedBps: speed,
+ })
+ }
+}
+
+func (m *Manager) recordAttempt(t *Task, relFile string, offset int64, rawURL string, attempt int, errKind string, httpStatus int) {
+ host := ""
+ if u, err := url.Parse(rawURL); err == nil {
+ host = u.Hostname()
+ }
+ entry := TaskAttempt{
+ Time: time.Now().UTC().Format(time.RFC3339),
+ File: relFile,
+ Offset: offset,
+ Host: host,
+ Attempt: attempt,
+ ErrorKind: errKind,
+ HTTPStatus: httpStatus,
+ }
+ t.Attempts = append(t.Attempts, entry)
+ if len(t.Attempts) > 200 {
+ t.Attempts = t.Attempts[len(t.Attempts)-200:]
+ }
+ ownerID := t.TaskID
+ if ownerID == "" && t.ProgressOwner != nil {
+ ownerID = t.ProgressOwner.TaskID
+ t.ProgressOwner.Attempts = t.Attempts
+ }
+ if ownerID != "" && m.db != nil {
+ _, _ = m.db.Exec(`
+ INSERT INTO task_attempts (task_id, attempt_time, file_path, offset_bytes, host, attempt_num, error_kind, http_status)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+ `, ownerID, entry.Time, entry.File, entry.Offset, entry.Host, entry.Attempt, entry.ErrorKind, entry.HTTPStatus)
+ }
+}
+
+func (m *Manager) saveTaskProgress(t Task) error {
+ if t.ProgressOwner != nil {
+ owner := t.ProgressOwner
+ for _, file := range t.Files {
+ file.Path = t.ProgressPrefix + file.Path
+ file.ItemDir = t.ItemDir
+ found := false
+ for i := range owner.Files {
+ if owner.Files[i].Path == file.Path {
+ owner.Files[i], found = file, true
+ break
+ }
+ }
+ if !found {
+ owner.Files = append(owner.Files, file)
+ }
+ }
+ if t.BytesDownloaded > 0 || t.TotalBytes > 0 {
+ owner.BytesDownloaded = t.BytesDownloaded
+ owner.TotalBytes = t.TotalBytes
+ owner.Progress = t.Progress
+ }
+ owner.Attempts = t.Attempts
+ return m.saveTaskProgress(*owner)
+ }
+ now := time.Now().UTC().Format(time.RFC3339)
+ t.UpdatedAt = now
+ if t.ErrorMessage == "" && t.LastError != "" {
+ t.ErrorMessage = t.LastError
+ }
+ t.LastError = t.ErrorMessage
+ filesJSON, _ := json.Marshal(t.Files)
+ attemptsJSON, _ := json.Marshal(t.Attempts)
+ res, err := m.db.Exec(`
+ UPDATE download_tasks
+ SET
+ cid = ?, page = ?, title = ?, part_title = ?,
+ mid = ?, author_uid = ?, author_name = ?, author_face = ?, cover_url = ?,
+ status = ?, pause_reason = ?, error_kind = ?, error_message = ?, quality_hint = ?,
+ bytes_downloaded = ?, total_bytes = ?, progress = ?,
+ item_key = ?, item_dir = ?, files_json = ?, attempts_json = ?, updated_at = ?
+ WHERE task_id = ? AND status = 'running'
+ `,
+ t.CID, t.Page, t.Title, t.PartTitle,
+ t.Mid, t.AuthorUID, t.AuthorName, t.AuthorFace, t.CoverURL,
+ t.Status, t.PauseReason, t.ErrorKind, t.ErrorMessage, t.QualityHint,
+ t.BytesDownloaded, t.TotalBytes, t.Progress,
+ t.ItemKey, t.ItemDir, string(filesJSON), string(attemptsJSON), t.UpdatedAt,
+ t.TaskID,
+ )
+ if err != nil {
+ return err
+ }
+ if changed, _ := res.RowsAffected(); changed == 0 {
+ return nil
+ }
+ m.taskFaults.Delete(t.TaskID)
+ m.emitUpdate(t)
+ return nil
+}
+
+func (m *Manager) emitUpdate(t Task) {
+ if t.ErrorMessage == "" && t.LastError != "" {
+ t.ErrorMessage = t.LastError
+ }
+ t.LastError = t.ErrorMessage
+ if m.onTaskUpdate != nil && t.TaskID != "" {
+ m.notifyMu.Lock()
+ if m.lastNotify == nil {
+ m.lastNotify = make(map[string]taskNotification)
+ }
+ previous := m.lastNotify[t.TaskID]
+ if previous.status == t.Status && t.Status == "running" && time.Since(previous.at) < time.Second {
+ m.notifyMu.Unlock()
+ return
+ }
+ switch t.Status {
+ case "completed", "failed", "canceled", "partial":
+ delete(m.lastNotify, t.TaskID)
+ default:
+ m.lastNotify[t.TaskID] = taskNotification{status: t.Status, at: time.Now()}
+ }
+ m.notifyMu.Unlock()
+ m.onTaskUpdate(t)
+ }
+}
+
+type taskNotification struct {
+ status string
+ at time.Time
+}
+
+func (m *Manager) persistTaskProgress(task Task) {
+ if err := m.saveTaskProgress(task); err != nil {
+ task.Status, task.ErrorKind, task.ErrorMessage = "failed", "storage", "任务状态写入失败,请检查存储后重试"
+ m.taskFaults.Store(task.TaskID, task)
+ m.emitUpdate(task)
+ }
+}
+
+func (m *Manager) withTaskFault(task Task) Task {
+ if fault, exists := m.taskFaults.Load(task.TaskID); exists {
+ return fault.(Task)
+ }
+ return task
+}
+
+// fillPartialReason backfills the concise missing-item summary on partial tasks
+// whose persisted error_message was left empty (for example, items recorded
+// before partial reasons were preserved on download_tasks). Must only be called
+// when no active rows cursor holds the single SQLite connection.
+func (m *Manager) fillPartialReason(task *Task) {
+ if task == nil || task.Status != "partial" || m.lib == nil {
+ return
+ }
+ if strings.TrimSpace(task.ErrorMessage) != "" || strings.TrimSpace(task.LastError) != "" || strings.TrimSpace(task.ItemKey) == "" {
+ return
+ }
+ if meta, ok, err := m.lib.GetItem(task.ItemKey); err == nil && ok && len(meta.Missing) > 0 {
+ task.ErrorMessage = summarizeMissingReasons(meta.Missing)
+ }
+}
+
+// Register task ownership before creating any file. A pre-existing name with
+// no task checkpoint or manifest is a user file, and must never be replaced.
+func (m *Manager) claimTaskFile(t *Task, root, rel, finalPath string) error {
+ owned := false
+ for _, file := range t.Files {
+ if taskFileIdentity(file.Path) == taskFileIdentity(rel) && taskFileOwned(file) {
+ owned = true
+ }
+ }
+ if t.ProgressOwner != nil {
+ for _, file := range t.ProgressOwner.Files {
+ if taskFileIdentity(file.Path) == taskFileIdentity(t.ProgressPrefix+rel) && strings.EqualFold(file.ItemDir, root) && taskFileOwned(file) {
+ owned = true
+ }
+ }
+ }
+ if m.lib != nil {
+ if meta, ok, err := m.lib.GetItem(t.ItemKey); err != nil {
+ return err
+ } else if ok && strings.EqualFold(meta.ItemDir, root) {
+ for _, file := range meta.Media {
+ if taskFileIdentity(file.Path) == taskFileIdentity(rel) {
+ owned = true
+ }
+ }
+ }
+ }
+ if !owned {
+ for _, p := range []string{finalPath, finalPath + ".part"} {
+ if _, err := os.Lstat(p); err == nil {
+ return &bilibili.SiteError{Kind: "storage", Message: "目标文件已存在且未由本任务登记,已保留原文件"}
+ } else if !os.IsNotExist(err) {
+ return err
+ }
+ }
+ }
+ found := false
+ for i := range t.Files {
+ if taskFileIdentity(t.Files[i].Path) == taskFileIdentity(rel) {
+ t.Files[i].Owned = true
+ found = true
+ }
+ }
+ if !found {
+ t.Files = append(t.Files, TaskFileProgress{Path: rel, Status: "waiting", Owned: true})
+ }
+ return m.saveTaskProgress(*t)
+}
+
+func taskFileIdentity(rel string) string {
+ return strings.TrimSuffix(filepath.ToSlash(rel), ".part")
+}
+
+func taskFileOwned(file TaskFileProgress) bool {
+ // Pre-ownership task records can prove a written file through a durable
+ // length checkpoint or hash. A waiting filename alone grants no ownership.
+ return file.Owned || file.SHA256 != "" || file.DownloadedBytes > 0 && file.TotalBytes >= file.DownloadedBytes
+}
+
+func taskRelativePath(task *Task, filePath string) string {
+ if task.ItemDir != "" {
+ if rel, err := filepath.Rel(task.ItemDir, filePath); err == nil {
+ return filepath.ToSlash(rel)
+ }
+ }
+ return filepath.Base(filePath)
+}
+
+type rowScanner interface {
+ Scan(dest ...any) error
+}
+
+func viaJSON(v *library.ItemVia) string {
+ if v == nil {
+ return ""
+ }
+ raw, _ := json.Marshal(v)
+ return string(raw)
+}
+
+func scanTask(r rowScanner) (Task, error) {
+ var t Task
+ var linkedInt int
+ var filesRaw, attemptsRaw, viaRaw string
+ err := r.Scan(
+ &t.TaskID, &t.Site, &t.Kind, &t.Source, &t.TargetID, &t.CID, &t.Page, &t.Title, &t.PartTitle,
+ &t.Mid, &t.AuthorUID, &t.AuthorName, &t.AuthorFace, &t.CoverURL, &linkedInt,
+ &t.Status, &t.PauseReason, &t.ErrorKind, &t.ErrorMessage, &t.QualityHint,
+ &t.BytesDownloaded, &t.TotalBytes, &t.Progress, &t.ItemKey, &t.ItemDir,
+ &filesRaw, &attemptsRaw, &t.CreatedAt, &t.UpdatedAt, &viaRaw,
+ )
+ if viaRaw != "" {
+ var via library.ItemVia
+ if json.Unmarshal([]byte(viaRaw), &via) == nil && via.UID != "" {
+ t.Via = &via
+ }
+ }
+ t.LastError = t.ErrorMessage
+ t.CacheLinkedVideos = linkedInt == 1
+ if filesRaw != "" {
+ _ = json.Unmarshal([]byte(filesRaw), &t.Files)
+ }
+ if attemptsRaw != "" {
+ _ = json.Unmarshal([]byte(attemptsRaw), &t.Attempts)
+ }
+ return t, err
+}
+
+func hashFileSHA256(filePath string) (string, int64, error) {
+ f, err := os.Open(filePath)
+ if err != nil {
+ return "", 0, err
+ }
+ defer f.Close()
+ h := sha256.New()
+ n, err := io.Copy(h, f)
+ if err != nil {
+ return "", 0, err
+ }
+ return hex.EncodeToString(h.Sum(nil)), n, nil
+}
+
+func isTempStagingPath(rel string) bool {
+ if strings.HasPrefix(path.Base(filepath.ToSlash(rel)), storage.TempPrefix) {
+ return true
+ }
+ for _, marker := range stagingMarkers {
+ if strings.HasSuffix(rel, marker) || strings.HasSuffix(rel, marker+".part") {
+ return true
+ }
+ }
+ return false
+}
+
+func cleanTaskPartFiles(t Task) {
+ if t.ItemDir == "" {
+ return
+ }
+ for _, file := range t.Files {
+ root, rel := t.ItemDir, file.Path
+ if file.ItemDir != "" {
+ root, rel = file.ItemDir, filepath.Base(file.Path)
+ }
+ rel = taskFileIdentity(rel)
+ isTemp := isTempStagingPath(rel)
+ // Always clean owned temporary staging files (e.g. .trace-*.m4s or *.stage.part)
+ // even if they reached "completed" before the task was canceled or failed.
+ if !taskFileOwned(file) || file.Status == "skipped" || (file.Status == "completed" && !isTemp) {
+ continue
+ }
+ candidates := []string{rel + ".part", rel + ".part.part", rel + ".raw", rel + ".raw.part", rel + stageSuffix, rel + stageSuffix + ".part"}
+ if isTemp {
+ candidates = append(candidates, rel)
+ }
+ for _, pending := range candidates {
+ partPath, err := library.ResolveItemPath(root, pending)
+ if err == nil {
+ _ = os.Remove(partPath)
+ }
+ }
+ }
+}
+
+func mergePartRecords(existing []library.VideoPartRecord, added library.VideoPartRecord) []library.VideoPartRecord {
+ out := make([]library.VideoPartRecord, 0, len(existing)+1)
+ replaced := false
+ for _, p := range existing {
+ if p.Page == added.Page || (p.CID > 0 && p.CID == added.CID) {
+ out = append(out, added)
+ replaced = true
+ } else {
+ out = append(out, p)
+ }
+ }
+ if !replaced {
+ out = append(out, added)
+ }
+ return out
+}
+
+func mergeMediaFiles(existing []library.MediaFile, added []library.MediaFile) []library.MediaFile {
+ byPath := make(map[string]library.MediaFile, len(existing)+len(added))
+ var order []string
+ for _, m := range existing {
+ byPath[m.Path] = m
+ order = append(order, m.Path)
+ }
+ for _, m := range added {
+ if _, seen := byPath[m.Path]; !seen {
+ order = append(order, m.Path)
+ }
+ byPath[m.Path] = m
+ }
+ out := make([]library.MediaFile, 0, len(order))
+ for _, p := range order {
+ out = append(out, byPath[p])
+ }
+ return out
+}
+
+func audioRank(id int) int {
+ switch id {
+ case 30251:
+ return 5
+ case 30250:
+ return 4
+ case 30280:
+ return 3
+ case 30232:
+ return 2
+ case 30216:
+ return 1
+ }
+ return 0
+}
+
+func isStopError(err error) bool {
+ return bilibili.IsKind(err, bilibili.ErrKindRiskControl) || bilibili.IsKind(err, bilibili.ErrKindRateLimited) || bilibili.IsKind(err, bilibili.ErrKindAuthRequired)
+}
+
+func isStorageError(err error) bool {
+ var pathErr *os.PathError
+ return errors.As(err, &pathErr) || bilibili.IsKind(err, "storage")
+}
+
+func targetQuality(quality string) int {
+ switch quality {
+ case "2160":
+ return 120
+ case "1080":
+ return 112
+ case "720":
+ return 74
+ }
+ return 127
+}
diff --git a/internal/download/tempnames_test.go b/internal/download/tempnames_test.go
new file mode 100644
index 0000000..67feca5
--- /dev/null
+++ b/internal/download/tempnames_test.go
@@ -0,0 +1,74 @@
+package download
+
+import (
+ "io/fs"
+ "path/filepath"
+ "sort"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/chialecode/trace/internal/storage"
+)
+
+// watchNames samples every name under root while a test runs.
+// The returned check fails the test for any name that was seen but is
+// neither a temporary name (*.part, .trace-*) nor still present at the end
+// as a finished file (allowed lists names the test itself removed).
+func watchNames(t *testing.T, root string) func(allowed ...string) {
+ t.Helper()
+ var mu sync.Mutex
+ seen := map[string]bool{}
+ stop := make(chan struct{})
+ done := make(chan struct{})
+ walk := func() map[string]bool {
+ out := map[string]bool{}
+ _ = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
+ if err == nil && !d.IsDir() {
+ out[p] = true
+ }
+ return nil
+ })
+ return out
+ }
+ go func() {
+ defer close(done)
+ for {
+ names := walk()
+ mu.Lock()
+ for p := range names {
+ seen[p] = true
+ }
+ mu.Unlock()
+ select {
+ case <-stop:
+ return
+ case <-time.After(time.Millisecond):
+ }
+ }
+ }()
+ return func(allowed ...string) {
+ t.Helper()
+ close(stop)
+ <-done
+ final := walk()
+ ok := map[string]bool{}
+ for _, a := range allowed {
+ ok[a] = true
+ }
+ var bad []string
+ mu.Lock()
+ for p := range seen {
+ name := filepath.Base(p)
+ if final[p] || storage.IsTempName(name) || ok[name] {
+ continue
+ }
+ bad = append(bad, p)
+ }
+ mu.Unlock()
+ sort.Strings(bad)
+ if len(bad) > 0 {
+ t.Fatalf("unfinished files with final-looking names were visible: %v", bad)
+ }
+ }
+}
diff --git a/internal/download/video.go b/internal/download/video.go
index 273a1ef..5aef09b 100644
--- a/internal/download/video.go
+++ b/internal/download/video.go
@@ -10,7 +10,6 @@ import (
"path/filepath"
"strconv"
"strings"
- "sync"
"github.com/chialecode/trace/internal/library"
"github.com/chialecode/trace/internal/settings"
@@ -50,16 +49,11 @@ func (m *Manager) executeVideoTask(ctx context.Context, task *Task) error {
return m.cacheVideoPart(ctx, task, false)
}
-// All operations on one video's manifest share this lock, including supplement
-// and upgrade. Different pages cannot overwrite one another's successful work.
-func (m *Manager) lockVideo(id string) func() {
- lock, _ := m.videoLocks.LoadOrStore(id, &sync.Mutex{})
- lock.(*sync.Mutex).Lock()
- return lock.(*sync.Mutex).Unlock
-}
-
func (m *Manager) cacheVideoPart(ctx context.Context, t *Task, upgrade bool) (result error) {
- unlock := m.lockVideo(t.TargetID)
+ unlock, err := m.lockItem(ctx, t.TargetID)
+ if err != nil {
+ return err
+ }
defer unlock()
if err := ctx.Err(); err != nil {
return err
@@ -227,8 +221,14 @@ func (m *Manager) cacheVideoPart(ctx context.Context, t *Task, upgrade bool) (re
var vPath, aPath string
var intermediate []library.MediaFile
part := library.VideoPartRecord{CID: page.CID, Page: page.Page, Title: page.Title, Duration: page.Duration, File: mp4Rel, Video: library.PartVideoInfo{Quality: plan.Video.Quality, QualityName: plan.Video.QualityName, CodecID: plan.Video.CodecID, Codecs: plan.Video.Codecs, Width: plan.Video.Width, Height: plan.Video.Height, FrameRate: plan.Video.FrameRate}, Available: availableRecord(plan)}
+ var summary MuxTrackSummary
if plan.Mode == "dash" {
- vRel := fmt.Sprintf("P%02d.video-%d-%d.m4s", page.Page, plan.Video.Quality, plan.Video.CodecID)
+ // The DASH streams are only material for the MP4: they carry a
+ // temporary name the whole time, so an export folder never shows a
+ // finished-looking file that is not part of the item (remote.md §6.1).
+ legacyV := fmt.Sprintf("P%02d.video-%d-%d.m4s", page.Page, plan.Video.Quality, plan.Video.CodecID)
+ vRel := storage.TempPrefix + legacyV
+ m.adoptLegacyName(t, meta.ItemDir, legacyV, vRel)
vPath = filepath.Join(meta.ItemDir, vRel)
m.setFileProgress(t, "video_stream", vRel, "downloading", 0, 0, 0)
n, hash, err := m.downloadStreamWithRefresh(ctx, plan.Video.URLs, vPath, t, videoURLs)
@@ -260,7 +260,9 @@ func (m *Manager) cacheVideoPart(ctx context.Context, t *Task, upgrade bool) (re
}
}
if mainAudio != nil {
- rel := fmt.Sprintf("P%02d.audio-%d.m4s", page.Page, mainAudio.Quality)
+ legacyA := fmt.Sprintf("P%02d.audio-%d.m4s", page.Page, mainAudio.Quality)
+ rel := storage.TempPrefix + legacyA
+ m.adoptLegacyName(t, meta.ItemDir, legacyA, rel)
aPath = filepath.Join(meta.ItemDir, rel)
m.setFileProgress(t, "audio_stream", rel, "downloading", 0, 0, 0)
n, hash, err := m.downloadStreamWithRefresh(ctx, mainAudio.URLs, aPath, t, audioURLs(mainAudio, isHigh))
@@ -273,34 +275,69 @@ func (m *Manager) cacheVideoPart(ctx context.Context, t *Task, upgrade bool) (re
}
}
m.setFileProgress(t, "video", mp4Rel, "verifying", 0, 0, 0)
- _, err = MuxDASHFilesContext(ctx, vPath, aPath, mp4Path+".part")
+ if _, err = MuxDASHFilesContext(ctx, vPath, aPath, mp4Path+".part"); err != nil {
+ m.setFileProgress(t, "video", mp4Rel, "failed", 0, 0, 0)
+ return err
+ }
+ summary, err = InspectMP4FileContext(ctx, mp4Path+".part")
+ if err == nil {
+ err = validateVideoOutput(summary, page.Duration, aPath != "")
+ }
+ if err != nil {
+ m.setFileProgress(t, "video", mp4Rel, "failed", 0, 0, 0)
+ return err
+ }
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if err := os.Rename(mp4Path+".part", mp4Path); err != nil {
+ return err
+ }
} else {
+ stageRel := mp4Rel + stageSuffix
+ stagePath := mp4Path + stageSuffix
m.setFileProgress(t, "video", mp4Rel, "downloading", 0, 0, 0)
- _, _, err = m.downloadStreamWithRefresh(ctx, plan.Video.URLs, mp4Path+".part", t, videoURLs)
- }
- if err != nil {
- m.setFileProgress(t, "video", mp4Rel, "failed", 0, 0, 0)
- return err
- }
- summary, err := InspectMP4FileContext(ctx, mp4Path+".part")
- if err == nil {
- err = validateVideoOutput(summary, page.Duration, aPath != "")
- }
- if err != nil {
- m.setFileProgress(t, "video", mp4Rel, "failed", 0, 0, 0)
- return err
- }
- if err := ctx.Err(); err != nil {
- return err
- }
- if err := os.Rename(mp4Path+".part", mp4Path); err != nil {
- return err
+ if _, _, err = m.downloadStreamWithRefresh(ctx, plan.Video.URLs, stagePath, t, videoURLs); err != nil {
+ if ctx.Err() == nil && !fileOrPartExists(stagePath) {
+ m.removeTempTaskProgress(t, stageRel)
+ }
+ m.setFileProgress(t, "video", mp4Rel, "failed", 0, 0, 0)
+ return err
+ }
+ m.setFileProgress(t, "video", mp4Rel, "verifying", 0, 0, 0)
+ summary, err = EnsureSingleMP4Context(ctx, stagePath, float64(page.Duration))
+ if err != nil {
+ if ctx.Err() == nil {
+ _ = os.Remove(stagePath)
+ m.removeTempTaskProgress(t, stageRel)
+ m.setFileProgress(t, "video", mp4Rel, "failed", 0, 0, 0)
+ }
+ return err
+ }
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if err := os.Rename(stagePath, mp4Path); err != nil {
+ return err
+ }
+ m.removeTempTaskProgress(t, stageRel)
}
m.setFileProgress(t, "video", mp4Rel, "completed", summary.FileBytes, summary.FileBytes, 0)
newMedia = append(newMedia, library.MediaFile{Role: "video", Path: mp4Rel, Bytes: summary.FileBytes, SHA256: summary.SHA256, Width: summary.Width, Height: summary.Height, Duration: int(math.Round(summary.DurationSec))})
for _, media := range intermediate {
meta.Media = withoutMedia(meta.Media, media.Path)
}
+ // Drop any previously registered intermediate streams for this page (both
+ // legacy Pxx.* and current .trace-Pxx.* names from an earlier quality/codec).
+ legacyPrefix := fmt.Sprintf("P%02d.", page.Page)
+ tempPrefix := storage.TempPrefix + legacyPrefix
+ for _, media := range meta.Media {
+ if (media.Role == "video_stream" || media.Role == "audio_stream") &&
+ (strings.HasPrefix(media.Path, legacyPrefix) || strings.HasPrefix(media.Path, tempPrefix)) {
+ intermediate = append(intermediate, media)
+ meta.Media = withoutMedia(meta.Media, media.Path)
+ }
+ }
meta.Media = mergeMediaFiles(meta.Media, newMedia)
clearMissing(&meta, fmt.Sprintf("P%02d.media", page.Page))
if cfg.SaveDanmaku {
@@ -377,7 +414,7 @@ func (m *Manager) saveVideoExtras(ctx context.Context, t *Task, meta *library.It
return err
}
} else {
- if err := m.writeExtra(t, meta, "danmaku", dmRel, raw); err != nil {
+ if err := m.writeExtra(ctx, t, meta, "danmaku", dmRel, raw); err != nil {
return err
}
part.Danmaku, part.DanmakuState = dmRel, "saved"
@@ -429,7 +466,7 @@ func (m *Manager) saveVideoExtras(ctx context.Context, t *Task, meta *library.It
rel string
data []byte
}{{vtt, track.VTT}, {srt, track.SRT}} {
- if err := m.writeExtra(t, meta, "subtitle", file.rel, file.data); err != nil {
+ if err := m.writeExtra(ctx, t, meta, "subtitle", file.rel, file.data); err != nil {
addMissing(meta, file.rel, "字幕写入失败")
return err
}
@@ -464,7 +501,7 @@ func (m *Manager) saveVideoExtras(ctx context.Context, t *Task, meta *library.It
return nil
}
-func (m *Manager) writeExtra(t *Task, meta *library.ItemMetadata, role, rel string, raw []byte) error {
+func (m *Manager) writeExtra(ctx context.Context, t *Task, meta *library.ItemMetadata, role, rel string, raw []byte) error {
full, err := library.ResolveItemPath(meta.ItemDir, rel)
if err != nil {
return err
@@ -472,6 +509,9 @@ func (m *Manager) writeExtra(t *Task, meta *library.ItemMetadata, role, rel stri
if err := m.claimTaskFile(t, meta.ItemDir, rel, full); err != nil {
return err
}
+ if err := ctx.Err(); err != nil {
+ return err
+ }
m.setFileProgress(t, role, rel, "verifying", 0, int64(len(raw)), 0)
if err := storage.WriteFileAtomic(full+".part", raw, 0600); err != nil {
m.setFileProgress(t, role, rel, "failed", 0, int64(len(raw)), 0)
@@ -487,7 +527,10 @@ func (m *Manager) writeExtra(t *Task, meta *library.ItemMetadata, role, rel stri
}
func (m *Manager) executeSupplementTask(ctx context.Context, t *Task) error {
- unlock := m.lockVideo(t.TargetID)
+ unlock, err := m.lockItem(ctx, t.TargetID)
+ if err != nil {
+ return err
+ }
defer unlock()
meta, ok, err := m.lib.GetItem(t.TargetID)
if err != nil {
@@ -539,8 +582,10 @@ func (m *Manager) executeUpgradeTask(ctx context.Context, t *Task) error {
for _, part := range meta.Parts {
child := Task{Site: "bilibili", Kind: "video", TargetID: meta.RawID, CID: part.CID, Page: part.Page, Source: t.Source, LinkedVideo: !meta.DirectCached, ProgressOwner: t, Attempts: t.Attempts}
if err := m.cacheVideoPart(ctx, &child, true); err != nil {
+ t.Attempts = child.Attempts
return err
}
+ t.Attempts = child.Attempts
if child.Status == "partial" {
t.Status = "partial"
}
diff --git a/internal/library/cache_root.go b/internal/library/cache_root.go
index 314fe10..d3d220e 100644
--- a/internal/library/cache_root.go
+++ b/internal/library/cache_root.go
@@ -6,8 +6,6 @@ import (
"os"
"path/filepath"
"strings"
- "sync"
- "time"
)
// ChangeCacheDir prepares a writable root and its durable ledger before the
@@ -38,7 +36,7 @@ func (s *Store) ChangeCacheDir(dir string, persist func() error) error {
defer s.mu.Unlock()
oldDir, oldRoots := s.cacheDir, append([]string(nil), s.extraRoots...)
s.cacheDir = dir
- if oldDir != "" && !strings.EqualFold(oldDir, dir) {
+ if oldDir != "" && !samePath(oldDir, dir) {
s.extraRoots = append(s.extraRoots, oldDir)
}
if err := s.saveRootsLocked(); err != nil {
@@ -53,71 +51,3 @@ func (s *Store) ChangeCacheDir(dir string, persist func() error) error {
}
return nil
}
-
-func rejectDirectoryLinks(dir string) error {
- for current := dir; ; current = filepath.Dir(current) {
- info, err := os.Lstat(current)
- if err != nil && !os.IsNotExist(err) {
- return err
- }
- if err == nil {
- if info.Mode()&os.ModeSymlink != 0 || !info.IsDir() {
- return fmt.Errorf("library: 保存位置含链接或非目录节点")
- }
- // EvalSymlinks also expands 8.3 short names (RUNNER~1), which
- // are not links: compare with the long form of the path.
- resolved, err := filepath.EvalSymlinks(current)
- if err != nil || !strings.EqualFold(filepath.Clean(resolved), filepath.Clean(longPathName(current))) {
- return fmt.Errorf("library: 保存位置含目录联接")
- }
- }
- if filepath.Dir(current) == current {
- break
- }
- }
- return nil
-}
-
-// verifiedDirTTL is how long a directory found free of links is trusted by
-// the read path (safeRegisteredPath). Showing a screen of thumbnails resolves
-// dozens of files under the same ancestors; walking every ancestor with
-// EvalSymlinks for each file made a page take seconds (DEC-057). Changing a
-// location, scanning and migrating still check in full.
-const verifiedDirTTL = 3 * time.Second
-
-var verifiedDirs sync.Map // cleaned lower-case dir -> time.Time verified
-
-// rejectDirectoryLinksRecent is rejectDirectoryLinks that stops at the first
-// ancestor verified within verifiedDirTTL (all of whose ancestors were then
-// verified too) and remembers what it walked.
-func rejectDirectoryLinksRecent(dir string) error {
- now := time.Now()
- var walked []string
- for current := filepath.Clean(dir); ; current = filepath.Dir(current) {
- key := strings.ToLower(current)
- if at, ok := verifiedDirs.Load(key); ok && now.Sub(at.(time.Time)) < verifiedDirTTL {
- break
- }
- info, err := os.Lstat(current)
- if err != nil && !os.IsNotExist(err) {
- return err
- }
- if err == nil {
- if info.Mode()&os.ModeSymlink != 0 || !info.IsDir() {
- return fmt.Errorf("library: 保存位置含链接或非目录节点")
- }
- resolved, err := filepath.EvalSymlinks(current)
- if err != nil || !strings.EqualFold(filepath.Clean(resolved), filepath.Clean(longPathName(current))) {
- return fmt.Errorf("library: 保存位置含目录联接")
- }
- walked = append(walked, key)
- }
- if filepath.Dir(current) == current {
- break
- }
- }
- for _, key := range walked {
- verifiedDirs.Store(key, now)
- }
- return nil
-}
diff --git a/internal/library/delete.go b/internal/library/delete.go
new file mode 100644
index 0000000..73a7e1c
--- /dev/null
+++ b/internal/library/delete.go
@@ -0,0 +1,435 @@
+package library
+
+import (
+ "errors"
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+
+ "github.com/chialecode/trace/internal/storage"
+)
+
+type pendingDeleteRecord struct {
+ ItemKey string `json:"itemKey"`
+ ItemDir string `json:"itemDir"`
+ RegisteredFiles []string `json:"registeredFiles"`
+}
+
+func (s *Store) readPendingDeletesLocked() ([]pendingDeleteRecord, error) {
+ if s.pendingDeletesPath == "" {
+ return nil, nil
+ }
+ raw, err := os.ReadFile(s.pendingDeletesPath)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil, nil
+ }
+ return nil, fmt.Errorf("library: 删除账本读取失败: %w", err)
+ }
+ var list []pendingDeleteRecord
+ if err := jsonUnmarshal(raw, &list); err != nil {
+ // Keep the original ledger in place: treating it as empty could resurrect
+ // files whose deletion was already committed before a crash.
+ return nil, fmt.Errorf("library: 删除账本损坏,原文件已保留: %w", err)
+ }
+ return list, nil
+}
+
+func (s *Store) writePendingDeletesLocked(list []pendingDeleteRecord) error {
+ if s.pendingDeletesPath == "" {
+ return nil
+ }
+ if len(list) == 0 {
+ err := os.Remove(s.pendingDeletesPath)
+ if os.IsNotExist(err) {
+ return nil
+ }
+ return err
+ }
+ return storage.WriteJSONAtomic(s.pendingDeletesPath, list, 0o600)
+}
+
+func (s *Store) cleanupPendingDeletesLocked() error {
+ pending, err := s.readPendingDeletesLocked()
+ if err != nil {
+ return err
+ }
+ if len(pending) == 0 {
+ return nil
+ }
+ roots := s.allRootsLocked()
+ var remaining []pendingDeleteRecord
+ for _, rec := range pending {
+ validRoot := false
+ for _, root := range roots {
+ if _, err := EnsureWithinRoot(root, rec.ItemDir); err == nil && !samePath(root, rec.ItemDir) {
+ validRoot = true
+ break
+ }
+ }
+ if !validRoot {
+ remaining = append(remaining, rec)
+ continue
+ }
+ var exists int
+ if err := s.db.QueryRow(`SELECT COUNT(1) FROM library_items WHERE item_key = ?`, rec.ItemKey).Scan(&exists); err != nil {
+ return err
+ }
+ if exists > 0 {
+ // Re-cached since pending delete was recorded; skip cleanup.
+ continue
+ }
+ allGone := true
+ for _, f := range rec.RegisteredFiles {
+ rel, err := filepath.Rel(rec.ItemDir, f)
+ if err != nil || !safeRegisteredPathStrict(rec.ItemDir, filepath.ToSlash(rel)) {
+ allGone = false
+ continue
+ }
+ if err := os.Remove(f); err != nil && !os.IsNotExist(err) {
+ allGone = false
+ }
+ }
+ if rec.ItemDir != "" {
+ removeEmptyDirsBottomUp(rec.ItemDir)
+ removeEmptyAuthorDirs(rec.ItemDir, roots)
+ }
+ if !allGone {
+ remaining = append(remaining, rec)
+ }
+ }
+ return s.writePendingDeletesLocked(remaining)
+}
+
+// PlanDelete computes the exact DeletePlan for an item without modifying disk or DB (FR-LIB-003, INV-09).
+func (s *Store) PlanDelete(itemKey string) (DeletePlan, error) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ return s.planDeleteLocked(itemKey)
+}
+
+func (s *Store) planDeleteLocked(itemKey string) (DeletePlan, error) {
+ meta, ok, err := s.getItemLocked(itemKey)
+ if err != nil {
+ return DeletePlan{}, err
+ }
+ if !ok {
+ return DeletePlan{}, fmt.Errorf("library: item %q not found", itemKey)
+ }
+ if meta.Status == "recording" {
+ return DeletePlan{}, fmt.Errorf("library: 正在录制的直播条目不能删除,请先停止录制")
+ }
+
+ plan := DeletePlan{
+ TargetKey: meta.ItemKey,
+ ItemKeys: []string{meta.ItemKey},
+ }
+
+ itemsToDelete := []ItemMetadata{meta}
+
+ // If deleting a dynamic item that references videos, check if each referenced video is shared or directly cached.
+ if meta.Kind == "dynamic" && len(meta.Videos) > 0 {
+ for _, vid := range meta.Videos {
+ vidKey := CanonicalItemKey(meta.Site, "video", vid)
+ vMeta, vOk, err := s.getItemLocked(vidKey)
+ if err != nil {
+ return DeletePlan{}, fmt.Errorf("library: check referenced video %s: %w", vidKey, err)
+ }
+ if !vOk {
+ continue
+ }
+ var otherRefs int
+ if err := s.db.QueryRow(`SELECT COUNT(1) FROM item_refs WHERE to_key = ? AND from_key != ?`, vidKey, meta.ItemKey).Scan(&otherRefs); err != nil {
+ return DeletePlan{}, fmt.Errorf("library: check shared refs for %s: %w", vidKey, err)
+ }
+ if otherRefs > 0 || vMeta.DirectCached {
+ plan.PreservedSharedVideos = append(plan.PreservedSharedVideos, vidKey)
+ } else {
+ plan.ItemKeys = append(plan.ItemKeys, vidKey)
+ itemsToDelete = append(itemsToDelete, vMeta)
+ }
+ }
+ }
+
+ seenFiles := make(map[string]bool)
+ seenUserFiles := make(map[string]bool)
+ for _, it := range itemsToDelete {
+ regFiles, userFiles := collectRegisteredAndUserFiles(it)
+ for _, f := range regFiles {
+ if !seenFiles[f] {
+ seenFiles[f] = true
+ plan.RegisteredFiles = append(plan.RegisteredFiles, f)
+ }
+ }
+ for _, uf := range userFiles {
+ if !seenUserFiles[uf] {
+ seenUserFiles[uf] = true
+ plan.PreservedUserFiles = append(plan.PreservedUserFiles, uf)
+ }
+ }
+ }
+ return plan, nil
+}
+
+func collectRegisteredAndUserFiles(meta ItemMetadata) (registeredAbs []string, userRel []string) {
+ if meta.ItemDir == "" {
+ return nil, nil
+ }
+ itemDir := filepath.Clean(meta.ItemDir)
+ regRel := make(map[string]bool)
+ addRel := func(rel string) {
+ rel = strings.TrimSpace(rel)
+ if rel == "" {
+ return
+ }
+ norm := strings.ToLower(filepath.ToSlash(filepath.Clean(filepath.FromSlash(rel))))
+ if !safeRegisteredPathStrict(itemDir, rel) {
+ return
+ }
+ if !regRel[norm] {
+ regRel[norm] = true
+ registeredAbs = append(registeredAbs, filepath.Join(itemDir, filepath.FromSlash(rel)))
+ }
+ }
+
+ visitManifestFiles(meta, func(f ManifestFile) {
+ addRel(f.Path)
+ })
+ for _, part := range meta.PendingParts {
+ addRel(part)
+ if meta.Kind == "live" && strings.HasPrefix(part, "part-") && strings.HasSuffix(part, ".mp4.part") {
+ // Both names are reserved before recording starts. A crash after the
+ // final rename can leave the MP4 present before its media row is saved.
+ addRel(strings.TrimSuffix(part, ".part"))
+ }
+ }
+ addRel("orig.json")
+
+ // Scan itemDir for *.part files (which belong to TRACE) and user-owned files (which MUST be preserved).
+ // Never traverse symlinks or Windows directory junctions (INV-08/09).
+ if rejectDirectoryLinks(itemDir) == nil {
+ _ = filepath.WalkDir(itemDir, func(path string, d fs.DirEntry, walkErr error) error {
+ if walkErr != nil {
+ return nil
+ }
+ if isLinkLike(d.Type()) {
+ if d.IsDir() {
+ return filepath.SkipDir
+ }
+ return nil
+ }
+ if d.IsDir() {
+ return nil
+ }
+ rel, rErr := filepath.Rel(itemDir, path)
+ if rErr != nil {
+ return nil
+ }
+ norm := strings.ToLower(filepath.ToSlash(rel))
+ if norm == "item.json" {
+ return nil
+ }
+ if strings.HasSuffix(norm, ".part") && regRel[strings.TrimSuffix(norm, ".part")] {
+ addRel(rel)
+ return nil
+ }
+ if !regRel[norm] {
+ userRel = append(userRel, filepath.ToSlash(rel))
+ }
+ return nil
+ })
+ }
+
+ // item.json is always deleted last among registered files.
+ addRel("item.json")
+ return registeredAbs, userRel
+}
+
+// Delete executes PlanDelete: removes only registered files and empty directories, never recursive RemoveAll (INV-09).
+func (s *Store) Delete(itemKey string) (DeletePlan, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.deleteWithPlanLocked(itemKey, true)
+}
+
+// DeleteItem removes an item from the index and optionally deletes its registered files from disk (INV-09).
+// It NEVER calls os.RemoveAll on the item directory; user-placed files are strictly preserved.
+func (s *Store) DeleteItem(itemKey string, deleteFiles bool) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ _, err := s.deleteWithPlanLocked(itemKey, deleteFiles)
+ return err
+}
+
+func (s *Store) deleteWithPlanLocked(itemKey string, deleteFiles bool) (DeletePlan, error) {
+ plan, err := s.planDeleteLocked(itemKey)
+ if err != nil {
+ return DeletePlan{}, err
+ }
+
+ var itemDirs []string
+ for _, k := range plan.ItemKeys {
+ if m, ok, _ := s.getItemLocked(k); ok && m.ItemDir != "" {
+ itemDirs = append(itemDirs, m.ItemDir)
+ }
+ }
+
+ // 1. Write pending-deletes.json before deleting files (data-and-cache.md §2.8).
+ if deleteFiles && len(plan.RegisteredFiles) > 0 {
+ pending, err := s.readPendingDeletesLocked()
+ if err != nil {
+ return plan, err
+ }
+ for _, k := range plan.ItemKeys {
+ m, ok, _ := s.getItemLocked(k)
+ if ok {
+ regFiles, _ := collectRegisteredAndUserFiles(m)
+ pending = append(pending, pendingDeleteRecord{
+ ItemKey: k,
+ ItemDir: m.ItemDir,
+ RegisteredFiles: regFiles,
+ })
+ }
+ }
+ if err := s.writePendingDeletesLocked(pending); err != nil {
+ return plan, err
+ }
+ }
+
+ // 2. Remove from index and references.
+ tx, err := s.db.Begin()
+ if err != nil {
+ return plan, err
+ }
+ defer tx.Rollback()
+ for _, k := range plan.ItemKeys {
+ if _, err := tx.Exec(`DELETE FROM library_items WHERE item_key = ?`, k); err != nil {
+ return plan, err
+ }
+ if _, err := tx.Exec(`DELETE FROM item_refs WHERE from_key = ? OR to_key = ?`, k, k); err != nil {
+ return plan, err
+ }
+ if _, err := tx.Exec(`UPDATE feed_items SET cached = 0, cache_status = '', item_key = '' WHERE item_key = ?`, k); err != nil {
+ return plan, err
+ }
+ }
+ if err := tx.Commit(); err != nil {
+ return plan, err
+ }
+
+ // 3. Delete only registered files one by one, then remove empty directories bottom-up (NEVER os.RemoveAll).
+ if deleteFiles {
+ allRemoved := true
+ var removeErrors []error
+ for _, f := range plan.RegisteredFiles {
+ if rErr := os.Remove(f); rErr != nil && !os.IsNotExist(rErr) {
+ allRemoved = false
+ removeErrors = append(removeErrors, rErr)
+ }
+ }
+ roots := s.allRootsLocked()
+ for _, dir := range itemDirs {
+ removeEmptyDirsBottomUp(dir)
+ removeEmptyAuthorDirs(dir, roots)
+ }
+ if allRemoved {
+ // Clear completed keys from pending-deletes.json.
+ pending, err := s.readPendingDeletesLocked()
+ if err != nil {
+ return plan, err
+ }
+ doneSet := make(map[string]bool, len(plan.ItemKeys))
+ for _, k := range plan.ItemKeys {
+ doneSet[k] = true
+ }
+ var rem []pendingDeleteRecord
+ for _, p := range pending {
+ if !doneSet[p.ItemKey] {
+ rem = append(rem, p)
+ }
+ }
+ if err := s.writePendingDeletesLocked(rem); err != nil {
+ return plan, err
+ }
+ }
+ if !allRemoved {
+ return plan, errors.Join(removeErrors...)
+ }
+ }
+
+ return plan, nil
+}
+
+// removeEmptyDirsBottomUp removes empty subdirectories (such as images/) and the item directory itself
+// ONLY if they are completely empty and not symlinks/junctions (using os.Remove, never os.RemoveAll).
+func removeEmptyDirsBottomUp(itemDir string) {
+ itemDir = filepath.Clean(itemDir)
+ if itemDir == "" || itemDir == "." {
+ return
+ }
+ if info, err := os.Lstat(itemDir); err != nil || !info.IsDir() || isLinkLike(info.Mode()) {
+ return
+ }
+ var dirs []string
+ _ = filepath.WalkDir(itemDir, func(path string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return nil
+ }
+ if isLinkLike(d.Type()) {
+ if d.IsDir() {
+ return filepath.SkipDir
+ }
+ return nil
+ }
+ if d.IsDir() {
+ dirs = append(dirs, path)
+ }
+ return nil
+ })
+ // Sort deepest paths first.
+ sort.Slice(dirs, func(i, j int) bool {
+ return len(dirs[i]) > len(dirs[j])
+ })
+ for _, d := range dirs {
+ info, err := os.Lstat(d)
+ if err != nil || !info.IsDir() || isLinkLike(info.Mode()) {
+ continue
+ }
+ entries, err := os.ReadDir(d)
+ if err == nil && len(entries) == 0 {
+ _ = os.Remove(d)
+ }
+ }
+}
+
+// removeEmptyAuthorDirs removes the now-empty kind folder (videos/, works/…)
+// and author folder above a deleted item, so deleting a creator's last item
+// leaves no empty folders. It only climbs inside a library root, never removes
+// the root or its site folder (/bilibili), and uses os.Remove, which
+// fails on any folder that still has files.
+func removeEmptyAuthorDirs(itemDir string, roots []string) {
+ itemDir = filepath.Clean(itemDir)
+ for _, root := range roots {
+ root = filepath.Clean(root)
+ rel, err := filepath.Rel(root, itemDir)
+ if err != nil || rel == "." || strings.HasPrefix(rel, "..") || filepath.IsAbs(rel) {
+ continue
+ }
+ // ///- : remove , then .
+ depth := len(strings.Split(filepath.ToSlash(rel), "/"))
+ dir := filepath.Dir(itemDir)
+ for depth--; depth >= 2; depth-- {
+ if info, err := os.Lstat(dir); err != nil || !info.IsDir() || isLinkLike(info.Mode()) {
+ return
+ }
+ if os.Remove(dir) != nil {
+ return
+ }
+ dir = filepath.Dir(dir)
+ }
+ return
+ }
+}
diff --git a/internal/library/feed.go b/internal/library/feed.go
new file mode 100644
index 0000000..542c2e9
--- /dev/null
+++ b/internal/library/feed.go
@@ -0,0 +1,523 @@
+package library
+
+import (
+ "database/sql"
+ "errors"
+ "fmt"
+ "strconv"
+ "strings"
+)
+
+// forwardContentSQL matches library_items rows that are forwarded posts or
+// content cached because of one (media library "转发", DEC-056).
+const forwardContentSQL = "(json_extract(json_data, '$.via.reason') = 'forward' OR (kind = 'dynamic' AND json_extract(json_data, '$.dynamicType') = 'DYNAMIC_TYPE_FORWARD'))"
+
+// viaUIDSQL is the indexed expression for the creator an item was cached for
+// (idx_library_items_via).
+const viaUIDSQL = "json_extract(json_data, '$.via.uid')"
+
+var likeEscaper = strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`)
+
+func escapeLikePattern(kw string) string {
+ return "%" + likeEscaper.Replace(kw) + "%"
+}
+
+// appendLibrarySiteAndAuthorClauses is appendSiteAndAuthorClauses for
+// library_items: an author filter also matches items cached for that creator
+// under their folder (collaboration videos and forwarded content, DEC-056).
+func appendLibrarySiteAndAuthorClauses(clauses []string, args []any, siteFilter string, mid int64, authorUID string, mids []int64, refs []AuthorRef) ([]string, []any) {
+ return appendSiteAndAuthorClausesVia(clauses, args, "", siteFilter, mid, authorUID, mids, refs, true)
+}
+
+// appendSiteAndAuthorClauses is the author filter for feed_items (colPrefix
+// "f."): an author's feed also has the collaboration videos cached for them
+// under their folder, though the uploader is someone else (DEC-061).
+func appendSiteAndAuthorClauses(clauses []string, args []any, colPrefix, siteFilter string, mid int64, authorUID string, mids []int64, refs []AuthorRef) ([]string, []any) {
+ return appendSiteAndAuthorClausesVia(clauses, args, colPrefix, siteFilter, mid, authorUID, mids, refs, false)
+}
+
+// collabItemKeysSQL selects the item keys of collaboration videos cached for
+// one of a site's creators; the site and creator placeholders follow.
+func collabItemKeysSQL(n int) string {
+ ph := strings.TrimSuffix(strings.Repeat("?,", n), ",")
+ return "(SELECT item_key FROM library_items WHERE site = ? AND " + viaUIDSQL + " IN (" + ph + ") AND json_extract(json_data, '$.via.reason') = '" + ViaCollab + "')"
+}
+
+func appendSiteAndAuthorClausesVia(clauses []string, args []any, colPrefix, siteFilter string, mid int64, authorUID string, mids []int64, refs []AuthorRef, withVia bool) ([]string, []any) {
+ normSiteFilter := strings.ToLower(strings.TrimSpace(siteFilter))
+ if normSiteFilter != "" && normSiteFilter != "all" {
+ clauses = append(clauses, colPrefix+"site = ?")
+ args = append(args, normSiteFilter)
+ }
+
+ var collected []AuthorRef
+ seen := make(map[string]bool)
+ addRef := func(site, uid string) {
+ uid = strings.TrimSpace(uid)
+ if uid == "" {
+ return
+ }
+ site = strings.ToLower(strings.TrimSpace(site))
+ if site == "" {
+ if normSiteFilter != "" && normSiteFilter != "all" {
+ site = normSiteFilter
+ } else {
+ site = "bilibili"
+ }
+ }
+ k := site + "\x00" + uid
+ if !seen[k] {
+ seen[k] = true
+ collected = append(collected, AuthorRef{Site: site, UID: uid})
+ }
+ }
+ if mid > 0 {
+ addRef("bilibili", strconv.FormatInt(mid, 10))
+ }
+ if strings.TrimSpace(authorUID) != "" {
+ addRef("", authorUID)
+ }
+ for _, m := range mids {
+ if m > 0 {
+ addRef("bilibili", strconv.FormatInt(m, 10))
+ }
+ }
+ for _, r := range refs {
+ addRef(r.Site, r.UID)
+ }
+ if len(collected) == 0 {
+ return clauses, args
+ }
+
+ bySite := make(map[string][]string)
+ var siteOrder []string
+ for _, r := range collected {
+ if _, ok := bySite[r.Site]; !ok {
+ siteOrder = append(siteOrder, r.Site)
+ }
+ bySite[r.Site] = append(bySite[r.Site], r.UID)
+ }
+ var orParts []string
+ for _, st := range siteOrder {
+ uids := bySite[st]
+ type colClause struct {
+ expr string
+ extra string
+ }
+ cols := []colClause{{expr: colPrefix + "author_uid"}}
+ if withVia {
+ cols[0].extra = " AND NOT " + viaForwardSQL
+ cols = append(cols, colClause{expr: viaUIDSQL})
+ }
+ for _, col := range cols {
+ if len(uids) == 1 {
+ orParts = append(orParts, "("+colPrefix+"site = ? AND "+col.expr+" = ?"+col.extra+")")
+ args = append(args, st, uids[0])
+ } else {
+ ph := make([]string, len(uids))
+ args = append(args, st)
+ for i, u := range uids {
+ ph[i] = "?"
+ args = append(args, u)
+ }
+ orParts = append(orParts, "("+colPrefix+"site = ? AND "+col.expr+" IN ("+strings.Join(ph, ",")+")"+col.extra+")")
+ }
+ }
+ if !withVia && colPrefix != "" {
+ orParts = append(orParts, "("+colPrefix+"item_key IN "+collabItemKeysSQL(len(uids))+")")
+ args = append(args, st)
+ for _, u := range uids {
+ args = append(args, u)
+ }
+ }
+ }
+ if len(orParts) == 1 {
+ clauses = append(clauses, orParts[0])
+ } else {
+ clauses = append(clauses, "("+strings.Join(orParts, " OR ")+")")
+ }
+ return clauses, args
+}
+
+// ListItems returns cached library items matching filter.
+func (s *Store) ListItems(filter FeedFilter) ([]ItemMetadata, error) {
+ var clauses []string
+ var args []any
+ switch filter.Kind {
+ case "image":
+ clauses = append(clauses, "(EXISTS (SELECT 1 FROM json_each(json_data, '$.media') WHERE json_extract(value, '$.role') = 'image') OR EXISTS (SELECT 1 FROM json_each(json_data, '$.notePages') WHERE json_extract(value, '$.kind') IN ('image', 'motion')))")
+ if filter.ExcludeForward {
+ clauses = append(clauses, "NOT "+forwardContentSQL)
+ }
+ case "forward":
+ clauses = append(clauses, forwardContentSQL)
+ case "", "all":
+ default:
+ clauses = append(clauses, "kind = ?")
+ args = append(args, filter.Kind)
+ if filter.ExcludeForward {
+ clauses = append(clauses, "NOT "+forwardContentSQL)
+ }
+ }
+ clauses, args = appendLibrarySiteAndAuthorClauses(clauses, args, filter.Site, filter.Mid, filter.AuthorUID, filter.Authors, filter.AuthorRefs)
+ if kw := strings.TrimSpace(filter.Keyword); kw != "" {
+ clauses = append(clauses, `(title LIKE ? ESCAPE '\' OR summary LIKE ? ESCAPE '\' OR author_name LIKE ? ESCAPE '\' OR raw_id LIKE ? ESCAPE '\')`)
+ pat := escapeLikePattern(kw)
+ args = append(args, pat, pat, pat, pat)
+ }
+
+ query := `SELECT json_data, item_dir, status, total_bytes, upgrade_available, upgrade_hint FROM library_items`
+ if len(clauses) > 0 {
+ query += " WHERE " + strings.Join(clauses, " AND ")
+ }
+ if strings.EqualFold(filter.Sort, "cached_at") {
+ query += " ORDER BY cached_at DESC, item_key DESC"
+ } else if strings.EqualFold(filter.Sort, "oldest") {
+ query += " ORDER BY pub_ts ASC, item_key ASC"
+ } else {
+ query += " ORDER BY pub_ts DESC, item_key DESC"
+ }
+ limit := filter.Limit
+ if limit <= 0 {
+ limit = 200
+ }
+ query += fmt.Sprintf(" LIMIT %d OFFSET %d", limit, max(0, filter.Offset))
+
+ s.mu.RLock()
+ allowMoved := s.allowMovedFiles
+ rows, err := s.db.Query(query, args...)
+ if err != nil {
+ s.mu.RUnlock()
+ return nil, err
+ }
+ 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 {
+ _ = rows.Close()
+ s.mu.RUnlock()
+ 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)
+ }
+ rowErr := rows.Err()
+ _ = rows.Close()
+ s.mu.RUnlock()
+ if rowErr != nil {
+ return nil, rowErr
+ }
+ if !allowMoved {
+ for i := range out {
+ refreshItemFileState(&out[i])
+ }
+ }
+ 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) {
+ if req.Direction == "around" && req.Cursor != nil {
+ pivot, err := s.feedAnchorCursor(req)
+ if err != nil || pivot == nil {
+ return FeedPageResult{}, err
+ }
+ halfLimit := req.Limit
+ if halfLimit <= 0 {
+ halfLimit = 30
+ }
+ beforeReq := req
+ beforeReq.Cursor = pivot
+ beforeReq.Order = "newest"
+ beforeReq.Direction = "newer"
+ beforeReq.Limit = halfLimit
+ before, err := s.FeedPage(beforeReq)
+ if err != nil {
+ return FeedPageResult{}, err
+ }
+ afterReq := beforeReq
+ afterReq.Direction = "older"
+ cursor := *pivot
+ cursor.Key += "\x00"
+ afterReq.Cursor = &cursor
+ after, err := s.FeedPage(afterReq)
+ if err != nil {
+ return FeedPageResult{}, err
+ }
+ result := after
+ result.Items = append(before.Items, after.Items...)
+ if req.Order == "oldest" {
+ for i, j := 0, len(result.Items)-1; i < j; i, j = i+1, j-1 {
+ result.Items[i], result.Items[j] = result.Items[j], result.Items[i]
+ }
+ result.HasMore = before.HasMore
+ }
+ if len(result.Items) > 0 {
+ first, last := result.Items[0], result.Items[len(result.Items)-1]
+ result.PrevCursor = &FeedCursor{PubTs: first.PubTs, Key: first.FeedKey}
+ result.NextCursor = &FeedCursor{PubTs: last.PubTs, Key: last.FeedKey}
+ }
+ return result, nil
+ }
+
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ order := strings.ToLower(strings.TrimSpace(req.Order))
+ if order != "oldest" {
+ order = "newest"
+ }
+ dir := strings.ToLower(strings.TrimSpace(req.Direction))
+ if dir != "newer" {
+ dir = "older"
+ }
+ limit := req.Limit
+ if limit <= 0 {
+ limit = 30
+ }
+
+ clauses, args := feedPageClauses(req)
+
+ // Determine SQL comparison and sort order for keyset cursor (pub_ts, feed_key).
+ wantDesc := (order == "newest" && dir == "older") || (order == "oldest" && dir == "newer")
+ reverseAfter := dir == "newer"
+
+ if req.Cursor != nil && (req.Cursor.Key != "" || req.Cursor.PubTs > 0) {
+ if wantDesc {
+ clauses = append(clauses, "(f.pub_ts < ? OR (f.pub_ts = ? AND f.feed_key < ?))")
+ } else {
+ clauses = append(clauses, "(f.pub_ts > ? OR (f.pub_ts = ? AND f.feed_key > ?))")
+ }
+ args = append(args, req.Cursor.PubTs, req.Cursor.PubTs, req.Cursor.Key)
+ }
+
+ query := `
+ SELECT
+ f.feed_key, f.site, f.kind, f.raw_id, f.mid, f.author_uid, f.author_name, f.author_face,
+ f.title, f.summary, f.cover_url, f.canonical_url, f.pub_ts, f.discovered_at,
+ f.cached, f.cache_status, f.item_key,
+ COALESCE(l.item_dir, ''), COALESCE(l.upgrade_available, 0), COALESCE(l.upgrade_hint, '')
+ FROM feed_items f
+ LEFT JOIN library_items l ON f.item_key = l.item_key
+ WHERE ` + strings.Join(clauses, " AND ")
+
+ if wantDesc {
+ query += " ORDER BY f.pub_ts DESC, f.feed_key DESC"
+ } else {
+ query += " ORDER BY f.pub_ts ASC, f.feed_key ASC"
+ }
+ query += fmt.Sprintf(" LIMIT %d", limit+1)
+
+ rows, err := s.db.Query(query, args...)
+ if err != nil {
+ return FeedPageResult{}, err
+ }
+ defer rows.Close()
+
+ var items []FeedEntry
+ for rows.Next() {
+ var e FeedEntry
+ var cachedInt, upAvail int
+ if err := rows.Scan(
+ &e.FeedKey, &e.Site, &e.Kind, &e.RawID, &e.Mid, &e.AuthorUID, &e.AuthorName, &e.AuthorFace,
+ &e.Title, &e.Summary, &e.CoverURL, &e.CanonicalURL, &e.PubTs, &e.DiscoveredAt,
+ &cachedInt, &e.CacheStatus, &e.ItemKey,
+ &e.ItemDir, &upAvail, &e.UpgradeHint,
+ ); err != nil {
+ return FeedPageResult{}, err
+ }
+ if e.AuthorUID == "" && e.Mid > 0 && e.Site == "bilibili" {
+ e.AuthorUID = strconv.FormatInt(e.Mid, 10)
+ }
+ e.Cached = cachedInt == 1
+ e.UpgradeAvailable = upAvail == 1
+ items = append(items, e)
+ }
+ if err := rows.Err(); err != nil {
+ return FeedPageResult{}, err
+ }
+
+ hasMore := false
+ if len(items) > limit {
+ hasMore = true
+ items = items[:limit]
+ }
+ if reverseAfter && len(items) > 1 {
+ for i, j := 0, len(items)-1; i < j; i, j = i+1, j-1 {
+ items[i], items[j] = items[j], items[i]
+ }
+ }
+
+ var res FeedPageResult
+ res.Items = items
+ res.HasMore = hasMore
+ if len(items) > 0 {
+ first := items[0]
+ last := items[len(items)-1]
+ res.PrevCursor = &FeedCursor{PubTs: first.PubTs, Key: first.FeedKey}
+ res.NextCursor = &FeedCursor{PubTs: last.PubTs, Key: last.FeedKey}
+ }
+ return res, nil
+}
+
+func feedPageClauses(req FeedPageRequest) ([]string, []any) {
+ clauses := []string{"NOT (f.kind = 'video' AND EXISTS (SELECT 1 FROM item_refs r WHERE r.to_key = f.feed_key))"}
+ var args []any
+ if req.CachedOnly {
+ clauses = append(clauses, "f.cached = 1")
+ }
+ if req.Kind != "" && req.Kind != "all" {
+ clauses = append(clauses, "f.kind = ?")
+ args = append(args, req.Kind)
+ }
+ clauses, args = appendSiteAndAuthorClauses(clauses, args, "f.", req.Site, 0, "", req.Authors, req.AuthorRefs)
+ return clauses, args
+}
+
+// Resolve a surviving key first; otherwise choose the newest item at or before
+// the saved timestamp (the earliest item if everything is newer). Resolving the
+// pivot before paging also handles more than one page of equal timestamps.
+func (s *Store) feedAnchorCursor(req FeedPageRequest) (*FeedCursor, error) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ clauses, args := feedPageClauses(req)
+ base := `SELECT f.feed_key, f.pub_ts FROM feed_items f WHERE ` + strings.Join(clauses, " AND ")
+ var pivot FeedCursor
+ if req.Cursor.Key != "" {
+ keyArgs := append(append([]any(nil), args...), req.Cursor.Key)
+ err := s.db.QueryRow(base+` AND f.feed_key = ?`, keyArgs...).Scan(&pivot.Key, &pivot.PubTs)
+ if err == nil {
+ return &pivot, nil
+ }
+ if !errors.Is(err, sql.ErrNoRows) {
+ return nil, err
+ }
+ }
+ if req.Cursor.PubTs > 0 {
+ tsArgs := append(append([]any(nil), args...), req.Cursor.PubTs)
+ err := s.db.QueryRow(base+` AND f.pub_ts <= ? ORDER BY f.pub_ts DESC, f.feed_key DESC LIMIT 1`, tsArgs...).Scan(&pivot.Key, &pivot.PubTs)
+ if err == nil {
+ return &pivot, nil
+ }
+ if !errors.Is(err, sql.ErrNoRows) {
+ return nil, err
+ }
+ }
+ order := "DESC"
+ if req.Cursor.PubTs > 0 {
+ order = "ASC"
+ }
+ err := s.db.QueryRow(base+" ORDER BY f.pub_ts "+order+", f.feed_key "+order+" LIMIT 1", args...).Scan(&pivot.Key, &pivot.PubTs)
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ return &pivot, err
+}
+
+// NewerCount returns the number of feed items published more recently than the given anchor (pubTs, key).
+func (s *Store) NewerCount(anchorPubTs int64, anchorKey string) (int, error) {
+ return s.newerCount(anchorPubTs, anchorKey, false)
+}
+
+func (s *Store) NewerCachedCount(anchorPubTs int64, anchorKey string) (int, error) {
+ return s.newerCount(anchorPubTs, anchorKey, true)
+}
+
+func (s *Store) newerCount(anchorPubTs int64, anchorKey string, cachedOnly bool) (int, error) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ if anchorPubTs <= 0 && anchorKey == "" {
+ return 0, nil
+ }
+ var count int
+ err := s.db.QueryRow(`
+ SELECT COUNT(1) FROM feed_items f
+ WHERE (? = 0 OR f.cached = 1) AND NOT (f.kind = 'video' AND EXISTS (SELECT 1 FROM item_refs r WHERE r.to_key = f.feed_key))
+ AND (f.pub_ts > ? OR (f.pub_ts = ? AND f.feed_key > ?))
+ `, cachedOnly, anchorPubTs, anchorPubTs, anchorKey).Scan(&count)
+ return count, err
+}
+
+// QueryFeed queries the unified feed (both online-discovered and locally cached items) ordered by pub_ts DESC.
+func (s *Store) QueryFeed(filter FeedFilter) ([]FeedEntry, error) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ var clauses []string
+ var args []any
+ if filter.Kind != "" && filter.Kind != "all" {
+ clauses = append(clauses, "f.kind = ?")
+ args = append(args, filter.Kind)
+ }
+ clauses, args = appendSiteAndAuthorClauses(clauses, args, "f.", filter.Site, filter.Mid, filter.AuthorUID, filter.Authors, filter.AuthorRefs)
+ if filter.CachedOnly {
+ clauses = append(clauses, "f.cached = 1")
+ }
+ if kw := strings.TrimSpace(filter.Keyword); kw != "" {
+ clauses = append(clauses, `(f.title LIKE ? ESCAPE '\' OR f.summary LIKE ? ESCAPE '\' OR f.author_name LIKE ? ESCAPE '\' OR f.raw_id LIKE ? ESCAPE '\')`)
+ pat := escapeLikePattern(kw)
+ args = append(args, pat, pat, pat, pat)
+ }
+
+ query := `
+ SELECT
+ f.feed_key, f.site, f.kind, f.raw_id, f.mid, f.author_uid, f.author_name, f.author_face,
+ f.title, f.summary, f.cover_url, f.canonical_url, f.pub_ts, f.discovered_at,
+ f.cached, f.cache_status, f.item_key,
+ COALESCE(l.item_dir, ''), COALESCE(l.upgrade_available, 0), COALESCE(l.upgrade_hint, '')
+ FROM feed_items f
+ LEFT JOIN library_items l ON f.item_key = l.item_key
+ `
+ if len(clauses) > 0 {
+ query += " WHERE " + strings.Join(clauses, " AND ")
+ }
+ if strings.EqualFold(filter.Sort, "oldest") {
+ query += " ORDER BY f.pub_ts ASC, f.feed_key ASC"
+ } else {
+ query += " ORDER BY f.pub_ts DESC, f.feed_key DESC"
+ }
+ limit := filter.Limit
+ if limit <= 0 {
+ limit = 200
+ }
+ query += fmt.Sprintf(" LIMIT %d OFFSET %d", limit, max(0, filter.Offset))
+
+ rows, err := s.db.Query(query, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var out []FeedEntry
+ for rows.Next() {
+ var e FeedEntry
+ var cachedInt, upAvail int
+ if err := rows.Scan(
+ &e.FeedKey, &e.Site, &e.Kind, &e.RawID, &e.Mid, &e.AuthorUID, &e.AuthorName, &e.AuthorFace,
+ &e.Title, &e.Summary, &e.CoverURL, &e.CanonicalURL, &e.PubTs, &e.DiscoveredAt,
+ &cachedInt, &e.CacheStatus, &e.ItemKey,
+ &e.ItemDir, &upAvail, &e.UpgradeHint,
+ ); err != nil {
+ return nil, err
+ }
+ if e.AuthorUID == "" && e.Mid > 0 && e.Site == "bilibili" {
+ e.AuthorUID = strconv.FormatInt(e.Mid, 10)
+ }
+ e.Cached = cachedInt == 1
+ e.UpgradeAvailable = upAvail == 1
+ out = append(out, e)
+ }
+ return out, rows.Err()
+}
diff --git a/internal/library/files.go b/internal/library/files.go
new file mode 100644
index 0000000..042ae70
--- /dev/null
+++ b/internal/library/files.go
@@ -0,0 +1,381 @@
+package library
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+
+ "github.com/chialecode/trace/internal/storage"
+)
+
+// ManifestFile is one file an item.json registers, relative to the item
+// folder (forward slashes), with what the manifest knows of it.
+type ManifestFile struct {
+ Path string `json:"path"`
+ Role string `json:"role,omitempty"`
+ Bytes int64 `json:"bytes,omitempty"`
+ SHA256 string `json:"sha256,omitempty"`
+}
+
+func cleanManifestRel(p string) string {
+ p = strings.TrimSpace(p)
+ if p == "" {
+ return ""
+ }
+ return filepath.ToSlash(filepath.Clean(filepath.FromSlash(p)))
+}
+
+// visitManifestFiles visits every file-path field referenced by meta in a
+// canonical order. Callers filter/deduplicate as needed.
+func visitManifestFiles(meta ItemMetadata, fn func(ManifestFile)) {
+ for _, m := range meta.Media {
+ if m.Path != "" {
+ fn(ManifestFile{Path: m.Path, Role: m.Role, Bytes: m.Bytes, SHA256: m.SHA256})
+ }
+ if m.Motion != "" {
+ fn(ManifestFile{Path: m.Motion, Role: "motion"})
+ }
+ }
+ for _, p := range meta.Parts {
+ if p.File != "" {
+ fn(ManifestFile{Path: p.File, Role: "video"})
+ }
+ if p.Danmaku != "" {
+ fn(ManifestFile{Path: p.Danmaku, Role: "danmaku"})
+ }
+ if p.Audio.SavedAs != "" {
+ fn(ManifestFile{Path: p.Audio.SavedAs, Role: "audio"})
+ }
+ for _, sub := range p.Subtitles {
+ if sub != "" {
+ fn(ManifestFile{Path: sub, Role: "subtitle"})
+ }
+ }
+ }
+ if meta.DouyinVideo != nil && meta.DouyinVideo.File != "" {
+ fn(ManifestFile{Path: meta.DouyinVideo.File, Role: "video"})
+ }
+ for _, np := range meta.NotePages {
+ if np.Image != "" {
+ fn(ManifestFile{Path: np.Image, Role: "image"})
+ }
+ if np.Cover != "" {
+ fn(ManifestFile{Path: np.Cover, Role: "cover"})
+ }
+ if np.Motion != "" {
+ fn(ManifestFile{Path: np.Motion, Role: "motion"})
+ }
+ if np.Video != "" {
+ fn(ManifestFile{Path: np.Video, Role: "video"})
+ }
+ if np.VideoInfo != nil && np.VideoInfo.File != "" {
+ fn(ManifestFile{Path: np.VideoInfo.File, Role: "video"})
+ }
+ }
+ if meta.Music != nil {
+ if meta.Music.File != "" {
+ fn(ManifestFile{Path: meta.Music.File, Role: "audio"})
+ }
+ if meta.Music.Cover != "" {
+ fn(ManifestFile{Path: meta.Music.Cover, Role: "cover"})
+ }
+ }
+ if meta.Live != nil {
+ for _, seg := range meta.Live.Segments {
+ if seg.File != "" {
+ fn(ManifestFile{Path: seg.File, Role: "live_segment", Bytes: seg.Bytes, SHA256: seg.SHA256})
+ }
+ }
+ }
+}
+
+// RegisteredFiles lists every finished file meta registers (media, parts,
+// danmaku, subtitles, note pages, music, live segments), each once, in a
+// stable order. Unfinished names (*.part, .trace-*) and paths that leave the
+// item folder are never listed; item.json itself is not either.
+func RegisteredFiles(meta ItemMetadata) []ManifestFile {
+ seen := map[string]int{}
+ var out []ManifestFile
+ visitManifestFiles(meta, func(f ManifestFile) {
+ rel := strings.TrimSpace(filepath.ToSlash(f.Path))
+ if rel == "" || strings.EqualFold(rel, "item.json") || strings.ContainsAny(rel, "\\:\x00") {
+ return
+ }
+ clean := cleanManifestRel(rel)
+ if clean == "" || strings.HasPrefix(clean, "../") || clean == ".." || strings.HasPrefix(clean, "/") || filepath.IsAbs(filepath.FromSlash(clean)) {
+ return
+ }
+ if storage.IsTempName(filepath.Base(clean)) {
+ return
+ }
+ key := strings.ToLower(clean)
+ if i, ok := seen[key]; ok {
+ if out[i].Bytes == 0 {
+ out[i].Bytes = f.Bytes
+ }
+ if out[i].SHA256 == "" {
+ out[i].SHA256 = f.SHA256
+ }
+ if out[i].Role == "" {
+ out[i].Role = f.Role
+ }
+ return
+ }
+ seen[key] = len(out)
+ f.Path = clean
+ out = append(out, f)
+ })
+ return out
+}
+
+func isRegisteredInManifest(meta ItemMetadata, normRel string) bool {
+ if normRel == "" {
+ return false
+ }
+ found := false
+ visitManifestFiles(meta, func(f ManifestFile) {
+ if !found && cleanManifestRel(f.Path) == normRel {
+ found = true
+ }
+ })
+ return found
+}
+
+func verifyItemFiles(itemDir string, meta *ItemMetadata, checkHash ...bool) (missing bool, totalBytes int64) {
+ missing, totalBytes, _ = verifyItemFilesDetail(itemDir, meta, len(checkHash) == 0 || checkHash[0])
+ return missing, totalBytes
+}
+
+// verifyItemFilesDetail is verifyItemFiles that also returns the manifest
+// paths that are missing, empty or no longer match the recorded size/hash.
+func verifyItemFilesDetail(itemDir string, meta *ItemMetadata, hash bool) (missing bool, totalBytes int64, missingPaths []string) {
+ checkedPaths := make(map[string]bool)
+ noted := make(map[string]bool)
+ note := func(rel string) {
+ if rel = cleanManifestRel(strings.TrimSpace(rel)); rel != "" && !noted[rel] {
+ noted[rel] = true
+ missingPaths = append(missingPaths, rel)
+ }
+ }
+
+ checkRel := func(rel string) (os.FileInfo, bool) {
+ rel = strings.TrimSpace(rel)
+ if rel == "" {
+ return nil, true
+ }
+ full, err := resolveItemPathRead(itemDir, rel)
+ if err != nil {
+ note(rel)
+ return nil, false
+ }
+ info, err := os.Lstat(full)
+ if err != nil || info.IsDir() || info.Size() == 0 {
+ note(rel)
+ return nil, false
+ }
+ norm := cleanManifestRel(rel)
+ if !checkedPaths[norm] {
+ checkedPaths[norm] = true
+ totalBytes += info.Size()
+ }
+ return info, true
+ }
+
+ for i := range meta.Media {
+ rel := meta.Media[i].Path
+ info, ok := checkRel(rel)
+ if !ok {
+ missing = true
+ } else if info != nil {
+ if meta.Media[i].Bytes > 0 && meta.Media[i].Bytes != info.Size() {
+ missing = true
+ note(rel)
+ } else if meta.Media[i].Bytes == 0 {
+ meta.Media[i].Bytes = info.Size()
+ }
+ if meta.Media[i].SHA256 != "" && hash {
+ if !VerifyMediaFile(itemDir, meta.Media[i], true) {
+ missing = true
+ note(rel)
+ }
+ }
+ }
+ if meta.Media[i].Motion != "" {
+ if _, ok := checkRel(meta.Media[i].Motion); !ok {
+ missing = true
+ }
+ }
+ }
+
+ visitManifestFiles(*meta, func(f ManifestFile) {
+ norm := cleanManifestRel(f.Path)
+ if norm == "" || checkedPaths[norm] || noted[norm] {
+ return
+ }
+ if _, ok := checkRel(f.Path); !ok {
+ missing = true
+ }
+ })
+
+ hasStructuredMedia := len(meta.Media) > 0 || len(meta.Parts) > 0 ||
+ (meta.DouyinVideo != nil && meta.DouyinVideo.File != "") ||
+ len(meta.NotePages) > 0 ||
+ (meta.Music != nil && meta.Music.File != "") ||
+ (meta.Live != nil && len(meta.Live.Segments) > 0)
+ if !hasStructuredMedia && meta.Kind != "dynamic" && meta.Status != "partial" && meta.Status != "recording" {
+ missing = true
+ }
+ return missing, totalBytes, missingPaths
+}
+
+// sumItemBytesAllowMoved computes TotalBytes for remote/allow-moved-files mode
+// (remote.md §6.1): files still on disk use their actual size (backfilling zero
+// Bytes in meta.Media), while files already uploaded and deleted retain their
+// manifest-recorded size without demoting meta.Status to missing_files.
+func sumItemBytesAllowMoved(itemDir string, meta *ItemMetadata) int64 {
+ seen := make(map[string]bool)
+ var totalBytes int64
+ addFile := func(rel string, recordedBytes int64) int64 {
+ norm := cleanManifestRel(rel)
+ if norm == "" || seen[strings.ToLower(norm)] {
+ return recordedBytes
+ }
+ seen[strings.ToLower(norm)] = true
+ size := recordedBytes
+ if full, err := resolveItemPathRead(itemDir, rel); err == nil {
+ if info, err := os.Lstat(full); err == nil && info.Mode().IsRegular() && info.Size() > 0 {
+ size = info.Size()
+ }
+ }
+ totalBytes += size
+ return size
+ }
+ for i := range meta.Media {
+ if meta.Media[i].Path != "" {
+ sz := addFile(meta.Media[i].Path, meta.Media[i].Bytes)
+ if meta.Media[i].Bytes == 0 && sz > 0 {
+ meta.Media[i].Bytes = sz
+ }
+ }
+ if meta.Media[i].Motion != "" {
+ addFile(meta.Media[i].Motion, 0)
+ }
+ }
+ visitManifestFiles(*meta, func(f ManifestFile) {
+ addFile(f.Path, f.Bytes)
+ })
+ return totalBytes
+}
+
+// VerifyMediaFile checks a registered file without rewriting its expected size.
+func VerifyMediaFile(itemDir string, file MediaFile, checkHash bool) bool {
+ full, err := resolveItemPathRead(itemDir, file.Path)
+ if err != nil {
+ return false
+ }
+ info, err := os.Lstat(full)
+ if err != nil || !info.Mode().IsRegular() || info.Size() <= 0 || file.Bytes > 0 && info.Size() != file.Bytes {
+ return false
+ }
+ if !checkHash || file.SHA256 == "" {
+ return true
+ }
+ f, err := os.Open(full)
+ if err != nil {
+ return false
+ }
+ defer f.Close()
+ h := sha256.New()
+ if _, err := io.Copy(h, f); err != nil {
+ return false
+ }
+ return strings.EqualFold(hex.EncodeToString(h.Sum(nil)), file.SHA256)
+}
+
+// RemoveItemFile deletes one file of an indexed item after it was uploaded
+// (docs/design/remote.md §6.2). Only a file the item's manifest registers,
+// or its item.json, inside the item folder, is removed (INV-09); the index
+// entry stays. A file already gone is not an error.
+func (s *Store) RemoveItemFile(itemKey, rel string) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ meta, ok, err := s.getItemLocked(itemKey)
+ if err != nil {
+ return err
+ }
+ if !ok || meta.ItemDir == "" {
+ return fmt.Errorf("library: item %s is not indexed", itemKey)
+ }
+ clean := cleanManifestRel(filepath.ToSlash(rel))
+ if !strings.EqualFold(clean, "item.json") && !isRegisteredInManifest(meta, clean) {
+ return fmt.Errorf("library: %s is not registered by %s", clean, itemKey)
+ }
+ if !safeRegisteredPathStrict(meta.ItemDir, clean) {
+ return fmt.Errorf("library: unsafe path %s", clean)
+ }
+ full, err := ResolveItemPath(meta.ItemDir, clean)
+ if err != nil {
+ return err
+ }
+ if err := os.Remove(full); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ return nil
+}
+
+// RemoveEmptyItemFolders removes the item's folder and the author and kind
+// folders above it when they are empty (never a library root).
+func (s *Store) RemoveEmptyItemFolders(itemKey string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ meta, ok, err := s.getItemLocked(itemKey)
+ if err != nil || !ok || meta.ItemDir == "" {
+ return
+ }
+ removeEmptyDirsBottomUp(meta.ItemDir)
+ if _, err := os.Stat(meta.ItemDir); os.IsNotExist(err) {
+ removeEmptyAuthorDirs(meta.ItemDir, s.allRootsLocked())
+ }
+}
+
+// AllItemKeys lists every indexed item key, sorted.
+func (s *Store) AllItemKeys() ([]string, error) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ rows, err := s.db.Query(`SELECT item_key FROM library_items`)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []string
+ for rows.Next() {
+ var k string
+ if err := rows.Scan(&k); err != nil {
+ return nil, err
+ }
+ out = append(out, k)
+ }
+ sort.Strings(out)
+ return out, rows.Err()
+}
+
+// RelativeItemDir is the item folder relative to the library root that holds
+// it (forward slashes), e.g. "bilibili/<作者>/videos/<条目>".
+func (s *Store) RelativeItemDir(itemDir string) (string, bool) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ itemDir = filepath.Clean(itemDir)
+ for _, root := range s.allRootsLocked() {
+ rel, err := filepath.Rel(filepath.Clean(root), itemDir)
+ if err != nil || rel == "." || strings.HasPrefix(rel, "..") || filepath.IsAbs(rel) {
+ continue
+ }
+ return filepath.ToSlash(rel), true
+ }
+ return "", false
+}
diff --git a/internal/library/fixes_test.go b/internal/library/fixes_test.go
new file mode 100644
index 0000000..d5dc4ba
--- /dev/null
+++ b/internal/library/fixes_test.go
@@ -0,0 +1,297 @@
+package library
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/chialecode/trace/internal/storage"
+)
+
+func TestAllowMovedFilesPreservesCompleteStatus(t *testing.T) {
+ tmp := t.TempDir()
+ db, _, _, err := storage.OpenSQLite(filepath.Join(tmp, "library.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ cacheDir := filepath.Join(tmp, "export")
+ store, err := OpenWithDataDir(db, cacheDir, tmp)
+ if err != nil {
+ t.Fatal(err)
+ }
+ store.SetAllowMovedFiles(true)
+
+ itemDir := filepath.Join(cacheDir, "bilibili", "1001_UP", "lives", "live_42_100")
+ if err := os.MkdirAll(itemDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ // Simulate segment 1 already uploaded & deleted locally while segment 2 finishes.
+ if err := os.WriteFile(filepath.Join(itemDir, "part-002.mp4"), []byte("seg2-bytes"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ saved, err := store.SaveItem(itemDir, ItemMetadata{
+ Version: 1,
+ ID: "42:100",
+ Site: "bilibili",
+ Kind: "live",
+ Status: "complete",
+ Title: "Live",
+ Author: ItemAuthor{Mid: 1001, Name: "UP"},
+ Media: []MediaFile{
+ {Role: "live_segment", Path: "part-001.mp4", Bytes: 1234, SHA256: "aaa"},
+ {Role: "live_segment", Path: "part-002.mp4", Bytes: 10, SHA256: "bbb"},
+ },
+ Live: &LiveRecordingInfo{
+ RoomID: 42,
+ Segments: []LiveSegmentInfo{
+ {File: "part-001.mp4", Bytes: 1234, SHA256: "aaa"},
+ {File: "part-002.mp4", Bytes: 10, SHA256: "bbb"},
+ },
+ },
+ })
+ if err != nil {
+ t.Fatalf("SaveItem: %v", err)
+ }
+ if saved.Status != "complete" || saved.TotalBytes != 1244 {
+ t.Fatalf("saved = status %q bytes %d, want complete / 1244", saved.Status, saved.TotalBytes)
+ }
+ // Remove segment 2 as well (everything moved to cloud).
+ _ = os.Remove(filepath.Join(itemDir, "part-002.mp4"))
+ got, ok, err := store.GetItem(saved.ItemKey)
+ if err != nil || !ok || got.Status != "complete" {
+ t.Fatalf("GetItem after move = (%q, %v, %v), want complete", got.Status, ok, err)
+ }
+ states := store.States([]string{saved.ItemKey})
+ if states[saved.ItemKey].Dot != "green" {
+ t.Fatalf("States after move = %+v, want green", states[saved.ItemKey])
+ }
+ list, err := store.ListItems(FeedFilter{})
+ if err != nil || len(list) != 1 || list[0].Status != "complete" {
+ t.Fatalf("ListItems after move = %+v, %v", list, err)
+ }
+}
+
+func TestMergeItemMetadataLiveSequentialOrderContentDedupAndSupplement(t *testing.T) {
+ // 1. Two machines recorded same broadcast: [L1 (001)] + [R1 (001), R2 (002)] -> [L1 (001), R1 (002), R2 (003)].
+ local := ItemMetadata{
+ ItemKey: "bilibili:live:42:100",
+ Kind: "live",
+ Media: []MediaFile{{Role: "live_segment", Path: "part-001.mp4", Bytes: 10, SHA256: "hashL1"}},
+ Live: &LiveRecordingInfo{
+ RoomID: 42,
+ Segments: []LiveSegmentInfo{{File: "part-001.mp4", Bytes: 10, SHA256: "hashL1"}},
+ },
+ }
+ imported := ItemMetadata{
+ ItemKey: "bilibili:live:42:100",
+ Kind: "live",
+ Media: []MediaFile{
+ {Role: "live_segment", Path: "part-001.mp4", Bytes: 11, SHA256: "hashR1"},
+ {Role: "live_segment", Path: "part-002.mp4", Bytes: 12, SHA256: "hashR2"},
+ },
+ Live: &LiveRecordingInfo{
+ RoomID: 42,
+ Segments: []LiveSegmentInfo{
+ {File: "part-001.mp4", Bytes: 11, SHA256: "hashR1"},
+ {File: "part-002.mp4", Bytes: 12, SHA256: "hashR2"},
+ },
+ },
+ }
+ merged, renames := MergeItemMetadata(local, imported, MergeUnion, nil)
+ if len(merged.Live.Segments) != 3 {
+ t.Fatalf("merged segments = %+v, want 3", merged.Live.Segments)
+ }
+ wantOrder := []struct{ file, sha string }{
+ {"part-001.mp4", "hashL1"},
+ {"part-002.mp4", "hashR1"},
+ {"part-003.mp4", "hashR2"},
+ }
+ for i, w := range wantOrder {
+ got := merged.Live.Segments[i]
+ if got.File != w.file || got.SHA256 != w.sha {
+ t.Fatalf("segment[%d] = %+v, want %+v", i, got, w)
+ }
+ }
+ if len(renames) != 2 || renames[0] != (SegmentRename{From: "part-001.mp4", To: "part-002.mp4"}) || renames[1] != (SegmentRename{From: "part-002.mp4", To: "part-003.mp4"}) {
+ t.Fatalf("renames = %+v", renames)
+ }
+ // Ensure caller's local slice was not mutated.
+ if len(local.Live.Segments) != 1 || len(local.Media) != 1 {
+ t.Fatal("MergeItemMetadata mutated local input slices")
+ }
+
+ // 2. Content deduplication even when duplicate segment is under an untaken filename.
+ local2 := ItemMetadata{
+ ItemKey: "bilibili:live:42:100",
+ Kind: "live",
+ Media: []MediaFile{{Role: "live_segment", Path: "part-001.mp4", Bytes: 12, SHA256: "hashB"}},
+ Live: &LiveRecordingInfo{
+ RoomID: 42,
+ Segments: []LiveSegmentInfo{{File: "part-001.mp4", Bytes: 12, SHA256: "hashB"}},
+ },
+ }
+ imported2 := ItemMetadata{
+ ItemKey: "bilibili:live:42:100",
+ Kind: "live",
+ Media: []MediaFile{
+ {Role: "live_segment", Path: "part-001.mp4", Bytes: 11, SHA256: "hashA"},
+ {Role: "live_segment", Path: "part-002.mp4", Bytes: 12, SHA256: "hashB"},
+ },
+ Live: &LiveRecordingInfo{
+ RoomID: 42,
+ Segments: []LiveSegmentInfo{
+ {File: "part-001.mp4", Bytes: 11, SHA256: "hashA"},
+ {File: "part-002.mp4", Bytes: 12, SHA256: "hashB"},
+ },
+ },
+ }
+ merged2, _ := MergeItemMetadata(local2, imported2, MergeUnion, nil)
+ if len(merged2.Live.Segments) != 2 {
+ t.Fatalf("duplicate segment not deduped: %+v", merged2.Live.Segments)
+ }
+
+ // 3. Supplementing NotePages, Music, and Parts fields previously cleared by KeepListedFiles.
+ full := ItemMetadata{
+ ItemKey: "douyin:dynamic:999",
+ Kind: "dynamic",
+ Media: []MediaFile{
+ {Role: "image", Path: "images/01.jpg"},
+ {Role: "image", Path: "images/02.jpg"},
+ {Role: "audio", Path: "music.mp3"},
+ },
+ NotePages: []NotePageRecord{
+ {Index: 1, Kind: "image", Image: "images/01.jpg"},
+ {Index: 2, Kind: "image", Image: "images/02.jpg"},
+ },
+ Music: &MusicInfo{Title: "BGM", File: "music.mp3"},
+ Parts: []VideoPartRecord{{Page: 1, File: "P01.mp4", Danmaku: "P01.danmaku.xml", Subtitles: []string{"P01.zh.srt"}}},
+ }
+ partial, _ := KeepListedFiles(full, func(rel string) bool {
+ return rel == "images/01.jpg" || rel == "P01.mp4"
+ })
+ if partial.NotePages[1].Image != "" || partial.Music.File != "" || partial.Parts[0].Danmaku != "" {
+ t.Fatalf("KeepListedFiles did not clear missing fields: %+v", partial)
+ }
+ supplemented, _ := MergeItemMetadata(partial, full, MergeUnion, nil)
+ if supplemented.NotePages[1].Image != "images/02.jpg" || supplemented.Music.File != "music.mp3" || supplemented.Parts[0].Danmaku != "P01.danmaku.xml" || len(supplemented.Parts[0].Subtitles) != 1 {
+ t.Fatalf("supplemented fields stayed empty: pages=%+v music=%+v parts=%+v", supplemented.NotePages, supplemented.Music, supplemented.Parts)
+ }
+}
+
+func TestUnsafeManifestPathsRejectsCrossPlatformTraversal(t *testing.T) {
+ bad := UnsafeManifestPaths(ItemMetadata{
+ Media: []MediaFile{
+ {Path: `..\..\evil.mp4`},
+ {Path: "C:evil.mp4"},
+ {Path: "ok\x00evil.mp4"},
+ {Path: "./ok.mp4"},
+ {Path: "images/01.jpg"},
+ },
+ })
+ if len(bad) != 4 {
+ t.Fatalf("UnsafeManifestPaths = %v, want 4 unsafe paths", bad)
+ }
+}
+
+func TestGetItemLiveShortKeyLikeEscapeAndDotLabel(t *testing.T) {
+ tmp := t.TempDir()
+ db, _, _, err := storage.OpenSQLite(filepath.Join(tmp, "library.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ cacheDir := filepath.Join(tmp, "cache")
+ store, err := OpenWithDataDir(db, cacheDir, tmp)
+ if err != nil {
+ t.Fatal(err)
+ }
+ liveDir := filepath.Join(cacheDir, "bilibili", "1001_UP", "lives", "live_42_100")
+ _ = os.MkdirAll(liveDir, 0o700)
+ _ = os.WriteFile(filepath.Join(liveDir, "part-001.mp4"), []byte("live"), 0o600)
+ if _, err := store.SaveItem(liveDir, ItemMetadata{
+ Version: 1, ID: "42:100", Site: "bilibili", Kind: "live", Status: "complete",
+ Title: "100% Pure_Test", Author: ItemAuthor{Mid: 1001, Name: "UP"},
+ Media: []MediaFile{{Role: "live_segment", Path: "part-001.mp4"}},
+ Live: &LiveRecordingInfo{RoomID: 42, Segments: []LiveSegmentInfo{{File: "part-001.mp4"}}},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ // Live short key "live:42:100" must resolve to "bilibili:live:42:100".
+ if got, ok, err := store.GetItem("live:42:100"); err != nil || !ok || got.ItemKey != "bilibili:live:42:100" {
+ t.Fatalf("GetItem(live:42:100) = (%+v, %v, %v)", got, ok, err)
+ }
+ // LIKE wildcard escaping: searching "100%" must match "100% Pure_Test",
+ // whereas searching "100X" must not match via unescaped '%'.
+ vidDir := filepath.Join(cacheDir, "bilibili", "1001_UP", "videos", "video_BV1like")
+ _ = os.MkdirAll(vidDir, 0o700)
+ _ = os.WriteFile(filepath.Join(vidDir, "P01.mp4"), []byte("vid"), 0o600)
+ if _, err := store.SaveItem(vidDir, ItemMetadata{
+ Version: 1, ID: "BV1like", Site: "bilibili", Kind: "video", Status: "complete",
+ Title: "1000 PureXTest", Author: ItemAuthor{Mid: 1001, Name: "UP"},
+ Media: []MediaFile{{Role: "video", Path: "P01.mp4"}},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ pctItems, err := store.ListItems(FeedFilter{Keyword: "100%"})
+ if err != nil || len(pctItems) != 1 || pctItems[0].ItemKey != "bilibili:live:42:100" {
+ t.Fatalf("ListItems(100%%) = %+v, err=%v", pctItems, err)
+ }
+ underItems, err := store.ListItems(FeedFilter{Keyword: "Pure_Test"})
+ if err != nil || len(underItems) != 1 || underItems[0].ItemKey != "bilibili:live:42:100" {
+ t.Fatalf("ListItems(Pure_Test) = %+v, err=%v", underItems, err)
+ }
+
+ // ComputeDotState belowBest without Missing or UpgradeAvailable must not say "部分缺失".
+ dot := ComputeDotState(ItemMetadata{
+ ItemKey: "bilibili:video:BV1q",
+ Status: "complete",
+ Parts: []VideoPartRecord{{
+ Page: 1,
+ File: "P01.mp4",
+ Video: PartVideoInfo{Quality: 64},
+ Available: PartAvailableInfo{BestVideo: 80},
+ }},
+ })
+ if dot.Dot != "yellow" || dot.Label != "非最高画质" {
+ t.Fatalf("ComputeDotState(belowBest) = %+v, want yellow / 非最高画质", dot)
+ }
+}
+
+func TestPlanDeleteFailsClosedOnDBError(t *testing.T) {
+ tmp := t.TempDir()
+ db, _, _, err := storage.OpenSQLite(filepath.Join(tmp, "library.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ cacheDir := filepath.Join(tmp, "cache")
+ store, err := OpenWithDataDir(db, cacheDir, tmp)
+ if err != nil {
+ t.Fatal(err)
+ }
+ vidDir := filepath.Join(cacheDir, "bilibili", "1001_UP", "videos", "video_BV1shared")
+ dynDir := filepath.Join(cacheDir, "bilibili", "1001_UP", "dynamics", "dyn_1")
+ _ = os.MkdirAll(vidDir, 0o700)
+ _ = os.MkdirAll(dynDir, 0o700)
+ _ = os.WriteFile(filepath.Join(vidDir, "P01.mp4"), []byte("v"), 0o600)
+ if _, err := store.SaveItem(vidDir, ItemMetadata{
+ Version: 1, ID: "BV1shared", Site: "bilibili", Kind: "video", Status: "complete",
+ Author: ItemAuthor{Mid: 1001, Name: "UP"}, Media: []MediaFile{{Role: "video", Path: "P01.mp4"}},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := store.SaveItem(dynDir, ItemMetadata{
+ Version: 1, ID: "1", Site: "bilibili", Kind: "dynamic", Status: "complete",
+ Author: ItemAuthor{Mid: 1001, Name: "UP"}, Videos: []string{"BV1shared"},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ // Drop item_refs to simulate a SQL error during shared-reference checking.
+ if _, err := db.Exec(`DROP TABLE item_refs`); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := store.PlanDelete("bilibili:dynamic:1"); err == nil {
+ t.Fatal("PlanDelete succeeded despite item_refs DB error")
+ }
+}
diff --git a/internal/library/junction_windows_test.go b/internal/library/junction_windows_test.go
index ea722f7..63eeb0e 100644
--- a/internal/library/junction_windows_test.go
+++ b/internal/library/junction_windows_test.go
@@ -78,3 +78,84 @@ func TestJunctionInsideItemIsNeitherServedNorDeleted(t *testing.T) {
t.Fatalf("file behind junction was removed or changed: %q %v", data, err)
}
}
+
+func TestRebuildAndAddRootIgnoreWindowsJunction(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")
+ store, err := OpenWithDataDir(db, cacheDir, tmp)
+ if err != nil {
+ t.Fatalf("OpenWithDataDir: %v", err)
+ }
+ if err := os.MkdirAll(cacheDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ outside := filepath.Join(tmp, "outside")
+ if err := os.MkdirAll(outside, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ // Put a non-TRACE item.json outside: if WalkDir traversed the junction,
+ // RebuildIndex would rename it via BackupCorruptFile!
+ outsideJSON := filepath.Join(outside, "item.json")
+ if err := os.WriteFile(outsideJSON, []byte(`{"not":"trace"}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ junc := filepath.Join(cacheDir, "linked_outside")
+ cmd := exec.Command("cmd", "/c", "mklink", "/J", junc, outside)
+ cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: 0x08000000}
+ if out, err := cmd.CombinedOutput(); err != nil {
+ t.Skipf("cannot create junction: %v %s", err, out)
+ }
+
+ rep, err := store.RebuildIndex()
+ if err != nil {
+ t.Fatalf("RebuildIndex: %v", err)
+ }
+ if rep.Scanned != 0 || len(rep.CorruptBackedUp) != 0 {
+ t.Fatalf("RebuildIndex traversed junction: %+v", rep)
+ }
+ if _, err := os.Stat(outsideJSON); err != nil {
+ t.Fatalf("outside item.json was touched through junction: %v", err)
+ }
+
+ // AddLibraryRoot must also skip junctions inside the scanned root.
+ addRep, err := store.AddLibraryRoot(cacheDir)
+ if err != nil {
+ t.Fatalf("AddLibraryRoot: %v", err)
+ }
+ if addRep.Scanned != 0 {
+ t.Fatalf("AddLibraryRoot traversed junction: %+v", addRep)
+ }
+ // Direct junction as root must be rejected.
+ if _, err := store.AddLibraryRoot(junc); err == nil {
+ t.Fatal("AddLibraryRoot accepted a junction root")
+ }
+
+ // Swapping an itemDir to a junction within the 3s read-cache TTL must be
+ // caught immediately by ResolveItemPath (no TTL cache on writes/deletes).
+ swapDir := filepath.Join(cacheDir, "swap_item")
+ if err := os.MkdirAll(swapDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if !safeRegisteredPathRead(swapDir, "a.mp4") {
+ t.Fatal("expected real swapDir to pass read check")
+ }
+ if err := os.Remove(swapDir); err != nil {
+ t.Fatal(err)
+ }
+ cmd2 := exec.Command("cmd", "/c", "mklink", "/J", swapDir, outside)
+ cmd2.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: 0x08000000}
+ if out, err := cmd2.CombinedOutput(); err != nil {
+ t.Skipf("cannot create second junction: %v %s", err, out)
+ }
+ if _, err := ResolveItemPath(swapDir, "a.mp4"); err == nil {
+ t.Fatal("ResolveItemPath trusted cached dir after swap to junction")
+ }
+ if safeRegisteredPathRead(swapDir, "a.mp4") {
+ t.Fatal("safeRegisteredPathRead cached itemDir itself after swap to junction")
+ }
+}
diff --git a/internal/library/library.go b/internal/library/library.go
index 37a984b..51d8330 100644
--- a/internal/library/library.go
+++ b/internal/library/library.go
@@ -1,24 +1,16 @@
package library
import (
- "context"
- "crypto/sha256"
"database/sql"
- "encoding/hex"
"encoding/json"
- "errors"
"fmt"
- "io"
- "io/fs"
"os"
"path/filepath"
- "sort"
"strconv"
"strings"
"sync"
"time"
- "github.com/chialecode/trace/internal/site/bilibili"
"github.com/chialecode/trace/internal/storage"
)
@@ -55,6 +47,9 @@ type Store struct {
extraRoots []string
rootsFilePath string
pendingDeletesPath string
+ node *ItemNode
+ onSaved []func(ItemMetadata)
+ allowMovedFiles bool
}
// Open initializes the library SQLite schema in db and sets the active cacheDir.
@@ -91,319 +86,27 @@ func OpenWithDataDir(db *sql.DB, cacheDir, dataDir string) (*Store, error) {
return s, nil
}
-var (
- migrateV2HookMu sync.Mutex
- migrateV2Hook func(tx *sql.Tx) error
-)
-
-// SetMigrateV2HookForTest installs a fault-injection callback invoked inside
-// the v1 -> v2 SQLite migration transaction right before PRAGMA user_version = 2.
-func SetMigrateV2HookForTest(fn func(tx *sql.Tx) error) func() {
- migrateV2HookMu.Lock()
- prev := migrateV2Hook
- migrateV2Hook = fn
- migrateV2HookMu.Unlock()
- return func() {
- migrateV2HookMu.Lock()
- migrateV2Hook = prev
- migrateV2HookMu.Unlock()
- }
-}
-
-func (s *Store) initSchema() error {
- v, err := storage.CheckSQLiteSchema(s.db, "library.db", CurrentSchemaVersion)
- if err != nil {
- return err
- }
- if v < CurrentSchemaVersion {
- return s.migrateSchemaToV2()
- }
- for _, q := range schemaV2Statements() {
- if _, err := s.db.Exec(q); err != nil {
- return fmt.Errorf("library: init schema: %w", err)
- }
- }
- return nil
-}
-
-func schemaV2Statements() []string {
- return []string{
- `CREATE TABLE IF NOT EXISTS library_items (
- item_key TEXT PRIMARY KEY,
- site TEXT NOT NULL,
- kind TEXT NOT NULL,
- raw_id TEXT NOT NULL,
- mid INTEGER NOT NULL DEFAULT 0,
- author_uid TEXT NOT NULL DEFAULT '',
- author_name TEXT NOT NULL DEFAULT '',
- author_face TEXT NOT NULL DEFAULT '',
- title TEXT NOT NULL DEFAULT '',
- summary TEXT NOT NULL DEFAULT '',
- cover_path TEXT NOT NULL DEFAULT '',
- canonical_url TEXT NOT NULL DEFAULT '',
- pub_ts INTEGER NOT NULL DEFAULT 0,
- cached_at TEXT NOT NULL DEFAULT '',
- status TEXT NOT NULL DEFAULT 'complete',
- item_dir TEXT NOT NULL DEFAULT '',
- total_bytes INTEGER NOT NULL DEFAULT 0,
- upgrade_available INTEGER NOT NULL DEFAULT 0,
- upgrade_hint TEXT NOT NULL DEFAULT '',
- json_data TEXT NOT NULL
- );`,
- `CREATE INDEX IF NOT EXISTS idx_library_items_pub_ts ON library_items(pub_ts DESC);`,
- `CREATE INDEX IF NOT EXISTS idx_library_items_mid ON library_items(mid);`,
- `CREATE INDEX IF NOT EXISTS idx_library_items_site_author ON library_items(site, author_uid);`,
- `CREATE INDEX IF NOT EXISTS idx_library_items_via ON library_items(site, json_extract(json_data, '$.via.uid'));`,
- `CREATE TABLE IF NOT EXISTS item_refs (
- from_key TEXT NOT NULL,
- to_key TEXT NOT NULL,
- PRIMARY KEY (from_key, to_key)
- );`,
- `CREATE INDEX IF NOT EXISTS idx_item_refs_to ON item_refs(to_key);`,
- `CREATE TABLE IF NOT EXISTS feed_items (
- feed_key TEXT PRIMARY KEY,
- site TEXT NOT NULL,
- kind TEXT NOT NULL,
- raw_id TEXT NOT NULL,
- mid INTEGER NOT NULL DEFAULT 0,
- author_uid TEXT NOT NULL DEFAULT '',
- author_name TEXT NOT NULL DEFAULT '',
- author_face TEXT NOT NULL DEFAULT '',
- title TEXT NOT NULL DEFAULT '',
- summary TEXT NOT NULL DEFAULT '',
- cover_url TEXT NOT NULL DEFAULT '',
- canonical_url TEXT NOT NULL DEFAULT '',
- pub_ts INTEGER NOT NULL DEFAULT 0,
- discovered_at TEXT NOT NULL DEFAULT '',
- cached INTEGER NOT NULL DEFAULT 0,
- cache_status TEXT NOT NULL DEFAULT '',
- item_key TEXT NOT NULL DEFAULT ''
- );`,
- `CREATE INDEX IF NOT EXISTS idx_feed_items_pub_ts ON feed_items(pub_ts DESC);`,
- `CREATE INDEX IF NOT EXISTS idx_feed_items_mid ON feed_items(mid);`,
- `CREATE INDEX IF NOT EXISTS idx_feed_items_site_author ON feed_items(site, author_uid);`,
- `CREATE TABLE IF NOT EXISTS download_tasks (
- task_id TEXT PRIMARY KEY,
- site TEXT NOT NULL,
- kind TEXT NOT NULL,
- source TEXT NOT NULL DEFAULT 'manual',
- target_id TEXT NOT NULL,
- cid INTEGER NOT NULL DEFAULT 0,
- page INTEGER NOT NULL DEFAULT 1,
- title TEXT NOT NULL DEFAULT '',
- part_title TEXT NOT NULL DEFAULT '',
- mid INTEGER NOT NULL DEFAULT 0,
- author_uid TEXT NOT NULL DEFAULT '',
- author_name TEXT NOT NULL DEFAULT '',
- author_face TEXT NOT NULL DEFAULT '',
- cover_url TEXT NOT NULL DEFAULT '',
- cache_linked_videos INTEGER NOT NULL DEFAULT 0,
- status TEXT NOT NULL DEFAULT 'queued',
- pause_reason TEXT NOT NULL DEFAULT '',
- error_kind TEXT NOT NULL DEFAULT '',
- error_message TEXT NOT NULL DEFAULT '',
- quality_hint TEXT NOT NULL DEFAULT '',
- bytes_downloaded INTEGER NOT NULL DEFAULT 0,
- total_bytes INTEGER NOT NULL DEFAULT 0,
- progress REAL NOT NULL DEFAULT 0,
- item_key TEXT NOT NULL DEFAULT '',
- item_dir TEXT NOT NULL DEFAULT '',
- files_json TEXT NOT NULL DEFAULT '[]',
- attempts_json TEXT NOT NULL DEFAULT '[]',
- created_at TEXT NOT NULL,
- updated_at TEXT NOT NULL
- );`,
- `CREATE INDEX IF NOT EXISTS idx_download_tasks_site_author ON download_tasks(site, author_uid);`,
- `CREATE TABLE IF NOT EXISTS task_attempts (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- task_id TEXT NOT NULL,
- attempt_time TEXT NOT NULL,
- file_path TEXT NOT NULL,
- offset_bytes INTEGER NOT NULL DEFAULT 0,
- host TEXT NOT NULL DEFAULT '',
- attempt_num INTEGER NOT NULL DEFAULT 1,
- error_kind TEXT NOT NULL DEFAULT '',
- http_status INTEGER NOT NULL DEFAULT 0
- );`,
- }
+// SetAllowMovedFiles configures remote/export mode (remote.md §6.1), where
+// uploaded files may be moved or deleted from the export folder without
+// demoting saved or queried items to missing_files. Default is false.
+func (s *Store) SetAllowMovedFiles(allow bool) {
+ s.mu.Lock()
+ s.allowMovedFiles = allow
+ s.mu.Unlock()
}
-func (s *Store) migrateSchemaToV2() error {
- tx, err := s.db.Begin()
- if err != nil {
- return fmt.Errorf("library: begin schema v2 migration: %w", err)
- }
- defer tx.Rollback()
-
- baseTables := []string{
- `CREATE TABLE IF NOT EXISTS library_items (
- item_key TEXT PRIMARY KEY,
- site TEXT NOT NULL,
- kind TEXT NOT NULL,
- raw_id TEXT NOT NULL,
- mid INTEGER NOT NULL DEFAULT 0,
- author_uid TEXT NOT NULL DEFAULT '',
- author_name TEXT NOT NULL DEFAULT '',
- author_face TEXT NOT NULL DEFAULT '',
- title TEXT NOT NULL DEFAULT '',
- summary TEXT NOT NULL DEFAULT '',
- cover_path TEXT NOT NULL DEFAULT '',
- canonical_url TEXT NOT NULL DEFAULT '',
- pub_ts INTEGER NOT NULL DEFAULT 0,
- cached_at TEXT NOT NULL DEFAULT '',
- status TEXT NOT NULL DEFAULT 'complete',
- item_dir TEXT NOT NULL DEFAULT '',
- total_bytes INTEGER NOT NULL DEFAULT 0,
- upgrade_available INTEGER NOT NULL DEFAULT 0,
- upgrade_hint TEXT NOT NULL DEFAULT '',
- json_data TEXT NOT NULL
- );`,
- `CREATE TABLE IF NOT EXISTS item_refs (
- from_key TEXT NOT NULL,
- to_key TEXT NOT NULL,
- PRIMARY KEY (from_key, to_key)
- );`,
- `CREATE TABLE IF NOT EXISTS feed_items (
- feed_key TEXT PRIMARY KEY,
- site TEXT NOT NULL,
- kind TEXT NOT NULL,
- raw_id TEXT NOT NULL,
- mid INTEGER NOT NULL DEFAULT 0,
- author_uid TEXT NOT NULL DEFAULT '',
- author_name TEXT NOT NULL DEFAULT '',
- author_face TEXT NOT NULL DEFAULT '',
- title TEXT NOT NULL DEFAULT '',
- summary TEXT NOT NULL DEFAULT '',
- cover_url TEXT NOT NULL DEFAULT '',
- canonical_url TEXT NOT NULL DEFAULT '',
- pub_ts INTEGER NOT NULL DEFAULT 0,
- discovered_at TEXT NOT NULL DEFAULT '',
- cached INTEGER NOT NULL DEFAULT 0,
- cache_status TEXT NOT NULL DEFAULT '',
- item_key TEXT NOT NULL DEFAULT ''
- );`,
- `CREATE TABLE IF NOT EXISTS download_tasks (
- task_id TEXT PRIMARY KEY,
- site TEXT NOT NULL,
- kind TEXT NOT NULL,
- source TEXT NOT NULL DEFAULT 'manual',
- target_id TEXT NOT NULL,
- cid INTEGER NOT NULL DEFAULT 0,
- page INTEGER NOT NULL DEFAULT 1,
- title TEXT NOT NULL DEFAULT '',
- part_title TEXT NOT NULL DEFAULT '',
- mid INTEGER NOT NULL DEFAULT 0,
- author_uid TEXT NOT NULL DEFAULT '',
- author_name TEXT NOT NULL DEFAULT '',
- author_face TEXT NOT NULL DEFAULT '',
- cover_url TEXT NOT NULL DEFAULT '',
- cache_linked_videos INTEGER NOT NULL DEFAULT 0,
- status TEXT NOT NULL DEFAULT 'queued',
- pause_reason TEXT NOT NULL DEFAULT '',
- error_kind TEXT NOT NULL DEFAULT '',
- error_message TEXT NOT NULL DEFAULT '',
- quality_hint TEXT NOT NULL DEFAULT '',
- bytes_downloaded INTEGER NOT NULL DEFAULT 0,
- total_bytes INTEGER NOT NULL DEFAULT 0,
- progress REAL NOT NULL DEFAULT 0,
- item_key TEXT NOT NULL DEFAULT '',
- item_dir TEXT NOT NULL DEFAULT '',
- files_json TEXT NOT NULL DEFAULT '[]',
- attempts_json TEXT NOT NULL DEFAULT '[]',
- created_at TEXT NOT NULL,
- updated_at TEXT NOT NULL
- );`,
- `CREATE TABLE IF NOT EXISTS task_attempts (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- task_id TEXT NOT NULL,
- attempt_time TEXT NOT NULL,
- file_path TEXT NOT NULL,
- offset_bytes INTEGER NOT NULL DEFAULT 0,
- host TEXT NOT NULL DEFAULT '',
- attempt_num INTEGER NOT NULL DEFAULT 1,
- error_kind TEXT NOT NULL DEFAULT '',
- http_status INTEGER NOT NULL DEFAULT 0
- );`,
- }
- for _, q := range baseTables {
- if _, err := tx.Exec(q); err != nil {
- return fmt.Errorf("library: migrate schema v2 base table: %w", err)
- }
- }
-
- for _, tbl := range []string{"library_items", "feed_items", "download_tasks"} {
- hasCol, err := tableHasColumnTx(tx, tbl, "author_uid")
- if err != nil {
- return err
- }
- if !hasCol {
- if _, err := tx.Exec(fmt.Sprintf(`ALTER TABLE %s ADD COLUMN author_uid TEXT NOT NULL DEFAULT ''`, tbl)); err != nil {
- return fmt.Errorf("library: add author_uid on %s: %w", tbl, err)
- }
- }
- if _, err := tx.Exec(fmt.Sprintf(`UPDATE %s SET author_uid = CASE WHEN mid > 0 THEN CAST(mid AS TEXT) ELSE '' END WHERE author_uid = ''`, tbl)); err != nil {
- return fmt.Errorf("library: backfill author_uid on %s: %w", tbl, err)
- }
- }
-
- indexes := []string{
- `CREATE INDEX IF NOT EXISTS idx_library_items_pub_ts ON library_items(pub_ts DESC);`,
- `CREATE INDEX IF NOT EXISTS idx_library_items_mid ON library_items(mid);`,
- `CREATE INDEX IF NOT EXISTS idx_library_items_site_author ON library_items(site, author_uid);`,
- `CREATE INDEX IF NOT EXISTS idx_library_items_via ON library_items(site, json_extract(json_data, '$.via.uid'));`,
- `CREATE INDEX IF NOT EXISTS idx_item_refs_to ON item_refs(to_key);`,
- `CREATE INDEX IF NOT EXISTS idx_feed_items_pub_ts ON feed_items(pub_ts DESC);`,
- `CREATE INDEX IF NOT EXISTS idx_feed_items_mid ON feed_items(mid);`,
- `CREATE INDEX IF NOT EXISTS idx_feed_items_site_author ON feed_items(site, author_uid);`,
- `CREATE INDEX IF NOT EXISTS idx_download_tasks_site_author ON download_tasks(site, author_uid);`,
- }
- for _, q := range indexes {
- if _, err := tx.Exec(q); err != nil {
- return fmt.Errorf("library: create schema v2 index: %w", err)
- }
- }
-
- migrateV2HookMu.Lock()
- hook := migrateV2Hook
- migrateV2HookMu.Unlock()
- if hook != nil {
- if err := hook(tx); err != nil {
- return err
- }
- }
-
- if _, err := tx.Exec(fmt.Sprintf(`PRAGMA user_version = %d`, CurrentSchemaVersion)); err != nil {
- return fmt.Errorf("library: stamp user_version %d: %w", CurrentSchemaVersion, err)
- }
- if err := tx.Commit(); err != nil {
- return fmt.Errorf("library: commit schema v2 migration: %w", err)
- }
- _, _ = s.db.Exec(`PRAGMA wal_checkpoint(PASSIVE)`)
- return nil
+// AllowMovedFiles reports whether remote/export allow-moved-files mode is active.
+func (s *Store) AllowMovedFiles() bool {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ return s.allowMovedFiles
}
-func tableHasColumnTx(tx *sql.Tx, table, column string) (bool, error) {
- rows, err := tx.Query(fmt.Sprintf(`PRAGMA table_info(%s)`, table))
- if err != nil {
- return false, err
- }
- defer rows.Close()
- for rows.Next() {
- var (
- cid int
- name, ctyp string
- notNull int
- dflt sql.NullString
- pk int
- )
- if err := rows.Scan(&cid, &name, &ctyp, ¬Null, &dflt, &pk); err != nil {
- return false, err
- }
- if strings.EqualFold(name, column) {
- return true, nil
- }
- }
- return false, rows.Err()
+// LibraryRoots returns all registered library root folders (active cacheDir first).
+func (s *Store) LibraryRoots() []string {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ return s.allRootsLocked()
}
func (s *Store) loadRootsLocked() error {
@@ -428,8 +131,12 @@ func (s *Store) loadRootsLocked() error {
s.extraRoots = nil
for _, r := range payload.Roots {
clean := filepath.Clean(strings.TrimSpace(r))
- if clean != "" && !seen[strings.ToLower(clean)] {
- seen[strings.ToLower(clean)] = true
+ if clean == "" || clean == "." {
+ continue
+ }
+ k := pathKey(clean)
+ if !seen[k] {
+ seen[k] = true
s.extraRoots = append(s.extraRoots, clean)
}
}
@@ -458,7 +165,7 @@ func (s *Store) allRootsLocked() []string {
if clean == "" || clean == "." {
return
}
- key := strings.ToLower(clean)
+ key := pathKey(clean)
if !seen[key] {
seen[key] = true
out = append(out, clean)
@@ -471,96 +178,6 @@ func (s *Store) allRootsLocked() []string {
return out
}
-type pendingDeleteRecord struct {
- ItemKey string `json:"itemKey"`
- ItemDir string `json:"itemDir"`
- RegisteredFiles []string `json:"registeredFiles"`
-}
-
-func (s *Store) readPendingDeletesLocked() ([]pendingDeleteRecord, error) {
- if s.pendingDeletesPath == "" {
- return nil, nil
- }
- raw, err := os.ReadFile(s.pendingDeletesPath)
- if err != nil {
- if os.IsNotExist(err) {
- return nil, nil
- }
- return nil, fmt.Errorf("library: 删除账本读取失败: %w", err)
- }
- var list []pendingDeleteRecord
- if err := json.Unmarshal(raw, &list); err != nil {
- // Keep the original ledger in place: treating it as empty could resurrect
- // files whose deletion was already committed before a crash.
- return nil, fmt.Errorf("library: 删除账本损坏,原文件已保留: %w", err)
- }
- return list, nil
-}
-
-func (s *Store) writePendingDeletesLocked(list []pendingDeleteRecord) error {
- if s.pendingDeletesPath == "" {
- return nil
- }
- if len(list) == 0 {
- err := os.Remove(s.pendingDeletesPath)
- if os.IsNotExist(err) {
- return nil
- }
- return err
- }
- return storage.WriteJSONAtomic(s.pendingDeletesPath, list, 0o600)
-}
-
-func (s *Store) cleanupPendingDeletesLocked() error {
- pending, err := s.readPendingDeletesLocked()
- if err != nil {
- return err
- }
- if len(pending) == 0 {
- return nil
- }
- var remaining []pendingDeleteRecord
- for _, rec := range pending {
- validRoot := false
- for _, root := range s.allRootsLocked() {
- if _, err := EnsureWithinRoot(root, rec.ItemDir); err == nil && !strings.EqualFold(root, rec.ItemDir) {
- validRoot = true
- break
- }
- }
- if !validRoot {
- remaining = append(remaining, rec)
- continue
- }
- var exists int
- if err := s.db.QueryRow(`SELECT COUNT(1) FROM library_items WHERE item_key = ?`, rec.ItemKey).Scan(&exists); err != nil {
- return err
- }
- if exists > 0 {
- // Re-cached since pending delete was recorded; skip cleanup.
- continue
- }
- allGone := true
- for _, f := range rec.RegisteredFiles {
- rel, err := filepath.Rel(rec.ItemDir, f)
- if err != nil || !safeRegisteredPath(rec.ItemDir, filepath.ToSlash(rel)) {
- allGone = false
- continue
- }
- if err := os.Remove(f); err != nil && !os.IsNotExist(err) {
- allGone = false
- }
- }
- if rec.ItemDir != "" {
- removeEmptyDirsBottomUp(rec.ItemDir)
- }
- if !allGone {
- remaining = append(remaining, rec)
- }
- }
- return s.writePendingDeletesLocked(remaining)
-}
-
// CacheDir returns the current root cache directory.
func (s *Store) CacheDir() string {
s.mu.RLock()
@@ -598,12 +215,19 @@ func (s *Store) saveItemLocked(itemDir string, meta ItemMetadata, checkHash ...b
}
meta.ItemDir = filepath.Clean(itemDir)
- missing, totalBytes := verifyItemFiles(meta.ItemDir, &meta, checkHash...)
- meta.TotalBytes = totalBytes
- if missing && meta.Status != "recording" && meta.Status != "failed" && meta.Status != "partial" {
- meta.Status = "missing_files"
- } else if meta.Status == "" || (meta.Status == "missing_files" && !missing) {
- meta.Status = "complete"
+ if s.allowMovedFiles {
+ meta.TotalBytes = sumItemBytesAllowMoved(meta.ItemDir, &meta)
+ if meta.Status == "" {
+ meta.Status = "complete"
+ }
+ } else {
+ missing, totalBytes := verifyItemFiles(meta.ItemDir, &meta, checkHash...)
+ meta.TotalBytes = totalBytes
+ if missing && meta.Status != "recording" && meta.Status != "failed" && meta.Status != "partial" {
+ meta.Status = "missing_files"
+ } else if meta.Status == "" || (meta.Status == "missing_files" && !missing) {
+ meta.Status = "complete"
+ }
}
itemJSONPath := filepath.Join(meta.ItemDir, "item.json")
@@ -615,6 +239,15 @@ func (s *Store) saveItemLocked(itemDir string, meta ItemMetadata, checkHash ...b
} else if !os.IsNotExist(err) {
return ItemMetadata{}, err
}
+ if meta.CachedBy == nil && s.node != nil {
+ n := *s.node
+ meta.CachedBy = &n
+ }
+ // The folder may have been emptied and removed by an upload (rclone
+ // move); the manifest is written into a new one (remote.md §6.1).
+ if err := os.MkdirAll(meta.ItemDir, 0o700); err != nil {
+ return ItemMetadata{}, err
+ }
if err := storage.WriteJSONAtomic(itemJSONPath, meta, 0o600); err != nil {
return ItemMetadata{}, err
}
@@ -622,683 +255,112 @@ func (s *Store) saveItemLocked(itemDir string, meta ItemMetadata, checkHash ...b
if err := s.upsertItemRowLocked(meta); err != nil {
return ItemMetadata{}, err
}
+ for _, fn := range s.onSaved {
+ fn(meta)
+ }
return meta, nil
}
-// RebuildIndex walks all registered library roots for item.json files, backs up corrupt files,
-// checks media file integrity (including hashes), and rebuilds the SQLite library_items index.
-func (s *Store) RebuildIndex() (RebuildReport, error) {
- return s.rebuildIndex(true)
-}
-
-// RefreshIndex is the media library's "刷新": the same scan as RebuildIndex,
-// but files are only checked for presence and size (no hashing), so it stays
-// quick on large libraries. The report lists what changed on disk.
-func (s *Store) RefreshIndex() (RebuildReport, error) {
- return s.rebuildIndex(false)
-}
-
-type indexedItem struct {
- site, kind, title, status, itemDir string
+// OnSaved registers fn to run after every manifest SaveItem (and recording
+// checkpoint) writes. fn runs with the store locked, so it must only hand
+// the item on (the uploader queues it) and never call back into the store.
+func (s *Store) OnSaved(fn func(ItemMetadata)) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.onSaved = append(s.onSaved, fn)
}
-func (s *Store) indexedItemsLocked() (map[string]indexedItem, error) {
- rows, err := s.db.Query(`SELECT item_key, site, kind, title, status, item_dir FROM library_items`)
+func (s *Store) upsertItemRowLocked(meta ItemMetadata) error {
+ tx, err := s.db.Begin()
if err != nil {
- return nil, err
+ return err
}
- defer rows.Close()
- out := make(map[string]indexedItem)
- for rows.Next() {
- var key string
- var it indexedItem
- if err := rows.Scan(&key, &it.site, &it.kind, &it.title, &it.status, &it.itemDir); err != nil {
- return nil, err
- }
- out[key] = it
+ defer tx.Rollback()
+ if err := upsertItemRowTx(tx, meta); err != nil {
+ return err
}
- return out, rows.Err()
+ return tx.Commit()
}
-func (s *Store) rebuildIndex(checkHash bool) (RebuildReport, error) {
- s.mu.Lock()
- defer s.mu.Unlock()
-
- var report RebuildReport
- previous, err := s.indexedItemsLocked()
+func upsertItemRowTx(tx *sql.Tx, meta ItemMetadata) error {
+ SanitizeItemMetadata(&meta)
+ jsonBytes, err := json.Marshal(meta)
if err != nil {
- return report, err
- }
- roots := s.allRootsLocked()
- if err := os.MkdirAll(s.cacheDir, 0o700); err != nil {
- return report, err
+ return err
}
- pendingMap := make(map[string]bool)
- pending, err := s.readPendingDeletesLocked()
- if err != nil {
- return report, err
- }
- for _, p := range pending {
- pendingMap[p.ItemKey] = true
+ summary := strings.TrimSpace(meta.Desc)
+ if summary == "" {
+ summary = strings.TrimSpace(meta.Text)
}
-
- seenKeys := make(map[string]bool)
- for _, root := range roots {
- if _, err := os.Stat(root); err != nil {
- return report, err
- }
- if err := rejectDirectoryLinks(root); err != nil {
- return report, err
+ coverPath := ""
+ for _, m := range meta.Media {
+ if m.Role == "cover" || m.Role == "image" {
+ coverPath = filepath.Join(meta.ItemDir, filepath.FromSlash(m.Path))
+ break
}
- err := filepath.WalkDir(root, func(path string, d fs.DirEntry, walkErr error) error {
- if walkErr != nil {
- return walkErr
- }
- if d.Type()&os.ModeSymlink != 0 {
- if d.IsDir() {
- return filepath.SkipDir
- }
- return nil
- }
- if d.IsDir() {
- return nil
- }
- if !strings.EqualFold(d.Name(), "item.json") {
- return nil
- }
- if report.Scanned >= 100000 {
- return fmt.Errorf("library: 清单扫描超过单轮上限,索引清理未执行")
- }
- report.Scanned++
-
- raw, rErr := os.ReadFile(path)
- if rErr != nil {
- return rErr
- }
- meta, pErr := ParseItemMetadata(raw)
- if pErr != nil {
- backup, bErr := storage.BackupCorruptFile(path)
- if bErr == nil && backup != "" {
- report.CorruptBackedUp = append(report.CorruptBackedUp, backup)
- }
- return bErr
- }
- if pendingMap[meta.ItemKey] || seenKeys[meta.ItemKey] {
- return nil
- }
-
- itemDir := filepath.Dir(path)
- if _, err := EnsureWithinRoot(root, itemDir); err != nil {
- return err
- }
- meta.ItemDir = filepath.Clean(itemDir)
- missing, totalBytes, missingPaths := verifyItemFilesDetail(meta.ItemDir, &meta, checkHash)
- meta.TotalBytes = totalBytes
- if missing && meta.Status != "recording" && meta.Status != "failed" && meta.Status != "partial" {
- if prev, ok := previous[meta.ItemKey]; ok && prev.status != "missing_files" {
- report.NewlyMissing = append(report.NewlyMissing, ChangedItem{ItemKey: meta.ItemKey, Site: meta.Site, Kind: meta.Kind, Title: meta.Title, ItemDir: meta.ItemDir, Files: missingPaths})
- }
- meta.Status = "missing_files"
- report.MissingFiles++
- if err := storage.WriteJSONAtomic(path, meta, 0o600); err != nil {
- return err
- }
- } else if meta.Status == "missing_files" && !missing {
- meta.Status = "complete"
- if err := storage.WriteJSONAtomic(path, meta, 0o600); err != nil {
- return err
- }
+ }
+ if coverPath == "" && len(meta.NotePages) > 0 {
+ for _, np := range meta.NotePages {
+ cand := np.Image
+ if cand == "" {
+ cand = np.Cover
}
-
- if err := s.upsertItemRowLocked(meta); err != nil {
- return err
+ if cand != "" {
+ coverPath = filepath.Join(meta.ItemDir, filepath.FromSlash(cand))
+ break
}
- seenKeys[meta.ItemKey] = true
- report.Indexed++
- return nil
- })
- if err != nil {
- return report, err
}
}
- rows, err := s.db.Query(`SELECT item_key FROM library_items`)
- if err != nil {
- return report, err
- }
- var stale []string
- for rows.Next() {
- var k string
- if err := rows.Scan(&k); err != nil {
- rows.Close()
- return report, err
- }
- if !seenKeys[k] {
- stale = append(stale, k)
- if prev, ok := previous[k]; ok && !pendingMap[k] {
- report.Removed = append(report.Removed, ChangedItem{ItemKey: k, Site: prev.site, Kind: prev.kind, Title: prev.title, ItemDir: prev.itemDir})
- }
- }
- }
- rowErr := rows.Err()
- if err := errors.Join(rowErr, rows.Close()); err != nil {
- return report, err
- }
- tx, err := s.db.Begin()
- if err != nil {
- return report, err
- }
- defer tx.Rollback()
- for _, k := range stale {
- if _, err := tx.Exec(`DELETE FROM library_items WHERE item_key = ?`, k); err != nil {
- return report, err
- }
- if _, err := tx.Exec(`DELETE FROM item_refs WHERE from_key = ? OR to_key = ?`, k, k); err != nil {
- return report, err
- }
- if _, err := tx.Exec(`UPDATE feed_items SET cached = 0, cache_status = '', item_key = '' WHERE item_key = ?`, k); err != nil {
- return report, err
- }
+ upAvail := 0
+ if meta.UpgradeAvailable {
+ upAvail = 1
}
- return report, tx.Commit()
-}
+ _, authorUID := NormalizeAuthorUID(meta.Site, meta.Author.UID, meta.Author.Mid)
-// AddLibraryRoot scans an existing cache folder (including bilibili/* and douyin/*/{works,lives}/*)
-// or legacy trace-data folder containing library/, and indexes its items without moving files
-// or overwriting existing keys (FR-LIB-006).
-func (s *Store) AddLibraryRoot(selectedDir string) (AddRootReport, error) {
- if strings.TrimSpace(selectedDir) == "" || !filepath.IsAbs(selectedDir) {
- return AddRootReport{}, fmt.Errorf("library: folder path cannot be empty")
- }
- selectedDir = filepath.Clean(selectedDir)
- info, err := os.Lstat(selectedDir)
+ _, err = tx.Exec(`
+ INSERT INTO library_items (
+ item_key, site, kind, raw_id, mid, author_uid, author_name, author_face,
+ title, summary, cover_path, canonical_url, pub_ts, cached_at,
+ status, item_dir, total_bytes, upgrade_available, upgrade_hint, json_data
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(item_key) DO UPDATE SET
+ mid = excluded.mid,
+ author_uid = excluded.author_uid,
+ author_name = excluded.author_name,
+ author_face = excluded.author_face,
+ title = excluded.title,
+ summary = excluded.summary,
+ cover_path = excluded.cover_path,
+ canonical_url = excluded.canonical_url,
+ pub_ts = excluded.pub_ts,
+ cached_at = excluded.cached_at,
+ status = excluded.status,
+ item_dir = excluded.item_dir,
+ total_bytes = excluded.total_bytes,
+ upgrade_available = excluded.upgrade_available,
+ upgrade_hint = excluded.upgrade_hint,
+ json_data = excluded.json_data
+ `,
+ meta.ItemKey, meta.Site, meta.Kind, meta.RawID,
+ meta.Author.Mid, authorUID, meta.Author.Name, meta.Author.Face,
+ meta.Title, summary, coverPath, meta.URL, meta.PubTs, meta.CachedAt,
+ meta.Status, meta.ItemDir, meta.TotalBytes, upAvail, meta.UpgradeHint, string(jsonBytes),
+ )
if err != nil {
- return AddRootReport{}, fmt.Errorf("library: stat folder: %w", err)
- }
- if info.Mode()&os.ModeSymlink != 0 {
- return AddRootReport{}, fmt.Errorf("library: symlink root folder is not allowed")
- }
- if !info.IsDir() {
- return AddRootReport{}, fmt.Errorf("library: %s is not a directory", selectedDir)
+ return err
}
- // Check if selectedDir is a legacy portable trace-data directory containing a library/ subdirectory (even without settings.json!).
- scanRoot := selectedDir
- libSub := filepath.Join(selectedDir, "library")
- if lInfo, lErr := os.Lstat(libSub); lErr == nil && lInfo.IsDir() && lInfo.Mode()&os.ModeSymlink == 0 {
- scanRoot = libSub
- } else {
- // Also check optional settings.json inside selectedDir.
- setBytes, sErr := os.ReadFile(filepath.Join(selectedDir, "settings.json"))
- if sErr == nil {
- var cfg struct {
- CacheRoot string `json:"cacheRoot"`
- CacheDir string `json:"cacheDir"`
- }
- if json.Unmarshal(setBytes, &cfg) == nil {
- cand := strings.TrimSpace(cfg.CacheRoot)
- if cand == "" {
- cand = strings.TrimSpace(cfg.CacheDir)
- }
- if cand != "" {
- if !filepath.IsAbs(cand) {
- cand = filepath.Join(selectedDir, cand)
- }
- if cInfo, cErr := os.Lstat(cand); cErr == nil && cInfo.IsDir() && cInfo.Mode()&os.ModeSymlink == 0 {
- scanRoot = filepath.Clean(cand)
- }
- }
- }
- }
- }
-
- s.mu.Lock()
- defer s.mu.Unlock()
-
- report := AddRootReport{Root: scanRoot}
- if err := rejectDirectoryLinks(scanRoot); err != nil {
- return report, err
- }
- oldRoots := append([]string(nil), s.extraRoots...)
- found := false
- for _, r := range s.allRootsLocked() {
- found = found || strings.EqualFold(r, scanRoot)
- }
- if !found {
- s.extraRoots = append(s.extraRoots, scanRoot)
- }
- // Register the recovery root before importing any index rows. A failed
- // ledger write must not leave rows whose source disappears after restart.
- if err := s.saveRootsLocked(); err != nil {
- s.extraRoots = oldRoots
- return report, err
- }
- err = filepath.WalkDir(scanRoot, func(path string, d fs.DirEntry, walkErr error) error {
- if walkErr != nil {
- return walkErr
- }
- // Never follow symlinks or junctions (INV-08).
- if d.Type()&os.ModeSymlink != 0 {
- if d.IsDir() {
- return filepath.SkipDir
- }
- return nil
- }
- if d.IsDir() {
- return nil
- }
- if !strings.EqualFold(d.Name(), "item.json") {
- return nil
- }
- if report.Scanned >= 100000 {
- return fmt.Errorf("library: 清单扫描超过单轮上限")
- }
- report.Scanned++
-
- raw, rErr := os.ReadFile(path)
- if rErr != nil {
- return rErr
- }
- meta, pErr := ParseItemMetadata(raw)
- if pErr != nil {
- return nil
- }
-
- // If itemKey already exists in index, keep existing item and count as Skipped.
- var existingCount int
- if err := s.db.QueryRow(`SELECT COUNT(1) FROM library_items WHERE item_key = ?`, meta.ItemKey).Scan(&existingCount); err != nil {
- return err
- }
- if existingCount > 0 {
- report.Skipped++
- return nil
- }
-
- itemDir := filepath.Dir(path)
- if _, err := EnsureWithinRoot(scanRoot, itemDir); err != nil {
- return err
- }
- meta.ItemDir = filepath.Clean(itemDir)
- missing, totalBytes := verifyItemFiles(meta.ItemDir, &meta)
- meta.TotalBytes = totalBytes
- if missing && meta.Status != "recording" && meta.Status != "failed" && meta.Status != "partial" {
- meta.Status = "missing_files"
- }
- if uErr := s.upsertItemRowLocked(meta); uErr != nil {
- return uErr
- }
- report.Added++
- return nil
- })
- return report, err
-}
-
-// MediaPath resolves and validates a whitelisted media file path belonging to key (INV-08).
-// It rejects '.', '..', backslashes, colons, null bytes, unregistered filenames, and symlinks/junctions.
-func (s *Store) MediaPath(key, relPath string) (string, error) {
- relPath = strings.TrimSpace(relPath)
- if relPath == "" {
- return "", fmt.Errorf("library: empty relative media path")
- }
- if strings.ContainsRune(relPath, 0) || strings.ContainsRune(relPath, '\\') || strings.ContainsRune(relPath, ':') {
- return "", fmt.Errorf("library: forbidden characters in media path")
- }
- if filepath.IsAbs(relPath) || strings.HasPrefix(relPath, "/") {
- return "", fmt.Errorf("library: media path must be relative")
- }
- segments := strings.Split(relPath, "/")
- for _, seg := range segments {
- if seg == "" || seg == "." || seg == ".." {
- return "", fmt.Errorf("library: invalid segment %q in media path", seg)
- }
- }
-
- meta, ok, err := s.GetItem(key)
- if err != nil {
- return "", err
- }
- if !ok || meta.ItemDir == "" {
- return "", fmt.Errorf("library: item %q not found", key)
- }
-
- normRel := filepath.ToSlash(filepath.Clean(filepath.FromSlash(relPath)))
- if !isRegisteredInManifest(meta, normRel) {
- return "", fmt.Errorf("library: file %q is not registered in item %q manifest", relPath, key)
- }
-
- fullPath, err := EnsureWithinRoot(meta.ItemDir, filepath.Join(meta.ItemDir, filepath.FromSlash(normRel)))
- if err != nil {
- return "", err
- }
-
- if !safeRegisteredPath(meta.ItemDir, relPath) {
- return "", fmt.Errorf("library: media path contains a link or invalid segment")
- }
-
- // Check Lstat on every segment from meta.ItemDir to fullPath and EvalSymlinks to reject symlinks/junctions.
- dirInfo, err := os.Lstat(meta.ItemDir)
- if err != nil {
- return "", err
- }
- if isLinkLike(dirInfo.Mode()) {
- return "", fmt.Errorf("library: item directory is a symlink")
- }
- fileInfo, err := os.Lstat(fullPath)
- if err != nil {
- return "", err
- }
- if isLinkLike(fileInfo.Mode()) || fileInfo.IsDir() {
- return "", fmt.Errorf("library: media target is a symlink or directory")
- }
-
- evalRoot, err1 := filepath.EvalSymlinks(meta.ItemDir)
- evalTarget, err2 := filepath.EvalSymlinks(fullPath)
- if err1 != nil || err2 != nil {
- return "", fmt.Errorf("library: symlink evaluation failed")
- }
- if _, err := EnsureWithinRoot(evalRoot, evalTarget); err != nil {
- return "", fmt.Errorf("library: symlink target escapes item directory")
- }
- return fullPath, nil
-}
-
-func cleanManifestRel(p string) string {
- p = strings.TrimSpace(p)
- if p == "" {
- return ""
- }
- return filepath.ToSlash(filepath.Clean(filepath.FromSlash(p)))
-}
-
-func isRegisteredInManifest(meta ItemMetadata, normRel string) bool {
- if normRel == "" {
- return false
- }
- for _, m := range meta.Media {
- if cleanManifestRel(m.Path) == normRel || cleanManifestRel(m.Motion) == normRel {
- return true
- }
- }
- for _, p := range meta.Parts {
- if cleanManifestRel(p.File) == normRel ||
- cleanManifestRel(p.Danmaku) == normRel ||
- cleanManifestRel(p.Audio.SavedAs) == normRel {
- return true
- }
- for _, sub := range p.Subtitles {
- if cleanManifestRel(sub) == normRel {
- return true
- }
- }
- }
- if meta.DouyinVideo != nil && cleanManifestRel(meta.DouyinVideo.File) == normRel {
- return true
- }
- for _, np := range meta.NotePages {
- if cleanManifestRel(np.Image) == normRel ||
- cleanManifestRel(np.Cover) == normRel ||
- cleanManifestRel(np.Motion) == normRel ||
- cleanManifestRel(np.Video) == normRel {
- return true
- }
- if np.VideoInfo != nil && cleanManifestRel(np.VideoInfo.File) == normRel {
- return true
- }
- }
- if meta.Music != nil {
- if cleanManifestRel(meta.Music.File) == normRel || cleanManifestRel(meta.Music.Cover) == normRel {
- return true
- }
- }
- if meta.Live != nil {
- for _, seg := range meta.Live.Segments {
- if cleanManifestRel(seg.File) == normRel {
- return true
- }
- }
- }
- return false
-}
-
-func verifyItemFiles(itemDir string, meta *ItemMetadata, checkHash ...bool) (missing bool, totalBytes int64) {
- missing, totalBytes, _ = verifyItemFilesDetail(itemDir, meta, len(checkHash) == 0 || checkHash[0])
- return missing, totalBytes
-}
-
-// verifyItemFilesDetail is verifyItemFiles that also returns the manifest
-// paths that are missing, empty or no longer match the recorded size/hash.
-func verifyItemFilesDetail(itemDir string, meta *ItemMetadata, hash bool) (missing bool, totalBytes int64, missingPaths []string) {
- checkHash := []bool{hash}
- checkedPaths := make(map[string]bool)
- noted := make(map[string]bool)
- note := func(rel string) {
- if rel = cleanManifestRel(strings.TrimSpace(rel)); rel != "" && !noted[rel] {
- noted[rel] = true
- missingPaths = append(missingPaths, rel)
- }
- }
-
- checkRel := func(rel string) bool {
- rel = strings.TrimSpace(rel)
- if rel == "" {
- return true
- }
- full, err := ResolveItemPath(itemDir, rel)
- if err != nil {
- note(rel)
- return false
- }
- info, err := os.Lstat(full)
- if err != nil || info.IsDir() || info.Size() == 0 {
- note(rel)
- return false
- }
- norm := cleanManifestRel(rel)
- if !checkedPaths[norm] {
- checkedPaths[norm] = true
- totalBytes += info.Size()
- }
- return true
- }
-
- for i := range meta.Media {
- rel := meta.Media[i].Path
- if !checkRel(rel) {
- missing = true
- } else if full, err := ResolveItemPath(itemDir, rel); err == nil {
- info, err := os.Lstat(full)
- if err != nil {
- missing = true
- continue
- }
- if meta.Media[i].Bytes > 0 && meta.Media[i].Bytes != info.Size() {
- missing = true
- note(rel)
- } else if meta.Media[i].Bytes == 0 {
- meta.Media[i].Bytes = info.Size()
- }
- if meta.Media[i].SHA256 != "" && (len(checkHash) == 0 || checkHash[0]) {
- if !VerifyMediaFile(itemDir, meta.Media[i], true) {
- missing = true
- note(rel)
- }
- }
- }
- if meta.Media[i].Motion != "" && !checkRel(meta.Media[i].Motion) {
- missing = true
- }
- }
-
- for _, part := range meta.Parts {
- if part.File != "" && !checkRel(part.File) {
- missing = true
- }
- if part.Danmaku != "" && !checkRel(part.Danmaku) {
- missing = true
- }
- if part.Audio.SavedAs != "" && !checkRel(part.Audio.SavedAs) {
- missing = true
- }
- for _, sub := range part.Subtitles {
- if sub != "" && !checkRel(sub) {
- missing = true
- }
- }
- }
-
- if meta.DouyinVideo != nil && meta.DouyinVideo.File != "" && !checkRel(meta.DouyinVideo.File) {
- missing = true
- }
-
- for _, np := range meta.NotePages {
- for _, rel := range []string{np.Image, np.Cover, np.Motion, np.Video} {
- if rel != "" && !checkRel(rel) {
- missing = true
- }
- }
- if np.VideoInfo != nil && np.VideoInfo.File != "" && !checkRel(np.VideoInfo.File) {
- missing = true
- }
- }
-
- if meta.Music != nil {
- if meta.Music.File != "" && !checkRel(meta.Music.File) {
- missing = true
- }
- if meta.Music.Cover != "" && !checkRel(meta.Music.Cover) {
- missing = true
- }
- }
-
- if meta.Live != nil {
- for _, seg := range meta.Live.Segments {
- if seg.File != "" && !checkRel(seg.File) {
- missing = true
- }
- }
- }
-
- hasStructuredMedia := len(meta.Media) > 0 || len(meta.Parts) > 0 ||
- (meta.DouyinVideo != nil && meta.DouyinVideo.File != "") ||
- len(meta.NotePages) > 0 ||
- (meta.Music != nil && meta.Music.File != "") ||
- (meta.Live != nil && len(meta.Live.Segments) > 0)
- if !hasStructuredMedia && meta.Kind != "dynamic" && meta.Status != "partial" && meta.Status != "recording" {
- missing = true
- }
- return missing, totalBytes, missingPaths
-}
-
-// VerifyMediaFile checks a registered file without rewriting its expected size.
-func VerifyMediaFile(itemDir string, file MediaFile, checkHash bool) bool {
- full, err := ResolveItemPath(itemDir, file.Path)
- if err != nil {
- return false
- }
- info, err := os.Lstat(full)
- if err != nil || !info.Mode().IsRegular() || info.Size() <= 0 || file.Bytes > 0 && info.Size() != file.Bytes {
- return false
- }
- if !checkHash || file.SHA256 == "" {
- return true
- }
- f, err := os.Open(full)
- if err != nil {
- return false
- }
- defer f.Close()
- h := sha256.New()
- if _, err := io.Copy(h, f); err != nil {
- return false
- }
- return strings.EqualFold(hex.EncodeToString(h.Sum(nil)), file.SHA256)
-}
-
-func (s *Store) upsertItemRowLocked(meta ItemMetadata) error {
- SanitizeItemMetadata(&meta)
- jsonBytes, err := json.Marshal(meta)
- if err != nil {
- return err
- }
-
- summary := strings.TrimSpace(meta.Desc)
- if summary == "" {
- summary = strings.TrimSpace(meta.Text)
- }
- coverPath := ""
- for _, m := range meta.Media {
- if m.Role == "cover" || m.Role == "image" {
- coverPath = filepath.Join(meta.ItemDir, filepath.FromSlash(m.Path))
- break
- }
- }
- if coverPath == "" && len(meta.NotePages) > 0 {
- for _, np := range meta.NotePages {
- cand := np.Image
- if cand == "" {
- cand = np.Cover
- }
- if cand != "" {
- coverPath = filepath.Join(meta.ItemDir, filepath.FromSlash(cand))
- break
- }
- }
- }
-
- upAvail := 0
- if meta.UpgradeAvailable {
- upAvail = 1
- }
- _, authorUID := NormalizeAuthorUID(meta.Site, meta.Author.UID, meta.Author.Mid)
-
- tx, err := s.db.Begin()
- if err != nil {
- return err
- }
- defer tx.Rollback()
- _, err = tx.Exec(`
- INSERT INTO library_items (
- item_key, site, kind, raw_id, mid, author_uid, author_name, author_face,
- title, summary, cover_path, canonical_url, pub_ts, cached_at,
- status, item_dir, total_bytes, upgrade_available, upgrade_hint, json_data
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- ON CONFLICT(item_key) DO UPDATE SET
- mid = excluded.mid,
- author_uid = excluded.author_uid,
- author_name = excluded.author_name,
- author_face = excluded.author_face,
- title = excluded.title,
- summary = excluded.summary,
- cover_path = excluded.cover_path,
- canonical_url = excluded.canonical_url,
- pub_ts = excluded.pub_ts,
- cached_at = excluded.cached_at,
- status = excluded.status,
- item_dir = excluded.item_dir,
- total_bytes = excluded.total_bytes,
- upgrade_available = excluded.upgrade_available,
- upgrade_hint = excluded.upgrade_hint,
- json_data = excluded.json_data
- `,
- meta.ItemKey, meta.Site, meta.Kind, meta.RawID,
- meta.Author.Mid, authorUID, meta.Author.Name, meta.Author.Face,
- meta.Title, summary, coverPath, meta.URL, meta.PubTs, meta.CachedAt,
- meta.Status, meta.ItemDir, meta.TotalBytes, upAvail, meta.UpgradeHint, string(jsonBytes),
- )
- if err != nil {
- return err
- }
-
- // Update item_refs for dynamic -> video references.
- if _, err := tx.Exec(`DELETE FROM item_refs WHERE from_key = ?`, meta.ItemKey); err != nil {
- return err
- }
- if meta.Kind == "dynamic" {
- for _, vid := range meta.Videos {
- vidKey := CanonicalItemKey(meta.Site, "video", vid)
- if _, err := tx.Exec(`INSERT OR IGNORE INTO item_refs (from_key, to_key) VALUES (?, ?)`, meta.ItemKey, vidKey); err != nil {
- return err
+ // Update item_refs for dynamic -> video references.
+ if _, err := tx.Exec(`DELETE FROM item_refs WHERE from_key = ?`, meta.ItemKey); err != nil {
+ return err
+ }
+ if meta.Kind == "dynamic" {
+ for _, vid := range meta.Videos {
+ vidKey := CanonicalItemKey(meta.Site, "video", vid)
+ if _, err := tx.Exec(`INSERT OR IGNORE INTO item_refs (from_key, to_key) VALUES (?, ?)`, meta.ItemKey, vidKey); err != nil {
+ return err
}
}
}
@@ -1324,10 +386,7 @@ func (s *Store) upsertItemRowLocked(meta ItemMetadata) error {
meta.Title, summary, coverPath, meta.URL, meta.PubTs, meta.CachedAt,
meta.Status, meta.ItemKey,
)
- if err != nil {
- return err
- }
- return tx.Commit()
+ return err
}
// UpsertFeedEntry inserts or updates an online-discovered item in the unified feed without overwriting existing cache linkage.
@@ -1408,8 +467,16 @@ func (s *Store) UpsertFeedEntry(entry FeedEntry) error {
// GetItem retrieves a single cached ItemMetadata by canonical itemKey ("::"), short key (":"), or rawID.
func (s *Store) GetItem(keyOrID string) (ItemMetadata, bool, error) {
s.mu.RLock()
- defer s.mu.RUnlock()
- return s.getItemLocked(keyOrID)
+ allowMoved := s.allowMovedFiles
+ meta, ok, err := s.getItemLocked(keyOrID)
+ s.mu.RUnlock()
+ if err != nil || !ok {
+ return meta, ok, err
+ }
+ if !allowMoved {
+ refreshItemFileState(&meta)
+ }
+ return meta, true, nil
}
func (s *Store) getItemLocked(keyOrID string) (ItemMetadata, bool, error) {
@@ -1423,15 +490,15 @@ func (s *Store) getItemLocked(keyOrID string) (ItemMetadata, bool, error) {
var upHint string
var err error
- switch strings.Count(keyOrID, ":") {
- case 0:
+ switch {
+ case strings.Count(keyOrID, ":") == 0:
err = s.db.QueryRow(`
SELECT json_data, item_dir, status, total_bytes, upgrade_available, upgrade_hint
FROM library_items
WHERE item_key = ? OR raw_id = ?
LIMIT 1
`, keyOrID, keyOrID).Scan(&jsonStr, &itemDir, &status, &totalBytes, &upAvail, &upHint)
- case 1:
+ case strings.Count(keyOrID, ":") == 1 || strings.HasPrefix(strings.ToLower(keyOrID), "live:"):
err = s.db.QueryRow(`
SELECT json_data, item_dir, status, total_bytes, upgrade_available, upgrade_hint
FROM library_items
@@ -1466,7 +533,6 @@ func (s *Store) getItemLocked(keyOrID string) (ItemMetadata, bool, error) {
meta.TotalBytes = totalBytes
meta.UpgradeAvailable = upAvail == 1
meta.UpgradeHint = upHint
- refreshItemFileState(&meta)
return meta, true, nil
}
@@ -1477,859 +543,191 @@ func refreshItemFileState(meta *ItemMetadata) {
}
}
-// States computes batch DotState for the given item keys (FR-CACHE-004).
-func (s *Store) States(keys []string) map[string]DotState {
- s.mu.RLock()
- defer s.mu.RUnlock()
-
- out := make(map[string]DotState, len(keys))
- for _, k := range keys {
- meta, ok, err := s.getItemLocked(k)
- if err != nil || !ok {
- out[k] = DotState{Key: k, Dot: "none", Label: "未缓存"}
- continue
- }
- dot := ComputeDotState(meta)
- if meta.Kind == "dynamic" && len(meta.Videos) > 0 {
- for _, vid := range meta.Videos {
- vMeta, vOk, _ := s.getItemLocked(CanonicalItemKey(meta.Site, "video", vid))
- if !vOk {
- dot.Dot = "red"
- dot.Label = "引用视频缺失"
- break
+func (s *Store) fetchItemsBatchLocked(itemKeys, rawIDs []string, byKey, byRaw map[string]ItemMetadata) {
+ const chunkSize = 400
+ queryChunk := func(col string, vals []string) {
+ for start := 0; start < len(vals); start += chunkSize {
+ end := min(start+chunkSize, len(vals))
+ chunk := vals[start:end]
+ ph := strings.TrimSuffix(strings.Repeat("?,", len(chunk)), ",")
+ args := make([]any, len(chunk))
+ for i, v := range chunk {
+ args[i] = v
+ }
+ rows, err := s.db.Query(`SELECT item_key, raw_id, json_data, item_dir, status, total_bytes, upgrade_available, upgrade_hint FROM library_items WHERE `+col+` IN (`+ph+`)`, args...)
+ if err != nil {
+ continue
+ }
+ for rows.Next() {
+ var itemKey, rawID, jsonStr, itemDir, status, upHint string
+ var totalBytes int64
+ var upAvail int
+ if err := rows.Scan(&itemKey, &rawID, &jsonStr, &itemDir, &status, &totalBytes, &upAvail, &upHint); err != nil {
+ continue
}
- vDot := ComputeDotState(vMeta)
- if vDot.Dot == "red" {
- dot.Dot = "red"
- dot.Label = vDot.Label
- break
+ meta, err := ParseItemMetadata([]byte(jsonStr))
+ if err != nil {
+ continue
}
- if vDot.Dot == "yellow" && dot.Dot == "green" {
- dot.Dot = "yellow"
- dot.Label = vDot.Label
+ meta.ItemDir = itemDir
+ meta.Status = status
+ meta.TotalBytes = totalBytes
+ meta.UpgradeAvailable = upAvail == 1
+ meta.UpgradeHint = upHint
+ byKey[itemKey] = meta
+ if _, exists := byRaw[rawID]; !exists {
+ byRaw[rawID] = meta
}
}
+ _ = rows.Close()
}
- dot.Key = k
- out[k] = dot
- }
- return out
-}
-
-// forwardContentSQL matches library_items rows that are forwarded posts or
-// content cached because of one (media library "转发", DEC-056).
-const forwardContentSQL = "(json_extract(json_data, '$.via.reason') = 'forward' OR (kind = 'dynamic' AND json_extract(json_data, '$.dynamicType') = 'DYNAMIC_TYPE_FORWARD'))"
-
-// viaUIDSQL is the indexed expression for the creator an item was cached for
-// (idx_library_items_via).
-const viaUIDSQL = "json_extract(json_data, '$.via.uid')"
-
-// appendLibrarySiteAndAuthorClauses is appendSiteAndAuthorClauses for
-// library_items: an author filter also matches items cached for that creator
-// under their folder (collaboration videos and forwarded content, DEC-056).
-func appendLibrarySiteAndAuthorClauses(clauses []string, args []any, siteFilter string, mid int64, authorUID string, mids []int64, refs []AuthorRef) ([]string, []any) {
- return appendSiteAndAuthorClausesVia(clauses, args, "", siteFilter, mid, authorUID, mids, refs, true)
-}
-
-// appendSiteAndAuthorClauses is the author filter for feed_items (colPrefix
-// "f."): an author's feed also has the collaboration videos cached for them
-// under their folder, though the uploader is someone else (DEC-061).
-func appendSiteAndAuthorClauses(clauses []string, args []any, colPrefix, siteFilter string, mid int64, authorUID string, mids []int64, refs []AuthorRef) ([]string, []any) {
- return appendSiteAndAuthorClausesVia(clauses, args, colPrefix, siteFilter, mid, authorUID, mids, refs, false)
-}
-
-// collabItemKeysSQL selects the item keys of collaboration videos cached for
-// one of a site's creators; the site and creator placeholders follow.
-func collabItemKeysSQL(n int) string {
- ph := strings.TrimSuffix(strings.Repeat("?,", n), ",")
- return "(SELECT item_key FROM library_items WHERE site = ? AND " + viaUIDSQL + " IN (" + ph + ") AND json_extract(json_data, '$.via.reason') = '" + ViaCollab + "')"
-}
-
-func appendSiteAndAuthorClausesVia(clauses []string, args []any, colPrefix, siteFilter string, mid int64, authorUID string, mids []int64, refs []AuthorRef, withVia bool) ([]string, []any) {
- normSiteFilter := strings.ToLower(strings.TrimSpace(siteFilter))
- if normSiteFilter != "" && normSiteFilter != "all" {
- clauses = append(clauses, colPrefix+"site = ?")
- args = append(args, normSiteFilter)
}
-
- var collected []AuthorRef
- seen := make(map[string]bool)
- addRef := func(site, uid string) {
- uid = strings.TrimSpace(uid)
- if uid == "" {
- return
- }
- site = strings.ToLower(strings.TrimSpace(site))
- if site == "" {
- if normSiteFilter != "" && normSiteFilter != "all" {
- site = normSiteFilter
- } else {
- site = "bilibili"
- }
- }
- k := site + "\x00" + uid
- if !seen[k] {
- seen[k] = true
- collected = append(collected, AuthorRef{Site: site, UID: uid})
- }
+ if len(itemKeys) > 0 {
+ queryChunk("item_key", itemKeys)
}
- if mid > 0 {
- addRef("bilibili", strconv.FormatInt(mid, 10))
+ if len(rawIDs) > 0 {
+ queryChunk("raw_id", rawIDs)
}
- if strings.TrimSpace(authorUID) != "" {
- addRef("", authorUID)
- }
- for _, m := range mids {
- if m > 0 {
- addRef("bilibili", strconv.FormatInt(m, 10))
- }
- }
- for _, r := range refs {
- addRef(r.Site, r.UID)
- }
- if len(collected) == 0 {
- return clauses, args
- }
-
- bySite := make(map[string][]string)
- var siteOrder []string
- for _, r := range collected {
- if _, ok := bySite[r.Site]; !ok {
- siteOrder = append(siteOrder, r.Site)
- }
- bySite[r.Site] = append(bySite[r.Site], r.UID)
- }
- var orParts []string
- for _, st := range siteOrder {
- uids := bySite[st]
- cols := []string{colPrefix + "author_uid"}
- if withVia {
- cols = append(cols, viaUIDSQL)
- }
- for _, col := range cols {
- if len(uids) == 1 {
- orParts = append(orParts, "("+colPrefix+"site = ? AND "+col+" = ?)")
- args = append(args, st, uids[0])
- } else {
- ph := make([]string, len(uids))
- args = append(args, st)
- for i, u := range uids {
- ph[i] = "?"
- args = append(args, u)
- }
- orParts = append(orParts, "("+colPrefix+"site = ? AND "+col+" IN ("+strings.Join(ph, ",")+"))")
- }
- }
- if !withVia && colPrefix != "" {
- orParts = append(orParts, "("+colPrefix+"item_key IN "+collabItemKeysSQL(len(uids))+")")
- args = append(args, st)
- for _, u := range uids {
- args = append(args, u)
- }
- }
- }
- if len(orParts) == 1 {
- clauses = append(clauses, orParts[0])
- } else {
- clauses = append(clauses, "("+strings.Join(orParts, " OR ")+")")
- }
- return clauses, args
}
-// ListItems returns cached library items matching filter.
-func (s *Store) ListItems(filter FeedFilter) ([]ItemMetadata, error) {
- s.mu.RLock()
- defer s.mu.RUnlock()
-
- var clauses []string
- var args []any
- switch filter.Kind {
- case "image":
- clauses = append(clauses, "(EXISTS (SELECT 1 FROM json_each(json_data, '$.media') WHERE json_extract(value, '$.role') = 'image') OR EXISTS (SELECT 1 FROM json_each(json_data, '$.notePages') WHERE json_extract(value, '$.kind') IN ('image', 'motion')))")
- if filter.ExcludeForward {
- clauses = append(clauses, "NOT "+forwardContentSQL)
- }
- case "forward":
- clauses = append(clauses, forwardContentSQL)
- case "", "all":
- default:
- clauses = append(clauses, "kind = ?")
- args = append(args, filter.Kind)
- if filter.ExcludeForward {
- clauses = append(clauses, "NOT "+forwardContentSQL)
- }
- }
- clauses, args = appendLibrarySiteAndAuthorClauses(clauses, args, filter.Site, filter.Mid, filter.AuthorUID, filter.Authors, filter.AuthorRefs)
- if kw := strings.TrimSpace(filter.Keyword); kw != "" {
- clauses = append(clauses, "(title LIKE ? OR summary LIKE ? OR author_name LIKE ? OR raw_id LIKE ?)")
- pat := "%" + kw + "%"
- args = append(args, pat, pat, pat, pat)
- }
-
- query := `SELECT json_data, item_dir, status, total_bytes, upgrade_available, upgrade_hint FROM library_items`
- if len(clauses) > 0 {
- query += " WHERE " + strings.Join(clauses, " AND ")
- }
- if strings.EqualFold(filter.Sort, "cached_at") {
- query += " ORDER BY cached_at DESC, item_key DESC"
- } else if strings.EqualFold(filter.Sort, "oldest") {
- query += " ORDER BY pub_ts ASC, item_key ASC"
- } else {
- query += " ORDER BY pub_ts DESC, item_key DESC"
- }
- limit := filter.Limit
- if limit <= 0 {
- limit = 200
- }
- query += fmt.Sprintf(" LIMIT %d OFFSET %d", limit, max(0, filter.Offset))
-
- rows, err := s.db.Query(query, args...)
- if err != nil {
- return nil, err
+// States computes batch DotState for the given item keys (FR-CACHE-004).
+func (s *Store) States(keys []string) map[string]DotState {
+ out := make(map[string]DotState, len(keys))
+ if len(keys) == 0 {
+ return out
}
- defer 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
+ seenKey := make(map[string]bool, len(keys))
+ seenRaw := make(map[string]bool)
+ var itemKeys, rawIDs []string
+ addKey := func(k string) {
+ if k != "" && !seenKey[k] {
+ seenKey[k] = true
+ itemKeys = append(itemKeys, k)
}
- 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
- refreshItemFileState(&meta)
- out = append(out, meta)
}
- return out, rows.Err()
-}
-
-// 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) {
- if req.Direction == "around" && req.Cursor != nil {
- pivot, err := s.feedAnchorCursor(req)
- if err != nil || pivot == nil {
- return FeedPageResult{}, err
- }
- beforeReq := req
- beforeReq.Cursor = pivot
- beforeReq.Order = "newest"
- beforeReq.Direction = "newer"
- beforeReq.Limit = 30
- before, err := s.FeedPage(beforeReq)
- if err != nil {
- return FeedPageResult{}, err
- }
- afterReq := beforeReq
- afterReq.Direction = "older"
- cursor := *pivot
- cursor.Key += "\x00"
- afterReq.Cursor = &cursor
- after, err := s.FeedPage(afterReq)
- if err != nil {
- return FeedPageResult{}, err
+ for _, raw := range keys {
+ k := strings.TrimSpace(raw)
+ if k == "" {
+ continue
}
- result := after
- result.Items = append(before.Items, after.Items...)
- if req.Order == "oldest" {
- for i, j := 0, len(result.Items)-1; i < j; i, j = i+1, j-1 {
- result.Items[i], result.Items[j] = result.Items[j], result.Items[i]
+ switch {
+ case strings.Count(k, ":") == 0:
+ addKey(k)
+ if !seenRaw[k] {
+ seenRaw[k] = true
+ rawIDs = append(rawIDs, k)
+ }
+ case strings.Count(k, ":") == 1 || strings.HasPrefix(strings.ToLower(k), "live:"):
+ addKey(k)
+ addKey("bilibili:" + k)
+ default:
+ if strings.HasPrefix(strings.ToLower(k), "douyin:note:") {
+ addKey("douyin:dynamic:" + k[len("douyin:note:"):])
+ } else {
+ addKey(k)
}
}
- if len(result.Items) > 0 {
- first, last := result.Items[0], result.Items[len(result.Items)-1]
- result.PrevCursor = &FeedCursor{PubTs: first.PubTs, Key: first.FeedKey}
- result.NextCursor = &FeedCursor{PubTs: last.PubTs, Key: last.FeedKey}
- }
- return result, nil
}
- s.mu.RLock()
- defer s.mu.RUnlock()
+ byKey := make(map[string]ItemMetadata, len(itemKeys))
+ byRaw := make(map[string]ItemMetadata, len(rawIDs))
- order := strings.ToLower(strings.TrimSpace(req.Order))
- if order != "oldest" {
- order = "newest"
- }
- dir := strings.ToLower(strings.TrimSpace(req.Direction))
- if dir != "newer" {
- dir = "older"
- }
- limit := req.Limit
- if limit <= 0 {
- limit = 30
- }
-
- clauses, args := feedPageClauses(req)
-
- // Determine SQL comparison and sort order for keyset cursor (pub_ts, feed_key).
- // For "newest" (DESC):
- // - direction="older": (pub_ts < c.PubTs OR (pub_ts = c.PubTs AND feed_key < c.Key)) ORDER BY pub_ts DESC, feed_key DESC
- // - direction="newer": (pub_ts > c.PubTs OR (pub_ts = c.PubTs AND feed_key > c.Key)) ORDER BY pub_ts ASC, feed_key ASC (then reverse)
- // For "oldest" (ASC):
- // - direction="older": (pub_ts > c.PubTs OR (pub_ts = c.PubTs AND feed_key > c.Key)) ORDER BY pub_ts ASC, feed_key ASC
- // - direction="newer": (pub_ts < c.PubTs OR (pub_ts = c.PubTs AND feed_key < c.Key)) ORDER BY pub_ts DESC, feed_key DESC (then reverse)
- wantDesc := (order == "newest" && dir == "older") || (order == "oldest" && dir == "newer")
- reverseAfter := dir == "newer"
-
- if req.Cursor != nil && (req.Cursor.Key != "" || req.Cursor.PubTs > 0) {
- if wantDesc {
- clauses = append(clauses, "(f.pub_ts < ? OR (f.pub_ts = ? AND f.feed_key < ?))")
- } else {
- clauses = append(clauses, "(f.pub_ts > ? OR (f.pub_ts = ? AND f.feed_key > ?))")
- }
- args = append(args, req.Cursor.PubTs, req.Cursor.PubTs, req.Cursor.Key)
- }
-
- query := `
- SELECT
- f.feed_key, f.site, f.kind, f.raw_id, f.mid, f.author_uid, f.author_name, f.author_face,
- f.title, f.summary, f.cover_url, f.canonical_url, f.pub_ts, f.discovered_at,
- f.cached, f.cache_status, f.item_key,
- COALESCE(l.item_dir, ''), COALESCE(l.upgrade_available, 0), COALESCE(l.upgrade_hint, '')
- FROM feed_items f
- LEFT JOIN library_items l ON f.item_key = l.item_key
- WHERE ` + strings.Join(clauses, " AND ")
-
- if wantDesc {
- query += " ORDER BY f.pub_ts DESC, f.feed_key DESC"
- } else {
- query += " ORDER BY f.pub_ts ASC, f.feed_key ASC"
- }
- query += fmt.Sprintf(" LIMIT %d", limit+1)
-
- rows, err := s.db.Query(query, args...)
- if err != nil {
- return FeedPageResult{}, err
- }
- defer rows.Close()
-
- var items []FeedEntry
- for rows.Next() {
- var e FeedEntry
- var cachedInt, upAvail int
- if err := rows.Scan(
- &e.FeedKey, &e.Site, &e.Kind, &e.RawID, &e.Mid, &e.AuthorUID, &e.AuthorName, &e.AuthorFace,
- &e.Title, &e.Summary, &e.CoverURL, &e.CanonicalURL, &e.PubTs, &e.DiscoveredAt,
- &cachedInt, &e.CacheStatus, &e.ItemKey,
- &e.ItemDir, &upAvail, &e.UpgradeHint,
- ); err != nil {
- return FeedPageResult{}, err
- }
- if e.AuthorUID == "" && e.Mid > 0 && e.Site == "bilibili" {
- e.AuthorUID = strconv.FormatInt(e.Mid, 10)
- }
- e.Cached = cachedInt == 1
- e.UpgradeAvailable = upAvail == 1
- items = append(items, e)
- }
- if err := rows.Err(); err != nil {
- return FeedPageResult{}, err
- }
-
- hasMore := false
- if len(items) > limit {
- hasMore = true
- items = items[:limit]
- }
- if reverseAfter && len(items) > 1 {
- for i, j := 0, len(items)-1; i < j; i, j = i+1, j-1 {
- items[i], items[j] = items[j], items[i]
- }
- }
-
- var res FeedPageResult
- res.Items = items
- res.HasMore = hasMore
- if len(items) > 0 {
- first := items[0]
- last := items[len(items)-1]
- res.PrevCursor = &FeedCursor{PubTs: first.PubTs, Key: first.FeedKey}
- res.NextCursor = &FeedCursor{PubTs: last.PubTs, Key: last.FeedKey}
- }
- return res, nil
-}
-
-func feedPageClauses(req FeedPageRequest) ([]string, []any) {
- clauses := []string{"NOT (f.kind = 'video' AND EXISTS (SELECT 1 FROM item_refs r WHERE r.to_key = f.feed_key))"}
- var args []any
- if req.CachedOnly {
- clauses = append(clauses, "f.cached = 1")
- }
- if req.Kind != "" && req.Kind != "all" {
- clauses = append(clauses, "f.kind = ?")
- args = append(args, req.Kind)
- }
- clauses, args = appendSiteAndAuthorClauses(clauses, args, "f.", req.Site, 0, "", req.Authors, req.AuthorRefs)
- return clauses, args
-}
-
-// Resolve a surviving key first; otherwise choose the newest item at or before
-// the saved timestamp (the earliest item if everything is newer). Resolving the
-// pivot before paging also handles more than one page of equal timestamps.
-func (s *Store) feedAnchorCursor(req FeedPageRequest) (*FeedCursor, error) {
s.mu.RLock()
- defer s.mu.RUnlock()
- clauses, args := feedPageClauses(req)
- base := `SELECT f.feed_key, f.pub_ts FROM feed_items f WHERE ` + strings.Join(clauses, " AND ")
- var pivot FeedCursor
- if req.Cursor.Key != "" {
- keyArgs := append(append([]any(nil), args...), req.Cursor.Key)
- err := s.db.QueryRow(base+` AND f.feed_key = ?`, keyArgs...).Scan(&pivot.Key, &pivot.PubTs)
- if err == nil {
- return &pivot, nil
- }
- if !errors.Is(err, sql.ErrNoRows) {
- return nil, err
- }
- }
- if req.Cursor.PubTs > 0 {
- tsArgs := append(append([]any(nil), args...), req.Cursor.PubTs)
- err := s.db.QueryRow(base+` AND f.pub_ts <= ? ORDER BY f.pub_ts DESC, f.feed_key DESC LIMIT 1`, tsArgs...).Scan(&pivot.Key, &pivot.PubTs)
- if err == nil {
- return &pivot, nil
- }
- if !errors.Is(err, sql.ErrNoRows) {
- return nil, err
- }
- }
- order := "DESC"
- if req.Cursor.PubTs > 0 {
- order = "ASC"
- }
- err := s.db.QueryRow(base+" ORDER BY f.pub_ts "+order+", f.feed_key "+order+" LIMIT 1", args...).Scan(&pivot.Key, &pivot.PubTs)
- if errors.Is(err, sql.ErrNoRows) {
- return nil, nil
- }
- return &pivot, err
-}
-
-// NewerCount returns the number of feed items published more recently than the given anchor (pubTs, key).
-func (s *Store) NewerCount(anchorPubTs int64, anchorKey string) (int, error) {
- return s.newerCount(anchorPubTs, anchorKey, false)
-}
-func (s *Store) NewerCachedCount(anchorPubTs int64, anchorKey string) (int, error) {
- return s.newerCount(anchorPubTs, anchorKey, true)
-}
-func (s *Store) newerCount(anchorPubTs int64, anchorKey string, cachedOnly bool) (int, error) {
- s.mu.RLock()
- defer s.mu.RUnlock()
-
- if anchorPubTs <= 0 && anchorKey == "" {
- return 0, nil
- }
- var count int
- err := s.db.QueryRow(`
- SELECT COUNT(1) FROM feed_items f
- WHERE (? = 0 OR f.cached = 1) AND NOT (f.kind = 'video' AND EXISTS (SELECT 1 FROM item_refs r WHERE r.to_key = f.feed_key))
- AND (f.pub_ts > ? OR (f.pub_ts = ? AND f.feed_key > ?))
- `, cachedOnly, anchorPubTs, anchorPubTs, anchorKey).Scan(&count)
- return count, err
-}
-
-// QueryFeed queries the unified feed (both online-discovered and locally cached items) ordered by pub_ts DESC.
-func (s *Store) QueryFeed(filter FeedFilter) ([]FeedEntry, error) {
- s.mu.RLock()
- defer s.mu.RUnlock()
-
- var clauses []string
- var args []any
- if filter.Kind != "" && filter.Kind != "all" {
- clauses = append(clauses, "f.kind = ?")
- args = append(args, filter.Kind)
- }
- clauses, args = appendSiteAndAuthorClauses(clauses, args, "f.", filter.Site, filter.Mid, filter.AuthorUID, filter.Authors, filter.AuthorRefs)
- if filter.CachedOnly {
- clauses = append(clauses, "f.cached = 1")
- }
- if kw := strings.TrimSpace(filter.Keyword); kw != "" {
- clauses = append(clauses, "(f.title LIKE ? OR f.summary LIKE ? OR f.author_name LIKE ? OR f.raw_id LIKE ?)")
- pat := "%" + kw + "%"
- args = append(args, pat, pat, pat, pat)
- }
-
- query := `
- SELECT
- f.feed_key, f.site, f.kind, f.raw_id, f.mid, f.author_uid, f.author_name, f.author_face,
- f.title, f.summary, f.cover_url, f.canonical_url, f.pub_ts, f.discovered_at,
- f.cached, f.cache_status, f.item_key,
- COALESCE(l.item_dir, ''), COALESCE(l.upgrade_available, 0), COALESCE(l.upgrade_hint, '')
- FROM feed_items f
- LEFT JOIN library_items l ON f.item_key = l.item_key
- `
- if len(clauses) > 0 {
- query += " WHERE " + strings.Join(clauses, " AND ")
- }
- if strings.EqualFold(filter.Sort, "oldest") {
- query += " ORDER BY f.pub_ts ASC, f.feed_key ASC"
- } else {
- query += " ORDER BY f.pub_ts DESC, f.feed_key DESC"
- }
- limit := filter.Limit
- if limit <= 0 {
- limit = 200
- }
- query += fmt.Sprintf(" LIMIT %d OFFSET %d", limit, max(0, filter.Offset))
-
- rows, err := s.db.Query(query, args...)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- var out []FeedEntry
- for rows.Next() {
- var e FeedEntry
- var cachedInt, upAvail int
- if err := rows.Scan(
- &e.FeedKey, &e.Site, &e.Kind, &e.RawID, &e.Mid, &e.AuthorUID, &e.AuthorName, &e.AuthorFace,
- &e.Title, &e.Summary, &e.CoverURL, &e.CanonicalURL, &e.PubTs, &e.DiscoveredAt,
- &cachedInt, &e.CacheStatus, &e.ItemKey,
- &e.ItemDir, &upAvail, &e.UpgradeHint,
- ); err != nil {
- return nil, err
- }
- if e.AuthorUID == "" && e.Mid > 0 && e.Site == "bilibili" {
- e.AuthorUID = strconv.FormatInt(e.Mid, 10)
- }
- e.Cached = cachedInt == 1
- e.UpgradeAvailable = upAvail == 1
- out = append(out, e)
- }
- return out, rows.Err()
-}
-
-// PlanDelete computes the exact DeletePlan for an item without modifying disk or DB (FR-LIB-003, INV-09).
-func (s *Store) PlanDelete(itemKey string) (DeletePlan, error) {
- s.mu.RLock()
- defer s.mu.RUnlock()
- return s.planDeleteLocked(itemKey)
-}
-
-func (s *Store) planDeleteLocked(itemKey string) (DeletePlan, error) {
- meta, ok, err := s.getItemLocked(itemKey)
- if err != nil {
- return DeletePlan{}, err
- }
- if !ok {
- return DeletePlan{}, fmt.Errorf("library: item %q not found", itemKey)
- }
- if meta.Status == "recording" {
- return DeletePlan{}, fmt.Errorf("library: 正在录制的直播条目不能删除,请先停止录制")
- }
-
- plan := DeletePlan{
- TargetKey: meta.ItemKey,
- ItemKeys: []string{meta.ItemKey},
- }
-
- itemsToDelete := []ItemMetadata{meta}
-
- // If deleting a dynamic item that references videos, check if each referenced video is shared or directly cached.
- if meta.Kind == "dynamic" && len(meta.Videos) > 0 {
- for _, vid := range meta.Videos {
- vidKey := CanonicalItemKey(meta.Site, "video", vid)
- vMeta, vOk, _ := s.getItemLocked(vidKey)
- if !vOk {
- continue
- }
- var otherRefs int
- _ = s.db.QueryRow(`SELECT COUNT(1) FROM item_refs WHERE to_key = ? AND from_key != ?`, vidKey, meta.ItemKey).Scan(&otherRefs)
- if otherRefs > 0 || vMeta.DirectCached {
- plan.PreservedSharedVideos = append(plan.PreservedSharedVideos, vidKey)
- } else {
- plan.ItemKeys = append(plan.ItemKeys, vidKey)
- itemsToDelete = append(itemsToDelete, vMeta)
- }
- }
- }
+ allowMoved := s.allowMovedFiles
+ s.fetchItemsBatchLocked(itemKeys, rawIDs, byKey, byRaw)
- seenFiles := make(map[string]bool)
- seenUserFiles := make(map[string]bool)
- for _, it := range itemsToDelete {
- regFiles, userFiles := collectRegisteredAndUserFiles(it)
- for _, f := range regFiles {
- if !seenFiles[f] {
- seenFiles[f] = true
- plan.RegisteredFiles = append(plan.RegisteredFiles, f)
- }
- }
- for _, uf := range userFiles {
- if !seenUserFiles[uf] {
- seenUserFiles[uf] = true
- plan.PreservedUserFiles = append(plan.PreservedUserFiles, uf)
+ // Fetch any videos referenced by matched dynamics in one extra batched query.
+ var refKeys []string
+ seenRef := make(map[string]bool)
+ for _, meta := range byKey {
+ if meta.Kind == "dynamic" && len(meta.Videos) > 0 {
+ for _, vid := range meta.Videos {
+ vk := CanonicalItemKey(meta.Site, "video", vid)
+ if _, ok := byKey[vk]; !ok && !seenRef[vk] {
+ seenRef[vk] = true
+ refKeys = append(refKeys, vk)
+ }
}
}
}
- return plan, nil
-}
-
-func collectRegisteredAndUserFiles(meta ItemMetadata) (registeredAbs []string, userRel []string) {
- if meta.ItemDir == "" {
- return nil, nil
- }
- itemDir := filepath.Clean(meta.ItemDir)
- regRel := make(map[string]bool)
- addRel := func(rel string) {
- rel = strings.TrimSpace(rel)
- if rel == "" {
- return
- }
- norm := strings.ToLower(filepath.ToSlash(filepath.Clean(filepath.FromSlash(rel))))
- if !safeRegisteredPath(itemDir, rel) {
- return
- }
- if !regRel[norm] {
- regRel[norm] = true
- registeredAbs = append(registeredAbs, filepath.Join(itemDir, filepath.FromSlash(rel)))
- }
- }
-
- for _, m := range meta.Media {
- addRel(m.Path)
- addRel(m.Motion)
- }
- for _, part := range meta.PendingParts {
- addRel(part)
- if meta.Kind == "live" && strings.HasPrefix(part, "part-") && strings.HasSuffix(part, ".mp4.part") {
- // Both names are reserved before recording starts. A crash after the
- // final rename can leave the MP4 present before its media row is saved.
- addRel(strings.TrimSuffix(part, ".part"))
- }
- }
- for _, p := range meta.Parts {
- addRel(p.File)
- addRel(p.Danmaku)
- addRel(p.Audio.SavedAs)
- for _, sub := range p.Subtitles {
- addRel(sub)
- }
- }
- if meta.DouyinVideo != nil {
- addRel(meta.DouyinVideo.File)
- }
- for _, np := range meta.NotePages {
- addRel(np.Image)
- addRel(np.Cover)
- addRel(np.Motion)
- addRel(np.Video)
- if np.VideoInfo != nil {
- addRel(np.VideoInfo.File)
- }
- }
- if meta.Music != nil {
- addRel(meta.Music.File)
- addRel(meta.Music.Cover)
- }
- if meta.Live != nil {
- for _, seg := range meta.Live.Segments {
- addRel(seg.File)
- }
- }
- addRel("orig.json")
-
- // Scan itemDir for *.part files (which belong to TRACE) and user-owned files (which MUST be preserved).
- _ = filepath.WalkDir(itemDir, func(path string, d fs.DirEntry, walkErr error) error {
- if walkErr != nil || d.IsDir() {
- return nil
- }
- rel, rErr := filepath.Rel(itemDir, path)
- if rErr != nil {
- return nil
- }
- norm := strings.ToLower(filepath.ToSlash(rel))
- if norm == "item.json" {
- return nil
- }
- if strings.HasSuffix(norm, ".part") && regRel[strings.TrimSuffix(norm, ".part")] {
- addRel(rel)
- return nil
- }
- if !regRel[norm] {
- userRel = append(userRel, filepath.ToSlash(rel))
- }
- return nil
- })
-
- // item.json is always deleted last among registered files.
- addRel("item.json")
- return registeredAbs, userRel
-}
-
-// Delete executes PlanDelete: removes only registered files and empty directories, never recursive RemoveAll (INV-09).
-func (s *Store) Delete(itemKey string) (DeletePlan, error) {
- s.mu.Lock()
- defer s.mu.Unlock()
- return s.deleteWithPlanLocked(itemKey, true)
-}
-
-// DeleteItem removes an item from the index and optionally deletes its registered files from disk (INV-09).
-// It NEVER calls os.RemoveAll on the item directory; user-placed files are strictly preserved.
-func (s *Store) DeleteItem(itemKey string, deleteFiles bool) error {
- s.mu.Lock()
- defer s.mu.Unlock()
- _, err := s.deleteWithPlanLocked(itemKey, deleteFiles)
- return err
-}
-
-func (s *Store) deleteWithPlanLocked(itemKey string, deleteFiles bool) (DeletePlan, error) {
- plan, err := s.planDeleteLocked(itemKey)
- if err != nil {
- return DeletePlan{}, err
- }
-
- var itemDirs []string
- for _, k := range plan.ItemKeys {
- if m, ok, _ := s.getItemLocked(k); ok && m.ItemDir != "" {
- itemDirs = append(itemDirs, m.ItemDir)
- }
+ if len(refKeys) > 0 {
+ s.fetchItemsBatchLocked(refKeys, nil, byKey, byRaw)
}
+ s.mu.RUnlock()
- // 1. Write pending-deletes.json before deleting files (data-and-cache.md §2.8).
- if deleteFiles && len(plan.RegisteredFiles) > 0 {
- pending, err := s.readPendingDeletesLocked()
- if err != nil {
- return plan, err
+ // Refresh on-disk file state outside the store lock once per unique item.
+ if !allowMoved {
+ for k, meta := range byKey {
+ refreshItemFileState(&meta)
+ byKey[k] = meta
}
- for _, k := range plan.ItemKeys {
- m, ok, _ := s.getItemLocked(k)
- if ok {
- regFiles, _ := collectRegisteredAndUserFiles(m)
- pending = append(pending, pendingDeleteRecord{
- ItemKey: k,
- ItemDir: m.ItemDir,
- RegisteredFiles: regFiles,
- })
+ for r, meta := range byRaw {
+ if updated, ok := byKey[meta.ItemKey]; ok {
+ byRaw[r] = updated
}
}
- if err := s.writePendingDeletesLocked(pending); err != nil {
- return plan, err
- }
}
- // 2. Remove from index and references.
- tx, err := s.db.Begin()
- if err != nil {
- return plan, err
- }
- defer tx.Rollback()
- for _, k := range plan.ItemKeys {
- if _, err := tx.Exec(`DELETE FROM library_items WHERE item_key = ?`, k); err != nil {
- return plan, err
- }
- if _, err := tx.Exec(`DELETE FROM item_refs WHERE from_key = ? OR to_key = ?`, k, k); err != nil {
- return plan, err
- }
- if _, err := tx.Exec(`UPDATE feed_items SET cached = 0, cache_status = '', item_key = '' WHERE item_key = ?`, k); err != nil {
- return plan, err
+ lookup := func(k string) (ItemMetadata, bool) {
+ k = strings.TrimSpace(k)
+ if k == "" {
+ return ItemMetadata{}, false
}
- }
- if err := tx.Commit(); err != nil {
- return plan, err
- }
-
- // 3. Delete only registered files one by one, then remove empty directories bottom-up (NEVER os.RemoveAll).
- if deleteFiles {
- allRemoved := true
- var removeErrors []error
- for _, f := range plan.RegisteredFiles {
- if rErr := os.Remove(f); rErr != nil && !os.IsNotExist(rErr) {
- allRemoved = false
- removeErrors = append(removeErrors, rErr)
+ switch {
+ case strings.Count(k, ":") == 0:
+ if m, ok := byKey[k]; ok {
+ return m, true
}
- }
- roots := s.allRootsLocked()
- for _, dir := range itemDirs {
- removeEmptyDirsBottomUp(dir)
- removeEmptyAuthorDirs(dir, roots)
- }
- if allRemoved {
- // Clear completed keys from pending-deletes.json.
- pending, err := s.readPendingDeletesLocked()
- if err != nil {
- return plan, err
- }
- doneSet := make(map[string]bool, len(plan.ItemKeys))
- for _, k := range plan.ItemKeys {
- doneSet[k] = true
- }
- var rem []pendingDeleteRecord
- for _, p := range pending {
- if !doneSet[p.ItemKey] {
- rem = append(rem, p)
- }
+ m, ok := byRaw[k]
+ return m, ok
+ case strings.Count(k, ":") == 1 || strings.HasPrefix(strings.ToLower(k), "live:"):
+ if m, ok := byKey[k]; ok {
+ return m, true
}
- if err := s.writePendingDeletesLocked(rem); err != nil {
- return plan, err
+ m, ok := byKey["bilibili:"+k]
+ return m, ok
+ default:
+ normKey := k
+ if strings.HasPrefix(strings.ToLower(normKey), "douyin:note:") {
+ normKey = "douyin:dynamic:" + normKey[len("douyin:note:"):]
}
- }
- if !allRemoved {
- return plan, errors.Join(removeErrors...)
+ m, ok := byKey[normKey]
+ return m, ok
}
}
- return plan, nil
-}
-
-// removeEmptyDirsBottomUp removes empty subdirectories (such as images/) and the item directory itself
-// ONLY if they are completely empty (using os.Remove, never os.RemoveAll).
-func removeEmptyDirsBottomUp(itemDir string) {
- itemDir = filepath.Clean(itemDir)
- if itemDir == "" || itemDir == "." {
- return
- }
- var dirs []string
- _ = filepath.WalkDir(itemDir, func(path string, d fs.DirEntry, err error) error {
- if err == nil && d.IsDir() {
- dirs = append(dirs, path)
- }
- return nil
- })
- // Sort deepest paths first.
- sort.Slice(dirs, func(i, j int) bool {
- return len(dirs[i]) > len(dirs[j])
- })
- for _, d := range dirs {
- entries, err := os.ReadDir(d)
- if err == nil && len(entries) == 0 {
- _ = os.Remove(d)
- }
- }
-}
-
-// removeEmptyAuthorDirs removes the now-empty kind folder (videos/, works/…)
-// and author folder above a deleted item, so deleting a creator's last item
-// leaves no empty folders (2026-11-15 user feedback). It only climbs inside a
-// library root, never removes the root or its site folder (/bilibili),
-// and uses os.Remove, which fails on any folder that still has files.
-func removeEmptyAuthorDirs(itemDir string, roots []string) {
- itemDir = filepath.Clean(itemDir)
- for _, root := range roots {
- root = filepath.Clean(root)
- rel, err := filepath.Rel(root, itemDir)
- if err != nil || rel == "." || strings.HasPrefix(rel, "..") || filepath.IsAbs(rel) {
+ for _, k := range keys {
+ meta, ok := lookup(k)
+ if !ok {
+ out[k] = DotState{Key: k, Dot: "none", Label: "未缓存"}
continue
}
- // ///
- : remove , then .
- depth := len(strings.Split(filepath.ToSlash(rel), "/"))
- dir := filepath.Dir(itemDir)
- for depth--; depth >= 2; depth-- {
- if os.Remove(dir) != nil {
- return
+ dot := ComputeDotState(meta)
+ if meta.Kind == "dynamic" && len(meta.Videos) > 0 {
+ for _, vid := range meta.Videos {
+ vMeta, vOk := byKey[CanonicalItemKey(meta.Site, "video", vid)]
+ if !vOk {
+ dot.Dot = "red"
+ dot.Label = "引用视频缺失"
+ break
+ }
+ vDot := ComputeDotState(vMeta)
+ if vDot.Dot == "red" {
+ dot.Dot = "red"
+ dot.Label = vDot.Label
+ break
+ }
+ if vDot.Dot == "yellow" && dot.Dot == "green" {
+ dot.Dot = "yellow"
+ dot.Label = vDot.Label
+ }
}
- dir = filepath.Dir(dir)
}
- return
+ dot.Key = k
+ out[k] = dot
}
+ return out
}
// MigrateCacheDir changes the active cache directory, optionally moving registered files to newDir,
@@ -2361,207 +759,16 @@ func (s *Store) listAllItemsLocked() ([]ItemMetadata, error) {
if err := rows.Scan(&jsonStr, &itemDir, &status, &totalBytes, &upAvail, &upHint); err != nil {
return nil, err
}
- if meta, err := ParseItemMetadata([]byte(jsonStr)); err != nil {
- return nil, err
- } else {
- meta.ItemDir = itemDir
- meta.Status = status
- meta.TotalBytes = totalBytes
- meta.UpgradeAvailable = upAvail == 1
- meta.UpgradeHint = upHint
- out = append(out, meta)
- }
- }
- return out, rows.Err()
-}
-
-// UpgradeCandidates returns up to 50 cached video items ordered by oldest UpgradeCheckedAt first (FR-CACHE-006).
-func (s *Store) UpgradeCandidates(limit int) ([]ItemMetadata, error) {
- if limit <= 0 || limit > 50 {
- limit = 50
- }
- items, err := s.ListItems(FeedFilter{Site: "bilibili", Kind: "video", Limit: 500})
- if err != nil {
- return nil, err
- }
- sort.SliceStable(items, func(i, j int) bool {
- ti, _ := time.Parse(time.RFC3339, items[i].UpgradeCheckedAt)
- tj, _ := time.Parse(time.RFC3339, items[j].UpgradeCheckedAt)
- if !ti.Equal(tj) {
- return ti.Before(tj)
- }
- return items[i].PubTs < items[j].PubTs
- })
- if len(items) > limit {
- items = items[:limit]
- }
- return items, nil
-}
-
-// CheckUpgradeKeys probes the given video keys (or all candidates if keys is empty) for quality upgrades.
-// When force is false, items checked within the last 24 hours are skipped without network requests (FR-CACHE-006).
-func (s *Store) CheckUpgradeKeys(ctx context.Context, client *bilibili.Client, keys []string, force bool, opts bilibili.PlaySelectionOptions) ([]ItemMetadata, error) {
- if client == nil {
- return nil, fmt.Errorf("library: bilibili client is nil")
- }
-
- var candidates []ItemMetadata
- if len(keys) == 0 {
- var err error
- candidates, err = s.UpgradeCandidates(50)
+ meta, err := ParseItemMetadata([]byte(jsonStr))
if err != nil {
return nil, err
}
- } else {
- for _, k := range keys {
- m, ok, err := s.GetItem(k)
- if err != nil {
- return nil, &bilibili.SiteError{Kind: "storage", Message: "读取缓存记录失败", Err: err}
- }
- if ok && m.Kind == "video" {
- candidates = append(candidates, m)
- }
- }
- }
-
- var upgradable []ItemMetadata
- now := time.Now().UTC()
- nowStr := now.Format(time.RFC3339)
-
- for _, meta := range candidates {
- if err := ctx.Err(); err != nil {
- return upgradable, err
- }
- if len(meta.Parts) == 0 {
- continue
- }
- if !force && meta.UpgradeCheckedAt != "" {
- if lastT, err := time.Parse(time.RFC3339, meta.UpgradeCheckedAt); err == nil && now.Sub(lastT) < 24*time.Hour {
- if meta.UpgradeAvailable {
- upgradable = append(upgradable, meta)
- }
- continue
- }
- }
-
- // Probe P1 only (data-and-cache.md §2.7).
- part := &meta.Parts[0]
- if part.CID <= 0 {
- continue
- }
- plan, err := client.PlayURL(ctx, meta.RawID, part.CID, opts)
- if err != nil {
- return upgradable, err
- }
-
- part.Available = PartAvailableInfo{
- AcceptQuality: plan.Available.AcceptQuality,
- Formats: plan.Available.Formats,
- Returned: plan.Available.Returned,
- BestVideo: plan.Available.BestVideo,
- BestAudio: plan.Available.BestAudio,
- HasDolby: plan.Available.HasDolby,
- HasFlac: plan.Available.HasFlac,
- ProbedAt: nowStr,
- Downgraded: plan.Available.Downgraded,
- DowngradeHint: plan.Available.DowngradeHint,
- }
-
- var hints []string
- if bilibili.QualityRank(plan.Video.Quality) > bilibili.QualityRank(part.Video.Quality) {
- hints = append(hints, fmt.Sprintf("P%02d 视频可由 %s (%d) 升级至 %s (%d)",
- part.Page,
- bilibili.QualityName(part.Video.Quality), part.Video.Quality,
- plan.Video.QualityName, plan.Video.Quality,
- ))
- }
- if plan.Audio != nil && audioPriority(plan.Audio.Quality) > audioPriority(part.Audio.Quality) {
- hints = append(hints, fmt.Sprintf("P%02d 音频可由 %s 升级至 %s",
- part.Page,
- part.Audio.Name,
- plan.Audio.Name,
- ))
- }
-
- meta.UpgradeCheckedAt = nowStr
- meta.UpgradeAvailable = len(hints) > 0
- meta.UpgradeHint = strings.Join(hints, ";")
- updated, err := s.SaveItem(meta.ItemDir, meta)
- if err != nil {
- return upgradable, &bilibili.SiteError{Kind: "storage", Message: "画质探测结果保存失败", Err: err}
- }
- if updated.UpgradeAvailable {
- upgradable = append(upgradable, updated)
- }
- }
-
- sort.SliceStable(upgradable, func(i, j int) bool {
- return upgradable[i].PubTs > upgradable[j].PubTs
- })
- return upgradable, nil
-}
-
-// CheckQualityUpgrade probes cached video items against the Bilibili PlayURL API (with force=true for direct calls).
-func (s *Store) CheckQualityUpgrade(ctx context.Context, client *bilibili.Client, opts bilibili.PlaySelectionOptions) ([]ItemMetadata, error) {
- return s.CheckUpgradeKeys(ctx, client, nil, true, opts)
-}
-
-func audioPriority(id int) int {
- switch id {
- case 30251:
- return 50
- case 30250:
- return 40
- case 30280:
- return 30
- case 30232:
- return 20
- case 30216:
- return 10
- default:
- return 0
- }
-}
-
-func safeRegisteredPath(root, rel string) bool {
- if rejectDirectoryLinksRecent(root) != nil {
- return false
- }
- if rel == "" || filepath.IsAbs(rel) || strings.ContainsAny(rel, "\\:\x00") {
- return false
- }
- current := root
- for _, part := range strings.Split(rel, "/") {
- if part == "" || part == "." || part == ".." {
- return false
- }
- current = filepath.Join(current, part)
- info, err := os.Lstat(current)
- if err != nil {
- if os.IsNotExist(err) {
- continue
- }
- return false
- }
- if isLinkLike(info.Mode()) {
- return false
- }
- }
- info, err := os.Lstat(root)
- return err == nil && info.IsDir() && !isLinkLike(info.Mode())
-}
-
-// isLinkLike reports symlinks and other reparse points. Since Go 1.23 a
-// Windows directory junction reports ModeIrregular instead of ModeSymlink.
-func isLinkLike(mode os.FileMode) bool {
- return mode&(os.ModeSymlink|os.ModeIrregular) != 0
-}
-
-// ResolveItemPath validates an item-relative path before a registered file is
-// read, written, or removed. The final file may be absent, but links are rejected.
-func ResolveItemPath(root, rel string) (string, error) {
- if !safeRegisteredPath(root, rel) {
- return "", fmt.Errorf("library: unsafe item-relative path")
+ meta.ItemDir = itemDir
+ meta.Status = status
+ meta.TotalBytes = totalBytes
+ meta.UpgradeAvailable = upAvail == 1
+ meta.UpgradeHint = upHint
+ out = append(out, meta)
}
- return EnsureWithinRoot(root, filepath.Join(root, filepath.FromSlash(rel)))
+ return out, rows.Err()
}
diff --git a/internal/library/library_test.go b/internal/library/library_test.go
index 5228dcd..4776e31 100644
--- a/internal/library/library_test.go
+++ b/internal/library/library_test.go
@@ -17,7 +17,7 @@ import (
"github.com/chialecode/trace/internal/storage"
)
-// C16: Filename sanitization and path traversal containment.
+// Filename sanitization and path traversal containment.
func TestSanitizeFileNameAndEnsureWithinRoot(t *testing.T) {
cases := []struct {
in string
@@ -49,7 +49,7 @@ func TestSanitizeFileNameAndEnsureWithinRoot(t *testing.T) {
}
}
-// C24, C25, C26, C28: Index rebuild from item.json after DB deletion, missing_files detection,
+// Index rebuild from item.json after DB deletion, missing_files detection,
// corrupt item.json backup, cache dir migration, and safe item deletion preserving user files.
func TestLibraryIndexRebuildMissingFilesMigrateAndDelete(t *testing.T) {
tmp := t.TempDir()
@@ -106,7 +106,7 @@ func TestLibraryIndexRebuildMissingFilesMigrateAndDelete(t *testing.T) {
t.Fatalf("SaveItem video: %v", err)
}
- // Also insert an online-only discovered feed item to verify unified feed order and deduplication (C24).
+ // Also insert an online-only discovered feed item to verify unified feed order and deduplication.
if err := store.UpsertFeedEntry(FeedEntry{
Site: "bilibili",
Kind: "dynamic",
@@ -132,12 +132,12 @@ func TestLibraryIndexRebuildMissingFilesMigrateAndDelete(t *testing.T) {
t.Fatalf("expected second item to be cached video BV17x411w7KC, got %+v", feed[1])
}
- // Create a corrupt item.json in another folder to verify C28 backup during RebuildIndex.
+ // Create a corrupt item.json in another folder to verify backup during RebuildIndex.
corruptDir := filepath.Join(cacheDir, "bilibili", "12345_TestUP", "dynamic_bad")
_ = os.MkdirAll(corruptDir, 0o700)
_ = os.WriteFile(filepath.Join(corruptDir, "item.json"), []byte("{corrupt"), 0o600)
- // Delete library.db and reopen a fresh DB, then RebuildIndex from item.json files (C25).
+ // Delete library.db and reopen a fresh DB, then RebuildIndex from item.json files.
_ = db.Close()
_ = os.Remove(dbPath)
db2, _, _, err := storage.OpenSQLite(dbPath)
@@ -158,7 +158,7 @@ func TestLibraryIndexRebuildMissingFilesMigrateAndDelete(t *testing.T) {
t.Fatalf("unexpected RebuildReport: %+v", rep)
}
- // Remove P01_Part1.mp4 on disk and rebuild -> status must become missing_files (C24).
+ // Remove P01_Part1.mp4 on disk and rebuild -> status must become missing_files.
_ = os.Remove(mp4Path)
repMissing, err := store2.RebuildIndex()
if err != nil {
@@ -172,7 +172,7 @@ func TestLibraryIndexRebuildMissingFilesMigrateAndDelete(t *testing.T) {
t.Fatalf("expected status=missing_files, got %+v ok=%v err=%v", gotItem, ok, err)
}
- // Restore file and migrate cacheDir to cache2 (C26).
+ // Restore file and migrate cacheDir to cache2.
_ = os.WriteFile(mp4Path, []byte("synthetic-mp4-bytes"), 0o600)
cacheDir2 := filepath.Join(tmp, "cache2")
repMig, err := store2.MigrateCacheDir(cacheDir2, true)
@@ -207,7 +207,7 @@ func TestLibraryIndexRebuildMissingFilesMigrateAndDelete(t *testing.T) {
}
}
-// R-01 (P0) & C26: PlanDelete and Delete preserve user-owned files, protect shared videos, and reject active recordings.
+// PlanDelete and Delete preserve user-owned files, protect shared videos, and reject active recordings.
func TestPlanDeleteAndDeletePreservesUserFiles(t *testing.T) {
tmp := t.TempDir()
db, _, _, err := storage.OpenSQLite(filepath.Join(tmp, "library.db"))
@@ -304,7 +304,7 @@ func TestPlanDeleteAndDeletePreservesUserFiles(t *testing.T) {
t.Fatalf("expected item.json to be deleted, stat err=%v", err)
}
if data, err := os.ReadFile(userFile); err != nil || string(data) != "keep-my-notes" {
- t.Fatalf("CRITICAL R-01: user-owned.txt was not preserved! err=%v data=%q", err, string(data))
+ t.Fatalf("user-owned.txt was not preserved! err=%v data=%q", err, string(data))
}
// 3. Active recording item cannot be deleted.
@@ -379,7 +379,7 @@ func TestMediaPathWhitelistAndSymlinkRejection(t *testing.T) {
}
}
-// C19: State dot inference (green, yellow, red, ring, none).
+// State dot inference (green, yellow, red, ring, none).
func TestStateDotInference(t *testing.T) {
tmp := t.TempDir()
db, _, _, _ := storage.OpenSQLite(filepath.Join(tmp, "library.db"))
@@ -415,7 +415,7 @@ func TestStateDotInference(t *testing.T) {
}
}
-// C24: Bidirectional keyset pagination (pub_ts, key) and NewerCount.
+// Bidirectional keyset pagination (pub_ts, key) and NewerCount.
func TestBidirectionalKeysetFeedAndAnchor(t *testing.T) {
tmp := t.TempDir()
db, _, _, _ := storage.OpenSQLite(filepath.Join(tmp, "library.db"))
@@ -459,13 +459,13 @@ func TestBidirectionalKeysetFeedAndAnchor(t *testing.T) {
t.Fatalf("NewerCount = %d, err=%v (want 2)", newer, err)
}
- // Bidirectional newer page from dyn_3 cursor: should return dyn_5, dyn_4 in newest-first order with no duplicates or omissions (C24, R10).
+ // Bidirectional newer page from dyn_3 cursor: should return dyn_5, dyn_4 in newest-first order with no duplicates or omissions.
pNewer, err := store.FeedPage(FeedPageRequest{Cursor: &FeedCursor{PubTs: p2.Items[0].PubTs, Key: p2.Items[0].FeedKey}, Order: "newest", Direction: "newer", Limit: 5})
if err != nil || len(pNewer.Items) != 2 || pNewer.Items[0].RawID != "dyn_5" || pNewer.Items[1].RawID != "dyn_4" {
t.Fatalf("FeedPage newer from dyn_3 = %+v, err=%v", pNewer, err)
}
- // Around cursor when anchor item still exists vs when anchor item was deleted (R10).
+ // Around cursor when anchor item still exists vs when anchor item was deleted.
pAround, err := store.FeedPage(FeedPageRequest{Cursor: &FeedCursor{PubTs: p2.Items[0].PubTs, Key: p2.Items[0].FeedKey}, Order: "newest", Direction: "around", Limit: 10})
if err != nil || len(pAround.Items) != 5 {
t.Fatalf("FeedPage around = %+v, err=%v", pAround, err)
@@ -544,7 +544,7 @@ func TestFeedAroundTimestampChoosesNearestOlderItemAcrossTies(t *testing.T) {
}
}
-// C25: Filter by type, subscription authors, and creator mid.
+// Filter by type, subscription authors, and creator mid.
func TestLibraryFilterByTypeSubscriptionAndCreator(t *testing.T) {
tmp := t.TempDir()
db, _, _, _ := storage.OpenSQLite(filepath.Join(tmp, "library.db"))
@@ -570,7 +570,7 @@ func TestLibraryFilterByTypeSubscriptionAndCreator(t *testing.T) {
}
}
-// C27: AddLibraryRoot recognizes legacy trace-data folder with library/ and NO settings.json, skipping duplicates.
+// AddLibraryRoot recognizes legacy trace-data folder with library/ and NO settings.json, skipping duplicates.
func TestAddLibraryRootLegacyWithoutSettingsJSON(t *testing.T) {
tmp := t.TempDir()
db, _, _, _ := storage.OpenSQLite(filepath.Join(tmp, "library.db"))
@@ -616,11 +616,7 @@ func TestAddLibraryRootLegacyWithoutSettingsJSON(t *testing.T) {
}
}
-func TestRebuildIndexFromItemJSONManifests(t *testing.T) {
- TestLibraryIndexRebuildMissingFilesMigrateAndDelete(t)
-}
-
-// C20 & C27: Quality upgrade detection and 24-hour cooldown.
+// Quality upgrade detection and 24-hour cooldown.
func TestCheckQualityUpgradeDetection(t *testing.T) {
tmp := t.TempDir()
db, _, _, err := storage.OpenSQLite(filepath.Join(tmp, "library.db"))
diff --git a/internal/library/longpath_windows_test.go b/internal/library/longpath_windows_test.go
index 59c4c62..7e7bb25 100644
--- a/internal/library/longpath_windows_test.go
+++ b/internal/library/longpath_windows_test.go
@@ -6,7 +6,6 @@ import (
"os"
"os/exec"
"path/filepath"
- "strings"
"syscall"
"testing"
@@ -44,7 +43,7 @@ func TestShortPathNamesAreNotLinksButJunctionsAre(t *testing.T) {
if err := rejectDirectoryLinks(short); err != nil {
t.Fatalf("short path taken for a link: %v", err)
}
- if !safeRegisteredPath(short, "part-001.mp4") {
+ if !safeRegisteredPathStrict(short, "part-001.mp4") || !safeRegisteredPathRead(short, "part-001.mp4") {
t.Fatal("a registered file under a short path was refused")
}
@@ -58,7 +57,3 @@ func TestShortPathNamesAreNotLinksButJunctionsAre(t *testing.T) {
t.Fatal("a junction was not rejected")
}
}
-
-func samePath(a, b string) bool {
- return strings.EqualFold(filepath.Clean(a), filepath.Clean(b))
-}
diff --git a/internal/library/merge.go b/internal/library/merge.go
new file mode 100644
index 0000000..7d4f911
--- /dev/null
+++ b/internal/library/merge.go
@@ -0,0 +1,512 @@
+package library
+
+import (
+ "encoding/json"
+ "fmt"
+ "path/filepath"
+ "regexp"
+ "sort"
+ "strconv"
+ "strings"
+)
+
+// Merge modes of an imported item that conflicts with the local one
+// (docs/design/remote.md §6.3).
+const (
+ // MergeKeepLocal keeps every local file and fills in only what the
+ // local item lacks.
+ MergeKeepLocal = "keep_local"
+ // MergeUseImported makes the imported manifest the item's manifest.
+ MergeUseImported = "use_imported"
+ // MergeUnion keeps local files of the same name, adds the rest and
+ // joins parts, live segments and incidents.
+ MergeUnion = "merge"
+)
+
+var livePartName = regexp.MustCompile(`^part-(\d+)(\.[A-Za-z0-9]+)$`)
+
+// SegmentRename is an imported live segment stored under another name
+// because the local item already has a different file with its name (two
+// installations recorded the same broadcast, each numbering from 001).
+type SegmentRename struct{ From, To string }
+
+func cloneItemMetadataSlices(meta ItemMetadata) ItemMetadata {
+ meta.Media = append([]MediaFile(nil), meta.Media...)
+ meta.Parts = append([]VideoPartRecord(nil), meta.Parts...)
+ for i := range meta.Parts {
+ meta.Parts[i].Subtitles = append([]string(nil), meta.Parts[i].Subtitles...)
+ }
+ meta.ExpectedPages = append([]int(nil), meta.ExpectedPages...)
+ meta.NotePages = append([]NotePageRecord(nil), meta.NotePages...)
+ for i := range meta.NotePages {
+ if meta.NotePages[i].VideoInfo != nil {
+ vi := *meta.NotePages[i].VideoInfo
+ meta.NotePages[i].VideoInfo = &vi
+ }
+ }
+ if meta.DouyinVideo != nil {
+ dv := *meta.DouyinVideo
+ meta.DouyinVideo = &dv
+ }
+ if meta.Music != nil {
+ mu := *meta.Music
+ meta.Music = &mu
+ }
+ if meta.CachedBy != nil {
+ cb := *meta.CachedBy
+ meta.CachedBy = &cb
+ }
+ if meta.Via != nil {
+ v := *meta.Via
+ meta.Via = &v
+ }
+ if meta.Live != nil {
+ lv := *meta.Live
+ lv.Segments = append([]LiveSegmentInfo(nil), lv.Segments...)
+ lv.Incidents = append([]LiveIncident(nil), lv.Incidents...)
+ meta.Live = &lv
+ }
+ meta.Missing = append([]MissingRecord(nil), meta.Missing...)
+ meta.PendingParts = append([]string(nil), meta.PendingParts...)
+ meta.Videos = append([]string(nil), meta.Videos...)
+ return meta
+}
+
+// MergeItemMetadata joins an imported manifest into the local one.
+// sameContent reports whether a registered path is present locally with the
+// imported content (same bytes and SHA-256); paths the local item has with
+// other content keep the local file except in MergeUseImported. Live
+// segments of the imported item whose names are taken by different local
+// files (and any following segments from that import) are renumbered
+// sequentially after the local ones (the returned renames say which imported
+// file goes to which name). The result keeps the local folder and cachedBy.
+func MergeItemMetadata(local, imported ItemMetadata, mode string, sameContent func(rel string) bool) (ItemMetadata, []SegmentRename) {
+ if mode == MergeUseImported {
+ out := cloneItemMetadataSlices(imported)
+ out.ItemDir, out.ItemKey, out.RawID = local.ItemDir, local.ItemKey, local.RawID
+ if local.CachedBy != nil {
+ cb := *local.CachedBy
+ out.CachedBy = &cb
+ }
+ out.Missing = nil
+ return out, nil
+ }
+ out := cloneItemMetadataSlices(local)
+ out.Missing = nil
+
+ // Track imported live segment paths so mergeLive owns all live-segment
+ // deduplication and sequential renumbering before updating out.Media.
+ importedLiveSegPaths := map[string]bool{}
+ if out.Live != nil && imported.Live != nil {
+ for _, seg := range imported.Live.Segments {
+ if norm := strings.ToLower(cleanManifestRel(seg.File)); norm != "" {
+ importedLiveSegPaths[norm] = true
+ }
+ }
+ }
+
+ // Media: by path; local wins (live segments merged below when both have Live).
+ have := map[string]bool{}
+ for _, m := range out.Media {
+ have[strings.ToLower(cleanManifestRel(m.Path))] = true
+ }
+ for _, m := range imported.Media {
+ key := strings.ToLower(cleanManifestRel(m.Path))
+ if importedLiveSegPaths[key] {
+ continue
+ }
+ if !have[key] {
+ out.Media = append(out.Media, m)
+ have[key] = true
+ }
+ }
+
+ // Video parts: by page; local wins, filling empty supplemented fields.
+ pageIdx := map[int]int{}
+ for i, p := range out.Parts {
+ pageIdx[p.Page] = i
+ }
+ for _, p := range imported.Parts {
+ if idx, exists := pageIdx[p.Page]; !exists {
+ p.Subtitles = append([]string(nil), p.Subtitles...)
+ pageIdx[p.Page] = len(out.Parts)
+ out.Parts = append(out.Parts, p)
+ } else {
+ cur := &out.Parts[idx]
+ if cur.File == "" {
+ cur.File = p.File
+ }
+ if cur.Danmaku == "" {
+ cur.Danmaku = p.Danmaku
+ }
+ if cur.Audio.SavedAs == "" && p.Audio.SavedAs != "" {
+ cur.Audio.SavedAs = p.Audio.SavedAs
+ }
+ if len(p.Subtitles) > 0 {
+ subSeen := map[string]bool{}
+ for _, s := range cur.Subtitles {
+ subSeen[strings.ToLower(cleanManifestRel(s))] = true
+ }
+ for _, s := range p.Subtitles {
+ k := strings.ToLower(cleanManifestRel(s))
+ if k != "" && !subSeen[k] {
+ subSeen[k] = true
+ cur.Subtitles = append(cur.Subtitles, s)
+ }
+ }
+ }
+ }
+ }
+ sort.SliceStable(out.Parts, func(i, j int) bool { return out.Parts[i].Page < out.Parts[j].Page })
+
+ for _, pg := range imported.ExpectedPages {
+ if !containsInt(out.ExpectedPages, pg) {
+ out.ExpectedPages = append(out.ExpectedPages, pg)
+ }
+ }
+ sort.Ints(out.ExpectedPages)
+
+ // NotePages: supplement empty fields on existing pages, then append any extra pages.
+ for i := 0; i < len(out.NotePages) && i < len(imported.NotePages); i++ {
+ dst, src := &out.NotePages[i], imported.NotePages[i]
+ if dst.Image == "" {
+ dst.Image = src.Image
+ }
+ if dst.Cover == "" {
+ dst.Cover = src.Cover
+ }
+ if dst.Motion == "" {
+ dst.Motion = src.Motion
+ }
+ if dst.Video == "" {
+ dst.Video = src.Video
+ }
+ if dst.VideoInfo == nil && src.VideoInfo != nil {
+ vi := *src.VideoInfo
+ dst.VideoInfo = &vi
+ }
+ }
+ if len(out.NotePages) < len(imported.NotePages) {
+ for _, np := range imported.NotePages[len(out.NotePages):] {
+ if np.VideoInfo != nil {
+ vi := *np.VideoInfo
+ np.VideoInfo = &vi
+ }
+ out.NotePages = append(out.NotePages, np)
+ }
+ }
+
+ if out.DouyinVideo == nil && imported.DouyinVideo != nil {
+ dv := *imported.DouyinVideo
+ out.DouyinVideo = &dv
+ }
+ if out.Music == nil && imported.Music != nil {
+ mu := *imported.Music
+ out.Music = &mu
+ } else if out.Music != nil && imported.Music != nil {
+ if out.Music.File == "" {
+ out.Music.File = imported.Music.File
+ }
+ if out.Music.Cover == "" {
+ out.Music.Cover = imported.Music.Cover
+ }
+ if out.Music.Title == "" {
+ out.Music.Title = imported.Music.Title
+ }
+ if out.Music.Author == "" {
+ out.Music.Author = imported.Music.Author
+ }
+ }
+ if out.CachedBy == nil && imported.CachedBy != nil {
+ cb := *imported.CachedBy
+ out.CachedBy = &cb
+ }
+ if out.Via == nil && imported.Via != nil {
+ v := *imported.Via
+ out.Via = &v
+ }
+
+ var renames []SegmentRename
+ if imported.Live != nil {
+ if out.Live == nil {
+ lv := *imported.Live
+ lv.Segments = append([]LiveSegmentInfo(nil), lv.Segments...)
+ lv.Incidents = append([]LiveIncident(nil), lv.Incidents...)
+ out.Live = &lv
+ } else {
+ lv := *out.Live
+ lv.Segments = append([]LiveSegmentInfo(nil), lv.Segments...)
+ lv.Incidents = append([]LiveIncident(nil), lv.Incidents...)
+ byName := map[string]LiveSegmentInfo{}
+ byContent := map[string]bool{}
+ next := 0
+ for _, seg := range lv.Segments {
+ byName[strings.ToLower(seg.File)] = seg
+ if seg.SHA256 != "" {
+ byContent[strings.ToLower(seg.SHA256)+"|"+strconv.FormatInt(seg.Bytes, 10)] = true
+ }
+ next = max(next, livePartNumber(seg.File))
+ }
+ for _, m := range out.Media {
+ next = max(next, livePartNumber(m.Path))
+ }
+ importedMediaByPath := map[string]MediaFile{}
+ for _, m := range imported.Media {
+ importedMediaByPath[strings.ToLower(cleanManifestRel(m.Path))] = m
+ }
+
+ renamed := map[string]string{}
+ needSeq := false
+ for _, seg := range imported.Live.Segments {
+ origFile := seg.File
+ keyName := strings.ToLower(origFile)
+ contentKey := ""
+ if seg.SHA256 != "" {
+ contentKey = strings.ToLower(seg.SHA256) + "|" + strconv.FormatInt(seg.Bytes, 10)
+ }
+ cur, taken := byName[keyName]
+ switch {
+ case contentKey != "" && byContent[contentKey]:
+ // Already present locally (under same or earlier merged name).
+ continue
+ case taken && (sameSegment(cur, seg) || (sameContent != nil && sameContent(origFile))):
+ // Already present locally under the same name.
+ continue
+ case taken && mode == MergeKeepLocal:
+ // The local file stays; the conflicting imported segment is not taken.
+ continue
+ case taken || needSeq:
+ // Two installations numbered from 001: append sequentially after local max.
+ needSeq = true
+ ext := filepath.Ext(origFile)
+ if m := livePartName.FindStringSubmatch(origFile); m != nil {
+ ext = m[2]
+ }
+ next++
+ to := fmt.Sprintf("part-%03d%s", next, ext)
+ if !strings.EqualFold(origFile, to) {
+ renamed[origFile] = to
+ renames = append(renames, SegmentRename{From: origFile, To: to})
+ }
+ seg.File = to
+ default:
+ // Non-conflicting supplement or gap fill: keep original filename.
+ next = max(next, livePartNumber(origFile))
+ }
+
+ lv.Segments = append(lv.Segments, seg)
+ byName[strings.ToLower(seg.File)] = seg
+ if contentKey != "" {
+ byContent[contentKey] = true
+ }
+ if !have[strings.ToLower(cleanManifestRel(seg.File))] {
+ if m, ok := importedMediaByPath[strings.ToLower(cleanManifestRel(origFile))]; ok {
+ m.Path = seg.File
+ out.Media = append(out.Media, m)
+ } else {
+ out.Media = append(out.Media, MediaFile{
+ Role: "live_segment",
+ Path: seg.File,
+ Bytes: seg.Bytes,
+ SHA256: seg.SHA256,
+ })
+ }
+ have[strings.ToLower(cleanManifestRel(seg.File))] = true
+ }
+ }
+
+ seen := map[string]bool{}
+ for _, in := range lv.Incidents {
+ seen[incidentKey(in)] = true
+ }
+ for _, in := range imported.Live.Incidents {
+ if to, ok := renamed[in.Part]; ok {
+ in.Part = to
+ }
+ if !seen[incidentKey(in)] && len(lv.Incidents) < MaxLiveIncidentsPerSession {
+ lv.Incidents = append(lv.Incidents, in)
+ seen[incidentKey(in)] = true
+ }
+ }
+ if lv.EndedAt == "" || (imported.Live.EndedAt != "" && imported.Live.EndedAt > lv.EndedAt) {
+ lv.EndedAt, lv.EndTitle, lv.StopReason = imported.Live.EndedAt, firstNonEmptyString(imported.Live.EndTitle, lv.EndTitle), firstNonEmptyString(imported.Live.StopReason, lv.StopReason)
+ }
+ if imported.Live.StartedAt != "" && (lv.StartedAt == "" || imported.Live.StartedAt < lv.StartedAt) {
+ lv.StartedAt = imported.Live.StartedAt
+ }
+ lv.PendingFile, lv.PendingBytes, lv.PendingDuration = "", 0, 0
+ out.Live = &lv
+ }
+ }
+ out.PendingParts = nil
+ return out, renames
+}
+
+func sameSegment(a, b LiveSegmentInfo) bool {
+ return a.SHA256 != "" && strings.EqualFold(a.SHA256, b.SHA256) && a.Bytes == b.Bytes
+}
+
+func incidentKey(in LiveIncident) string {
+ return in.Kind + "|" + in.At + "|" + in.Part
+}
+
+func livePartNumber(name string) int {
+ m := livePartName.FindStringSubmatch(filepath.Base(name))
+ if m == nil {
+ return 0
+ }
+ n, _ := strconv.Atoi(m[1])
+ return n
+}
+
+func containsInt(list []int, v int) bool {
+ for _, x := range list {
+ if x == v {
+ return true
+ }
+ }
+ return false
+}
+
+func firstNonEmptyString(vals ...string) string {
+ for _, v := range vals {
+ if strings.TrimSpace(v) != "" {
+ return v
+ }
+ }
+ return ""
+}
+
+// PortableManifest is item.json as it goes into an export folder or the
+// cloud: the runtime fields of this installation (the item folder's
+// absolute path, the index key, the computed size) are left out.
+func PortableManifest(meta ItemMetadata) ([]byte, error) {
+ meta.ItemDir, meta.ItemKey, meta.RawID, meta.TotalBytes = "", "", "", 0
+ raw, err := json.MarshalIndent(meta, "", " ")
+ if err != nil {
+ return nil, err
+ }
+ return append(raw, '\n'), nil
+}
+
+// UnsafeManifestPaths lists the registered paths of meta that are absolute,
+// contain forbidden characters (\, :, \x00), or contain '.'/'..' segments;
+// such a manifest is never imported (OS-independent).
+func UnsafeManifestPaths(meta ItemMetadata) []string {
+ var bad []string
+ visitManifestFiles(meta, func(f ManifestFile) {
+ rel := strings.TrimSpace(f.Path)
+ if rel == "" {
+ return
+ }
+ if strings.ContainsAny(rel, "\\:\x00") || strings.HasPrefix(rel, "/") || filepath.IsAbs(rel) || filepath.VolumeName(rel) != "" {
+ bad = append(bad, rel)
+ return
+ }
+ for _, seg := range strings.Split(rel, "/") {
+ if seg == "" || seg == "." || seg == ".." {
+ bad = append(bad, rel)
+ return
+ }
+ }
+ })
+ return bad
+}
+
+// KeepListedFiles drops from meta every registered file keep rejects (files
+// an import could not verify) and records each in Missing, so the item is
+// partial rather than missing files; a later import adds them back. It
+// returns the dropped paths.
+func KeepListedFiles(meta ItemMetadata, keep func(rel string) bool) (ItemMetadata, []string) {
+ meta = cloneItemMetadataSlices(meta)
+ var dropped []string
+ ok := func(rel string) bool {
+ rel = strings.TrimSpace(rel)
+ if rel == "" || keep(cleanManifestRel(filepath.ToSlash(rel))) {
+ return true
+ }
+ dropped = append(dropped, cleanManifestRel(filepath.ToSlash(rel)))
+ return false
+ }
+ var media []MediaFile
+ for _, m := range meta.Media {
+ if !ok(m.Path) {
+ continue
+ }
+ if !ok(m.Motion) {
+ m.Motion = ""
+ }
+ media = append(media, m)
+ }
+ meta.Media = media
+ var parts []VideoPartRecord
+ for _, p := range meta.Parts {
+ if !ok(p.File) {
+ continue
+ }
+ if !ok(p.Danmaku) {
+ p.Danmaku = ""
+ }
+ if !ok(p.Audio.SavedAs) {
+ p.Audio.SavedAs = ""
+ }
+ var subs []string
+ for _, s := range p.Subtitles {
+ if ok(s) {
+ subs = append(subs, s)
+ }
+ }
+ p.Subtitles = subs
+ parts = append(parts, p)
+ }
+ meta.Parts = parts
+ if meta.DouyinVideo != nil && !ok(meta.DouyinVideo.File) {
+ meta.DouyinVideo = nil
+ }
+ for i := range meta.NotePages {
+ np := &meta.NotePages[i]
+ if !ok(np.Image) {
+ np.Image = ""
+ }
+ if !ok(np.Cover) {
+ np.Cover = ""
+ }
+ if !ok(np.Motion) {
+ np.Motion = ""
+ }
+ if !ok(np.Video) {
+ np.Video = ""
+ }
+ if np.VideoInfo != nil && !ok(np.VideoInfo.File) {
+ np.VideoInfo = nil
+ }
+ }
+ if meta.Music != nil {
+ if !ok(meta.Music.File) {
+ meta.Music.File = ""
+ }
+ if !ok(meta.Music.Cover) {
+ meta.Music.Cover = ""
+ }
+ }
+ if meta.Live != nil {
+ lv := *meta.Live
+ var segs []LiveSegmentInfo
+ for _, s := range lv.Segments {
+ if ok(s.File) {
+ segs = append(segs, s)
+ }
+ }
+ lv.Segments = segs
+ meta.Live = &lv
+ }
+ seen := map[string]bool{}
+ for _, d := range dropped {
+ if seen[d] {
+ continue
+ }
+ seen[d] = true
+ meta.Missing = append(meta.Missing, MissingRecord{Item: d, Reason: "导入时缺失或校验不符,下次导入补上"})
+ }
+ return meta, dropped
+}
diff --git a/internal/library/migration.go b/internal/library/migration.go
index bd31b44..e76a454 100644
--- a/internal/library/migration.go
+++ b/internal/library/migration.go
@@ -1,12 +1,16 @@
package library
import (
+ "crypto/sha256"
+ "encoding/hex"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
+
+ "github.com/chialecode/trace/internal/storage"
)
func (s *Store) moveRegisteredCache(newDir string, persist func() error) (RebuildReport, error) {
@@ -27,7 +31,7 @@ func (s *Store) moveRegisteredCache(newDir string, persist func() error) (Rebuil
if err != nil {
return RebuildReport{}, err
}
- if strings.EqualFold(oldDir, newDir) {
+ if samePath(oldDir, newDir) {
if persist != nil {
if err := persist(); err != nil {
return RebuildReport{}, err
@@ -35,7 +39,14 @@ func (s *Store) moveRegisteredCache(newDir string, persist func() error) (Rebuil
}
return s.RebuildIndex()
}
- var originals, copies []string
+
+ type migratedItem struct {
+ itemKey string
+ itemDir string
+ files []string
+ }
+ var migrated []migratedItem
+ var copies []string
rollback := func() {
for _, path := range copies {
_ = os.Remove(path)
@@ -46,6 +57,7 @@ func (s *Store) moveRegisteredCache(newDir string, persist func() error) (Rebuil
}
}
}
+
for _, item := range items {
if _, err := EnsureWithinRoot(oldDir, item.ItemDir); err != nil {
continue
@@ -68,17 +80,28 @@ func (s *Store) moveRegisteredCache(newDir string, persist func() error) (Rebuil
rollback()
return RebuildReport{}, err
}
+
+ // Map expected SHA-256 digests from the manifest for verification during copy.
+ expectedSHA := map[string]string{}
+ for _, mf := range RegisteredFiles(item) {
+ if mf.SHA256 != "" {
+ expectedSHA[strings.ToLower(mf.Path)] = mf.SHA256
+ }
+ }
+
registered, _ := collectRegisteredAndUserFiles(item)
+ var origForItem []string
for _, source := range registered {
if _, err := os.Lstat(source); os.IsNotExist(err) {
continue
}
rel, err := filepath.Rel(item.ItemDir, source)
- if err != nil || !safeRegisteredPath(item.ItemDir, filepath.ToSlash(rel)) {
+ relSlash := filepath.ToSlash(rel)
+ if err != nil || !safeRegisteredPathStrict(item.ItemDir, relSlash) {
rollback()
return RebuildReport{}, fmt.Errorf("library: 迁移文件路径无效")
}
- dest, err := ResolveItemPath(destDir, filepath.ToSlash(rel))
+ dest, err := ResolveItemPath(destDir, relSlash)
if err != nil {
rollback()
return RebuildReport{}, err
@@ -87,27 +110,22 @@ func (s *Store) moveRegisteredCache(newDir string, persist func() error) (Rebuil
rollback()
return RebuildReport{}, err
}
- input, err := os.Open(source)
- if err != nil {
+ if _, err := os.Lstat(dest); err == nil {
rollback()
- return RebuildReport{}, err
+ return RebuildReport{}, fmt.Errorf("library: 目标文件已存在: %s", dest)
}
- output, err := os.OpenFile(dest, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
- if err != nil {
- input.Close()
+ if err := copyFileAtomicVerified(source, dest, expectedSHA[strings.ToLower(cleanManifestRel(relSlash))]); err != nil {
rollback()
return RebuildReport{}, err
}
copies = append(copies, dest)
- _, copyErr := io.Copy(output, input)
- err = errors.Join(copyErr, input.Close(), output.Sync(), output.Close())
- if err != nil {
- rollback()
- return RebuildReport{}, err
- }
- originals = append(originals, source)
+ origForItem = append(origForItem, source)
+ }
+ if len(origForItem) > 0 {
+ migrated = append(migrated, migratedItem{itemKey: item.ItemKey, itemDir: item.ItemDir, files: origForItem})
}
}
+
if err := s.ChangeCacheDir(newDir, persist); err != nil {
rollback()
return RebuildReport{}, err
@@ -116,15 +134,82 @@ func (s *Store) moveRegisteredCache(newDir string, persist func() error) (Rebuil
if err != nil {
return report, err
} // Original files remain recoverable on any indexing failure.
- for _, path := range originals {
- if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
- return report, err
+
+ // Clean up migrated originals; never abort mid-way, record any locked files
+ // into pending-deletes.json so they are cleaned on next startup.
+ var removeErrs []error
+ var leftover []pendingDeleteRecord
+ for _, mi := range migrated {
+ var failedFiles []string
+ for _, path := range mi.files {
+ if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
+ failedFiles = append(failedFiles, path)
+ removeErrs = append(removeErrs, err)
+ }
}
+ if len(failedFiles) > 0 {
+ leftover = append(leftover, pendingDeleteRecord{
+ ItemKey: mi.itemKey + ":migrated",
+ ItemDir: mi.itemDir,
+ RegisteredFiles: failedFiles,
+ })
+ }
+ removeEmptyDirsBottomUp(mi.itemDir)
+ removeEmptyAuthorDirs(mi.itemDir, []string{oldDir})
}
- for _, item := range items {
- if _, err := EnsureWithinRoot(oldDir, item.ItemDir); err == nil {
- removeEmptyDirsBottomUp(item.ItemDir)
+ if len(leftover) > 0 {
+ s.mu.Lock()
+ if existing, rErr := s.readPendingDeletesLocked(); rErr == nil {
+ _ = s.writePendingDeletesLocked(append(existing, leftover...))
}
+ s.mu.Unlock()
+ }
+ if len(removeErrs) > 0 {
+ return report, errors.Join(removeErrs...)
}
return report, nil
}
+
+func copyFileAtomicVerified(src, dst, wantSHA string) error {
+ input, err := os.Open(src)
+ if err != nil {
+ return err
+ }
+ defer input.Close()
+
+ tmp := storage.TempSiblingPath(dst)
+ output, err := os.OpenFile(tmp, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
+ if err != nil {
+ return err
+ }
+ cleanupTmp := func() {
+ _ = output.Close()
+ _ = os.Remove(tmp)
+ }
+
+ h := sha256.New()
+ if _, err := io.Copy(io.MultiWriter(output, h), input); err != nil {
+ cleanupTmp()
+ return err
+ }
+ if err := output.Sync(); err != nil {
+ cleanupTmp()
+ return err
+ }
+ if err := output.Close(); err != nil {
+ _ = os.Remove(tmp)
+ return err
+ }
+ if wantSHA != "" {
+ gotSHA := hex.EncodeToString(h.Sum(nil))
+ if !strings.EqualFold(gotSHA, wantSHA) {
+ _ = os.Remove(tmp)
+ return fmt.Errorf("library: 迁移校验和不一致 (%s)", filepath.Base(dst))
+ }
+ }
+ if err := os.Rename(tmp, dst); err != nil {
+ _ = os.Remove(tmp)
+ return err
+ }
+ return nil
+}
diff --git a/internal/library/node.go b/internal/library/node.go
new file mode 100644
index 0000000..20ce2c2
--- /dev/null
+++ b/internal/library/node.go
@@ -0,0 +1,93 @@
+package library
+
+import (
+ "crypto/rand"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/chialecode/trace/internal/storage"
+)
+
+// NodeFileName is the file in the data directory that holds this
+// installation's node ID (docs/design/remote.md §6.1, §8).
+const NodeFileName = "node.json"
+
+type nodeFile struct {
+ Version int `json:"version"`
+ Node string `json:"node"`
+ Name string `json:"name,omitempty"`
+ CreatedAt string `json:"createdAt"`
+}
+
+// LoadOrCreateNode returns the node of dataDir, creating node.json with a
+// random ID the first time. The ID never changes afterwards; name is used
+// when the file has none (a name given later wins over the computer's name).
+func LoadOrCreateNode(dataDir, name string) (ItemNode, error) {
+ path := filepath.Join(dataDir, NodeFileName)
+ raw, err := os.ReadFile(path)
+ if err == nil {
+ var f nodeFile
+ if jErr := json.Unmarshal(raw, &f); jErr == nil && validNodeID(f.Node) {
+ changed := false
+ if strings.TrimSpace(name) != "" && f.Name != strings.TrimSpace(name) {
+ f.Name = strings.TrimSpace(name)
+ changed = true
+ }
+ if changed {
+ _ = storage.WriteJSONAtomic(path, f, 0o600)
+ }
+ return ItemNode{Node: f.Node, Name: f.Name}, nil
+ }
+ if _, bErr := storage.BackupCorruptFile(path); bErr != nil {
+ return ItemNode{}, bErr
+ }
+ } else if !errors.Is(err, os.ErrNotExist) {
+ return ItemNode{}, err
+ }
+ var rnd [16]byte
+ if _, err := rand.Read(rnd[:]); err != nil {
+ return ItemNode{}, fmt.Errorf("library: node id: %w", err)
+ }
+ f := nodeFile{Version: 1, Node: hex.EncodeToString(rnd[:]), Name: strings.TrimSpace(name), CreatedAt: time.Now().UTC().Format(time.RFC3339)}
+ if err := storage.WriteJSONAtomic(path, f, 0o600); err != nil {
+ return ItemNode{}, err
+ }
+ return ItemNode{Node: f.Node, Name: f.Name}, nil
+}
+
+func validNodeID(id string) bool {
+ if len(id) != 32 {
+ return false
+ }
+ _, err := hex.DecodeString(id)
+ return err == nil
+}
+
+// SetNode makes every item saved from now on without a CachedBy record
+// this installation as the one that cached it.
+func (s *Store) SetNode(node ItemNode) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if node.Node == "" {
+ s.node = nil
+ return
+ }
+ n := node
+ s.node = &n
+}
+
+// Node is the installation set with SetNode, or the zero value.
+func (s *Store) Node() ItemNode {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ if s.node == nil {
+ return ItemNode{}
+ }
+ return *s.node
+}
diff --git a/internal/library/paths.go b/internal/library/paths.go
new file mode 100644
index 0000000..f964e60
--- /dev/null
+++ b/internal/library/paths.go
@@ -0,0 +1,251 @@
+package library
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "sync"
+ "time"
+)
+
+// samePath compares two cleaned filesystem paths using the OS's case sensitivity.
+func samePath(a, b string) bool {
+ ca, cb := filepath.Clean(a), filepath.Clean(b)
+ if runtime.GOOS == "windows" {
+ return strings.EqualFold(ca, cb)
+ }
+ return ca == cb
+}
+
+// pathKey returns a canonical map key for a filesystem path.
+func pathKey(p string) string {
+ c := filepath.Clean(p)
+ if runtime.GOOS == "windows" {
+ return strings.ToLower(c)
+ }
+ return c
+}
+
+// IsLinkLike reports symlinks and other reparse points. Since Go 1.23 a
+// Windows directory junction reports ModeIrregular instead of ModeSymlink.
+func IsLinkLike(mode os.FileMode) bool {
+ return mode&(os.ModeSymlink|os.ModeIrregular) != 0
+}
+
+func isLinkLike(mode os.FileMode) bool {
+ return IsLinkLike(mode)
+}
+
+// verifiedDirTTL is how long an ancestor directory found free of links is
+// trusted by the read path (safeRegisteredPathRead). Showing a screen of
+// thumbnails resolves dozens of files under the same ancestors; walking every
+// ancestor with EvalSymlinks for each file made a page take seconds (DEC-057).
+// The item directory itself, the leaf file, and all write/delete/migration/scan
+// paths always check in full without using this cache (data-and-cache.md §3).
+const verifiedDirTTL = 3 * time.Second
+
+var verifiedDirs sync.Map // pathKey(dir) -> time.Time verified
+
+func checkSingleDirLink(current string) (exists bool, err error) {
+ info, err := os.Lstat(current)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return false, nil
+ }
+ return false, err
+ }
+ if isLinkLike(info.Mode()) || !info.IsDir() {
+ return true, fmt.Errorf("library: 保存位置含链接或非目录节点")
+ }
+ // EvalSymlinks also expands 8.3 short names (RUNNER~1), which are not links:
+ // compare with the long form of the path.
+ resolved, err := filepath.EvalSymlinks(current)
+ if err != nil || !samePath(resolved, longPathName(current)) {
+ return true, fmt.Errorf("library: 保存位置含目录联接")
+ }
+ return true, nil
+}
+
+func checkDirectoryLinks(dir string, useRecentCache bool) error {
+ now := time.Now()
+ var walked []string
+ for current := filepath.Clean(dir); ; current = filepath.Dir(current) {
+ key := pathKey(current)
+ if useRecentCache {
+ if at, ok := verifiedDirs.Load(key); ok && now.Sub(at.(time.Time)) < verifiedDirTTL {
+ break
+ }
+ }
+ exists, err := checkSingleDirLink(current)
+ if err != nil {
+ return err
+ }
+ if exists && useRecentCache {
+ walked = append(walked, key)
+ }
+ if filepath.Dir(current) == current {
+ break
+ }
+ }
+ for _, key := range walked {
+ verifiedDirs.Store(key, now)
+ }
+ return nil
+}
+
+// RejectDirectoryLinks verifies that dir and all of its existing ancestors are
+// real directories (no symlinks or Windows directory junctions).
+func RejectDirectoryLinks(dir string) error {
+ return checkDirectoryLinks(dir, false)
+}
+
+func rejectDirectoryLinks(dir string) error {
+ return checkDirectoryLinks(dir, false)
+}
+
+func rejectDirectoryLinksRecent(dir string) error {
+ return checkDirectoryLinks(dir, true)
+}
+
+func safeRegisteredPathChecked(root, rel string, allowAncestorCache bool) bool {
+ root = filepath.Clean(root)
+ if allowAncestorCache {
+ // Cache only ancestors strictly above root; always check root itself
+ // and every relative segment fresh (data-and-cache.md §3).
+ parent := filepath.Dir(root)
+ if parent != root {
+ if rejectDirectoryLinksRecent(parent) != nil {
+ return false
+ }
+ }
+ if exists, err := checkSingleDirLink(root); err != nil || !exists {
+ return false
+ }
+ } else {
+ if rejectDirectoryLinks(root) != nil {
+ return false
+ }
+ }
+ if rel == "" || filepath.IsAbs(rel) || strings.ContainsAny(rel, "\\:\x00") {
+ return false
+ }
+ current := root
+ for _, part := range strings.Split(rel, "/") {
+ if part == "" || part == "." || part == ".." {
+ return false
+ }
+ current = filepath.Join(current, part)
+ info, err := os.Lstat(current)
+ if err != nil {
+ if os.IsNotExist(err) {
+ continue
+ }
+ return false
+ }
+ if isLinkLike(info.Mode()) {
+ return false
+ }
+ }
+ info, err := os.Lstat(root)
+ return err == nil && info.IsDir() && !isLinkLike(info.Mode())
+}
+
+// safeRegisteredPathStrict checks root, all ancestors, and all segments without
+// any TTL cache. Used for all write, delete, migration, and transfer paths.
+func safeRegisteredPathStrict(root, rel string) bool {
+ return safeRegisteredPathChecked(root, rel, false)
+}
+
+// safeRegisteredPathRead caches ancestor directories strictly above root for
+// verifiedDirTTL while always checking root and every relative segment fresh.
+func safeRegisteredPathRead(root, rel string) bool {
+ return safeRegisteredPathChecked(root, rel, true)
+}
+
+// ResolveItemPath validates an item-relative path strictly (no ancestor cache)
+// before a registered file is written, renamed, or removed (INV-08). The final
+// file may be absent, but any symlink or junction is rejected.
+func ResolveItemPath(root, rel string) (string, error) {
+ if !safeRegisteredPathStrict(root, rel) {
+ return "", fmt.Errorf("library: unsafe item-relative path")
+ }
+ return EnsureWithinRoot(root, filepath.Join(root, filepath.FromSlash(rel)))
+}
+
+func resolveItemPathRead(root, rel string) (string, error) {
+ if !safeRegisteredPathRead(root, rel) {
+ return "", fmt.Errorf("library: unsafe item-relative path")
+ }
+ return EnsureWithinRoot(root, filepath.Join(root, filepath.FromSlash(rel)))
+}
+
+// MediaPath resolves and validates a whitelisted media file path belonging to key (INV-08).
+// It rejects '.', '..', backslashes, colons, null bytes, unregistered filenames, and symlinks/junctions.
+func (s *Store) MediaPath(key, relPath string) (string, error) {
+ relPath = strings.TrimSpace(relPath)
+ if relPath == "" {
+ return "", fmt.Errorf("library: empty relative media path")
+ }
+ if strings.ContainsRune(relPath, 0) || strings.ContainsRune(relPath, '\\') || strings.ContainsRune(relPath, ':') {
+ return "", fmt.Errorf("library: forbidden characters in media path")
+ }
+ if filepath.IsAbs(relPath) || strings.HasPrefix(relPath, "/") {
+ return "", fmt.Errorf("library: media path must be relative")
+ }
+ segments := strings.Split(relPath, "/")
+ for _, seg := range segments {
+ if seg == "" || seg == "." || seg == ".." {
+ return "", fmt.Errorf("library: invalid segment %q in media path", seg)
+ }
+ }
+
+ meta, ok, err := s.GetItem(key)
+ if err != nil {
+ return "", err
+ }
+ if !ok || meta.ItemDir == "" {
+ return "", fmt.Errorf("library: item %q not found", key)
+ }
+
+ normRel := filepath.ToSlash(filepath.Clean(filepath.FromSlash(relPath)))
+ if !isRegisteredInManifest(meta, normRel) {
+ return "", fmt.Errorf("library: file %q is not registered in item %q manifest", relPath, key)
+ }
+
+ fullPath, err := EnsureWithinRoot(meta.ItemDir, filepath.Join(meta.ItemDir, filepath.FromSlash(normRel)))
+ if err != nil {
+ return "", err
+ }
+
+ if !safeRegisteredPathRead(meta.ItemDir, relPath) {
+ return "", fmt.Errorf("library: media path contains a link or invalid segment")
+ }
+
+ // Check Lstat on meta.ItemDir and fullPath and EvalSymlinks to reject symlinks/junctions.
+ dirInfo, err := os.Lstat(meta.ItemDir)
+ if err != nil {
+ return "", err
+ }
+ if isLinkLike(dirInfo.Mode()) {
+ return "", fmt.Errorf("library: item directory is a symlink")
+ }
+ fileInfo, err := os.Lstat(fullPath)
+ if err != nil {
+ return "", err
+ }
+ if isLinkLike(fileInfo.Mode()) || fileInfo.IsDir() {
+ return "", fmt.Errorf("library: media target is a symlink or directory")
+ }
+
+ evalRoot, err1 := filepath.EvalSymlinks(meta.ItemDir)
+ evalTarget, err2 := filepath.EvalSymlinks(fullPath)
+ if err1 != nil || err2 != nil {
+ return "", fmt.Errorf("library: symlink evaluation failed")
+ }
+ if _, err := EnsureWithinRoot(evalRoot, evalTarget); err != nil {
+ return "", fmt.Errorf("library: symlink target escapes item directory")
+ }
+ return fullPath, nil
+}
diff --git a/internal/library/rebuild.go b/internal/library/rebuild.go
new file mode 100644
index 0000000..44dcd47
--- /dev/null
+++ b/internal/library/rebuild.go
@@ -0,0 +1,343 @@
+package library
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/chialecode/trace/internal/storage"
+)
+
+// RebuildIndex walks all registered library roots for item.json files, backs up corrupt files,
+// checks media file integrity (including hashes), and rebuilds the SQLite library_items index.
+func (s *Store) RebuildIndex() (RebuildReport, error) {
+ return s.rebuildIndex(true)
+}
+
+// RefreshIndex is the media library's "刷新": the same scan as RebuildIndex,
+// but files are only checked for presence and size (no hashing), so it stays
+// quick on large libraries. The report lists what changed on disk.
+func (s *Store) RefreshIndex() (RebuildReport, error) {
+ return s.rebuildIndex(false)
+}
+
+type indexedItem struct {
+ site, kind, title, status, itemDir string
+}
+
+func (s *Store) indexedItemsLocked() (map[string]indexedItem, error) {
+ rows, err := s.db.Query(`SELECT item_key, site, kind, title, status, item_dir FROM library_items`)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ out := make(map[string]indexedItem)
+ for rows.Next() {
+ var key string
+ var it indexedItem
+ if err := rows.Scan(&key, &it.site, &it.kind, &it.title, &it.status, &it.itemDir); err != nil {
+ return nil, err
+ }
+ out[key] = it
+ }
+ return out, rows.Err()
+}
+
+func (s *Store) rebuildIndex(checkHash bool) (RebuildReport, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ var report RebuildReport
+ previous, err := s.indexedItemsLocked()
+ if err != nil {
+ return report, err
+ }
+ roots := s.allRootsLocked()
+ if err := os.MkdirAll(s.cacheDir, 0o700); err != nil {
+ return report, err
+ }
+
+ pendingMap := make(map[string]bool)
+ pending, err := s.readPendingDeletesLocked()
+ if err != nil {
+ return report, err
+ }
+ for _, p := range pending {
+ pendingMap[p.ItemKey] = true
+ }
+
+ seenKeys := make(map[string]bool)
+ var discovered []ItemMetadata
+ for _, root := range roots {
+ if _, err := os.Stat(root); err != nil {
+ return report, err
+ }
+ if err := rejectDirectoryLinks(root); err != nil {
+ return report, err
+ }
+ err := filepath.WalkDir(root, func(path string, d fs.DirEntry, walkErr error) error {
+ if walkErr != nil {
+ return walkErr
+ }
+ // Never follow symlinks or Windows directory junctions (INV-08).
+ if isLinkLike(d.Type()) {
+ if d.IsDir() {
+ return filepath.SkipDir
+ }
+ return nil
+ }
+ if d.IsDir() {
+ return nil
+ }
+ if !strings.EqualFold(d.Name(), "item.json") {
+ return nil
+ }
+ if report.Scanned >= 100000 {
+ return fmt.Errorf("library: 清单扫描超过单轮上限,索引清理未执行")
+ }
+ report.Scanned++
+
+ raw, rErr := os.ReadFile(path)
+ if rErr != nil {
+ return rErr
+ }
+ meta, pErr := ParseItemMetadata(raw)
+ if pErr != nil {
+ backup, bErr := storage.BackupCorruptFile(path)
+ if bErr == nil && backup != "" {
+ report.CorruptBackedUp = append(report.CorruptBackedUp, backup)
+ }
+ return bErr
+ }
+ if pendingMap[meta.ItemKey] || seenKeys[meta.ItemKey] {
+ return nil
+ }
+
+ itemDir := filepath.Dir(path)
+ if _, err := EnsureWithinRoot(root, itemDir); err != nil {
+ return err
+ }
+ meta.ItemDir = filepath.Clean(itemDir)
+ missing, totalBytes, missingPaths := verifyItemFilesDetail(meta.ItemDir, &meta, checkHash)
+ meta.TotalBytes = totalBytes
+ if missing && meta.Status != "recording" && meta.Status != "failed" && meta.Status != "partial" {
+ if prev, ok := previous[meta.ItemKey]; ok && prev.status != "missing_files" {
+ report.NewlyMissing = append(report.NewlyMissing, ChangedItem{ItemKey: meta.ItemKey, Site: meta.Site, Kind: meta.Kind, Title: meta.Title, ItemDir: meta.ItemDir, Files: missingPaths})
+ }
+ meta.Status = "missing_files"
+ report.MissingFiles++
+ if err := storage.WriteJSONAtomic(path, meta, 0o600); err != nil {
+ return err
+ }
+ } else if meta.Status == "missing_files" && !missing {
+ meta.Status = "complete"
+ if err := storage.WriteJSONAtomic(path, meta, 0o600); err != nil {
+ return err
+ }
+ }
+
+ discovered = append(discovered, meta)
+ seenKeys[meta.ItemKey] = true
+ report.Indexed++
+ return nil
+ })
+ if err != nil {
+ return report, err
+ }
+ }
+
+ var stale []string
+ for k, prev := range previous {
+ if !seenKeys[k] {
+ stale = append(stale, k)
+ if !pendingMap[k] {
+ report.Removed = append(report.Removed, ChangedItem{ItemKey: k, Site: prev.site, Kind: prev.kind, Title: prev.title, ItemDir: prev.itemDir})
+ }
+ }
+ }
+
+ tx, err := s.db.Begin()
+ if err != nil {
+ return report, err
+ }
+ defer tx.Rollback()
+ for _, meta := range discovered {
+ if err := upsertItemRowTx(tx, meta); err != nil {
+ return report, err
+ }
+ }
+ for _, k := range stale {
+ if _, err := tx.Exec(`DELETE FROM library_items WHERE item_key = ?`, k); err != nil {
+ return report, err
+ }
+ if _, err := tx.Exec(`DELETE FROM item_refs WHERE from_key = ? OR to_key = ?`, k, k); err != nil {
+ return report, err
+ }
+ if _, err := tx.Exec(`UPDATE feed_items SET cached = 0, cache_status = '', item_key = '' WHERE item_key = ?`, k); err != nil {
+ return report, err
+ }
+ }
+ return report, tx.Commit()
+}
+
+// AddLibraryRoot scans an existing cache folder (including bilibili/* and douyin/*/{works,lives}/*)
+// or legacy trace-data folder containing library/, and indexes its items without moving files
+// or overwriting existing keys (FR-LIB-006).
+func (s *Store) AddLibraryRoot(selectedDir string) (AddRootReport, error) {
+ if strings.TrimSpace(selectedDir) == "" || !filepath.IsAbs(selectedDir) {
+ return AddRootReport{}, fmt.Errorf("library: folder path cannot be empty")
+ }
+ selectedDir = filepath.Clean(selectedDir)
+ info, err := os.Lstat(selectedDir)
+ if err != nil {
+ return AddRootReport{}, fmt.Errorf("library: stat folder: %w", err)
+ }
+ if isLinkLike(info.Mode()) {
+ return AddRootReport{}, fmt.Errorf("library: symlink root folder is not allowed")
+ }
+ if !info.IsDir() {
+ return AddRootReport{}, fmt.Errorf("library: %s is not a directory", selectedDir)
+ }
+
+ // Check if selectedDir is a legacy portable trace-data directory containing a library/ subdirectory (even without settings.json).
+ scanRoot := selectedDir
+ libSub := filepath.Join(selectedDir, "library")
+ if lInfo, lErr := os.Lstat(libSub); lErr == nil && lInfo.IsDir() && !isLinkLike(lInfo.Mode()) {
+ scanRoot = libSub
+ } else {
+ // Also check optional settings.json inside selectedDir.
+ setBytes, sErr := os.ReadFile(filepath.Join(selectedDir, "settings.json"))
+ if sErr == nil {
+ var cfg struct {
+ CacheRoot string `json:"cacheRoot"`
+ CacheDir string `json:"cacheDir"`
+ }
+ if json.Unmarshal(setBytes, &cfg) == nil {
+ cand := strings.TrimSpace(cfg.CacheRoot)
+ if cand == "" {
+ cand = strings.TrimSpace(cfg.CacheDir)
+ }
+ if cand != "" {
+ if !filepath.IsAbs(cand) {
+ cand = filepath.Join(selectedDir, cand)
+ }
+ if cInfo, cErr := os.Lstat(cand); cErr == nil && cInfo.IsDir() && !isLinkLike(cInfo.Mode()) {
+ scanRoot = filepath.Clean(cand)
+ }
+ }
+ }
+ }
+ }
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ report := AddRootReport{Root: scanRoot}
+ if err := rejectDirectoryLinks(scanRoot); err != nil {
+ return report, err
+ }
+ existing, err := s.indexedItemsLocked()
+ if err != nil {
+ return report, err
+ }
+ oldRoots := append([]string(nil), s.extraRoots...)
+ found := false
+ for _, r := range s.allRootsLocked() {
+ found = found || samePath(r, scanRoot)
+ }
+ if !found {
+ s.extraRoots = append(s.extraRoots, scanRoot)
+ }
+ // Register the recovery root before importing any index rows. A failed
+ // ledger write must not leave rows whose source disappears after restart.
+ if err := s.saveRootsLocked(); err != nil {
+ s.extraRoots = oldRoots
+ return report, err
+ }
+
+ var toInsert []ItemMetadata
+ seenNew := make(map[string]bool)
+ err = filepath.WalkDir(scanRoot, func(path string, d fs.DirEntry, walkErr error) error {
+ if walkErr != nil {
+ return walkErr
+ }
+ // Never follow symlinks or Windows directory junctions (INV-08).
+ if isLinkLike(d.Type()) {
+ if d.IsDir() {
+ return filepath.SkipDir
+ }
+ return nil
+ }
+ if d.IsDir() {
+ return nil
+ }
+ if !strings.EqualFold(d.Name(), "item.json") {
+ return nil
+ }
+ if report.Scanned >= 100000 {
+ return fmt.Errorf("library: 清单扫描超过单轮上限")
+ }
+ report.Scanned++
+
+ raw, rErr := os.ReadFile(path)
+ if rErr != nil {
+ return rErr
+ }
+ meta, pErr := ParseItemMetadata(raw)
+ if pErr != nil {
+ return nil
+ }
+
+ // If itemKey already exists in index, keep existing item and count as Skipped.
+ if _, ok := existing[meta.ItemKey]; ok || seenNew[meta.ItemKey] {
+ report.Skipped++
+ return nil
+ }
+
+ itemDir := filepath.Dir(path)
+ if _, err := EnsureWithinRoot(scanRoot, itemDir); err != nil {
+ return err
+ }
+ meta.ItemDir = filepath.Clean(itemDir)
+ missing, totalBytes := verifyItemFiles(meta.ItemDir, &meta)
+ meta.TotalBytes = totalBytes
+ if missing && meta.Status != "recording" && meta.Status != "failed" && meta.Status != "partial" {
+ meta.Status = "missing_files"
+ }
+ toInsert = append(toInsert, meta)
+ seenNew[meta.ItemKey] = true
+ report.Added++
+ return nil
+ })
+ if err != nil {
+ return report, err
+ }
+ if len(toInsert) == 0 {
+ return report, nil
+ }
+ tx, err := s.db.Begin()
+ if err != nil {
+ return report, err
+ }
+ defer tx.Rollback()
+ for _, meta := range toInsert {
+ if err := upsertItemRowTx(tx, meta); err != nil {
+ return report, err
+ }
+ }
+ if err := tx.Commit(); err != nil {
+ return report, err
+ }
+ return report, nil
+}
+
+func jsonUnmarshal(raw []byte, v any) error {
+ if len(raw) == 0 {
+ return errors.New("empty json")
+ }
+ return json.Unmarshal(raw, v)
+}
diff --git a/internal/library/schema.go b/internal/library/schema.go
index 02f4143..75b0cd8 100644
--- a/internal/library/schema.go
+++ b/internal/library/schema.go
@@ -49,6 +49,9 @@ type ItemMetadata struct {
// cached for a member who is not the uploader; DEC-056). Optional; older
// manifests have none.
Via *ItemVia `json:"via,omitempty"`
+ // CachedBy is the TRACE installation that cached the item (DEC-062 ⑧);
+ // optional, older manifests have none.
+ CachedBy *ItemNode `json:"cachedBy,omitempty"`
// Runtime-populated fields
ItemKey string `json:"itemKey,omitempty"`
@@ -142,6 +145,13 @@ const (
ViaCollab = "collab"
)
+// ItemNode names a TRACE installation: its random node ID and a readable
+// name (the computer's or the remote's name).
+type ItemNode struct {
+ Node string `json:"node"`
+ Name string `json:"name,omitempty"`
+}
+
// ItemVia records the creator an item was cached for when that creator is not
// the item's author (DEC-056). It never changes Author.
type ItemVia struct {
@@ -779,26 +789,20 @@ func ComputeDotState(meta ItemMetadata) DotState {
d.Label = "部分缓存"
}
case "complete":
- incomplete := false
- for _, page := range meta.ExpectedPages {
- found := false
- for _, part := range meta.Parts {
- if part.Page == page && part.File != "" {
- found = true
- }
- }
- incomplete = incomplete || !found
- }
+ incomplete := expectedPagesIncomplete(meta)
belowBest := false
for _, part := range meta.Parts {
belowBest = belowBest || part.Available.BestVideo > part.Video.Quality || audioPriority(part.Available.BestAudio) > audioPriority(part.Audio.Quality)
}
if meta.UpgradeAvailable || len(meta.Missing) > 0 || incomplete || belowBest {
d.Dot = "yellow"
- if meta.UpgradeAvailable {
+ switch {
+ case meta.UpgradeAvailable:
d.Label = "可升级画质"
- } else {
+ case len(meta.Missing) > 0 || incomplete:
d.Label = "部分缺失"
+ default:
+ d.Label = "非最高画质"
}
} else {
d.Dot = "green"
@@ -811,6 +815,36 @@ func ComputeDotState(meta ItemMetadata) DotState {
return d
}
+// expectedPagesIncomplete reports whether a page the item expects has no file.
+func expectedPagesIncomplete(meta ItemMetadata) bool {
+ for _, page := range meta.ExpectedPages {
+ found := false
+ for _, part := range meta.Parts {
+ if part.Page == page && part.File != "" {
+ found = true
+ }
+ }
+ if !found {
+ return true
+ }
+ }
+ return false
+}
+
+// NeedsCompletion reports whether a cached item lacks content that caching
+// it again can fill: it is partial, or complete with missing records or
+// expected pages without a file. A better quality being available is not
+// missing content, and paused or failed items are not counted here.
+func NeedsCompletion(meta ItemMetadata) bool {
+ switch meta.Status {
+ case "partial":
+ return true
+ case "complete":
+ return len(meta.Missing) > 0 || expectedPagesIncomplete(meta)
+ }
+ return false
+}
+
func parseFlexibleUnix(v any) int64 {
switch val := v.(type) {
case float64:
diff --git a/internal/library/schema_migrate.go b/internal/library/schema_migrate.go
new file mode 100644
index 0000000..31b9227
--- /dev/null
+++ b/internal/library/schema_migrate.go
@@ -0,0 +1,238 @@
+package library
+
+import (
+ "database/sql"
+ "fmt"
+ "strings"
+ "sync"
+
+ "github.com/chialecode/trace/internal/storage"
+)
+
+var (
+ migrateV2HookMu sync.Mutex
+ migrateV2Hook func(tx *sql.Tx) error
+)
+
+// SetMigrateV2HookForTest installs a fault-injection callback invoked inside
+// the v1 -> v2 SQLite migration transaction right before PRAGMA user_version = 2.
+func SetMigrateV2HookForTest(fn func(tx *sql.Tx) error) func() {
+ migrateV2HookMu.Lock()
+ prev := migrateV2Hook
+ migrateV2Hook = fn
+ migrateV2HookMu.Unlock()
+ return func() {
+ migrateV2HookMu.Lock()
+ migrateV2Hook = prev
+ migrateV2HookMu.Unlock()
+ }
+}
+
+func (s *Store) initSchema() error {
+ v, err := storage.CheckSQLiteSchema(s.db, "library.db", CurrentSchemaVersion)
+ if err != nil {
+ return err
+ }
+ if v < CurrentSchemaVersion {
+ return s.migrateSchemaToV2()
+ }
+ for _, q := range schemaV2Statements() {
+ if _, err := s.db.Exec(q); err != nil {
+ return fmt.Errorf("library: init schema: %w", err)
+ }
+ }
+ return nil
+}
+
+func schemaV2Tables() []string {
+ return []string{
+ `CREATE TABLE IF NOT EXISTS library_items (
+ item_key TEXT PRIMARY KEY,
+ site TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ raw_id TEXT NOT NULL,
+ mid INTEGER NOT NULL DEFAULT 0,
+ author_uid TEXT NOT NULL DEFAULT '',
+ author_name TEXT NOT NULL DEFAULT '',
+ author_face TEXT NOT NULL DEFAULT '',
+ title TEXT NOT NULL DEFAULT '',
+ summary TEXT NOT NULL DEFAULT '',
+ cover_path TEXT NOT NULL DEFAULT '',
+ canonical_url TEXT NOT NULL DEFAULT '',
+ pub_ts INTEGER NOT NULL DEFAULT 0,
+ cached_at TEXT NOT NULL DEFAULT '',
+ status TEXT NOT NULL DEFAULT 'complete',
+ item_dir TEXT NOT NULL DEFAULT '',
+ total_bytes INTEGER NOT NULL DEFAULT 0,
+ upgrade_available INTEGER NOT NULL DEFAULT 0,
+ upgrade_hint TEXT NOT NULL DEFAULT '',
+ json_data TEXT NOT NULL
+ );`,
+ `CREATE TABLE IF NOT EXISTS item_refs (
+ from_key TEXT NOT NULL,
+ to_key TEXT NOT NULL,
+ PRIMARY KEY (from_key, to_key)
+ );`,
+ `CREATE TABLE IF NOT EXISTS feed_items (
+ feed_key TEXT PRIMARY KEY,
+ site TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ raw_id TEXT NOT NULL,
+ mid INTEGER NOT NULL DEFAULT 0,
+ author_uid TEXT NOT NULL DEFAULT '',
+ author_name TEXT NOT NULL DEFAULT '',
+ author_face TEXT NOT NULL DEFAULT '',
+ title TEXT NOT NULL DEFAULT '',
+ summary TEXT NOT NULL DEFAULT '',
+ cover_url TEXT NOT NULL DEFAULT '',
+ canonical_url TEXT NOT NULL DEFAULT '',
+ pub_ts INTEGER NOT NULL DEFAULT 0,
+ discovered_at TEXT NOT NULL DEFAULT '',
+ cached INTEGER NOT NULL DEFAULT 0,
+ cache_status TEXT NOT NULL DEFAULT '',
+ item_key TEXT NOT NULL DEFAULT ''
+ );`,
+ `CREATE TABLE IF NOT EXISTS download_tasks (
+ task_id TEXT PRIMARY KEY,
+ site TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ source TEXT NOT NULL DEFAULT 'manual',
+ target_id TEXT NOT NULL,
+ cid INTEGER NOT NULL DEFAULT 0,
+ page INTEGER NOT NULL DEFAULT 1,
+ title TEXT NOT NULL DEFAULT '',
+ part_title TEXT NOT NULL DEFAULT '',
+ mid INTEGER NOT NULL DEFAULT 0,
+ author_uid TEXT NOT NULL DEFAULT '',
+ author_name TEXT NOT NULL DEFAULT '',
+ author_face TEXT NOT NULL DEFAULT '',
+ cover_url TEXT NOT NULL DEFAULT '',
+ cache_linked_videos INTEGER NOT NULL DEFAULT 0,
+ status TEXT NOT NULL DEFAULT 'queued',
+ pause_reason TEXT NOT NULL DEFAULT '',
+ error_kind TEXT NOT NULL DEFAULT '',
+ error_message TEXT NOT NULL DEFAULT '',
+ quality_hint TEXT NOT NULL DEFAULT '',
+ bytes_downloaded INTEGER NOT NULL DEFAULT 0,
+ total_bytes INTEGER NOT NULL DEFAULT 0,
+ progress REAL NOT NULL DEFAULT 0,
+ item_key TEXT NOT NULL DEFAULT '',
+ item_dir TEXT NOT NULL DEFAULT '',
+ files_json TEXT NOT NULL DEFAULT '[]',
+ attempts_json TEXT NOT NULL DEFAULT '[]',
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+ );`,
+ `CREATE TABLE IF NOT EXISTS task_attempts (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ task_id TEXT NOT NULL,
+ attempt_time TEXT NOT NULL,
+ file_path TEXT NOT NULL,
+ offset_bytes INTEGER NOT NULL DEFAULT 0,
+ host TEXT NOT NULL DEFAULT '',
+ attempt_num INTEGER NOT NULL DEFAULT 1,
+ error_kind TEXT NOT NULL DEFAULT '',
+ http_status INTEGER NOT NULL DEFAULT 0
+ );`,
+ }
+}
+
+func schemaV2Indexes() []string {
+ return []string{
+ `CREATE INDEX IF NOT EXISTS idx_library_items_pub_ts ON library_items(pub_ts DESC);`,
+ `CREATE INDEX IF NOT EXISTS idx_library_items_mid ON library_items(mid);`,
+ `CREATE INDEX IF NOT EXISTS idx_library_items_site_author ON library_items(site, author_uid);`,
+ `CREATE INDEX IF NOT EXISTS idx_library_items_via ON library_items(site, json_extract(json_data, '$.via.uid'));`,
+ `CREATE INDEX IF NOT EXISTS idx_item_refs_to ON item_refs(to_key);`,
+ `CREATE INDEX IF NOT EXISTS idx_feed_items_pub_ts ON feed_items(pub_ts DESC);`,
+ `CREATE INDEX IF NOT EXISTS idx_feed_items_mid ON feed_items(mid);`,
+ `CREATE INDEX IF NOT EXISTS idx_feed_items_site_author ON feed_items(site, author_uid);`,
+ `CREATE INDEX IF NOT EXISTS idx_download_tasks_site_author ON download_tasks(site, author_uid);`,
+ }
+}
+
+func schemaV2Statements() []string {
+ tables := schemaV2Tables()
+ indexes := schemaV2Indexes()
+ out := make([]string, 0, len(tables)+len(indexes))
+ out = append(out, tables...)
+ out = append(out, indexes...)
+ return out
+}
+
+func (s *Store) migrateSchemaToV2() error {
+ tx, err := s.db.Begin()
+ if err != nil {
+ return fmt.Errorf("library: begin schema v2 migration: %w", err)
+ }
+ defer tx.Rollback()
+
+ for _, q := range schemaV2Tables() {
+ if _, err := tx.Exec(q); err != nil {
+ return fmt.Errorf("library: migrate schema v2 base table: %w", err)
+ }
+ }
+
+ for _, tbl := range []string{"library_items", "feed_items", "download_tasks"} {
+ hasCol, err := tableHasColumnTx(tx, tbl, "author_uid")
+ if err != nil {
+ return err
+ }
+ if !hasCol {
+ if _, err := tx.Exec(fmt.Sprintf(`ALTER TABLE %s ADD COLUMN author_uid TEXT NOT NULL DEFAULT ''`, tbl)); err != nil {
+ return fmt.Errorf("library: add author_uid on %s: %w", tbl, err)
+ }
+ }
+ if _, err := tx.Exec(fmt.Sprintf(`UPDATE %s SET author_uid = CASE WHEN mid > 0 THEN CAST(mid AS TEXT) ELSE '' END WHERE author_uid = ''`, tbl)); err != nil {
+ return fmt.Errorf("library: backfill author_uid on %s: %w", tbl, err)
+ }
+ }
+
+ for _, q := range schemaV2Indexes() {
+ if _, err := tx.Exec(q); err != nil {
+ return fmt.Errorf("library: create schema v2 index: %w", err)
+ }
+ }
+
+ migrateV2HookMu.Lock()
+ hook := migrateV2Hook
+ migrateV2HookMu.Unlock()
+ if hook != nil {
+ if err := hook(tx); err != nil {
+ return err
+ }
+ }
+
+ if _, err := tx.Exec(fmt.Sprintf(`PRAGMA user_version = %d`, CurrentSchemaVersion)); err != nil {
+ return fmt.Errorf("library: stamp user_version %d: %w", CurrentSchemaVersion, err)
+ }
+ if err := tx.Commit(); err != nil {
+ return fmt.Errorf("library: commit schema v2 migration: %w", err)
+ }
+ _, _ = s.db.Exec(`PRAGMA wal_checkpoint(PASSIVE)`)
+ return nil
+}
+
+func tableHasColumnTx(tx *sql.Tx, table, column string) (bool, error) {
+ rows, err := tx.Query(fmt.Sprintf(`PRAGMA table_info(%s)`, table))
+ if err != nil {
+ return false, err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var (
+ cid int
+ name, ctyp string
+ notNull int
+ dflt sql.NullString
+ pk int
+ )
+ if err := rows.Scan(&cid, &name, &ctyp, ¬Null, &dflt, &pk); err != nil {
+ return false, err
+ }
+ if strings.EqualFold(name, column) {
+ return true, nil
+ }
+ }
+ return false, rows.Err()
+}
diff --git a/internal/library/statistics.go b/internal/library/statistics.go
index b21611e..bb938ad 100644
--- a/internal/library/statistics.go
+++ b/internal/library/statistics.go
@@ -15,16 +15,16 @@ func (s *Store) Statistics() (Statistics, error) {
if err := s.db.QueryRow(`SELECT COUNT(*), COALESCE(SUM(total_bytes), 0) FROM library_items`).Scan(&stats.Items, &stats.Bytes); err != nil {
return stats, err
}
- // A collaboration video cached for a member is listed under that member,
- // whose folder holds it, not under the uploader (DEC-061).
+ // A collaboration or forwarded video cached under another creator's folder is
+ // listed under that creator in the media library, not under the uploader (DEC-056, DEC-061).
rows, err := s.db.Query(`
SELECT site, owner_uid, MAX(owner_mid), MAX(owner_name), MAX(owner_face), COALESCE(MAX(pub_ts), 0)
FROM (
SELECT site, pub_ts,
- CASE WHEN ` + collabSQL + ` THEN ` + viaUIDSQL + ` ELSE author_uid END AS owner_uid,
- CASE WHEN ` + collabSQL + ` THEN 0 ELSE mid END AS owner_mid,
- CASE WHEN ` + collabSQL + ` THEN COALESCE(json_extract(json_data, '$.via.name'), '') ELSE author_name END AS owner_name,
- CASE WHEN ` + collabSQL + ` THEN '' ELSE author_face END AS owner_face
+ CASE WHEN ` + viaOwnerSQL + ` THEN ` + viaUIDSQL + ` ELSE author_uid END AS owner_uid,
+ CASE WHEN ` + viaOwnerSQL + ` THEN 0 ELSE mid END AS owner_mid,
+ CASE WHEN ` + viaOwnerSQL + ` THEN COALESCE(json_extract(json_data, '$.via.name'), '') ELSE author_name END AS owner_name,
+ CASE WHEN ` + viaOwnerSQL + ` THEN '' ELSE author_face END AS owner_face
FROM library_items
)
WHERE owner_uid != ''
@@ -54,6 +54,14 @@ func (s *Store) Statistics() (Statistics, error) {
// for a member other than the uploader (DEC-056).
const collabSQL = "(json_extract(json_data, '$.via.reason') = '" + ViaCollab + "' AND COALESCE(" + viaUIDSQL + ", '') != '')"
+// viaForwardSQL matches library_items rows cached solely because another
+// creator forwarded them (stored in the forwarder's forwards/ folder, DEC-056).
+const viaForwardSQL = "(json_extract(json_data, '$.via.reason') = '" + ViaForward + "' AND COALESCE(" + viaUIDSQL + ", '') != '')"
+
+// viaOwnerSQL matches library_items rows stored under via.uid's folder
+// (collaboration videos and forwarded content, DEC-056, DEC-061, DEC-063).
+const viaOwnerSQL = "(json_extract(json_data, '$.via.reason') IN ('" + ViaCollab + "', '" + ViaForward + "') AND COALESCE(" + viaUIDSQL + ", '') != '')"
+
// LatestPubByAuthor returns the newest cached pub_ts for each (site, author_uid)
// across library_items and cached feed_items, supporting multi-site HomeSeen baselines.
func (s *Store) LatestPubByAuthor() ([]ItemAuthor, error) {
@@ -64,15 +72,16 @@ func (s *Store) LatestPubByAuthor() ([]ItemAuthor, error) {
FROM (
SELECT site, author_uid, mid, author_name, author_face, pub_ts
FROM library_items
- WHERE author_uid != '' AND pub_ts > 0
+ WHERE author_uid != '' AND pub_ts > 0 AND NOT ` + viaForwardSQL + `
UNION ALL
SELECT site, ` + viaUIDSQL + `, 0, COALESCE(json_extract(json_data, '$.via.name'), ''), '', pub_ts
FROM library_items
- WHERE ` + collabSQL + ` AND pub_ts > 0
+ WHERE ` + viaOwnerSQL + ` AND pub_ts > 0
UNION ALL
SELECT site, author_uid, mid, author_name, author_face, pub_ts
FROM feed_items
WHERE cached = 1 AND author_uid != '' AND pub_ts > 0
+ AND NOT (kind = 'video' AND EXISTS (SELECT 1 FROM item_refs r WHERE r.to_key = feed_items.feed_key))
)
GROUP BY site, author_uid
ORDER BY 6 DESC, site, author_uid
diff --git a/internal/library/upgrade.go b/internal/library/upgrade.go
new file mode 100644
index 0000000..9d54127
--- /dev/null
+++ b/internal/library/upgrade.go
@@ -0,0 +1,200 @@
+package library
+
+import (
+ "context"
+ "fmt"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/chialecode/trace/internal/site/bilibili"
+)
+
+// UpgradeCandidates returns up to 50 cached Bilibili video items ordered by
+// oldest UpgradeCheckedAt first (FR-CACHE-006), querying all indexed videos
+// directly without scanning disk for non-returned items.
+func (s *Store) UpgradeCandidates(limit int) ([]ItemMetadata, error) {
+ if limit <= 0 || limit > 50 {
+ limit = 50
+ }
+ s.mu.RLock()
+ allowMoved := s.allowMovedFiles
+ rows, err := s.db.Query(`
+ SELECT json_data, item_dir, status, total_bytes, upgrade_available, upgrade_hint
+ FROM library_items
+ WHERE site = 'bilibili' AND kind = 'video'
+ `)
+ if err != nil {
+ s.mu.RUnlock()
+ return nil, err
+ }
+ var items []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 {
+ _ = rows.Close()
+ s.mu.RUnlock()
+ 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
+ items = append(items, meta)
+ }
+ rowErr := rows.Err()
+ _ = rows.Close()
+ s.mu.RUnlock()
+ if rowErr != nil {
+ return nil, rowErr
+ }
+ sort.SliceStable(items, func(i, j int) bool {
+ ti, _ := time.Parse(time.RFC3339, items[i].UpgradeCheckedAt)
+ tj, _ := time.Parse(time.RFC3339, items[j].UpgradeCheckedAt)
+ if !ti.Equal(tj) {
+ return ti.Before(tj)
+ }
+ return items[i].PubTs < items[j].PubTs
+ })
+ if len(items) > limit {
+ items = items[:limit]
+ }
+ if !allowMoved {
+ for i := range items {
+ refreshItemFileState(&items[i])
+ }
+ }
+ return items, nil
+}
+
+// CheckUpgradeKeys probes the given video keys (or all candidates if keys is empty) for quality upgrades.
+// When force is false, items checked within the last 24 hours are skipped without network requests (FR-CACHE-006).
+func (s *Store) CheckUpgradeKeys(ctx context.Context, client *bilibili.Client, keys []string, force bool, opts bilibili.PlaySelectionOptions) ([]ItemMetadata, error) {
+ if client == nil {
+ return nil, fmt.Errorf("library: bilibili client is nil")
+ }
+
+ var candidates []ItemMetadata
+ if len(keys) == 0 {
+ var err error
+ candidates, err = s.UpgradeCandidates(50)
+ if err != nil {
+ return nil, err
+ }
+ } else {
+ for _, k := range keys {
+ m, ok, err := s.GetItem(k)
+ if err != nil {
+ return nil, &bilibili.SiteError{Kind: "storage", Message: "读取缓存记录失败", Err: err}
+ }
+ if ok && m.Kind == "video" {
+ candidates = append(candidates, m)
+ }
+ }
+ }
+
+ var upgradable []ItemMetadata
+ now := time.Now().UTC()
+ nowStr := now.Format(time.RFC3339)
+
+ for _, meta := range candidates {
+ if err := ctx.Err(); err != nil {
+ return upgradable, err
+ }
+ if len(meta.Parts) == 0 {
+ continue
+ }
+ if !force && meta.UpgradeCheckedAt != "" {
+ if lastT, err := time.Parse(time.RFC3339, meta.UpgradeCheckedAt); err == nil && now.Sub(lastT) < 24*time.Hour {
+ if meta.UpgradeAvailable {
+ upgradable = append(upgradable, meta)
+ }
+ continue
+ }
+ }
+
+ // Probe P1 only (data-and-cache.md §2.7).
+ part := &meta.Parts[0]
+ if part.CID <= 0 {
+ continue
+ }
+ plan, err := client.PlayURL(ctx, meta.RawID, part.CID, opts)
+ if err != nil {
+ return upgradable, err
+ }
+
+ part.Available = PartAvailableInfo{
+ AcceptQuality: plan.Available.AcceptQuality,
+ Formats: plan.Available.Formats,
+ Returned: plan.Available.Returned,
+ BestVideo: plan.Available.BestVideo,
+ BestAudio: plan.Available.BestAudio,
+ HasDolby: plan.Available.HasDolby,
+ HasFlac: plan.Available.HasFlac,
+ ProbedAt: nowStr,
+ Downgraded: plan.Available.Downgraded,
+ DowngradeHint: plan.Available.DowngradeHint,
+ }
+
+ var hints []string
+ if bilibili.QualityRank(plan.Video.Quality) > bilibili.QualityRank(part.Video.Quality) {
+ hints = append(hints, fmt.Sprintf("P%02d 视频可由 %s (%d) 升级至 %s (%d)",
+ part.Page,
+ bilibili.QualityName(part.Video.Quality), part.Video.Quality,
+ plan.Video.QualityName, plan.Video.Quality,
+ ))
+ }
+ if plan.Audio != nil && audioPriority(plan.Audio.Quality) > audioPriority(part.Audio.Quality) {
+ hints = append(hints, fmt.Sprintf("P%02d 音频可由 %s 升级至 %s",
+ part.Page,
+ part.Audio.Name,
+ plan.Audio.Name,
+ ))
+ }
+
+ meta.UpgradeCheckedAt = nowStr
+ meta.UpgradeAvailable = len(hints) > 0
+ meta.UpgradeHint = strings.Join(hints, ";")
+ updated, err := s.SaveItem(meta.ItemDir, meta)
+ if err != nil {
+ return upgradable, &bilibili.SiteError{Kind: "storage", Message: "画质探测结果保存失败", Err: err}
+ }
+ if updated.UpgradeAvailable {
+ upgradable = append(upgradable, updated)
+ }
+ }
+
+ sort.SliceStable(upgradable, func(i, j int) bool {
+ return upgradable[i].PubTs > upgradable[j].PubTs
+ })
+ return upgradable, nil
+}
+
+// CheckQualityUpgrade probes cached video items against the Bilibili PlayURL API (with force=true for direct calls).
+func (s *Store) CheckQualityUpgrade(ctx context.Context, client *bilibili.Client, opts bilibili.PlaySelectionOptions) ([]ItemMetadata, error) {
+ return s.CheckUpgradeKeys(ctx, client, nil, true, opts)
+}
+
+func audioPriority(id int) int {
+ switch id {
+ case 30251:
+ return 50
+ case 30250:
+ return 40
+ case 30280:
+ return 30
+ case 30232:
+ return 20
+ case 30216:
+ return 10
+ default:
+ return 0
+ }
+}
diff --git a/internal/library/works.go b/internal/library/works.go
index 78246cf..1b35c9b 100644
--- a/internal/library/works.go
+++ b/internal/library/works.go
@@ -27,9 +27,10 @@ func (s *Store) CountCachedWorks(refs []AuthorRef) (map[string]int, error) {
switch siteID {
case "bilibili":
err = s.db.QueryRow(`SELECT COUNT(*) FROM library_items WHERE site = 'bilibili' AND kind = 'video'
- AND (author_uid = ? OR (`+collabSQL+` AND `+viaUIDSQL+` = ?))`, uid, uid).Scan(&n)
+ AND ((author_uid = ? AND NOT `+viaForwardSQL+`) OR (`+collabSQL+` AND `+viaUIDSQL+` = ?))`, uid, uid).Scan(&n)
case "douyin":
- err = s.db.QueryRow(`SELECT COUNT(*) FROM library_items WHERE site = 'douyin' AND kind IN ('video', 'dynamic') AND author_uid = ?`, uid).Scan(&n)
+ err = s.db.QueryRow(`SELECT COUNT(*) FROM library_items WHERE site = 'douyin' AND kind IN ('video', 'dynamic')
+ AND (author_uid = ? OR (`+collabSQL+` AND `+viaUIDSQL+` = ?))`, uid, uid).Scan(&n)
default:
continue
}
diff --git a/internal/library/works_test.go b/internal/library/works_test.go
index 9626404..b1137cf 100644
--- a/internal/library/works_test.go
+++ b/internal/library/works_test.go
@@ -81,3 +81,116 @@ func TestCollabVideoBelongsToMemberItWasCachedFor(t *testing.T) {
t.Fatalf("cached works = %+v", counts)
}
}
+
+// A video cached only because a creator forwarded it in a dynamic (via.reason == "forward",
+// stored under the forwarder's forwards/ directory) must belong to the forwarder in the
+// Media Library author list, item list, latest-pub lookup, and cached-works count — never
+// creating a phantom author row for the original uploader.
+func TestForwardVideoBelongsToForwarderNotUploaderInLibrary(t *testing.T) {
+ tmp := t.TempDir()
+ db, _, _, err := storage.OpenSQLite(filepath.Join(tmp, "library.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ store, err := OpenWithDataDir(db, filepath.Join(tmp, "cache"), tmp)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ fwdDir := filepath.Join(store.CacheDir(), "bilibili", "3546", "forwards", "BV1fwdvid")
+ if err := os.MkdirAll(fwdDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := store.SaveItem(fwdDir, ItemMetadata{
+ Site: "bilibili",
+ Kind: "video",
+ ID: "BV1fwdvid",
+ Title: "被转发的视频",
+ PubTs: 200,
+ Status: "complete",
+ DirectCached: false,
+ Author: ItemAuthor{Site: "bilibili", Mid: 9999, UID: "9999", Name: "原视频作者"},
+ Via: &ItemVia{Reason: ViaForward, Site: "bilibili", UID: "3546", Name: "转发动态作者", DynamicID: "127286"},
+ }); err != nil {
+ t.Fatal(err)
+ }
+
+ dynDir := filepath.Join(store.CacheDir(), "bilibili", "3546", "dynamics", "127286")
+ if err := os.MkdirAll(dynDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := store.SaveItem(dynDir, ItemMetadata{
+ Site: "bilibili",
+ Kind: "dynamic",
+ ID: "127286",
+ Title: "转发动态",
+ PubTs: 210,
+ Status: "complete",
+ DirectCached: true,
+ Author: ItemAuthor{Site: "bilibili", Mid: 3546, UID: "3546", Name: "转发动态作者"},
+ Videos: []string{"BV1fwdvid"},
+ }); err != nil {
+ t.Fatal(err)
+ }
+
+ // 1. Statistics(): forwarder appears once, original uploader does NOT appear at all.
+ stats, err := store.Statistics()
+ if err != nil {
+ t.Fatal(err)
+ }
+ owners := map[string]int{}
+ for _, a := range stats.Authors {
+ owners[a.UID]++
+ if a.UID == "3546" && (a.Name != "转发动态作者" || a.Mid != 3546) {
+ t.Fatalf("forwarder author row = %+v, want name=转发动态作者 mid=3546", a)
+ }
+ }
+ if owners["9999"] != 0 || owners["3546"] != 1 {
+ t.Fatalf("library authors = %+v, want forwarder only (no phantom uploader 9999)", stats.Authors)
+ }
+
+ // 2. ListItems(): forwarder sees both dynamic & forwarded video; original uploader sees neither.
+ fwdItems, err := store.ListItems(FeedFilter{Site: "bilibili", AuthorUID: "3546"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(fwdItems) != 2 {
+ t.Fatalf("ListItems(forwarder) = %d items (%+v), want 2", len(fwdItems), fwdItems)
+ }
+ uploaderItems, err := store.ListItems(FeedFilter{Site: "bilibili", AuthorUID: "9999"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(uploaderItems) != 0 {
+ t.Fatalf("ListItems(original uploader) = %+v, want 0", uploaderItems)
+ }
+
+ // 3. LatestPubByAuthor(): must not attribute forwarded video to original uploader.
+ latestRows, err := store.LatestPubByAuthor()
+ if err != nil {
+ t.Fatal(err)
+ }
+ latest := map[string]int64{}
+ for _, a := range latestRows {
+ latest[a.Site+":"+a.UID] = a.LatestPubTs
+ }
+ if latest["bilibili:9999"] != 0 {
+ t.Fatalf("LatestPubByAuthor(uploader) = %d, want 0", latest["bilibili:9999"])
+ }
+ if latest["bilibili:3546"] != 210 {
+ t.Fatalf("LatestPubByAuthor(forwarder) = %d, want 210", latest["bilibili:3546"])
+ }
+
+ // 4. CountCachedWorks(): must not count forwarded video for original uploader.
+ counts, err := store.CountCachedWorks([]AuthorRef{
+ {Site: "bilibili", UID: "3546"},
+ {Site: "bilibili", UID: "9999"},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if counts["bilibili:9999"] != 0 {
+ t.Fatalf("CountCachedWorks(uploader) = %d, want 0", counts["bilibili:9999"])
+ }
+}
diff --git a/internal/live/audit_regression_test.go b/internal/live/audit_regression_test.go
new file mode 100644
index 0000000..d8ef31f
--- /dev/null
+++ b/internal/live/audit_regression_test.go
@@ -0,0 +1,1509 @@
+package live
+
+import (
+ "bytes"
+ "context"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/Eyevinn/mp4ff/aac"
+ "github.com/Eyevinn/mp4ff/mp4"
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/site"
+ "github.com/chialecode/trace/internal/subscription"
+)
+
+func TestSignedURLNeverLeaksIntoErrorsOrRoomState(t *testing.T) {
+ mgr, _, _, srv, _ := setupLiveTestHarness(t, http.NotFoundHandler())
+ // Close server immediately so Do() fails with a *url.Error carrying the full signed URL.
+ srv.Close()
+
+ signedBili := srv.URL + "/live/stream.m3u8?sign=BILI_SECRET_SIG&expires=1999999999&token=BILI_TOK"
+ _, err := mgr.fetchLiveLimitedBytes(context.Background(), signedBili, maxM3U8PlaylistBytes)
+ if err == nil {
+ t.Fatal("expected network error from closed server")
+ }
+ for _, secret := range []string{"BILI_SECRET_SIG", "BILI_TOK", "expires=1999999999", "sign="} {
+ if strings.Contains(err.Error(), secret) {
+ t.Fatalf("fetchLiveLimitedBytes leaked %q in error: %v", secret, err)
+ }
+ }
+
+ signedDouyin := srv.URL + "/live/stream.flv?x-expires=1999999999&upsig=DY_SECRET_SIG&sessionid=DY_TOK"
+ _, flvErr := OpenHTTPFLVStream(context.Background(), site.DouyinLiveTransport("Mozilla/5.0 Test", true), []string{signedDouyin}, time.Second)
+ if flvErr == nil {
+ t.Fatal("expected network error from OpenHTTPFLVStream on closed server")
+ }
+ for _, secret := range []string{"DY_SECRET_SIG", "DY_TOK", "upsig=", "x-expires="} {
+ if strings.Contains(flvErr.Error(), secret) {
+ t.Fatalf("OpenHTTPFLVStream leaked %q in error: %v", secret, flvErr)
+ }
+ }
+
+ rawURLErr := &url.Error{
+ Op: "Get",
+ URL: "https://cdn.example.invalid/live/a.flv?sign=RAW_SECRET&token=RAW_TOK",
+ Err: errors.New("connection reset by peer"),
+ }
+ sess := &recordSession{}
+ mgr.setSessionStop(sess, "network", rawURLErr)
+ if strings.Contains(sess.lastErr, "RAW_SECRET") || strings.Contains(sess.lastErr, "RAW_TOK") || strings.Contains(sess.lastErr, "cdn.example.invalid") {
+ t.Fatalf("setSessionStop leaked URL/secret into lastErr: %q", sess.lastErr)
+ }
+ if !strings.Contains(sess.lastErr, "connection reset by peer") {
+ t.Fatalf("expected underlying reason preserved, got %q", sess.lastErr)
+ }
+}
+
+func TestLiveCoverWriteOrderOwnershipAndSignedDouyinCover(t *testing.T) {
+ jpegBytes := []byte{0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 'J', 'F', 'I', 'F', 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0xFF, 0xD9}
+ const sigQuery = "x-expires=1999999999&token=COVER_SIG_SECRET"
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/bili/cover.jpg", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "image/jpeg")
+ _, _ = w.Write(jpegBytes)
+ })
+ mux.HandleFunc("/dy/signed-cover.jpg", func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.RawQuery != sigQuery {
+ w.WriteHeader(http.StatusForbidden)
+ return
+ }
+ w.Header().Set("Content-Type", "image/jpeg")
+ _, _ = w.Write(jpegBytes)
+ })
+ mux.HandleFunc("/dy/huge-cover.jpg", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "image/jpeg")
+ _, _ = w.Write(jpegBytes[:3])
+ chunk := bytes.Repeat([]byte{0xAA}, 1<<20)
+ for i := 0; i < 17; i++ {
+ _, _ = w.Write(chunk)
+ }
+ })
+
+ mgr, lib, _, srv, _ := setupLiveTestHarness(t, mux)
+
+ // 1. Bilibili saveLiveCover writes cover.jpg BEFORE saving item.json (never persists 0-byte cover).
+ sess := regressionLiveSession(t, lib)
+ mgr.mu.Lock()
+ mgr.states[sess.roomID] = RoomState{RoomID: sess.roomID, Cover: srv.URL + "/bili/cover.jpg?" + sigQuery}
+ mgr.mu.Unlock()
+
+ var saveCalls atomic.Int32
+ var badWriteOrder atomic.Bool
+ lib.OnSaved(func(meta library.ItemMetadata) {
+ saveCalls.Add(1)
+ for _, mf := range meta.Media {
+ if mf.Role == "cover" {
+ info, err := os.Stat(filepath.Join(meta.ItemDir, mf.Path))
+ if err != nil || info.Size() == 0 || mf.Bytes == 0 || mf.SHA256 == "" {
+ badWriteOrder.Store(true)
+ }
+ }
+ }
+ })
+ if err := mgr.saveLiveCover(context.Background(), sess); err != nil {
+ t.Fatalf("saveLiveCover: %v", err)
+ }
+ if badWriteOrder.Load() || saveCalls.Load() != 1 {
+ t.Fatalf("cover write order violated: badWriteOrder=%v saveCalls=%d", badWriteOrder.Load(), saveCalls.Load())
+ }
+ rawMeta, _ := os.ReadFile(filepath.Join(sess.itemDir, "item.json"))
+ if strings.Contains(string(rawMeta), "COVER_SIG_SECRET") {
+ t.Fatalf("signed cover query leaked into item.json: %s", string(rawMeta))
+ }
+
+ // 2. Douyin saveDouyinLiveCover protects pre-existing unowned cover.jpg.
+ dyDir := filepath.Join(lib.CacheDir(), "douyin", "unowned-cover-test")
+ if err := os.MkdirAll(dyDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ existingCover := filepath.Join(dyDir, "cover.jpg")
+ if err := os.WriteFile(existingCover, []byte("USER_OWNED_PHOTO"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ dyMeta, err := lib.SaveItem(dyDir, library.ItemMetadata{
+ Site: "douyin", Kind: "live", ID: "live:7400991", Status: "recording",
+ Live: &library.LiveRecordingInfo{RoomIDStr: "7400991"},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ dySess := &recordSession{
+ siteID: string(site.Douyin),
+ itemDir: dyDir,
+ itemMeta: dyMeta,
+ coverURL: srv.URL + "/dy/signed-cover.jpg?" + sigQuery,
+ }
+ transport := site.DouyinLiveTransport("Mozilla/5.0 Test", true)
+ if err := mgr.saveDouyinLiveCover(context.Background(), dySess, transport); err == nil {
+ t.Fatal("expected storage error when unowned cover.jpg exists")
+ }
+ if got, _ := os.ReadFile(existingCover); string(got) != "USER_OWNED_PHOTO" {
+ t.Fatalf("unowned cover.jpg was overwritten: %q", string(got))
+ }
+
+ // 3. Douyin saveDouyinLiveCover rejects >16 MiB cover overflow instead of silently truncating.
+ hugeDir := filepath.Join(lib.CacheDir(), "douyin", "huge-cover-test")
+ if err := os.MkdirAll(hugeDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ hugeMeta, _ := lib.SaveItem(hugeDir, library.ItemMetadata{
+ Site: "douyin", Kind: "live", ID: "live:7400992", Status: "recording",
+ Live: &library.LiveRecordingInfo{RoomIDStr: "7400992"},
+ })
+ hugeSess := &recordSession{
+ siteID: string(site.Douyin),
+ itemDir: hugeDir,
+ itemMeta: hugeMeta,
+ coverURL: srv.URL + "/dy/huge-cover.jpg",
+ }
+ _ = mgr.saveDouyinLiveCover(context.Background(), hugeSess, transport)
+ if _, statErr := os.Stat(filepath.Join(hugeDir, "cover.jpg")); !os.IsNotExist(statErr) {
+ t.Fatalf("oversized cover (>16 MiB) should be rejected, statErr=%v", statErr)
+ }
+
+ // 4. Signed Douyin cover uses unstripped in-memory status.Cover (succeeds on 403-without-query CDN)
+ // while RoomState.Cover and item.json remain stripped.
+ dyProv := newFakeDouyinLiveProvider()
+ const secUID = "MS4wLjABAAAA_signed_cover_dy"
+ dyProv.statusFn = func(uid, _ string, _ int) (site.LiveStatus, error) {
+ return site.LiveStatus{
+ Site: site.Douyin, AccountUID: secUID, RoomID: "7400993", WebRID: "99301",
+ Status: site.LiveStateLive, Title: "签名封面测试", Cover: srv.URL + "/dy/signed-cover.jpg?" + sigQuery,
+ }, nil
+ }
+ mgr.RegisterSiteProvider(dyProv)
+ st, err := mgr.CheckAccountLiveStatus(context.Background(), site.Douyin, secUID, "99301", true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(st.Cover, "COVER_SIG_SECRET") {
+ t.Fatalf("RoomState.Cover leaked signed query: %q", st.Cover)
+ }
+ mgr.mu.Lock()
+ rawCover := mgr.douyinRawCovers[secUID]
+ mgr.mu.Unlock()
+ if !strings.Contains(rawCover, sigQuery) {
+ t.Fatalf("expected unstripped cover cached in memory, got %q", rawCover)
+ }
+ okDir := filepath.Join(lib.CacheDir(), "douyin", "ok-cover-test")
+ _ = os.MkdirAll(okDir, 0o700)
+ okMeta, _ := lib.SaveItem(okDir, library.ItemMetadata{
+ Site: "douyin", Kind: "live", ID: "live:7400993", Status: "recording",
+ Live: &library.LiveRecordingInfo{RoomIDStr: "7400993"},
+ })
+ okSess := &recordSession{
+ siteID: string(site.Douyin),
+ itemDir: okDir,
+ itemMeta: okMeta,
+ coverURL: rawCover,
+ }
+ if err := mgr.saveDouyinLiveCover(context.Background(), okSess, transport); err != nil {
+ t.Fatalf("saveDouyinLiveCover with signed query failed: %v", err)
+ }
+ if got, err := os.ReadFile(filepath.Join(okDir, "cover.jpg")); err != nil || !bytes.Equal(got, jpegBytes) {
+ t.Fatalf("signed cover not saved: len=%d err=%v", len(got), err)
+ }
+}
+
+func TestDiskFreeWalksUpAndRecordersRecreateDeletedItemDir(t *testing.T) {
+ missingNested := filepath.Join(t.TempDir(), "removed-by-rclone", "sub", "itemDir")
+ free, err := getFreeDiskBytes(missingNested)
+ if err != nil || free == 0 {
+ t.Fatalf("getFreeDiskBytes on non-existent nested dir failed: free=%d err=%v", free, err)
+ }
+
+ initBytes, fragBytes := splitSyntheticHLSInitAndFrag(t)
+ flvBytes := buildSyntheticFLVBytes(t, "avc", 35)
+ mgr, lib, base := regressionRecorder(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/index":
+ _, _ = w.Write([]byte("#EXTM3U\n#EXT-X-TARGETDURATION:1\n#EXT-X-MEDIA-SEQUENCE:1\n#EXT-X-MAP:URI=\"/init\"\n#EXTINF:1,\n/frag\n#EXT-X-ENDLIST\n"))
+ case "/init":
+ _, _ = w.Write(initBytes)
+ case "/frag":
+ _, _ = w.Write(fragBytes)
+ case "/live.flv":
+ w.Header().Set("Content-Type", "video/x-flv")
+ _, _ = w.Write(flvBytes)
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ mgr.minFreeBytes = 1
+ mgr.freeBytesFunc = getFreeDiskBytes
+
+ // Remove itemDir completely (simulating rclone move removing emptied dir) before HLS and FLV writes.
+ sessHLS := regressionLiveSession(t, lib)
+ if err := os.RemoveAll(sessHLS.itemDir); err != nil {
+ t.Fatal(err)
+ }
+ if n, err := mgr.recordHLSSegment(context.Background(), sessHLS, []string{base + "/index"}, filepath.Join(sessHLS.itemDir, "part-001.mp4.part"), true); err != nil || n == 0 {
+ t.Fatalf("HLS recording failed after empty itemDir removal: n=%d err=%v", n, err)
+ }
+
+ sessFLV := regressionLiveSession(t, lib)
+ if err := os.RemoveAll(sessFLV.itemDir); err != nil {
+ t.Fatal(err)
+ }
+ var conn *activeFLVConn
+ defer func() {
+ if conn != nil {
+ _ = conn.Close()
+ }
+ }()
+ if n, err := mgr.recordFLVPartWithTransport(context.Background(), sessFLV, site.DouyinLiveTransport("Mozilla/5.0 Test", true), []string{base + "/live.flv"}, &conn, filepath.Join(sessFLV.itemDir, "part-001.mp4.part")); err != nil || n == 0 {
+ t.Fatalf("FLV recording failed after empty itemDir removal: n=%d err=%v", n, err)
+ }
+}
+
+func TestOpenHTTPFLVStreamIdleTimeoutUsesSharedHelper(t *testing.T) {
+ release := make(chan struct{})
+ mux := http.NewServeMux()
+ mux.HandleFunc("/stall.flv", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "video/x-flv")
+ w.WriteHeader(http.StatusOK)
+ if f, ok := w.(http.Flusher); ok {
+ f.Flush()
+ }
+ select {
+ case <-release:
+ case <-r.Context().Done():
+ }
+ })
+ _, _, _, srv, _ := setupLiveTestHarness(t, mux)
+ defer close(release)
+
+ rc, err := OpenHTTPFLVStream(context.Background(), site.DouyinLiveTransport("Mozilla/5.0 Test", true), []string{srv.URL + "/stall.flv"}, 80*time.Millisecond)
+ if err != nil {
+ t.Fatalf("OpenHTTPFLVStream: %v", err)
+ }
+ defer rc.Close()
+
+ buf := make([]byte, 64)
+ start := time.Now()
+ _, readErr := rc.Read(buf)
+ if readErr == nil || !site.IsKind(readErr, site.ErrKindNetwork) {
+ t.Fatalf("expected network idle timeout error, got %v", readErr)
+ }
+ if elapsed := time.Since(start); elapsed > 2*time.Second {
+ t.Fatalf("idle read timeout took too long: %v", elapsed)
+ }
+}
+
+func TestFLVRemuxLongGOPNotKilledAsAudioOnlyAndMetadataType4(t *testing.T) {
+ sps := mustHex(t, testAVCSPSHex)
+ pps := mustHex(t, testAVCPPSHex)
+ idr := mustHex(t, testAVCSliceHex)
+ pSlice := mustHex(t, testAVCPSlice)
+
+ // 1. Verify raw Enhanced FLV PacketType=4 (Metadata) is ignored cleanly.
+ if flvExPacketMetadata != 4 {
+ t.Fatalf("flvExPacketMetadata = %d, want 4", flvExPacketMetadata)
+ }
+ metaTag := FLVTag{
+ Type: flvTagTypeVideo,
+ Timestamp: 0,
+ Data: []byte{0x80 | (1 << 4) | 4, 'h', 'v', 'c', '1', 0x01, 0x02},
+ }
+ parsedMeta, err := ParseFLVTag(metaTag)
+ if err != nil || parsedMeta.Kind != ParsedTagIgnored {
+ t.Fatalf("Enhanced FLV PacketType=4 metadata rejected: parsed=%+v err=%v", parsedMeta, err)
+ }
+
+ // 2. Video+audio stream with >3s GOP (4.5s of P-frames + audio before first keyframe) MUST NOT fail as audio-only.
+ fb := newFLVBuilder(0x05)
+ fb.writeClassicVideoConfig(0, flvVideoCodecAVC, buildAVCDecConfBytes(t, sps, pps, 4))
+ fb.writeAACConfig(0, testAACConfig48kStereo)
+
+ // 4.5s of non-keyframe video + audio before first IDR at 4500ms.
+ for ms := uint32(0); ms < 4500; ms += 40 {
+ fb.writeAACFrame(ms, testAACSilentFrame)
+ fb.writeClassicVideoFrame(ms, flvVideoCodecAVC, false, 0, packLengthPrefixedNALUs(4, pSlice))
+ }
+ // First IDR at 4500ms followed by 2 seconds of video+audio.
+ for i := 0; i < 50; i++ {
+ ts := uint32(4500 + i*40)
+ fb.writeAACFrame(ts, testAACSilentFrame)
+ isKey := i%25 == 0
+ nalu := pSlice
+ if isKey {
+ nalu = idr
+ }
+ fb.writeClassicVideoFrame(ts, flvVideoCodecAVC, isKey, 0, packLengthPrefixedNALUs(4, nalu))
+ }
+
+ _, summary, _ := remuxSinglePartAndFinalize(t, fb.buf.Bytes())
+ if !summary.MoovBeforeMdat || summary.TrackCount != 2 || summary.DurationSec < 1.8 {
+ t.Fatalf("4.5s GOP stream failed to remux cleanly: %+v", summary)
+ }
+}
+
+func TestFLVRemuxOutOfWindowInitialAudioDoesNotLoopForever(t *testing.T) {
+ sps := mustHex(t, testAVCSPSHex)
+ pps := mustHex(t, testAVCPPSHex)
+ idr := mustHex(t, testAVCSliceHex)
+ pSlice := mustHex(t, testAVCPSlice)
+
+ fb := newFLVBuilder(0x05)
+ fb.writeClassicVideoConfig(0, flvVideoCodecAVC, buildAVCDecConfBytes(t, sps, pps, 4))
+ fb.writeAACConfig(0, testAACConfig48kStereo)
+ // First video keyframe at 1000ms.
+ fb.writeClassicVideoFrame(1000, flvVideoCodecAVC, true, 0, packLengthPrefixedNALUs(4, idr))
+ // Out-of-window initial audio frames (>10s ahead of keyframe) must be dropped, not trigger rollover loop!
+ fb.writeAACFrame(30000, testAACSilentFrame)
+ fb.writeAACFrame(30021, testAACSilentFrame)
+ // Subsequent normal frames aligned with video.
+ for i := 1; i < 45; i++ {
+ ts := uint32(1000 + i*40)
+ fb.writeAACFrame(ts, testAACSilentFrame)
+ isKey := i%25 == 0
+ nalu := pSlice
+ if isKey {
+ nalu = idr
+ }
+ fb.writeClassicVideoFrame(ts, flvVideoCodecAVC, isKey, 0, packLengthPrefixedNALUs(4, nalu))
+ }
+
+ dir := t.TempDir()
+ parts, err := RemuxFLVStream(
+ context.Background(),
+ bytes.NewReader(fb.buf.Bytes()),
+ FLVRemuxOptions{},
+ func(partIndex int) (PartTarget, func(FLVCheckpoint, error) error, error) {
+ if partIndex > 3 {
+ return nil, nil, errors.New("infinite rollover loop detected")
+ }
+ p := filepath.Join(dir, fmt.Sprintf("part-%03d.mp4.part", partIndex))
+ f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0o600)
+ if err != nil {
+ return nil, nil, err
+ }
+ return f, func(_ FLVCheckpoint, _ error) error { return f.Close() }, nil
+ },
+ nil,
+ )
+ if err != nil {
+ t.Fatalf("RemuxFLVStream failed: %v", err)
+ }
+ if len(parts) != 1 {
+ t.Fatalf("expected 1 part without rollover loop, got %d parts", len(parts))
+ }
+}
+
+func TestFinalizeLivePartAcceptsCrossTrackLateAudioOffset(t *testing.T) {
+ sps, _ := hex.DecodeString(testAVCSPSHex)
+ pps, _ := hex.DecodeString(testAVCPPSHex)
+ init := mp4.CreateEmptyInit()
+ init.Moov.Mvhd.Timescale = 1000
+ v := init.AddEmptyTrack(30000, "video", "und")
+ if err := v.SetAVCDescriptor("avc1", [][]byte{sps}, [][]byte{pps}, true); err != nil {
+ t.Fatal(err)
+ }
+ v.Tkhd.Width, v.Tkhd.Height = mp4.Fixed32(640<<16), mp4.Fixed32(360<<16)
+ a := init.AddEmptyTrack(48000, "audio", "und")
+ if err := a.SetAACDescriptor(aac.AAClc, 48000); err != nil {
+ t.Fatal(err)
+ }
+ var buf bytes.Buffer
+ if err := init.Encode(&buf); err != nil {
+ t.Fatal(err)
+ }
+ videoSample := append([]byte{0, 0, 0, byte(len(sps))}, sps...)
+ audioSample := testAACSilentFrame
+ syncFlags := mp4.SampleFlags{SampleDependsOn: 2}.Encode()
+
+ // Video runs [0s .. 2.0s]; audio starts late at 1.8s and runs [1.8s .. 3.8s] -> combined timeline ~3.8s!
+ vf, _ := mp4.CreateFragment(1, 1)
+ for i := 0; i < 60; i++ {
+ vf.AddFullSample(mp4.FullSample{
+ Sample: mp4.Sample{Flags: syncFlags, Dur: 1000, Size: uint32(len(videoSample))},
+ DecodeTime: uint64(i) * 1000,
+ Data: videoSample,
+ })
+ }
+ if err := vf.Encode(&buf); err != nil {
+ t.Fatal(err)
+ }
+ af, _ := mp4.CreateFragment(2, 2)
+ audioStart := uint64(86400) // 1.8s at 48kHz
+ for i := 0; i < 94; i++ {
+ af.AddFullSample(mp4.FullSample{
+ Sample: mp4.Sample{Flags: syncFlags, Dur: 1024, Size: uint32(len(audioSample))},
+ DecodeTime: audioStart + uint64(i)*1024,
+ Data: audioSample,
+ })
+ }
+ if err := af.Encode(&buf); err != nil {
+ t.Fatal(err)
+ }
+
+ dir := t.TempDir()
+ partPath := filepath.Join(dir, "part-001.mp4.part")
+ finalPath := filepath.Join(dir, "part-001.mp4")
+ if err := os.WriteFile(partPath, buf.Bytes(), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ summary, err := finalizeLivePart(context.Background(), partPath, finalPath)
+ if err != nil {
+ t.Fatalf("finalizeLivePart rejected valid recording with >1s late audio offset: %v", err)
+ }
+ if !summary.MoovBeforeMdat || summary.DurationSec < 3.5 {
+ t.Fatalf("unexpected summary for late-audio recording: %+v", summary)
+ }
+}
+
+func TestReconnectInnerRetryNeverReusesExpiredDouyinURL(t *testing.T) {
+ const secUID = "MS4wLjABAAAA_reconnect_retry_dy"
+ const roomID = "7400000000000008801"
+ flv := buildSyntheticFLVBytes(t, "avc", 35)
+
+ var v1Hits, v2Hits atomic.Int32
+ mux := http.NewServeMux()
+ mux.HandleFunc("/live/v1.flv", func(w http.ResponseWriter, r *http.Request) {
+ v1Hits.Add(1)
+ w.Header().Set("Content-Type", "video/x-flv")
+ _, _ = w.Write(flv)
+ })
+ mux.HandleFunc("/live/v2.flv", func(w http.ResponseWriter, r *http.Request) {
+ v2Hits.Add(1)
+ w.Header().Set("Content-Type", "video/x-flv")
+ _, _ = w.Write(flv)
+ })
+
+ mgr, _, _, srv, _ := setupLiveTestHarness(t, mux)
+ prov := newFakeDouyinLiveProvider()
+ transport := site.DouyinLiveTransport("Mozilla/5.0 Test", true)
+
+ prov.statusFn = func(uid, _ string, _ int) (site.LiveStatus, error) {
+ st := site.LiveStateLive
+ if v2Hits.Load() >= 1 {
+ st = site.LiveStateOffline
+ }
+ return site.LiveStatus{
+ Site: site.Douyin, AccountUID: secUID, RoomID: roomID, WebRID: "880101",
+ Status: st, Title: "重连不复用旧URL", LiveSince: 1794024000,
+ }, nil
+ }
+ var selectCalls atomic.Int32
+ prov.streamFn = func(uid, _ string, _ []string, _ int) (site.LiveStreamPlan, error) {
+ n := selectCalls.Add(1)
+ switch n {
+ case 1:
+ return site.LiveStreamPlan{
+ Site: site.Douyin, AccountUID: secUID, RoomID: roomID, WebRID: "880101",
+ Status: site.LiveStateLive, Transport: site.LiveTransportHTTPFLV, Format: "flv", Codec: "avc", QualityName: "原画",
+ URLs: []string{srv.URL + "/live/v1.flv"}, Media: transport,
+ }, nil
+ case 2, 3:
+ // Transient errors during reconnect must stay in inner retry loop, NEVER reusing v1.flv!
+ return site.LiveStreamPlan{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindNetwork, Message: "临时网络错误"}
+ default:
+ return site.LiveStreamPlan{
+ Site: site.Douyin, AccountUID: secUID, RoomID: roomID, WebRID: "880101",
+ Status: site.LiveStateLive, Transport: site.LiveTransportHTTPFLV, Format: "flv", Codec: "avc", QualityName: "原画",
+ URLs: []string{srv.URL + "/live/v2.flv"}, Media: transport,
+ }, nil
+ }
+ }
+ mgr.RegisterSiteProvider(prov)
+
+ if _, err := mgr.StartDouyinRecording(context.Background(), secUID, "880101"); err != nil {
+ t.Fatalf("StartDouyinRecording: %v", err)
+ }
+ done := waitUntilRoomIdle(t, mgr, "douyin:live:"+roomID, 6*time.Second)
+ if v1Hits.Load() != 1 || v2Hits.Load() != 1 || done.RecordSegments != 2 {
+ t.Fatalf("expired URL reused or reconnect failed: v1Hits=%d v2Hits=%d segments=%d stop=%q", v1Hits.Load(), v2Hits.Load(), done.RecordSegments, done.StopReason)
+ }
+}
+
+func TestObserveTransferSpeedVBRNotFlaggedSlow(t *testing.T) {
+ mgr, _, _, _, _ := setupLiveTestHarness(t, http.NotFoundHandler())
+ sess := &recordSession{
+ roomID: 9901,
+ slow: newSlowDetector(),
+ nominalByteRate: 1_000_000, // 8 Mbps nominal
+ }
+ base := time.Date(2026, 11, 20, 10, 0, 0, 0, time.UTC)
+
+ // Healthy VBR stream: 200 KB for 2s of media downloaded in 1.0s (2x real-time, far below 8 Mbps nominal).
+ for i := 0; i < 40; i++ {
+ start := base.Add(time.Duration(i) * time.Second)
+ end := start.Add(time.Second)
+ mgr.observeTransferSpeed(sess, start, end, 200_000, 2.0, "part-001.mp4.part")
+ }
+ if len(sess.incidents) != 0 {
+ t.Fatalf("healthy real-time VBR stream falsely flagged slow: %+v", sess.incidents)
+ }
+
+ // Fallback when mediaDurationSec == 0: rate below 0.9 * nominal for >=30s triggers slow.
+ for i := 0; i < 35; i++ {
+ start := base.Add(time.Duration(100+i) * time.Second)
+ end := start.Add(time.Second)
+ mgr.observeTransferSpeed(sess, start, end, 200_000, 0, "part-001.mp4.part")
+ }
+ if len(sess.incidents) != 1 || sess.incidents[0].Kind != library.LiveIncidentSlow {
+ t.Fatalf("expected nominalByteRate fallback slow incident when mediaDurationSec<=0, got %+v", sess.incidents)
+ }
+}
+
+func TestShortSegmentClampsDurationAndRecoverySkipsMovedShortSegment(t *testing.T) {
+ if got := roundedLiveDurationSec(0.2); got != 1 {
+ t.Fatalf("roundedLiveDurationSec(0.2) = %d, want 1", got)
+ }
+ if got := roundedLiveDurationSec(0); got != 0 {
+ t.Fatalf("roundedLiveDurationSec(0) = %d, want 0", got)
+ }
+
+ mgr, lib, _ := regressionRecorder(t, http.NotFoundHandler())
+ lib.SetAllowMovedFiles(true)
+ dir := filepath.Join(lib.CacheDir(), "bilibili", "short-moved")
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ // Legacy finalized <0.5s segment with Duration=0, SHA256 set, Live.Segments DurationSec=0.35, moved away.
+ saved, err := lib.SaveItem(dir, library.ItemMetadata{
+ Site: "bilibili",
+ Kind: "live",
+ ID: "live:555:100",
+ Status: "complete",
+ Media: []library.MediaFile{{
+ Role: "live_segment", Path: "part-001.mp4", Bytes: 12345, SHA256: "deadbeef", Duration: 0,
+ }},
+ Live: &library.LiveRecordingInfo{
+ RoomID: 555, LiveSince: 100, StopReason: "ended",
+ Segments: []library.LiveSegmentInfo{{File: "part-001.mp4", Bytes: 12345, SHA256: "deadbeef", DurationSec: 0.35}},
+ },
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ mgr.RecoverOrphanParts()
+
+ got, ok, err := lib.GetItem(saved.ItemKey)
+ if err != nil || !ok {
+ t.Fatalf("GetItem: ok=%v err=%v", ok, err)
+ }
+ if got.Status != "complete" || len(got.PendingParts) != 0 || len(got.Live.Incidents) != 0 {
+ t.Fatalf("RecoverOrphanParts corrupted moved short segment: %+v", got)
+ }
+}
+
+func TestDouyinStatusCacheInvalidationOfflinePreserveAndCacheHitAutoStart(t *testing.T) {
+ const secUID = "MS4wLjABAAAA_cache_truth_dy"
+ const roomID = "7400000000000007701"
+ flv := buildSyntheticFLVBytes(t, "avc", 35)
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/live/stream.flv", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "video/x-flv")
+ _, _ = w.Write(flv)
+ })
+ mgr, _, subMgr, srv, _ := setupLiveTestHarness(t, mux)
+ prov := newFakeDouyinLiveProvider()
+ transport := site.DouyinLiveTransport("Mozilla/5.0 Test", true)
+
+ var online atomic.Bool
+ online.Store(true)
+ prov.statusFn = func(uid, _ string, _ int) (site.LiveStatus, error) {
+ if online.Load() {
+ return site.LiveStatus{
+ Site: site.Douyin, AccountUID: secUID, RoomID: roomID, WebRID: "770101",
+ Status: site.LiveStateLive, Title: "开播中", LiveSince: 1794024000,
+ }, nil
+ }
+ return site.LiveStatus{
+ Site: site.Douyin, AccountUID: secUID, WebRID: "770101",
+ Status: site.LiveStateOffline,
+ }, nil
+ }
+ prov.streamFn = func(uid, _ string, _ []string, _ int) (site.LiveStreamPlan, error) {
+ return site.LiveStreamPlan{
+ Site: site.Douyin, AccountUID: secUID, RoomID: roomID, WebRID: "770101",
+ Status: site.LiveStateLive, Transport: site.LiveTransportHTTPFLV, Format: "flv", Codec: "avc", QualityName: "原画",
+ URLs: []string{srv.URL + "/live/stream.flv"}, Media: transport,
+ }, nil
+ }
+ mgr.RegisterSiteProvider(prov)
+
+ // 1. Prime cache while account is NOT auto-record.
+ if _, err := mgr.CheckAccountLiveStatus(context.Background(), site.Douyin, secUID, "770101", true); err != nil {
+ t.Fatal(err)
+ }
+ // Seed incidents + RecordItemDir on douyin:live:, then switch to offline (douyin:user:).
+ mgr.mu.Lock()
+ st := mgr.douyinStates["douyin:live:"+roomID]
+ st.RecordItemDir = filepath.Join("synthetic", "dir", roomID)
+ st.StopReason = "ended"
+ st.LastError = "last-err"
+ st.Incidents = []library.LiveIncident{{Kind: library.LiveIncidentReconnect, At: "2026-11-20T00:00:00Z", Count: 1}}
+ mgr.douyinStates["douyin:live:"+roomID] = st
+ mgr.mu.Unlock()
+
+ online.Store(false)
+ offSt, err := mgr.CheckAccountLiveStatus(context.Background(), site.Douyin, secUID, "770101", true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if offSt.RoomKey != "douyin:user:"+secUID || offSt.RecordItemDir != st.RecordItemDir || len(offSt.Incidents) != 1 || offSt.StopReason != "ended" {
+ t.Fatalf("offline transition lost RecordItemDir/Incidents/StopReason: %+v", offSt)
+ }
+
+ // 2. ClearIdleIncidents must immediately reflect in CachedAccountState (not stale douyinStatusCache).
+ if !mgr.ClearIdleIncidents("douyin", "", secUID) {
+ t.Fatal("expected ClearIdleIncidents to clear offline Douyin incidents")
+ }
+ cachedAfterClear, ok := mgr.CachedAccountState(site.Douyin, secUID)
+ if !ok || len(cachedAfterClear.Incidents) != 0 {
+ t.Fatalf("CachedAccountState returned stale incidents after ClearIdleIncidents: %+v", cachedAfterClear)
+ }
+
+ // 3. Cache hit in CheckAccountLiveStatus evaluates autoStart when AutoRecord is enabled!
+ online.Store(true)
+ if _, err := mgr.CheckAccountLiveStatus(context.Background(), site.Douyin, secUID, "770101", true); err != nil {
+ t.Fatal(err)
+ }
+ callsBefore := prov.statusCallCount(secUID)
+ // Enable AutoRecord subscription now, then refresh WITHOUT force (cache hit!).
+ if _, err := subMgr.Create("自动录播", "", []subscription.AccountRef{{Site: "douyin", UID: secUID, Name: "抖音主播"}}, subscription.SubRules{AutoRecord: true}); err != nil {
+ t.Fatal(err)
+ }
+ online.Store(false) // so recording finishes cleanly after 1 part
+ if _, err := mgr.CheckAccountLiveStatus(context.Background(), site.Douyin, secUID, "770101", false); err != nil {
+ t.Fatal(err)
+ }
+ if prov.statusCallCount(secUID) != callsBefore {
+ t.Fatalf("expected cache hit with 0 extra status calls, before=%d after=%d", callsBefore, prov.statusCallCount(secUID))
+ }
+ if prov.streamCallCount("770101") == 0 {
+ t.Fatal("cache hit in CheckAccountLiveStatus skipped autoStart")
+ }
+ waitUntilRoomIdle(t, mgr, "douyin:live:"+roomID, 5*time.Second)
+
+ // After session ended with StopReason="ended", CachedAccountState must report offline (not stuck live).
+ cachedEnded, ok := mgr.CachedAccountState(site.Douyin, secUID)
+ if !ok || cachedEnded.LiveStatus != 0 {
+ t.Fatalf("CachedAccountState stuck live after session ended: ok=%v st=%+v", ok, cachedEnded)
+ }
+}
+
+func TestRefreshForAccountsFiltersStrictlyToRequestedBilibiliUIDs(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("/room/v1/Room/get_status_info_by_uids", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": 0,
+ "data": map[string]any{
+ "4001": map[string]any{"uid": 4001, "room_id": 9401, "title": "Live 1", "uname": "U4001", "live_status": 1, "live_time": 1794024000},
+ "4002": map[string]any{"uid": 4002, "room_id": 9402, "title": "Offline 2", "uname": "U4002", "live_status": 0},
+ },
+ })
+ })
+ mgr, _, _, _, _ := setupLiveTestHarness(t, mux)
+
+ // Pre-populate another live Bilibili room and a live Douyin room.
+ mgr.mu.Lock()
+ mgr.states[9401] = RoomState{Site: "bilibili", AccountUID: "4001", UID: 4001, RoomID: 9401, RoomIDStr: "9401", RoomKey: "bilibili:live:9401", LiveStatus: 1}
+ mgr.douyinStates["douyin:live:7400999"] = RoomState{Site: "douyin", AccountUID: "sec_other", RoomIDStr: "7400999", RoomKey: "douyin:live:7400999", LiveStatus: 1}
+ mgr.mu.Unlock()
+
+ rooms, err := mgr.RefreshForAccounts(context.Background(), []int64{4002})
+ if err != nil {
+ t.Fatalf("RefreshForAccounts: %v", err)
+ }
+ if len(rooms) != 1 || rooms[0].Site != "bilibili" || rooms[0].UID != 4002 || rooms[0].RoomID != 9402 {
+ t.Fatalf("RefreshForAccounts returned unrelated rooms: %+v", rooms)
+ }
+}
+
+func TestEmptyTargetAndPrefixGuardsNeverStopWrongRecordingOrMatchIdleRoom(t *testing.T) {
+ const secUID = "MS4wLjABAAAA_empty_guard_dy"
+ const roomID = "7400000000000006601"
+ flv := buildSyntheticFLVBytes(t, "avc", 45)
+ holdDone := make(chan struct{})
+ started := make(chan struct{}, 1)
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/live/hold.flv", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "video/x-flv")
+ _, _ = w.Write(flv)
+ if f, ok := w.(http.Flusher); ok {
+ f.Flush()
+ }
+ select {
+ case started <- struct{}{}:
+ default:
+ }
+ select {
+ case <-holdDone:
+ case <-r.Context().Done():
+ }
+ })
+ mgr, _, _, srv, _ := setupLiveTestHarness(t, mux)
+ prov := newFakeDouyinLiveProvider()
+ transport := site.DouyinLiveTransport("Mozilla/5.0 Test", true)
+ prov.statusFn = func(uid, _ string, _ int) (site.LiveStatus, error) {
+ return site.LiveStatus{Site: site.Douyin, AccountUID: secUID, RoomID: roomID, WebRID: "", Status: site.LiveStateLive, Title: "无WebRID直播"}, nil
+ }
+ prov.streamFn = func(uid, _ string, _ []string, _ int) (site.LiveStreamPlan, error) {
+ return site.LiveStreamPlan{
+ Site: site.Douyin, AccountUID: secUID, RoomID: roomID, WebRID: "",
+ Status: site.LiveStateLive, Transport: site.LiveTransportHTTPFLV, Format: "flv", Codec: "avc",
+ URLs: []string{srv.URL + "/live/hold.flv"}, Media: transport,
+ }, nil
+ }
+ mgr.RegisterSiteProvider(prov)
+
+ // Add idle Bilibili and Douyin rooms with empty RecordSession / WebRID.
+ mgr.mu.Lock()
+ mgr.states[9111] = RoomState{Site: "bilibili", UID: 111, RoomID: 9111}
+ mgr.douyinStates["douyin:user:idle_sec"] = RoomState{Site: "douyin", AccountUID: "idle_sec"}
+ mgr.mu.Unlock()
+
+ if _, err := mgr.StartDouyinRecording(context.Background(), secUID, roomID); err != nil {
+ t.Fatalf("StartDouyinRecording: %v", err)
+ }
+ <-started
+
+ // Empty / malformed keys must error and must NOT stop the active Douyin session with empty webRID.
+ if _, err := mgr.StopDouyinRecording(""); err == nil {
+ t.Fatal("expected error for StopDouyinRecording(\"\")")
+ }
+ if _, err := mgr.StopRecordingByKey(""); err == nil {
+ t.Fatal("expected error for StopRecordingByKey(\"\")")
+ }
+ if _, err := mgr.StopRecordingByKey("bilibili:live:invalid"); err == nil {
+ t.Fatal("expected error for StopRecordingByKey(\"bilibili:live:invalid\")")
+ }
+ if _, err := mgr.StopRecording(0); err == nil {
+ t.Fatal("expected error for StopRecording(0)")
+ }
+ if _, err := mgr.StopRecordingByKey("bilibili:user:999999"); err != nil {
+ t.Fatalf("StopRecordingByKey(bilibili:user:999999) unexpected error: %v", err)
+ }
+
+ // Active Douyin session must still be running!
+ if st, ok := mgr.CachedAccountState(site.Douyin, secUID); !ok || !st.Recording {
+ t.Fatalf("active Douyin recording was stopped by empty/unrelated key: ok=%v st=%+v", ok, st)
+ }
+
+ // RecordingPreview with bare prefixes must NOT match idle rooms.
+ for _, badKey := range []string{"", " ", "live:", "douyin:", "douyin:live:", "douyin:user:", "bilibili:", "bilibili:live:"} {
+ if pv, ok := mgr.RecordingPreview(badKey); ok {
+ t.Fatalf("RecordingPreview(%q) unexpectedly matched %+v", badKey, pv)
+ }
+ }
+
+ close(holdDone)
+ if _, err := mgr.StopDouyinRecording(roomID); err != nil {
+ t.Fatalf("StopDouyinRecording(%s): %v", roomID, err)
+ }
+}
+
+func TestCancelRecordingsPreservesStopReasonAndReentrantStopForSiteNoDeadlock(t *testing.T) {
+ initBytes, fragBytes := splitSyntheticHLSInitAndFrag(t)
+ var hits atomic.Int32
+ var srvURL string
+ var mgrRef atomic.Pointer[Manager]
+ var reentrantDone atomic.Bool
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/room/v1/Room/get_status_info_by_uids", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
+ "6001": map[string]any{"uid": 6001, "room_id": 9601, "title": "Reentrant", "uname": "U6001", "live_status": 1, "live_time": 1794024000},
+ }})
+ })
+ mux.HandleFunc("/room/v1/Room/room_init", func(w http.ResponseWriter, r *http.Request) {
+ // On reconnect (call >= 2), trigger -101 auth expired which synchronously invokes StopForSite on the recording goroutine!
+ if hits.Load() >= 2 {
+ _ = json.NewEncoder(w).Encode(map[string]any{"code": -101, "message": "账号未登录"})
+ return
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
+ "room_id": 9601, "uid": 6001, "live_status": 1, "live_time": 1794024000,
+ }})
+ })
+ mux.HandleFunc("/xlive/web-room/v2/index/getRoomPlayInfo", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
+ "room_id": 9601, "uid": 6001, "live_status": 1,
+ "playurl_info": map[string]any{"playurl": map[string]any{"stream": []map[string]any{{
+ "protocol_name": "http_hls",
+ "format": []map[string]any{{"format_name": "fmp4", "codec": []map[string]any{{
+ "codec_name": "avc", "current_qn": 10000, "base_url": "/hls/index.m3u8",
+ "url_info": []map[string]any{{"host": srvURL, "extra": ""}},
+ }}}},
+ }}}},
+ }})
+ })
+ mux.HandleFunc("/hls/index.m3u8", func(w http.ResponseWriter, r *http.Request) {
+ if hits.Add(1) == 1 {
+ _, _ = w.Write([]byte("#EXTM3U\n#EXT-X-TARGETDURATION:1\n#EXT-X-MEDIA-SEQUENCE:1\n#EXT-X-MAP:URI=\"/hls/init.mp4\"\n#EXTINF:1,\n/hls/seg1.m4s\n"))
+ return
+ }
+ w.WriteHeader(http.StatusBadGateway) // force reconnect -> RoomInit -> -101
+ })
+ mux.HandleFunc("/hls/init.mp4", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write(initBytes) })
+ mux.HandleFunc("/hls/seg1.m4s", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write(fragBytes) })
+
+ mgr, _, _, srv, _ := setupLiveTestHarness(t, mux)
+ srvURL = srv.URL
+ mgrRef.Store(mgr)
+ mgr.finalizeTimeout = 10 * time.Second
+
+ // Register re-entrant StopForSite inside Bilibili client's AuthExpiredHandler (mirrors service/backend.go).
+ mgr.client.SetAuthExpiredHandler(func() {
+ if m := mgrRef.Load(); m != nil {
+ m.StopForSite(site.Bilibili, "auth_required")
+ reentrantDone.Store(true)
+ }
+ })
+
+ start := time.Now()
+ if _, err := mgr.StartRecording(context.Background(), 9601); err != nil {
+ t.Fatalf("StartRecording: %v", err)
+ }
+ done := waitUntilRoomIdle(t, mgr, "bilibili:live:9601", 4*time.Second)
+ if elapsed := time.Since(start); elapsed > 4*time.Second {
+ t.Fatalf("re-entrant StopForSite deadlocked or took too long: %v", elapsed)
+ }
+ if !reentrantDone.Load() || done.StopReason != "auth_required" {
+ t.Fatalf("expected re-entrant StopForSite to stop with auth_required: reentrant=%v state=%+v", reentrantDone.Load(), done)
+ }
+
+ // Verify CancelRecordings preserves an existing stopReason.
+ dummyCtx, dummyCancel := context.WithCancel(context.Background())
+ defer dummyCancel()
+ s := &recordSession{roomID: 1234, stopReason: "user_stop", cancel: dummyCancel, doneCh: make(chan struct{})}
+ mgr.mu.Lock()
+ mgr.sessions[1234] = s
+ mgr.mu.Unlock()
+ mgr.CancelRecordings("app_closed")
+ if s.stopReason != "user_stop" || dummyCtx.Err() == nil {
+ t.Fatalf("CancelRecordings overwrote existing stopReason or failed to cancel: reason=%q err=%v", s.stopReason, dummyCtx.Err())
+ }
+ mgr.mu.Lock()
+ delete(mgr.sessions, 1234)
+ mgr.mu.Unlock()
+}
+
+func TestPerKeyStartDoesNotBlockStopOrOtherRoomsAndHintPrunesUserKey(t *testing.T) {
+ roomABlocked := make(chan struct{})
+ roomARelease := make(chan struct{})
+ initBytes, fragBytes := splitSyntheticHLSInitAndFrag(t)
+ var srvURL string
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/room/v1/Room/room_init", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
+ "room_id": 9702, "uid": 7002, "live_status": 1, "live_time": 1794024000,
+ }})
+ })
+ mux.HandleFunc("/room/v1/Room/get_status_info_by_uids", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
+ "7002": map[string]any{"uid": 7002, "room_id": 9702, "title": "Room B", "uname": "U7002", "live_status": 1, "live_time": 1794024000},
+ }})
+ })
+ mux.HandleFunc("/xlive/web-room/v2/index/getRoomPlayInfo", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
+ "room_id": 9702, "uid": 7002, "live_status": 1,
+ "playurl_info": map[string]any{"playurl": map[string]any{"stream": []map[string]any{{
+ "protocol_name": "http_hls",
+ "format": []map[string]any{{"format_name": "fmp4", "codec": []map[string]any{{
+ "codec_name": "avc", "current_qn": 10000, "base_url": "/hls/b.m3u8",
+ "url_info": []map[string]any{{"host": srvURL, "extra": ""}},
+ }}}},
+ }}}},
+ }})
+ })
+ mux.HandleFunc("/hls/b.m3u8", func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte("#EXTM3U\n#EXT-X-TARGETDURATION:1\n#EXT-X-MEDIA-SEQUENCE:1\n#EXT-X-MAP:URI=\"/hls/init.mp4\"\n#EXTINF:1,\n/hls/seg1.m4s\n"))
+ })
+ mux.HandleFunc("/hls/init.mp4", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write(initBytes) })
+ mux.HandleFunc("/hls/seg1.m4s", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write(fragBytes) })
+
+ var stateEvents []RoomState
+ var evMu sync.Mutex
+ mgr, _, _, srv, _ := setupLiveTestHarness(t, mux)
+ srvURL = srv.URL
+ mgr.onState = func(st RoomState) {
+ evMu.Lock()
+ stateEvents = append(stateEvents, st)
+ evMu.Unlock()
+ }
+
+ // Register a Douyin provider whose SelectLiveStream blocks until cancelled by Manager.Stop().
+ blockingProv := &blockingDouyinProvider{blocked: roomABlocked, release: roomARelease}
+ mgr.RegisterSiteProvider(blockingProv)
+
+ // Start Douyin Room A in background (blocked in SelectLiveStream).
+ roomADone := make(chan error, 1)
+ go func() {
+ _, err := mgr.StartDouyinRecording(context.Background(), "MS4wLjABAAAA_blocked_start_a", "970101")
+ roomADone <- err
+ }()
+ <-roomABlocked
+
+ // Unrelated Bilibili Room B must start immediately without being blocked by Room A!
+ stB, err := mgr.StartRecording(context.Background(), 9702)
+ if err != nil || !stB.Recording {
+ close(roomARelease)
+ t.Fatalf("unrelated Room B was blocked by Room A start: st=%+v err=%v", stB, err)
+ }
+
+ // ObserveAccountLiveHint prunes old douyin:user:, invalidates cache, and emits onState.
+ const hintUID = "MS4wLjABAAAA_hint_prune"
+ mgr.mu.Lock()
+ mgr.douyinStates["douyin:user:"+hintUID] = RoomState{Site: "douyin", AccountUID: hintUID, RoomKey: "douyin:user:" + hintUID, LiveStatus: 0}
+ mgr.douyinStatusCache[hintUID] = douyinCachedStatusEntry{fetchedAt: mgr.nowLocked()}
+ mgr.mu.Unlock()
+
+ mgr.ObserveAccountLiveHint(site.Douyin, hintUID, "55501", "740055501")
+ mgr.mu.Lock()
+ _, oldStillPresent := mgr.douyinStates["douyin:user:"+hintUID]
+ _, cacheStillPresent := mgr.douyinStatusCache[hintUID]
+ mgr.mu.Unlock()
+ if oldStillPresent || cacheStillPresent {
+ t.Fatalf("ObserveAccountLiveHint failed to prune old user key or cache: old=%v cache=%v", oldStillPresent, cacheStillPresent)
+ }
+ evMu.Lock()
+ sawHintEvent := false
+ for _, ev := range stateEvents {
+ if ev.RoomKey == "douyin:live:740055501" && ev.LiveStatus == 1 {
+ sawHintEvent = true
+ }
+ }
+ evMu.Unlock()
+ if !sawHintEvent {
+ t.Fatal("ObserveAccountLiveHint did not emit onState")
+ }
+
+ // Stop() must cancel Room A's in-flight start and complete quickly (never blocked by Room A).
+ stopDone := make(chan struct{})
+ go func() {
+ mgr.Stop()
+ close(stopDone)
+ }()
+ select {
+ case <-stopDone:
+ case <-time.After(3 * time.Second):
+ close(roomARelease)
+ t.Fatal("Manager.Stop() blocked on slow StartRecording I/O")
+ }
+ select {
+ case <-roomADone:
+ case <-time.After(2 * time.Second):
+ close(roomARelease)
+ t.Fatal("Room A StartRecording was not cancelled by Manager.Stop()")
+ }
+}
+
+func TestM3U8ParserEdgeCasesAndRecoveryDedupAndMultiSubORMerge(t *testing.T) {
+ // 1. UTF-8 BOM + quoted URI containing comma + sticky EXT-X-KEY encryption + EXT-X-MAP BYTERANGE.
+ p1 := parseM3U8PlaylistDetails("\uFEFF#EXTM3U\n#EXT-X-TARGETDURATION:2\n#EXT-X-KEY:METHOD=AES-128,URI=\"https://cdn.example/k\"\n#EXT-X-KEY:METHOD=NONE\n#EXT-X-MAP:URI=\"https://cdn.example/a,b/init.mp4\"\n#EXTINF:2.0,\nseg1.m4s\n", "https://cdn.example/live/index.m3u8")
+ if !p1.valid || !p1.encrypted || p1.mapURI != "https://cdn.example/a,b/init.mp4" {
+ t.Fatalf("unexpected BOM/sticky-key/comma-URI parse: %+v", p1)
+ }
+
+ p2 := parseM3U8PlaylistDetails("#EXTM3U\n#EXT-X-MAP:URI=\"init.mp4\",BYTERANGE=\"720@0\"\n#EXTINF:1.0,\nseg1.m4s\n", "https://cdn.example/index.m3u8")
+ if p2.valid {
+ t.Fatalf("expected EXT-X-MAP BYTERANGE to invalidate playlist: %+v", p2)
+ }
+
+ p3 := parseM3U8PlaylistDetails("#EXTM3U\n#EXT-X-STREAM-INF:CODECS=\"avc1.640032,mp4a.40.2\",BANDWIDTH=5000000\nhigh.m3u8\n", "https://cdn.example/master.m3u8")
+ if v, ok := p3.bestVariantInfo(); !ok || v.bandwidth != 5000000 {
+ t.Fatalf("quoted CODECS comma broke BANDWIDTH parsing: v=%+v ok=%v", v, ok)
+ }
+
+ // 2. RecoverOrphanParts: no duplicate convert_failed across restarts, clears empty PendingParts & marks 0-segment "failed",
+ // and backfills Codec without applying Bilibili quality fallback on Douyin.
+ mgr, lib, _ := regressionRecorder(t, http.NotFoundHandler())
+ corruptDir := filepath.Join(lib.CacheDir(), "bilibili", "corrupt-dedup")
+ _ = os.MkdirAll(corruptDir, 0o700)
+ _ = os.WriteFile(filepath.Join(corruptDir, "part-001.mp4.part"), []byte("corrupt-bytes"), 0o600)
+ cMeta, _ := lib.SaveItem(corruptDir, library.ItemMetadata{
+ Site: "bilibili", Kind: "live", ID: "live:801:1", Status: "recording",
+ PendingParts: []string{"part-001.mp4.part"},
+ Live: &library.LiveRecordingInfo{RoomID: 801, LiveSince: 1},
+ })
+ mgr.RecoverOrphanParts()
+ mgr.RecoverOrphanParts()
+ gotCorrupt, _, _ := lib.GetItem(cMeta.ItemKey)
+ if gotCorrupt.Live == nil || len(gotCorrupt.Live.Incidents) != 1 {
+ t.Fatalf("RecoverOrphanParts duplicated convert_failed across restarts: %+v", gotCorrupt.Live)
+ }
+
+ emptyDir := filepath.Join(lib.CacheDir(), "douyin", "empty-pending")
+ _ = os.MkdirAll(emptyDir, 0o700)
+ eMeta, _ := lib.SaveItem(emptyDir, library.ItemMetadata{
+ Site: "douyin", Kind: "live", ID: "live:802", Status: "recording",
+ PendingParts: []string{"part-001.mp4.part"}, // crashed before .part file was created
+ Live: &library.LiveRecordingInfo{RoomIDStr: "802", PendingFile: "part-001.mp4.part", PendingBytes: 0},
+ })
+ mgr.RecoverOrphanParts()
+ rawEmpty, err := os.ReadFile(filepath.Join(emptyDir, "item.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ diskEmpty, err := library.ParseItemMetadata(rawEmpty)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(diskEmpty.PendingParts) != 0 || diskEmpty.Status != "failed" || len(diskEmpty.Live.Incidents) != 0 {
+ t.Fatalf("empty PendingParts not cleared or marked failed in item.json: %+v", diskEmpty)
+ }
+ gotEmpty, _, _ := lib.GetItem(eMeta.ItemKey)
+ if len(gotEmpty.PendingParts) != 0 || gotEmpty.Status == "complete" || len(gotEmpty.Live.Incidents) != 0 {
+ t.Fatalf("empty PendingParts not cleared or marked complete: %+v", gotEmpty)
+ }
+
+ dyValidDir := filepath.Join(lib.CacheDir(), "douyin", "valid-codec-backfill")
+ _ = os.MkdirAll(dyValidDir, 0o700)
+ initBytes, fragBytes := regressionLiveSamples(t)
+ _ = os.WriteFile(filepath.Join(dyValidDir, "part-001.mp4.part"), append(append([]byte(nil), initBytes...), fragBytes...), 0o600)
+ dyValidMeta, _ := lib.SaveItem(dyValidDir, library.ItemMetadata{
+ Site: "douyin", Kind: "live", ID: "live:803", Status: "recording",
+ PendingParts: []string{"part-001.mp4.part"},
+ Live: &library.LiveRecordingInfo{RoomIDStr: "803", Quality: 10000, QualityName: "", Codec: ""},
+ })
+ mgr.RecoverOrphanParts()
+ gotDY, _, _ := lib.GetItem(dyValidMeta.ItemKey)
+ if gotDY.Status != "complete" || gotDY.Live.Codec == "" || gotDY.Live.QualityName != "" {
+ t.Fatalf("Douyin recovery should backfill Codec and skip Bilibili quality fallback: %+v", gotDY.Live)
+ }
+
+ // 3. Multi-subscription OR-merge for LiveNotify / AutoRecord + acc.Site == "".
+ uids, subByUID, _ := collectBilibiliRefreshTargets([]subscription.Subscription{
+ {Name: "SubA", Enabled: true, Accounts: []subscription.AccountRef{{Site: "bilibili", UID: "8001", Name: "U8001"}}},
+ {Name: "SubB", Enabled: true, LiveNotify: true, Rules: subscription.SubRules{AutoRecord: true}, Accounts: []subscription.AccountRef{{Site: "", UID: "8001", Name: "U8001"}}},
+ }, nil, false)
+ if len(uids) != 1 || uids[0] != 8001 || !subByUID[8001].LiveNotify || !subByUID[8001].Rules.AutoRecord {
+ t.Fatalf("multi-sub OR-merge failed: uids=%v merged=%+v", uids, subByUID[8001])
+ }
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/room/v1/Room/get_status_info_by_uids", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
+ "8001": map[string]any{"uid": 8001, "room_id": 9801, "title": "Empty-Site", "uname": "U8001", "live_status": 1, "live_time": 1794024000},
+ }})
+ })
+ var notified atomic.Int32
+ mgr2, _, subMgr2, _, _ := setupLiveTestHarness(t, mux)
+ mgr2.onNotify = func(n Notification) {
+ if n.UID == 8001 {
+ notified.Add(1)
+ }
+ }
+ if _, err := subMgr2.Upsert(subscription.Subscription{
+ Name: "SubEmptySite",
+ Enabled: true,
+ LiveNotify: true,
+ Accounts: []subscription.AccountRef{{Site: "", UID: "8001", Name: "U8001"}},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := mgr2.PollNow(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if notified.Load() != 1 {
+ t.Fatalf("empty acc.Site subscription failed to emit notification: count=%d", notified.Load())
+ }
+}
+
+func TestBilibiliReconnectInnerRetryNeverUsesZeroedSelectionAndAudioStallBounded(t *testing.T) {
+ // 1. Bilibili reconnect inner retry loop survives transient LiveRoomPlayInfo errors without using zeroed selection.
+ initBytes, fragBytes := splitSyntheticHLSInitAndFrag(t)
+ var srvURL string
+ var playInfoCalls, m3u8Calls atomic.Int32
+ var roomLive atomic.Bool
+ roomLive.Store(true)
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/room/v1/Room/get_status_info_by_uids", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
+ "8101": map[string]any{"uid": 8101, "room_id": 9811, "title": "Bili Retry", "uname": "U8101", "live_status": 1, "live_time": 1794024000},
+ }})
+ })
+ mux.HandleFunc("/room/v1/Room/room_init", func(w http.ResponseWriter, r *http.Request) {
+ st := 0
+ if roomLive.Load() {
+ st = 1
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
+ "room_id": 9811, "uid": 8101, "live_status": st, "live_time": 1794024000,
+ }})
+ })
+ mux.HandleFunc("/xlive/web-room/v2/index/getRoomPlayInfo", func(w http.ResponseWriter, r *http.Request) {
+ call := playInfoCalls.Add(1)
+ if call == 2 || call == 3 {
+ w.WriteHeader(http.StatusBadGateway) // transient error during reconnect!
+ return
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
+ "room_id": 9811, "uid": 8101, "live_status": 1,
+ "playurl_info": map[string]any{"playurl": map[string]any{"stream": []map[string]any{{
+ "protocol_name": "http_hls",
+ "format": []map[string]any{{"format_name": "fmp4", "codec": []map[string]any{{
+ "codec_name": "avc", "current_qn": 10000, "base_url": "/hls/index.m3u8",
+ "url_info": []map[string]any{{"host": srvURL, "extra": ""}},
+ }}}},
+ }}}},
+ }})
+ })
+ mux.HandleFunc("/hls/index.m3u8", func(w http.ResponseWriter, r *http.Request) {
+ switch m3u8Calls.Add(1) {
+ case 1:
+ _, _ = w.Write([]byte("#EXTM3U\n#EXT-X-TARGETDURATION:1\n#EXT-X-MEDIA-SEQUENCE:1\n#EXT-X-MAP:URI=\"/hls/init.mp4\"\n#EXTINF:1,\n/hls/seg1.m4s\n"))
+ case 2:
+ w.WriteHeader(http.StatusBadGateway) // trigger reconnect
+ default:
+ roomLive.Store(false)
+ _, _ = w.Write([]byte("#EXTM3U\n#EXT-X-TARGETDURATION:1\n#EXT-X-MEDIA-SEQUENCE:2\n#EXT-X-MAP:URI=\"/hls/init.mp4\"\n#EXTINF:1,\n/hls/seg2.m4s\n#EXT-X-ENDLIST\n"))
+ }
+ })
+ mux.HandleFunc("/hls/init.mp4", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write(initBytes) })
+ mux.HandleFunc("/hls/seg1.m4s", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write(fragBytes) })
+ mux.HandleFunc("/hls/seg2.m4s", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write(fragBytes) })
+
+ mgr, _, _, srv, _ := setupLiveTestHarness(t, mux)
+ srvURL = srv.URL
+
+ // Manual start must also clear any previous stoppedBroadcasts entry.
+ mgr.mu.Lock()
+ mgr.stoppedBroadcasts[9811] = 1794024000
+ mgr.mu.Unlock()
+
+ if _, err := mgr.StartRecording(context.Background(), 9811); err != nil {
+ t.Fatalf("StartRecording: %v", err)
+ }
+ mgr.mu.Lock()
+ _, stillSuppressed := mgr.stoppedBroadcasts[9811]
+ mgr.mu.Unlock()
+ if stillSuppressed {
+ t.Fatal("manual StartRecording did not clear stoppedBroadcasts")
+ }
+
+ done := waitUntilRoomIdle(t, mgr, "bilibili:live:9811", 6*time.Second)
+ if done.RecordSegments != 2 || playInfoCalls.Load() != 4 {
+ t.Fatalf("Bilibili reconnect retry failed: segments=%d playInfoCalls=%d state=%+v", done.RecordSegments, playInfoCalls.Load(), done)
+ }
+
+ // 2. Audio buffer stays bounded if video track stalls while audio keeps arriving.
+ sps := mustHex(t, testAVCSPSHex)
+ pps := mustHex(t, testAVCPPSHex)
+ idr := mustHex(t, testAVCSliceHex)
+ fb := newFLVBuilder(0x05)
+ fb.writeClassicVideoConfig(0, flvVideoCodecAVC, buildAVCDecConfBytes(t, sps, pps, 4))
+ fb.writeAACConfig(0, testAACConfig48kStereo)
+ fb.writeClassicVideoFrame(0, flvVideoCodecAVC, true, 0, packLengthPrefixedNALUs(4, idr))
+ for i := 0; i < maxPreInitAudioSamples+400; i++ {
+ fb.writeAACFrame(uint32(i*20), testAACSilentFrame)
+ }
+ remuxer := NewFLVRemuxer(bytes.NewReader(fb.buf.Bytes()), FLVRemuxOptions{})
+ partPath := filepath.Join(t.TempDir(), "stall.mp4.part")
+ f, err := os.Create(partPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cp, err := remuxer.WritePart(context.Background(), f, nil)
+ _ = f.Close()
+ if err != nil || cp.BytesWritten <= 0 {
+ t.Fatalf("video-stalled FLV stream failed: cp=%+v err=%v", cp, err)
+ }
+}
+
+func TestFinishPartRetainsPendingPartsOnSaveErrorAndEmitsOnState(t *testing.T) {
+ initBytes, fragBytes := regressionLiveSamples(t)
+ mgr, lib, _ := regressionRecorder(t, http.NotFoundHandler())
+
+ var stateUpdates atomic.Int32
+ mgr.onState = func(st RoomState) {
+ if st.RoomID == 42 {
+ stateUpdates.Add(1)
+ }
+ }
+
+ sess := regressionLiveSession(t, lib)
+ mgr.mu.Lock()
+ mgr.states[42] = RoomState{Site: "bilibili", RoomID: 42, Recording: true}
+ mgr.sessions[42] = sess
+ mgr.mu.Unlock()
+
+ partPath := filepath.Join(sess.itemDir, "part-001.mp4.part")
+ if err := os.WriteFile(partPath, append(append([]byte(nil), initBytes...), fragBytes...), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := mgr.finishPart(sess, partJob{path: partPath, partRel: "part-001.mp4", pending: "part-001.mp4.part", codec: "avc"}); err != nil {
+ t.Fatalf("finishPart: %v", err)
+ }
+ if stateUpdates.Load() == 0 {
+ t.Fatal("expected finishPart to emit onState after completing part")
+ }
+ if len(sess.itemMeta.Media) == 0 || sess.itemMeta.Media[0].Duration < 1 {
+ t.Fatalf("expected Duration >= 1 on finished part: %+v", sess.itemMeta.Media)
+ }
+
+ // Failure case: place a conflicting item.json in badDir so SaveItem rejects manifest save;
+ // PendingParts must retain part-002.mp4.part and .part file must remain on disk!
+ badDir := filepath.Join(lib.CacheDir(), "conflict-save-dir")
+ if err := os.MkdirAll(badDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(badDir, "item.json"), []byte(`{"version":1,"site":"bilibili","kind":"live","id":"live:other:999"}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ badPart := filepath.Join(badDir, "part-002.mp4.part")
+ if err := os.WriteFile(badPart, append(append([]byte(nil), initBytes...), fragBytes...), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ badSess := &recordSession{
+ roomID: 43,
+ itemDir: badDir,
+ itemMeta: library.ItemMetadata{
+ Site: "bilibili", Kind: "live", ID: "live:43:100", Status: "recording",
+ PendingParts: []string{"part-002.mp4.part"},
+ Live: &library.LiveRecordingInfo{RoomID: 43, LiveSince: 100},
+ },
+ }
+ if err := mgr.finishPart(badSess, partJob{path: badPart, partRel: "part-002.mp4", pending: "part-002.mp4.part", codec: "avc"}); err == nil {
+ t.Fatal("expected SaveItem error for conflicting item.json")
+ }
+ if len(badSess.itemMeta.PendingParts) != 1 || badSess.itemMeta.PendingParts[0] != "part-002.mp4.part" {
+ t.Fatalf("PendingParts was mutated before SaveItem succeeded: %+v", badSess.itemMeta.PendingParts)
+ }
+ if _, err := os.Stat(badPart); err != nil {
+ t.Fatalf(".part file should remain on disk when SaveItem fails: %v", err)
+ }
+}
+
+type blockingDouyinProvider struct {
+ blocked chan struct{}
+ release chan struct{}
+ once sync.Once
+}
+
+func (b *blockingDouyinProvider) SiteID() site.ID { return site.Douyin }
+
+func (b *blockingDouyinProvider) CheckLiveStatus(ctx context.Context, uid, cachedWebRID string) (site.LiveStatus, error) {
+ return site.LiveStatus{Site: site.Douyin, AccountUID: uid, WebRID: cachedWebRID, Status: site.LiveStateOffline}, nil
+}
+
+func (b *blockingDouyinProvider) SelectLiveStream(ctx context.Context, uid, roomOrWebRID string, codecOrder []string) (site.LiveStreamPlan, error) {
+ b.once.Do(func() { close(b.blocked) })
+ select {
+ case <-b.release:
+ return site.LiveStreamPlan{}, errors.New("released")
+ case <-ctx.Done():
+ return site.LiveStreamPlan{}, ctx.Err()
+ }
+}
+
+// Concurrent StartRecording calls targeting a Bilibili canonical room ID and
+// its short ID must serialize on the canonical room slot so only one caller
+// runs LiveRoomPlayInfo/SaveItem and both observe the same active session.
+func TestConcurrentStartRecordingCanonicalAndShortIDSerializes(t *testing.T) {
+ initBytes, fragBytes := splitSyntheticHLSInitAndFrag(t)
+ var srvURL string
+ var playInfoHits atomic.Int32
+ playEntered := make(chan struct{})
+ playRelease := make(chan struct{})
+ var playOnce sync.Once
+ holdHLS := make(chan struct{})
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/room/v1/Room/room_init", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": 0,
+ "data": map[string]any{
+ "room_id": 21452505,
+ "short_id": 100,
+ "uid": 50100,
+ "live_status": 1,
+ "live_time": 1794041000,
+ },
+ })
+ })
+ mux.HandleFunc("/room/v1/Room/get_status_info_by_uids", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": 0,
+ "data": map[string]any{
+ "50100": map[string]any{
+ "uid": 50100, "room_id": 21452505, "title": "短号并发测试", "uname": "主播", "live_status": 1, "live_time": 1794041000,
+ },
+ },
+ })
+ })
+ mux.HandleFunc("/xlive/web-room/v2/index/getRoomPlayInfo", func(w http.ResponseWriter, r *http.Request) {
+ playInfoHits.Add(1)
+ playOnce.Do(func() { close(playEntered) })
+ select {
+ case <-playRelease:
+ case <-r.Context().Done():
+ return
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": 0,
+ "data": map[string]any{
+ "room_id": 21452505, "uid": 50100, "live_status": 1,
+ "playurl_info": map[string]any{
+ "playurl": map[string]any{
+ "stream": []map[string]any{{
+ "protocol_name": "http_hls",
+ "format": []map[string]any{{
+ "format_name": "fmp4",
+ "codec": []map[string]any{{
+ "codec_name": "avc", "current_qn": 10000,
+ "base_url": "/hls/short_race.m3u8",
+ "url_info": []map[string]any{{"host": srvURL, "extra": ""}},
+ }},
+ }},
+ }},
+ },
+ },
+ },
+ })
+ })
+ mux.HandleFunc("/hls/short_race.m3u8", func(w http.ResponseWriter, r *http.Request) {
+ select {
+ case <-holdHLS:
+ case <-r.Context().Done():
+ return
+ }
+ _, _ = w.Write([]byte("#EXTM3U\n#EXT-X-VERSION:7\n#EXT-X-TARGETDURATION:2\n#EXT-X-MEDIA-SEQUENCE:1\n#EXT-X-MAP:URI=\"/hls/init.mp4\"\n#EXTINF:2.0,\n/hls/seg1.m4s\n"))
+ })
+ mux.HandleFunc("/hls/init.mp4", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write(initBytes) })
+ mux.HandleFunc("/hls/seg1.m4s", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write(fragBytes) })
+
+ mgr, _, _, srv, _ := setupLiveTestHarness(t, mux)
+ srvURL = srv.URL
+ mgr.freeBytesFunc = func(string) (uint64, error) { return 8 << 30, nil }
+ defer close(holdHLS)
+
+ type startRes struct {
+ st RoomState
+ err error
+ }
+ resA := make(chan startRes, 1)
+ resB := make(chan startRes, 1)
+
+ // Caller A starts with canonical room ID 21452505 and pauses inside LiveRoomPlayInfo.
+ go func() {
+ st, err := mgr.StartRecording(context.Background(), 21452505)
+ resA <- startRes{st, err}
+ }()
+ select {
+ case <-playEntered:
+ case <-time.After(3 * time.Second):
+ t.Fatal("timed out waiting for canonical start to enter LiveRoomPlayInfo")
+ }
+
+ // Caller B starts concurrently with short ID 100 (resolves to canonical 21452505);
+ // it must wait on bilibili:room:21452505 rather than issuing a second LiveRoomPlayInfo.
+ go func() {
+ st, err := mgr.StartRecording(context.Background(), 100)
+ resB <- startRes{st, err}
+ }()
+ time.Sleep(80 * time.Millisecond)
+ if got := playInfoHits.Load(); got != 1 {
+ t.Fatalf("expected short-ID caller to serialize behind canonical slot (1 PlayInfo call), got %d", got)
+ }
+
+ close(playRelease)
+ a := <-resA
+ b := <-resB
+ if a.err != nil || b.err != nil {
+ t.Fatalf("concurrent StartRecording failed: a=%v b=%v", a.err, b.err)
+ }
+ if !a.st.Recording || !b.st.Recording || a.st.RoomID != 21452505 || b.st.RoomID != 21452505 {
+ t.Fatalf("unexpected concurrent start states: a=%+v b=%+v", a.st, b.st)
+ }
+ if a.st.RecordItemDir != b.st.RecordItemDir {
+ t.Fatalf("canonical and short start diverged: %q vs %q", a.st.RecordItemDir, b.st.RecordItemDir)
+ }
+ if got := playInfoHits.Load(); got != 1 {
+ t.Fatalf("expected exactly 1 LiveRoomPlayInfo call across serialized starts, got %d", got)
+ }
+ _, _ = mgr.StopRecording(21452505)
+ waitUntilRoomIdle(t, mgr, "21452505", 5*time.Second)
+}
+
+// StartRecordingByKey must route "douyin:web:" as a webRID (not uid)
+// and reject empty "douyin:web:"; StopRecordingByKey must not overwrite a
+// matched Bilibili room ID with a UID scan fallback.
+func TestStartRecordingByKeyHandlesDouyinWebPrefix(t *testing.T) {
+ flvBytes := buildSyntheticFLVBytes(t, "avc", 30)
+ mux := http.NewServeMux()
+ mux.HandleFunc("/live/web_key.flv", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "video/x-flv")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write(flvBytes)
+ })
+ mgr, _, _, srv, _ := setupLiveTestHarness(t, mux)
+ mgr.freeBytesFunc = func(string) (uint64, error) { return 8 << 30, nil }
+
+ var gotUID, gotRoom string
+ var callMu sync.Mutex
+ prov := newFakeDouyinLiveProvider()
+ prov.streamFn = func(uid, roomOrWebRID string, codecOrder []string, call int) (site.LiveStreamPlan, error) {
+ callMu.Lock()
+ gotUID, gotRoom = uid, roomOrWebRID
+ callMu.Unlock()
+ return site.LiveStreamPlan{
+ Site: site.Douyin,
+ AccountUID: "sec_web_key_01",
+ RoomID: "7400000000000099881",
+ WebRID: "99881",
+ Status: site.LiveStateLive,
+ Quality: 10000,
+ QualityName: "原画",
+ Codec: "avc",
+ Protocol: "http_stream",
+ Format: "flv",
+ Transport: site.LiveTransportHTTPFLV,
+ URLs: []string{srv.URL + "/live/web_key.flv"},
+ Media: site.DouyinLiveTransport("Mozilla/5.0 Test", true),
+ }, nil
+ }
+ prov.statusFn = func(uid, cachedWebRID string, call int) (site.LiveStatus, error) {
+ return site.LiveStatus{
+ Site: site.Douyin,
+ AccountUID: "sec_web_key_01",
+ RoomID: "7400000000000099881",
+ WebRID: "99881",
+ Uname: "WebKey主播",
+ Title: "WebKey测试",
+ Status: site.LiveStateOffline,
+ LiveSince: 1794042000,
+ }, nil
+ }
+ mgr.RegisterSiteProvider(prov)
+
+ if _, err := mgr.StartRecordingByKey(context.Background(), "douyin:web:"); !site.IsKind(err, site.ErrKindBadRequest) {
+ t.Fatalf("expected bad_request for empty douyin:web:, got %v", err)
+ }
+ st, err := mgr.StartRecordingByKey(context.Background(), "douyin:web:99881")
+ if err != nil {
+ t.Fatalf("StartRecordingByKey(douyin:web:99881): %v", err)
+ }
+ callMu.Lock()
+ uidSeen, roomSeen := gotUID, gotRoom
+ callMu.Unlock()
+ if uidSeen != "" || roomSeen != "99881" {
+ t.Fatalf("douyin:web:99881 routed wrong: uid=%q roomOrWebRID=%q, want uid=\"\" roomOrWebRID=\"99881\"", uidSeen, roomSeen)
+ }
+ if st.RoomIDStr != "7400000000000099881" {
+ t.Fatalf("unexpected room state: %+v", st)
+ }
+ waitUntilRoomIdle(t, mgr, "douyin:live:7400000000000099881", 5*time.Second)
+}
diff --git a/internal/live/bilibili_record.go b/internal/live/bilibili_record.go
new file mode 100644
index 0000000..bebe09b
--- /dev/null
+++ b/internal/live/bilibili_record.go
@@ -0,0 +1,275 @@
+package live
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strconv"
+ "time"
+
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/site"
+ "github.com/chialecode/trace/internal/site/bilibili"
+)
+
+// StartRecording begins recording a Bilibili live room into /bilibili//lives/-/.
+func (m *Manager) StartRecording(ctx context.Context, roomOrShortID int64) (RoomState, error) {
+ if roomOrShortID <= 0 {
+ return RoomState{}, &bilibili.SiteError{Site: site.Bilibili, Kind: site.ErrKindBadRequest, Message: "无效的直播间房间号"}
+ }
+ opCtx, cancelOp := m.withManagerContext(ctx)
+ defer cancelOp()
+
+ release, err := m.acquireStartSlot(opCtx, site.Bilibili, "bilibili:start:"+strconv.FormatInt(roomOrShortID, 10))
+ if err != nil {
+ return RoomState{}, err
+ }
+ defer release()
+
+ // Fast path: if already recording this exact roomID, return active state with 0 network calls.
+ m.mu.Lock()
+ if sess := m.sessions[roomOrShortID]; sess != nil {
+ st := m.states[roomOrShortID]
+ m.normalizeBilibiliRoomStateLocked(&st)
+ m.hydrateBilibiliStateFromSessionLocked(&st, sess)
+ m.mu.Unlock()
+ return st, nil
+ }
+ m.mu.Unlock()
+
+ st, err := m.OpenRoom(opCtx, roomOrShortID)
+ if err != nil {
+ return RoomState{}, err
+ }
+ if st.RoomID > 0 {
+ releaseCanon, cErr := m.acquireStartSlot(opCtx, site.Bilibili, "bilibili:room:"+strconv.FormatInt(st.RoomID, 10))
+ if cErr != nil {
+ return RoomState{}, cErr
+ }
+ defer releaseCanon()
+ }
+ if st.LiveStatus != 1 {
+ return st, &bilibili.SiteError{
+ Site: site.Bilibili,
+ Kind: bilibili.ErrKindUnavailable,
+ Message: fmt.Sprintf("直播间当前状态为「%s」,仅在直播中时支持录制", st.StatusText),
+ }
+ }
+ if st.LiveSince <= 0 {
+ return st, &bilibili.SiteError{Site: site.Bilibili, Kind: bilibili.ErrKindSchemaChanged, Message: "站点未返回本场直播的开播时间,无法建立录像条目"}
+ }
+
+ m.mu.Lock()
+ if sess := m.sessions[st.RoomID]; sess != nil {
+ cur := m.states[st.RoomID]
+ m.normalizeBilibiliRoomStateLocked(&cur)
+ m.hydrateBilibiliStateFromSessionLocked(&cur, sess)
+ m.mu.Unlock()
+ return cur, nil
+ }
+ codecOrder := append([]string(nil), m.liveSettings.CodecOrder...)
+ m.mu.Unlock()
+
+ cacheRoot := m.lib.CacheDir()
+ if err := m.checkStartDiskSpace(cacheRoot, site.Bilibili); err != nil {
+ return st, err
+ }
+
+ // Verify play info is accessible and not encrypted (203) before creating session.
+ playSel, err := m.client.LiveRoomPlayInfo(opCtx, st.RoomID, codecOrder)
+ if err != nil {
+ return st, err
+ }
+ if playSel.QualityName == "" && playSel.Quality > 0 {
+ playSel.QualityName = bilibili.LiveQualityFallbackName(playSel.Quality)
+ }
+
+ now := m.now().UTC()
+ sessionID := fmt.Sprintf("%d:%d", st.RoomID, st.LiveSince)
+ itemDir, err := library.EnsureWithinRoot(cacheRoot, filepath.Join(cacheRoot, "bilibili", strconv.FormatInt(st.UID, 10), "lives", fmt.Sprintf("%d-%d", st.RoomID, st.LiveSince)))
+ if err != nil {
+ return st, err
+ }
+
+ meta := library.ItemMetadata{
+ Version: 1,
+ ID: "live:" + sessionID,
+ Site: "bilibili",
+ Kind: "live",
+ Status: "recording",
+ Title: st.Title,
+ URL: fmt.Sprintf("https://live.bilibili.com/%d", st.RoomID),
+ PubTs: st.LiveSince,
+ CachedAt: now.Format(time.RFC3339),
+ Author: library.ItemAuthor{
+ Mid: st.UID,
+ Name: st.Uname,
+ Face: st.Face,
+ },
+ }
+ // Look up by the canonical key: "live::" has two colons and
+ // would be taken as a full key without the site, never matching.
+ existing, exists, err := m.lib.GetItem(library.CanonicalItemKey("bilibili", "live", sessionID))
+ if err != nil {
+ return st, err
+ }
+ if exists {
+ meta = existing
+ if existing.ItemDir != "" {
+ itemDir = existing.ItemDir
+ }
+ meta.Status = "recording"
+ }
+ if err := os.MkdirAll(itemDir, 0o700); err != nil {
+ return st, err
+ }
+ if meta.Live == nil {
+ meta.Live = &library.LiveRecordingInfo{RoomID: st.RoomID, LiveSince: st.LiveSince, StartedAt: now.Format(time.RFC3339)}
+ }
+ meta.Live.EndedAt, meta.Live.StopReason = "", ""
+ meta.Live.Quality = playSel.Quality
+ meta.Live.QualityName = playSel.QualityName
+ meta.Live.Codec = playSel.Codec
+ meta.Live.Source = "manual"
+ if bilibili.AutomaticRequestSource(ctx) != "" {
+ meta.Live.Source = "auto"
+ st.Source = "auto"
+ }
+ savedMeta, err := m.lib.SaveItem(itemDir, meta)
+ if err != nil {
+ return st, err
+ }
+
+ recParent := context.Background()
+ if meta.Live.Source == "auto" {
+ recParent = bilibili.WithAutomaticRequests(recParent, "live")
+ }
+ recCtx, recCancel := context.WithCancel(recParent)
+ initialTransport := string(site.LiveTransportHLSFMP4)
+ if playSel.Format == "flv" || playSel.Protocol == "http_stream" {
+ initialTransport = string(site.LiveTransportHTTPFLV)
+ }
+ sess := &recordSession{
+ siteID: string(site.Bilibili),
+ coverURL: st.Cover,
+ sessionID: sessionID,
+ startedAt: now,
+ reportAt: now,
+ roomID: st.RoomID,
+ uid: st.UID,
+ uname: st.Uname,
+ face: st.Face,
+ title: st.Title,
+ itemDir: itemDir,
+ itemMeta: savedMeta,
+ cancel: recCancel,
+ doneCh: make(chan struct{}),
+ nextPart: nextPartNumber(savedMeta),
+ lastSequence: savedMeta.Live.LastSequence,
+ hasSequence: savedMeta.Live.HasSequence,
+ quality: playSel.Quality,
+ qualityName: playSel.QualityName,
+ codec: playSel.Codec,
+ streamTransport: initialTransport,
+ previewSupport: true,
+ previewReason: previewReasonWaitingFirstFragment,
+ }
+ m.initSessionIncidents(sess)
+ for _, media := range savedMeta.Media {
+ if media.Role == "live_segment" {
+ sess.segments = append(sess.segments, media.Path)
+ sess.bytesTotal += media.Bytes
+ }
+ }
+
+ m.mu.Lock()
+ if m.stopping {
+ m.mu.Unlock()
+ recCancel()
+ return RoomState{}, &bilibili.SiteError{Site: site.Bilibili, Kind: bilibili.ErrKindUnavailable, Message: "应用正在退出,不能开始新的录制"}
+ }
+ if existingSess := m.sessions[st.RoomID]; existingSess != nil {
+ cur := m.states[st.RoomID]
+ m.normalizeBilibiliRoomStateLocked(&cur)
+ m.hydrateBilibiliStateFromSessionLocked(&cur, existingSess)
+ m.mu.Unlock()
+ recCancel()
+ return cur, nil
+ }
+ delete(m.stoppedBroadcasts, st.RoomID)
+ m.sessions[st.RoomID] = sess
+ st.Recording = true
+ st.RecordSession = sessionID
+ st.RecordItemDir = itemDir
+ st.Quality = playSel.Quality
+ st.QualityName = playSel.QualityName
+ st.Codec = playSel.Codec
+ st.StopReason = ""
+ st.LastError = ""
+ m.normalizeBilibiliRoomStateLocked(&st)
+ hydrateSessionPreviewFieldsLocked(&st, sess)
+ m.states[st.RoomID] = st
+ m.wg.Add(1)
+ m.mu.Unlock()
+
+ go m.runRecordingSession(recCtx, sess, playSel, codecOrder)
+
+ if m.onState != nil {
+ m.onState(st)
+ }
+ return st, nil
+}
+
+// StopRecording stops an active recording for roomID and finalizes item.json,
+// suppressing auto-restart for the remainder of the current broadcast (live.md §3).
+func (m *Manager) StopRecording(roomID int64) (RoomState, error) {
+ if roomID <= 0 {
+ return RoomState{}, &bilibili.SiteError{Site: site.Bilibili, Kind: site.ErrKindBadRequest, Message: "无效的直播间房间号"}
+ }
+ return m.stopRecordingInternal(roomID, "user_stop", true)
+}
+
+func (m *Manager) stopRecordingInternal(roomID int64, reason string, suppressAutoRestart bool) (RoomState, error) {
+ m.mu.Lock()
+ if suppressAutoRestart {
+ m.stoppedBroadcasts[roomID] = m.states[roomID].LiveSince
+ }
+ sess, ok := m.sessions[roomID]
+ if ok && sess != nil && sess.stopReason == "" {
+ sess.stopReason = reason
+ }
+ timeout := m.finalizeTimeout
+ m.mu.Unlock()
+ if !ok || sess == nil {
+ m.mu.Lock()
+ st := m.states[roomID]
+ st.Recording = false
+ m.normalizeBilibiliRoomStateLocked(&st)
+ m.mu.Unlock()
+ return st, nil
+ }
+
+ if timeout <= 0 {
+ timeout = 30 * time.Second
+ }
+ sess.cancel()
+ timer := time.NewTimer(timeout)
+ defer timer.Stop()
+ select {
+ case <-sess.doneCh:
+ case <-timer.C:
+ m.mu.Lock()
+ state := m.states[roomID]
+ m.mu.Unlock()
+ return state, &bilibili.SiteError{Site: site.Bilibili, Kind: "storage", Message: "录制收尾已到时间上限,临时片段会在下次启动时恢复"}
+ }
+
+ // runSessionLoop already wrote the finalized RoomState (including any
+ // manifest-save LastError) and emitted onState before closing sess.doneCh.
+ m.mu.Lock()
+ st := m.states[roomID]
+ m.normalizeBilibiliRoomStateLocked(&st)
+ m.mu.Unlock()
+ return st, nil
+}
diff --git a/internal/live/bilibili_status.go b/internal/live/bilibili_status.go
new file mode 100644
index 0000000..54e78d5
--- /dev/null
+++ b/internal/live/bilibili_status.go
@@ -0,0 +1,419 @@
+package live
+
+import (
+ "context"
+ "fmt"
+ "strconv"
+ "time"
+
+ "github.com/chialecode/trace/internal/site"
+ "github.com/chialecode/trace/internal/site/bilibili"
+ "github.com/chialecode/trace/internal/subscription"
+)
+
+// Status queries live status for the given UIDs using a 60-second in-memory cache and <=50 UID batching (live.md §1).
+func (m *Manager) Status(ctx context.Context, uids []int64) (map[int64]bilibili.LiveUserStatus, error) {
+ if err := m.client.RequireAuth("live:status"); err != nil {
+ return nil, err
+ }
+ now := m.now()
+ result := make(map[int64]bilibili.LiveUserStatus, len(uids))
+ var uncached []int64
+ seen := make(map[int64]bool, len(uids))
+
+ m.mu.Lock()
+ for _, uid := range uids {
+ if uid <= 0 || seen[uid] {
+ continue
+ }
+ seen[uid] = true
+ if entry, ok := m.statusCache[uid]; ok && now.Sub(entry.fetchedAt) < statusCacheTTL {
+ result[uid] = entry.status
+ } else {
+ uncached = append(uncached, uid)
+ }
+ }
+ m.mu.Unlock()
+
+ if len(uncached) > 0 {
+ fetched, err := m.client.LiveStatusByUIDs(ctx, uncached)
+ if err != nil {
+ return nil, err
+ }
+ m.mu.Lock()
+ for _, uid := range uncached {
+ st := fetched[uid]
+ if st.UID == 0 {
+ st.UID = uid
+ }
+ m.statusCache[uid] = cachedStatusEntry{
+ status: st,
+ fetchedAt: now,
+ }
+ result[uid] = st
+ }
+ m.mu.Unlock()
+ }
+ return result, nil
+}
+
+// PollNow queries live status for all subscribed Bilibili creators (in <=50 UID batches),
+// detects 0/2 -> 1 transitions (ignoring 2=carousel), and emits start notifications without triggering auto-recording.
+func (m *Manager) PollNow(ctx context.Context) ([]RoomState, error) {
+ return m.refreshAccounts(ctx, nil, false, true, false)
+}
+
+// RefreshForAccounts reads the live status of the given Bilibili accounts (cached for
+// 60 seconds) and returns only the room states matching the requested UIDs. Like a poll
+// round it starts recording a broadcast found live when the account's subscription
+// records broadcasts, so a status refresh on the account page or by an update check
+// does not leave it unrecorded until the next round.
+func (m *Manager) RefreshForAccounts(ctx context.Context, uids []int64) ([]RoomState, error) {
+ return m.refreshAccounts(ctx, uids, true, false, true)
+}
+
+func collectBilibiliRefreshTargets(subList []subscription.Subscription, selected []int64, filterToSelected bool) ([]int64, map[int64]subscription.Subscription, map[int64]bool) {
+ subByUID := make(map[int64]subscription.Subscription, len(subList))
+ allowed := make(map[int64]bool, len(selected))
+ for _, uid := range selected {
+ if uid > 0 {
+ allowed[uid] = true
+ }
+ }
+ var uids []int64
+ mergeSub := func(uid int64, s subscription.Subscription) {
+ if uid <= 0 || (filterToSelected && !allowed[uid]) {
+ return
+ }
+ if existing, exists := subByUID[uid]; exists {
+ existing.LiveAutoRecord = existing.LiveAutoRecord || s.LiveAutoRecord
+ existing.Rules.AutoRecord = existing.Rules.AutoRecord || s.Rules.AutoRecord
+ existing.LiveNotify = existing.LiveNotify || s.LiveNotify
+ existing.Uname = firstNonEmpty(existing.Uname, s.Uname)
+ existing.Face = firstNonEmpty(existing.Face, s.Face)
+ if existing.RoomID <= 0 && s.RoomID > 0 {
+ existing.RoomID = s.RoomID
+ }
+ subByUID[uid] = existing
+ return
+ }
+ subByUID[uid] = s
+ uids = append(uids, uid)
+ }
+
+ for _, s := range subList {
+ for _, acc := range s.Accounts {
+ if acc.Site != "" && acc.Site != string(site.Bilibili) {
+ continue
+ }
+ if uid, pErr := strconv.ParseInt(acc.UID, 10, 64); pErr == nil && uid > 0 {
+ mergeSub(uid, s)
+ }
+ }
+ if s.Mid > 0 {
+ mergeSub(s.Mid, s)
+ }
+ }
+ // A user page can show a creator before they are subscribed. Explicit UI
+ // lookups may query these accounts, without enabling rules or notifications.
+ for _, uid := range selected {
+ if uid > 0 {
+ if _, exists := subByUID[uid]; !exists {
+ subByUID[uid] = subscription.Subscription{Mid: uid}
+ uids = append(uids, uid)
+ }
+ }
+ }
+ return uids, subByUID, allowed
+}
+
+func (m *Manager) refreshAccounts(ctx context.Context, selected []int64, filterToSelected, force, autoRecord bool) ([]RoomState, error) {
+ if err := m.client.RequireAuth("live:poll"); err != nil {
+ return nil, err
+ }
+ var subList []subscription.Subscription
+ var err error
+ if m.subs != nil {
+ subList, err = m.subs.List()
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ uids, subByUID, allowed := collectBilibiliRefreshTargets(subList, selected, filterToSelected)
+ if len(uids) == 0 {
+ if filterToSelected {
+ return nil, nil
+ }
+ return m.ListRooms(), nil
+ }
+
+ var statusMap map[int64]bilibili.LiveUserStatus
+ if force {
+ statusMap, err = m.client.LiveStatusByUIDs(ctx, uids)
+ } else {
+ statusMap, err = m.Status(ctx, uids)
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ now := m.now().UTC()
+ nowStr := now.Format(time.RFC3339)
+ var toAutoRecord []int64
+ var notifications []Notification
+
+ m.mu.Lock()
+ notifyGlobal := m.liveSettings.NotifyOnStart
+ for _, uid := range uids {
+ sub := subByUID[uid]
+ st, ok := statusMap[uid]
+ if !ok {
+ st = bilibili.LiveUserStatus{
+ UID: uid,
+ RoomID: sub.RoomID,
+ Uname: sub.Uname,
+ Face: sub.Face,
+ LiveStatus: 0,
+ }
+ }
+ if force {
+ m.statusCache[uid] = cachedStatusEntry{status: st, fetchedAt: now}
+ }
+
+ prev, hadPrev := m.prevLive[uid]
+ m.prevLive[uid] = st.LiveStatus
+
+ if st.LiveStatus != 1 && st.RoomID > 0 {
+ delete(m.stoppedBroadcasts, st.RoomID)
+ }
+
+ // Transition 0/2 -> 1 triggers notification and auto-record (LiveStatus==2 carousel never triggers).
+ if st.LiveStatus == 1 && (!hadPrev || prev != 1) {
+ if notifyGlobal && sub.LiveNotify {
+ notifications = append(notifications, Notification{
+ Site: string(site.Bilibili),
+ AccountUID: strconv.FormatInt(uid, 10),
+ UID: uid,
+ RoomID: st.RoomID,
+ RoomIDStr: strconv.FormatInt(st.RoomID, 10),
+ Uname: firstNonEmpty(st.Uname, sub.Uname),
+ Title: st.Title,
+ StartedAt: nowStr,
+ })
+ }
+ }
+
+ autoRecEnabled := sub.LiveAutoRecord || sub.Rules.AutoRecord
+ if st.LiveStatus == 1 && autoRecEnabled && st.RoomID > 0 {
+ if stopped, ok := m.stoppedBroadcasts[st.RoomID]; ok && st.LiveTime > 0 && stopped != st.LiveTime {
+ delete(m.stoppedBroadcasts, st.RoomID)
+ }
+ _, suppressed := m.stoppedBroadcasts[st.RoomID]
+ if _, already := m.sessions[st.RoomID]; autoRecord && !m.stopping && !already && !suppressed {
+ toAutoRecord = append(toAutoRecord, st.RoomID)
+ }
+ }
+
+ key := st.RoomID
+ if key <= 0 {
+ key = -uid
+ }
+ existing := m.states[key]
+ if existing.RecordItemDir == "" && len(existing.Incidents) == 0 && existing.StopReason == "" && existing.LastError == "" {
+ for oldKey, old := range m.states {
+ if oldKey != key && old.UID == uid {
+ existing = old
+ break
+ }
+ }
+ }
+ recSess := m.sessions[st.RoomID]
+ roomState := RoomState{
+ Site: string(site.Bilibili),
+ AccountUID: strconv.FormatInt(uid, 10),
+ UID: uid,
+ RoomID: st.RoomID,
+ ShortID: st.ShortID,
+ Uname: firstNonEmpty(st.Uname, sub.Uname),
+ Face: firstNonEmpty(st.Face, sub.Face),
+ Title: st.Title,
+ Cover: st.Cover,
+ AreaName: st.AreaName,
+ LiveStatus: st.LiveStatus,
+ LiveSince: st.LiveTime,
+ StatusText: LiveStatusText(st.LiveStatus),
+ Quality: existing.Quality,
+ QualityName: existing.QualityName,
+ Codec: existing.Codec,
+ Recording: recSess != nil,
+ Incidents: cloneIncidents(existing.Incidents),
+ // The last session's folder stays with its incidents after it ends,
+ // so Tasks › 录制异常 shows them on that session only.
+ RecordItemDir: existing.RecordItemDir,
+ StopReason: existing.StopReason,
+ LastError: existing.LastError,
+ UpdatedAt: nowStr,
+ }
+ m.normalizeBilibiliRoomStateLocked(&roomState)
+ if recSess != nil {
+ m.hydrateBilibiliStateFromSessionLocked(&roomState, recSess)
+ } else {
+ hydrateSessionPreviewFieldsLocked(&roomState, nil)
+ }
+ m.states[key] = roomState
+ for oldKey, state := range m.states {
+ if oldKey != key && state.UID == uid {
+ delete(m.states, oldKey)
+ }
+ }
+ }
+ m.mu.Unlock()
+
+ for _, n := range notifications {
+ if m.onNotify != nil {
+ m.onNotify(n)
+ }
+ }
+ for _, roomID := range toAutoRecord {
+ if _, rErr := m.StartRecording(ctx, roomID); rErr != nil {
+ m.mu.Lock()
+ if st, ok := m.states[roomID]; ok {
+ st.LastError = sanitizeLiveError(rErr)
+ m.states[roomID] = st
+ }
+ m.mu.Unlock()
+ if isAutoStartBatchStopError(rErr) {
+ if site.IsRoundStop(rErr) && m.client != nil {
+ m.client.ReportAutomaticError(ctx, rErr)
+ }
+ if site.IsCircuitBreak(rErr) {
+ m.recordSiteAutoStop(site.Bilibili, site.KindOf(rErr))
+ }
+ break
+ }
+ }
+ }
+
+ rooms := m.ListRooms()
+ if !filterToSelected {
+ return rooms, nil
+ }
+ filtered := make([]RoomState, 0, len(allowed))
+ for _, r := range rooms {
+ if r.Site == string(site.Bilibili) && allowed[r.UID] {
+ filtered = append(filtered, r)
+ }
+ }
+ return filtered, nil
+}
+
+// OpenRoom resolves and inspects a single live room by roomID or shortID.
+func (m *Manager) OpenRoom(ctx context.Context, roomOrShortID int64) (RoomState, error) {
+ info, err := m.client.RoomInit(ctx, roomOrShortID)
+ if err != nil {
+ return RoomState{}, err
+ }
+
+ var userSt bilibili.LiveUserStatus
+ if info.UID > 0 {
+ stMap, sErr := m.Status(ctx, []int64{info.UID})
+ if sErr != nil {
+ return RoomState{}, sErr
+ }
+ userSt = stMap[info.UID]
+ }
+
+ now := m.now().UTC()
+ nowStr := now.Format(time.RFC3339)
+ m.mu.Lock()
+ existing := m.states[info.RoomID]
+ recSess := m.sessions[info.RoomID]
+ st := RoomState{
+ Site: string(site.Bilibili),
+ UID: info.UID,
+ RoomID: info.RoomID,
+ ShortID: info.ShortID,
+ Uname: firstNonEmpty(userSt.Uname, fmt.Sprintf("UID %d", info.UID)),
+ Face: userSt.Face,
+ Title: firstNonEmpty(userSt.Title, fmt.Sprintf("直播间 %d", info.RoomID)),
+ Cover: userSt.Cover,
+ AreaName: userSt.AreaName,
+ LiveStatus: info.LiveStatus,
+ LiveSince: max(info.LiveTime, userSt.LiveTime),
+ StatusText: LiveStatusText(info.LiveStatus),
+ Quality: existing.Quality,
+ QualityName: existing.QualityName,
+ Codec: existing.Codec,
+ Recording: recSess != nil,
+ Incidents: cloneIncidents(existing.Incidents),
+ // The last session's folder stays with its incidents after it ends,
+ // so Tasks › 录制异常 shows them on that session only.
+ RecordItemDir: existing.RecordItemDir,
+ StopReason: existing.StopReason,
+ LastError: existing.LastError,
+ UpdatedAt: nowStr,
+ }
+ m.normalizeBilibiliRoomStateLocked(&st)
+ if recSess != nil {
+ m.hydrateBilibiliStateFromSessionLocked(&st, recSess)
+ } else {
+ hydrateSessionPreviewFieldsLocked(&st, nil)
+ }
+ m.states[info.RoomID] = st
+ m.mu.Unlock()
+ return st, nil
+}
+
+func (m *Manager) normalizeBilibiliRoomStateLocked(st *RoomState) {
+ if st == nil {
+ return
+ }
+ if st.Site == "" {
+ st.Site = string(site.Bilibili)
+ }
+ if st.AccountUID == "" && st.UID > 0 {
+ st.AccountUID = strconv.FormatInt(st.UID, 10)
+ }
+ if st.RoomIDStr == "" && st.RoomID > 0 {
+ st.RoomIDStr = strconv.FormatInt(st.RoomID, 10)
+ }
+ if st.RoomKey == "" {
+ if st.RoomIDStr != "" {
+ st.RoomKey = "bilibili:live:" + st.RoomIDStr
+ } else if st.AccountUID != "" {
+ st.RoomKey = "bilibili:user:" + st.AccountUID
+ }
+ }
+ if st.QualityName == "" && st.Quality > 0 {
+ st.QualityName = bilibili.LiveQualityFallbackName(st.Quality)
+ }
+}
+
+func (m *Manager) hydrateBilibiliStateFromSessionLocked(st *RoomState, sess *recordSession) {
+ if st == nil || sess == nil {
+ return
+ }
+ st.Recording = true
+ st.RecordSession = sess.sessionID
+ st.RecordDurationSec = m.nowLocked().Sub(sess.startedAt).Seconds()
+ st.RecordBytes = sess.bytesTotal
+ st.RecordSegments = len(sess.segments)
+ st.RecordItemDir = sess.itemDir
+ if sess.quality > 0 {
+ st.Quality = sess.quality
+ }
+ if sess.qualityName != "" {
+ st.QualityName = sess.qualityName
+ }
+ if sess.codec != "" {
+ st.Codec = sess.codec
+ }
+ if sess.stopReason != "" {
+ st.StopReason = sess.stopReason
+ }
+ if sess.lastErr != "" {
+ st.LastError = sess.lastErr
+ }
+ hydrateSessionPreviewFieldsLocked(st, sess)
+}
diff --git a/internal/live/cover.go b/internal/live/cover.go
index fb1754d..4113ed1 100644
--- a/internal/live/cover.go
+++ b/internal/live/cover.go
@@ -1,63 +1,186 @@
package live
import (
+ "bytes"
"context"
"crypto/sha256"
"encoding/hex"
+ "errors"
+ "io"
+ "mime"
+ "net/http"
"os"
+ "strings"
"github.com/chialecode/trace/internal/library"
- "github.com/chialecode/trace/internal/site/bilibili"
+ "github.com/chialecode/trace/internal/site"
"github.com/chialecode/trace/internal/storage"
)
-func (m *Manager) saveLiveCover(ctx context.Context, session *recordSession) error {
+const maxLiveCoverBytes = 16 << 20 // 16 MiB cover image limit
+
+func (m *Manager) hasVerifiedCover(sess *recordSession) bool {
m.mu.Lock()
- url := m.states[session.roomID].Cover
+ media := append([]library.MediaFile(nil), sess.itemMeta.Media...)
+ itemDir := sess.itemDir
m.mu.Unlock()
- if url == "" {
- return nil
- }
- for _, file := range session.itemMeta.Media {
- if file.Role == "cover" && library.VerifyMediaFile(session.itemDir, file, true) {
- return nil
+ for _, file := range media {
+ if file.Role == "cover" && library.VerifyMediaFile(itemDir, file, true) {
+ return true
}
}
- const rel = "cover.jpg"
- path, err := library.ResolveItemPath(session.itemDir, rel)
+ return false
+}
+
+func (m *Manager) checkCoverTargetWritable(sess *recordSession, siteID site.ID, rel string) (string, error) {
+ path, err := library.ResolveItemPath(sess.itemDir, rel)
if err != nil {
- return err
+ return "", err
}
+ m.mu.Lock()
owned := false
- for _, file := range session.itemMeta.Media {
- owned = owned || file.Path == rel
+ for _, file := range sess.itemMeta.Media {
+ if file.Path == rel {
+ owned = true
+ break
+ }
}
+ m.mu.Unlock()
if !owned {
if _, err := os.Lstat(path); err == nil {
- return &bilibili.SiteError{Kind: "storage", Message: "封面目标已存在且未登记,原文件已保留"}
+ return "", &site.Error{Site: siteID, Kind: site.ErrKindStorage, Message: "封面目标已存在且未登记,原文件已保留"}
} else if !os.IsNotExist(err) {
- return err
+ return "", err
}
}
- raw, err := m.client.FetchImage(ctx, url)
+ return path, nil
+}
+
+// commitLiveCover writes the cover file atomically BEFORE registering it in
+// itemMeta.Media and saving item.json, preserving remote write-order safety
+// and protecting any pre-existing unowned user file.
+func (m *Manager) commitLiveCover(sess *recordSession, siteID site.ID, rel, sourceURL string, raw []byte) error {
+ path, err := m.checkCoverTargetWritable(sess, siteID, rel)
+ if err != nil {
+ return err
+ }
+ if err := storage.WriteFileAtomic(path, raw, 0o600); err != nil {
+ return err
+ }
+ hash := sha256.Sum256(raw)
+ media := library.MediaFile{
+ Role: "cover",
+ Path: rel,
+ Bytes: int64(len(raw)),
+ SHA256: hex.EncodeToString(hash[:]),
+ Source: sourceURL,
+ }
+ m.mu.Lock()
+ sess.itemMeta.Media = mergeLiveMedia(sess.itemMeta.Media, media)
+ clearLiveMissing(&sess.itemMeta, "cover")
+ m.mu.Unlock()
+ return m.saveSession(sess)
+}
+
+func (m *Manager) saveLiveCover(ctx context.Context, sess *recordSession) error {
+ m.mu.Lock()
+ coverURL := firstNonEmpty(sess.coverURL, m.states[sess.roomID].Cover)
+ m.mu.Unlock()
+ if coverURL == "" || m.hasVerifiedCover(sess) {
+ return nil
+ }
+ const rel = "cover.jpg"
+ if _, err := m.checkCoverTargetWritable(sess, site.Bilibili, rel); err != nil {
+ return err
+ }
+ leave := sess.enterExternal()
+ raw, err := m.client.FetchImage(ctx, coverURL)
+ leave()
if err != nil {
- addLiveMissing(&session.itemMeta, "cover", "封面保存失败")
+ m.mu.Lock()
+ addLiveMissing(&sess.itemMeta, "cover", "封面保存失败")
+ m.mu.Unlock()
if liveStopReason(err) != "" {
return err
}
return nil
}
- if !owned {
- session.itemMeta.Media = mergeLiveMedia(session.itemMeta.Media, library.MediaFile{Role: "cover", Path: rel})
- if err := m.saveSession(session); err != nil {
- return err
+ return m.commitLiveCover(sess, site.Bilibili, rel, sanitizeLiveURL(coverURL), raw)
+}
+
+func (m *Manager) saveDouyinLiveCover(ctx context.Context, sess *recordSession, transport site.MediaTransportSpec) error {
+ m.mu.Lock()
+ coverURL := strings.TrimSpace(sess.coverURL)
+ idleTimeout := m.flvIdleTimeout
+ m.mu.Unlock()
+ if coverURL == "" || m.hasVerifiedCover(sess) {
+ return nil
+ }
+ if idleTimeout <= 0 {
+ idleTimeout = defaultFLVIdleTimeout
+ }
+ vodSpec := site.DouyinVODTransport(transport.UserAgent, transport.AllowLocalhost)
+ if err := vodSpec.ValidateURL(coverURL); err != nil {
+ return nil
+ }
+ httpClient, tr := newLiveTransportClientWithTransport(vodSpec, defaultFLVConnectTimeout)
+ defer tr.CloseIdleConnections()
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, coverURL, nil)
+ if err != nil {
+ return nil
+ }
+ vodSpec.ApplyHeaders(req)
+ resp, err := httpClient.Do(req)
+ if err != nil {
+ var se *site.Error
+ if errors.As(err, &se) && liveStopReason(se) != "" {
+ return se
}
+ return nil
}
- if err := storage.WriteFileAtomic(path, raw, 0600); err != nil {
- return err
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ se := mapLiveHTTPStatus(site.Douyin, resp.StatusCode)
+ if liveStopReason(se) != "" {
+ return se
+ }
+ return nil
}
- hash := sha256.Sum256(raw)
- session.itemMeta.Media = mergeLiveMedia(session.itemMeta.Media, library.MediaFile{Role: "cover", Path: rel, Bytes: int64(len(raw)), SHA256: hex.EncodeToString(hash[:]), Source: url})
- clearLiveMissing(&session.itemMeta, "cover")
- return m.saveSession(session)
+ reader := site.WrapIdleReadCloser(resp.Body, idleTimeout, func() error {
+ return &site.Error{Site: site.Douyin, Kind: site.ErrKindNetwork, Message: "直播封面下载超时"}
+ })
+ defer reader.Close()
+ raw, err := io.ReadAll(io.LimitReader(reader, maxLiveCoverBytes+1))
+ if err != nil || len(raw) < 8 || int64(len(raw)) > maxLiveCoverBytes {
+ return nil
+ }
+ ext := sniffLiveCoverExt(raw, resp.Header.Get("Content-Type"))
+ if ext == "" {
+ return nil
+ }
+ return m.commitLiveCover(sess, site.Douyin, "cover"+ext, "", raw)
+}
+
+func sniffLiveCoverExt(b []byte, ct string) string {
+ switch {
+ case len(b) >= 3 && b[0] == 0xFF && b[1] == 0xD8 && b[2] == 0xFF:
+ return ".jpg"
+ case len(b) >= 8 && bytes.Equal(b[:8], []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1A, '\n'}):
+ return ".png"
+ case len(b) >= 12 && bytes.Equal(b[:4], []byte("RIFF")) && bytes.Equal(b[8:12], []byte("WEBP")):
+ return ".webp"
+ case len(b) >= 6 && (bytes.Equal(b[:6], []byte("GIF87a")) || bytes.Equal(b[:6], []byte("GIF89a"))):
+ return ".gif"
+ }
+ mt, _, _ := mime.ParseMediaType(ct)
+ switch strings.ToLower(strings.TrimSpace(mt)) {
+ case "image/jpeg", "image/jpg":
+ return ".jpg"
+ case "image/png":
+ return ".png"
+ case "image/webp":
+ return ".webp"
+ }
+ return ""
}
diff --git a/internal/live/disk.go b/internal/live/disk.go
new file mode 100644
index 0000000..624a704
--- /dev/null
+++ b/internal/live/disk.go
@@ -0,0 +1,46 @@
+package live
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+// nearestExistingDir walks upward from dir until it finds an existing directory
+// so disk space queries keep working after remote upload/move removes an empty itemDir
+// or before cacheRoot is created.
+func nearestExistingDir(dir string) string {
+ clean := filepath.Clean(strings.TrimSpace(dir))
+ if clean == "" || clean == "." {
+ if wd, err := os.Getwd(); err == nil {
+ return wd
+ }
+ return "."
+ }
+ if abs, err := filepath.Abs(clean); err == nil {
+ clean = abs
+ }
+ cur := clean
+ for {
+ info, err := os.Stat(cur)
+ if err == nil {
+ if info.IsDir() {
+ return cur
+ }
+ parent := filepath.Dir(cur)
+ if parent == cur {
+ return cur
+ }
+ cur = parent
+ continue
+ }
+ if !os.IsNotExist(err) {
+ return cur
+ }
+ parent := filepath.Dir(cur)
+ if parent == cur {
+ return cur
+ }
+ cur = parent
+ }
+}
diff --git a/internal/live/disk_linux.go b/internal/live/disk_linux.go
new file mode 100644
index 0000000..97ecf73
--- /dev/null
+++ b/internal/live/disk_linux.go
@@ -0,0 +1,30 @@
+//go:build linux
+
+package live
+
+import (
+ "fmt"
+
+ "golang.org/x/sys/unix"
+)
+
+func getFreeDiskBytes(dir string) (uint64, error) {
+ target := nearestExistingDir(dir)
+ var stat unix.Statfs_t
+ if err := unix.Statfs(target, &stat); err != nil {
+ return 0, err
+ }
+ var blockSize uint64
+ if stat.Frsize > 0 {
+ blockSize = uint64(stat.Frsize)
+ } else if stat.Bsize > 0 {
+ blockSize = uint64(stat.Bsize)
+ } else {
+ return 0, fmt.Errorf("live: invalid statfs block size for %s", target)
+ }
+ return uint64(stat.Bavail) * blockSize, nil
+}
+
+func isPlatformDiskFullError(error) bool {
+ return false
+}
diff --git a/internal/live/disk_other.go b/internal/live/disk_other.go
index ce9dc13..3b44b19 100644
--- a/internal/live/disk_other.go
+++ b/internal/live/disk_other.go
@@ -1,13 +1,25 @@
-//go:build !windows
+//go:build !windows && !linux
package live
-import "golang.org/x/sys/unix"
+import (
+ "fmt"
+
+ "golang.org/x/sys/unix"
+)
func getFreeDiskBytes(dir string) (uint64, error) {
+ target := nearestExistingDir(dir)
var stat unix.Statfs_t
- if err := unix.Statfs(dir, &stat); err != nil {
+ if err := unix.Statfs(target, &stat); err != nil {
return 0, err
}
+ if stat.Bsize <= 0 {
+ return 0, fmt.Errorf("live: invalid statfs block size for %s", target)
+ }
return uint64(stat.Bavail) * uint64(stat.Bsize), nil
}
+
+func isPlatformDiskFullError(error) bool {
+ return false
+}
diff --git a/internal/live/disk_windows.go b/internal/live/disk_windows.go
index fe2a0c4..fe34344 100644
--- a/internal/live/disk_windows.go
+++ b/internal/live/disk_windows.go
@@ -1,16 +1,16 @@
+//go:build windows
+
package live
import (
+ "errors"
+
"golang.org/x/sys/windows"
- "path/filepath"
)
func getFreeDiskBytes(dir string) (uint64, error) {
- abs, err := filepath.Abs(dir)
- if err != nil {
- abs = dir
- }
- ptr, err := windows.UTF16PtrFromString(abs)
+ target := nearestExistingDir(dir)
+ ptr, err := windows.UTF16PtrFromString(target)
if err != nil {
return 0, err
}
@@ -20,3 +20,7 @@ func getFreeDiskBytes(dir string) (uint64, error) {
}
return freeBytesAvailable, nil
}
+
+func isPlatformDiskFullError(err error) bool {
+ return errors.Is(err, windows.ERROR_DISK_FULL) || errors.Is(err, windows.ERROR_HANDLE_DISK_FULL)
+}
diff --git a/internal/live/douyin_budget_test.go b/internal/live/douyin_budget_test.go
index ded5feb..2ec4924 100644
--- a/internal/live/douyin_budget_test.go
+++ b/internal/live/douyin_budget_test.go
@@ -14,8 +14,7 @@ import (
// account it can with the live check gap between requests, those checked
// longest ago first, so an account's interval stays the round's until the
// accounts no longer fit in one round, and grows by about the gap per
-// further account, not with a share of a fixed hourly budget (dev
-// 2026-11-18: 17 accounts were about 18 minutes apart). An account newly
+// further account, not with a share of a fixed hourly budget. An account newly
// linked to an auto-record subscription is checked in the next round.
func TestDouyinLiveChecksPacedThroughRound(t *testing.T) {
mgr, _, subMgr, _, _ := setupLiveTestHarness(t, http.NewServeMux())
diff --git a/internal/live/douyin_live.go b/internal/live/douyin_live.go
deleted file mode 100644
index f0d64ec..0000000
--- a/internal/live/douyin_live.go
+++ /dev/null
@@ -1,2218 +0,0 @@
-package live
-
-import (
- "bytes"
- "context"
- "crypto/sha256"
- "encoding/hex"
- "errors"
- "fmt"
- "io"
- "math"
- "mime"
- "net"
- "net/http"
- "net/url"
- "os"
- "path/filepath"
- "sort"
- "strconv"
- "strings"
- "time"
-
- "github.com/chialecode/trace/internal/library"
- "github.com/chialecode/trace/internal/site"
- "github.com/chialecode/trace/internal/site/bilibili"
- "github.com/chialecode/trace/internal/storage"
- "github.com/chialecode/trace/internal/subscription"
-)
-
-const (
- defaultDouyinAutoPollInterval = 90 * time.Second
- // DefaultDouyinLiveGap is the least time between two Douyin live checks.
- // Douyin has no batch status request, so each account costs a request;
- // a round checks every account it can at this pace (a 3-minute round:
- // 30 accounts), the longest unchecked first, and an account's interval
- // grows past the round only by this gap per further account. The checks
- // do not take the site's hourly quota, which stays for update checks,
- // automatic caching and starting recordings (DEC-060 ⑤): a share of the
- // quota left 17 accounts about 18 minutes apart and the interval growing
- // with every account added (dev 2026-11-18).
- DefaultDouyinLiveGap = 6 * time.Second
- defaultFLVConnectTimeout = 10 * time.Second
- defaultFLVIdleTimeout = 15 * time.Second
-)
-
-// LiveRoomAliveChecker is an optional extension on site.LiveProvider for batch room alive checks (e.g. Douyin check_alive).
-type LiveRoomAliveChecker interface {
- CheckRoomsAlive(ctx context.Context, roomIDs []string) (map[string]bool, error)
-}
-
-// LiveAuthChecker is an optional extension on site.LiveProvider to report whether site credentials are active.
-type LiveAuthChecker interface {
- HasAuth() bool
-}
-
-// LiveErrorReporter is an optional extension on site.LiveProvider to report automatic background errors.
-type LiveErrorReporter interface {
- ReportAutomaticError(ctx context.Context, err error)
-}
-
-// WebRIDSyncFunc persists a backfilled or invalidated Douyin web_rid back to subscription storage.
-type WebRIDSyncFunc func(siteID site.ID, uid, webRID string, invalidated bool)
-
-// SiteBackoffChecker reports whether background polling for a given site is currently in backoff.
-type SiteBackoffChecker func(siteID site.ID) (bool, time.Time)
-
-type douyinCachedStatusEntry struct {
- status site.LiveStatus
- state RoomState
- fetchedAt time.Time
-}
-
-// RegisterSiteProvider registers a cross-site LiveProvider (such as Douyin or Bilibili).
-func (m *Manager) RegisterSiteProvider(provider site.LiveProvider) {
- if provider == nil {
- return
- }
- m.mu.Lock()
- m.siteProviders[provider.SiteID()] = provider
- m.mu.Unlock()
-}
-
-// SetWebRIDSyncFunc sets a callback invoked whenever Douyin live status backfills or invalidates an account's web_rid.
-func (m *Manager) SetWebRIDSyncFunc(fn WebRIDSyncFunc) {
- m.mu.Lock()
- m.webRIDSyncFn = fn
- m.mu.Unlock()
-}
-
-// SetSiteBackoffChecker sets a per-site backoff predicate used by background live polling.
-func (m *Manager) SetSiteBackoffChecker(fn SiteBackoffChecker) {
- m.mu.Lock()
- m.siteBackoffFn = fn
- m.mu.Unlock()
-}
-
-// SetDouyinPollMinInterval overrides the 90s minimum per-account auto-record poll interval (used by unit tests).
-func (m *Manager) SetDouyinPollMinInterval(d time.Duration) {
- m.mu.Lock()
- if d >= 0 {
- m.douyinPollMinInterval = d
- }
- m.mu.Unlock()
-}
-
-// SetDouyinLiveGap overrides the least time between two Douyin live checks
-// (used by unit tests; 0 sends them back to back).
-func (m *Manager) SetDouyinLiveGap(d time.Duration) {
- m.mu.Lock()
- m.douyinLiveGap = max(d, 0)
- m.mu.Unlock()
-}
-
-// DouyinLiveGap is the least time between two Douyin live checks.
-func (m *Manager) DouyinLiveGap() time.Duration {
- m.mu.Lock()
- defer m.mu.Unlock()
- return m.douyinLiveGap
-}
-
-// douyinLiveChecksPerRoundLocked is how many Douyin live requests one poll
-// round may make: as many as fit in the round at the live check gap.
-func (m *Manager) douyinLiveChecksPerRoundLocked() int {
- sec := max(m.liveSettings.PollIntervalSeconds, 60)
- if m.douyinLiveGap <= 0 {
- return math.MaxInt32
- }
- return max(1, int(time.Duration(sec)*time.Second/m.douyinLiveGap))
-}
-
-// waitDouyinLiveGap waits the gap before a round's next live check; false
-// when ctx ends first.
-func (m *Manager) waitDouyinLiveGap(ctx context.Context) bool {
- m.mu.Lock()
- gap, wait := m.douyinLiveGap, m.douyinGapWait
- m.mu.Unlock()
- if gap <= 0 {
- return ctx.Err() == nil
- }
- if wait != nil {
- return wait(ctx, gap)
- }
- t := time.NewTimer(gap)
- defer t.Stop()
- select {
- case <-ctx.Done():
- return false
- case <-t.C:
- return true
- }
-}
-
-// DouyinLiveCheckEvery estimates how often each of n auto-record Douyin
-// accounts gets its live status checked.
-func (m *Manager) DouyinLiveCheckEvery(n int) time.Duration {
- m.mu.Lock()
- defer m.mu.Unlock()
- if n <= 0 {
- return 0
- }
- sec := max(m.liveSettings.PollIntervalSeconds, 60)
- per := m.douyinLiveChecksPerRoundLocked()
- rounds := (n + per - 1) / per
- return max(m.douyinPollMinInterval, time.Duration(rounds*sec)*time.Second)
-}
-
-// SetFLVIdleTimeout overrides the 15s per-read idle timeout on HTTP-FLV streams (used by unit tests).
-func (m *Manager) SetFLVIdleTimeout(d time.Duration) {
- m.mu.Lock()
- if d > 0 {
- m.flvIdleTimeout = d
- }
- m.mu.Unlock()
-}
-
-func (m *Manager) getSiteProvider(siteID site.ID) (site.LiveProvider, bool) {
- m.mu.Lock()
- defer m.mu.Unlock()
- p, ok := m.siteProviders[siteID]
- return p, ok
-}
-
-func (m *Manager) hasSiteAuth(siteID site.ID) bool {
- if siteID == site.Bilibili {
- return m.client != nil && m.client.HasAuth()
- }
- p, ok := m.getSiteProvider(siteID)
- if !ok {
- return false
- }
- if checker, ok := p.(LiveAuthChecker); ok {
- return checker.HasAuth()
- }
- return true
-}
-
-func (m *Manager) isSiteInBackoff(siteID site.ID) bool {
- m.mu.Lock()
- fn := m.siteBackoffFn
- m.mu.Unlock()
- if fn != nil {
- inBackoff, _ := fn(siteID)
- return inBackoff
- }
- if m.subs != nil {
- if perSite, ok := any(m.subs).(interface {
- IsSiteInBackoff(site string) (bool, time.Time)
- }); ok {
- inBackoff, _ := perSite.IsSiteInBackoff(string(siteID))
- return inBackoff
- }
- if siteID == site.Bilibili {
- inBackoff, _ := m.subs.IsInBackoff()
- return inBackoff
- }
- }
- return false
-}
-
-func (m *Manager) recordSiteAutoStop(siteID site.ID, reason string) {
- if m.subs == nil {
- return
- }
- if perSite, ok := any(m.subs).(interface {
- RecordSiteAutomaticStop(site, reason string)
- }); ok {
- perSite.RecordSiteAutomaticStop(string(siteID), reason)
- return
- }
- if siteID == site.Bilibili {
- m.subs.RecordAutomaticStop(reason)
- }
-}
-
-func (m *Manager) syncWebRID(siteID site.ID, uid, webRID string, invalidated bool) {
- m.mu.Lock()
- fn := m.webRIDSyncFn
- m.mu.Unlock()
- if fn != nil {
- fn(siteID, uid, webRID, invalidated)
- }
- if m.subs != nil {
- if updater, ok := any(m.subs).(interface {
- UpdateAccountWebRID(site, uid, webRID string) error
- }); ok {
- target := webRID
- if invalidated && target == "" {
- target = ""
- }
- _ = updater.UpdateAccountWebRID(string(siteID), uid, target)
- }
- }
-}
-
-// ObserveAccountLiveHint records a live web_rid or room_id hint discovered passively
-// (e.g. from Douyin aweme/post page 1) with zero extra network requests.
-func (m *Manager) ObserveAccountLiveHint(siteID site.ID, uid, webRID, roomID string) {
- if siteID != site.Douyin {
- return
- }
- normUID, err := site.NormalizeUID(site.Douyin, uid)
- if err != nil {
- return
- }
- webRID = strings.TrimSpace(webRID)
- roomID = strings.TrimSpace(roomID)
-
- subAcc := m.findDouyinSubAccount(normUID)
- var syncNeeded bool
- nowStr := m.nowFunc().UTC().Format(time.RFC3339)
- m.mu.Lock()
- if webRID != "" && m.douyinWebRIDHints[normUID] != webRID {
- m.douyinWebRIDHints[normUID] = webRID
- syncNeeded = true
- }
- if roomID != "" && roomID != "0" {
- m.douyinRoomHints[normUID] = roomID
- effWebRID := firstNonEmpty(webRID, firstNonEmpty(m.douyinWebRIDHints[normUID], subAcc.WebRID))
- stateKey := douyinStateKey(roomID, normUID, effWebRID)
- prev := m.douyinStates[stateKey]
- roomInt, _ := strconv.ParseInt(roomID, 10, 64)
- prev.Site = string(site.Douyin)
- prev.AccountUID = normUID
- prev.UniqueID = firstNonEmpty(prev.UniqueID, subAcc.UniqueID)
- prev.RoomID = roomInt
- prev.RoomIDStr = roomID
- prev.WebRID = firstNonEmpty(effWebRID, prev.WebRID)
- prev.RoomKey = "douyin:live:" + roomID
- prev.LiveState = site.LiveStateLive
- prev.LiveStatus = 1
- prev.StatusText = "直播中"
- prev.Uname = firstNonEmpty(prev.Uname, subAcc.Name)
- prev.Face = sanitizeLiveURL(firstNonEmpty(prev.Face, subAcc.Face))
- prev.UpdatedAt = nowStr
- m.douyinStates[stateKey] = prev
- }
- start := roomID != "" && roomID != "0" && m.douyinShouldAutoStartLocked(site.LiveStatus{Status: site.LiveStateLive, RoomID: roomID})
- m.mu.Unlock()
-
- if syncNeeded {
- m.syncWebRID(site.Douyin, normUID, webRID, false)
- }
- // An update check that sees the account live starts its recording when
- // a subscription records its broadcasts, before the account's turn for
- // a live check (dev 2026-11-18). Starting asks for the stream, which
- // confirms the broadcast; a hint gone stale just starts nothing.
- if start && m.douyinAccountAutoRecords(normUID) {
- target := firstNonEmpty(webRID, roomID)
- go func() {
- _, _ = m.StartDouyinRecording(site.WithAutomaticRequests(context.Background(), "live"), normUID, target)
- }()
- }
-}
-
-// CachedAccountState returns the most recently observed live RoomState for (siteID, uid)
-// from memory without issuing any network requests (used by subscription grid & sidebar).
-func (m *Manager) CachedAccountState(siteID site.ID, uid string) (RoomState, bool) {
- normUID, err := site.NormalizeUID(siteID, uid)
- if err != nil {
- return RoomState{}, false
- }
- m.mu.Lock()
- defer m.mu.Unlock()
-
- switch siteID {
- case site.Bilibili:
- mid, _ := strconv.ParseInt(normUID, 10, 64)
- if mid <= 0 {
- return RoomState{}, false
- }
- for _, st := range m.states {
- if st.UID == mid {
- if st.Site == "" {
- st.Site = string(site.Bilibili)
- }
- st.AccountUID = normUID
- sess := m.sessions[st.RoomID]
- if sess != nil {
- st.Recording = true
- st.RecordSession = sess.sessionID
- st.RecordBytes = sess.bytesTotal
- st.RecordSegments = len(sess.segments)
- st.RecordItemDir = sess.itemDir
- }
- hydrateSessionPreviewFieldsLocked(&st, sess)
- return st, true
- }
- }
- return RoomState{}, false
-
- case site.Douyin:
- for _, sess := range m.douyinSessions {
- if sess != nil && sess.accountUID == normUID {
- if st, ok := m.douyinStates[sess.stateKey]; ok {
- return m.hydrateDouyinStateLocked(st), true
- }
- }
- }
- if cached, ok := m.douyinStatusCache[normUID]; ok {
- return m.hydrateDouyinStateLocked(cached.state), true
- }
- if rid := m.douyinRoomHints[normUID]; rid != "" {
- if st, ok := m.douyinStates["douyin:live:"+rid]; ok {
- return m.hydrateDouyinStateLocked(st), true
- }
- }
- var best RoomState
- var found bool
- for _, st := range m.douyinStates {
- if st.AccountUID != normUID {
- continue
- }
- if !found || st.UpdatedAt > best.UpdatedAt {
- best = st
- found = true
- }
- }
- if found {
- return m.hydrateDouyinStateLocked(best), true
- }
- return RoomState{}, false
- }
- return RoomState{}, false
-}
-
-// CachedStatesByAccountKeys returns in-memory cached live states keyed by ":" with 0 network requests.
-func (m *Manager) CachedStatesByAccountKeys(accountKeys []string) map[string]RoomState {
- out := make(map[string]RoomState, len(accountKeys))
- for _, key := range accountKeys {
- siteID, uid, err := site.ParseAccountKey(strings.TrimSpace(key))
- if err != nil {
- continue
- }
- if st, ok := m.CachedAccountState(siteID, uid); ok {
- out[site.AccountKey(siteID, uid)] = st
- }
- }
- return out
-}
-
-// StatusByAccountKeys queries live status across mixed Bilibili and Douyin ":" keys,
-// using <=50 UID batching for Bilibili and the 60s single-account cache for Douyin.
-func (m *Manager) StatusByAccountKeys(ctx context.Context, accountKeys []string) (map[string]RoomState, error) {
- out := make(map[string]RoomState, len(accountKeys))
- var biliMids []int64
- var douyinUIDs []string
- seen := make(map[string]bool, len(accountKeys))
-
- for _, rawKey := range accountKeys {
- siteID, uid, err := site.ParseAccountKey(strings.TrimSpace(rawKey))
- if err != nil {
- continue
- }
- canon := site.AccountKey(siteID, uid)
- if seen[canon] {
- continue
- }
- seen[canon] = true
- switch siteID {
- case site.Bilibili:
- if mid, pErr := strconv.ParseInt(uid, 10, 64); pErr == nil && mid > 0 {
- biliMids = append(biliMids, mid)
- }
- case site.Douyin:
- douyinUIDs = append(douyinUIDs, uid)
- }
- }
-
- var firstErr error
- if len(biliMids) > 0 && m.client != nil && m.client.HasAuth() {
- if _, err := m.RefreshForAccounts(ctx, biliMids); err != nil {
- firstErr = err
- } else {
- for _, mid := range biliMids {
- uidStr := strconv.FormatInt(mid, 10)
- if st, ok := m.CachedAccountState(site.Bilibili, uidStr); ok {
- out[site.AccountKey(site.Bilibili, uidStr)] = st
- }
- }
- }
- }
-
- for _, secUID := range douyinUIDs {
- st, err := m.CheckAccountLiveStatus(ctx, site.Douyin, secUID, "", false)
- if err != nil {
- if firstErr == nil {
- firstErr = err
- }
- continue
- }
- out[site.AccountKey(site.Douyin, secUID)] = st
- }
- return out, firstErr
-}
-
-// CheckAccountLiveStatus queries live status for one creator account using a 60s TTL cache
-// (unless force is true) and synchronizes any backfilled/invalidated Douyin web_rid.
-func (m *Manager) CheckAccountLiveStatus(ctx context.Context, siteID site.ID, uid, webRIDHint string, force bool) (RoomState, error) {
- switch siteID {
- case site.Bilibili:
- normUID, err := site.NormalizeUID(site.Bilibili, uid)
- if err != nil {
- return RoomState{}, &site.Error{Site: site.Bilibili, Kind: site.ErrKindBadRequest, Message: "无效的哔哩哔哩 UID"}
- }
- mid, _ := strconv.ParseInt(normUID, 10, 64)
- if _, err := m.refreshAccounts(ctx, []int64{mid}, force, true); err != nil {
- return RoomState{}, err
- }
- st, _ := m.CachedAccountState(site.Bilibili, normUID)
- return st, nil
-
- case site.Douyin:
- normUID, err := site.NormalizeUID(site.Douyin, uid)
- if err != nil {
- return RoomState{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindBadRequest, Message: "无效的抖音主播 sec_uid"}
- }
- provider, ok := m.getSiteProvider(site.Douyin)
- if !ok {
- return RoomState{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindUnavailable, Message: "抖音直播服务未初始化"}
- }
-
- now := m.nowFunc()
- subAcc := m.findDouyinSubAccount(normUID)
-
- m.mu.Lock()
- if !force {
- if cached, hit := m.douyinStatusCache[normUID]; hit && now.Sub(cached.fetchedAt) < statusCacheTTL {
- hydrated := m.hydrateDouyinStateLocked(cached.state)
- m.mu.Unlock()
- return hydrated, nil
- }
- }
- effectiveWebRID := firstNonEmpty(strings.TrimSpace(webRIDHint), firstNonEmpty(m.douyinWebRIDHints[normUID], subAcc.WebRID))
- m.mu.Unlock()
-
- liveSt, err := provider.CheckLiveStatus(ctx, normUID, effectiveWebRID)
- if err != nil {
- return RoomState{}, err
- }
- if liveSt.AccountUID == "" {
- liveSt.AccountUID = normUID
- }
- st := m.applyDouyinLiveStatus(liveSt, effectiveWebRID, subAcc, now)
- if m.douyinAccountAutoRecords(normUID) {
- // The check counts as the account's live check, and a broadcast
- // it finds is recorded as a poll round would.
- m.mu.Lock()
- m.douyinLastAutoPoll[normUID] = now
- m.mu.Unlock()
- if m.autoStartDouyin(ctx, liveSt, st) {
- if rec, ok := m.CachedAccountState(site.Douyin, normUID); ok {
- st = rec
- }
- }
- }
- return st, nil
-
- default:
- return RoomState{}, site.ErrUnknownSite
- }
-}
-
-// OpenDouyinRoom inspects a Douyin live room by web_rid (or room_id with uidHint) and updates tracked state.
-func (m *Manager) OpenDouyinRoom(ctx context.Context, webRIDOrRoomID, uidHint string) (RoomState, error) {
- provider, ok := m.getSiteProvider(site.Douyin)
- if !ok {
- return RoomState{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindUnavailable, Message: "抖音直播服务未初始化"}
- }
- target := strings.TrimSpace(webRIDOrRoomID)
- uid := strings.TrimSpace(uidHint)
- if target == "" && uid == "" {
- return RoomState{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindBadRequest, Message: "缺少抖音直播间号或主播标识"}
- }
-
- var subAcc subscription.AccountRef
- if uid != "" {
- if norm, err := site.NormalizeUID(site.Douyin, uid); err == nil {
- uid = norm
- subAcc = m.findDouyinSubAccount(uid)
- if target == "" {
- m.mu.Lock()
- target = firstNonEmpty(m.douyinWebRIDHints[uid], subAcc.WebRID)
- m.mu.Unlock()
- }
- }
- }
-
- liveSt, err := provider.CheckLiveStatus(ctx, uid, target)
- if err != nil {
- return RoomState{}, err
- }
- if subAcc.UID == "" && liveSt.AccountUID != "" {
- subAcc = m.findDouyinSubAccount(liveSt.AccountUID)
- }
- return m.applyDouyinLiveStatus(liveSt, target, subAcc, m.nowFunc()), nil
-}
-
-func (m *Manager) applyDouyinLiveStatus(liveSt site.LiveStatus, queriedWebRID string, subAcc subscription.AccountRef, now time.Time) RoomState {
- secUID := strings.TrimSpace(liveSt.AccountUID)
- newWebRID := strings.TrimSpace(liveSt.WebRID)
- roomIDStr := strings.TrimSpace(liveSt.RoomID)
-
- var needSync bool
- var syncVal string
- var syncInvalidated bool
-
- m.mu.Lock()
- if secUID != "" {
- if liveSt.InvalidatedWebRID {
- if newWebRID != "" {
- m.douyinWebRIDHints[secUID] = newWebRID
- syncVal = newWebRID
- syncInvalidated = true
- } else {
- delete(m.douyinWebRIDHints, secUID)
- syncVal = ""
- syncInvalidated = true
- }
- needSync = true
- } else if newWebRID != "" && m.douyinWebRIDHints[secUID] != newWebRID {
- m.douyinWebRIDHints[secUID] = newWebRID
- syncVal = newWebRID
- if subAcc.UID != "" && subAcc.WebRID != newWebRID {
- needSync = true
- } else if queriedWebRID == "" {
- needSync = true
- }
- }
- if roomIDStr != "" && roomIDStr != "0" {
- m.douyinRoomHints[secUID] = roomIDStr
- } else if liveSt.Status == site.LiveStateOffline || liveSt.Status == site.LiveStateNone {
- delete(m.douyinRoomHints, secUID)
- }
- }
-
- liveInt, statusText := mapSiteLiveStateDisplay(liveSt.Status)
- var parsedRoomID int64
- if roomIDStr != "" {
- parsedRoomID, _ = strconv.ParseInt(roomIDStr, 10, 64)
- }
-
- stateKey := douyinStateKey(roomIDStr, secUID, newWebRID)
- existing := m.douyinStates[stateKey]
- var recSess *recordSession
- if roomIDStr != "" {
- recSess = m.douyinSessions[roomIDStr]
- }
-
- st := RoomState{
- Site: string(site.Douyin),
- AccountUID: secUID,
- UniqueID: subAcc.UniqueID,
- RoomID: parsedRoomID,
- RoomIDStr: roomIDStr,
- WebRID: firstNonEmpty(newWebRID, m.douyinWebRIDHints[secUID]),
- RoomKey: stateKey,
- LiveState: liveSt.Status,
- Uname: firstNonEmpty(liveSt.Uname, subAcc.Name),
- Face: sanitizeLiveURL(firstNonEmpty(liveSt.Face, subAcc.Face)),
- Title: liveSt.Title,
- Cover: sanitizeLiveURL(liveSt.Cover),
- AreaName: liveSt.AreaName,
- LiveStatus: liveInt,
- LiveSince: liveSt.LiveSince,
- StatusText: statusText,
- Quality: firstPositiveInt(liveSt.Quality, existing.Quality),
- QualityName: firstNonEmpty(liveSt.QualityName, existing.QualityName),
- Codec: firstNonEmpty(liveSt.Codec, existing.Codec),
- Recording: recSess != nil,
- Incidents: cloneIncidents(existing.Incidents),
- // The last session's folder stays with its incidents after it ends,
- // so Tasks › 录制异常 shows them on that session only.
- RecordItemDir: existing.RecordItemDir,
- StopReason: existing.StopReason,
- LastError: existing.LastError,
- UpdatedAt: now.UTC().Format(time.RFC3339),
- }
- st = m.hydrateDouyinStateLocked(st)
- m.douyinStates[stateKey] = st
- if secUID != "" {
- for k, old := range m.douyinStates {
- if k != stateKey && old.AccountUID == secUID && !m.isRoomActivelyRecordingLocked(old.RoomIDStr) {
- delete(m.douyinStates, k)
- }
- }
- m.douyinStatusCache[secUID] = douyinCachedStatusEntry{
- status: liveSt,
- state: st,
- fetchedAt: now,
- }
- }
- m.mu.Unlock()
-
- if needSync && secUID != "" {
- m.syncWebRID(site.Douyin, secUID, syncVal, syncInvalidated)
- }
- return st
-}
-
-func (m *Manager) isRoomActivelyRecordingLocked(roomIDStr string) bool {
- if roomIDStr == "" {
- return false
- }
- _, ok := m.douyinSessions[roomIDStr]
- return ok
-}
-
-func (m *Manager) hydrateDouyinStateLocked(st RoomState) RoomState {
- if st.Site == "" {
- st.Site = string(site.Douyin)
- }
- if sess := m.douyinSessions[st.RoomIDStr]; sess != nil {
- st.Recording = true
- st.RecordSession = sess.sessionID
- st.RecordDurationSec = m.nowFunc().Sub(sess.startedAt).Seconds()
- st.RecordBytes = sess.bytesTotal
- st.RecordSegments = len(sess.segments)
- st.RecordItemDir = sess.itemDir
- if sess.quality > 0 {
- st.Quality = sess.quality
- }
- if sess.qualityName != "" {
- st.QualityName = sess.qualityName
- }
- if sess.codec != "" {
- st.Codec = sess.codec
- }
- if sess.stopReason != "" {
- st.StopReason = sess.stopReason
- }
- if sess.lastErr != "" {
- st.LastError = sess.lastErr
- }
- hydrateSessionPreviewFieldsLocked(&st, sess)
- } else {
- st.Recording = false
- hydrateSessionPreviewFieldsLocked(&st, nil)
- }
- return st
-}
-
-func douyinStateKey(roomIDStr, secUID, webRID string) string {
- if roomIDStr != "" && roomIDStr != "0" {
- return "douyin:live:" + roomIDStr
- }
- if secUID != "" {
- return "douyin:user:" + secUID
- }
- return "douyin:web:" + webRID
-}
-
-func mapSiteLiveStateDisplay(state string) (int, string) {
- switch state {
- case site.LiveStateLive:
- return 1, "直播中"
- case site.LiveStateRound:
- return 2, "轮播中"
- case site.LiveStateAudioOnly:
- return 0, "语音直播(暂不支持录制)"
- default:
- return 0, "未开播"
- }
-}
-
-func (m *Manager) findDouyinSubAccount(secUID string) subscription.AccountRef {
- if m.subs == nil || secUID == "" {
- return subscription.AccountRef{}
- }
- list, err := m.subs.List()
- if err != nil {
- return subscription.AccountRef{}
- }
- for _, s := range list {
- for _, acc := range s.Accounts {
- if acc.Site == string(site.Douyin) && acc.UID == secUID {
- if acc.Name == "" {
- acc.Name = s.Name
- }
- if acc.Face == "" {
- acc.Face = s.Face
- }
- return acc
- }
- }
- }
- return subscription.AccountRef{}
-}
-
-// douyinAccountAutoRecords tells whether a subscription records the
-// broadcasts of a Douyin account.
-func (m *Manager) douyinAccountAutoRecords(secUID string) bool {
- if m.subs == nil || secUID == "" {
- return false
- }
- list, err := m.subs.List()
- if err != nil {
- return false
- }
- for _, s := range list {
- if !s.Rules.AutoRecord && !s.LiveAutoRecord {
- continue
- }
- for _, acc := range s.Accounts {
- if acc.Site != string(site.Douyin) {
- continue
- }
- if norm, err := site.NormalizeUID(site.Douyin, acc.UID); err == nil && norm == secUID {
- return true
- }
- }
- }
- return false
-}
-
-// douyinShouldAutoStartLocked tells whether a broadcast a check found should
-// start recording: it is live and neither recorded already nor stopped by
-// hand. The caller holds m.mu.
-func (m *Manager) douyinShouldAutoStartLocked(liveSt site.LiveStatus) bool {
- if liveSt.Status != site.LiveStateLive || liveSt.RoomID == "" || m.stopping {
- return false
- }
- _, running := m.douyinSessions[liveSt.RoomID]
- return !running && !m.douyinStoppedRooms[liveSt.RoomID]
-}
-
-// autoStartDouyin starts recording a broadcast found live outside a poll
-// round (an account's status refreshed by hand or by an update check), for
-// an account whose subscription records broadcasts. It reports whether a
-// recording started.
-func (m *Manager) autoStartDouyin(ctx context.Context, liveSt site.LiveStatus, st RoomState) bool {
- m.mu.Lock()
- if liveSt.Status != site.LiveStateLive && liveSt.RoomID != "" {
- delete(m.douyinStoppedRooms, liveSt.RoomID)
- }
- start := m.douyinShouldAutoStartLocked(liveSt)
- m.mu.Unlock()
- if !start {
- return false
- }
- if _, err := m.StartDouyinRecording(ctx, liveSt.AccountUID, firstNonEmpty(st.WebRID, liveSt.RoomID)); err != nil {
- m.mu.Lock()
- for k, rs := range m.douyinStates {
- if rs.AccountUID == liveSt.AccountUID {
- rs.LastError = err.Error()
- m.douyinStates[k] = rs
- }
- }
- m.mu.Unlock()
- return false
- }
- return true
-}
-
-// PollDouyinAutoRecordNow polls subscribed Douyin accounts with AutoRecord enabled,
-// enforcing >= 90s per-account interval, checking known active room_ids via CheckRoomsAlive
-// when supported, and auto-starting HTTP-FLV recording on live broadcasts.
-func (m *Manager) PollDouyinAutoRecordNow(ctx context.Context) ([]RoomState, error) {
- return m.pollDouyinAutoRecord(ctx)
-}
-
-func (m *Manager) pollDouyinAutoRecord(ctx context.Context) ([]RoomState, error) {
- provider, ok := m.getSiteProvider(site.Douyin)
- if !ok || m.subs == nil {
- return m.ListRooms(), nil
- }
- if !m.hasSiteAuth(site.Douyin) {
- return m.ListRooms(), nil
- }
- subList, err := m.subs.List()
- if err != nil {
- return nil, err
- }
-
- type autoTarget struct {
- sub subscription.Subscription
- acc subscription.AccountRef
- }
- var targets []autoTarget
- seen := make(map[string]bool)
- for _, s := range subList {
- if !s.Rules.AutoRecord && !s.LiveAutoRecord {
- continue
- }
- for _, acc := range s.Accounts {
- if acc.Site != string(site.Douyin) {
- continue
- }
- normUID, nErr := site.NormalizeUID(site.Douyin, acc.UID)
- if nErr != nil || seen[normUID] {
- continue
- }
- seen[normUID] = true
- acc.UID = normUID
- targets = append(targets, autoTarget{sub: s, acc: acc})
- }
- }
- if len(targets) == 0 {
- return m.ListRooms(), nil
- }
- // The accounts checked longest ago go first (never checked: first of
- // all), so a round that cannot check them all goes round all of them.
- m.mu.Lock()
- sort.SliceStable(targets, func(i, j int) bool {
- return m.douyinLastAutoPoll[targets[i].acc.UID].Before(m.douyinLastAutoPoll[targets[j].acc.UID])
- })
- requests := m.douyinLiveChecksPerRoundLocked()
- m.mu.Unlock()
- sent := 0 // live requests of this round, spaced by the live check gap
-
- // Step 1: Check known active room_ids via CheckRoomsAlive (batch check_alive) when supported.
- if aliveChecker, ok := provider.(LiveRoomAliveChecker); ok {
- var knownRooms []string
- roomToUID := make(map[string]string)
- m.mu.Lock()
- for _, t := range targets {
- if rid := m.douyinRoomHints[t.acc.UID]; rid != "" && rid != "0" {
- knownRooms = append(knownRooms, rid)
- roomToUID[rid] = t.acc.UID
- }
- }
- m.mu.Unlock()
-
- // A round with a single request spends it on an account's status:
- // the recordings notice an ended broadcast themselves.
- if len(knownRooms) > 0 && requests >= 2 {
- requests--
- sent++
- aliveMap, aErr := aliveChecker.CheckRoomsAlive(ctx, knownRooms)
- if aErr != nil {
- if site.IsRoundStop(aErr) {
- if rep, rOK := provider.(LiveErrorReporter); rOK {
- rep.ReportAutomaticError(ctx, aErr)
- }
- if site.IsCircuitBreak(aErr) {
- m.recordSiteAutoStop(site.Douyin, site.KindOf(aErr))
- }
- return nil, aErr
- }
- } else {
- now := m.nowFunc()
- m.mu.Lock()
- for _, rid := range knownRooms {
- alive, present := aliveMap[rid]
- if present && !alive {
- uid := roomToUID[rid]
- delete(m.douyinRoomHints, uid)
- delete(m.douyinStoppedRooms, rid)
- m.douyinPrevLive[uid] = site.LiveStateOffline
- if sess := m.douyinSessions[rid]; sess != nil {
- if sess.stopReason == "" {
- sess.stopReason = "ended"
- }
- sess.cancel()
- }
- key := "douyin:live:" + rid
- if st, has := m.douyinStates[key]; has {
- st.LiveStatus = 0
- st.LiveState = site.LiveStateOffline
- st.StatusText = "未开播"
- st.Recording = false
- st.UpdatedAt = now.UTC().Format(time.RFC3339)
- m.douyinStates[key] = st
- }
- }
- }
- m.mu.Unlock()
- }
- }
- }
-
- // Step 2: Poll each AutoRecord Douyin account whose last poll was >= douyinPollMinInterval ago.
- m.mu.Lock()
- minInterval := m.douyinPollMinInterval
- notifyGlobal := m.liveSettings.NotifyOnStart
- m.mu.Unlock()
-
- var notifications []Notification
- type startReq struct {
- uid string
- webRID string
- }
- var toStart []startReq
-
- for _, t := range targets {
- if ctx.Err() != nil {
- break
- }
- uid := t.acc.UID
- now := m.nowFunc()
-
- m.mu.Lock()
- lastAt, hadLast := m.douyinLastAutoPoll[uid]
- _, alreadyRec := m.douyinSessions[m.douyinRoomHints[uid]]
- webRIDHint := firstNonEmpty(m.douyinWebRIDHints[uid], t.acc.WebRID)
- m.mu.Unlock()
-
- if alreadyRec {
- continue
- }
- if hadLast && minInterval > 0 && now.Sub(lastAt) < minInterval {
- continue
- }
- if requests <= 0 {
- break
- }
- if sent > 0 && !m.waitDouyinLiveGap(ctx) {
- break
- }
- requests--
- sent++
-
- m.mu.Lock()
- m.douyinLastAutoPoll[uid] = now
- m.mu.Unlock()
-
- liveSt, cErr := provider.CheckLiveStatus(ctx, uid, webRIDHint)
- if cErr != nil {
- if site.IsRoundStop(cErr) {
- if rep, rOK := provider.(LiveErrorReporter); rOK {
- rep.ReportAutomaticError(ctx, cErr)
- }
- if site.IsCircuitBreak(cErr) {
- m.recordSiteAutoStop(site.Douyin, site.KindOf(cErr))
- }
- return m.ListRooms(), cErr
- }
- continue
- }
- if liveSt.AccountUID == "" {
- liveSt.AccountUID = uid
- }
- roomState := m.applyDouyinLiveStatus(liveSt, webRIDHint, t.acc, now)
-
- m.mu.Lock()
- prev := m.douyinPrevLive[uid]
- m.douyinPrevLive[uid] = liveSt.Status
- if liveSt.Status != site.LiveStateLive && liveSt.RoomID != "" {
- delete(m.douyinStoppedRooms, liveSt.RoomID)
- }
- if liveSt.Status == site.LiveStateLive && prev != site.LiveStateLive && notifyGlobal && t.sub.LiveNotify {
- notifications = append(notifications, Notification{
- Site: string(site.Douyin),
- AccountUID: uid,
- RoomID: roomState.RoomID,
- RoomIDStr: liveSt.RoomID,
- WebRID: roomState.WebRID,
- Uname: firstNonEmpty(roomState.Uname, t.sub.Name),
- Title: roomState.Title,
- StartedAt: now.UTC().Format(time.RFC3339),
- })
- }
- shouldStart := m.douyinShouldAutoStartLocked(liveSt)
- m.mu.Unlock()
-
- if shouldStart {
- toStart = append(toStart, startReq{uid: uid, webRID: firstNonEmpty(roomState.WebRID, liveSt.RoomID)})
- }
- }
-
- for _, n := range notifications {
- if m.onNotify != nil {
- m.onNotify(n)
- }
- }
- for _, req := range toStart {
- if _, sErr := m.StartDouyinRecording(bilibili.WithAutomaticRequests(ctx, "live"), req.uid, req.webRID); sErr != nil {
- m.mu.Lock()
- for k, st := range m.douyinStates {
- if st.AccountUID == req.uid {
- st.LastError = sErr.Error()
- m.douyinStates[k] = st
- }
- }
- m.mu.Unlock()
- }
- }
- return m.ListRooms(), nil
-}
-
-// StartRecordingByKey dispatches live recording start by canonical room/account key or numeric Bilibili room ID.
-func (m *Manager) StartRecordingByKey(ctx context.Context, key string) (RoomState, error) {
- key = strings.TrimSpace(key)
- switch {
- case strings.HasPrefix(key, "douyin:live:"):
- rid := strings.TrimPrefix(key, "douyin:live:")
- return m.StartDouyinRecording(ctx, "", rid)
- case strings.HasPrefix(key, "douyin:user:"):
- uid := strings.TrimPrefix(key, "douyin:user:")
- return m.StartDouyinRecording(ctx, uid, "")
- case strings.HasPrefix(key, "douyin:"):
- uid := strings.TrimPrefix(key, "douyin:")
- return m.StartDouyinRecording(ctx, uid, "")
- case strings.HasPrefix(key, "bilibili:live:"):
- rid, err := strconv.ParseInt(strings.TrimPrefix(key, "bilibili:live:"), 10, 64)
- if err != nil || rid <= 0 {
- return RoomState{}, &site.Error{Site: site.Bilibili, Kind: site.ErrKindBadRequest, Message: "无效的直播间房间号"}
- }
- return m.StartRecording(ctx, rid)
- default:
- if rid, err := strconv.ParseInt(key, 10, 64); err == nil && rid > 0 {
- m.mu.Lock()
- _, isDouyinRoom := m.douyinStates["douyin:live:"+key]
- m.mu.Unlock()
- if isDouyinRoom {
- return m.StartDouyinRecording(ctx, "", key)
- }
- return m.StartRecording(ctx, rid)
- }
- return RoomState{}, &site.Error{Kind: site.ErrKindBadRequest, Message: "无效的直播间标识"}
- }
-}
-
-// StopRecordingByKey stops an active Bilibili or Douyin live recording by room key, account key, or room ID.
-func (m *Manager) StopRecordingByKey(key string) (RoomState, error) {
- key = strings.TrimSpace(key)
- switch {
- case strings.HasPrefix(key, "douyin:live:"):
- return m.StopDouyinRecording(strings.TrimPrefix(key, "douyin:live:"))
- case strings.HasPrefix(key, "douyin:user:"):
- return m.StopDouyinRecording(strings.TrimPrefix(key, "douyin:user:"))
- case strings.HasPrefix(key, "douyin:"):
- return m.StopDouyinRecording(strings.TrimPrefix(key, "douyin:"))
- case strings.HasPrefix(key, "bilibili:live:"):
- rid, _ := strconv.ParseInt(strings.TrimPrefix(key, "bilibili:live:"), 10, 64)
- return m.StopRecording(rid)
- default:
- m.mu.Lock()
- _, hasDouyin := m.douyinSessions[key]
- m.mu.Unlock()
- if hasDouyin {
- return m.StopDouyinRecording(key)
- }
- if rid, err := strconv.ParseInt(key, 10, 64); err == nil && rid > 0 {
- return m.StopRecording(rid)
- }
- return m.StopDouyinRecording(key)
- }
-}
-
-// StartDouyinRecording starts an HTTP-FLV live recording into
-// /douyin//lives// with item key douyin:live:.
-func (m *Manager) StartDouyinRecording(ctx context.Context, uid, roomOrWebRID string) (RoomState, error) {
- m.startMu.Lock()
- defer m.startMu.Unlock()
-
- m.mu.Lock()
- stopping := m.stopping
- m.mu.Unlock()
- if stopping {
- return RoomState{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindUnavailable, Message: "应用正在退出,不能开始新的录制"}
- }
-
- provider, ok := m.getSiteProvider(site.Douyin)
- if !ok {
- return RoomState{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindUnavailable, Message: "抖音直播服务未初始化"}
- }
-
- uid = strings.TrimSpace(uid)
- target := strings.TrimSpace(roomOrWebRID)
- if uid == "" && target != "" {
- m.mu.Lock()
- if st, exists := m.douyinStates["douyin:live:"+target]; exists && st.AccountUID != "" {
- uid = st.AccountUID
- if st.WebRID != "" {
- target = st.WebRID
- }
- } else {
- for _, st := range m.douyinStates {
- if st.WebRID == target || st.RoomIDStr == target {
- uid = st.AccountUID
- break
- }
- }
- }
- m.mu.Unlock()
- }
- if uid != "" {
- if normUID, err := site.NormalizeUID(site.Douyin, uid); err == nil {
- uid = normUID
- }
- if target == "" {
- subAcc := m.findDouyinSubAccount(uid)
- m.mu.Lock()
- target = firstNonEmpty(m.douyinWebRIDHints[uid], firstNonEmpty(subAcc.WebRID, m.douyinRoomHints[uid]))
- m.mu.Unlock()
- }
- }
-
- m.mu.Lock()
- codecOrder := append([]string(nil), m.liveSettings.CodecOrder...)
- m.mu.Unlock()
-
- cacheRoot := m.lib.CacheDir()
- if m.freeBytesFunc != nil && m.minFreeBytes > 0 {
- freeBytes, fErr := m.freeBytesFunc(cacheRoot)
- if fErr != nil {
- return RoomState{}, fErr
- }
- if freeBytes < m.minFreeBytes {
- return RoomState{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindStorage, Message: "磁盘可用空间不足 1 GiB,无法开始录制"}
- }
- }
-
- plan, err := provider.SelectLiveStream(ctx, uid, target, codecOrder)
- if err != nil {
- return RoomState{}, err
- }
- if plan.Status == site.LiveStateAudioOnly {
- return RoomState{}, &site.Error{
- Site: site.Douyin,
- Kind: site.ErrKindUnavailable,
- Unsupported: true,
- Message: "这个直播间是语音直播,暂不支持录制",
- }
- }
- if plan.Status != site.LiveStateLive {
- return RoomState{}, &site.Error{
- Site: site.Douyin,
- Kind: site.ErrKindUnavailable,
- Message: "主播当前未开播,仅在直播中时支持录制",
- }
- }
- if len(plan.URLs) == 0 || (plan.Transport != "" && plan.Transport != site.LiveTransportHTTPFLV) || strings.EqualFold(plan.Format, "ts") {
- return RoomState{}, &site.Error{
- Site: site.Douyin,
- Kind: site.ErrKindUnavailable,
- Unsupported: true,
- Message: "这个直播间仅提供 HLS 流或缺少可录制的 HTTP-FLV 流,当前版本暂不支持录制",
- }
- }
-
- roomID := strings.TrimSpace(plan.RoomID)
- if roomID == "" || library.SanitizeFileName(roomID) != roomID {
- return RoomState{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindSchemaChanged, Message: "抖音直播间缺少有效 room_id"}
- }
- secUID, err := site.NormalizeUID(site.Douyin, firstNonEmpty(plan.AccountUID, uid))
- if err != nil {
- return RoomState{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindSchemaChanged, Message: "抖音直播间缺少有效主播 sec_uid"}
- }
- plan.AccountUID = secUID
-
- m.mu.Lock()
- if existingSess, already := m.douyinSessions[roomID]; already && existingSess != nil {
- st := m.hydrateDouyinStateLocked(m.douyinStates[existingSess.stateKey])
- m.mu.Unlock()
- return st, nil
- }
- m.mu.Unlock()
-
- subAcc := m.findDouyinSubAccount(secUID)
- // Populate room display metadata from cache or CheckLiveStatus.
- st, okCached := m.CachedAccountState(site.Douyin, secUID)
- if !okCached || st.RoomIDStr != roomID || st.Title == "" {
- forceFresh := !okCached || st.RoomIDStr != roomID
- if freshSt, cErr := m.CheckAccountLiveStatus(ctx, site.Douyin, secUID, firstNonEmpty(plan.WebRID, target), forceFresh); cErr == nil {
- st = freshSt
- }
- }
-
- now := m.nowFunc().UTC()
- liveSince := st.LiveSince
- if liveSince <= 0 {
- liveSince = now.Unix()
- }
- webRID := firstNonEmpty(plan.WebRID, st.WebRID)
- canonicalURL := "https://live.douyin.com/" + firstNonEmpty(webRID, roomID)
-
- itemDir, err := library.EnsureWithinRoot(cacheRoot, filepath.Join(cacheRoot, "douyin", site.DouyinAuthorDir(secUID), "lives", roomID))
- if err != nil {
- return RoomState{}, err
- }
- itemKey := library.CanonicalItemKey("douyin", "live", roomID)
- existingMeta, exists, err := m.lib.GetItem(itemKey)
- if err != nil {
- return RoomState{}, err
- }
- if exists && existingMeta.ItemDir != "" {
- itemDir = existingMeta.ItemDir
- }
- if err := os.MkdirAll(itemDir, 0o700); err != nil {
- return RoomState{}, err
- }
-
- parsedRoomInt, _ := strconv.ParseInt(roomID, 10, 64)
- title := firstNonEmpty(st.Title, "抖音直播 "+firstNonEmpty(webRID, roomID))
- uname := firstNonEmpty(st.Uname, subAcc.Name)
- face := sanitizeLiveURL(firstNonEmpty(st.Face, subAcc.Face))
-
- meta := library.ItemMetadata{
- Version: 1,
- ID: "live:" + roomID,
- Site: "douyin",
- Kind: "live",
- Status: "recording",
- Title: title,
- URL: canonicalURL,
- PubTs: liveSince,
- CachedAt: now.Format(time.RFC3339),
- Author: library.ItemAuthor{
- Site: "douyin",
- UID: secUID,
- UniqueID: subAcc.UniqueID,
- Name: uname,
- Face: face,
- },
- }
- if exists {
- meta = existingMeta
- meta.Status = "recording"
- if title != "" {
- meta.Title = title
- }
- meta.URL = canonicalURL
- meta.Author.Site = "douyin"
- meta.Author.UID = secUID
- if uname != "" {
- meta.Author.Name = uname
- }
- if face != "" {
- meta.Author.Face = face
- }
- }
- if meta.Live == nil {
- meta.Live = &library.LiveRecordingInfo{
- RoomID: parsedRoomInt,
- RoomIDStr: roomID,
- WebRID: webRID,
- LiveSince: liveSince,
- StartedAt: now.Format(time.RFC3339),
- }
- }
- meta.Live.RoomID = parsedRoomInt
- meta.Live.RoomIDStr = roomID
- if webRID != "" {
- meta.Live.WebRID = webRID
- }
- meta.Live.EndedAt, meta.Live.StopReason = "", ""
- meta.Live.Quality = plan.Quality
- meta.Live.QualityName = plan.QualityName
- meta.Live.Codec = plan.Codec
- meta.Live.Source = "manual"
- if bilibili.AutomaticRequestSource(ctx) != "" {
- meta.Live.Source = "auto"
- }
-
- savedMeta, err := m.lib.SaveItem(itemDir, meta)
- if err != nil {
- return RoomState{}, err
- }
-
- transport := plan.Media
- if len(transport.AllowedDomains) == 0 {
- transport = site.DouyinLiveTransport("", false)
- }
-
- recParent := context.Background()
- if meta.Live.Source == "auto" {
- recParent = bilibili.WithAutomaticRequests(recParent, "live")
- }
- recCtx, recCancel := context.WithCancel(recParent)
- stateKey := "douyin:live:" + roomID
- sess := &recordSession{
- siteID: string(site.Douyin),
- accountUID: secUID,
- roomIDStr: roomID,
- webRID: webRID,
- stateKey: stateKey,
- coverURL: st.Cover,
- transport: transport,
- sessionID: roomID,
- roomID: parsedRoomInt,
- uname: uname,
- face: face,
- title: title,
- itemDir: itemDir,
- itemMeta: savedMeta,
- cancel: recCancel,
- doneCh: make(chan struct{}),
- startedAt: now,
- reportAt: now,
- nextPart: nextPartNumber(savedMeta),
- lastSequence: savedMeta.Live.LastSequence,
- hasSequence: savedMeta.Live.HasSequence,
- quality: plan.Quality,
- qualityName: plan.QualityName,
- codec: plan.Codec,
- streamTransport: string(site.LiveTransportHTTPFLV),
- previewSupport: true,
- previewReason: previewReasonWaitingFirstFragment,
- }
- m.initSessionIncidents(sess)
- if plan.BitrateBps > 0 {
- sess.nominalByteRate = float64(plan.BitrateBps) / 8.0
- }
- for _, media := range savedMeta.Media {
- if media.Role == "live_segment" {
- sess.segments = append(sess.segments, media.Path)
- sess.bytesTotal += media.Bytes
- }
- }
-
- outState := RoomState{
- Site: string(site.Douyin),
- AccountUID: secUID,
- UniqueID: subAcc.UniqueID,
- RoomID: parsedRoomInt,
- RoomIDStr: roomID,
- WebRID: webRID,
- RoomKey: stateKey,
- LiveState: site.LiveStateLive,
- Uname: uname,
- Face: face,
- Title: title,
- Cover: sanitizeLiveURL(st.Cover),
- AreaName: st.AreaName,
- LiveStatus: 1,
- LiveSince: liveSince,
- Source: meta.Live.Source,
- StatusText: "直播中",
- Quality: plan.Quality,
- QualityName: plan.QualityName,
- Codec: plan.Codec,
- Transport: string(site.LiveTransportHTTPFLV),
- Recording: true,
- RecordSession: roomID,
- RecordBytes: sess.bytesTotal,
- RecordSegments: len(sess.segments),
- RecordItemDir: itemDir,
- PreviewSupported: true,
- PreviewReason: previewReasonWaitingFirstFragment,
- Incidents: cloneIncidents(sess.incidents),
- UpdatedAt: now.Format(time.RFC3339),
- }
-
- m.mu.Lock()
- delete(m.douyinStoppedRooms, roomID)
- m.douyinSessions[roomID] = sess
- m.douyinStates[stateKey] = outState
- for k, old := range m.douyinStates {
- if k != stateKey && old.AccountUID == secUID && !m.isRoomActivelyRecordingLocked(old.RoomIDStr) {
- delete(m.douyinStates, k)
- }
- }
- m.mu.Unlock()
-
- m.wg.Add(1)
- go m.runDouyinRecordingSession(recCtx, sess, plan, codecOrder)
-
- if m.onState != nil {
- m.onState(outState)
- }
- return outState, nil
-}
-
-// StopDouyinRecording stops an active Douyin live recording by room_id, web_rid, or主播 sec_uid,
-// suppressing auto-restart for the remainder of that room_id broadcast.
-func (m *Manager) StopDouyinRecording(roomOrUID string) (RoomState, error) {
- target := strings.TrimSpace(roomOrUID)
- m.mu.Lock()
- var sess *recordSession
- var roomID string
- if s, ok := m.douyinSessions[target]; ok {
- sess = s
- roomID = target
- } else {
- for rid, s := range m.douyinSessions {
- if s.accountUID == target || s.webRID == target || s.stateKey == target {
- sess = s
- roomID = rid
- break
- }
- }
- }
- if roomID != "" {
- m.douyinStoppedRooms[roomID] = true
- }
- if sess != nil && sess.stopReason == "" {
- sess.stopReason = "user_stop"
- }
- m.mu.Unlock()
-
- if sess == nil {
- m.mu.Lock()
- for _, st := range m.douyinStates {
- if st.RoomIDStr == target || st.AccountUID == target || st.WebRID == target || st.RoomKey == target {
- st.Recording = false
- m.mu.Unlock()
- return st, nil
- }
- }
- m.mu.Unlock()
- return RoomState{Site: string(site.Douyin)}, nil
- }
-
- sess.cancel()
- select {
- case <-sess.doneCh:
- case <-time.After(m.finalizeTimeout):
- m.mu.Lock()
- state := m.douyinStates[sess.stateKey]
- m.mu.Unlock()
- return state, &site.Error{Site: site.Douyin, Kind: site.ErrKindStorage, Message: "录制收尾已到时间上限,临时片段会在下次启动时恢复"}
- }
-
- m.mu.Lock()
- st := m.douyinStates[sess.stateKey]
- st.Recording = false
- st.RecordDurationSec = m.nowFunc().Sub(sess.startedAt).Seconds()
- st.RecordBytes = sess.bytesTotal
- st.RecordSegments = len(sess.segments)
- st.RecordItemDir = sess.itemDir
- st.Incidents = cloneIncidents(sess.incidents)
- st.StopReason = sess.stopReason
- if sess.lastErr != "" {
- st.LastError = sess.lastErr
- }
- hydrateSessionPreviewFieldsLocked(&st, nil)
- m.douyinStates[sess.stateKey] = st
- m.mu.Unlock()
-
- if m.onState != nil {
- m.onState(st)
- }
- return st, nil
-}
-
-func (m *Manager) runDouyinRecordingSession(ctx context.Context, sess *recordSession, initial site.LiveStreamPlan, codecOrder []string) {
- defer m.wg.Done()
- defer close(sess.doneCh)
- defer func() {
- m.mu.Lock()
- delete(m.douyinSessions, sess.roomIDStr)
- m.mu.Unlock()
- }()
-
- var flvConn *activeFLVConn
- defer func() {
- if flvConn != nil {
- _ = flvConn.Close()
- }
- }()
-
- plan := initial
- if len(plan.Media.AllowedDomains) == 0 {
- plan.Media = sess.transport
- }
- _ = m.saveDouyinLiveCover(ctx, sess, plan.Media)
-
- provider, _ := m.getSiteProvider(site.Douyin)
- var lostAt time.Time
-
- for ctx.Err() == nil {
- m.mu.Lock()
- stopped := sess.stopReason != ""
- m.mu.Unlock()
- if stopped {
- break
- }
- if m.freeBytesFunc != nil && m.minFreeBytes > 0 {
- if free, fErr := m.freeBytesFunc(sess.itemDir); fErr != nil {
- m.setSessionStop(sess, "storage", fErr)
- break
- } else if free < m.minFreeBytes {
- m.recordSessionIncident(sess, library.LiveIncident{
- Kind: library.LiveIncidentDisk,
- At: m.nowFunc().UTC().Format(time.RFC3339),
- Reason: "保存位置磁盘空间不足,录制已停止",
- }, true)
- m.setSessionStop(sess, "storage", &site.Error{Site: site.Douyin, Kind: site.ErrKindStorage, Message: "磁盘空间不足 1 GiB,已停止录制"})
- break
- }
- }
-
- partRel := fmt.Sprintf("part-%03d.mp4", sess.nextPart)
- pending := partRel + ".part"
- path, err := library.ResolveItemPath(sess.itemDir, pending)
- if err != nil {
- m.setSessionStop(sess, "storage", err)
- break
- }
- for _, candidate := range []string{path, strings.TrimSuffix(path, ".part")} {
- if _, statErr := os.Lstat(candidate); statErr == nil {
- err = &site.Error{Site: site.Douyin, Kind: site.ErrKindStorage, Message: "录像目标已存在且未登记,原文件已保留"}
- break
- } else if !os.IsNotExist(statErr) {
- err = statErr
- break
- }
- }
- if err != nil {
- m.setSessionStop(sess, "storage", err)
- break
- }
-
- m.mu.Lock()
- sess.itemMeta.PendingParts = append(sess.itemMeta.PendingParts, pending)
- sess.itemMeta.Live.Codec = plan.Codec
- sess.itemMeta.Live.Quality = plan.Quality
- sess.itemMeta.Live.QualityName = plan.QualityName
- sess.codec, sess.quality, sess.qualityName = plan.Codec, plan.Quality, plan.QualityName
- if st, ok := m.douyinStates[sess.stateKey]; ok {
- st.Codec, st.Quality, st.QualityName = plan.Codec, plan.Quality, plan.QualityName
- m.douyinStates[sess.stateKey] = st
- }
- m.mu.Unlock()
- if err := m.saveSession(sess); err != nil {
- m.setSessionStop(sess, "storage", err)
- break
- }
-
- sess.segmentDuration, sess.wroteMedia = 0, false
- m.beginSessionPart(sess, sess.nextPart, path, string(site.LiveTransportHTTPFLV))
- n, recordErr := m.recordFLVPartWithTransport(ctx, sess, plan.Media, plan.URLs, &flvConn, path)
- m.endSessionPart(sess)
- if !errors.Is(recordErr, errSegmentRollover) && flvConn != nil {
- _ = flvConn.Close()
- flvConn = nil
- }
-
- if n > 0 {
- job := partJob{path: path, partRel: partRel, pending: pending, codec: sess.codec, quality: plan.Quality, qualityName: plan.QualityName}
- if errors.Is(recordErr, errSegmentRollover) && ctx.Err() == nil {
- m.finishPartAsync(sess, job)
- } else {
- sess.waitPartsFinished()
- if err := m.finishPart(sess, job); err != nil {
- m.setSessionStop(sess, "storage", err)
- break
- }
- }
- sess.nextPart++
- if sess.wroteMedia {
- lostAt = time.Time{}
- }
- } else {
- _ = os.Remove(path)
- m.mu.Lock()
- sess.itemMeta.PendingParts = removePending(sess.itemMeta.PendingParts, pending)
- clearLiveCheckpoint(&sess.itemMeta, pending)
- m.mu.Unlock()
- }
-
- if err := m.saveSession(sess); err != nil {
- if isDiskFullError(err) {
- m.recordSessionIncident(sess, library.LiveIncident{
- Kind: library.LiveIncidentDisk,
- At: m.nowFunc().UTC().Format(time.RFC3339),
- Part: pending,
- Reason: "保存位置磁盘空间不足,录制已停止",
- }, true)
- }
- m.setSessionStop(sess, "storage", err)
- break
- }
- if ctx.Err() != nil {
- break
- }
- if errors.Is(recordErr, errSegmentRollover) {
- continue
- }
- if recordErr != nil {
- if isDiskFullError(recordErr) {
- m.recordSessionIncident(sess, library.LiveIncident{
- Kind: library.LiveIncidentDisk,
- At: m.nowFunc().UTC().Format(time.RFC3339),
- Part: pending,
- Reason: "保存位置磁盘空间不足,录制已停止",
- }, true)
- }
- if reason := liveStopReason(recordErr); reason != "" {
- if rep, ok := provider.(LiveErrorReporter); ok {
- rep.ReportAutomaticError(ctx, recordErr)
- }
- if reason == "risk_control" || reason == "rate_limited" {
- m.recordSiteAutoStop(site.Douyin, reason)
- }
- m.setSessionStop(sess, reason, recordErr)
- break
- }
- m.mu.Lock()
- sess.lastErr = recordErr.Error()
- m.mu.Unlock()
- if lostAt.IsZero() {
- lostAt = m.nowFunc()
- }
- if m.maxStreamLossDur > 0 && m.nowFunc().Sub(lostAt) >= m.maxStreamLossDur {
- m.setSessionStop(sess, "stream_timeout", recordErr)
- break
- }
- }
-
- m.markSessionDisconnected(sess, m.nowFunc())
- select {
- case <-ctx.Done():
- case <-time.After(m.reconnectWait):
- }
- if ctx.Err() != nil {
- break
- }
- if provider == nil {
- m.setSessionStop(sess, "ended", nil)
- break
- }
-
- // Never reuse an expired/disconnected FLV URL; check room state and re-select stream.
- liveSt, statusErr := provider.CheckLiveStatus(ctx, sess.accountUID, sess.webRID)
- if statusErr == nil {
- if liveSt.Status != site.LiveStateLive || (liveSt.RoomID != "" && liveSt.RoomID != sess.roomIDStr) {
- m.setSessionStop(sess, "ended", nil)
- break
- }
- if liveSt.WebRID != "" {
- sess.webRID = liveSt.WebRID
- }
- } else if reason := liveStopReason(statusErr); reason != "" {
- if rep, ok := provider.(LiveErrorReporter); ok {
- rep.ReportAutomaticError(ctx, statusErr)
- }
- if reason == "risk_control" || reason == "rate_limited" {
- m.recordSiteAutoStop(site.Douyin, reason)
- }
- m.setSessionStop(sess, reason, statusErr)
- break
- }
-
- freshPlan, selErr := provider.SelectLiveStream(ctx, sess.accountUID, firstNonEmpty(sess.webRID, sess.roomIDStr), codecOrder)
- if selErr != nil {
- var sErr *site.Error
- if errors.As(selErr, &sErr) && sErr.Kind == site.ErrKindUnavailable && !sErr.Unsupported {
- // Room went offline right between CheckLiveStatus and SelectLiveStream.
- if st2, sErr2 := provider.CheckLiveStatus(ctx, sess.accountUID, sess.webRID); sErr2 == nil && st2.Status != site.LiveStateLive {
- m.setSessionStop(sess, "ended", nil)
- break
- }
- }
- if reason := liveStopReason(selErr); reason != "" {
- if rep, ok := provider.(LiveErrorReporter); ok {
- rep.ReportAutomaticError(ctx, selErr)
- }
- if reason == "risk_control" || reason == "rate_limited" {
- m.recordSiteAutoStop(site.Douyin, reason)
- }
- m.setSessionStop(sess, reason, selErr)
- break
- }
- if lostAt.IsZero() {
- lostAt = m.nowFunc()
- }
- if m.maxStreamLossDur > 0 && m.nowFunc().Sub(lostAt) >= m.maxStreamLossDur {
- m.setSessionStop(sess, "stream_timeout", selErr)
- break
- }
- continue
- }
- if freshPlan.Status == site.LiveStateAudioOnly || (freshPlan.Transport != "" && freshPlan.Transport != site.LiveTransportHTTPFLV) || strings.EqualFold(freshPlan.Format, "ts") {
- m.setSessionStop(sess, site.ErrKindBlocked, &site.Error{
- Site: site.Douyin,
- Kind: site.ErrKindBlocked,
- Message: "直播间已切换为不支持录制的流格式",
- })
- break
- }
- if freshPlan.Status != site.LiveStateLive || len(freshPlan.URLs) == 0 || (freshPlan.RoomID != "" && freshPlan.RoomID != sess.roomIDStr) {
- m.setSessionStop(sess, "ended", nil)
- break
- }
- if len(freshPlan.Media.AllowedDomains) == 0 {
- freshPlan.Media = sess.transport
- }
- if freshPlan.BitrateBps > 0 {
- m.setSessionNominalBitrateBps(sess, freshPlan.BitrateBps)
- }
- plan = freshPlan
- }
-
- sess.waitPartsFinished()
- m.closeSessionSlowIncident(sess, m.nowFunc())
- m.mu.Lock()
- if sess.stopReason == "" {
- if ctx.Err() != nil {
- sess.stopReason = "app_closed"
- } else {
- sess.stopReason = "ended"
- }
- }
- reason := sess.stopReason
- state := m.douyinStates[sess.stateKey]
- state.Recording = false
- state.StopReason = reason
- state.LastError = sess.lastErr
- state.RecordDurationSec = m.nowFunc().Sub(sess.startedAt).Seconds()
- state.RecordBytes = sess.bytesTotal
- state.RecordSegments = len(sess.segments)
- state.Incidents = cloneIncidents(sess.incidents)
- hydrateSessionPreviewFieldsLocked(&state, nil)
- if reason == "ended" {
- state.LiveStatus = 0
- state.LiveState = site.LiveStateOffline
- state.StatusText = "未开播"
- }
- m.douyinStates[sess.stateKey] = state
- m.mu.Unlock()
-
- sess.itemMeta.Live.StopReason = reason
- sess.itemMeta.Live.EndedAt = m.nowFunc().UTC().Format(time.RFC3339)
- sess.itemMeta.Live.EndTitle = state.Title
- sess.itemMeta.Status = "complete"
- if len(sess.itemMeta.Live.Segments) == 0 {
- sess.itemMeta.Status = "failed"
- }
- if reason != "ended" && reason != "user_stop" && reason != "app_closed" {
- addLiveMissing(&sess.itemMeta, "recording", "录制提前结束 ("+reason+")")
- }
- if len(sess.itemMeta.PendingParts) > 0 || len(sess.itemMeta.Missing) > 0 {
- sess.itemMeta.Status = "partial"
- }
- if err := m.saveSession(sess); err != nil {
- m.setSessionStop(sess, "storage", err)
- state.StopReason, state.LastError = "storage", "录像清单写入失败,已保留可恢复文件"
- m.mu.Lock()
- m.douyinStates[sess.stateKey] = state
- m.mu.Unlock()
- }
- if m.onState != nil {
- m.onState(state)
- }
-}
-
-type activeFLVConn struct {
- body io.ReadCloser
- remuxer *FLVRemuxer
-}
-
-func (c *activeFLVConn) Close() error {
- if c == nil || c.body == nil {
- return nil
- }
- err := c.body.Close()
- c.body = nil
- return err
-}
-
-func (m *Manager) recordBilibiliFLVPart(
- ctx context.Context,
- sess *recordSession,
- urls []string,
- connPtr **activeFLVConn,
- partPath string,
-) (int64, error) {
- allowLocal := false
- if m.client != nil {
- allowLocal = m.client.ValidateMediaURL("http://127.0.0.1:1/test.flv") == nil
- }
- spec := site.BilibiliMediaTransport(allowLocal)
- spec.Referer = "https://live.bilibili.com/"
- spec.Origin = "https://live.bilibili.com"
- return m.recordFLVPartWithTransport(ctx, sess, spec, urls, connPtr, partPath)
-}
-
-func (m *Manager) recordFLVPartWithTransport(
- ctx context.Context,
- sess *recordSession,
- transport site.MediaTransportSpec,
- urls []string,
- connPtr **activeFLVConn,
- partPath string,
-) (written int64, result error) {
- partBase := filepath.Base(partPath)
- if *connPtr == nil {
- m.mu.Lock()
- idleDur := m.flvIdleTimeout
- m.mu.Unlock()
- body, err := OpenHTTPFLVStream(ctx, transport, urls, idleDur)
- if err != nil {
- return 0, err
- }
- m.markSessionReconnected(sess, m.nowFunc(), true, partBase)
- remuxer := NewFLVRemuxer(body, FLVRemuxOptions{})
- *connPtr = &activeFLVConn{
- body: body,
- remuxer: remuxer,
- }
- }
-
- f, err := os.OpenFile(partPath, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0o600)
- if err != nil {
- return 0, err
- }
- defer func() {
- if sErr := f.Sync(); sErr != nil && result == nil {
- result = sErr
- }
- if cErr := f.Close(); cErr != nil && result == nil {
- result = cErr
- }
- }()
-
- var prevBytes int64
- var prevDur float64
- prevCheckAt := m.nowFunc()
- cp, wErr := (*connPtr).remuxer.WritePart(ctx, f, func(cp FLVCheckpoint) error {
- if m.freeBytesFunc != nil && m.minFreeBytes > 0 {
- free, fErr := m.freeBytesFunc(sess.itemDir)
- if fErr != nil {
- return fErr
- }
- if free < m.minFreeBytes {
- return &site.Error{Site: transport.Site, Kind: site.ErrKindStorage, Message: "磁盘空间不足 1 GiB,已停止录制"}
- }
- }
- checkNow := m.nowFunc()
- delta := cp.BytesWritten - prevBytes
- deltaDur := cp.DurationSec - prevDur
- if delta > 0 {
- m.observeTransferSpeed(sess, prevCheckAt, checkNow, delta, deltaDur, partBase)
- prevBytes = cp.BytesWritten
- written = cp.BytesWritten
- m.addSessionBytes(sess, delta)
- }
- prevCheckAt = checkNow
- if cp.DurationSec > prevDur {
- prevDur = cp.DurationSec
- }
- sess.wroteMedia = true
- sess.segmentDuration = cp.DurationSec
- sess.lastSequence = cp.Sequence
- sess.hasSequence = true
- if cp.Codec != "" {
- sess.codec = cp.Codec
- }
- m.commitSessionPart(sess, cp.BytesWritten, cp.DurationSec)
- return m.saveCheckpoint(sess, func(meta *library.ItemMetadata) {
- if cp.Codec != "" {
- meta.Live.Codec = cp.Codec
- }
- meta.Live.LastSequence = cp.Sequence
- meta.Live.HasSequence = true
- meta.Live.PendingFile = partBase
- meta.Live.PendingBytes = cp.BytesWritten
- meta.Live.PendingDuration = cp.DurationSec
- })
- })
- if cp.BytesWritten > written {
- m.addSessionBytes(sess, cp.BytesWritten-written)
- written = cp.BytesWritten
- }
- return written, wErr
-}
-
-// OpenHTTPFLVStream opens an HTTP-FLV live stream over HTTPS (or localhost in tests),
-// enforcing a 10s connect/header timeout, per-read idle timeout, <=5 redirect hops (ValidateRedirectURL),
-// Referer/Origin headers with Cookie stripped, and rejecting HTML/JSON disguised responses.
-func OpenHTTPFLVStream(ctx context.Context, transport site.MediaTransportSpec, urls []string, idleTimeout time.Duration) (io.ReadCloser, error) {
- if idleTimeout <= 0 {
- idleTimeout = defaultFLVIdleTimeout
- }
- var cleanURLs []string
- var lastValidateErr error
- for _, u := range urls {
- u = strings.TrimSpace(u)
- if u == "" {
- continue
- }
- if err := transport.ValidateURL(u); err != nil {
- lastValidateErr = err
- continue
- }
- cleanURLs = append(cleanURLs, u)
- }
- if len(cleanURLs) == 0 {
- if lastValidateErr != nil {
- return nil, lastValidateErr
- }
- return nil, &site.Error{Site: transport.Site, Kind: site.ErrKindUnavailable, Message: "直播拉流地址列表为空"}
- }
-
- httpClient := newLiveTransportClient(transport, defaultFLVConnectTimeout)
- var lastErr error
- for _, targetURL := range cleanURLs {
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil)
- if err != nil {
- lastErr = err
- continue
- }
- transport.ApplyHeaders(req)
-
- resp, err := httpClient.Do(req)
- if err != nil {
- var se *site.Error
- if errors.As(err, &se) {
- lastErr = se
- if site.IsRoundStop(se) || se.Kind == site.ErrKindBlocked {
- return nil, se
- }
- continue
- }
- lastErr = &site.Error{Site: transport.Site, Kind: site.ErrKindNetwork, Message: "连接直播流节点失败", Err: err}
- continue
- }
-
- if resp.StatusCode != http.StatusOK {
- _ = resp.Body.Close()
- se := mapLiveHTTPStatus(transport.Site, resp.StatusCode)
- lastErr = se
- if site.IsRoundStop(se) {
- return nil, se
- }
- continue
- }
-
- ct := strings.TrimSpace(resp.Header.Get("Content-Type"))
- if badErr := checkLiveFLVContentType(transport.Site, ct); badErr != nil {
- _ = resp.Body.Close()
- return nil, badErr
- }
-
- return newFLVIdleReader(resp.Body, idleTimeout), nil
- }
- if lastErr != nil {
- return nil, lastErr
- }
- return nil, &site.Error{Site: transport.Site, Kind: site.ErrKindNetwork, Message: "无法连接任何直播流节点"}
-}
-
-func newLiveTransportClient(spec site.MediaTransportSpec, connectTimeout time.Duration) *http.Client {
- if connectTimeout <= 0 {
- connectTimeout = defaultFLVConnectTimeout
- }
- dialer := &net.Dialer{Timeout: connectTimeout, KeepAlive: 30 * time.Second}
- guard := site.NewGuardedMediaDialer(spec.Site, spec.AllowLocalhost, dialer, "已拦截内网或回环直播流节点地址")
- tr := &http.Transport{
- Proxy: guard.Proxy,
- MaxIdleConns: 8,
- IdleConnTimeout: 30 * time.Second,
- TLSHandshakeTimeout: connectTimeout,
- ResponseHeaderTimeout: connectTimeout,
- DialContext: guard.DialContext,
- }
- return &http.Client{
- Transport: tr,
- CheckRedirect: func(req *http.Request, via []*http.Request) error {
- if len(via) >= 5 {
- return &site.Error{
- Site: spec.Site,
- Kind: site.ErrKindBlocked,
- Message: "直播流重定向超过 5 跳上限",
- }
- }
- if err := spec.ValidateRedirectURL(req.URL.String()); err != nil {
- return err
- }
- spec.ApplyHeaders(req)
- return nil
- },
- }
-}
-
-func mapLiveHTTPStatus(siteID site.ID, status int) *site.Error {
- switch status {
- case http.StatusUnauthorized:
- return &site.Error{Site: siteID, Kind: site.ErrKindAuthRequired, HTTPStatus: status, Message: "直播拉流需要有效登录凭证 (401)"}
- case http.StatusPreconditionFailed:
- return &site.Error{Site: siteID, Kind: site.ErrKindRiskControl, HTTPStatus: status, Message: "直播请求触发风控 (412),已停止录制"}
- case http.StatusTooManyRequests:
- return &site.Error{Site: siteID, Kind: site.ErrKindRateLimited, HTTPStatus: status, Message: "直播请求触发频率限制 (429),已停止录制"}
- case http.StatusForbidden:
- return &site.Error{Site: siteID, Kind: site.ErrKindForbidden, HTTPStatus: status, Message: "直播流地址已过期或被拒绝 (403)"}
- case http.StatusNotFound, http.StatusGone:
- return &site.Error{Site: siteID, Kind: site.ErrKindUnavailable, HTTPStatus: status, Message: fmt.Sprintf("直播流节点不可用 (%d)", status)}
- default:
- return &site.Error{Site: siteID, Kind: site.ErrKindNetwork, HTTPStatus: status, Message: fmt.Sprintf("直播流 HTTP 状态异常 (%d)", status)}
- }
-}
-
-func checkLiveFLVContentType(siteID site.ID, rawCT string) error {
- if rawCT == "" {
- return nil
- }
- mt, _, err := mime.ParseMediaType(rawCT)
- if err != nil {
- mt = strings.ToLower(strings.TrimSpace(strings.SplitN(rawCT, ";", 2)[0]))
- }
- mt = strings.ToLower(strings.TrimSpace(mt))
- switch mt {
- case "text/html", "application/xhtml+xml", "application/json", "text/json", "text/plain", "application/vnd.apple.mpegurl", "application/x-mpegurl":
- return &site.Error{
- Site: siteID,
- Kind: site.ErrKindSchemaChanged,
- Message: fmt.Sprintf("直播流返回了非 FLV 响应类型 (%s)", mt),
- }
- }
- return nil
-}
-
-type flvIdleReader struct {
- r io.ReadCloser
- timeout time.Duration
-}
-
-func newFLVIdleReader(r io.ReadCloser, timeout time.Duration) io.ReadCloser {
- if timeout <= 0 {
- return r
- }
- return &flvIdleReader{r: r, timeout: timeout}
-}
-
-func (f *flvIdleReader) Read(p []byte) (int, error) {
- type res struct {
- n int
- err error
- }
- ch := make(chan res, 1)
- go func() {
- n, err := f.r.Read(p)
- ch <- res{n: n, err: err}
- }()
- timer := time.NewTimer(f.timeout)
- defer timer.Stop()
- select {
- case out := <-ch:
- return out.n, out.err
- case <-timer.C:
- _ = f.r.Close()
- return 0, &site.Error{Kind: site.ErrKindNetwork, Message: "直播流超过 15 秒无数据返回"}
- }
-}
-
-func (f *flvIdleReader) Close() error {
- return f.r.Close()
-}
-
-func (m *Manager) saveDouyinLiveCover(ctx context.Context, sess *recordSession, transport site.MediaTransportSpec) error {
- if strings.TrimSpace(sess.coverURL) == "" {
- return nil
- }
- for _, mf := range sess.itemMeta.Media {
- if mf.Role == "cover" && library.VerifyMediaFile(sess.itemDir, mf, true) {
- return nil
- }
- }
- vodSpec := site.DouyinVODTransport(transport.UserAgent, transport.AllowLocalhost)
- if err := vodSpec.ValidateURL(sess.coverURL); err != nil {
- return nil
- }
- client := newLiveTransportClient(vodSpec, defaultFLVConnectTimeout)
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, sess.coverURL, nil)
- if err != nil {
- return nil
- }
- vodSpec.ApplyHeaders(req)
- resp, err := client.Do(req)
- if err != nil {
- return nil
- }
- defer resp.Body.Close()
- if resp.StatusCode != http.StatusOK {
- return nil
- }
- raw, err := io.ReadAll(io.LimitReader(resp.Body, 16*1024*1024))
- if err != nil || len(raw) < 8 {
- return nil
- }
- ext := sniffLiveCoverExt(raw, resp.Header.Get("Content-Type"))
- if ext == "" {
- return nil
- }
- rel := "cover" + ext
- full, err := library.ResolveItemPath(sess.itemDir, rel)
- if err != nil {
- return nil
- }
- if err := storage.WriteFileAtomic(full, raw, 0o600); err != nil {
- return nil
- }
- sum := sha256.Sum256(raw)
- sess.itemMeta.Media = mergeLiveMedia(sess.itemMeta.Media, library.MediaFile{
- Role: "cover",
- Path: rel,
- Bytes: int64(len(raw)),
- SHA256: hex.EncodeToString(sum[:]),
- })
- _ = m.saveSession(sess)
- return nil
-}
-
-func sniffLiveCoverExt(b []byte, ct string) string {
- switch {
- case len(b) >= 3 && b[0] == 0xFF && b[1] == 0xD8 && b[2] == 0xFF:
- return ".jpg"
- case len(b) >= 8 && bytes.Equal(b[:8], []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1A, '\n'}):
- return ".png"
- case len(b) >= 12 && bytes.Equal(b[:4], []byte("RIFF")) && bytes.Equal(b[8:12], []byte("WEBP")):
- return ".webp"
- case len(b) >= 6 && (bytes.Equal(b[:6], []byte("GIF87a")) || bytes.Equal(b[:6], []byte("GIF89a"))):
- return ".gif"
- }
- mt, _, _ := mime.ParseMediaType(ct)
- switch strings.ToLower(strings.TrimSpace(mt)) {
- case "image/jpeg", "image/jpg":
- return ".jpg"
- case "image/png":
- return ".png"
- case "image/webp":
- return ".webp"
- }
- return ""
-}
-
-func sanitizeLiveURL(raw string) string {
- raw = strings.TrimSpace(raw)
- if raw == "" {
- return ""
- }
- u, err := url.Parse(raw)
- if err != nil || u.Scheme == "" || u.Host == "" {
- return ""
- }
- u.User = nil
- u.RawQuery = ""
- u.Fragment = ""
- return u.String()
-}
-
-func firstPositiveInt(a, b int) int {
- if a > 0 {
- return a
- }
- return b
-}
-
-// LiveCheckTimes returns when each account's live status was last fetched
-// by a check, keyed ":".
-func (m *Manager) LiveCheckTimes() map[string]time.Time {
- m.mu.Lock()
- defer m.mu.Unlock()
- out := make(map[string]time.Time, len(m.statusCache)+len(m.douyinLastAutoPoll))
- for uid, e := range m.statusCache {
- if !e.fetchedAt.IsZero() {
- out[string(site.Bilibili)+":"+strconv.FormatInt(uid, 10)] = e.fetchedAt
- }
- }
- for uid, at := range m.douyinLastAutoPoll {
- out[string(site.Douyin)+":"+uid] = at
- }
- return out
-}
-
-// LiveCheckEvery estimates how often an auto-record account of siteID has
-// its live status checked, n being that site's auto-record accounts:
-// Bilibili checks them all each round, Douyin within its budget.
-func (m *Manager) LiveCheckEvery(siteID site.ID, n int) time.Duration {
- if siteID == site.Douyin {
- return m.DouyinLiveCheckEvery(n)
- }
- m.mu.Lock()
- defer m.mu.Unlock()
- return time.Duration(max(m.liveSettings.PollIntervalSeconds, 60)) * time.Second
-}
diff --git a/internal/live/douyin_poll.go b/internal/live/douyin_poll.go
new file mode 100644
index 0000000..02f1ee7
--- /dev/null
+++ b/internal/live/douyin_poll.go
@@ -0,0 +1,293 @@
+package live
+
+import (
+ "context"
+ "math"
+ "sort"
+ "time"
+
+ "github.com/chialecode/trace/internal/site"
+ "github.com/chialecode/trace/internal/site/bilibili"
+ "github.com/chialecode/trace/internal/subscription"
+)
+
+// douyinLiveChecksPerRoundLocked is how many Douyin live requests one poll
+// round may make: as many as fit in the round at the live check gap.
+func (m *Manager) douyinLiveChecksPerRoundLocked() int {
+ sec := max(m.liveSettings.PollIntervalSeconds, 60)
+ if m.douyinLiveGap <= 0 {
+ return math.MaxInt32
+ }
+ return max(1, int(time.Duration(sec)*time.Second/m.douyinLiveGap))
+}
+
+// waitDouyinLiveGap waits the gap before a round's next live check; false
+// when ctx ends first.
+func (m *Manager) waitDouyinLiveGap(ctx context.Context) bool {
+ m.mu.Lock()
+ gap, wait := m.douyinLiveGap, m.douyinGapWait
+ m.mu.Unlock()
+ if gap <= 0 {
+ return ctx.Err() == nil
+ }
+ if wait != nil {
+ return wait(ctx, gap)
+ }
+ t := time.NewTimer(gap)
+ defer t.Stop()
+ select {
+ case <-ctx.Done():
+ return false
+ case <-t.C:
+ return true
+ }
+}
+
+// PollDouyinAutoRecordNow polls subscribed Douyin accounts with AutoRecord enabled,
+// enforcing >= 90s per-account interval, checking known active room_ids via CheckRoomsAlive
+// when supported, and auto-starting HTTP-FLV recording on live broadcasts.
+func (m *Manager) PollDouyinAutoRecordNow(ctx context.Context) ([]RoomState, error) {
+ return m.pollDouyinAutoRecord(ctx)
+}
+
+func (m *Manager) pollDouyinAutoRecord(ctx context.Context) ([]RoomState, error) {
+ provider, ok := m.getSiteProvider(site.Douyin)
+ if !ok || m.subs == nil {
+ return m.ListRooms(), nil
+ }
+ if !m.hasSiteAuth(site.Douyin) {
+ return m.ListRooms(), nil
+ }
+ subList, err := m.subs.List()
+ if err != nil {
+ return nil, err
+ }
+
+ type autoTarget struct {
+ sub subscription.Subscription
+ acc subscription.AccountRef
+ }
+ var targets []autoTarget
+ targetIdx := make(map[string]int)
+ for _, s := range subList {
+ if !s.Rules.AutoRecord && !s.LiveAutoRecord {
+ continue
+ }
+ for _, acc := range s.Accounts {
+ if acc.Site != string(site.Douyin) {
+ continue
+ }
+ normUID, nErr := site.NormalizeUID(site.Douyin, acc.UID)
+ if nErr != nil {
+ continue
+ }
+ acc.UID = normUID
+ if idx, exists := targetIdx[normUID]; exists {
+ // Multi-subscription OR-merge so LiveNotify/WebRID on later subscriptions aren't shadowed.
+ targets[idx].sub.LiveNotify = targets[idx].sub.LiveNotify || s.LiveNotify
+ targets[idx].sub.Name = firstNonEmpty(targets[idx].sub.Name, s.Name)
+ targets[idx].acc.WebRID = firstNonEmpty(targets[idx].acc.WebRID, acc.WebRID)
+ targets[idx].acc.Name = firstNonEmpty(targets[idx].acc.Name, acc.Name)
+ targets[idx].acc.Face = firstNonEmpty(targets[idx].acc.Face, acc.Face)
+ continue
+ }
+ targetIdx[normUID] = len(targets)
+ targets = append(targets, autoTarget{sub: s, acc: acc})
+ }
+ }
+ if len(targets) == 0 {
+ return m.ListRooms(), nil
+ }
+ // The accounts checked longest ago go first (never checked: first of
+ // all), so a round that cannot check them all goes round all of them.
+ m.mu.Lock()
+ sort.SliceStable(targets, func(i, j int) bool {
+ return m.douyinLastAutoPoll[targets[i].acc.UID].Before(m.douyinLastAutoPoll[targets[j].acc.UID])
+ })
+ requests := m.douyinLiveChecksPerRoundLocked()
+ m.mu.Unlock()
+ sent := 0 // live requests of this round, spaced by the live check gap
+
+ // Step 1: Check known active room_ids via CheckRoomsAlive (batch check_alive) when supported.
+ if aliveChecker, ok := provider.(LiveRoomAliveChecker); ok {
+ var knownRooms []string
+ roomToUID := make(map[string]string)
+ m.mu.Lock()
+ for _, t := range targets {
+ if rid := m.douyinRoomHints[t.acc.UID]; rid != "" && rid != "0" {
+ knownRooms = append(knownRooms, rid)
+ roomToUID[rid] = t.acc.UID
+ }
+ }
+ m.mu.Unlock()
+
+ // A round with a single request spends it on an account's status:
+ // the recordings notice an ended broadcast themselves.
+ if len(knownRooms) > 0 && requests >= 2 {
+ requests--
+ sent++
+ aliveMap, aErr := aliveChecker.CheckRoomsAlive(ctx, knownRooms)
+ if aErr != nil {
+ if site.IsRoundStop(aErr) {
+ if rep, rOK := provider.(LiveErrorReporter); rOK {
+ rep.ReportAutomaticError(ctx, aErr)
+ }
+ if site.IsCircuitBreak(aErr) {
+ m.recordSiteAutoStop(site.Douyin, site.KindOf(aErr))
+ }
+ return nil, aErr
+ }
+ } else {
+ now := m.now()
+ m.mu.Lock()
+ for _, rid := range knownRooms {
+ alive, present := aliveMap[rid]
+ if present && !alive {
+ uid := roomToUID[rid]
+ delete(m.douyinRoomHints, uid)
+ delete(m.douyinStoppedRooms, rid)
+ delete(m.douyinStatusCache, uid)
+ m.douyinPrevLive[uid] = site.LiveStateOffline
+ if sess := m.douyinSessions[rid]; sess != nil {
+ if sess.stopReason == "" {
+ sess.stopReason = "ended"
+ }
+ sess.cancel()
+ }
+ key := "douyin:live:" + rid
+ if st, has := m.douyinStates[key]; has {
+ st.LiveStatus = 0
+ st.LiveState = site.LiveStateOffline
+ st.StatusText = "未开播"
+ st.Recording = false
+ st.UpdatedAt = now.UTC().Format(time.RFC3339)
+ m.douyinStates[key] = st
+ }
+ }
+ }
+ m.mu.Unlock()
+ }
+ }
+ }
+
+ // Step 2: Poll each AutoRecord Douyin account whose last poll was >= douyinPollMinInterval ago.
+ m.mu.Lock()
+ minInterval := m.douyinPollMinInterval
+ notifyGlobal := m.liveSettings.NotifyOnStart
+ m.mu.Unlock()
+
+ var notifications []Notification
+ type startReq struct {
+ uid string
+ webRID string
+ }
+ var toStart []startReq
+
+ for _, t := range targets {
+ if ctx.Err() != nil {
+ break
+ }
+ uid := t.acc.UID
+ checkNow := m.now()
+
+ m.mu.Lock()
+ lastAt, hadLast := m.douyinLastAutoPoll[uid]
+ alreadyRec := m.isDouyinAccountRecordingLocked(uid)
+ webRIDHint := firstNonEmpty(m.douyinWebRIDHints[uid], t.acc.WebRID)
+ m.mu.Unlock()
+
+ if alreadyRec {
+ continue
+ }
+ if hadLast && minInterval > 0 && checkNow.Sub(lastAt) < minInterval {
+ continue
+ }
+ if requests <= 0 {
+ break
+ }
+ if sent > 0 && !m.waitDouyinLiveGap(ctx) {
+ break
+ }
+ requests--
+ sent++
+
+ // Capture timestamp after gap sleep so cache/poll timestamps reflect actual check time.
+ now := m.now()
+ m.mu.Lock()
+ m.douyinLastAutoPoll[uid] = now
+ m.mu.Unlock()
+
+ liveSt, cErr := provider.CheckLiveStatus(ctx, uid, webRIDHint)
+ if cErr != nil {
+ if site.IsRoundStop(cErr) {
+ if rep, rOK := provider.(LiveErrorReporter); rOK {
+ rep.ReportAutomaticError(ctx, cErr)
+ }
+ if site.IsCircuitBreak(cErr) {
+ m.recordSiteAutoStop(site.Douyin, site.KindOf(cErr))
+ }
+ return m.ListRooms(), cErr
+ }
+ continue
+ }
+ if liveSt.AccountUID == "" {
+ liveSt.AccountUID = uid
+ }
+ roomState := m.applyDouyinLiveStatus(liveSt, webRIDHint, t.acc, now)
+
+ m.mu.Lock()
+ prev := m.douyinPrevLive[uid]
+ m.douyinPrevLive[uid] = liveSt.Status
+ if liveSt.Status != site.LiveStateLive && liveSt.RoomID != "" {
+ delete(m.douyinStoppedRooms, liveSt.RoomID)
+ }
+ if liveSt.Status == site.LiveStateLive && prev != site.LiveStateLive && notifyGlobal && t.sub.LiveNotify {
+ notifications = append(notifications, Notification{
+ Site: string(site.Douyin),
+ AccountUID: uid,
+ RoomID: roomState.RoomID,
+ RoomIDStr: liveSt.RoomID,
+ WebRID: roomState.WebRID,
+ Uname: firstNonEmpty(roomState.Uname, t.sub.Name),
+ Title: roomState.Title,
+ StartedAt: now.UTC().Format(time.RFC3339),
+ })
+ }
+ shouldStart := m.douyinShouldAutoStartLocked(liveSt)
+ m.mu.Unlock()
+
+ if shouldStart {
+ toStart = append(toStart, startReq{uid: uid, webRID: firstNonEmpty(roomState.WebRID, liveSt.RoomID)})
+ }
+ }
+
+ for _, n := range notifications {
+ if m.onNotify != nil {
+ m.onNotify(n)
+ }
+ }
+ for _, req := range toStart {
+ if _, sErr := m.StartDouyinRecording(bilibili.WithAutomaticRequests(ctx, "live"), req.uid, req.webRID); sErr != nil {
+ m.mu.Lock()
+ for k, st := range m.douyinStates {
+ if st.AccountUID == req.uid {
+ st.LastError = sanitizeLiveError(sErr)
+ m.douyinStates[k] = st
+ }
+ }
+ m.mu.Unlock()
+ if isAutoStartBatchStopError(sErr) {
+ if site.IsRoundStop(sErr) {
+ if rep, rOK := provider.(LiveErrorReporter); rOK {
+ rep.ReportAutomaticError(ctx, sErr)
+ }
+ }
+ if site.IsCircuitBreak(sErr) {
+ m.recordSiteAutoStop(site.Douyin, site.KindOf(sErr))
+ }
+ break
+ }
+ }
+ }
+ return m.ListRooms(), nil
+}
diff --git a/internal/live/douyin_record.go b/internal/live/douyin_record.go
new file mode 100644
index 0000000..032bd3f
--- /dev/null
+++ b/internal/live/douyin_record.go
@@ -0,0 +1,564 @@
+package live
+
+import (
+ "context"
+ "errors"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/site"
+ "github.com/chialecode/trace/internal/site/bilibili"
+)
+
+// StartDouyinRecording starts an HTTP-FLV live recording into
+// /douyin//lives// with item key douyin:live:.
+func (m *Manager) StartDouyinRecording(ctx context.Context, uid, roomOrWebRID string) (RoomState, error) {
+ uid = strings.TrimSpace(uid)
+ target := strings.TrimSpace(roomOrWebRID)
+ if uid == "" && target == "" {
+ return RoomState{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindBadRequest, Message: "缺少抖音直播间号或主播标识"}
+ }
+
+ provider, ok := m.getSiteProvider(site.Douyin)
+ if !ok {
+ return RoomState{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindUnavailable, Message: "抖音直播服务未初始化"}
+ }
+
+ opCtx, cancelOp := m.withManagerContext(ctx)
+ defer cancelOp()
+
+ if uid == "" && target != "" {
+ m.mu.Lock()
+ if st, exists := m.douyinStates["douyin:live:"+target]; exists && st.AccountUID != "" {
+ uid = st.AccountUID
+ if st.WebRID != "" {
+ target = st.WebRID
+ }
+ } else {
+ for _, st := range m.douyinStates {
+ if st.WebRID == target || st.RoomIDStr == target {
+ uid = st.AccountUID
+ break
+ }
+ }
+ }
+ m.mu.Unlock()
+ }
+ if uid != "" {
+ if normUID, err := site.NormalizeUID(site.Douyin, uid); err == nil {
+ uid = normUID
+ }
+ if target == "" {
+ subAcc := m.findDouyinSubAccount(uid)
+ m.mu.Lock()
+ target = firstNonEmpty(m.douyinWebRIDHints[uid], firstNonEmpty(subAcc.WebRID, m.douyinRoomHints[uid]))
+ m.mu.Unlock()
+ }
+ }
+
+ startKey := "douyin:start:" + firstNonEmpty(uid, target)
+ releaseStart, err := m.acquireStartSlot(opCtx, site.Douyin, startKey)
+ if err != nil {
+ return RoomState{}, err
+ }
+ defer releaseStart()
+
+ m.mu.Lock()
+ codecOrder := append([]string(nil), m.liveSettings.CodecOrder...)
+ m.mu.Unlock()
+
+ cacheRoot := m.lib.CacheDir()
+ if err := m.checkStartDiskSpace(cacheRoot, site.Douyin); err != nil {
+ return RoomState{}, err
+ }
+
+ plan, err := provider.SelectLiveStream(opCtx, uid, target, codecOrder)
+ if err != nil {
+ return RoomState{}, err
+ }
+ if plan.Status == site.LiveStateAudioOnly {
+ return RoomState{}, &site.Error{
+ Site: site.Douyin,
+ Kind: site.ErrKindUnavailable,
+ Unsupported: true,
+ Message: "这个直播间是语音直播,暂不支持录制",
+ }
+ }
+ if plan.Status != site.LiveStateLive {
+ return RoomState{}, &site.Error{
+ Site: site.Douyin,
+ Kind: site.ErrKindUnavailable,
+ Message: "主播当前未开播,仅在直播中时支持录制",
+ }
+ }
+ if len(plan.URLs) == 0 || (plan.Transport != "" && plan.Transport != site.LiveTransportHTTPFLV) || strings.EqualFold(plan.Format, "ts") {
+ return RoomState{}, &site.Error{
+ Site: site.Douyin,
+ Kind: site.ErrKindUnavailable,
+ Unsupported: true,
+ Message: "这个直播间仅提供 HLS 流或缺少可录制的 HTTP-FLV 流,当前版本暂不支持录制",
+ }
+ }
+
+ roomID := strings.TrimSpace(plan.RoomID)
+ if roomID == "" || library.SanitizeFileName(roomID) != roomID {
+ return RoomState{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindSchemaChanged, Message: "抖音直播间缺少有效 room_id"}
+ }
+ secUID, err := site.NormalizeUID(site.Douyin, firstNonEmpty(plan.AccountUID, uid))
+ if err != nil {
+ return RoomState{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindSchemaChanged, Message: "抖音直播间缺少有效主播 sec_uid"}
+ }
+ plan.AccountUID = secUID
+
+ releaseRoom, err := m.acquireStartSlot(opCtx, site.Douyin, "douyin:room:"+roomID)
+ if err != nil {
+ return RoomState{}, err
+ }
+ defer releaseRoom()
+
+ m.mu.Lock()
+ if existingSess, already := m.douyinSessions[roomID]; already && existingSess != nil {
+ st := m.hydrateDouyinStateLocked(m.douyinStates[existingSess.stateKey])
+ m.mu.Unlock()
+ return st, nil
+ }
+ m.mu.Unlock()
+
+ subAcc := m.findDouyinSubAccount(secUID)
+ // Populate room display metadata from cache or CheckLiveStatus.
+ st, okCached := m.CachedAccountState(site.Douyin, secUID)
+ if !okCached || st.RoomIDStr != roomID || st.Title == "" {
+ forceFresh := !okCached || st.RoomIDStr != roomID
+ if freshSt, cErr := m.checkAccountLiveStatus(opCtx, site.Douyin, secUID, firstNonEmpty(plan.WebRID, target), forceFresh, false); cErr == nil {
+ st = freshSt
+ }
+ }
+
+ m.mu.Lock()
+ rawCover := firstNonEmpty(m.douyinRawCovers[secUID], st.Cover)
+ m.mu.Unlock()
+
+ now := m.now().UTC()
+ liveSince := st.LiveSince
+ if liveSince <= 0 {
+ liveSince = now.Unix()
+ }
+ webRID := firstNonEmpty(plan.WebRID, st.WebRID)
+ canonicalURL := "https://live.douyin.com/" + firstNonEmpty(webRID, roomID)
+
+ itemDir, err := library.EnsureWithinRoot(cacheRoot, filepath.Join(cacheRoot, "douyin", site.DouyinAuthorDir(secUID), "lives", roomID))
+ if err != nil {
+ return RoomState{}, err
+ }
+ itemKey := library.CanonicalItemKey("douyin", "live", roomID)
+ existingMeta, exists, err := m.lib.GetItem(itemKey)
+ if err != nil {
+ return RoomState{}, err
+ }
+ if exists && existingMeta.ItemDir != "" {
+ itemDir = existingMeta.ItemDir
+ }
+ if err := os.MkdirAll(itemDir, 0o700); err != nil {
+ return RoomState{}, err
+ }
+
+ parsedRoomInt, _ := strconv.ParseInt(roomID, 10, 64)
+ title := firstNonEmpty(st.Title, "抖音直播 "+firstNonEmpty(webRID, roomID))
+ uname := firstNonEmpty(st.Uname, subAcc.Name)
+ face := sanitizeLiveURL(firstNonEmpty(st.Face, subAcc.Face))
+
+ meta := library.ItemMetadata{
+ Version: 1,
+ ID: "live:" + roomID,
+ Site: "douyin",
+ Kind: "live",
+ Status: "recording",
+ Title: title,
+ URL: canonicalURL,
+ PubTs: liveSince,
+ CachedAt: now.Format(time.RFC3339),
+ Author: library.ItemAuthor{
+ Site: "douyin",
+ UID: secUID,
+ UniqueID: subAcc.UniqueID,
+ Name: uname,
+ Face: face,
+ },
+ }
+ if exists {
+ meta = existingMeta
+ meta.Status = "recording"
+ if title != "" {
+ meta.Title = title
+ }
+ meta.URL = canonicalURL
+ meta.Author.Site = "douyin"
+ meta.Author.UID = secUID
+ if uname != "" {
+ meta.Author.Name = uname
+ }
+ if face != "" {
+ meta.Author.Face = face
+ }
+ }
+ if meta.Live == nil {
+ meta.Live = &library.LiveRecordingInfo{
+ RoomID: parsedRoomInt,
+ RoomIDStr: roomID,
+ WebRID: webRID,
+ LiveSince: liveSince,
+ StartedAt: now.Format(time.RFC3339),
+ }
+ }
+ meta.Live.RoomID = parsedRoomInt
+ meta.Live.RoomIDStr = roomID
+ if webRID != "" {
+ meta.Live.WebRID = webRID
+ }
+ meta.Live.EndedAt, meta.Live.StopReason = "", ""
+ meta.Live.Quality = plan.Quality
+ meta.Live.QualityName = plan.QualityName
+ meta.Live.Codec = plan.Codec
+ meta.Live.Source = "manual"
+ if bilibili.AutomaticRequestSource(ctx) != "" {
+ meta.Live.Source = "auto"
+ }
+
+ savedMeta, err := m.lib.SaveItem(itemDir, meta)
+ if err != nil {
+ return RoomState{}, err
+ }
+
+ transport := plan.Media
+ if len(transport.AllowedDomains) == 0 {
+ transport = site.DouyinLiveTransport("", false)
+ }
+
+ recParent := context.Background()
+ if meta.Live.Source == "auto" {
+ recParent = bilibili.WithAutomaticRequests(recParent, "live")
+ }
+ recCtx, recCancel := context.WithCancel(recParent)
+ stateKey := "douyin:live:" + roomID
+ sess := &recordSession{
+ siteID: string(site.Douyin),
+ accountUID: secUID,
+ roomIDStr: roomID,
+ webRID: webRID,
+ stateKey: stateKey,
+ coverURL: rawCover,
+ transport: transport,
+ sessionID: roomID,
+ roomID: parsedRoomInt,
+ uname: uname,
+ face: face,
+ title: title,
+ itemDir: itemDir,
+ itemMeta: savedMeta,
+ cancel: recCancel,
+ doneCh: make(chan struct{}),
+ startedAt: now,
+ reportAt: now,
+ nextPart: nextPartNumber(savedMeta),
+ lastSequence: savedMeta.Live.LastSequence,
+ hasSequence: savedMeta.Live.HasSequence,
+ quality: plan.Quality,
+ qualityName: plan.QualityName,
+ codec: plan.Codec,
+ streamTransport: string(site.LiveTransportHTTPFLV),
+ previewSupport: true,
+ previewReason: previewReasonWaitingFirstFragment,
+ }
+ m.initSessionIncidents(sess)
+ if plan.BitrateBps > 0 {
+ sess.nominalByteRate = float64(plan.BitrateBps) / 8.0
+ }
+ for _, media := range savedMeta.Media {
+ if media.Role == "live_segment" {
+ sess.segments = append(sess.segments, media.Path)
+ sess.bytesTotal += media.Bytes
+ }
+ }
+
+ outState := RoomState{
+ Site: string(site.Douyin),
+ AccountUID: secUID,
+ UniqueID: subAcc.UniqueID,
+ RoomID: parsedRoomInt,
+ RoomIDStr: roomID,
+ WebRID: webRID,
+ RoomKey: stateKey,
+ LiveState: site.LiveStateLive,
+ Uname: uname,
+ Face: face,
+ Title: title,
+ Cover: sanitizeLiveURL(rawCover),
+ AreaName: st.AreaName,
+ LiveStatus: 1,
+ LiveSince: liveSince,
+ Source: meta.Live.Source,
+ StatusText: "直播中",
+ Quality: plan.Quality,
+ QualityName: plan.QualityName,
+ Codec: plan.Codec,
+ Transport: string(site.LiveTransportHTTPFLV),
+ Recording: true,
+ RecordSession: roomID,
+ RecordBytes: sess.bytesTotal,
+ RecordSegments: len(sess.segments),
+ RecordItemDir: itemDir,
+ PreviewSupported: true,
+ PreviewReason: previewReasonWaitingFirstFragment,
+ Incidents: cloneIncidents(sess.incidents),
+ UpdatedAt: now.Format(time.RFC3339),
+ }
+
+ m.mu.Lock()
+ if m.stopping {
+ m.mu.Unlock()
+ recCancel()
+ return RoomState{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindUnavailable, Message: "应用正在退出,不能开始新的录制"}
+ }
+ if existingSess, already := m.douyinSessions[roomID]; already && existingSess != nil {
+ cur := m.hydrateDouyinStateLocked(m.douyinStates[existingSess.stateKey])
+ m.mu.Unlock()
+ recCancel()
+ return cur, nil
+ }
+ delete(m.douyinStoppedRooms, roomID)
+ m.douyinSessions[roomID] = sess
+ m.douyinStates[stateKey] = outState
+ for k, old := range m.douyinStates {
+ if k != stateKey && old.AccountUID == secUID && !m.isRoomActivelyRecordingLocked(old.RoomIDStr) {
+ delete(m.douyinStates, k)
+ }
+ }
+ m.wg.Add(1)
+ m.mu.Unlock()
+
+ go m.runDouyinRecordingSession(recCtx, sess, plan, codecOrder)
+
+ if m.onState != nil {
+ m.onState(outState)
+ }
+ return outState, nil
+}
+
+// StopDouyinRecording stops an active Douyin live recording by room_id, web_rid, or sec_uid,
+// suppressing auto-restart for the remainder of that room_id broadcast.
+func (m *Manager) StopDouyinRecording(roomOrUID string) (RoomState, error) {
+ target := strings.TrimSpace(roomOrUID)
+ if target == "" {
+ return RoomState{Site: string(site.Douyin)}, &site.Error{
+ Site: site.Douyin,
+ Kind: site.ErrKindBadRequest,
+ Message: "缺少抖音直播间号或主播标识",
+ }
+ }
+ m.mu.Lock()
+ var sess *recordSession
+ var roomID string
+ if s, ok := m.douyinSessions[target]; ok {
+ sess = s
+ roomID = target
+ } else {
+ for rid, s := range m.douyinSessions {
+ if s == nil {
+ continue
+ }
+ if s.accountUID == target || (s.webRID != "" && s.webRID == target) || s.stateKey == target {
+ sess = s
+ roomID = rid
+ break
+ }
+ }
+ }
+ if roomID != "" {
+ m.douyinStoppedRooms[roomID] = true
+ }
+ if sess != nil && sess.stopReason == "" {
+ sess.stopReason = "user_stop"
+ }
+ timeout := m.finalizeTimeout
+ m.mu.Unlock()
+
+ if sess == nil {
+ m.mu.Lock()
+ for _, st := range m.douyinStates {
+ if st.RoomIDStr == target || st.AccountUID == target || (st.WebRID != "" && st.WebRID == target) || st.RoomKey == target {
+ st.Recording = false
+ hydrateSessionPreviewFieldsLocked(&st, nil)
+ m.mu.Unlock()
+ return st, nil
+ }
+ }
+ m.mu.Unlock()
+ return RoomState{Site: string(site.Douyin)}, nil
+ }
+
+ if timeout <= 0 {
+ timeout = 30 * time.Second
+ }
+ sess.cancel()
+ timer := time.NewTimer(timeout)
+ defer timer.Stop()
+ select {
+ case <-sess.doneCh:
+ case <-timer.C:
+ m.mu.Lock()
+ state := m.douyinStates[sess.stateKey]
+ m.mu.Unlock()
+ return state, &site.Error{Site: site.Douyin, Kind: site.ErrKindStorage, Message: "录制收尾已到时间上限,临时片段会在下次启动时恢复"}
+ }
+
+ // runSessionLoop already wrote the finalized RoomState (including any
+ // manifest-save LastError) and emitted onState before closing sess.doneCh.
+ m.mu.Lock()
+ st := m.douyinStates[sess.stateKey]
+ m.mu.Unlock()
+ return st, nil
+}
+
+func (m *Manager) runDouyinRecordingSession(ctx context.Context, sess *recordSession, initial site.LiveStreamPlan, codecOrder []string) {
+ plan := initial
+ if len(plan.Media.AllowedDomains) == 0 {
+ plan.Media = sess.transport
+ }
+ provider, _ := m.getSiteProvider(site.Douyin)
+
+ m.runSessionLoop(ctx, sess, sessionDriver{
+ siteID: site.Douyin,
+ unregister: func() {
+ m.mu.Lock()
+ delete(m.douyinSessions, sess.roomIDStr)
+ m.mu.Unlock()
+ },
+ saveCover: func(ctx context.Context) error {
+ return m.saveDouyinLiveCover(ctx, sess, plan.Media)
+ },
+ currentMeta: func() partStreamMeta {
+ return partStreamMeta{
+ codec: plan.Codec,
+ quality: plan.Quality,
+ qualityName: plan.QualityName,
+ }
+ },
+ updateStateMeta: func(pm partStreamMeta) {
+ if st, ok := m.douyinStates[sess.stateKey]; ok {
+ st.Codec, st.Quality, st.QualityName = pm.codec, pm.quality, pm.qualityName
+ m.douyinStates[sess.stateKey] = st
+ }
+ },
+ recordPart: func(ctx context.Context, flvConn **activeFLVConn, partPath string) (int64, error) {
+ m.beginSessionPart(sess, sess.nextPart, partPath, string(site.LiveTransportHTTPFLV))
+ return m.recordFLVPartWithTransport(ctx, sess, plan.Media, plan.URLs, flvConn, partPath)
+ },
+ reportStopError: func(ctx context.Context, err error, reason string) {
+ if rep, ok := provider.(LiveErrorReporter); ok {
+ leave := sess.enterExternal()
+ rep.ReportAutomaticError(ctx, err)
+ leave()
+ }
+ if reason == site.ErrKindRiskControl || reason == site.ErrKindRateLimited {
+ m.recordSiteAutoStop(site.Douyin, reason)
+ }
+ },
+ reconnect: func(ctx context.Context) (reconnectOutcome, error) {
+ if provider == nil {
+ return reconnectEnded, nil
+ }
+ m.mu.Lock()
+ curWebRID := sess.webRID
+ m.mu.Unlock()
+
+ // Never reuse an expired/disconnected FLV URL; check room state and re-select stream.
+ leave := sess.enterExternal()
+ liveSt, statusErr := provider.CheckLiveStatus(ctx, sess.accountUID, curWebRID)
+ leave()
+ if statusErr == nil {
+ if liveSt.Status != site.LiveStateLive || (liveSt.RoomID != "" && liveSt.RoomID != sess.roomIDStr) {
+ return reconnectEnded, nil
+ }
+ if liveSt.WebRID != "" {
+ m.mu.Lock()
+ sess.webRID = liveSt.WebRID
+ curWebRID = liveSt.WebRID
+ m.mu.Unlock()
+ }
+ } else if liveStopReason(statusErr) != "" {
+ return reconnectStop, statusErr
+ }
+
+ leave = sess.enterExternal()
+ freshPlan, selErr := provider.SelectLiveStream(ctx, sess.accountUID, firstNonEmpty(curWebRID, sess.roomIDStr), codecOrder)
+ leave()
+ if selErr != nil {
+ var sErr *site.Error
+ if errors.As(selErr, &sErr) && sErr.Kind == site.ErrKindUnavailable && !sErr.Unsupported {
+ // Room went offline right between CheckLiveStatus and SelectLiveStream.
+ leave = sess.enterExternal()
+ st2, sErr2 := provider.CheckLiveStatus(ctx, sess.accountUID, curWebRID)
+ leave()
+ if sErr2 == nil && st2.Status != site.LiveStateLive {
+ return reconnectEnded, nil
+ }
+ }
+ if liveStopReason(selErr) != "" {
+ return reconnectStop, selErr
+ }
+ return reconnectRetry, selErr
+ }
+ if freshPlan.Status == site.LiveStateAudioOnly || (freshPlan.Transport != "" && freshPlan.Transport != site.LiveTransportHTTPFLV) || strings.EqualFold(freshPlan.Format, "ts") {
+ return reconnectStop, &site.Error{
+ Site: site.Douyin,
+ Kind: site.ErrKindBlocked,
+ Message: "直播间已切换为不支持录制的流格式",
+ }
+ }
+ if freshPlan.Status != site.LiveStateLive || len(freshPlan.URLs) == 0 || (freshPlan.RoomID != "" && freshPlan.RoomID != sess.roomIDStr) {
+ return reconnectEnded, nil
+ }
+ if len(freshPlan.Media.AllowedDomains) == 0 {
+ freshPlan.Media = sess.transport
+ }
+ if freshPlan.BitrateBps > 0 {
+ m.setSessionNominalBitrateBps(sess, freshPlan.BitrateBps)
+ }
+ plan = freshPlan
+ return reconnectOK, nil
+ },
+ finalizeState: func(reason string, now time.Time) RoomState {
+ state := m.douyinStates[sess.stateKey]
+ state.Recording = false
+ state.StopReason = reason
+ state.LastError = sess.lastErr
+ state.RecordDurationSec = now.Sub(sess.startedAt).Seconds()
+ state.RecordBytes = sess.bytesTotal
+ state.RecordSegments = len(sess.segments)
+ state.RecordItemDir = sess.itemDir
+ state.Incidents = cloneIncidents(sess.incidents)
+ hydrateSessionPreviewFieldsLocked(&state, nil)
+ if reason == "ended" {
+ state.LiveStatus = 0
+ state.LiveState = site.LiveStateOffline
+ state.StatusText = "未开播"
+ if sess.accountUID != "" {
+ delete(m.douyinStatusCache, sess.accountUID)
+ if m.douyinRoomHints[sess.accountUID] == sess.roomIDStr {
+ delete(m.douyinRoomHints, sess.accountUID)
+ }
+ m.douyinPrevLive[sess.accountUID] = site.LiveStateOffline
+ }
+ }
+ m.douyinStates[sess.stateKey] = state
+ return state
+ },
+ saveStateLocked: func(state RoomState) {
+ m.douyinStates[sess.stateKey] = state
+ },
+ })
+}
diff --git a/internal/live/douyin_status.go b/internal/live/douyin_status.go
new file mode 100644
index 0000000..489c18a
--- /dev/null
+++ b/internal/live/douyin_status.go
@@ -0,0 +1,715 @@
+package live
+
+import (
+ "context"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/chialecode/trace/internal/site"
+ "github.com/chialecode/trace/internal/subscription"
+)
+
+type douyinCachedStatusEntry struct {
+ status site.LiveStatus
+ state RoomState
+ fetchedAt time.Time
+}
+
+// ObserveAccountLiveHint records a live web_rid or room_id hint discovered passively
+// (e.g. from Douyin aweme/post page 1) with zero extra network requests.
+func (m *Manager) ObserveAccountLiveHint(siteID site.ID, uid, webRID, roomID string) {
+ if siteID != site.Douyin {
+ return
+ }
+ normUID, err := site.NormalizeUID(site.Douyin, uid)
+ if err != nil {
+ return
+ }
+ webRID = strings.TrimSpace(webRID)
+ roomID = strings.TrimSpace(roomID)
+
+ subAcc := m.findDouyinSubAccount(normUID)
+ var syncNeeded bool
+ var notify *RoomState
+ nowStr := m.now().UTC().Format(time.RFC3339)
+ m.mu.Lock()
+ if webRID != "" && m.douyinWebRIDHints[normUID] != webRID {
+ m.douyinWebRIDHints[normUID] = webRID
+ syncNeeded = true
+ }
+ if roomID != "" && roomID != "0" {
+ m.douyinRoomHints[normUID] = roomID
+ effWebRID := firstNonEmpty(webRID, firstNonEmpty(m.douyinWebRIDHints[normUID], subAcc.WebRID))
+ stateKey := douyinStateKey(roomID, normUID, effWebRID)
+ prev, exists := m.douyinStates[stateKey]
+ if !exists {
+ if old, ok := m.findPrevDouyinStateLocked(normUID); ok {
+ prev.RecordItemDir = old.RecordItemDir
+ prev.Incidents = cloneIncidents(old.Incidents)
+ prev.StopReason = old.StopReason
+ prev.LastError = old.LastError
+ prev.Quality = old.Quality
+ prev.QualityName = old.QualityName
+ prev.Codec = old.Codec
+ }
+ }
+ roomInt, _ := strconv.ParseInt(roomID, 10, 64)
+ prev.Site = string(site.Douyin)
+ prev.AccountUID = normUID
+ prev.UniqueID = firstNonEmpty(prev.UniqueID, subAcc.UniqueID)
+ prev.RoomID = roomInt
+ prev.RoomIDStr = roomID
+ prev.WebRID = firstNonEmpty(effWebRID, prev.WebRID)
+ prev.RoomKey = "douyin:live:" + roomID
+ prev.LiveState = site.LiveStateLive
+ prev.LiveStatus = 1
+ prev.StatusText = "直播中"
+ prev.Uname = firstNonEmpty(prev.Uname, subAcc.Name)
+ prev.Face = sanitizeLiveURL(firstNonEmpty(prev.Face, subAcc.Face))
+ prev.UpdatedAt = nowStr
+ hydrated := m.hydrateDouyinStateLocked(prev)
+ m.douyinStates[stateKey] = hydrated
+ for k, old := range m.douyinStates {
+ if k != stateKey && old.AccountUID == normUID && !m.isRoomActivelyRecordingLocked(old.RoomIDStr) {
+ delete(m.douyinStates, k)
+ }
+ }
+ delete(m.douyinStatusCache, normUID)
+ cp := hydrated
+ notify = &cp
+ }
+ start := roomID != "" && roomID != "0" && m.douyinShouldAutoStartLocked(site.LiveStatus{Status: site.LiveStateLive, RoomID: roomID})
+ m.mu.Unlock()
+
+ if syncNeeded {
+ m.syncWebRID(site.Douyin, normUID, webRID, false)
+ }
+ if notify != nil && m.onState != nil {
+ m.onState(*notify)
+ }
+ // An update check that sees the account live starts its recording when
+ // a subscription records its broadcasts, before the account's turn for
+ // a live check. Starting asks for the stream, which confirms the broadcast;
+ // a hint gone stale just starts nothing.
+ if start && m.douyinAccountAutoRecords(normUID) {
+ target := firstNonEmpty(webRID, roomID)
+ m.mu.Lock()
+ if !m.stopping && m.douyinShouldAutoStartLocked(site.LiveStatus{Status: site.LiveStateLive, RoomID: roomID}) {
+ baseCtx := m.baseCtxLocked()
+ m.wg.Add(1)
+ m.mu.Unlock()
+ go func() {
+ defer m.wg.Done()
+ _, _ = m.StartDouyinRecording(site.WithAutomaticRequests(baseCtx, "live"), normUID, target)
+ }()
+ return
+ }
+ m.mu.Unlock()
+ }
+}
+
+// CachedAccountState returns the most recently observed live RoomState for (siteID, uid)
+// from memory without issuing any network requests (used by subscription grid & sidebar).
+func (m *Manager) CachedAccountState(siteID site.ID, uid string) (RoomState, bool) {
+ normUID, err := site.NormalizeUID(siteID, uid)
+ if err != nil {
+ return RoomState{}, false
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ switch siteID {
+ case site.Bilibili:
+ mid, _ := strconv.ParseInt(normUID, 10, 64)
+ if mid <= 0 {
+ return RoomState{}, false
+ }
+ for _, st := range m.states {
+ if st.UID == mid {
+ m.normalizeBilibiliRoomStateLocked(&st)
+ st.AccountUID = normUID
+ if sess := m.sessions[st.RoomID]; sess != nil {
+ m.hydrateBilibiliStateFromSessionLocked(&st, sess)
+ } else {
+ st.Recording = false
+ hydrateSessionPreviewFieldsLocked(&st, nil)
+ }
+ return st, true
+ }
+ }
+ return RoomState{}, false
+
+ case site.Douyin:
+ return m.cachedDouyinStateLocked(normUID)
+ }
+ return RoomState{}, false
+}
+
+// cachedDouyinStateLocked resolves the single source of truth (m.douyinStates)
+// for normUID without ever returning stale douyinStatusCache snapshots.
+func (m *Manager) cachedDouyinStateLocked(normUID string) (RoomState, bool) {
+ for _, sess := range m.douyinSessions {
+ if sess != nil && sess.accountUID == normUID {
+ if st, ok := m.douyinStates[sess.stateKey]; ok {
+ return m.hydrateDouyinStateLocked(st), true
+ }
+ }
+ }
+ if rid := m.douyinRoomHints[normUID]; rid != "" {
+ if st, ok := m.douyinStates["douyin:live:"+rid]; ok {
+ return m.hydrateDouyinStateLocked(st), true
+ }
+ }
+ var best RoomState
+ var found bool
+ for _, st := range m.douyinStates {
+ if st.AccountUID != normUID {
+ continue
+ }
+ if !found || st.UpdatedAt > best.UpdatedAt {
+ best = st
+ found = true
+ }
+ }
+ if found {
+ return m.hydrateDouyinStateLocked(best), true
+ }
+ return RoomState{}, false
+}
+
+func (m *Manager) findPrevDouyinStateLocked(secUID string) (RoomState, bool) {
+ if secUID == "" {
+ return RoomState{}, false
+ }
+ var best RoomState
+ var found bool
+ for _, old := range m.douyinStates {
+ if old.AccountUID != secUID {
+ continue
+ }
+ oldHasMeta := old.RecordItemDir != "" || len(old.Incidents) > 0 || old.StopReason != "" || old.LastError != ""
+ bestHasMeta := best.RecordItemDir != "" || len(best.Incidents) > 0 || best.StopReason != "" || best.LastError != ""
+ if !found || (oldHasMeta && !bestHasMeta) || (oldHasMeta == bestHasMeta && old.UpdatedAt > best.UpdatedAt) {
+ best = old
+ found = true
+ }
+ }
+ return best, found
+}
+
+// CachedStatesByAccountKeys returns in-memory cached live states keyed by ":" with 0 network requests.
+func (m *Manager) CachedStatesByAccountKeys(accountKeys []string) map[string]RoomState {
+ out := make(map[string]RoomState, len(accountKeys))
+ for _, key := range accountKeys {
+ siteID, uid, err := site.ParseAccountKey(strings.TrimSpace(key))
+ if err != nil {
+ continue
+ }
+ if st, ok := m.CachedAccountState(siteID, uid); ok {
+ out[site.AccountKey(siteID, uid)] = st
+ }
+ }
+ return out
+}
+
+// StatusByAccountKeys queries live status across mixed Bilibili and Douyin ":" keys,
+// using <=50 UID batching for Bilibili and the 60s single-account cache for Douyin.
+func (m *Manager) StatusByAccountKeys(ctx context.Context, accountKeys []string) (map[string]RoomState, error) {
+ out := make(map[string]RoomState, len(accountKeys))
+ var biliMids []int64
+ var douyinUIDs []string
+ seen := make(map[string]bool, len(accountKeys))
+
+ for _, rawKey := range accountKeys {
+ siteID, uid, err := site.ParseAccountKey(strings.TrimSpace(rawKey))
+ if err != nil {
+ continue
+ }
+ canon := site.AccountKey(siteID, uid)
+ if seen[canon] {
+ continue
+ }
+ seen[canon] = true
+ switch siteID {
+ case site.Bilibili:
+ if mid, pErr := strconv.ParseInt(uid, 10, 64); pErr == nil && mid > 0 {
+ biliMids = append(biliMids, mid)
+ }
+ case site.Douyin:
+ douyinUIDs = append(douyinUIDs, uid)
+ }
+ }
+
+ var firstErr error
+ if len(biliMids) > 0 && m.client != nil && m.client.HasAuth() {
+ if _, err := m.RefreshForAccounts(ctx, biliMids); err != nil {
+ firstErr = err
+ } else {
+ for _, mid := range biliMids {
+ uidStr := strconv.FormatInt(mid, 10)
+ if st, ok := m.CachedAccountState(site.Bilibili, uidStr); ok {
+ out[site.AccountKey(site.Bilibili, uidStr)] = st
+ }
+ }
+ }
+ }
+
+ for _, secUID := range douyinUIDs {
+ st, err := m.CheckAccountLiveStatus(ctx, site.Douyin, secUID, "", false)
+ if err != nil {
+ if firstErr == nil {
+ firstErr = err
+ }
+ continue
+ }
+ out[site.AccountKey(site.Douyin, secUID)] = st
+ }
+ return out, firstErr
+}
+
+// CheckAccountLiveStatus queries live status for one creator account using a 60s TTL cache
+// (unless force is true) and synchronizes any backfilled/invalidated Douyin web_rid.
+// A Douyin broadcast it finds for an account that records automatically
+// starts recording.
+func (m *Manager) CheckAccountLiveStatus(ctx context.Context, siteID site.ID, uid, webRIDHint string, force bool) (RoomState, error) {
+ return m.checkAccountLiveStatus(ctx, siteID, uid, webRIDHint, force, true)
+}
+
+// checkAccountLiveStatus is CheckAccountLiveStatus; autoStart=false only reads
+// the status (used by StartDouyinRecording so reading room metadata never
+// re-enters recording start).
+func (m *Manager) checkAccountLiveStatus(ctx context.Context, siteID site.ID, uid, webRIDHint string, force, autoStart bool) (RoomState, error) {
+ switch siteID {
+ case site.Bilibili:
+ normUID, err := site.NormalizeUID(site.Bilibili, uid)
+ if err != nil {
+ return RoomState{}, &site.Error{Site: site.Bilibili, Kind: site.ErrKindBadRequest, Message: "无效的哔哩哔哩 UID"}
+ }
+ mid, _ := strconv.ParseInt(normUID, 10, 64)
+ if _, err := m.refreshAccounts(ctx, []int64{mid}, true, force, autoStart); err != nil {
+ return RoomState{}, err
+ }
+ st, _ := m.CachedAccountState(site.Bilibili, normUID)
+ return st, nil
+
+ case site.Douyin:
+ normUID, err := site.NormalizeUID(site.Douyin, uid)
+ if err != nil {
+ return RoomState{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindBadRequest, Message: "无效的抖音主播 sec_uid"}
+ }
+ provider, ok := m.getSiteProvider(site.Douyin)
+ if !ok {
+ return RoomState{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindUnavailable, Message: "抖音直播服务未初始化"}
+ }
+
+ now := m.now()
+ subAcc := m.findDouyinSubAccount(normUID)
+
+ m.mu.Lock()
+ if !force {
+ if cached, hit := m.douyinStatusCache[normUID]; hit && now.Sub(cached.fetchedAt) < statusCacheTTL {
+ hydrated, okCur := m.cachedDouyinStateLocked(normUID)
+ if !okCur {
+ hydrated = m.hydrateDouyinStateLocked(cached.state)
+ }
+ liveSt := cached.status
+ m.mu.Unlock()
+ if autoStart && m.douyinAccountAutoRecords(normUID) {
+ if m.autoStartDouyin(ctx, liveSt, hydrated) {
+ if rec, ok := m.CachedAccountState(site.Douyin, normUID); ok {
+ hydrated = rec
+ }
+ }
+ }
+ return hydrated, nil
+ }
+ }
+ effectiveWebRID := firstNonEmpty(strings.TrimSpace(webRIDHint), firstNonEmpty(m.douyinWebRIDHints[normUID], subAcc.WebRID))
+ m.mu.Unlock()
+
+ liveSt, err := provider.CheckLiveStatus(ctx, normUID, effectiveWebRID)
+ if err != nil {
+ return RoomState{}, err
+ }
+ if liveSt.AccountUID == "" {
+ liveSt.AccountUID = normUID
+ }
+ st := m.applyDouyinLiveStatus(liveSt, effectiveWebRID, subAcc, now)
+ if autoStart && m.douyinAccountAutoRecords(normUID) {
+ // The check counts as the account's live check, and a broadcast
+ // it finds is recorded as a poll round would.
+ m.mu.Lock()
+ m.douyinLastAutoPoll[normUID] = now
+ m.mu.Unlock()
+ if m.autoStartDouyin(ctx, liveSt, st) {
+ if rec, ok := m.CachedAccountState(site.Douyin, normUID); ok {
+ st = rec
+ }
+ }
+ }
+ return st, nil
+
+ default:
+ return RoomState{}, site.ErrUnknownSite
+ }
+}
+
+// OpenDouyinRoom inspects a Douyin live room by web_rid (or room_id with uidHint) and updates tracked state.
+func (m *Manager) OpenDouyinRoom(ctx context.Context, webRIDOrRoomID, uidHint string) (RoomState, error) {
+ provider, ok := m.getSiteProvider(site.Douyin)
+ if !ok {
+ return RoomState{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindUnavailable, Message: "抖音直播服务未初始化"}
+ }
+ target := strings.TrimSpace(webRIDOrRoomID)
+ uid := strings.TrimSpace(uidHint)
+ if target == "" && uid == "" {
+ return RoomState{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindBadRequest, Message: "缺少抖音直播间号或主播标识"}
+ }
+
+ var subAcc subscription.AccountRef
+ if uid != "" {
+ if norm, err := site.NormalizeUID(site.Douyin, uid); err == nil {
+ uid = norm
+ subAcc = m.findDouyinSubAccount(uid)
+ if target == "" {
+ m.mu.Lock()
+ target = firstNonEmpty(m.douyinWebRIDHints[uid], subAcc.WebRID)
+ m.mu.Unlock()
+ }
+ }
+ }
+
+ liveSt, err := provider.CheckLiveStatus(ctx, uid, target)
+ if err != nil {
+ return RoomState{}, err
+ }
+ if subAcc.UID == "" && liveSt.AccountUID != "" {
+ subAcc = m.findDouyinSubAccount(liveSt.AccountUID)
+ }
+ return m.applyDouyinLiveStatus(liveSt, target, subAcc, m.now()), nil
+}
+
+func (m *Manager) applyDouyinLiveStatus(liveSt site.LiveStatus, queriedWebRID string, subAcc subscription.AccountRef, now time.Time) RoomState {
+ secUID := strings.TrimSpace(liveSt.AccountUID)
+ newWebRID := strings.TrimSpace(liveSt.WebRID)
+ roomIDStr := strings.TrimSpace(liveSt.RoomID)
+
+ var needSync bool
+ var syncVal string
+ var syncInvalidated bool
+
+ m.mu.Lock()
+ if secUID != "" {
+ if liveSt.InvalidatedWebRID {
+ if newWebRID != "" {
+ m.douyinWebRIDHints[secUID] = newWebRID
+ syncVal = newWebRID
+ syncInvalidated = true
+ } else {
+ delete(m.douyinWebRIDHints, secUID)
+ syncVal = ""
+ syncInvalidated = true
+ }
+ needSync = true
+ } else if newWebRID != "" && m.douyinWebRIDHints[secUID] != newWebRID {
+ m.douyinWebRIDHints[secUID] = newWebRID
+ syncVal = newWebRID
+ if subAcc.UID != "" && subAcc.WebRID != newWebRID {
+ needSync = true
+ } else if queriedWebRID == "" {
+ needSync = true
+ }
+ }
+ if roomIDStr != "" && roomIDStr != "0" {
+ m.douyinRoomHints[secUID] = roomIDStr
+ } else if liveSt.Status == site.LiveStateOffline || liveSt.Status == site.LiveStateNone {
+ delete(m.douyinRoomHints, secUID)
+ }
+ if rawCover := strings.TrimSpace(liveSt.Cover); rawCover != "" {
+ m.douyinRawCovers[secUID] = rawCover
+ }
+ }
+
+ liveInt, statusText := mapSiteLiveStateDisplay(liveSt.Status)
+ var parsedRoomID int64
+ if roomIDStr != "" {
+ parsedRoomID, _ = strconv.ParseInt(roomIDStr, 10, 64)
+ }
+
+ stateKey := douyinStateKey(roomIDStr, secUID, newWebRID)
+ existing, hasDirect := m.douyinStates[stateKey]
+ if (!hasDirect || (existing.RecordItemDir == "" && len(existing.Incidents) == 0 && existing.StopReason == "" && existing.LastError == "")) && secUID != "" {
+ if prev, ok := m.findPrevDouyinStateLocked(secUID); ok {
+ if existing.RecordItemDir == "" {
+ existing.RecordItemDir = prev.RecordItemDir
+ }
+ if len(existing.Incidents) == 0 {
+ existing.Incidents = prev.Incidents
+ }
+ if existing.StopReason == "" {
+ existing.StopReason = prev.StopReason
+ }
+ if existing.LastError == "" {
+ existing.LastError = prev.LastError
+ }
+ if existing.Quality == 0 {
+ existing.Quality = prev.Quality
+ }
+ if existing.QualityName == "" {
+ existing.QualityName = prev.QualityName
+ }
+ if existing.Codec == "" {
+ existing.Codec = prev.Codec
+ }
+ }
+ }
+ var recSess *recordSession
+ if roomIDStr != "" {
+ recSess = m.douyinSessions[roomIDStr]
+ }
+
+ st := RoomState{
+ Site: string(site.Douyin),
+ AccountUID: secUID,
+ UniqueID: subAcc.UniqueID,
+ RoomID: parsedRoomID,
+ RoomIDStr: roomIDStr,
+ WebRID: firstNonEmpty(newWebRID, m.douyinWebRIDHints[secUID]),
+ RoomKey: stateKey,
+ LiveState: liveSt.Status,
+ Uname: firstNonEmpty(liveSt.Uname, subAcc.Name),
+ Face: sanitizeLiveURL(firstNonEmpty(liveSt.Face, subAcc.Face)),
+ Title: liveSt.Title,
+ Cover: sanitizeLiveURL(liveSt.Cover),
+ AreaName: liveSt.AreaName,
+ LiveStatus: liveInt,
+ LiveSince: liveSt.LiveSince,
+ StatusText: statusText,
+ Quality: firstPositiveInt(liveSt.Quality, existing.Quality),
+ QualityName: firstNonEmpty(liveSt.QualityName, existing.QualityName),
+ Codec: firstNonEmpty(liveSt.Codec, existing.Codec),
+ Recording: recSess != nil,
+ Incidents: cloneIncidents(existing.Incidents),
+ // The last session's folder stays with its incidents after it ends,
+ // so Tasks › 录制异常 shows them on that session only.
+ RecordItemDir: existing.RecordItemDir,
+ StopReason: existing.StopReason,
+ LastError: existing.LastError,
+ UpdatedAt: now.UTC().Format(time.RFC3339),
+ }
+ st = m.hydrateDouyinStateLocked(st)
+ m.douyinStates[stateKey] = st
+ if secUID != "" {
+ for k, old := range m.douyinStates {
+ if k != stateKey && old.AccountUID == secUID && !m.isRoomActivelyRecordingLocked(old.RoomIDStr) {
+ delete(m.douyinStates, k)
+ }
+ }
+ m.douyinStatusCache[secUID] = douyinCachedStatusEntry{
+ status: liveSt,
+ state: st,
+ fetchedAt: now,
+ }
+ }
+ m.mu.Unlock()
+
+ if needSync && secUID != "" {
+ m.syncWebRID(site.Douyin, secUID, syncVal, syncInvalidated)
+ }
+ return st
+}
+
+func (m *Manager) isRoomActivelyRecordingLocked(roomIDStr string) bool {
+ if roomIDStr == "" {
+ return false
+ }
+ _, ok := m.douyinSessions[roomIDStr]
+ return ok
+}
+
+func (m *Manager) isDouyinAccountRecordingLocked(uid string) bool {
+ if uid == "" {
+ return false
+ }
+ if rid := m.douyinRoomHints[uid]; rid != "" {
+ if _, ok := m.douyinSessions[rid]; ok {
+ return true
+ }
+ }
+ for _, sess := range m.douyinSessions {
+ if sess != nil && sess.accountUID == uid {
+ return true
+ }
+ }
+ return false
+}
+
+func (m *Manager) hydrateDouyinStateLocked(st RoomState) RoomState {
+ if st.Site == "" {
+ st.Site = string(site.Douyin)
+ }
+ if sess := m.douyinSessions[st.RoomIDStr]; sess != nil {
+ st.Recording = true
+ st.RecordSession = sess.sessionID
+ st.RecordDurationSec = m.nowLocked().Sub(sess.startedAt).Seconds()
+ st.RecordBytes = sess.bytesTotal
+ st.RecordSegments = len(sess.segments)
+ st.RecordItemDir = sess.itemDir
+ if sess.quality > 0 {
+ st.Quality = sess.quality
+ }
+ if sess.qualityName != "" {
+ st.QualityName = sess.qualityName
+ }
+ if sess.codec != "" {
+ st.Codec = sess.codec
+ }
+ if sess.stopReason != "" {
+ st.StopReason = sess.stopReason
+ }
+ if sess.lastErr != "" {
+ st.LastError = sess.lastErr
+ }
+ hydrateSessionPreviewFieldsLocked(&st, sess)
+ } else {
+ st.Recording = false
+ hydrateSessionPreviewFieldsLocked(&st, nil)
+ }
+ return st
+}
+
+func douyinStateKey(roomIDStr, secUID, webRID string) string {
+ if roomIDStr != "" && roomIDStr != "0" {
+ return "douyin:live:" + roomIDStr
+ }
+ if secUID != "" {
+ return "douyin:user:" + secUID
+ }
+ return "douyin:web:" + webRID
+}
+
+func mapSiteLiveStateDisplay(state string) (int, string) {
+ switch state {
+ case site.LiveStateLive:
+ return 1, "直播中"
+ case site.LiveStateRound:
+ return 2, "轮播中"
+ case site.LiveStateAudioOnly:
+ return 0, "语音直播(暂不支持录制)"
+ default:
+ return 0, "未开播"
+ }
+}
+
+func (m *Manager) findDouyinSubAccount(secUID string) subscription.AccountRef {
+ if m.subs == nil || secUID == "" {
+ return subscription.AccountRef{}
+ }
+ list, err := m.subs.List()
+ if err != nil {
+ return subscription.AccountRef{}
+ }
+ for _, s := range list {
+ for _, acc := range s.Accounts {
+ if acc.Site == string(site.Douyin) && acc.UID == secUID {
+ if acc.Name == "" {
+ acc.Name = s.Name
+ }
+ if acc.Face == "" {
+ acc.Face = s.Face
+ }
+ return acc
+ }
+ }
+ }
+ return subscription.AccountRef{}
+}
+
+// douyinAccountAutoRecords tells whether a subscription records the
+// broadcasts of a Douyin account.
+func (m *Manager) douyinAccountAutoRecords(secUID string) bool {
+ if m.subs == nil || secUID == "" {
+ return false
+ }
+ list, err := m.subs.List()
+ if err != nil {
+ return false
+ }
+ for _, s := range list {
+ if !s.Rules.AutoRecord && !s.LiveAutoRecord {
+ continue
+ }
+ for _, acc := range s.Accounts {
+ if acc.Site != string(site.Douyin) {
+ continue
+ }
+ if norm, err := site.NormalizeUID(site.Douyin, acc.UID); err == nil && norm == secUID {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+// douyinShouldAutoStartLocked tells whether a broadcast a check found should
+// start recording: it is live and neither recorded already nor stopped by
+// hand. The caller holds m.mu.
+func (m *Manager) douyinShouldAutoStartLocked(liveSt site.LiveStatus) bool {
+ if liveSt.Status != site.LiveStateLive || liveSt.RoomID == "" || m.stopping {
+ return false
+ }
+ _, running := m.douyinSessions[liveSt.RoomID]
+ return !running && !m.douyinStoppedRooms[liveSt.RoomID]
+}
+
+// autoStartDouyin starts recording a broadcast found live outside a poll
+// round (an account's status refreshed by hand or by an update check), for
+// an account whose subscription records broadcasts. It reports whether a
+// recording started.
+func (m *Manager) autoStartDouyin(ctx context.Context, liveSt site.LiveStatus, st RoomState) bool {
+ m.mu.Lock()
+ if liveSt.Status != site.LiveStateLive && liveSt.RoomID != "" {
+ delete(m.douyinStoppedRooms, liveSt.RoomID)
+ }
+ start := m.douyinShouldAutoStartLocked(liveSt)
+ m.mu.Unlock()
+ if !start {
+ return false
+ }
+ if _, err := m.StartDouyinRecording(ctx, liveSt.AccountUID, firstNonEmpty(st.WebRID, liveSt.RoomID)); err != nil {
+ m.mu.Lock()
+ for k, rs := range m.douyinStates {
+ if rs.AccountUID == liveSt.AccountUID {
+ rs.LastError = sanitizeLiveError(err)
+ m.douyinStates[k] = rs
+ }
+ }
+ m.mu.Unlock()
+ return false
+ }
+ return true
+}
+
+func sanitizeLiveURL(raw string) string {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return ""
+ }
+ u, err := url.Parse(raw)
+ if err != nil || u.Scheme == "" || u.Host == "" {
+ return ""
+ }
+ u.User = nil
+ u.RawQuery = ""
+ u.Fragment = ""
+ return u.String()
+}
+
+func firstPositiveInt(a, b int) int {
+ if a > 0 {
+ return a
+ }
+ return b
+}
diff --git a/internal/live/finalize.go b/internal/live/finalize.go
new file mode 100644
index 0000000..faa8252
--- /dev/null
+++ b/internal/live/finalize.go
@@ -0,0 +1,108 @@
+package live
+
+import (
+ "context"
+ "errors"
+ "math"
+ "os"
+ "path/filepath"
+
+ "github.com/Eyevinn/mp4ff/mp4"
+ "github.com/chialecode/trace/internal/download"
+)
+
+// liveFinalizeToleranceSec bounds how far the converted duration may differ
+// from the source timeline. Real Bilibili parts differ by under 0.02 s (the
+// audio and video tracks end a fraction of a frame apart).
+const liveFinalizeToleranceSec = 1.0
+
+type contextFile struct {
+ *os.File
+ ctx context.Context
+}
+
+func (f contextFile) Read(p []byte) (int, error) {
+ if err := f.ctx.Err(); err != nil {
+ return 0, err
+ }
+ return f.File.Read(p)
+}
+
+func (f contextFile) Write(p []byte) (int, error) {
+ if err := f.ctx.Err(); err != nil {
+ return 0, err
+ }
+ return f.File.Write(p)
+}
+
+func (f contextFile) Seek(offset int64, whence int) (int64, error) {
+ if err := f.ctx.Err(); err != nil {
+ return 0, err
+ }
+ return f.File.Seek(offset, whence)
+}
+
+// finalizeLivePart defragments a recorded fMP4 .part into a progressive MP4
+// with moov before mdat. Media samples stay on disk while mp4ff reads metadata
+// and copies them to the progressive output. The original .part remains until
+// its manifest is saved. The output must keep the source's own media timeline;
+// the recorder's running duration (HLS EXTINF sum) is only an estimate and is
+// not compared.
+func finalizeLivePart(ctx context.Context, partPath, finalPath string) (download.MuxTrackSummary, error) {
+ f, err := os.Open(partPath)
+ if err != nil {
+ return download.MuxTrackSummary{}, err
+ }
+ defer f.Close()
+ source := contextFile{File: f, ctx: ctx}
+ parsed, err := mp4.DecodeFile(source, mp4.WithDecodeMode(mp4.DecModeLazyMdat), mp4.WithDecodeFlags(mp4.DecStartOnMoof))
+ if err != nil {
+ return download.MuxTrackSummary{}, err
+ }
+ trimFragmentOverlaps(parsed)
+ sourceSec := fragmentTimelineSec(parsed)
+ if err := os.MkdirAll(filepath.Dir(finalPath), 0o700); err != nil {
+ return download.MuxTrackSummary{}, err
+ }
+ out, err := os.CreateTemp(filepath.Dir(finalPath), ".trace-live-*.part")
+ if err != nil {
+ return download.MuxTrackSummary{}, err
+ }
+ name := out.Name()
+ defer os.Remove(name)
+ if err := mp4.Defragment(parsed, source, contextFile{File: out, ctx: ctx}); err != nil {
+ _ = out.Close()
+ return download.MuxTrackSummary{}, err
+ }
+ if err := out.Sync(); err != nil {
+ _ = out.Close()
+ return download.MuxTrackSummary{}, err
+ }
+ if err := out.Close(); err != nil {
+ return download.MuxTrackSummary{}, err
+ }
+ summary, err := download.InspectMP4FileContext(ctx, name)
+ if err != nil {
+ return summary, err
+ }
+ if !finalizedLivePart(summary) || sourceSec > 0 && math.Abs(summary.DurationSec-sourceSec) > liveFinalizeToleranceSec {
+ return summary, errors.New("直播录像轨道或时长校验失败")
+ }
+ if err := ctx.Err(); err != nil {
+ return summary, err
+ }
+ if err := os.Rename(name, finalPath); err != nil {
+ return summary, err
+ }
+ return summary, nil
+}
+
+// finalizedLivePart reports whether an MP4 is a converted recording: a video
+// track, moov before mdat and a positive duration.
+func finalizedLivePart(summary download.MuxTrackSummary) bool {
+ video := false
+ for _, handler := range summary.Handlers {
+ video = video || handler == "vide"
+ }
+ return video && summary.MoovBeforeMdat && summary.DurationSec > 0
+}
diff --git a/internal/live/flv.go b/internal/live/flv.go
index 4ad9c84..e5e41cd 100644
--- a/internal/live/flv.go
+++ b/internal/live/flv.go
@@ -17,7 +17,6 @@ const (
flvHeaderSize = 9
flvTagHeaderSize = 11
flvMaxHeaderOffset = 64 * 1024
- flvMaxTagDataSize = 32 * 1024 * 1024 // 32 MiB upper bound per FLV tag
flvTagTypeAudio uint8 = 8
flvTagTypeVideo uint8 = 9
@@ -32,7 +31,7 @@ const (
flvExPacketCodedFrames uint8 = 1
flvExPacketSequenceEnd uint8 = 2
flvExPacketCodedFramesX uint8 = 3
- flvExPacketMetadata uint8 = 5
+ flvExPacketMetadata uint8 = 4
)
// VideoCodec identifies the normalized ISO BMFF sample entry FourCC for live video.
@@ -211,9 +210,6 @@ func (fr *FLVReader) NextTag() (FLVTag, error) {
}
tagType := fr.scratch[0] & 0x1f
dataSize := uint32(fr.scratch[1])<<16 | uint32(fr.scratch[2])<<8 | uint32(fr.scratch[3])
- if dataSize > flvMaxTagDataSize {
- return FLVTag{}, &FLVFormatError{Reason: fmt.Sprintf("单标签长度超限 (%d 字节)", dataSize)}
- }
rawTS := uint32(fr.scratch[4])<<16 | uint32(fr.scratch[5])<<8 | uint32(fr.scratch[6]) | uint32(fr.scratch[7])<<24
data := make([]byte, dataSize)
@@ -668,6 +664,35 @@ func normalizeLengthPrefixedNALUs(payload []byte, naluLenSize int) ([]byte, erro
return nil, &FLVFormatError{Reason: "视频编码帧为空"}
}
+ // Zero-copy fast path: validate 4-byte length-prefixed NALUs in place and return
+ // payload directly when no zero-length NALU needs to be stripped.
+ if naluLenSize == 4 {
+ hasNonEmpty := false
+ hasEmpty := false
+ for off := 0; off < len(payload); {
+ if len(payload)-off < 4 {
+ return nil, &FLVFormatError{Reason: "NALU 长度前缀截断"}
+ }
+ naluLen := binary.BigEndian.Uint32(payload[off : off+4])
+ off += 4
+ if naluLen == 0 {
+ hasEmpty = true
+ continue
+ }
+ if uint64(naluLen) > uint64(len(payload)-off) {
+ return nil, &FLVFormatError{Reason: "NALU 载荷长度越界"}
+ }
+ hasNonEmpty = true
+ off += int(naluLen)
+ }
+ if !hasNonEmpty {
+ return nil, &FLVFormatError{Reason: "视频帧不含有效非空 NALU"}
+ }
+ if !hasEmpty {
+ return payload, nil
+ }
+ }
+
outCap := len(payload)
if naluLenSize < 4 {
outCap += 32
diff --git a/internal/live/flv_stream.go b/internal/live/flv_stream.go
new file mode 100644
index 0000000..2e98e83
--- /dev/null
+++ b/internal/live/flv_stream.go
@@ -0,0 +1,336 @@
+package live
+
+import (
+ "bufio"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "mime"
+ "net"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/site"
+)
+
+const (
+ defaultFLVConnectTimeout = 10 * time.Second
+ defaultFLVIdleTimeout = 15 * time.Second
+ flvReadBufferSize = 64 << 10 // 64 KiB buffered reader over FLV stream
+)
+
+type activeFLVConn struct {
+ body io.ReadCloser
+ remuxer *FLVRemuxer
+}
+
+func (c *activeFLVConn) Close() error {
+ if c == nil || c.body == nil {
+ return nil
+ }
+ err := c.body.Close()
+ c.body = nil
+ return err
+}
+
+type transportCloseReadCloser struct {
+ io.ReadCloser
+ tr *http.Transport
+ closeOnce sync.Once
+ closeErr error
+}
+
+func (t *transportCloseReadCloser) Close() error {
+ t.closeOnce.Do(func() {
+ if t.ReadCloser != nil {
+ t.closeErr = t.ReadCloser.Close()
+ }
+ if t.tr != nil {
+ t.tr.CloseIdleConnections()
+ }
+ })
+ return t.closeErr
+}
+
+func (m *Manager) recordBilibiliFLVPart(
+ ctx context.Context,
+ sess *recordSession,
+ urls []string,
+ connPtr **activeFLVConn,
+ partPath string,
+) (int64, error) {
+ allowLocal := m.client != nil && m.client.AllowLocalhost()
+ spec := site.BilibiliMediaTransport(allowLocal)
+ spec.Referer = "https://live.bilibili.com/"
+ spec.Origin = "https://live.bilibili.com"
+ return m.recordFLVPartWithTransport(ctx, sess, spec, urls, connPtr, partPath)
+}
+
+func (m *Manager) recordFLVPartWithTransport(
+ ctx context.Context,
+ sess *recordSession,
+ transport site.MediaTransportSpec,
+ urls []string,
+ connPtr **activeFLVConn,
+ partPath string,
+) (written int64, result error) {
+ partBase := filepath.Base(partPath)
+ if *connPtr == nil {
+ m.mu.Lock()
+ idleDur := m.flvIdleTimeout
+ m.mu.Unlock()
+ body, err := OpenHTTPFLVStream(ctx, transport, urls, idleDur)
+ if err != nil {
+ return 0, err
+ }
+ m.markSessionReconnected(sess, m.now(), true, partBase)
+ remuxer := NewFLVRemuxer(bufio.NewReaderSize(body, flvReadBufferSize), FLVRemuxOptions{})
+ *connPtr = &activeFLVConn{
+ body: body,
+ remuxer: remuxer,
+ }
+ }
+
+ if err := os.MkdirAll(filepath.Dir(partPath), 0o700); err != nil {
+ return 0, err
+ }
+ f, err := os.OpenFile(partPath, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0o600)
+ if err != nil {
+ return 0, err
+ }
+ defer func() {
+ if sErr := f.Sync(); sErr != nil && result == nil {
+ result = sErr
+ }
+ if cErr := f.Close(); cErr != nil && result == nil {
+ result = cErr
+ }
+ }()
+
+ var prevBytes int64
+ var prevDur float64
+ prevCheckAt := m.now()
+ cp, wErr := (*connPtr).remuxer.WritePart(ctx, f, func(cp FLVCheckpoint) error {
+ if err := m.checkDiskSpace(sess.itemDir, transport.Site); err != nil {
+ return err
+ }
+ checkNow := m.now()
+ delta := cp.BytesWritten - prevBytes
+ deltaDur := cp.DurationSec - prevDur
+ if delta > 0 {
+ m.observeTransferSpeed(sess, prevCheckAt, checkNow, delta, deltaDur, partBase)
+ prevBytes = cp.BytesWritten
+ written = cp.BytesWritten
+ m.addSessionBytes(sess, delta)
+ }
+ prevCheckAt = checkNow
+ if cp.DurationSec > prevDur {
+ prevDur = cp.DurationSec
+ }
+ sess.segmentDuration = cp.DurationSec
+ m.mu.Lock()
+ sess.wroteMedia = true
+ sess.lastSequence = cp.Sequence
+ sess.hasSequence = true
+ if cp.Codec != "" {
+ sess.codec = cp.Codec
+ }
+ m.mu.Unlock()
+
+ m.commitSessionPart(sess, cp.BytesWritten, cp.DurationSec)
+ return m.saveCheckpoint(sess, func(meta *library.ItemMetadata) {
+ if cp.Codec != "" {
+ meta.Live.Codec = cp.Codec
+ }
+ meta.Live.LastSequence = cp.Sequence
+ meta.Live.HasSequence = true
+ meta.Live.PendingFile = partBase
+ meta.Live.PendingBytes = cp.BytesWritten
+ meta.Live.PendingDuration = cp.DurationSec
+ })
+ })
+ if cp.BytesWritten > written {
+ m.addSessionBytes(sess, cp.BytesWritten-written)
+ written = cp.BytesWritten
+ }
+ return written, wErr
+}
+
+// OpenHTTPFLVStream opens an HTTP-FLV live stream over HTTPS (or localhost in tests),
+// enforcing a 10s connect/header timeout, per-read idle timeout, <=5 redirect hops (ValidateRedirectURL),
+// Referer/Origin headers with Cookie stripped, and rejecting HTML/JSON disguised responses.
+func OpenHTTPFLVStream(ctx context.Context, transport site.MediaTransportSpec, urls []string, idleTimeout time.Duration) (io.ReadCloser, error) {
+ if idleTimeout <= 0 {
+ idleTimeout = defaultFLVIdleTimeout
+ }
+ var cleanURLs []string
+ var lastValidateErr error
+ for _, u := range urls {
+ u = strings.TrimSpace(u)
+ if u == "" {
+ continue
+ }
+ if err := transport.ValidateURL(u); err != nil {
+ lastValidateErr = err
+ continue
+ }
+ cleanURLs = append(cleanURLs, u)
+ }
+ if len(cleanURLs) == 0 {
+ if lastValidateErr != nil {
+ return nil, lastValidateErr
+ }
+ return nil, &site.Error{Site: transport.Site, Kind: site.ErrKindUnavailable, Message: "直播拉流地址列表为空"}
+ }
+
+ httpClient, tr := newLiveTransportClientWithTransport(transport, defaultFLVConnectTimeout)
+ var lastErr error
+ for _, targetURL := range cleanURLs {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil)
+ if err != nil {
+ lastErr = &site.Error{
+ Site: transport.Site,
+ Kind: site.ErrKindNetwork,
+ Message: "创建直播流请求失败",
+ Err: site.UnwrapURLError(err),
+ }
+ continue
+ }
+ transport.ApplyHeaders(req)
+
+ resp, err := httpClient.Do(req)
+ if err != nil {
+ var se *site.Error
+ if errors.As(err, &se) {
+ lastErr = se
+ if site.IsRoundStop(se) || se.Kind == site.ErrKindBlocked {
+ tr.CloseIdleConnections()
+ return nil, se
+ }
+ continue
+ }
+ lastErr = &site.Error{
+ Site: transport.Site,
+ Kind: site.ErrKindNetwork,
+ Message: "连接直播流节点失败",
+ Err: site.UnwrapURLError(err),
+ }
+ continue
+ }
+
+ if resp.StatusCode != http.StatusOK {
+ _ = resp.Body.Close()
+ se := mapLiveHTTPStatus(transport.Site, resp.StatusCode)
+ lastErr = se
+ if site.IsRoundStop(se) {
+ tr.CloseIdleConnections()
+ return nil, se
+ }
+ continue
+ }
+
+ ct := strings.TrimSpace(resp.Header.Get("Content-Type"))
+ if badErr := checkLiveFLVContentType(transport.Site, ct); badErr != nil {
+ _ = resp.Body.Close()
+ tr.CloseIdleConnections()
+ return nil, badErr
+ }
+
+ timeoutSec := max(1, int(idleTimeout.Seconds()))
+ idleBody := site.WrapIdleReadCloser(resp.Body, idleTimeout, func() error {
+ return &site.Error{
+ Site: transport.Site,
+ Kind: site.ErrKindNetwork,
+ Message: fmt.Sprintf("直播流超过 %d 秒无数据返回", timeoutSec),
+ }
+ })
+ return &transportCloseReadCloser{ReadCloser: idleBody, tr: tr}, nil
+ }
+ tr.CloseIdleConnections()
+ if lastErr != nil {
+ return nil, lastErr
+ }
+ return nil, &site.Error{Site: transport.Site, Kind: site.ErrKindNetwork, Message: "无法连接任何直播流节点"}
+}
+
+func newLiveTransportClient(spec site.MediaTransportSpec, connectTimeout time.Duration) *http.Client {
+ c, _ := newLiveTransportClientWithTransport(spec, connectTimeout)
+ return c
+}
+
+func newLiveTransportClientWithTransport(spec site.MediaTransportSpec, connectTimeout time.Duration) (*http.Client, *http.Transport) {
+ if connectTimeout <= 0 {
+ connectTimeout = defaultFLVConnectTimeout
+ }
+ dialer := &net.Dialer{Timeout: connectTimeout, KeepAlive: 30 * time.Second}
+ guard := site.NewGuardedMediaDialer(spec.Site, spec.AllowLocalhost, dialer, "已拦截内网或回环直播流节点地址")
+ tr := &http.Transport{
+ Proxy: guard.Proxy,
+ MaxIdleConns: 8,
+ IdleConnTimeout: 30 * time.Second,
+ TLSHandshakeTimeout: connectTimeout,
+ ResponseHeaderTimeout: connectTimeout,
+ DialContext: guard.DialContext,
+ }
+ client := &http.Client{
+ Transport: tr,
+ CheckRedirect: func(req *http.Request, via []*http.Request) error {
+ if len(via) >= 5 {
+ return &site.Error{
+ Site: spec.Site,
+ Kind: site.ErrKindBlocked,
+ Message: "直播流重定向超过 5 跳上限",
+ }
+ }
+ if err := spec.ValidateRedirectURL(req.URL.String()); err != nil {
+ return err
+ }
+ spec.ApplyHeaders(req)
+ return nil
+ },
+ }
+ return client, tr
+}
+
+func mapLiveHTTPStatus(siteID site.ID, status int) *site.Error {
+ switch status {
+ case http.StatusUnauthorized:
+ return &site.Error{Site: siteID, Kind: site.ErrKindAuthRequired, HTTPStatus: status, Message: "直播拉流需要有效登录凭证 (401)"}
+ case http.StatusPreconditionFailed:
+ return &site.Error{Site: siteID, Kind: site.ErrKindRiskControl, HTTPStatus: status, Message: "直播请求触发风控 (412),已停止录制"}
+ case http.StatusTooManyRequests:
+ return &site.Error{Site: siteID, Kind: site.ErrKindRateLimited, HTTPStatus: status, Message: "直播请求触发频率限制 (429),已停止录制"}
+ case http.StatusForbidden:
+ return &site.Error{Site: siteID, Kind: site.ErrKindForbidden, HTTPStatus: status, Message: "直播流地址已过期或被拒绝 (403)"}
+ case http.StatusNotFound, http.StatusGone:
+ return &site.Error{Site: siteID, Kind: site.ErrKindUnavailable, HTTPStatus: status, Message: fmt.Sprintf("直播流节点不可用 (%d)", status)}
+ default:
+ return &site.Error{Site: siteID, Kind: site.ErrKindNetwork, HTTPStatus: status, Message: fmt.Sprintf("直播流 HTTP 状态异常 (%d)", status)}
+ }
+}
+
+func checkLiveFLVContentType(siteID site.ID, rawCT string) error {
+ if rawCT == "" {
+ return nil
+ }
+ mt, _, err := mime.ParseMediaType(rawCT)
+ if err != nil {
+ mt = strings.ToLower(strings.TrimSpace(strings.SplitN(rawCT, ";", 2)[0]))
+ }
+ mt = strings.ToLower(strings.TrimSpace(mt))
+ switch mt {
+ case "text/html", "application/xhtml+xml", "application/json", "text/json", "text/plain", "application/vnd.apple.mpegurl", "application/x-mpegurl":
+ return &site.Error{
+ Site: siteID,
+ Kind: site.ErrKindSchemaChanged,
+ Message: fmt.Sprintf("直播流返回了非 FLV 响应类型 (%s)", mt),
+ }
+ }
+ return nil
+}
diff --git a/internal/live/flv_test.go b/internal/live/flv_test.go
index b035a3e..42db5f9 100644
--- a/internal/live/flv_test.go
+++ b/internal/live/flv_test.go
@@ -349,7 +349,7 @@ func TestFLVRemuxDomesticCodecID12HEVCAndEnhancedFLVHVC1(t *testing.T) {
fb := newFLVBuilder(0x05)
hvcC := buildHEVCDecConfBytes(t, vps, sps, pps, 4)
- // Enhanced Metadata (PacketType=5) must be skipped cleanly.
+ // Enhanced Metadata (PacketType=4) must be skipped cleanly.
fb.writeEnhancedVideo(0, 1, flvExPacketMetadata, "hvc1", []byte("hdr-info-ignored"))
// SequenceStart (PacketType=0)
fb.writeEnhancedVideo(0, 1, flvExPacketSequenceStart, "hvc1", hvcC)
diff --git a/internal/live/hls.go b/internal/live/hls.go
new file mode 100644
index 0000000..a5c7c97
--- /dev/null
+++ b/internal/live/hls.go
@@ -0,0 +1,351 @@
+package live
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "math"
+ "net/http"
+ "os"
+ "path/filepath"
+ "time"
+
+ "github.com/Eyevinn/mp4ff/mp4"
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/site"
+ "github.com/chialecode/trace/internal/site/bilibili"
+)
+
+// hlsSequenceGapSlackSec is how much a sequence gap may exceed the time since
+// the previous segment and still count as lost segments (EXTINF rounding and
+// playlist windows), rather than as a restarted stream's new numbering.
+const hlsSequenceGapSlackSec = 30.0
+
+func (m *Manager) fetchLiveBytes(ctx context.Context, targetURL string) ([]byte, error) {
+ return m.fetchLiveLimitedBytes(ctx, targetURL, 32*1024*1024)
+}
+
+func (m *Manager) fetchLiveLimitedBytes(ctx context.Context, targetURL string, maxBytes int64) ([]byte, error) {
+ if err := m.client.ValidateMediaURL(targetURL); err != nil {
+ return nil, err
+ }
+ mediaClient, _ := m.client.MediaHTTPClient()
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil)
+ if err != nil {
+ return nil, &site.Error{
+ Site: site.Bilibili,
+ Kind: site.ErrKindNetwork,
+ Message: "创建直播流请求失败",
+ Err: site.UnwrapURLError(err),
+ }
+ }
+ req.Header.Set("User-Agent", bilibili.DefaultUserAgent)
+ req.Header.Set("Referer", "https://live.bilibili.com/")
+ req.Header.Set("Origin", "https://live.bilibili.com")
+
+ resp, err := mediaClient.Do(req)
+ if err != nil {
+ var se *site.Error
+ if errors.As(err, &se) {
+ return nil, se
+ }
+ return nil, &site.Error{
+ Site: site.Bilibili,
+ Kind: site.ErrKindNetwork,
+ Message: "请求直播流节点失败",
+ Err: site.UnwrapURLError(err),
+ }
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode == http.StatusPreconditionFailed {
+ return nil, &bilibili.SiteError{
+ Site: site.Bilibili,
+ Kind: bilibili.ErrKindRiskControl,
+ HTTPStatus: resp.StatusCode,
+ Message: "直播请求触发风控,已停止录制",
+ }
+ }
+ if resp.StatusCode != http.StatusOK {
+ kind := bilibili.ErrKindNetwork
+ if resp.StatusCode == http.StatusTooManyRequests {
+ kind = bilibili.ErrKindRateLimited
+ }
+ if resp.StatusCode == http.StatusUnauthorized {
+ kind = bilibili.ErrKindAuthRequired
+ }
+ return nil, &bilibili.SiteError{
+ Site: site.Bilibili,
+ Kind: kind,
+ HTTPStatus: resp.StatusCode,
+ Message: "直播节点请求失败",
+ }
+ }
+ reader := m.client.WrapMediaReader(resp.Body)
+ defer reader.Close()
+ data, err := io.ReadAll(io.LimitReader(reader, maxBytes+1))
+ if err != nil {
+ var se *site.Error
+ if errors.As(err, &se) {
+ return nil, se
+ }
+ return nil, &site.Error{
+ Site: site.Bilibili,
+ Kind: site.ErrKindNetwork,
+ Message: "读取直播流数据失败",
+ Err: site.UnwrapURLError(err),
+ }
+ }
+ if int64(len(data)) > maxBytes {
+ return nil, &bilibili.SiteError{
+ Site: site.Bilibili,
+ Kind: bilibili.ErrKindSchemaChanged,
+ Message: "直播响应超过大小上限",
+ }
+ }
+ return data, nil
+}
+
+func (m *Manager) recordHLSSegment(ctx context.Context, sess *recordSession, urls []string, partPath string, isFMP4 bool) (written int64, result error) {
+ if len(urls) == 0 || !isFMP4 {
+ return 0, &bilibili.SiteError{Site: site.Bilibili, Kind: bilibili.ErrKindUnavailable, Message: "没有可录制的 HLS fMP4 流"}
+ }
+ if err := os.MkdirAll(filepath.Dir(partPath), 0o700); err != nil {
+ return 0, err
+ }
+ f, err := os.OpenFile(partPath, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0o600)
+ if err != nil {
+ return 0, err
+ }
+ defer func() {
+ if err := f.Sync(); err != nil && result == nil {
+ result = err
+ }
+ if err := f.Close(); err != nil && result == nil {
+ result = err
+ }
+ }()
+
+ urlIdx := 0
+ playlistURL, initURI := urls[0], ""
+ followedVariant := false
+ var initBytes []byte
+ partBase := filepath.Base(partPath)
+ lastNew := m.now()
+
+ for ctx.Err() == nil {
+ if err := m.checkDiskSpace(sess.itemDir, site.Bilibili); err != nil {
+ return written, err
+ }
+ raw, err := m.fetchLiveLimitedBytes(ctx, playlistURL, maxM3U8PlaylistBytes)
+ if err != nil {
+ if written == 0 && !followedVariant && urlIdx+1 < len(urls) && liveStopReason(err) == "" {
+ urlIdx++
+ playlistURL = urls[urlIdx]
+ continue
+ }
+ return written, err
+ }
+ playlist := parseM3U8PlaylistDetails(string(raw), playlistURL)
+ if len(playlist.variants) > 0 && len(playlist.segments) == 0 && playlist.valid {
+ // Some nodes answer with a multivariant playlist. Follow it once; a
+ // second level of indirection is treated as a schema change.
+ variant, ok := playlist.bestVariantInfo()
+ if followedVariant || !ok {
+ return written, &bilibili.SiteError{Site: site.Bilibili, Kind: bilibili.ErrKindSchemaChanged, Message: "直播播放列表结构不完整(多级索引)"}
+ }
+ if err := m.client.ValidateMediaURL(variant.uri); err != nil {
+ return written, &bilibili.SiteError{Site: site.Bilibili, Kind: bilibili.ErrKindSchemaChanged, Message: "直播播放列表指向不受支持的节点"}
+ }
+ if variant.bandwidth > 0 {
+ m.setSessionNominalBitrateBps(sess, variant.bandwidth)
+ }
+ playlistURL, followedVariant = variant.uri, true
+ continue
+ }
+ if playlist.encrypted {
+ return written, &bilibili.SiteError{Site: site.Bilibili, Kind: bilibili.ErrKindBlocked, Message: "不支持加密的直播分片"}
+ }
+ if !playlist.valid {
+ return written, &bilibili.SiteError{Site: site.Bilibili, Kind: bilibili.ErrKindSchemaChanged, Message: "直播播放列表结构不完整:" + playlist.invalidReason}
+ }
+ m.markSessionReconnected(sess, m.now(), false, partBase)
+
+ m.mu.Lock()
+ lastSeq, hasSeq, wroteMedia := sess.lastSequence, sess.hasSequence, sess.wroteMedia
+ m.mu.Unlock()
+
+ if hasSeq && len(playlist.segments) > 0 && playlist.segments[len(playlist.segments)-1].seq < lastSeq {
+ // A sequence reset starts a new part even when the same init URI is
+ // reused. Keeping the old watermark would skip the new broadcast data.
+ m.mu.Lock()
+ sess.lastSequence, sess.hasSequence = 0, false
+ m.mu.Unlock()
+ return written, errSegmentRollover
+ }
+ newCount := 0
+ if wroteMedia && playlist.mapURI == initURI {
+ for _, segment := range playlist.segments {
+ if !hasSeq || segment.seq > lastSeq {
+ freshInit, err := m.fetchLiveBytes(ctx, segment.mapURI)
+ if err != nil {
+ return written, err
+ }
+ if !bytes.Equal(freshInit, initBytes) {
+ return written, errSegmentRollover
+ }
+ break
+ }
+ }
+ }
+ for _, segment := range playlist.segments {
+ if hasSeq && segment.seq <= lastSeq {
+ continue
+ }
+ if wroteMedia && (segment.discontinuity || hasSeq && segment.seq-lastSeq > 4 || segment.mapURI != initURI) {
+ return written, errSegmentRollover
+ }
+ if initURI == "" {
+ initBytes, err = m.fetchLiveBytes(ctx, segment.mapURI)
+ if err != nil {
+ return written, err
+ }
+ if !validLiveInit(initBytes) {
+ return written, &bilibili.SiteError{Site: site.Bilibili, Kind: bilibili.ErrKindSchemaChanged, Message: "直播初始化分片缺少有效视频轨"}
+ }
+ initURI = segment.mapURI
+ n, err := f.Write(initBytes)
+ written += int64(n)
+ m.addSessionBytes(sess, int64(n))
+ if err != nil {
+ return written, err
+ }
+ }
+ fetchStart := m.now()
+ fragment, err := m.fetchLiveBytes(ctx, segment.uri)
+ fetchEnd := m.now()
+ if err != nil {
+ return written, err
+ }
+ if !validLiveFragment(fragment) {
+ return written, &bilibili.SiteError{Site: site.Bilibili, Kind: bilibili.ErrKindSchemaChanged, Message: "直播媒体分片不完整"}
+ }
+ n, err := f.Write(fragment)
+ written += int64(n)
+ m.addSessionBytes(sess, int64(n))
+ if err != nil {
+ return written, err
+ }
+ // Persist complete fragments only; fsync never leaves half a fragment as
+ // the checkpoint used by startup recovery.
+ if err := f.Sync(); err != nil {
+ return written, err
+ }
+ if !segment.discontinuity && hasSeq && segment.seq > lastSeq+1 {
+ dropped := int(segment.seq - lastSeq - 1)
+ targetDur := playlist.targetDuration
+ if targetDur <= 0 {
+ targetDur = segment.duration
+ }
+ if targetDur <= 0 {
+ targetDur = 1.0
+ }
+ // A gap longer than the time since the previous segment cannot be
+ // lost media: the restarted stream numbers its segments from a new
+ // base (seen jumping by 100 million after a reconnect).
+ if lostSec := float64(dropped) * targetDur; sess.lastSequenceAt.IsZero() || lostSec <= fetchEnd.Sub(sess.lastSequenceAt).Seconds()+hlsSequenceGapSlackSec {
+ atStr := fetchEnd.UTC().Format(time.RFC3339)
+ m.recordSessionIncident(sess, library.LiveIncident{
+ Kind: library.LiveIncidentLostSegments,
+ At: atStr,
+ EndedAt: atStr,
+ DurationSec: lostSec,
+ LostSegments: dropped,
+ Count: 1,
+ Part: partBase,
+ Reason: fmt.Sprintf("HLS 媒体分片序号跳号,丢失 %d 段", dropped),
+ }, true)
+ }
+ }
+ m.observeTransferSpeed(sess, fetchStart, fetchEnd, int64(len(fragment)), segment.duration, partBase)
+
+ lastSeq, hasSeq, wroteMedia = segment.seq, true, true
+ sess.lastSequenceAt = fetchEnd
+ sess.segmentDuration += segment.duration
+ dur := sess.segmentDuration
+ m.mu.Lock()
+ sess.lastSequence, sess.hasSequence, sess.wroteMedia = lastSeq, hasSeq, wroteMedia
+ m.mu.Unlock()
+
+ m.commitSessionPart(sess, written, dur)
+ if err := m.saveCheckpoint(sess, func(meta *library.ItemMetadata) {
+ meta.Live.LastSequence, meta.Live.HasSequence = lastSeq, hasSeq
+ meta.Live.PendingFile = partBase
+ meta.Live.PendingBytes, meta.Live.PendingDuration = written, dur
+ }); err != nil {
+ return written, err
+ }
+ newCount++
+ }
+ now := m.now()
+ m.mu.Lock()
+ noSegTimeout := m.noSegmentTimeout
+ pollWait := m.hlsPollInterval
+ m.mu.Unlock()
+
+ if newCount > 0 {
+ lastNew = now
+ } else if noSegTimeout > 0 && now.Sub(lastNew) >= noSegTimeout {
+ return written, &bilibili.SiteError{Site: site.Bilibili, Kind: bilibili.ErrKindNetwork, Message: "超过 10 秒未收到新直播分片"}
+ }
+ if playlist.endList {
+ return written, nil
+ }
+ if pollWait <= 0 {
+ pollWait = time.Duration(math.Max(1, math.Min(5, playlist.targetDuration)) * float64(time.Second))
+ }
+ timer := time.NewTimer(pollWait)
+ select {
+ case <-ctx.Done():
+ timer.Stop()
+ case <-timer.C:
+ }
+ }
+ return written, ctx.Err()
+}
+
+func validLiveInit(raw []byte) bool {
+ file, err := mp4.DecodeFile(bytes.NewReader(raw), mp4.WithDecodeFlags(mp4.DecStartOnMoof))
+ if err != nil || file == nil {
+ return false
+ }
+ moov := file.Moov
+ if file.Init != nil {
+ moov = file.Init.Moov
+ }
+ if moov == nil {
+ return false
+ }
+ for _, track := range moov.Traks {
+ if track.Mdia != nil && track.Mdia.Hdlr != nil && track.Mdia.Hdlr.HandlerType == "vide" {
+ return true
+ }
+ }
+ return false
+}
+
+func validLiveFragment(raw []byte) bool {
+ file, err := mp4.DecodeFile(bytes.NewReader(raw), mp4.WithDecodeFlags(mp4.DecStartOnMoof))
+ if err != nil || file == nil || len(file.Segments) == 0 {
+ return false
+ }
+ for _, segment := range file.Segments {
+ for _, fragment := range segment.Fragments {
+ if fragment.Moof != nil && fragment.Mdat != nil && len(fragment.Mdat.Data) > 0 {
+ return true
+ }
+ }
+ }
+ return false
+}
diff --git a/internal/live/incidents.go b/internal/live/incidents.go
index 686cc24..2c4c790 100644
--- a/internal/live/incidents.go
+++ b/internal/live/incidents.go
@@ -39,6 +39,23 @@ func (m *Manager) SetNowFunc(fn func() time.Time) {
m.mu.Unlock()
}
+func (m *Manager) now() time.Time {
+ m.mu.Lock()
+ fn := m.nowFunc
+ m.mu.Unlock()
+ if fn == nil {
+ return time.Now()
+ }
+ return fn()
+}
+
+func (m *Manager) nowLocked() time.Time {
+ if m.nowFunc == nil {
+ return time.Now()
+ }
+ return m.nowFunc()
+}
+
func roundDurationSec(sec float64) float64 {
if sec <= 0 || math.IsNaN(sec) || math.IsInf(sec, 0) {
return 0
@@ -68,6 +85,16 @@ func dropResolvedConvertFailed(list []library.LiveIncident, part string) []libra
return keep
}
+func hasConvertFailedIncident(list []library.LiveIncident, part string) bool {
+ partBase := filepath.Base(strings.TrimSpace(part))
+ for _, inc := range list {
+ if inc.Kind == library.LiveIncidentConvertFailed && inc.Part == partBase {
+ return true
+ }
+ }
+ return false
+}
+
func normalizeSingleIncident(inc library.LiveIncident) (library.LiveIncident, bool) {
inc.Kind = strings.TrimSpace(inc.Kind)
if inc.Kind == "" {
@@ -164,16 +191,6 @@ func (m *Manager) initSessionIncidents(sess *recordSession) {
}
}
-func (m *Manager) syncSessionIncidentsLocked(sess *recordSession) (RoomState, bool) {
- if sess == nil {
- return RoomState{}, false
- }
- if sess.itemMeta.Live != nil {
- sess.itemMeta.Live.Incidents = cloneIncidents(sess.incidents)
- }
- return m.syncSessionRoomStateLocked(sess)
-}
-
func (m *Manager) recordSessionIncident(sess *recordSession, inc library.LiveIncident, notifyState bool) {
if sess == nil {
return
@@ -181,7 +198,7 @@ func (m *Manager) recordSessionIncident(sess *recordSession, inc library.LiveInc
var notify *RoomState
m.mu.Lock()
if inc.At == "" {
- inc.At = m.nowFunc().UTC().Format(time.RFC3339)
+ inc.At = m.nowLocked().UTC().Format(time.RFC3339)
}
sess.incidents, _, _ = appendCoalescedIncident(sess.incidents, inc)
if st, ok := m.syncSessionRoomStateLocked(sess); ok && notifyState {
@@ -194,7 +211,9 @@ func (m *Manager) recordSessionIncident(sess *recordSession, inc library.LiveInc
m.mu.Unlock()
if notify != nil && m.onState != nil {
+ leave := sess.enterExternal()
m.onState(*notify)
+ leave()
}
}
@@ -263,7 +282,9 @@ func (m *Manager) markSessionReconnected(sess *recordSession, recoveredAt time.T
m.mu.Unlock()
if notify != nil && m.onState != nil {
+ leave := sess.enterExternal()
m.onState(*notify)
+ leave()
}
}
@@ -301,8 +322,7 @@ func (m *Manager) observeTransferSpeed(
if actualByteRate < mediaByteRate*0.95 {
isSlow = true
}
- }
- if !isSlow && sess.nominalByteRate > 0 && wallSec >= 0.2 {
+ } else if sess.nominalByteRate > 0 && wallSec >= 0.2 {
if actualByteRate < sess.nominalByteRate*0.90 {
isSlow = true
}
@@ -353,7 +373,9 @@ func (m *Manager) observeTransferSpeed(
m.mu.Unlock()
if notify != nil && m.onState != nil {
+ leave := sess.enterExternal()
m.onState(*notify)
+ leave()
}
}
@@ -391,7 +413,7 @@ func isDiskFullError(err error) bool {
if err == nil {
return false
}
- if errors.Is(err, syscall.ENOSPC) {
+ if errors.Is(err, syscall.ENOSPC) || isPlatformDiskFullError(err) {
return true
}
msg := err.Error()
diff --git a/internal/live/incidents_test.go b/internal/live/incidents_test.go
index 9442d60..438dae9 100644
--- a/internal/live/incidents_test.go
+++ b/internal/live/incidents_test.go
@@ -59,10 +59,10 @@ func splitSyntheticHLSInitAndFrag(t *testing.T) ([]byte, []byte) {
return initBuf.Bytes(), fragBuf.Bytes()
}
-// M4-K33: Even when legacy LiveSettings carries MaxConcurrentRecordings=1,
+// Even when legacy LiveSettings carries MaxConcurrentRecordings=1,
// starting 5 live recordings simultaneously (3 Bilibili HLS + 2 Douyin HTTP-FLV) succeeds for all 5
// with zero "已达到同时录制上限" errors, and all 5 finalize valid MP4 segments.
-func TestConcurrentRecordingsUnlimited_M4K33(t *testing.T) {
+func TestConcurrentRecordingsUnlimited(t *testing.T) {
initBytes, fragBytes := splitSyntheticHLSInitAndFrag(t)
flvBytes := buildSyntheticFLVBytes(t, "avc", 45)
@@ -264,11 +264,11 @@ func TestConcurrentRecordingsUnlimited_M4K33(t *testing.T) {
}
}
-// M4-K34: Collects all 5 incident types (lost_segments, reconnect, slow, disk, convert_failed)
+// Collects all 5 incident types (lost_segments, reconnect, slow, disk, convert_failed)
// strictly from recording data with 0 extra site/CDN requests, injectable clock (no 30s sleep),
// real-time visibility while recording, item.json persistence without URL/Cookie leaks,
// 1-minute per-kind coalescing, and 200-entry cap.
-func TestLiveRecordingIncidentsAllFiveKindsCoalesceAndCap_M4K34(t *testing.T) {
+func TestLiveRecordingIncidentsAllFiveKindsCoalesceAndCap(t *testing.T) {
// --- Part A: Coalescing (<= 60s merges, > 60s separates) & 200-entry cap ---
var coalesced []library.LiveIncident
baseT := time.Date(2026, 11, 15, 10, 0, 0, 0, time.UTC)
@@ -531,7 +531,7 @@ func TestLiveRecordingIncidentsAllFiveKindsCoalesceAndCap_M4K34(t *testing.T) {
}
waitUntilRoomIdle(t, mgr, "douyin:live:7400000000000007801", 6*time.Second)
- // --- Part D: Orphan corrupt .part recovery -> records 'convert_failed' with F-004 reason ---
+ // --- Part D: Orphan corrupt .part recovery -> records 'convert_failed' reason ---
orphanDir := filepath.Join(cacheDir, "bilibili", "live", "9602-corrupt")
if err := os.MkdirAll(orphanDir, 0o755); err != nil {
t.Fatal(err)
diff --git a/internal/live/live_preview.go b/internal/live/live_preview.go
index 0618470..fd0f670 100644
--- a/internal/live/live_preview.go
+++ b/internal/live/live_preview.go
@@ -107,7 +107,9 @@ func (m *Manager) beginSessionPart(sess *recordSession, partIndex int, partPath
}
m.mu.Unlock()
if notify != nil && m.onState != nil {
+ leave := sess.enterExternal()
m.onState(*notify)
+ leave()
}
}
@@ -130,7 +132,9 @@ func (m *Manager) commitSessionPart(sess *recordSession, bytesWritten int64, dur
}
m.mu.Unlock()
if notify != nil && m.onState != nil {
+ leave := sess.enterExternal()
m.onState(*notify)
+ leave()
}
}
@@ -158,7 +162,9 @@ func (m *Manager) endSessionPart(sess *recordSession) {
}
m.mu.Unlock()
if notify != nil && m.onState != nil {
+ leave := sess.enterExternal()
m.onState(*notify)
+ leave()
}
}
@@ -179,32 +185,8 @@ func (m *Manager) syncSessionRoomStateLocked(sess *recordSession) (RoomState, bo
if !ok {
return RoomState{}, false
}
- if st.Site == "" {
- st.Site = string(site.Bilibili)
- }
- if st.AccountUID == "" && st.UID > 0 {
- st.AccountUID = strconv.FormatInt(st.UID, 10)
- }
- if st.RoomIDStr == "" && st.RoomID > 0 {
- st.RoomIDStr = strconv.FormatInt(st.RoomID, 10)
- st.RoomKey = "bilibili:live:" + st.RoomIDStr
- }
- st.Recording = true
- st.RecordSession = sess.sessionID
- st.RecordDurationSec = m.nowFunc().Sub(sess.startedAt).Seconds()
- st.RecordBytes = sess.bytesTotal
- st.RecordSegments = len(sess.segments)
- st.RecordItemDir = sess.itemDir
- if sess.quality > 0 {
- st.Quality = sess.quality
- }
- if sess.qualityName != "" {
- st.QualityName = sess.qualityName
- }
- if sess.codec != "" {
- st.Codec = sess.codec
- }
- hydrateSessionPreviewFieldsLocked(&st, sess)
+ m.normalizeBilibiliRoomStateLocked(&st)
+ m.hydrateBilibiliStateFromSessionLocked(&st, sess)
m.states[sess.roomID] = st
return st, true
}
@@ -224,17 +206,17 @@ func (m *Manager) RecordingPreview(key string) (RecordingPreview, bool) {
if sess := m.matchBilibiliSessionLocked(target); sess != nil {
st := m.states[sess.roomID]
- return m.buildBilibiliPreviewLocked(st, sess), true
+ return m.buildPreviewLocked(site.Bilibili, st, sess), true
}
if sess := m.matchDouyinSessionLocked(target); sess != nil {
st := m.douyinStates[sess.stateKey]
- return m.buildDouyinPreviewLocked(st, sess), true
+ return m.buildPreviewLocked(site.Douyin, st, sess), true
}
if st, ok := m.matchBilibiliStateLocked(target); ok {
- return m.buildBilibiliPreviewLocked(st, nil), true
+ return m.buildPreviewLocked(site.Bilibili, st, nil), true
}
if st, ok := m.matchDouyinStateLocked(target); ok {
- return m.buildDouyinPreviewLocked(st, nil), true
+ return m.buildPreviewLocked(site.Douyin, st, nil), true
}
return RecordingPreview{}, false
}
@@ -243,10 +225,13 @@ func (m *Manager) matchBilibiliSessionLocked(target string) *recordSession {
trimmed := target
switch {
case strings.HasPrefix(target, "bilibili:live:"):
- trimmed = strings.TrimPrefix(target, "bilibili:live:")
+ trimmed = strings.TrimSpace(strings.TrimPrefix(target, "bilibili:live:"))
+ if trimmed == "" {
+ return nil
+ }
case strings.HasPrefix(target, "bilibili:user:"):
- uid, err := strconv.ParseInt(strings.TrimPrefix(target, "bilibili:user:"), 10, 64)
- if err != nil {
+ uid, err := strconv.ParseInt(strings.TrimSpace(strings.TrimPrefix(target, "bilibili:user:")), 10, 64)
+ if err != nil || uid <= 0 {
return nil
}
for _, sess := range m.sessions {
@@ -256,8 +241,8 @@ func (m *Manager) matchBilibiliSessionLocked(target string) *recordSession {
}
return nil
case strings.HasPrefix(target, "bilibili:"):
- rest := strings.TrimPrefix(target, "bilibili:")
- if num, err := strconv.ParseInt(rest, 10, 64); err == nil {
+ rest := strings.TrimSpace(strings.TrimPrefix(target, "bilibili:"))
+ if num, err := strconv.ParseInt(rest, 10, 64); err == nil && num > 0 {
if sess := m.sessions[num]; sess != nil {
return sess
}
@@ -269,18 +254,25 @@ func (m *Manager) matchBilibiliSessionLocked(target string) *recordSession {
}
return nil
case strings.HasPrefix(target, "live:"):
- sid := strings.TrimPrefix(target, "live:")
+ sid := strings.TrimSpace(strings.TrimPrefix(target, "live:"))
+ if sid == "" {
+ return nil
+ }
for _, sess := range m.sessions {
- if sess != nil && sess.sessionID == sid {
+ if sess != nil && sess.sessionID != "" && sess.sessionID == sid {
return sess
}
}
+ return nil
case strings.HasPrefix(target, "douyin:"):
return nil
}
+ if trimmed == "" {
+ return nil
+ }
for _, sess := range m.sessions {
- if sess != nil && sess.sessionID == trimmed {
+ if sess != nil && sess.sessionID != "" && sess.sessionID == trimmed {
return sess
}
}
@@ -298,20 +290,24 @@ func (m *Manager) matchBilibiliSessionLocked(target string) *recordSession {
}
func (m *Manager) matchDouyinSessionLocked(target string) *recordSession {
- candidates := []string{target}
- switch {
- case strings.HasPrefix(target, "bilibili:"):
+ if strings.HasPrefix(target, "bilibili:") {
return nil
- case strings.HasPrefix(target, "douyin:live:"):
- candidates = append(candidates, strings.TrimPrefix(target, "douyin:live:"))
- case strings.HasPrefix(target, "douyin:user:"):
- candidates = append(candidates, strings.TrimPrefix(target, "douyin:user:"))
- case strings.HasPrefix(target, "douyin:web:"):
- candidates = append(candidates, strings.TrimPrefix(target, "douyin:web:"))
- case strings.HasPrefix(target, "douyin:"):
- candidates = append(candidates, strings.TrimPrefix(target, "douyin:"))
- case strings.HasPrefix(target, "live:"):
- candidates = append(candidates, strings.TrimPrefix(target, "live:"))
+ }
+ var candidates []string
+ hadPrefix := false
+ for _, pfx := range []string{"douyin:live:", "douyin:user:", "douyin:web:", "douyin:", "live:"} {
+ if strings.HasPrefix(target, pfx) {
+ hadPrefix = true
+ rest := strings.TrimSpace(strings.TrimPrefix(target, pfx))
+ if rest == "" {
+ return nil
+ }
+ candidates = append(candidates, target, rest)
+ break
+ }
+ }
+ if !hadPrefix {
+ candidates = []string{target}
}
for _, c := range candidates {
@@ -325,7 +321,7 @@ func (m *Manager) matchDouyinSessionLocked(target string) *recordSession {
if sess == nil {
continue
}
- if sess.stateKey == c || sess.accountUID == c || sess.webRID == c || sess.roomIDStr == c || sess.sessionID == c {
+ if sess.stateKey == c || sess.accountUID == c || (sess.webRID != "" && sess.webRID == c) || sess.roomIDStr == c || sess.sessionID == c {
return sess
}
}
@@ -339,19 +335,30 @@ func (m *Manager) matchBilibiliStateLocked(target string) (RoomState, bool) {
}
trimmed := target
byUIDOnly := false
+ hasBiliPrefix := false
switch {
case strings.HasPrefix(target, "bilibili:live:"):
- trimmed = strings.TrimPrefix(target, "bilibili:live:")
+ trimmed = strings.TrimSpace(strings.TrimPrefix(target, "bilibili:live:"))
+ hasBiliPrefix = true
case strings.HasPrefix(target, "bilibili:user:"):
- trimmed = strings.TrimPrefix(target, "bilibili:user:")
+ trimmed = strings.TrimSpace(strings.TrimPrefix(target, "bilibili:user:"))
byUIDOnly = true
+ hasBiliPrefix = true
case strings.HasPrefix(target, "bilibili:"):
- trimmed = strings.TrimPrefix(target, "bilibili:")
+ trimmed = strings.TrimSpace(strings.TrimPrefix(target, "bilibili:"))
+ hasBiliPrefix = true
+ }
+ if hasBiliPrefix && trimmed == "" {
+ return RoomState{}, false
}
num, err := strconv.ParseInt(trimmed, 10, 64)
if err != nil || num <= 0 {
+ sid := strings.TrimSpace(strings.TrimPrefix(target, "live:"))
+ if sid == "" {
+ return RoomState{}, false
+ }
for _, st := range m.states {
- if target != "" && st.RecordSession == strings.TrimPrefix(target, "live:") {
+ if st.RecordSession != "" && st.RecordSession == sid {
return st, true
}
}
@@ -374,16 +381,19 @@ func (m *Manager) matchDouyinStateLocked(target string) (RoomState, bool) {
if strings.HasPrefix(target, "bilibili:") {
return RoomState{}, false
}
- if st, ok := m.douyinStates[target]; ok {
- return m.hydrateDouyinStateLocked(st), true
- }
trimmed := target
for _, pfx := range []string{"douyin:live:", "douyin:user:", "douyin:web:", "douyin:", "live:"} {
if strings.HasPrefix(target, pfx) {
- trimmed = strings.TrimPrefix(target, pfx)
+ trimmed = strings.TrimSpace(strings.TrimPrefix(target, pfx))
+ if trimmed == "" {
+ return RoomState{}, false
+ }
break
}
}
+ if st, ok := m.douyinStates[target]; ok {
+ return m.hydrateDouyinStateLocked(st), true
+ }
if st, ok := m.douyinStates["douyin:live:"+trimmed]; ok {
return m.hydrateDouyinStateLocked(st), true
}
@@ -391,121 +401,22 @@ func (m *Manager) matchDouyinStateLocked(target string) (RoomState, bool) {
return m.hydrateDouyinStateLocked(st), true
}
for _, st := range m.douyinStates {
- if st.RoomIDStr == trimmed || st.AccountUID == trimmed || st.WebRID == trimmed || st.RoomKey == trimmed {
+ if st.RoomIDStr == trimmed || st.AccountUID == trimmed || (st.WebRID != "" && st.WebRID == trimmed) || st.RoomKey == trimmed || (st.RecordSession != "" && st.RecordSession == trimmed) {
return m.hydrateDouyinStateLocked(st), true
}
}
return RoomState{}, false
}
-func (m *Manager) buildBilibiliPreviewLocked(st RoomState, sess *recordSession) RecordingPreview {
- roomID := st.RoomID
- uid := st.UID
- uname := st.Uname
- title := st.Title
- codec := st.Codec
- quality := st.Quality
- qualityName := st.QualityName
- transport := firstNonEmpty(st.Transport, string(site.LiveTransportHLSFMP4))
- itemDir := st.RecordItemDir
- stopReason := st.StopReason
- lastErr := st.LastError
- durSec := st.RecordDurationSec
- speedBps := st.RecordSpeedBps
- bytesWritten := st.RecordBytes
- segments := st.RecordSegments
- incidents := cloneIncidents(st.Incidents)
-
- var partPath, previewReason string
- var partIndex int
- var partBytes int64
- var partDur float64
- var partReady, previewSupported, recording bool
-
- if sess != nil {
- recording = true
- if sess.roomID > 0 {
- roomID = sess.roomID
- }
- if sess.uid > 0 {
- uid = sess.uid
- }
- uname = firstNonEmpty(uname, sess.uname)
- title = firstNonEmpty(title, sess.title)
- codec = firstNonEmpty(sess.codec, codec)
- if sess.quality > 0 {
- quality = sess.quality
- }
- qualityName = firstNonEmpty(sess.qualityName, qualityName)
- transport = firstNonEmpty(sess.streamTransport, transport)
- itemDir = firstNonEmpty(sess.itemDir, itemDir)
- stopReason = firstNonEmpty(sess.stopReason, stopReason)
- lastErr = firstNonEmpty(sess.lastErr, lastErr)
- durSec = m.nowFunc().Sub(sess.startedAt).Seconds()
- if sess.lastSpeedBps > 0 {
- speedBps = sess.lastSpeedBps
- }
- bytesWritten = sess.bytesTotal
- segments = len(sess.segments)
- incidents = cloneIncidents(sess.incidents)
- partPath = sess.activePartPath
- partIndex = sess.activePartIndex
- partBytes = sess.activePartBytes
- partDur = sess.activePartDur
- partReady = sess.activePartReady
- previewSupported = sess.previewSupport
- previewReason = sess.previewReason
- }
- if qualityName == "" && quality > 0 {
- qualityName = bilibili.LiveQualityFallbackName(quality)
- }
- roomStr := st.RoomIDStr
- if roomStr == "" && roomID > 0 {
- roomStr = strconv.FormatInt(roomID, 10)
- }
- uidStr := st.AccountUID
- if uidStr == "" && uid > 0 {
- uidStr = strconv.FormatInt(uid, 10)
- }
- recKey := st.RoomKey
- if recKey == "" && roomStr != "" {
- recKey = "bilibili:live:" + roomStr
- }
-
- return RecordingPreview{
- RecordingKey: recKey,
- Site: string(site.Bilibili),
- AccountUID: uidStr,
- RoomID: roomID,
- RoomIDStr: roomStr,
- Uname: uname,
- Title: title,
- Codec: codec,
- Quality: quality,
- QualityName: qualityName,
- Transport: transport,
- AudioOnly: false,
- Recording: recording,
- PartPath: partPath,
- PartIndex: partIndex,
- PartBytes: partBytes,
- PartDurationSec: partDur,
- PartReady: partReady,
- PreviewSupported: previewSupported,
- PreviewReason: previewReason,
- ItemDir: itemDir,
- DurationSec: durSec,
- SpeedBps: speedBps,
- BytesWritten: bytesWritten,
- Segments: segments,
- Incidents: incidents,
- StopReason: stopReason,
- LastError: lastErr,
+func (m *Manager) buildPreviewLocked(siteID site.ID, st RoomState, sess *recordSession) RecordingPreview {
+ isDouyin := siteID == site.Douyin
+ defaultTransport := string(site.LiveTransportHLSFMP4)
+ if isDouyin {
+ defaultTransport = string(site.LiveTransportHTTPFLV)
}
-}
-func (m *Manager) buildDouyinPreviewLocked(st RoomState, sess *recordSession) RecordingPreview {
roomID := st.RoomID
+ uid := st.UID
roomStr := st.RoomIDStr
uidStr := st.AccountUID
webRID := st.WebRID
@@ -514,8 +425,8 @@ func (m *Manager) buildDouyinPreviewLocked(st RoomState, sess *recordSession) Re
codec := st.Codec
quality := st.Quality
qualityName := st.QualityName
- transport := firstNonEmpty(st.Transport, string(site.LiveTransportHTTPFLV))
- audioOnly := st.AudioOnly || st.LiveState == site.LiveStateAudioOnly
+ transport := firstNonEmpty(st.Transport, defaultTransport)
+ audioOnly := isDouyin && (st.AudioOnly || st.LiveState == site.LiveStateAudioOnly)
itemDir := st.RecordItemDir
stopReason := st.StopReason
lastErr := st.LastError
@@ -539,6 +450,9 @@ func (m *Manager) buildDouyinPreviewLocked(st RoomState, sess *recordSession) Re
if sess.roomID > 0 {
roomID = sess.roomID
}
+ if sess.uid > 0 {
+ uid = sess.uid
+ }
roomStr = firstNonEmpty(sess.roomIDStr, roomStr)
uidStr = firstNonEmpty(sess.accountUID, uidStr)
webRID = firstNonEmpty(sess.webRID, webRID)
@@ -550,11 +464,13 @@ func (m *Manager) buildDouyinPreviewLocked(st RoomState, sess *recordSession) Re
}
qualityName = firstNonEmpty(sess.qualityName, qualityName)
transport = firstNonEmpty(sess.streamTransport, transport)
- audioOnly = audioOnly || sess.audioOnly
+ if isDouyin {
+ audioOnly = audioOnly || sess.audioOnly
+ }
itemDir = firstNonEmpty(sess.itemDir, itemDir)
stopReason = firstNonEmpty(sess.stopReason, stopReason)
lastErr = firstNonEmpty(sess.lastErr, lastErr)
- durSec = m.nowFunc().Sub(sess.startedAt).Seconds()
+ durSec = m.nowLocked().Sub(sess.startedAt).Seconds()
if sess.lastSpeedBps > 0 {
speedBps = sess.lastSpeedBps
}
@@ -569,17 +485,23 @@ func (m *Manager) buildDouyinPreviewLocked(st RoomState, sess *recordSession) Re
previewSupported = sess.previewSupport
previewReason = sess.previewReason
}
+ if !isDouyin && qualityName == "" && quality > 0 {
+ qualityName = bilibili.LiveQualityFallbackName(quality)
+ }
if roomStr == "" && roomID > 0 {
roomStr = strconv.FormatInt(roomID, 10)
}
+ if !isDouyin && uidStr == "" && uid > 0 {
+ uidStr = strconv.FormatInt(uid, 10)
+ }
recKey := st.RoomKey
if recKey == "" && roomStr != "" {
- recKey = "douyin:live:" + roomStr
+ recKey = string(siteID) + ":live:" + roomStr
}
return RecordingPreview{
RecordingKey: recKey,
- Site: string(site.Douyin),
+ Site: string(siteID),
AccountUID: uidStr,
RoomID: roomID,
RoomIDStr: roomStr,
diff --git a/internal/live/live_preview_test.go b/internal/live/live_preview_test.go
index 138e11c..ff93904 100644
--- a/internal/live/live_preview_test.go
+++ b/internal/live/live_preview_test.go
@@ -34,8 +34,6 @@ func TestBilibiliHLSRecordingPreviewStateRolloverAndZeroExtraHTTP(t *testing.T)
fragBytes := fragBuf.Bytes()
var totalHTTPHits atomic.Int64
- var triggerRollover atomic.Bool
- var servedRolloverErr atomic.Bool
var srvURL string
mux := http.NewServeMux()
@@ -105,14 +103,6 @@ func TestBilibiliHLSRecordingPreviewStateRolloverAndZeroExtraHTTP(t *testing.T)
})
mux.HandleFunc("/hls/index.m3u8", func(w http.ResponseWriter, r *http.Request) {
totalHTTPHits.Add(1)
- if triggerRollover.Load() {
- if servedRolloverErr.CompareAndSwap(false, true) {
- w.WriteHeader(http.StatusBadGateway)
- return
- }
- _, _ = w.Write([]byte("#EXTM3U\n#EXT-X-VERSION:7\n#EXT-X-TARGETDURATION:1\n#EXT-X-MEDIA-SEQUENCE:20\n#EXT-X-MAP:URI=\"/hls/init.mp4\"\n#EXTINF:1.0,\n/hls/seg2.m4s\n"))
- return
- }
_, _ = w.Write([]byte("#EXTM3U\n#EXT-X-VERSION:7\n#EXT-X-TARGETDURATION:1\n#EXT-X-MEDIA-SEQUENCE:10\n#EXT-X-MAP:URI=\"/hls/init.mp4\"\n#EXTINF:1.0,\n/hls/seg1.m4s\n"))
})
mux.HandleFunc("/hls/init.mp4", func(w http.ResponseWriter, r *http.Request) {
@@ -191,15 +181,7 @@ func TestBilibiliHLSRecordingPreviewStateRolloverAndZeroExtraHTTP(t *testing.T)
t.Fatalf("preview queries triggered %d unexpected HTTP hits", got-hitsBefore)
}
- // Restore fast poll and trigger disconnect rollover into part-002.mp4.part!
- liveMgr.mu.Lock()
- liveMgr.hlsPollInterval = 25 * time.Millisecond
- liveMgr.mu.Unlock()
- triggerRollover.Store(true)
-
- // Wait for part-002.mp4.part to become active & ready (note: existing timer had 10s left from above,
- // so let's also verify stop/start or wait if needed — wait: recordHLSSegment uses time.After(m.hlsPollInterval) on NEXT iteration!).
- // Wait: the goroutine is currently sleeping in <-time.After(40ms) or <-time.After(10s)! Let's avoid setting 10s above by gating HTTP count on a dedicated counter or short sleep!
+ // Stop the active recording cleanly and verify part-001.mp4 finalizes and preview resets.
_, _ = liveMgr.StopRecording(9001)
waitUntilRoomIdle(t, liveMgr, "bilibili:live:9001", 4*time.Second)
diff --git a/internal/live/live_test.go b/internal/live/live_test.go
index 4998c6c..a0bcc52 100644
--- a/internal/live/live_test.go
+++ b/internal/live/live_test.go
@@ -22,7 +22,7 @@ import (
"github.com/chialecode/trace/internal/subscription"
)
-// C32: Live state transitions (0/2 -> 1 notifies, 2=carousel does NOT notify/record),
+// Live state transitions (0/2 -> 1 notifies, 2=carousel does NOT notify/record),
// HLS fMP4 recording, and disconnect rollover into registered part files.
func TestLiveTransitionsCarouselFilterAndRecordingRollover(t *testing.T) {
vM4S, err := download.BuildSyntheticVideoM4S(30, 30)
@@ -222,13 +222,18 @@ func TestLiveTransitionsCarouselFilterAndRecordingRollover(t *testing.T) {
// Wait for recording session to finish after ENDLIST.
deadline := time.Now().Add(5 * time.Second)
+ finished := false
for time.Now().Before(deadline) {
rooms := liveMgr.ListRooms()
if len(rooms) == 1 && !rooms[0].Recording {
+ finished = true
break
}
time.Sleep(25 * time.Millisecond)
}
+ if !finished {
+ t.Fatalf("timed out waiting for room 8888 to finish recording: %+v", liveMgr.ListRooms())
+ }
for _, name := range []string{"part-001.mp4", "part-002.mp4", "item.json"} {
p := filepath.Join(stRec.RecordItemDir, name)
@@ -257,9 +262,9 @@ func TestLiveTransitionsCarouselFilterAndRecordingRollover(t *testing.T) {
}
}
-// C32 & R-14: 60s status batch cache, HLS sequence/discontinuity/MAP rollover,
-// conversion failure keeping .part as partial, disk space < 1 GiB stop, maxRecordings limit,
-// and manual stop suppressing auto-restart during the same broadcast.
+// 60s status batch cache, HLS sequence/discontinuity/MAP rollover,
+// conversion failure keeping .part as partial, disk space < 1 GiB stop,
+// unlimited concurrent recordings, and manual stop suppressing auto-restart.
func TestLiveStatusBatchCacheAndHLSRecorder(t *testing.T) {
vM4S, err := download.BuildSyntheticVideoM4S(30, 30)
if err != nil {
@@ -421,8 +426,8 @@ func TestLiveStatusBatchCacheAndHLSRecorder(t *testing.T) {
liveMgr.hlsPollInterval = 20 * time.Millisecond
liveMgr.reconnectWait = 20 * time.Millisecond
- now := time.Date(2026, 11, 7, 15, 0, 0, 0, time.UTC)
- liveMgr.nowFunc = func() time.Time { return now }
+ clock := newFakeAdvanceClock(time.Date(2026, 11, 7, 15, 0, 0, 0, time.UTC))
+ liveMgr.SetNowFunc(clock.Now)
var freeDisk atomic.Uint64
freeDisk.Store(10 << 30)
liveMgr.freeBytesFunc = func(string) (uint64, error) { return freeDisk.Load(), nil }
@@ -434,12 +439,12 @@ func TestLiveStatusBatchCacheAndHLSRecorder(t *testing.T) {
if err != nil || len(st1) != 2 || statusHits.Load() != 1 {
t.Fatalf("Status call 1: len=%d hits=%d err=%v", len(st1), statusHits.Load(), err)
}
- now = now.Add(30 * time.Second)
+ clock.Advance(30 * time.Second)
_, err = liveMgr.Status(ctx, []int64{2001, 2002})
if err != nil || statusHits.Load() != 1 {
t.Fatalf("Status call within 60s should use cache, hits=%d err=%v", statusHits.Load(), err)
}
- now = now.Add(31 * time.Second)
+ clock.Advance(31 * time.Second)
_, err = liveMgr.Status(ctx, []int64{2001})
if err != nil || statusHits.Load() != 2 {
t.Fatalf("Status call after 60s should re-fetch, hits=%d err=%v", statusHits.Load(), err)
@@ -459,6 +464,7 @@ func TestLiveStatusBatchCacheAndHLSRecorder(t *testing.T) {
}
// Wait for 9001 to finish
deadline := time.Now().Add(5 * time.Second)
+ finished9001 := false
for time.Now().Before(deadline) {
rooms := liveMgr.ListRooms()
active := false
@@ -468,24 +474,29 @@ func TestLiveStatusBatchCacheAndHLSRecorder(t *testing.T) {
}
}
if !active {
+ finished9001 = true
break
}
time.Sleep(20 * time.Millisecond)
}
+ if !finished9001 {
+ t.Fatalf("timed out waiting for room 9001 to finish recording")
+ }
for _, f := range []string{"part-001.mp4", "part-002.mp4"} {
if _, err := os.Stat(filepath.Join(rec1.RecordItemDir, f)); err != nil {
t.Fatalf("expected %s after discontinuity/gap rollover: %v", f, err)
}
}
- // 3. Conversion failure preserves .part on disk and marks item "partial" (R-14)
- now = now.Add(10 * time.Second)
+ // 3. Conversion failure preserves .part on disk and marks item "partial"
+ clock.Advance(10 * time.Second)
corruptMode.Store(true)
recCorrupt, err := liveMgr.StartRecording(ctx, 9002)
if err != nil {
t.Fatalf("StartRecording 9002 corrupt: %v", err)
}
deadline = time.Now().Add(5 * time.Second)
+ finished9002 := false
for time.Now().Before(deadline) {
rooms := liveMgr.ListRooms()
active := false
@@ -495,10 +506,14 @@ func TestLiveStatusBatchCacheAndHLSRecorder(t *testing.T) {
}
}
if !active {
+ finished9002 = true
break
}
time.Sleep(20 * time.Millisecond)
}
+ if !finished9002 {
+ t.Fatalf("timed out waiting for room 9002 to finish recording")
+ }
partPath := filepath.Join(recCorrupt.RecordItemDir, "part-001.mp4.part")
if _, err := os.Stat(partPath); err != nil {
t.Fatalf("expected corrupt .part file to be preserved on disk: %v", err)
diff --git a/internal/live/m3u8.go b/internal/live/m3u8.go
new file mode 100644
index 0000000..56d7bc7
--- /dev/null
+++ b/internal/live/m3u8.go
@@ -0,0 +1,233 @@
+package live
+
+import (
+ "math"
+ "net/url"
+ "strconv"
+ "strings"
+)
+
+type m3u8Segment struct {
+ uri string
+ seq int64
+ discontinuity bool
+ mapURI string
+ duration float64
+}
+
+type m3u8Playlist struct {
+ mapURI string
+ targetDuration float64
+ mediaSequence int64
+ hasDiscontinuity bool
+ segments []m3u8Segment
+ endList bool
+ valid bool
+ invalidReason string
+ encrypted bool
+ // variants is set for a multivariant (master) playlist instead of segments.
+ variants []m3u8Variant
+}
+
+type m3u8Variant struct {
+ uri string
+ bandwidth int64
+}
+
+func (p m3u8Playlist) bestVariantInfo() (m3u8Variant, bool) {
+ best := -1
+ for i, v := range p.variants {
+ if v.uri != "" && (best < 0 || v.bandwidth > p.variants[best].bandwidth) {
+ best = i
+ }
+ }
+ if best < 0 {
+ return m3u8Variant{}, false
+ }
+ return p.variants[best], true
+}
+
+// parseM3U8Attributes splits a comma-separated HLS attribute list while respecting quoted strings.
+func parseM3U8Attributes(raw string) [][2]string {
+ var attrs [][2]string
+ for i := 0; i < len(raw); {
+ for i < len(raw) && (raw[i] == ',' || raw[i] == ' ' || raw[i] == '\t') {
+ i++
+ }
+ if i >= len(raw) {
+ break
+ }
+ eq := strings.IndexByte(raw[i:], '=')
+ if eq < 0 {
+ break
+ }
+ key := strings.TrimSpace(raw[i : i+eq])
+ i += eq + 1
+ for i < len(raw) && (raw[i] == ' ' || raw[i] == '\t') {
+ i++
+ }
+ var val string
+ if i < len(raw) && (raw[i] == '"' || raw[i] == '\'') {
+ quote := raw[i]
+ i++
+ start := i
+ for i < len(raw) && raw[i] != quote {
+ i++
+ }
+ val = raw[start:i]
+ if i < len(raw) && raw[i] == quote {
+ i++
+ }
+ for i < len(raw) && raw[i] != ',' {
+ i++
+ }
+ } else {
+ start := i
+ for i < len(raw) && raw[i] != ',' {
+ i++
+ }
+ val = strings.TrimSpace(raw[start:i])
+ }
+ if key != "" {
+ attrs = append(attrs, [2]string{key, val})
+ }
+ }
+ return attrs
+}
+
+func parseM3U8PlaylistDetails(content string, baseURL string) m3u8Playlist {
+ content = strings.TrimPrefix(content, "\uFEFF")
+ baseParsed, _ := url.Parse(baseURL)
+ resolveRef := func(ref string) string {
+ ref = strings.Trim(strings.TrimSpace(ref), `"'`)
+ if ref == "" {
+ return ""
+ }
+ if baseParsed != nil {
+ if u, err := baseParsed.Parse(ref); err == nil {
+ return u.String()
+ }
+ }
+ return ref
+ }
+
+ out := m3u8Playlist{
+ targetDuration: 1.0,
+ mediaSequence: 0,
+ valid: strings.HasPrefix(strings.TrimSpace(content), "#EXTM3U"),
+ }
+ if !out.valid {
+ out.invalidReason = "缺少 #EXTM3U 头"
+ }
+ invalidate := func(reason string) {
+ if out.valid {
+ out.valid, out.invalidReason = false, reason
+ }
+ }
+ var curSeq int64
+ var duration float64
+ nextDisc := false
+ pendingVariant := int64(-1)
+
+ lines := strings.Split(content, "\n")
+ for _, line := range lines {
+ line = strings.TrimSpace(strings.TrimPrefix(line, "\uFEFF"))
+ if line == "" {
+ continue
+ }
+ if strings.HasPrefix(line, "#EXT-X-TARGETDURATION:") {
+ val := strings.TrimSpace(strings.TrimPrefix(line, "#EXT-X-TARGETDURATION:"))
+ if td, err := strconv.ParseFloat(val, 64); err == nil && td > 0 && !math.IsNaN(td) && !math.IsInf(td, 0) {
+ out.targetDuration = td
+ }
+ continue
+ }
+ if strings.HasPrefix(line, "#EXT-X-MEDIA-SEQUENCE:") {
+ val := strings.TrimSpace(strings.TrimPrefix(line, "#EXT-X-MEDIA-SEQUENCE:"))
+ if seq, err := strconv.ParseInt(val, 10, 64); err == nil && seq >= 0 {
+ out.mediaSequence = seq
+ curSeq = seq
+ }
+ continue
+ }
+ if line == "#EXT-X-DISCONTINUITY" {
+ out.hasDiscontinuity = true
+ nextDisc = true
+ continue
+ }
+ if strings.HasPrefix(line, "#EXT-X-KEY:") {
+ method := ""
+ for _, kv := range parseM3U8Attributes(strings.TrimPrefix(line, "#EXT-X-KEY:")) {
+ if strings.EqualFold(kv[0], "METHOD") {
+ method = strings.TrimSpace(kv[1])
+ }
+ }
+ // Sticky encryption flag: once any key specifies a non-NONE method,
+ // a later METHOD=NONE does not clear the playlist's encrypted state.
+ if !strings.EqualFold(method, "NONE") {
+ out.encrypted = true
+ }
+ continue
+ }
+ if strings.HasPrefix(line, "#EXT-X-BYTERANGE:") {
+ invalidate("不支持按字节范围切分的分片")
+ continue
+ }
+ if strings.HasPrefix(line, "#EXT-X-STREAM-INF:") {
+ pendingVariant = 0
+ for _, kv := range parseM3U8Attributes(strings.TrimPrefix(line, "#EXT-X-STREAM-INF:")) {
+ if strings.EqualFold(kv[0], "BANDWIDTH") {
+ if bw, err := strconv.ParseInt(strings.TrimSpace(kv[1]), 10, 64); err == nil && bw > 0 {
+ pendingVariant = bw
+ }
+ }
+ }
+ continue
+ }
+ if strings.HasPrefix(line, "#EXTINF:") {
+ value := strings.SplitN(strings.TrimPrefix(line, "#EXTINF:"), ",", 2)[0]
+ duration, _ = strconv.ParseFloat(strings.TrimSpace(value), 64)
+ if duration <= 0 || math.IsNaN(duration) || math.IsInf(duration, 0) {
+ invalidate("分片时长无效")
+ }
+ continue
+ }
+ if strings.HasPrefix(line, "#EXT-X-MAP:") {
+ for _, kv := range parseM3U8Attributes(strings.TrimPrefix(line, "#EXT-X-MAP:")) {
+ switch {
+ case strings.EqualFold(kv[0], "URI"):
+ out.mapURI = resolveRef(kv[1])
+ case strings.EqualFold(kv[0], "BYTERANGE") && strings.TrimSpace(kv[1]) != "":
+ invalidate("不支持按字节范围切分的初始化分片")
+ }
+ }
+ continue
+ }
+ if strings.HasPrefix(line, "#EXT-X-ENDLIST") {
+ out.endList = true
+ continue
+ }
+ if strings.HasPrefix(line, "#") {
+ continue
+ }
+ if pendingVariant >= 0 {
+ out.variants = append(out.variants, m3u8Variant{uri: resolveRef(line), bandwidth: pendingVariant})
+ pendingVariant = -1
+ continue
+ }
+ out.segments = append(out.segments, m3u8Segment{
+ uri: resolveRef(line),
+ seq: curSeq,
+ discontinuity: nextDisc,
+ mapURI: out.mapURI,
+ duration: duration,
+ })
+ if out.mapURI == "" {
+ invalidate("分片缺少 fMP4 初始化分片(EXT-X-MAP)")
+ }
+ curSeq++
+ nextDisc = false
+ duration = 0
+ }
+ return out
+}
diff --git a/internal/live/manager.go b/internal/live/manager.go
index 6fdd3d0..466eac3 100644
--- a/internal/live/manager.go
+++ b/internal/live/manager.go
@@ -3,17 +3,11 @@ package live
import (
"context"
"errors"
- "fmt"
- "io"
- "math"
- "net/http"
- "net/url"
- "os"
- "path/filepath"
"sort"
"strconv"
"strings"
"sync"
+ "sync/atomic"
"time"
"github.com/chialecode/trace/internal/library"
@@ -138,12 +132,25 @@ type recordSession struct {
nominalByteRate float64
pendingReconnectAt time.Time
pendingReconnectHadMedia bool
+ // inExternal tracks active external site-client / callback invocations on this
+ // session so re-entrant StopForSite never deadlocks waiting on doneCh.
+ inExternal atomic.Int32
// saveMu serializes writes of the manifest (item.json); finishDone
// closes when the parts converting in the background are done.
saveMu sync.Mutex
finishDone chan struct{}
}
+func (sess *recordSession) enterExternal() func() {
+ if sess == nil {
+ return func() {}
+ }
+ sess.inExternal.Add(1)
+ return func() {
+ sess.inExternal.Add(-1)
+ }
+}
+
type cachedStatusEntry struct {
status bilibili.LiveUserStatus
fetchedAt time.Time
@@ -152,7 +159,7 @@ type cachedStatusEntry struct {
// Manager coordinates live status polling, transition notifications, and stream recording.
type Manager struct {
mu sync.Mutex
- startMu sync.Mutex
+ starting map[string]chan struct{}
lib *library.Store
subs *subscription.Manager
client *bilibili.Client
@@ -178,6 +185,7 @@ type Manager struct {
flvIdleTimeout time.Duration
douyinStates map[string]RoomState
douyinStatusCache map[string]douyinCachedStatusEntry
+ douyinRawCovers map[string]string
douyinLastAutoPoll map[string]time.Time
douyinWebRIDHints map[string]string
douyinRoomHints map[string]string
@@ -186,8 +194,11 @@ type Manager struct {
douyinStoppedRooms map[string]bool
stopping bool
+ stopDeadline time.Time
finalizeTimeout time.Duration
+ baseCtx context.Context
+ baseCancel context.CancelFunc
pollCancel context.CancelFunc
pollWake chan struct{}
wg sync.WaitGroup
@@ -210,10 +221,9 @@ func NewManager(
onNotify func(Notification),
onState func(RoomState),
) *Manager {
- if liveSettings.MaxConcurrentRecordings <= 0 {
- liveSettings.MaxConcurrentRecordings = 2
- }
+ baseCtx, baseCancel := context.WithCancel(context.Background())
return &Manager{
+ starting: make(map[string]chan struct{}),
lib: lib,
subs: subs,
client: client,
@@ -232,6 +242,7 @@ func NewManager(
flvIdleTimeout: defaultFLVIdleTimeout,
douyinStates: make(map[string]RoomState),
douyinStatusCache: make(map[string]douyinCachedStatusEntry),
+ douyinRawCovers: make(map[string]string),
douyinLastAutoPoll: make(map[string]time.Time),
douyinWebRIDHints: make(map[string]string),
douyinRoomHints: make(map[string]string),
@@ -239,6 +250,8 @@ func NewManager(
douyinSessions: make(map[string]*recordSession),
douyinStoppedRooms: make(map[string]bool),
finalizeTimeout: 30 * time.Second,
+ baseCtx: baseCtx,
+ baseCancel: baseCancel,
pollWake: make(chan struct{}, 1),
hlsPollInterval: 0, // 0 uses #EXT-X-TARGETDURATION clamped to [1s, 5s]
reconnectWait: 6 * time.Second,
@@ -249,6 +262,70 @@ func NewManager(
}
}
+func (m *Manager) baseCtxLocked() context.Context {
+ if m.baseCtx == nil {
+ m.baseCtx, m.baseCancel = context.WithCancel(context.Background())
+ }
+ return m.baseCtx
+}
+
+func (m *Manager) withManagerContext(ctx context.Context) (context.Context, context.CancelFunc) {
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ m.mu.Lock()
+ base := m.baseCtxLocked()
+ m.mu.Unlock()
+ opCtx, cancel := context.WithCancel(ctx)
+ stop := context.AfterFunc(base, cancel)
+ return opCtx, func() {
+ stop()
+ cancel()
+ }
+}
+
+// acquireStartSlot serializes concurrent start attempts for the same key without
+// holding a global mutex across blocking network or storage I/O.
+func (m *Manager) acquireStartSlot(ctx context.Context, siteID site.ID, key string) (func(), error) {
+ for {
+ m.mu.Lock()
+ if m.stopping {
+ m.mu.Unlock()
+ return nil, &site.Error{Site: siteID, Kind: site.ErrKindUnavailable, Message: "应用正在退出,不能开始新的录制"}
+ }
+ if m.starting == nil {
+ m.starting = make(map[string]chan struct{})
+ }
+ waitCh, busy := m.starting[key]
+ if !busy {
+ ch := make(chan struct{})
+ m.starting[key] = ch
+ m.mu.Unlock()
+ var once sync.Once
+ return func() {
+ once.Do(func() {
+ m.mu.Lock()
+ if m.starting[key] == ch {
+ delete(m.starting, key)
+ }
+ close(ch)
+ m.mu.Unlock()
+ })
+ }, nil
+ }
+ baseDone := m.baseCtxLocked().Done()
+ m.mu.Unlock()
+
+ select {
+ case <-waitCh:
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-baseDone:
+ return nil, &site.Error{Site: siteID, Kind: site.ErrKindUnavailable, Message: "应用正在退出,不能开始新的录制"}
+ }
+ }
+}
+
// Start recovers registered recording parts and starts background status polling.
func (m *Manager) Start(parentCtx context.Context) {
m.RecoverOrphanParts()
@@ -258,41 +335,57 @@ func (m *Manager) Start(parentCtx context.Context) {
m.mu.Unlock()
return
}
+ if parentCtx == nil {
+ parentCtx = context.Background()
+ }
m.stopping = false
- ctx, cancel := context.WithCancel(parentCtx)
+ m.stopDeadline = time.Time{}
+ if m.baseCancel != nil {
+ m.baseCancel()
+ }
+ m.baseCtx, m.baseCancel = context.WithCancel(parentCtx)
+ ctx, cancel := context.WithCancel(m.baseCtx)
m.pollCancel = cancel
+ m.wg.Add(1)
m.mu.Unlock()
- m.wg.Add(1)
go m.pollLoop(ctx)
}
// Stop cancels polling and recordings, allowing a bounded finalization window.
func (m *Manager) Stop() {
- m.startMu.Lock()
m.mu.Lock()
m.stopping = true
- cancel := m.pollCancel
+ timeout := m.finalizeTimeout
+ if timeout <= 0 {
+ timeout = 30 * time.Second
+ }
+ m.stopDeadline = time.Now().Add(timeout)
+ pollCancel := m.pollCancel
m.pollCancel = nil
+ baseCancel := m.baseCancel
m.mu.Unlock()
- m.startMu.Unlock()
- if cancel != nil {
- cancel()
+
+ if pollCancel != nil {
+ pollCancel()
+ }
+ if baseCancel != nil {
+ baseCancel()
}
m.CancelRecordings("app_closed")
+
done := make(chan struct{})
go func() { m.wg.Wait(); close(done) }()
+ timer := time.NewTimer(timeout)
+ defer timer.Stop()
select {
case <-done:
- case <-time.After(m.finalizeTimeout):
+ case <-timer.C:
}
}
// UpdateSettings updates live polling and recording settings.
func (m *Manager) UpdateSettings(s settings.LiveSettings) {
- if s.MaxConcurrentRecordings <= 0 {
- s.MaxConcurrentRecordings = 2
- }
m.mu.Lock()
m.liveSettings = s
m.mu.Unlock()
@@ -309,34 +402,57 @@ func (m *Manager) pollLoop(ctx context.Context) {
cfg := m.liveSettings
m.mu.Unlock()
+ var subs []subscription.Subscription
hasBiliAuto := false
hasDouyinAuto := false
+ var biliUIDs []int64
+ seenBili := make(map[int64]bool)
if m.subs != nil {
- if subs, err := m.subs.List(); err == nil {
+ if list, err := m.subs.List(); err == nil {
+ subs = list
for _, sub := range subs {
- if sub.Rules.AutoRecord || sub.LiveAutoRecord {
- for _, acc := range sub.Accounts {
- switch acc.Site {
- case string(site.Douyin):
+ auto := sub.Rules.AutoRecord || sub.LiveAutoRecord
+ includeBili := cfg.PollEnabled || auto
+ for _, acc := range sub.Accounts {
+ switch acc.Site {
+ case string(site.Douyin):
+ if auto {
hasDouyinAuto = true
- case "", string(site.Bilibili):
+ }
+ case "", string(site.Bilibili):
+ if auto {
hasBiliAuto = true
}
+ if includeBili {
+ if uid, err := strconv.ParseInt(acc.UID, 10, 64); err == nil && uid > 0 && !seenBili[uid] {
+ seenBili[uid] = true
+ biliUIDs = append(biliUIDs, uid)
+ }
+ }
}
- if sub.Mid > 0 {
+ }
+ if sub.Mid > 0 {
+ if auto {
hasBiliAuto = true
}
+ if includeBili && !seenBili[sub.Mid] {
+ seenBili[sub.Mid] = true
+ biliUIDs = append(biliUIDs, sub.Mid)
+ }
}
}
}
}
if !cfg.PollEnabled && !hasBiliAuto && !hasDouyinAuto {
+ timer := time.NewTimer(time.Minute)
select {
case <-ctx.Done():
+ timer.Stop()
return
case <-m.pollWake:
+ timer.Stop()
continue
- case <-time.After(time.Minute):
+ case <-timer.C:
continue
}
}
@@ -344,27 +460,9 @@ func (m *Manager) pollLoop(ctx context.Context) {
// Rounds start an interval apart: the Douyin checks spaced through
// the round do not push the next one back.
roundStart := time.Now()
- if (cfg.PollEnabled || hasBiliAuto) && m.client != nil && m.client.HasAuth() && m.subs != nil {
+ if (cfg.PollEnabled || hasBiliAuto) && m.client != nil && m.client.HasAuth() && len(biliUIDs) > 0 {
if !m.isSiteInBackoff(site.Bilibili) {
- var uids []int64
- if list, err := m.subs.List(); err == nil {
- for _, sub := range list {
- if cfg.PollEnabled || sub.Rules.AutoRecord || sub.LiveAutoRecord {
- for _, account := range sub.Accounts {
- if account.Site != "" && account.Site != string(site.Bilibili) {
- continue
- }
- uid, _ := strconv.ParseInt(account.UID, 10, 64)
- if uid > 0 {
- uids = append(uids, uid)
- }
- }
- }
- }
- }
- if len(uids) > 0 {
- _, _ = m.refreshAccounts(bilibili.WithAutomaticRequests(ctx, "live"), uids, true, true)
- }
+ _, _ = m.refreshAccounts(bilibili.WithAutomaticRequests(ctx, "live"), biliUIDs, true, true, true)
}
}
@@ -390,318 +488,6 @@ func (m *Manager) pollLoop(ctx context.Context) {
}
}
-// Status queries live status for the given UIDs using a 60-second in-memory cache and <=50 UID batching (live.md §1).
-func (m *Manager) Status(ctx context.Context, uids []int64) (map[int64]bilibili.LiveUserStatus, error) {
- if err := m.client.RequireAuth("live:status"); err != nil {
- return nil, err
- }
- now := m.nowFunc()
- result := make(map[int64]bilibili.LiveUserStatus, len(uids))
- var uncached []int64
- seen := make(map[int64]bool, len(uids))
-
- m.mu.Lock()
- for _, uid := range uids {
- if uid <= 0 || seen[uid] {
- continue
- }
- seen[uid] = true
- if entry, ok := m.statusCache[uid]; ok && now.Sub(entry.fetchedAt) < statusCacheTTL {
- result[uid] = entry.status
- } else {
- uncached = append(uncached, uid)
- }
- }
- m.mu.Unlock()
-
- if len(uncached) > 0 {
- fetched, err := m.client.LiveStatusByUIDs(ctx, uncached)
- if err != nil {
- return nil, err
- }
- m.mu.Lock()
- for _, uid := range uncached {
- st := fetched[uid]
- if st.UID == 0 {
- st.UID = uid
- }
- m.statusCache[uid] = cachedStatusEntry{
- status: st,
- fetchedAt: now,
- }
- result[uid] = st
- }
- m.mu.Unlock()
- }
- return result, nil
-}
-
-// PollNow queries live status for all subscribed creators (in <=50 UID batches),
-// detects 0/2 -> 1 transitions (ignoring 2=carousel), emits notifications, and triggers auto-recording.
-func (m *Manager) PollNow(ctx context.Context) ([]RoomState, error) {
- return m.refreshAccounts(ctx, nil, true, false)
-}
-
-// RefreshForAccounts reads the live status of the given accounts (cached for
-// 60 seconds). Like a poll round it starts recording a broadcast found live
-// when the account's subscription records broadcasts, so a status refresh on
-// the account page or by an update check does not leave it unrecorded until
-// the next round (dev 2026-11-18).
-func (m *Manager) RefreshForAccounts(ctx context.Context, uids []int64) ([]RoomState, error) {
- return m.refreshAccounts(ctx, uids, false, true)
-}
-
-func (m *Manager) refreshAccounts(ctx context.Context, selected []int64, force, autoRecord bool) ([]RoomState, error) {
- if err := m.client.RequireAuth("live:poll"); err != nil {
- return nil, err
- }
- var subList []subscription.Subscription
- var err error
- if m.subs != nil {
- subList, err = m.subs.List()
- if err != nil {
- return nil, err
- }
- }
-
- subByUID := make(map[int64]subscription.Subscription, len(subList))
- allowed := make(map[int64]bool)
- for _, uid := range selected {
- allowed[uid] = true
- }
- var uids []int64
- for _, s := range subList {
-
- for _, acc := range s.Accounts {
- if acc.Site != "bilibili" {
- continue
- }
- uid, err := strconv.ParseInt(acc.UID, 10, 64)
- if err == nil && uid > 0 && (selected == nil || allowed[uid]) {
- if _, exists := subByUID[uid]; !exists {
- subByUID[uid] = s
- uids = append(uids, uid)
- }
- }
- }
- if s.Mid > 0 && (selected == nil || allowed[s.Mid]) {
- if _, exists := subByUID[s.Mid]; !exists {
- subByUID[s.Mid] = s
- uids = append(uids, s.Mid)
- }
- }
- }
- // A user page can show a creator before they are subscribed. Explicit UI
- // lookups may query these accounts, without enabling rules or notifications.
- for _, uid := range selected {
- if uid > 0 {
- if _, exists := subByUID[uid]; !exists {
- subByUID[uid] = subscription.Subscription{Mid: uid}
- uids = append(uids, uid)
- }
- }
- }
- if len(uids) == 0 {
- return m.ListRooms(), nil
- }
-
- var statusMap map[int64]bilibili.LiveUserStatus
- if force {
- statusMap, err = m.client.LiveStatusByUIDs(ctx, uids)
- } else {
- statusMap, err = m.Status(ctx, uids)
- }
- if err != nil {
- return nil, err
- }
-
- now := m.nowFunc().UTC()
- nowStr := now.Format(time.RFC3339)
- var toAutoRecord []int64
- var notifications []Notification
-
- m.mu.Lock()
- notifyGlobal := m.liveSettings.NotifyOnStart
- for _, uid := range uids {
- sub := subByUID[uid]
- st, ok := statusMap[uid]
- if !ok {
- st = bilibili.LiveUserStatus{
- UID: uid,
- RoomID: sub.RoomID,
- Uname: sub.Uname,
- Face: sub.Face,
- LiveStatus: 0,
- }
- }
- if force {
- m.statusCache[uid] = cachedStatusEntry{status: st, fetchedAt: now}
- }
-
- prev, hadPrev := m.prevLive[uid]
- m.prevLive[uid] = st.LiveStatus
-
- if st.LiveStatus != 1 && st.RoomID > 0 {
- delete(m.stoppedBroadcasts, st.RoomID)
- }
-
- // Transition 0/2 -> 1 triggers notification and auto-record (LiveStatus==2 carousel never triggers).
- if st.LiveStatus == 1 && (!hadPrev || prev != 1) {
- if notifyGlobal && sub.LiveNotify {
- notifications = append(notifications, Notification{
- Site: string(site.Bilibili),
- AccountUID: strconv.FormatInt(uid, 10),
- UID: uid,
- RoomID: st.RoomID,
- RoomIDStr: strconv.FormatInt(st.RoomID, 10),
- Uname: firstNonEmpty(st.Uname, sub.Uname),
- Title: st.Title,
- StartedAt: nowStr,
- })
- }
- }
-
- autoRecEnabled := sub.LiveAutoRecord || sub.Rules.AutoRecord
- if st.LiveStatus == 1 && autoRecEnabled && st.RoomID > 0 {
- if stopped, ok := m.stoppedBroadcasts[st.RoomID]; ok && st.LiveTime > 0 && stopped != st.LiveTime {
- delete(m.stoppedBroadcasts, st.RoomID)
- }
- _, suppressed := m.stoppedBroadcasts[st.RoomID]
- if _, already := m.sessions[st.RoomID]; autoRecord && !m.stopping && !already && !suppressed {
- toAutoRecord = append(toAutoRecord, st.RoomID)
- }
- }
-
- key := st.RoomID
- if key <= 0 {
- key = -uid
- }
- existing := m.states[key]
- recSess := m.sessions[st.RoomID]
- roomState := RoomState{
- UID: uid,
- RoomID: st.RoomID,
- ShortID: st.ShortID,
- Uname: firstNonEmpty(st.Uname, sub.Uname),
- Face: firstNonEmpty(st.Face, sub.Face),
- Title: st.Title,
- Cover: st.Cover,
- AreaName: st.AreaName,
- LiveStatus: st.LiveStatus,
- LiveSince: st.LiveTime,
- StatusText: LiveStatusText(st.LiveStatus),
- Quality: existing.Quality,
- QualityName: existing.QualityName,
- Codec: existing.Codec,
- Recording: recSess != nil,
- Incidents: cloneIncidents(existing.Incidents),
- // The last session's folder stays with its incidents after it ends,
- // so Tasks › 录制异常 shows them on that session only.
- RecordItemDir: existing.RecordItemDir,
- StopReason: existing.StopReason,
- LastError: existing.LastError,
- UpdatedAt: nowStr,
- }
- if recSess != nil {
- roomState.RecordSession = recSess.sessionID
- roomState.RecordBytes = recSess.bytesTotal
- roomState.RecordSegments = len(recSess.segments)
- roomState.RecordItemDir = recSess.itemDir
- roomState.Quality = recSess.quality
- roomState.QualityName = recSess.qualityName
- roomState.Codec = recSess.codec
- hydrateSessionPreviewFieldsLocked(&roomState, recSess)
- }
- m.states[key] = roomState
- for oldKey, state := range m.states {
- if oldKey != key && state.UID == uid {
- delete(m.states, oldKey)
- }
- }
- }
- m.mu.Unlock()
-
- for _, n := range notifications {
- if m.onNotify != nil {
- m.onNotify(n)
- }
- }
- for _, roomID := range toAutoRecord {
- if _, rErr := m.StartRecording(ctx, roomID); rErr != nil {
- m.mu.Lock()
- if st, ok := m.states[roomID]; ok {
- st.LastError = rErr.Error()
- m.states[roomID] = st
- }
- m.mu.Unlock()
- }
- }
-
- return m.ListRooms(), nil
-}
-
-// OpenRoom resolves and inspects a single live room by roomID or shortID.
-func (m *Manager) OpenRoom(ctx context.Context, roomOrShortID int64) (RoomState, error) {
- info, err := m.client.RoomInit(ctx, roomOrShortID)
- if err != nil {
- return RoomState{}, err
- }
-
- var userSt bilibili.LiveUserStatus
- if info.UID > 0 {
- stMap, sErr := m.Status(ctx, []int64{info.UID})
- if sErr != nil {
- return RoomState{}, sErr
- }
- userSt = stMap[info.UID]
- }
-
- now := m.nowFunc().UTC()
- nowStr := now.Format(time.RFC3339)
- m.mu.Lock()
- existing := m.states[info.RoomID]
- recSess := m.sessions[info.RoomID]
- st := RoomState{
- UID: info.UID,
- RoomID: info.RoomID,
- ShortID: info.ShortID,
- Uname: firstNonEmpty(userSt.Uname, fmt.Sprintf("UID %d", info.UID)),
- Face: userSt.Face,
- Title: firstNonEmpty(userSt.Title, fmt.Sprintf("直播间 %d", info.RoomID)),
- Cover: userSt.Cover,
- AreaName: userSt.AreaName,
- LiveStatus: info.LiveStatus,
- LiveSince: max(info.LiveTime, userSt.LiveTime),
- StatusText: LiveStatusText(info.LiveStatus),
- Quality: existing.Quality,
- QualityName: existing.QualityName,
- Codec: existing.Codec,
- Recording: recSess != nil,
- Incidents: cloneIncidents(existing.Incidents),
- // The last session's folder stays with its incidents after it ends,
- // so Tasks › 录制异常 shows them on that session only.
- RecordItemDir: existing.RecordItemDir,
- StopReason: existing.StopReason,
- LastError: existing.LastError,
- UpdatedAt: nowStr,
- }
- if recSess != nil {
- st.RecordSession = recSess.sessionID
- st.RecordBytes = recSess.bytesTotal
- st.RecordSegments = len(recSess.segments)
- st.RecordItemDir = recSess.itemDir
- st.Quality = recSess.quality
- st.QualityName = recSess.qualityName
- st.Codec = recSess.codec
- hydrateSessionPreviewFieldsLocked(&st, recSess)
- } else {
- hydrateSessionPreviewFieldsLocked(&st, nil)
- }
- m.states[info.RoomID] = st
- m.mu.Unlock()
- return st, nil
-}
-
// ListRooms returns all tracked live rooms ordered by LiveStatus (live first) and RoomID.
func (m *Manager) ListRooms() []RoomState {
m.mu.Lock()
@@ -709,39 +495,9 @@ func (m *Manager) ListRooms() []RoomState {
out := make([]RoomState, 0, len(m.states)+len(m.douyinStates))
for _, st := range m.states {
- if st.Site == "" {
- st.Site = string(site.Bilibili)
- }
- if st.AccountUID == "" && st.UID > 0 {
- st.AccountUID = strconv.FormatInt(st.UID, 10)
- }
- if st.RoomIDStr == "" && st.RoomID > 0 {
- st.RoomIDStr = strconv.FormatInt(st.RoomID, 10)
- st.RoomKey = "bilibili:live:" + st.RoomIDStr
- }
+ m.normalizeBilibiliRoomStateLocked(&st)
if sess := m.sessions[st.RoomID]; sess != nil {
- st.Recording = true
- st.RecordSession = sess.sessionID
- st.RecordDurationSec = m.nowFunc().Sub(sess.startedAt).Seconds()
- st.RecordBytes = sess.bytesTotal
- st.RecordSegments = len(sess.segments)
- st.RecordItemDir = sess.itemDir
- if sess.quality > 0 {
- st.Quality = sess.quality
- }
- if sess.qualityName != "" {
- st.QualityName = sess.qualityName
- }
- if sess.codec != "" {
- st.Codec = sess.codec
- }
- if sess.stopReason != "" {
- st.StopReason = sess.stopReason
- }
- if sess.lastErr != "" {
- st.LastError = sess.lastErr
- }
- hydrateSessionPreviewFieldsLocked(&st, sess)
+ m.hydrateBilibiliStateFromSessionLocked(&st, sess)
} else {
st.Recording = false
hydrateSessionPreviewFieldsLocked(&st, nil)
@@ -772,285 +528,29 @@ func (m *Manager) ListRooms() []RoomState {
return out
}
-// StartRecording begins recording a Bilibili live room into /bilibili//lives/-/.
-func (m *Manager) StartRecording(ctx context.Context, roomOrShortID int64) (RoomState, error) {
- m.startMu.Lock()
- defer m.startMu.Unlock()
- m.mu.Lock()
- stopping := m.stopping
- m.mu.Unlock()
- if stopping {
- return RoomState{}, &bilibili.SiteError{Kind: bilibili.ErrKindUnavailable, Message: "应用正在退出,不能开始新的录制"}
- }
- st, err := m.OpenRoom(ctx, roomOrShortID)
- if err != nil {
- return RoomState{}, err
- }
- if st.LiveStatus != 1 {
- return st, &bilibili.SiteError{
- Kind: bilibili.ErrKindUnavailable,
- Message: fmt.Sprintf("直播间当前状态为「%s」,仅在直播中时支持录制", st.StatusText),
- }
- }
- if st.LiveSince <= 0 {
- return st, &bilibili.SiteError{Kind: bilibili.ErrKindSchemaChanged, Message: "站点未返回本场直播的开播时间,无法建立录像条目"}
- }
-
- m.mu.Lock()
- if _, already := m.sessions[st.RoomID]; already {
- m.mu.Unlock()
- return m.OpenRoom(ctx, st.RoomID)
- }
- codecOrder := append([]string(nil), m.liveSettings.CodecOrder...)
- m.mu.Unlock()
-
- cacheRoot := m.lib.CacheDir()
- if m.freeBytesFunc != nil && m.minFreeBytes > 0 {
- freeBytes, fErr := m.freeBytesFunc(cacheRoot)
- if fErr != nil {
- return st, fErr
- }
- if freeBytes < m.minFreeBytes {
- return st, &bilibili.SiteError{Kind: "storage", Message: "磁盘可用空间不足 1 GiB,无法开始录制"}
- }
- }
-
- // Verify play info is accessible and not encrypted (203) before creating session.
- playSel, err := m.client.LiveRoomPlayInfo(ctx, st.RoomID, codecOrder)
- if err != nil {
- return st, err
- }
- if playSel.QualityName == "" && playSel.Quality > 0 {
- playSel.QualityName = bilibili.LiveQualityFallbackName(playSel.Quality)
- }
-
- now := m.nowFunc().UTC()
- sessionID := fmt.Sprintf("%d:%d", st.RoomID, st.LiveSince)
- itemDir, err := library.EnsureWithinRoot(cacheRoot, filepath.Join(cacheRoot, "bilibili", strconv.FormatInt(st.UID, 10), "lives", fmt.Sprintf("%d-%d", st.RoomID, st.LiveSince)))
- if err != nil {
- return st, err
- }
- if err := os.MkdirAll(itemDir, 0o700); err != nil {
- return st, err
- }
-
- meta := library.ItemMetadata{
- Version: 1,
- ID: "live:" + sessionID,
- Site: "bilibili",
- Kind: "live",
- Status: "recording",
- Title: st.Title,
- URL: fmt.Sprintf("https://live.bilibili.com/%d", st.RoomID),
- PubTs: st.LiveSince,
- CachedAt: now.Format(time.RFC3339),
- Author: library.ItemAuthor{
- Mid: st.UID,
- Name: st.Uname,
- Face: st.Face,
- },
- }
- // Look up by the canonical key: "live::" has two colons and
- // would be taken as a full key without the site, never matching, so a
- // recording restarted after an exit or update began a blank item that
- // collided with part-001.mp4 and dropped the earlier parts.
- existing, exists, err := m.lib.GetItem(library.CanonicalItemKey("bilibili", "live", sessionID))
- if err != nil {
- return st, err
- }
- if exists {
- meta = existing
- itemDir = existing.ItemDir
- meta.Status = "recording"
- }
- if meta.Live == nil {
- meta.Live = &library.LiveRecordingInfo{RoomID: st.RoomID, LiveSince: st.LiveSince, StartedAt: now.Format(time.RFC3339)}
- }
- meta.Live.EndedAt, meta.Live.StopReason = "", ""
- meta.Live.Quality = playSel.Quality
- meta.Live.QualityName = playSel.QualityName
- meta.Live.Codec = playSel.Codec
- meta.Live.Source = "manual"
- if bilibili.AutomaticRequestSource(ctx) != "" {
- meta.Live.Source = "auto"
- st.Source = "auto"
- }
- savedMeta, err := m.lib.SaveItem(itemDir, meta)
- if err != nil {
- return st, err
- }
-
- recParent := context.Background()
- if meta.Live.Source == "auto" {
- recParent = bilibili.WithAutomaticRequests(recParent, "live")
- }
- recCtx, recCancel := context.WithCancel(recParent)
- initialTransport := string(site.LiveTransportHLSFMP4)
- if playSel.Format == "flv" || playSel.Protocol == "http_stream" {
- initialTransport = string(site.LiveTransportHTTPFLV)
- }
- sess := &recordSession{
- sessionID: sessionID,
- startedAt: now, reportAt: now,
- roomID: st.RoomID,
- uid: st.UID,
- uname: st.Uname,
- face: st.Face,
- title: st.Title,
- itemDir: itemDir,
- itemMeta: savedMeta,
- cancel: recCancel,
- doneCh: make(chan struct{}),
- nextPart: nextPartNumber(meta), lastSequence: meta.Live.LastSequence, hasSequence: meta.Live.HasSequence,
- quality: playSel.Quality,
- qualityName: playSel.QualityName,
- codec: playSel.Codec,
- streamTransport: initialTransport,
- previewSupport: true,
- previewReason: previewReasonWaitingFirstFragment,
- }
- m.initSessionIncidents(sess)
- for _, media := range meta.Media {
- if media.Role == "live_segment" {
- sess.segments = append(sess.segments, media.Path)
- sess.bytesTotal += media.Bytes
- }
- }
-
- m.mu.Lock()
- m.sessions[st.RoomID] = sess
- st.Recording = true
- st.RecordSession = sessionID
- st.RecordItemDir = itemDir
- st.Quality = playSel.Quality
- st.QualityName = playSel.QualityName
- st.Codec = playSel.Codec
- st.StopReason = ""
- st.LastError = ""
- hydrateSessionPreviewFieldsLocked(&st, sess)
- m.states[st.RoomID] = st
- m.mu.Unlock()
-
- m.wg.Add(1)
- go m.runRecordingSession(recCtx, sess, playSel, codecOrder)
-
- if m.onState != nil {
- m.onState(st)
- }
- return st, nil
-}
-
-// StopRecording stops an active recording for roomID and finalizes item.json,
-// suppressing auto-restart for the remainder of the current broadcast (live.md §3).
-func (m *Manager) StopRecording(roomID int64) (RoomState, error) {
- return m.stopRecordingInternal(roomID, "user_stop", true)
-}
-
-func (m *Manager) stopRecordingInternal(roomID int64, reason string, suppressAutoRestart bool) (RoomState, error) {
+func (m *Manager) checkStartDiskSpace(cacheRoot string, siteID site.ID) error {
m.mu.Lock()
- if suppressAutoRestart {
- m.stoppedBroadcasts[roomID] = m.states[roomID].LiveSince
- }
- sess, ok := m.sessions[roomID]
- if ok && sess != nil && sess.stopReason == "" {
- sess.stopReason = reason
- }
+ freeFn := m.freeBytesFunc
+ minFree := m.minFreeBytes
m.mu.Unlock()
- if !ok || sess == nil {
- m.mu.Lock()
- st := m.states[roomID]
- st.Recording = false
- m.mu.Unlock()
- return st, nil
+ if freeFn == nil || minFree == 0 {
+ return nil
}
-
- sess.cancel()
- select {
- case <-sess.doneCh:
- case <-time.After(m.finalizeTimeout):
- m.mu.Lock()
- state := m.states[roomID]
- m.mu.Unlock()
- return state, &bilibili.SiteError{Kind: "storage", Message: "录制收尾已到时间上限,临时片段会在下次启动时恢复"}
+ freeBytes, fErr := freeFn(cacheRoot)
+ if fErr != nil {
+ return fErr
}
-
- m.mu.Lock()
- st := m.states[roomID]
- st.Recording = false
- st.RecordDurationSec = m.nowFunc().Sub(sess.startedAt).Seconds()
- st.RecordBytes = sess.bytesTotal
- st.RecordSegments = len(sess.segments)
- st.RecordItemDir = sess.itemDir
- st.Incidents = cloneIncidents(sess.incidents)
- st.StopReason = sess.stopReason
- if sess.lastErr != "" {
- st.LastError = sess.lastErr
+ if freeBytes < minFree {
+ return &site.Error{Site: siteID, Kind: site.ErrKindStorage, Message: "磁盘可用空间不足 1 GiB,无法开始录制"}
}
- hydrateSessionPreviewFieldsLocked(&st, nil)
- m.states[roomID] = st
- m.mu.Unlock()
-
- if m.onState != nil {
- m.onState(st)
- }
- return st, nil
-}
-
-func (m *Manager) fetchLiveBytes(ctx context.Context, targetURL string) ([]byte, error) {
- return m.fetchLiveLimitedBytes(ctx, targetURL, 32*1024*1024)
-}
-
-func (m *Manager) fetchLiveLimitedBytes(ctx context.Context, targetURL string, maxBytes int64) ([]byte, error) {
- if err := m.client.ValidateMediaURL(targetURL); err != nil {
- return nil, err
- }
- mediaClient, _ := m.client.MediaHTTPClient()
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil)
- if err != nil {
- return nil, err
- }
- req.Header.Set("User-Agent", bilibili.DefaultUserAgent)
- req.Header.Set("Referer", "https://live.bilibili.com/")
- req.Header.Set("Origin", "https://live.bilibili.com")
-
- resp, err := mediaClient.Do(req)
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
- if resp.StatusCode == http.StatusPreconditionFailed {
- return nil, &bilibili.SiteError{
- Kind: bilibili.ErrKindRiskControl,
- HTTPStatus: resp.StatusCode,
- Message: "直播请求触发风控,已停止录制",
- }
- }
- if resp.StatusCode != http.StatusOK {
- kind := bilibili.ErrKindNetwork
- if resp.StatusCode == 429 {
- kind = bilibili.ErrKindRateLimited
- }
- if resp.StatusCode == 401 {
- kind = bilibili.ErrKindAuthRequired
- }
- return nil, &bilibili.SiteError{Kind: kind, HTTPStatus: resp.StatusCode, Message: "直播节点请求失败"}
- }
- reader := m.client.WrapMediaReader(resp.Body)
- defer reader.Close()
- data, err := io.ReadAll(io.LimitReader(reader, maxBytes+1))
- if err != nil {
- return nil, err
- }
- if int64(len(data)) > maxBytes {
- return nil, &bilibili.SiteError{Kind: bilibili.ErrKindSchemaChanged, Message: "直播响应超过大小上限"}
- }
- return data, nil
+ return nil
}
func (m *Manager) addSessionBytes(sess *recordSession, delta int64) {
m.mu.Lock()
sess.bytesTotal += delta
- elapsed := m.nowFunc().Sub(sess.reportAt)
+ now := m.nowLocked()
+ elapsed := now.Sub(sess.reportAt)
if elapsed < time.Second {
m.mu.Unlock()
return
@@ -1061,7 +561,7 @@ func (m *Manager) addSessionBytes(sess *recordSession, delta int64) {
if sess.siteID == string(site.Douyin) {
st = m.douyinStates[sess.stateKey]
st.RecordBytes = sess.bytesTotal
- st.RecordDurationSec = m.nowFunc().Sub(sess.startedAt).Seconds()
+ st.RecordDurationSec = now.Sub(sess.startedAt).Seconds()
st.RecordSpeedBps = speedBps
st.RecordSegments = len(sess.segments)
st.Recording = true
@@ -1069,193 +569,25 @@ func (m *Manager) addSessionBytes(sess *recordSession, delta int64) {
m.douyinStates[sess.stateKey] = st
} else {
st = m.states[sess.roomID]
+ m.normalizeBilibiliRoomStateLocked(&st)
st.RecordBytes = sess.bytesTotal
- st.RecordDurationSec = m.nowFunc().Sub(sess.startedAt).Seconds()
+ st.RecordDurationSec = now.Sub(sess.startedAt).Seconds()
st.RecordSpeedBps = speedBps
st.RecordSegments = len(sess.segments)
st.Recording = true
hydrateSessionPreviewFieldsLocked(&st, sess)
m.states[sess.roomID] = st
}
- sess.reportAt = m.nowFunc()
+ sess.reportAt = now
sess.reportBytes = sess.bytesTotal
m.mu.Unlock()
if m.onState != nil {
+ leave := sess.enterExternal()
m.onState(st)
+ leave()
}
}
-type m3u8Segment struct {
- uri string
- seq int64
- discontinuity bool
- mapURI string
- duration float64
-}
-
-type m3u8Playlist struct {
- mapURI string
- targetDuration float64
- mediaSequence int64
- hasDiscontinuity bool
- segments []m3u8Segment
- endList bool
- valid bool
- invalidReason string
- encrypted bool
- // variants is set for a multivariant (master) playlist instead of segments.
- variants []m3u8Variant
-}
-
-type m3u8Variant struct {
- uri string
- bandwidth int64
-}
-
-// bestVariant picks the highest-bandwidth variant; ties keep playlist order.
-func (p m3u8Playlist) bestVariant() (string, bool) {
- v, ok := p.bestVariantInfo()
- return v.uri, ok
-}
-
-func (p m3u8Playlist) bestVariantInfo() (m3u8Variant, bool) {
- best := -1
- for i, v := range p.variants {
- if v.uri != "" && (best < 0 || v.bandwidth > p.variants[best].bandwidth) {
- best = i
- }
- }
- if best < 0 {
- return m3u8Variant{}, false
- }
- return p.variants[best], true
-}
-
-func parseM3U8PlaylistDetails(content string, baseURL string) m3u8Playlist {
- baseParsed, _ := url.Parse(baseURL)
- resolveRef := func(ref string) string {
- ref = strings.Trim(strings.TrimSpace(ref), `"'`)
- if ref == "" {
- return ""
- }
- if baseParsed != nil {
- if u, err := baseParsed.Parse(ref); err == nil {
- return u.String()
- }
- }
- return ref
- }
-
- out := m3u8Playlist{
- targetDuration: 1.0,
- mediaSequence: 0,
- valid: strings.HasPrefix(strings.TrimSpace(content), "#EXTM3U"),
- }
- if !out.valid {
- out.invalidReason = "缺少 #EXTM3U 头"
- }
- invalidate := func(reason string) {
- if out.valid {
- out.valid, out.invalidReason = false, reason
- }
- }
- var curSeq int64
- var duration float64
- nextDisc := false
- pendingVariant := int64(-1)
-
- lines := strings.Split(content, "\n")
- for _, line := range lines {
- line = strings.TrimSpace(line)
- if line == "" {
- continue
- }
- if strings.HasPrefix(line, "#EXT-X-TARGETDURATION:") {
- val := strings.TrimSpace(strings.TrimPrefix(line, "#EXT-X-TARGETDURATION:"))
- if td, err := strconv.ParseFloat(val, 64); err == nil && td > 0 && !math.IsNaN(td) && !math.IsInf(td, 0) {
- out.targetDuration = td
- }
- continue
- }
- if strings.HasPrefix(line, "#EXT-X-MEDIA-SEQUENCE:") {
- val := strings.TrimSpace(strings.TrimPrefix(line, "#EXT-X-MEDIA-SEQUENCE:"))
- if seq, err := strconv.ParseInt(val, 10, 64); err == nil && seq >= 0 {
- out.mediaSequence = seq
- curSeq = seq
- }
- continue
- }
- if line == "#EXT-X-DISCONTINUITY" {
- out.hasDiscontinuity = true
- nextDisc = true
- continue
- }
- if strings.HasPrefix(line, "#EXT-X-KEY:") {
- out.encrypted = !strings.Contains(strings.ToUpper(line), "METHOD=NONE")
- continue
- }
- if strings.HasPrefix(line, "#EXT-X-BYTERANGE:") {
- invalidate("不支持按字节范围切分的分片")
- continue
- }
- if strings.HasPrefix(line, "#EXT-X-STREAM-INF:") {
- pendingVariant = 0
- for _, attr := range strings.Split(strings.TrimPrefix(line, "#EXT-X-STREAM-INF:"), ",") {
- if k, v, ok := strings.Cut(strings.TrimSpace(attr), "="); ok && strings.EqualFold(k, "BANDWIDTH") {
- if bw, err := strconv.ParseInt(strings.TrimSpace(v), 10, 64); err == nil && bw > 0 {
- pendingVariant = bw
- }
- }
- }
- continue
- }
- if strings.HasPrefix(line, "#EXTINF:") {
- value := strings.SplitN(strings.TrimPrefix(line, "#EXTINF:"), ",", 2)[0]
- duration, _ = strconv.ParseFloat(value, 64)
- if duration <= 0 || math.IsNaN(duration) || math.IsInf(duration, 0) {
- invalidate("分片时长无效")
- }
- continue
- }
- if strings.HasPrefix(line, "#EXT-X-MAP:") {
- attrs := strings.TrimPrefix(line, "#EXT-X-MAP:")
- for _, part := range strings.Split(attrs, ",") {
- kv := strings.SplitN(strings.TrimSpace(part), "=", 2)
- if len(kv) == 2 && strings.EqualFold(kv[0], "URI") {
- out.mapURI = resolveRef(kv[1])
- }
- }
- continue
- }
- if strings.HasPrefix(line, "#EXT-X-ENDLIST") {
- out.endList = true
- continue
- }
- if strings.HasPrefix(line, "#") {
- continue
- }
- if pendingVariant >= 0 {
- out.variants = append(out.variants, m3u8Variant{uri: resolveRef(line), bandwidth: pendingVariant})
- pendingVariant = -1
- continue
- }
- out.segments = append(out.segments, m3u8Segment{
- uri: resolveRef(line),
- seq: curSeq,
- discontinuity: nextDisc,
- mapURI: out.mapURI,
- duration: duration,
- })
- if out.mapURI == "" {
- invalidate("分片缺少 fMP4 初始化分片(EXT-X-MAP)")
- }
- curSeq++
- nextDisc = false
- duration = 0
- }
- return out
-}
-
// LiveStatusText returns the Chinese label for a Bilibili live_status code.
func LiveStatusText(status int) string {
switch status {
@@ -1286,22 +618,68 @@ func firstNonEmpty(a, b string) string {
return b
}
+func isAutoStartBatchStopError(err error) bool {
+ if err == nil {
+ return false
+ }
+ if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
+ return true
+ }
+ switch liveStopReason(err) {
+ case site.ErrKindAuthRequired, site.ErrKindRiskControl, site.ErrKindRateLimited,
+ site.ErrKindQuota, site.ErrKindBackoff, site.ErrKindStorage:
+ return true
+ }
+ return false
+}
+
// CancelRecordings only signals sessions, so it is safe from inside a site
-// request made by a recording goroutine. Normal session cleanup still runs.
+// request made by a recording goroutine. Existing stop reasons are preserved.
func (m *Manager) CancelRecordings(reason string) {
m.mu.Lock()
defer m.mu.Unlock()
for _, session := range m.sessions {
- session.stopReason = reason
+ if session.stopReason == "" {
+ session.stopReason = reason
+ }
session.cancel()
}
for _, session := range m.douyinSessions {
- session.stopReason = reason
+ if session.stopReason == "" {
+ session.stopReason = reason
+ }
session.cancel()
}
}
-// StopForSite cancels and waits for active recordings belonging to siteID without affecting other sites.
+// CancelRecordingsForSite signals active recordings belonging to siteID without waiting.
+func (m *Manager) CancelRecordingsForSite(siteID site.ID, reason string) {
+ if reason == "" {
+ reason = "auth_required"
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ switch siteID {
+ case site.Bilibili:
+ for _, session := range m.sessions {
+ if session.stopReason == "" {
+ session.stopReason = reason
+ }
+ session.cancel()
+ }
+ case site.Douyin:
+ for _, session := range m.douyinSessions {
+ if session.stopReason == "" {
+ session.stopReason = reason
+ }
+ session.cancel()
+ }
+ }
+}
+
+// StopForSite cancels active recordings belonging to siteID without affecting other sites,
+// waiting for sessions that are not currently inside an external site-client/callback
+// call so re-entrant invocations from recording goroutines never self-deadlock.
func (m *Manager) StopForSite(siteID site.ID, reason string) {
if reason == "" {
reason = "auth_required"
@@ -1315,7 +693,9 @@ func (m *Manager) StopForSite(siteID site.ID, reason string) {
session.stopReason = reason
}
session.cancel()
- waitChs = append(waitChs, session.doneCh)
+ if session.inExternal.Load() == 0 {
+ waitChs = append(waitChs, session.doneCh)
+ }
}
case site.Douyin:
for _, session := range m.douyinSessions {
@@ -1323,12 +703,17 @@ func (m *Manager) StopForSite(siteID site.ID, reason string) {
session.stopReason = reason
}
session.cancel()
- waitChs = append(waitChs, session.doneCh)
+ if session.inExternal.Load() == 0 {
+ waitChs = append(waitChs, session.doneCh)
+ }
}
}
timeout := m.finalizeTimeout
m.mu.Unlock()
+ if len(waitChs) == 0 {
+ return
+ }
if timeout <= 0 {
timeout = 30 * time.Second
}
diff --git a/internal/live/manual_refresh_record_test.go b/internal/live/manual_refresh_record_test.go
index 6180846..7d2e222 100644
--- a/internal/live/manual_refresh_record_test.go
+++ b/internal/live/manual_refresh_record_test.go
@@ -16,8 +16,7 @@ import (
// Refreshing an account's live status by hand (the account page) starts
// recording a broadcast it finds live when the account's subscription
-// records broadcasts, without waiting for the next poll round (dev
-// 2026-11-18: the refresh showed 直播中 and nothing recorded). An account
+// records broadcasts, without waiting for the next poll round. An account
// whose subscription does not record is only refreshed.
func TestManualLiveRefreshStartsAutoRecording(t *testing.T) {
const (
diff --git a/internal/live/moved_files_test.go b/internal/live/moved_files_test.go
new file mode 100644
index 0000000..857b34c
--- /dev/null
+++ b/internal/live/moved_files_test.go
@@ -0,0 +1,151 @@
+package live
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/Eyevinn/mp4ff/mp4"
+ "github.com/chialecode/trace/internal/credential"
+ "github.com/chialecode/trace/internal/download"
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/settings"
+ "github.com/chialecode/trace/internal/site/bilibili"
+ "github.com/chialecode/trace/internal/storage"
+ "github.com/chialecode/trace/internal/subscription"
+)
+
+// After the first segment is finished, its file and
+// item.json are moved away (the user's rclone move or the uploader). The
+// recording goes on, the next segment is finalized normally, and the
+// item.json written then lists both finished segments.
+func TestRecordingContinuesWhenFinishedSegmentsAreMovedAway(t *testing.T) {
+ vM4S, err := download.BuildSyntheticVideoM4S(30, 30)
+ if err != nil {
+ t.Fatal(err)
+ }
+ parsed, err := mp4.DecodeFile(bytes.NewReader(vM4S), mp4.WithDecodeFlags(mp4.DecStartOnMoof))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var initBuf, fragBuf bytes.Buffer
+ _ = parsed.Init.Encode(&initBuf)
+ _ = parsed.Segments[0].Fragments[0].Encode(&fragBuf)
+
+ var srvURL string
+ var hits atomic.Int32
+ var live atomic.Bool
+ live.Store(true)
+ var recordDir atomic.Value
+ var moved atomic.Bool
+ mux := http.NewServeMux()
+ mux.HandleFunc("/room/v1/Room/get_status_info_by_uids", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{"1001": map[string]any{
+ "uid": 1001, "room_id": 8888, "title": "合成直播", "uname": "Streamer1001", "live_status": 1, "live_time": 1794024000}}})
+ })
+ mux.HandleFunc("/room/v1/Room/room_init", func(w http.ResponseWriter, r *http.Request) {
+ st := 0
+ if live.Load() {
+ st = 1
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{"room_id": 8888, "short_id": 88, "uid": 1001, "live_status": st, "live_time": 1794024000}})
+ })
+ mux.HandleFunc("/xlive/web-room/v2/index/getRoomPlayInfo", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{"room_id": 8888, "uid": 1001, "live_status": 1,
+ "playurl_info": map[string]any{"playurl": map[string]any{"stream": []map[string]any{{"protocol_name": "http_hls",
+ "format": []map[string]any{{"format_name": "fmp4", "codec": []map[string]any{{"codec_name": "avc", "current_qn": 10000, "base_url": "/hls/index.m3u8",
+ "url_info": []map[string]any{{"host": srvURL, "extra": "?expires=1999999999"}}}}}}}}}}}})
+ })
+ mux.HandleFunc("/hls/index.m3u8", func(w http.ResponseWriter, r *http.Request) {
+ switch hits.Add(1) {
+ case 1:
+ _, _ = w.Write([]byte("#EXTM3U\n#EXT-X-VERSION:7\n#EXT-X-TARGETDURATION:1\n#EXT-X-MEDIA-SEQUENCE:10\n#EXT-X-MAP:URI=\"/hls/init.mp4\"\n#EXTINF:1.0,\n/hls/seg1.m4s\n"))
+ case 2:
+ w.WriteHeader(http.StatusBadGateway) // the recorder finalizes part-001 and reconnects
+ default:
+ // part-001 and item.json are finished: move them away first.
+ if dir, ok := recordDir.Load().(string); ok && !moved.Load() {
+ if _, err := os.Stat(filepath.Join(dir, "part-001.mp4")); err == nil {
+ _ = os.Remove(filepath.Join(dir, "part-001.mp4"))
+ _ = os.Remove(filepath.Join(dir, "item.json"))
+ moved.Store(true)
+ }
+ }
+ live.Store(false)
+ _, _ = w.Write([]byte("#EXTM3U\n#EXT-X-VERSION:7\n#EXT-X-TARGETDURATION:1\n#EXT-X-MEDIA-SEQUENCE:11\n#EXT-X-MAP:URI=\"/hls/init.mp4\"\n#EXTINF:1.0,\n/hls/seg2.m4s\n#EXT-X-ENDLIST\n"))
+ }
+ })
+ mux.HandleFunc("/hls/init.mp4", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write(initBuf.Bytes()) })
+ mux.HandleFunc("/hls/seg1.m4s", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write(fragBuf.Bytes()) })
+ mux.HandleFunc("/hls/seg2.m4s", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write(fragBuf.Bytes()) })
+ srv := httptest.NewServer(mux)
+ defer srv.Close()
+ srvURL = srv.URL
+
+ tmp := t.TempDir()
+ db, _, _, _ := storage.OpenSQLite(filepath.Join(tmp, "library.db"))
+ defer db.Close()
+ cacheDir := filepath.Join(tmp, "cache")
+ lib, _ := library.Open(db, cacheDir)
+ lib.SetAllowMovedFiles(true)
+ cred, _, _ := credential.Open(filepath.Join(tmp, "cred.dpapi"))
+ _, _ = cred.SaveManual("SESSDATA=s; bili_jct=c", "rt")
+ client := bilibili.NewClient(bilibili.ClientOptions{CredStore: cred, Endpoints: bilibili.Endpoints{APIBase: srv.URL, LiveAPIBase: srv.URL}, PacingInterval: -1, AllowLocalhost: true})
+ subMgr, _ := subscription.NewManager(db, lib, nil, client, settings.Default(cacheDir).Subscription, nil)
+ _, _ = subMgr.Upsert(subscription.Subscription{Mid: 1001, Uname: "Streamer1001", Enabled: true, LiveNotify: true})
+ mgr := NewManager(lib, subMgr, client, settings.Default(cacheDir).Live, func(Notification) {}, nil)
+ mgr.hlsPollInterval = 30 * time.Millisecond
+ mgr.reconnectWait = 30 * time.Millisecond
+ mgr.freeBytesFunc = func(string) (uint64, error) { return 10 << 30, nil }
+
+ checkNames := watchNames(t, cacheDir)
+ ctx := context.Background()
+ if _, err := mgr.PollNow(ctx); err != nil {
+ t.Fatal(err)
+ }
+ st, err := mgr.StartRecording(ctx, 8888)
+ if err != nil || !st.Recording {
+ t.Fatalf("StartRecording = %+v, %v", st, err)
+ }
+ recordDir.Store(st.RecordItemDir)
+ deadline := time.Now().Add(5 * time.Second)
+ finished := false
+ for time.Now().Before(deadline) {
+ if rooms := mgr.ListRooms(); len(rooms) == 1 && !rooms[0].Recording {
+ finished = true
+ break
+ }
+ time.Sleep(25 * time.Millisecond)
+ }
+ if !finished {
+ t.Fatalf("timed out waiting for recording to finish: %+v", mgr.ListRooms())
+ }
+ if !moved.Load() {
+ t.Fatal("the test did not move part-001 away during the recording")
+ }
+ checkNames("part-001.mp4", "item.json")
+ if _, err := os.Stat(filepath.Join(st.RecordItemDir, "part-002.mp4")); err != nil {
+ t.Fatalf("part-002.mp4: %v", err)
+ }
+ raw, err := os.ReadFile(filepath.Join(st.RecordItemDir, "item.json"))
+ if err != nil {
+ t.Fatalf("item.json was not written after the next segment: %v", err)
+ }
+ var meta library.ItemMetadata
+ if err := json.Unmarshal(raw, &meta); err != nil {
+ t.Fatal(err)
+ }
+ if meta.Live == nil || len(meta.Live.Segments) != 2 {
+ t.Fatalf("item.json segments = %+v, want both finished segments", meta.Live)
+ }
+ if meta.Status != "complete" || meta.Live.Segments[1].File != "part-002.mp4" {
+ t.Fatalf("item after the move = status %q segments %+v, want complete with part-002.mp4", meta.Status, meta.Live.Segments)
+ }
+}
diff --git a/internal/live/overlap.go b/internal/live/overlap.go
index 9b0da2a..74cb3ab 100644
--- a/internal/live/overlap.go
+++ b/internal/live/overlap.go
@@ -55,6 +55,7 @@ func trimFragmentOverlaps(f *mp4.File) int {
trimmed++
}
te.end = start
+ te.last = nil
}
for _, trun := range traf.Truns {
// Make every duration explicit so Defragment keeps a trimmed value.
@@ -71,12 +72,11 @@ func trimFragmentOverlaps(f *mp4.File) int {
return trimmed
}
-// fragmentTimelineSec returns the longest track timeline of a recorded fMP4 in
-// seconds: from the first fragment's tfdt to the end of the last sample. Run it
-// after trimFragmentOverlaps, which makes every sample duration explicit. It is
-// the reference for checking the defragmented output: the HLS EXTINF sum only
-// approximates the media and drifts by tenths of a second over a few minutes.
-// It returns 0 when the file has no usable decode times.
+// fragmentTimelineSec returns the combined cross-track timeline of a recorded
+// fMP4 in seconds: max_i(end_i/ts_i) - min_i(first_i/ts_i), matching how
+// mp4.Defragment computes mvhd.Duration across tracks with differing start
+// offsets. Run it after trimFragmentOverlaps, which makes every sample duration
+// explicit. It returns 0 when the file has no usable decode times.
func fragmentTimelineSec(f *mp4.File) float64 {
if f == nil || f.Moov == nil {
return 0
@@ -87,7 +87,11 @@ func fragmentTimelineSec(f *mp4.File) float64 {
timescale[trak.Tkhd.TrackID] = trak.Mdia.Mdhd.Timescale
}
}
- type span struct{ first, end uint64 }
+ type span struct {
+ first uint64
+ end uint64
+ has bool
+ }
spans := map[uint32]*span{}
for _, seg := range f.Segments {
for _, frag := range seg.Fragments {
@@ -100,14 +104,21 @@ func fragmentTimelineSec(f *mp4.File) float64 {
}
id := traf.Tfhd.TrackID
start := traf.Tfdt.BaseMediaDecodeTime()
+ end := start
+ for _, trun := range traf.Truns {
+ end += trun.Duration(0)
+ }
+ if end <= start {
+ continue
+ }
s := spans[id]
if s == nil {
- s = &span{first: start}
+ s = &span{first: start, end: end, has: true}
spans[id] = s
+ continue
}
- end := start
- for _, trun := range traf.Truns {
- end += trun.Duration(0)
+ if start < s.first {
+ s.first = start
}
if end > s.end {
s.end = end
@@ -115,11 +126,28 @@ func fragmentTimelineSec(f *mp4.File) float64 {
}
}
}
- longest := 0.0
+ var minFirst, maxEnd float64
+ found := false
for id, s := range spans {
- if ts := timescale[id]; ts > 0 && s.end > s.first {
- longest = max(longest, float64(s.end-s.first)/float64(ts))
+ if ts := timescale[id]; ts > 0 && s.has && s.end > s.first {
+ firstSec := float64(s.first) / float64(ts)
+ endSec := float64(s.end) / float64(ts)
+ if !found {
+ minFirst = firstSec
+ maxEnd = endSec
+ found = true
+ } else {
+ if firstSec < minFirst {
+ minFirst = firstSec
+ }
+ if endSec > maxEnd {
+ maxEnd = endSec
+ }
+ }
}
}
- return longest
+ if !found || maxEnd <= minFirst {
+ return 0
+ }
+ return maxEnd - minFirst
}
diff --git a/internal/live/part_finish.go b/internal/live/part_finish.go
index 9f6f0b7..6389467 100644
--- a/internal/live/part_finish.go
+++ b/internal/live/part_finish.go
@@ -24,10 +24,42 @@ type partJob struct {
qualityName string
}
-// finishPartAsync converts a part while the session records the next one.
-// Converting a long part takes tens of seconds (3.3 GB took about 40); a
-// live playlist keeps only the last few seconds, so converting it in the
-// recording loop lost the segments published meanwhile (dev 2026-11-18).
+func roundedLiveDurationSec(sec float64) int {
+ if sec <= 0 || math.IsNaN(sec) || math.IsInf(sec, 0) {
+ return 0
+ }
+ return max(1, int(math.Round(sec)))
+}
+
+func removeFileWithRetry(path string) error {
+ var err error
+ for attempt := 0; attempt < 5; attempt++ {
+ err = os.Remove(path)
+ if err == nil || os.IsNotExist(err) {
+ return nil
+ }
+ time.Sleep(time.Duration(attempt+1) * 20 * time.Millisecond)
+ }
+ return err
+}
+
+func (m *Manager) finishContext() (context.Context, context.CancelFunc) {
+ m.mu.Lock()
+ stopping := m.stopping
+ deadline := m.stopDeadline
+ timeout := m.finalizeTimeout
+ m.mu.Unlock()
+ if timeout <= 0 {
+ timeout = 30 * time.Second
+ }
+ if stopping && !deadline.IsZero() {
+ return context.WithDeadline(context.Background(), deadline)
+ }
+ return context.WithTimeout(context.Background(), timeout)
+}
+
+// finishPartAsync converts a part while the session records the next one, so
+// converting a long part never stalls playlist polling or loses segments.
// Parts of a session convert one at a time and in order; the session waits
// for them before it ends.
func (m *Manager) finishPartAsync(sess *recordSession, job partJob) {
@@ -56,23 +88,24 @@ func (sess *recordSession) waitPartsFinished() {
}
// finishPart converts a recorded part to MP4 and registers it in the
-// session's manifest; the .part goes once the manifest names the MP4. A
-// failed conversion keeps the .part and records the incident. The error is
-// the manifest's: the session cannot go on without it.
+// session's manifest; PendingParts retains the .part entry until the manifest
+// save succeeds, and the .part file is removed only after commit. A failed
+// conversion keeps the .part and records the incident.
func (m *Manager) finishPart(sess *recordSession, job partJob) error {
- finishCtx, cancel := context.WithTimeout(context.Background(), m.finalizeTimeout)
+ finishCtx, cancel := m.finishContext()
summary, conversionErr := convertPart(finishCtx, job.path, filepath.Join(sess.itemDir, job.partRel))
cancel()
if conversionErr != nil {
+ reason := "直播录像转换失败:" + sanitizeLiveError(conversionErr)
m.mu.Lock()
addLiveMissing(&sess.itemMeta, job.pending, "转换失败,临时片段已保留")
- sess.lastErr = "直播录像转换失败:" + conversionErr.Error()
+ sess.lastErr = reason
m.mu.Unlock()
m.recordSessionIncident(sess, library.LiveIncident{
Kind: library.LiveIncidentConvertFailed,
- At: m.nowFunc().UTC().Format(time.RFC3339),
+ At: m.now().UTC().Format(time.RFC3339),
Part: job.pending,
- Reason: "直播录像转换失败:" + library.SanitizeLiveIncidentText(conversionErr.Error()),
+ Reason: reason,
}, true)
return m.writeSessionMeta(sess, false)
}
@@ -80,18 +113,53 @@ func (m *Manager) finishPart(sess *recordSession, job partJob) error {
if codec == "" && len(summary.Codecs) > 0 {
codec = summary.Codecs[0]
}
- m.mu.Lock()
- sess.itemMeta.Media = mergeLiveMedia(sess.itemMeta.Media, library.MediaFile{Role: "live_segment", Path: job.partRel, Bytes: summary.FileBytes, SHA256: summary.SHA256, Duration: int(math.Round(summary.DurationSec)), Width: summary.Width, Height: summary.Height})
- sess.itemMeta.PendingParts = removePending(sess.itemMeta.PendingParts, job.pending)
- clearLiveCheckpoint(&sess.itemMeta, job.pending)
- clearLiveMissing(&sess.itemMeta, job.pending)
- sess.itemMeta.Live.Segments = mergeLiveSegment(sess.itemMeta.Live.Segments, library.LiveSegmentInfo{File: job.partRel, Bytes: summary.FileBytes, SHA256: summary.SHA256, DurationSec: summary.DurationSec, Codec: codec, Width: summary.Width, Height: summary.Height, Quality: job.quality, QualityName: job.qualityName})
- sess.segments = append(sess.segments, job.partRel)
- m.mu.Unlock()
- if err := m.writeSessionMeta(sess, false); err != nil {
+ mediaEntry := library.MediaFile{
+ Role: "live_segment",
+ Path: job.partRel,
+ Bytes: summary.FileBytes,
+ SHA256: summary.SHA256,
+ Duration: roundedLiveDurationSec(summary.DurationSec),
+ Width: summary.Width,
+ Height: summary.Height,
+ }
+ segEntry := library.LiveSegmentInfo{
+ File: job.partRel,
+ Bytes: summary.FileBytes,
+ SHA256: summary.SHA256,
+ DurationSec: summary.DurationSec,
+ Codec: codec,
+ Width: summary.Width,
+ Height: summary.Height,
+ Quality: job.quality,
+ QualityName: job.qualityName,
+ }
+ applyPart := func(meta *library.ItemMetadata) {
+ meta.Media = mergeLiveMedia(meta.Media, mediaEntry)
+ meta.PendingParts = removePending(meta.PendingParts, job.pending)
+ clearLiveCheckpoint(meta, job.pending)
+ clearLiveMissing(meta, job.pending)
+ if meta.Live != nil {
+ meta.Live.Segments = mergeLiveSegment(meta.Live.Segments, segEntry)
+ }
+ }
+
+ var notify *RoomState
+ if err := m.commitSessionMeta(sess, false, applyPart, func() {
+ sess.segments = append(sess.segments, job.partRel)
+ if st, ok := m.syncSessionRoomStateLocked(sess); ok {
+ cp := st
+ notify = &cp
+ }
+ }); err != nil {
return err
}
- _ = os.Remove(job.path)
+
+ _ = removeFileWithRetry(job.path)
+ if notify != nil && m.onState != nil {
+ leave := sess.enterExternal()
+ m.onState(*notify)
+ leave()
+ }
return nil
}
@@ -106,24 +174,52 @@ func (m *Manager) saveSession(sess *recordSession) error {
// change (only what the library derives is taken back). fromLoop also
// records the sequence the loop reached; a background part leaves it.
func (m *Manager) writeSessionMeta(sess *recordSession, fromLoop bool) error {
+ return m.commitSessionMeta(sess, fromLoop, nil, nil)
+}
+
+// commitSessionMeta atomically applies mutate to a snapshot, persists it via
+// m.lib.SaveItem, and only commits mutate + onSavedLocked back into sess once
+// persistence succeeds.
+func (m *Manager) commitSessionMeta(
+ sess *recordSession,
+ fromLoop bool,
+ mutate func(meta *library.ItemMetadata),
+ onSavedLocked func(),
+) error {
sess.saveMu.Lock()
defer sess.saveMu.Unlock()
m.mu.Lock()
- if fromLoop {
+ if fromLoop && sess.itemMeta.Live != nil {
sess.itemMeta.Live.LastSequence, sess.itemMeta.Live.HasSequence = sess.lastSequence, sess.hasSequence
}
- sess.itemMeta.Live.Incidents = cloneIncidents(sess.incidents)
metaCopy := snapshotItemMeta(sess.itemMeta)
+ if mutate != nil {
+ mutate(&metaCopy)
+ }
+ if metaCopy.Live != nil {
+ metaCopy.Live.Incidents = cloneIncidents(sess.incidents)
+ }
m.mu.Unlock()
+
saved, err := m.lib.SaveItem(sess.itemDir, metaCopy)
- if err == nil {
- m.mu.Lock()
- sess.itemMeta.Version, sess.itemMeta.Site, sess.itemMeta.Kind = saved.Version, saved.Site, saved.Kind
- sess.itemMeta.RawID, sess.itemMeta.ItemKey, sess.itemMeta.ItemDir = saved.RawID, saved.ItemKey, saved.ItemDir
- sess.itemMeta.CachedAt, sess.itemMeta.TotalBytes, sess.itemMeta.Status = saved.CachedAt, saved.TotalBytes, saved.Status
- m.mu.Unlock()
+ if err != nil {
+ return err
}
- return err
+ m.mu.Lock()
+ if mutate != nil {
+ mutate(&sess.itemMeta)
+ }
+ if sess.itemMeta.Live != nil {
+ sess.itemMeta.Live.Incidents = cloneIncidents(sess.incidents)
+ }
+ sess.itemMeta.Version, sess.itemMeta.Site, sess.itemMeta.Kind = saved.Version, saved.Site, saved.Kind
+ sess.itemMeta.RawID, sess.itemMeta.ItemKey, sess.itemMeta.ItemDir = saved.RawID, saved.ItemKey, saved.ItemDir
+ sess.itemMeta.CachedAt, sess.itemMeta.TotalBytes, sess.itemMeta.Status = saved.CachedAt, saved.TotalBytes, saved.Status
+ if onSavedLocked != nil {
+ onSavedLocked()
+ }
+ m.mu.Unlock()
+ return nil
}
// saveCheckpoint applies update to the manifest and writes it as the
@@ -133,7 +229,9 @@ func (m *Manager) saveCheckpoint(sess *recordSession, update func(meta *library.
defer sess.saveMu.Unlock()
m.mu.Lock()
update(&sess.itemMeta)
- sess.itemMeta.Live.Incidents = cloneIncidents(sess.incidents)
+ if sess.itemMeta.Live != nil {
+ sess.itemMeta.Live.Incidents = cloneIncidents(sess.incidents)
+ }
metaCopy := snapshotItemMeta(sess.itemMeta)
m.mu.Unlock()
_, err := m.lib.SaveRecordingCheckpoint(sess.itemDir, metaCopy)
diff --git a/internal/live/part_finish_test.go b/internal/live/part_finish_test.go
index 1a7914d..0a4676b 100644
--- a/internal/live/part_finish_test.go
+++ b/internal/live/part_finish_test.go
@@ -18,9 +18,8 @@ import (
// A rollover converts the finished part in the background: the next part
// keeps fetching segments while the previous one converts, so a long part's
-// conversion no longer lets the live playlist move past unfetched segments
-// (dev 2026-11-18: 12 segments lost after a 3.3 GB part). Both parts end up
-// registered, in order, with nothing pending and no lost segments.
+// conversion no longer lets the live playlist move past unfetched segments.
+// Both parts end up registered, in order, with nothing pending and no lost segments.
func TestRolloverConvertsPreviousPartWhileRecording(t *testing.T) {
initBytes, fragBytes := splitSyntheticHLSInitAndFrag(t)
const roomID = int64(9701)
@@ -111,12 +110,17 @@ func TestRolloverConvertsPreviousPartWhileRecording(t *testing.T) {
t.Fatal(err)
}
deadline := time.Now().Add(10 * time.Second)
+ finished := false
for time.Now().Before(deadline) {
if st, ok := roomState(mgr, roomID); ok && !st.Recording && ended.Load() {
+ finished = true
break
}
time.Sleep(10 * time.Millisecond)
}
+ if !finished {
+ t.Fatalf("timed out waiting for room %d to finish recording", roomID)
+ }
if !progressed.Load() {
t.Fatal("the next part fetched nothing while the previous part converted")
}
diff --git a/internal/live/recorder.go b/internal/live/recorder.go
index 4e5cd86..66efd26 100644
--- a/internal/live/recorder.go
+++ b/internal/live/recorder.go
@@ -1,171 +1,44 @@
package live
import (
- "bytes"
"context"
"errors"
"fmt"
- "io"
- "math"
"os"
- "path/filepath"
- "slices"
"strings"
"time"
- "github.com/Eyevinn/mp4ff/mp4"
- "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"
)
-// RecoverOrphanParts processes only files named in a live item's pending list.
-// It also converts a registered live segment saved without a duration (raw
-// fragments under the final name). Imported roots are already represented by
-// the library index; unrelated files
-// and user-created .part files are never scanned or renamed.
-func (m *Manager) RecoverOrphanParts() {
- if m.lib == nil {
- return
- }
- for offset := 0; ; offset += 200 {
- items, err := m.lib.ListItems(library.FeedFilter{Kind: "live", Limit: 200, Offset: offset})
- if err != nil {
- return
- }
- for _, meta := range items {
- m.mu.Lock()
- active := false
- for _, session := range m.sessions {
- active = active || session.itemDir == meta.ItemDir
- }
- for _, session := range m.douyinSessions {
- active = active || session.itemDir == meta.ItemDir
- }
- m.mu.Unlock()
- if active {
- continue
- }
- // A segment saved with no duration was never converted (an earlier
- // recovery accepted raw fragments); convert it like a pending part.
- for _, media := range meta.Media {
- pending := media.Path + ".part"
- if media.Role == "live_segment" && media.Duration <= 0 && strings.HasPrefix(media.Path, "part-") && !slices.Contains(meta.PendingParts, pending) {
- meta.PendingParts = append(meta.PendingParts, pending)
- }
- }
- if len(meta.PendingParts) == 0 {
- continue
- }
- var remaining []string
- for _, rel := range meta.PendingParts {
- if !strings.HasPrefix(rel, "part-") || !strings.HasSuffix(rel, ".mp4.part") {
- remaining = append(remaining, rel)
- continue
- }
- partPath, err := library.ResolveItemPath(meta.ItemDir, rel)
- if err != nil {
- remaining = append(remaining, rel)
- continue
- }
- finalRel := strings.TrimSuffix(rel, ".part")
- finalPath, err := library.ResolveItemPath(meta.ItemDir, finalRel)
- if err != nil {
- remaining = append(remaining, rel)
- continue
- }
- ctx, cancel := context.WithTimeout(context.Background(), m.finalizeTimeout)
- if meta.Live != nil && meta.Live.PendingFile == rel {
- if info, statErr := os.Stat(partPath); statErr == nil && meta.Live.PendingBytes > 0 && info.Size() > meta.Live.PendingBytes {
- err = os.Truncate(partPath, meta.Live.PendingBytes)
- }
- }
- var summary download.MuxTrackSummary
- if err == nil {
- if _, statErr := os.Stat(partPath); os.IsNotExist(statErr) {
- summary, err = download.InspectMP4FileContext(ctx, finalPath)
- if err == nil && !finalizedLivePart(summary) {
- // The final name holds the unconverted fragments (for example a
- // ".part" renamed by hand): convert it instead of accepting it.
- if err = os.Rename(finalPath, partPath); err == nil {
- if summary, err = finalizeLivePart(ctx, partPath, finalPath); err == nil {
- _ = os.Remove(partPath)
- } else {
- _ = os.Rename(partPath, finalPath) // keep the file where the item expects it
- }
- }
- }
- } else {
- summary, err = finalizeLivePart(ctx, partPath, finalPath)
- }
- }
- cancel()
- if err != nil {
- remaining = append(remaining, rel)
- addLiveMissing(&meta, rel, "转换失败")
- if meta.Live != nil {
- meta.Live.Incidents, _, _ = appendCoalescedIncident(meta.Live.Incidents, library.LiveIncident{
- Kind: library.LiveIncidentConvertFailed,
- At: m.nowFunc().UTC().Format(time.RFC3339),
- Part: rel,
- Reason: "直播录像转换失败:" + library.SanitizeLiveIncidentText(err.Error()),
- })
- }
- continue
- }
- meta.Media = mergeLiveMedia(meta.Media, library.MediaFile{Role: "live_segment", Path: finalRel, Bytes: summary.FileBytes, SHA256: summary.SHA256, Duration: int(math.Round(summary.DurationSec)), Width: summary.Width, Height: summary.Height})
- if meta.Live != nil {
- qName := meta.Live.QualityName
- if qName == "" && meta.Live.Quality > 0 {
- qName = bilibili.LiveQualityFallbackName(meta.Live.Quality)
- }
- meta.Live.QualityName = qName
- meta.Live.Segments = mergeLiveSegment(meta.Live.Segments, library.LiveSegmentInfo{File: finalRel, Bytes: summary.FileBytes, SHA256: summary.SHA256, DurationSec: summary.DurationSec, Codec: meta.Live.Codec, Quality: meta.Live.Quality, QualityName: qName, Width: summary.Width, Height: summary.Height})
- meta.Live.Incidents = dropResolvedConvertFailed(meta.Live.Incidents, rel)
- }
- clearLiveMissing(&meta, rel)
- clearLiveCheckpoint(&meta, rel)
- }
- meta.PendingParts = remaining
- meta.Status = "complete"
- if len(remaining) > 0 || len(meta.Missing) > 0 {
- meta.Status = "partial"
- }
- if meta.Live != nil && meta.Live.StopReason == "" {
- meta.Live.StopReason = "app_closed"
- meta.Live.EndedAt = m.nowFunc().UTC().Format(time.RFC3339)
- }
- if _, err := m.lib.SaveItem(meta.ItemDir, meta); err == nil {
- for _, original := range itemsPendingToRemove(items, meta) {
- if path, err := library.ResolveItemPath(meta.ItemDir, original); err == nil {
- _ = os.Remove(path)
- }
- }
- }
- }
- if len(items) < 200 {
- return
- }
- }
+type partStreamMeta struct {
+ codec string
+ quality int
+ qualityName string
}
-func itemsPendingToRemove(items []library.ItemMetadata, saved library.ItemMetadata) []string {
- var result []string
- for _, item := range items {
- if item.ItemKey == saved.ItemKey {
- for _, rel := range item.PendingParts {
- found := false
- for _, pending := range saved.PendingParts {
- found = found || rel == pending
- }
- if !found {
- result = append(result, rel)
- }
- }
- }
- }
- return result
+type reconnectOutcome uint8
+
+const (
+ reconnectOK reconnectOutcome = iota
+ reconnectRetry
+ reconnectEnded
+ reconnectStop
+)
+
+type sessionDriver struct {
+ siteID site.ID
+ unregister func()
+ saveCover func(ctx context.Context) error
+ currentMeta func() partStreamMeta
+ updateStateMeta func(meta partStreamMeta) // called under m.mu
+ recordPart func(ctx context.Context, flvConn **activeFLVConn, partPath string) (int64, error)
+ reportStopError func(ctx context.Context, err error, reason string)
+ reconnect func(ctx context.Context) (reconnectOutcome, error)
+ finalizeState func(reason string, now time.Time) RoomState // called under m.mu
+ saveStateLocked func(state RoomState) // called under m.mu
}
func nextPartNumber(meta library.ItemMetadata) int {
@@ -186,19 +59,129 @@ func nextPartNumber(meta library.ItemMetadata) int {
}
func (m *Manager) runRecordingSession(ctx context.Context, sess *recordSession, initial bilibili.LivePlaySelection, codecOrder []string) {
+ selection := initial
+ m.runSessionLoop(ctx, sess, sessionDriver{
+ siteID: site.Bilibili,
+ unregister: func() {
+ m.mu.Lock()
+ delete(m.sessions, sess.roomID)
+ m.mu.Unlock()
+ },
+ saveCover: func(ctx context.Context) error {
+ return m.saveLiveCover(ctx, sess)
+ },
+ currentMeta: func() partStreamMeta {
+ qName := selection.QualityName
+ if qName == "" && selection.Quality > 0 {
+ qName = bilibili.LiveQualityFallbackName(selection.Quality)
+ }
+ return partStreamMeta{
+ codec: selection.Codec,
+ quality: selection.Quality,
+ qualityName: qName,
+ }
+ },
+ updateStateMeta: func(pm partStreamMeta) {
+ if st, ok := m.states[sess.roomID]; ok {
+ st.Codec, st.Quality, st.QualityName = pm.codec, pm.quality, pm.qualityName
+ m.states[sess.roomID] = st
+ }
+ },
+ recordPart: func(ctx context.Context, flvConn **activeFLVConn, partPath string) (int64, error) {
+ if selection.Format == "flv" || selection.Protocol == "http_stream" {
+ m.beginSessionPart(sess, sess.nextPart, partPath, string(site.LiveTransportHTTPFLV))
+ return m.recordBilibiliFLVPart(ctx, sess, selection.URLs, flvConn, partPath)
+ }
+ if *flvConn != nil {
+ _ = (*flvConn).Close()
+ *flvConn = nil
+ }
+ m.beginSessionPart(sess, sess.nextPart, partPath, string(site.LiveTransportHLSFMP4))
+ return m.recordHLSSegment(ctx, sess, selection.URLs, partPath, true)
+ },
+ reportStopError: func(ctx context.Context, err error, reason string) {
+ if m.client != nil {
+ leave := sess.enterExternal()
+ m.client.ReportAutomaticError(ctx, err)
+ leave()
+ }
+ if reason == site.ErrKindRiskControl || reason == site.ErrKindRateLimited {
+ m.recordSiteAutoStop(site.Bilibili, reason)
+ }
+ },
+ reconnect: func(ctx context.Context) (reconnectOutcome, error) {
+ m.mu.Lock()
+ var liveSince int64
+ if sess.itemMeta.Live != nil {
+ liveSince = sess.itemMeta.Live.LiveSince
+ }
+ m.mu.Unlock()
+
+ leave := sess.enterExternal()
+ room, err := m.client.RoomInit(ctx, sess.roomID)
+ leave()
+ if err == nil && (room.LiveStatus != 1 || (room.LiveTime > 0 && room.LiveTime != liveSince)) {
+ return reconnectEnded, nil
+ }
+ var fresh bilibili.LivePlaySelection
+ if err == nil {
+ leave = sess.enterExternal()
+ fresh, err = m.client.LiveRoomPlayInfo(ctx, sess.roomID, codecOrder)
+ leave()
+ }
+ if err != nil {
+ if liveStopReason(err) != "" {
+ return reconnectStop, err
+ }
+ return reconnectRetry, err
+ }
+ if fresh.LiveStatus != 1 || len(fresh.URLs) == 0 {
+ return reconnectEnded, nil
+ }
+ selection = fresh
+ return reconnectOK, nil
+ },
+ finalizeState: func(reason string, now time.Time) RoomState {
+ state := m.states[sess.roomID]
+ m.normalizeBilibiliRoomStateLocked(&state)
+ state.Recording = false
+ state.StopReason = reason
+ state.LastError = sess.lastErr
+ state.RecordDurationSec = now.Sub(sess.startedAt).Seconds()
+ state.RecordBytes = sess.bytesTotal
+ state.RecordSegments = len(sess.segments)
+ state.RecordItemDir = sess.itemDir
+ state.Incidents = cloneIncidents(sess.incidents)
+ hydrateSessionPreviewFieldsLocked(&state, nil)
+ m.states[sess.roomID] = state
+ return state
+ },
+ saveStateLocked: func(state RoomState) {
+ m.states[sess.roomID] = state
+ },
+ })
+}
+
+func (m *Manager) runSessionLoop(ctx context.Context, sess *recordSession, driver sessionDriver) {
defer m.wg.Done()
defer close(sess.doneCh)
- defer func() { m.mu.Lock(); delete(m.sessions, sess.roomID); m.mu.Unlock() }()
+ defer driver.unregister()
+
var flvConn *activeFLVConn
defer func() {
if flvConn != nil {
_ = flvConn.Close()
}
}()
- selection := initial
- if err := m.saveLiveCover(ctx, sess); err != nil {
- m.setSessionStop(sess, liveStopReason(err), err)
+
+ if err := driver.saveCover(ctx); err != nil {
+ reason := liveStopReason(err)
+ if reason == "" {
+ reason = "storage"
+ }
+ m.setSessionStop(sess, reason, err)
}
+
var lostAt time.Time
for ctx.Err() == nil {
m.mu.Lock()
@@ -207,6 +190,18 @@ func (m *Manager) runRecordingSession(ctx context.Context, sess *recordSession,
if stopped {
break
}
+ if err := m.checkDiskSpace(sess.itemDir, driver.siteID); err != nil {
+ if isDiskFullError(err) {
+ m.recordSessionIncident(sess, library.LiveIncident{
+ Kind: library.LiveIncidentDisk,
+ At: m.now().UTC().Format(time.RFC3339),
+ Reason: "保存位置磁盘空间不足,录制已停止",
+ }, true)
+ }
+ m.setSessionStop(sess, "storage", err)
+ break
+ }
+
partRel := fmt.Sprintf("part-%03d.mp4", sess.nextPart)
pending := partRel + ".part"
path, err := library.ResolveItemPath(sess.itemDir, pending)
@@ -216,7 +211,7 @@ func (m *Manager) runRecordingSession(ctx context.Context, sess *recordSession,
}
for _, candidate := range []string{path, strings.TrimSuffix(path, ".part")} {
if _, statErr := os.Lstat(candidate); statErr == nil {
- err = &bilibili.SiteError{Kind: "storage", Message: "录像目标已存在且未登记,原文件已保留"}
+ err = &site.Error{Site: driver.siteID, Kind: site.ErrKindStorage, Message: "录像目标已存在且未登记,原文件已保留"}
break
} else if !os.IsNotExist(statErr) {
err = statErr
@@ -227,44 +222,48 @@ func (m *Manager) runRecordingSession(ctx context.Context, sess *recordSession,
m.setSessionStop(sess, "storage", err)
break
}
- qName := selection.QualityName
- if qName == "" && selection.Quality > 0 {
- qName = bilibili.LiveQualityFallbackName(selection.Quality)
- }
+
+ pm := driver.currentMeta()
m.mu.Lock()
sess.itemMeta.PendingParts = append(sess.itemMeta.PendingParts, pending)
- sess.itemMeta.Live.Codec, sess.itemMeta.Live.Quality, sess.itemMeta.Live.QualityName = selection.Codec, selection.Quality, qName
- sess.codec, sess.quality, sess.qualityName = selection.Codec, selection.Quality, qName
- if st, ok := m.states[sess.roomID]; ok {
- st.Codec, st.Quality, st.QualityName = selection.Codec, selection.Quality, qName
- m.states[sess.roomID] = st
+ if sess.itemMeta.Live != nil {
+ sess.itemMeta.Live.Codec = pm.codec
+ sess.itemMeta.Live.Quality = pm.quality
+ sess.itemMeta.Live.QualityName = pm.qualityName
}
+ sess.codec, sess.quality, sess.qualityName = pm.codec, pm.quality, pm.qualityName
+ driver.updateStateMeta(pm)
m.mu.Unlock()
if err := m.saveSession(sess); err != nil {
m.setSessionStop(sess, "storage", err)
break
}
- sess.segmentDuration, sess.wroteMedia = 0, false
- var n int64
- var recordErr error
- if selection.Format == "flv" || selection.Protocol == "http_stream" {
- m.beginSessionPart(sess, sess.nextPart, path, string(site.LiveTransportHTTPFLV))
- n, recordErr = m.recordBilibiliFLVPart(ctx, sess, selection.URLs, &flvConn, path)
- } else {
- if flvConn != nil {
- _ = flvConn.Close()
- flvConn = nil
- }
- m.beginSessionPart(sess, sess.nextPart, path, string(site.LiveTransportHLSFMP4))
- n, recordErr = m.recordHLSSegment(ctx, sess, selection.URLs, path, true)
- }
+
+ sess.segmentDuration = 0
+ m.mu.Lock()
+ sess.wroteMedia = false
+ m.mu.Unlock()
+
+ n, recordErr := driver.recordPart(ctx, &flvConn, path)
m.endSessionPart(sess)
if !errors.Is(recordErr, errSegmentRollover) && flvConn != nil {
_ = flvConn.Close()
flvConn = nil
}
+
if n > 0 {
- job := partJob{path: path, partRel: partRel, pending: pending, codec: selection.Codec, quality: selection.Quality, qualityName: qName}
+ m.mu.Lock()
+ actualCodec := firstNonEmpty(sess.codec, pm.codec)
+ wroteMedia := sess.wroteMedia
+ m.mu.Unlock()
+ job := partJob{
+ path: path,
+ partRel: partRel,
+ pending: pending,
+ codec: actualCodec,
+ quality: pm.quality,
+ qualityName: pm.qualityName,
+ }
if errors.Is(recordErr, errSegmentRollover) && ctx.Err() == nil {
m.finishPartAsync(sess, job)
} else {
@@ -275,21 +274,22 @@ func (m *Manager) runRecordingSession(ctx context.Context, sess *recordSession,
}
}
sess.nextPart++
- if sess.wroteMedia {
+ if wroteMedia {
lostAt = time.Time{}
}
} else {
- _ = os.Remove(path)
+ _ = removeFileWithRetry(path)
m.mu.Lock()
sess.itemMeta.PendingParts = removePending(sess.itemMeta.PendingParts, pending)
clearLiveCheckpoint(&sess.itemMeta, pending)
m.mu.Unlock()
}
+
if err := m.saveSession(sess); err != nil {
if isDiskFullError(err) {
m.recordSessionIncident(sess, library.LiveIncident{
Kind: library.LiveIncidentDisk,
- At: m.nowFunc().UTC().Format(time.RFC3339),
+ At: m.now().UTC().Format(time.RFC3339),
Part: pending,
Reason: "保存位置磁盘空间不足,录制已停止",
}, true)
@@ -307,69 +307,43 @@ func (m *Manager) runRecordingSession(ctx context.Context, sess *recordSession,
if isDiskFullError(recordErr) {
m.recordSessionIncident(sess, library.LiveIncident{
Kind: library.LiveIncidentDisk,
- At: m.nowFunc().UTC().Format(time.RFC3339),
+ At: m.now().UTC().Format(time.RFC3339),
Part: pending,
Reason: "保存位置磁盘空间不足,录制已停止",
}, true)
}
if reason := liveStopReason(recordErr); reason != "" {
- m.client.ReportAutomaticError(ctx, recordErr)
- if m.subs != nil && (reason == "risk_control" || reason == "rate_limited") {
- m.subs.RecordAutomaticStop(reason)
- }
+ driver.reportStopError(ctx, recordErr, reason)
m.setSessionStop(sess, reason, recordErr)
break
}
m.mu.Lock()
- sess.lastErr = recordErr.Error()
+ sess.lastErr = sanitizeLiveError(recordErr)
+ maxLoss := m.maxStreamLossDur
m.mu.Unlock()
- now := m.nowFunc()
+ now := m.now()
if lostAt.IsZero() {
lostAt = now
}
- if m.maxStreamLossDur > 0 && now.Sub(lostAt) >= m.maxStreamLossDur {
+ if maxLoss > 0 && now.Sub(lostAt) >= maxLoss {
m.setSessionStop(sess, "stream_timeout", recordErr)
break
}
}
- m.markSessionDisconnected(sess, m.nowFunc())
- select {
- case <-ctx.Done():
- case <-time.After(m.reconnectWait):
- }
- if ctx.Err() != nil {
- break
- }
- room, err := m.client.RoomInit(ctx, sess.roomID)
- if err == nil && (room.LiveStatus != 1 || room.LiveTime > 0 && room.LiveTime != sess.itemMeta.Live.LiveSince) {
- m.setSessionStop(sess, "ended", nil)
- break
- }
- if err == nil {
- selection, err = m.client.LiveRoomPlayInfo(ctx, sess.roomID, codecOrder)
- }
- if err != nil {
- if reason := liveStopReason(err); reason != "" {
- m.setSessionStop(sess, reason, err)
- break
- }
- now := m.nowFunc()
- if lostAt.IsZero() {
- lostAt = now
- }
- if m.maxStreamLossDur > 0 && now.Sub(lostAt) >= m.maxStreamLossDur {
- m.setSessionStop(sess, "stream_timeout", err)
- break
- }
- continue
- }
- if selection.LiveStatus != 1 || len(selection.URLs) == 0 {
- m.setSessionStop(sess, "ended", nil)
+
+ // Inner reconnect loop: keep retrying wait + status check + stream
+ // re-selection until a fresh valid stream is acquired or the session stops,
+ // so transient errors never reuse an expired URL or zeroed selection.
+ m.markSessionDisconnected(sess, m.now())
+ if !m.reconnectSessionLoop(ctx, sess, driver, &lostAt) {
break
}
}
+
sess.waitPartsFinished()
- m.closeSessionSlowIncident(sess, m.nowFunc())
+ now := m.now()
+ m.closeSessionSlowIncident(sess, now)
+
m.mu.Lock()
if sess.stopReason == "" {
if ctx.Err() != nil {
@@ -379,16 +353,14 @@ func (m *Manager) runRecordingSession(ctx context.Context, sess *recordSession,
}
}
reason := sess.stopReason
- state := m.states[sess.roomID]
- state.Recording, state.StopReason, state.LastError = false, reason, sess.lastErr
- state.RecordDurationSec, state.RecordBytes, state.RecordSegments = m.nowFunc().Sub(sess.startedAt).Seconds(), sess.bytesTotal, len(sess.segments)
- state.Incidents = cloneIncidents(sess.incidents)
- hydrateSessionPreviewFieldsLocked(&state, nil)
- m.states[sess.roomID] = state
- m.mu.Unlock()
- sess.itemMeta.Live.StopReason, sess.itemMeta.Live.EndedAt, sess.itemMeta.Live.EndTitle = reason, m.nowFunc().UTC().Format(time.RFC3339), state.Title
+ state := driver.finalizeState(reason, now)
+ if sess.itemMeta.Live != nil {
+ sess.itemMeta.Live.StopReason = reason
+ sess.itemMeta.Live.EndedAt = now.UTC().Format(time.RFC3339)
+ sess.itemMeta.Live.EndTitle = state.Title
+ }
sess.itemMeta.Status = "complete"
- if len(sess.itemMeta.Live.Segments) == 0 {
+ if !hasAnyLiveSegment(sess.itemMeta) {
sess.itemMeta.Status = "failed"
}
if reason != "ended" && reason != "user_stop" && reason != "app_closed" {
@@ -397,24 +369,108 @@ func (m *Manager) runRecordingSession(ctx context.Context, sess *recordSession,
if len(sess.itemMeta.PendingParts) > 0 || len(sess.itemMeta.Missing) > 0 {
sess.itemMeta.Status = "partial"
}
+ m.mu.Unlock()
+
if err := m.saveSession(sess); err != nil {
m.setSessionStop(sess, "storage", err)
- state.StopReason, state.LastError = "storage", "录像清单写入失败,已保留可恢复文件"
+ state.StopReason = "storage"
+ state.LastError = "录像清单写入失败,已保留可恢复文件"
m.mu.Lock()
- m.states[sess.roomID] = state
+ driver.saveStateLocked(state)
m.mu.Unlock()
}
if m.onState != nil {
+ leave := sess.enterExternal()
m.onState(state)
+ leave()
+ }
+}
+
+func (m *Manager) reconnectSessionLoop(
+ ctx context.Context,
+ sess *recordSession,
+ driver sessionDriver,
+ lostAt *time.Time,
+) bool {
+ for {
+ m.mu.Lock()
+ wait := m.reconnectWait
+ maxLoss := m.maxStreamLossDur
+ stopped := sess.stopReason != ""
+ m.mu.Unlock()
+ if stopped || ctx.Err() != nil {
+ return false
+ }
+ if wait > 0 {
+ timer := time.NewTimer(wait)
+ select {
+ case <-ctx.Done():
+ timer.Stop()
+ return false
+ case <-timer.C:
+ }
+ }
+ if ctx.Err() != nil {
+ return false
+ }
+
+ outcome, err := driver.reconnect(ctx)
+ switch outcome {
+ case reconnectOK:
+ return true
+ case reconnectEnded:
+ m.setSessionStop(sess, "ended", nil)
+ return false
+ case reconnectStop:
+ reason := liveStopReason(err)
+ if reason == "" {
+ reason = site.ErrKindBlocked
+ }
+ driver.reportStopError(ctx, err, reason)
+ m.setSessionStop(sess, reason, err)
+ return false
+ default:
+ if err != nil {
+ m.mu.Lock()
+ sess.lastErr = sanitizeLiveError(err)
+ m.mu.Unlock()
+ }
+ now := m.now()
+ if lostAt.IsZero() {
+ *lostAt = now
+ }
+ if maxLoss > 0 && now.Sub(*lostAt) >= maxLoss {
+ m.setSessionStop(sess, "stream_timeout", err)
+ return false
+ }
+ }
}
}
+func (m *Manager) checkDiskSpace(dir string, siteID site.ID) error {
+ m.mu.Lock()
+ freeFn := m.freeBytesFunc
+ minFree := m.minFreeBytes
+ m.mu.Unlock()
+ if freeFn == nil || minFree == 0 {
+ return nil
+ }
+ free, err := freeFn(dir)
+ if err != nil {
+ return err
+ }
+ if free < minFree {
+ return &site.Error{Site: siteID, Kind: site.ErrKindStorage, Message: "磁盘空间不足 1 GiB,已停止录制"}
+ }
+ return nil
+}
+
func (m *Manager) setSessionStop(sess *recordSession, reason string, err error) {
m.mu.Lock()
defer m.mu.Unlock()
sess.stopReason = reason
if err != nil {
- sess.lastErr = err.Error()
+ sess.lastErr = sanitizeLiveError(err)
}
}
@@ -436,325 +492,25 @@ func liveStopReason(err error) string {
return ""
}
-func (m *Manager) recordHLSSegment(ctx context.Context, sess *recordSession, urls []string, partPath string, isFMP4 bool) (written int64, result error) {
- if len(urls) == 0 || !isFMP4 {
- return 0, &bilibili.SiteError{Kind: bilibili.ErrKindUnavailable, Message: "没有可录制的 HLS fMP4 流"}
- }
- f, err := os.OpenFile(partPath, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0600)
- if err != nil {
- return 0, err
- }
- defer func() {
- if err := f.Sync(); err != nil && result == nil {
- result = err
- }
- if err := f.Close(); err != nil && result == nil {
- result = err
- }
- }()
- playlistURL, initURI := urls[0], ""
- followedVariant := false
- var initBytes []byte
- partBase := filepath.Base(partPath)
- lastNew := m.nowFunc()
- for ctx.Err() == nil {
- if m.freeBytesFunc != nil && m.minFreeBytes > 0 {
- free, err := m.freeBytesFunc(sess.itemDir)
- if err != nil {
- return written, err
- }
- if free < m.minFreeBytes {
- return written, &bilibili.SiteError{Kind: "storage", Message: "磁盘空间不足 1 GiB,已停止录制"}
- }
- }
- raw, err := m.fetchLiveLimitedBytes(ctx, playlistURL, maxM3U8PlaylistBytes)
- if err != nil {
- if written == 0 && len(urls) > 1 && playlistURL == urls[0] && liveStopReason(err) == "" {
- playlistURL = urls[1]
- continue
- }
- return written, err
- }
- playlist := parseM3U8PlaylistDetails(string(raw), playlistURL)
- if len(playlist.variants) > 0 && len(playlist.segments) == 0 && playlist.valid {
- // Some nodes answer with a multivariant playlist. Follow it once; a
- // second level of indirection is treated as a schema change.
- variant, ok := playlist.bestVariantInfo()
- if followedVariant || !ok {
- return written, &bilibili.SiteError{Kind: bilibili.ErrKindSchemaChanged, Message: "直播播放列表结构不完整(多级索引)"}
- }
- if err := m.client.ValidateMediaURL(variant.uri); err != nil {
- return written, &bilibili.SiteError{Kind: bilibili.ErrKindSchemaChanged, Message: "直播播放列表指向不受支持的节点"}
- }
- if variant.bandwidth > 0 {
- m.setSessionNominalBitrateBps(sess, variant.bandwidth)
- }
- playlistURL, followedVariant = variant.uri, true
- continue
- }
- if playlist.encrypted {
- return written, &bilibili.SiteError{Kind: bilibili.ErrKindBlocked, Message: "不支持加密的直播分片"}
- }
- if !playlist.valid {
- return written, &bilibili.SiteError{Kind: bilibili.ErrKindSchemaChanged, Message: "直播播放列表结构不完整:" + playlist.invalidReason}
- }
- m.markSessionReconnected(sess, m.nowFunc(), false, partBase)
- if sess.hasSequence && len(playlist.segments) > 0 && playlist.segments[len(playlist.segments)-1].seq < sess.lastSequence {
- // A sequence reset starts a new part even when the same init URI is
- // reused. Keeping the old watermark would skip the new broadcast data.
- sess.lastSequence, sess.hasSequence = 0, false
- return written, errSegmentRollover
- }
- newCount := 0
- if sess.wroteMedia && playlist.mapURI == initURI {
- for _, segment := range playlist.segments {
- if !sess.hasSequence || segment.seq > sess.lastSequence {
- freshInit, err := m.fetchLiveBytes(ctx, segment.mapURI)
- if err != nil {
- return written, err
- }
- if !bytes.Equal(freshInit, initBytes) {
- return written, errSegmentRollover
- }
- break
- }
- }
- }
- for _, segment := range playlist.segments {
- if sess.hasSequence && segment.seq <= sess.lastSequence {
- continue
- }
- if sess.wroteMedia && (segment.discontinuity || sess.hasSequence && segment.seq-sess.lastSequence > 4 || segment.mapURI != initURI) {
- return written, errSegmentRollover
- }
- if initURI == "" {
- initBytes, err = m.fetchLiveBytes(ctx, segment.mapURI)
- if err != nil {
- return written, err
- }
- if !validLiveInit(initBytes) {
- return written, &bilibili.SiteError{Kind: bilibili.ErrKindSchemaChanged, Message: "直播初始化分片缺少有效视频轨"}
- }
- initURI = segment.mapURI
- n, err := f.Write(initBytes)
- written += int64(n)
- m.addSessionBytes(sess, int64(n))
- if err != nil {
- return written, err
- }
- }
- if segment.discontinuity && sess.wroteMedia {
- return written, errSegmentRollover
- }
- fetchStart := m.nowFunc()
- fragment, err := m.fetchLiveBytes(ctx, segment.uri)
- fetchEnd := m.nowFunc()
- if err != nil {
- return written, err
- }
- if !validLiveFragment(fragment) {
- return written, &bilibili.SiteError{Kind: bilibili.ErrKindSchemaChanged, Message: "直播媒体分片不完整"}
- }
- n, err := f.Write(fragment)
- written += int64(n)
- m.addSessionBytes(sess, int64(n))
- if err != nil {
- return written, err
- }
- // Persist complete fragments only; fsync never leaves half a fragment as
- // the checkpoint used by startup recovery.
- if err := f.Sync(); err != nil {
- return written, err
- }
- if !segment.discontinuity && sess.hasSequence && segment.seq > sess.lastSequence+1 {
- dropped := int(segment.seq - sess.lastSequence - 1)
- targetDur := playlist.targetDuration
- if targetDur <= 0 {
- targetDur = segment.duration
- }
- if targetDur <= 0 {
- targetDur = 1.0
- }
- // A gap longer than the time since the previous segment cannot be
- // lost media: the restarted stream numbers its segments from a new
- // base (seen jumping by 100 million after a reconnect).
- if lostSec := float64(dropped) * targetDur; sess.lastSequenceAt.IsZero() || lostSec <= fetchEnd.Sub(sess.lastSequenceAt).Seconds()+hlsSequenceGapSlackSec {
- atStr := fetchEnd.UTC().Format(time.RFC3339)
- m.recordSessionIncident(sess, library.LiveIncident{
- Kind: library.LiveIncidentLostSegments,
- At: atStr,
- EndedAt: atStr,
- DurationSec: lostSec,
- LostSegments: dropped,
- Count: 1,
- Part: partBase,
- Reason: fmt.Sprintf("HLS 媒体分片序号跳号,丢失 %d 段", dropped),
- }, true)
- }
- }
- m.observeTransferSpeed(sess, fetchStart, fetchEnd, int64(len(fragment)), segment.duration, partBase)
- sess.lastSequence, sess.hasSequence, sess.wroteMedia = segment.seq, true, true
- sess.lastSequenceAt = fetchEnd
- sess.segmentDuration += segment.duration
- m.commitSessionPart(sess, written, sess.segmentDuration)
- seq, hasSeq, dur := sess.lastSequence, sess.hasSequence, sess.segmentDuration
- if err := m.saveCheckpoint(sess, func(meta *library.ItemMetadata) {
- meta.Live.LastSequence, meta.Live.HasSequence = seq, hasSeq
- meta.Live.PendingFile = partBase
- meta.Live.PendingBytes, meta.Live.PendingDuration = written, dur
- }); err != nil {
- return written, err
- }
- newCount++
- }
- now := m.nowFunc()
- if newCount > 0 {
- lastNew = now
- } else if m.noSegmentTimeout > 0 && now.Sub(lastNew) >= m.noSegmentTimeout {
- return written, &bilibili.SiteError{Kind: bilibili.ErrKindNetwork, Message: "超过 10 秒未收到新直播分片"}
- }
- if playlist.endList {
- return written, nil
- }
- wait := m.hlsPollInterval
- if wait <= 0 {
- wait = time.Duration(math.Max(1, math.Min(5, playlist.targetDuration)) * float64(time.Second))
- }
- select {
- case <-ctx.Done():
- case <-time.After(wait):
- }
- }
- return written, ctx.Err()
-}
-
-func validLiveInit(raw []byte) bool {
- file, err := mp4.DecodeFile(bytes.NewReader(raw), mp4.WithDecodeFlags(mp4.DecStartOnMoof))
- if err != nil || file == nil {
- return false
- }
- moov := file.Moov
- if file.Init != nil {
- moov = file.Init.Moov
- }
- if moov == nil {
- return false
+func sanitizeLiveError(err error) string {
+ if err == nil {
+ return ""
}
- for _, track := range moov.Traks {
- if track.Mdia != nil && track.Mdia.Hdlr != nil && track.Mdia.Hdlr.HandlerType == "vide" {
- return true
+ var se *site.Error
+ if errors.As(err, &se) {
+ if clean := library.SanitizeLiveIncidentText(se.Error()); clean != "" {
+ return clean
}
+ return "直播请求失败"
}
- return false
-}
-
-func validLiveFragment(raw []byte) bool {
- file, err := mp4.DecodeFile(bytes.NewReader(raw), mp4.WithDecodeFlags(mp4.DecStartOnMoof))
- if err != nil || file == nil || len(file.Segments) == 0 {
- return false
+ unwrapped := site.UnwrapURLError(err)
+ if unwrapped == nil {
+ unwrapped = err
}
- for _, segment := range file.Segments {
- for _, fragment := range segment.Fragments {
- if fragment.Moof != nil && fragment.Mdat != nil && len(fragment.Mdat.Data) > 0 {
- return true
- }
- }
+ if clean := library.SanitizeLiveIncidentText(unwrapped.Error()); clean != "" {
+ return clean
}
- return false
-}
-
-type contextFile struct {
- *os.File
- ctx context.Context
-}
-
-func (f contextFile) Read(p []byte) (int, error) {
- if err := f.ctx.Err(); err != nil {
- return 0, err
- }
- return f.File.Read(p)
-}
-func (f contextFile) Write(p []byte) (int, error) {
- if err := f.ctx.Err(); err != nil {
- return 0, err
- }
- return f.File.Write(p)
-}
-func (f contextFile) Seek(offset int64, whence int) (int64, error) {
- if err := f.ctx.Err(); err != nil {
- return 0, err
- }
- return f.File.Seek(offset, whence)
-}
-
-// Media samples stay on disk while mp4ff reads metadata and copies them to the
-// progressive output. The original .part remains until its manifest is saved.
-// The output must keep the source's own media timeline; the recorder's running
-// duration (HLS EXTINF sum) is only an estimate and is not compared.
-func finalizeLivePart(ctx context.Context, partPath, finalPath string) (download.MuxTrackSummary, error) {
- f, err := os.Open(partPath)
- if err != nil {
- return download.MuxTrackSummary{}, err
- }
- defer f.Close()
- source := contextFile{File: f, ctx: ctx}
- parsed, err := mp4.DecodeFile(source, mp4.WithDecodeMode(mp4.DecModeLazyMdat), mp4.WithDecodeFlags(mp4.DecStartOnMoof))
- if err != nil {
- return download.MuxTrackSummary{}, err
- }
- trimFragmentOverlaps(parsed)
- sourceSec := fragmentTimelineSec(parsed)
- out, err := os.CreateTemp(filepath.Dir(finalPath), ".trace-live-*.part")
- if err != nil {
- return download.MuxTrackSummary{}, err
- }
- name := out.Name()
- defer os.Remove(name)
- if err := mp4.Defragment(parsed, source, contextFile{File: out, ctx: ctx}); err != nil {
- _ = out.Close()
- return download.MuxTrackSummary{}, err
- }
- if err := out.Sync(); err != nil {
- _ = out.Close()
- return download.MuxTrackSummary{}, err
- }
- if err := out.Close(); err != nil {
- return download.MuxTrackSummary{}, err
- }
- summary, err := download.InspectMP4FileContext(ctx, name)
- if err != nil {
- return summary, err
- }
- if !finalizedLivePart(summary) || sourceSec > 0 && math.Abs(summary.DurationSec-sourceSec) > liveFinalizeToleranceSec {
- return summary, errors.New("直播录像轨道或时长校验失败")
- }
- if err := ctx.Err(); err != nil {
- return summary, err
- }
- if err := os.Rename(name, finalPath); err != nil {
- return summary, err
- }
- return summary, nil
-}
-
-// hlsSequenceGapSlackSec is how much a sequence gap may exceed the time since
-// the previous segment and still count as lost segments (EXTINF rounding and
-// playlist windows), rather than as a restarted stream's new numbering.
-const hlsSequenceGapSlackSec = 30.0
-
-// liveFinalizeToleranceSec bounds how far the converted duration may differ
-// from the source timeline. Real Bilibili parts differ by under 0.02 s (the
-// audio and video tracks end a fraction of a frame apart).
-const liveFinalizeToleranceSec = 1.0
-
-// finalizedLivePart reports whether an MP4 is a converted recording: a video
-// track, moov before mdat and a positive duration.
-func finalizedLivePart(summary download.MuxTrackSummary) bool {
- video := false
- for _, handler := range summary.Handlers {
- video = video || handler == "vide"
- }
- return video && summary.MoovBeforeMdat && summary.DurationSec > 0
+ return "直播请求失败"
}
func mergeLiveMedia(files []library.MediaFile, added library.MediaFile) []library.MediaFile {
@@ -766,6 +522,7 @@ func mergeLiveMedia(files []library.MediaFile, added library.MediaFile) []librar
}
return append(files, added)
}
+
func removePending(values []string, value string) []string {
var result []string
for _, candidate := range values {
@@ -785,10 +542,12 @@ func mergeLiveSegment(segments []library.LiveSegmentInfo, added library.LiveSegm
}
return append(segments, added)
}
+
func addLiveMissing(meta *library.ItemMetadata, item, reason string) {
clearLiveMissing(meta, item)
meta.Missing = append(meta.Missing, library.MissingRecord{Item: item, Reason: reason})
}
+
func clearLiveMissing(meta *library.ItemMetadata, item string) {
var keep []library.MissingRecord
for _, missing := range meta.Missing {
@@ -799,10 +558,11 @@ func clearLiveMissing(meta *library.ItemMetadata, item string) {
meta.Missing = keep
}
-func clearLiveCheckpoint(meta *library.ItemMetadata, rel string) {
- if meta.Live != nil && meta.Live.PendingFile == rel {
- meta.Live.PendingFile, meta.Live.PendingBytes, meta.Live.PendingDuration = "", 0, 0
+func clearLiveCheckpoint(meta *library.ItemMetadata, pending string) {
+ if meta.Live == nil || meta.Live.PendingFile != pending {
+ return
}
+ meta.Live.PendingFile = ""
+ meta.Live.PendingBytes = 0
+ meta.Live.PendingDuration = 0
}
-
-var _ io.ReadSeeker = contextFile{}
diff --git a/internal/live/recovery.go b/internal/live/recovery.go
new file mode 100644
index 0000000..19721e4
--- /dev/null
+++ b/internal/live/recovery.go
@@ -0,0 +1,239 @@
+package live
+
+import (
+ "context"
+ "os"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/chialecode/trace/internal/download"
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/site"
+ "github.com/chialecode/trace/internal/site/bilibili"
+)
+
+// RecoverOrphanParts processes only files named in a live item's pending list.
+// It also converts a registered live segment saved without a duration (raw
+// fragments under the final name), while skipping already-finalized short
+// segments whose SHA256 and Live.Segments duration are recorded. Unrelated
+// files and user-created .part files are never scanned or renamed.
+func (m *Manager) RecoverOrphanParts() {
+ if m.lib == nil {
+ return
+ }
+ for offset := 0; ; offset += 200 {
+ items, err := m.lib.ListItems(library.FeedFilter{Kind: "live", Limit: 200, Offset: offset})
+ if err != nil {
+ return
+ }
+ for _, meta := range items {
+ m.mu.Lock()
+ active := false
+ for _, session := range m.sessions {
+ active = active || session.itemDir == meta.ItemDir
+ }
+ for _, session := range m.douyinSessions {
+ active = active || session.itemDir == meta.ItemDir
+ }
+ timeout := m.finalizeTimeout
+ m.mu.Unlock()
+ if active {
+ continue
+ }
+ if timeout <= 0 {
+ timeout = 30 * time.Second
+ }
+
+ // A segment saved with no duration was never converted (an earlier
+ // recovery accepted raw fragments); convert it like a pending part,
+ // unless SHA256 + Live.Segments already confirm it was finalized.
+ for _, media := range meta.Media {
+ if media.Role != "live_segment" || media.Duration > 0 || !strings.HasPrefix(media.Path, "part-") {
+ continue
+ }
+ if hasFinalizedLiveSegment(meta, media) {
+ continue
+ }
+ pending := media.Path + ".part"
+ if !slices.Contains(meta.PendingParts, pending) {
+ meta.PendingParts = append(meta.PendingParts, pending)
+ }
+ }
+ if len(meta.PendingParts) == 0 {
+ continue
+ }
+ var remaining []string
+ for _, rel := range meta.PendingParts {
+ if !strings.HasPrefix(rel, "part-") || !strings.HasSuffix(rel, ".mp4.part") {
+ remaining = append(remaining, rel)
+ continue
+ }
+ partPath, err := library.ResolveItemPath(meta.ItemDir, rel)
+ if err != nil {
+ remaining = append(remaining, rel)
+ continue
+ }
+ finalRel := strings.TrimSuffix(rel, ".part")
+ finalPath, err := library.ResolveItemPath(meta.ItemDir, finalRel)
+ if err != nil {
+ remaining = append(remaining, rel)
+ continue
+ }
+
+ partInfo, partStatErr := os.Stat(partPath)
+ _, finalStatErr := os.Stat(finalPath)
+ pendingEmpty := (os.IsNotExist(partStatErr) || (partStatErr == nil && partInfo.Size() == 0)) &&
+ os.IsNotExist(finalStatErr) &&
+ (meta.Live == nil || meta.Live.PendingFile != rel || meta.Live.PendingBytes == 0)
+ if pendingEmpty {
+ if partStatErr == nil {
+ _ = removeFileWithRetry(partPath)
+ }
+ clearLiveMissing(&meta, rel)
+ clearLiveCheckpoint(&meta, rel)
+ continue
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), timeout)
+ if meta.Live != nil && meta.Live.PendingFile == rel {
+ if partStatErr == nil && meta.Live.PendingBytes > 0 && partInfo.Size() > meta.Live.PendingBytes {
+ err = os.Truncate(partPath, meta.Live.PendingBytes)
+ }
+ }
+ var summary download.MuxTrackSummary
+ if err == nil {
+ if os.IsNotExist(partStatErr) {
+ summary, err = download.InspectMP4FileContext(ctx, finalPath)
+ if err == nil && !finalizedLivePart(summary) {
+ // The final name holds the unconverted fragments (for example a
+ // ".part" renamed by hand): convert it instead of accepting it.
+ if err = os.Rename(finalPath, partPath); err == nil {
+ if summary, err = finalizeLivePart(ctx, partPath, finalPath); err == nil {
+ _ = removeFileWithRetry(partPath)
+ } else {
+ _ = os.Rename(partPath, finalPath) // keep the file where the item expects it
+ }
+ }
+ }
+ } else {
+ summary, err = finalizeLivePart(ctx, partPath, finalPath)
+ }
+ }
+ cancel()
+ if err != nil {
+ remaining = append(remaining, rel)
+ addLiveMissing(&meta, rel, "转换失败")
+ if meta.Live != nil && !hasConvertFailedIncident(meta.Live.Incidents, rel) {
+ meta.Live.Incidents, _, _ = appendCoalescedIncident(meta.Live.Incidents, library.LiveIncident{
+ Kind: library.LiveIncidentConvertFailed,
+ At: m.now().UTC().Format(time.RFC3339),
+ Part: rel,
+ Reason: "直播录像转换失败:" + sanitizeLiveError(err),
+ })
+ }
+ continue
+ }
+ meta.Media = mergeLiveMedia(meta.Media, library.MediaFile{
+ Role: "live_segment",
+ Path: finalRel,
+ Bytes: summary.FileBytes,
+ SHA256: summary.SHA256,
+ Duration: roundedLiveDurationSec(summary.DurationSec),
+ Width: summary.Width,
+ Height: summary.Height,
+ })
+ if meta.Live != nil {
+ codec := meta.Live.Codec
+ if codec == "" && len(summary.Codecs) > 0 {
+ codec = summary.Codecs[0]
+ meta.Live.Codec = codec
+ }
+ qName := meta.Live.QualityName
+ if qName == "" && meta.Live.Quality > 0 && (meta.Site == "" || meta.Site == string(site.Bilibili)) {
+ qName = bilibili.LiveQualityFallbackName(meta.Live.Quality)
+ }
+ meta.Live.QualityName = qName
+ meta.Live.Segments = mergeLiveSegment(meta.Live.Segments, library.LiveSegmentInfo{
+ File: finalRel,
+ Bytes: summary.FileBytes,
+ SHA256: summary.SHA256,
+ DurationSec: summary.DurationSec,
+ Codec: codec,
+ Quality: meta.Live.Quality,
+ QualityName: qName,
+ Width: summary.Width,
+ Height: summary.Height,
+ })
+ meta.Live.Incidents = dropResolvedConvertFailed(meta.Live.Incidents, rel)
+ }
+ clearLiveMissing(&meta, rel)
+ clearLiveCheckpoint(&meta, rel)
+ }
+ meta.PendingParts = remaining
+ meta.Status = "complete"
+ if !hasAnyLiveSegment(meta) {
+ meta.Status = "failed"
+ }
+ if len(remaining) > 0 || len(meta.Missing) > 0 {
+ meta.Status = "partial"
+ }
+ if meta.Live != nil && meta.Live.StopReason == "" {
+ meta.Live.StopReason = "app_closed"
+ meta.Live.EndedAt = m.now().UTC().Format(time.RFC3339)
+ }
+ if _, err := m.lib.SaveItem(meta.ItemDir, meta); err == nil {
+ for _, original := range itemsPendingToRemove(items, meta) {
+ if path, err := library.ResolveItemPath(meta.ItemDir, original); err == nil {
+ _ = removeFileWithRetry(path)
+ }
+ }
+ }
+ }
+ if len(items) < 200 {
+ return
+ }
+ }
+}
+
+func hasFinalizedLiveSegment(meta library.ItemMetadata, media library.MediaFile) bool {
+ if media.SHA256 == "" || meta.Live == nil {
+ return false
+ }
+ for _, seg := range meta.Live.Segments {
+ if seg.File == media.Path && seg.DurationSec > 0 {
+ return true
+ }
+ }
+ return false
+}
+
+func hasAnyLiveSegment(meta library.ItemMetadata) bool {
+ if meta.Live != nil && len(meta.Live.Segments) > 0 {
+ return true
+ }
+ for _, mf := range meta.Media {
+ if mf.Role == "live_segment" {
+ return true
+ }
+ }
+ return false
+}
+
+func itemsPendingToRemove(items []library.ItemMetadata, saved library.ItemMetadata) []string {
+ var result []string
+ for _, item := range items {
+ if item.ItemKey == saved.ItemKey {
+ for _, rel := range item.PendingParts {
+ found := false
+ for _, pending := range saved.PendingParts {
+ found = found || rel == pending
+ }
+ if !found {
+ result = append(result, rel)
+ }
+ }
+ }
+ }
+ return result
+}
diff --git a/internal/live/regression_test.go b/internal/live/regression_test.go
index d84584d..f958b0c 100644
--- a/internal/live/regression_test.go
+++ b/internal/live/regression_test.go
@@ -253,7 +253,7 @@ func TestRecordingPreservesUserOwnedTargetName(t *testing.T) {
// Some live nodes answer the playurl address with a multivariant playlist; the
// recorder follows the best variant once and records from the media playlist,
// whose entries are relative and carry Bilibili-style EXTINF titles and the
-// site's own #EXT-BILI-AUX tag (seen in ACT-007).
+// site's own #EXT-BILI-AUX tag.
func TestRecorderFollowsMultivariantPlaylistOnce(t *testing.T) {
init, fragment := regressionLiveSamples(t)
var masterHits atomic.Int32
diff --git a/internal/live/remux.go b/internal/live/remux.go
index 70a62f7..43ce17e 100644
--- a/internal/live/remux.go
+++ b/internal/live/remux.go
@@ -16,6 +16,7 @@ const (
videoTimescale uint32 = 90000
defaultSingleTrackWaitMs int64 = 3000
+ defaultKeyframeWaitMs int64 = 30_000
defaultMinKeyframeMs int64 = 1000
defaultMaxFragmentMs int64 = 2000
defaultMaxFragmentBytes int64 = 4 * 1024 * 1024
@@ -24,6 +25,8 @@ const (
preKeyframeAudioKeepWindowMs int64 = 100
maxPreKeyframeAudioSamples int = 256
+ maxBufferedAudioSamples int = 512
+ maxPreInitAudioSamples int = 1024
)
// ErrNoVideoKeyframe indicates the FLV stream ended before a decodable video keyframe arrived.
@@ -191,7 +194,7 @@ func (rm *FLVRemuxer) WritePart(
if errors.Is(err, io.EOF) {
rm.eofReached = true
if !ps.started {
- if ps.preAudioSeen {
+ if ps.preAudioSeen && !ps.preVideoSeen && ps.activeVideoCfg == nil {
return FLVCheckpoint{}, &UnsupportedCodecError{
Media: "stream",
Codec: "audio-only",
@@ -207,8 +210,11 @@ func (rm *FLVRemuxer) WritePart(
}
// On truncated tail or read error after valid frames were buffered, flush already-verified
// complete samples before surfacing the stream error so checkpoints stay current.
+ // Never swallow storage/disk-full errors from flushing.
if ps.started && (errors.Is(err, ErrFLVTruncated) || (!IsFLVFormatError(err) && !IsUnsupportedCodec(err))) {
- _ = ps.flushFinal()
+ if flushErr := ps.flushFinal(); flushErr != nil && (isDiskFullError(flushErr) || liveStopReason(flushErr) == "storage") {
+ return ps.lastCheckpoint, flushErr
+ }
}
return ps.lastCheckpoint, err
}
@@ -242,6 +248,7 @@ func (rm *FLVRemuxer) WritePart(
case ParsedTagVideoConfig:
newCfg := pkt.VideoConfig
+ ps.preVideoSeen = true
if ps.started && ps.activeVideoCfg != nil {
if bytes.Equal(newCfg.Canonical, ps.activeVideoCfg.Canonical) {
// Identical parameter-set resend: update wire NALU prefix length if needed, do not split.
@@ -324,7 +331,8 @@ type partWriterState struct {
activeVideoCfg *VideoConfig
activeAudioCfg *AudioConfig
- // Pre-keyframe audio tracking (detects >3s audio-only streams and preserves simultaneous t=0 AAC).
+ // Pre-keyframe track presence (detects >3s audio-only streams without killing >3s GOP video streams).
+ preVideoSeen bool
preAudioSeen bool
preAudioUnwrap tsUnwrapper
preAudioOriginMs int64
@@ -353,6 +361,7 @@ type partWriterState struct {
lastVideoDur uint32
lastAudioDur uint32
+ encodeBuf bytes.Buffer
seqNumber uint32
writtenBytes int64
flushedVideoEndDTS uint64
@@ -364,6 +373,7 @@ type partWriterState struct {
}
func (ps *partWriterState) handleVideoFrame(pkt ParsedTag) (rollover bool, err error) {
+ ps.preVideoSeen = true
if ps.activeVideoCfg == nil || ps.activeVideoCfg.Codec != pkt.VideoCodec {
return false, nil
}
@@ -491,20 +501,22 @@ func (ps *partWriterState) handleAudioFrame(pkt ParsedTag) (rollover bool, err e
if !ps.preAudioSeen {
ps.preAudioSeen = true
ps.preAudioOriginMs = aMs
- } else if aMs-ps.preAudioOriginMs > ps.opts.SingleTrackWaitMs {
- return false, &UnsupportedCodecError{
- Media: "stream",
- Codec: "audio-only",
- Reason: "超过 3 秒仅收到音频包而无视频关键帧",
+ } else if elapsedMs := aMs - ps.preAudioOriginMs; !ps.preVideoSeen && ps.activeVideoCfg == nil {
+ if elapsedMs > ps.opts.SingleTrackWaitMs {
+ return false, &UnsupportedCodecError{
+ Media: "stream",
+ Codec: "audio-only",
+ Reason: "超过 3 秒仅收到音频包而无视频关键帧",
+ }
}
+ } else if elapsedMs > max(ps.opts.SingleTrackWaitMs*10, defaultKeyframeWaitMs) {
+ return false, ErrNoVideoKeyframe
}
if ps.activeAudioCfg != nil {
- cp := make([]byte, len(pkt.RawPayload))
- copy(cp, pkt.RawPayload)
ps.preAudioPackets = append(ps.preAudioPackets, preKeyframeAudioPacket{
rawTS: pkt.Timestamp,
unwrappedMs: aMs,
- data: cp,
+ data: pkt.RawPayload,
})
if len(ps.preAudioPackets) > maxPreKeyframeAudioSamples {
ps.preAudioPackets = ps.preAudioPackets[len(ps.preAudioPackets)-maxPreKeyframeAudioSamples:]
@@ -525,7 +537,8 @@ func (ps *partWriterState) handleAudioFrame(pkt ParsedTag) (rollover bool, err e
}
func (ps *partWriterState) appendAudioSample(rawTS uint32, rawPayload []byte) (rollover bool, err error) {
- unwrappedMs := ps.audioUnwrap.unwrap(rawTS)
+ candidateUnwrap := ps.audioUnwrap.clone()
+ unwrappedMs := candidateUnwrap.unwrap(rawTS)
relMs := unwrappedMs - ps.originMs
if ps.hasPrevAudio {
deltaMs := relMs - ps.prevAudioMs
@@ -538,8 +551,9 @@ func (ps *partWriterState) appendAudioSample(rawTS uint32, rawPayload []byte) (r
ps.prevAudioMs = relMs
}
} else {
+ // Drop out-of-window initial audio instead of rolling over in an infinite 1-frame loop.
if relMs < -ps.opts.MaxBackwardJumpMs || relMs > ps.opts.MaxForwardJumpMs {
- return true, nil
+ return false, nil
}
if relMs < 0 {
relMs = 0
@@ -547,6 +561,7 @@ func (ps *partWriterState) appendAudioSample(rawTS uint32, rawPayload []byte) (r
ps.prevAudioMs = relMs
ps.hasPrevAudio = true
}
+ ps.audioUnwrap = candidateUnwrap
dts := mulDiv64(uint64(relMs), uint64(ps.activeAudioCfg.SampleRate), 1000)
if len(ps.aBuf) > 0 || ps.minAudioDTS > 0 {
@@ -576,14 +591,32 @@ func (ps *partWriterState) appendAudioSample(rawTS uint32, rawPayload []byte) (r
ps.lastAudioDur = uint32(dur64)
}
- dataCopy := make([]byte, len(rawPayload))
- copy(dataCopy, rawPayload)
ps.aBuf = append(ps.aBuf, bufferedMediaSample{
dts: dts,
isKeyframe: true,
- data: dataCopy,
+ data: rawPayload,
})
- ps.bufferedBytes += int64(len(dataCopy))
+ ps.bufferedBytes += int64(len(rawPayload))
+
+ // Bound audio buffer memory if the video track stalls while audio continues arriving.
+ if ps.initWritten && ps.initHasAudio {
+ if len(ps.aBuf) >= maxBufferedAudioSamples || ps.bufferedBytes >= ps.opts.MaxFragmentBytes {
+ if err := ps.flushAudioOnly(); err != nil {
+ return false, err
+ }
+ }
+ } else if !ps.initWritten && len(ps.aBuf) > maxPreInitAudioSamples {
+ excess := len(ps.aBuf) - maxPreInitAudioSamples
+ for i := 0; i < excess; i++ {
+ ps.bufferedBytes -= int64(len(ps.aBuf[i].data))
+ }
+ if ps.bufferedBytes < 0 {
+ ps.bufferedBytes = 0
+ }
+ kept := make([]bufferedMediaSample, maxPreInitAudioSamples)
+ copy(kept, ps.aBuf[excess:])
+ ps.aBuf = kept
+ }
return false, nil
}
@@ -600,8 +633,35 @@ func (ps *partWriterState) flushPending(flushAll bool) error {
return err
}
}
+ vFlush, aFlush := ps.selectFlushSamples(flushAll)
+ if len(vFlush) == 0 && len(aFlush) == 0 {
+ return nil
+ }
+ frag, err := ps.buildMediaFragment(vFlush, aFlush)
+ if err != nil {
+ return err
+ }
+ return ps.writeAndCheckpointFragment(frag)
+}
- var vFlush []bufferedMediaSample
+// flushAudioOnly drains buffered audio samples while preserving any in-flight video lookahead frame.
+func (ps *partWriterState) flushAudioOnly() error {
+ if !ps.initWritten || !ps.initHasAudio || len(ps.aBuf) < 2 {
+ return nil
+ }
+ split := len(ps.aBuf) - 1
+ aFlush := ps.aBuf[:split]
+ remaining := make([]bufferedMediaSample, 1)
+ remaining[0] = ps.aBuf[split]
+ ps.aBuf = remaining
+ frag, err := ps.buildMediaFragment(nil, aFlush)
+ if err != nil {
+ return err
+ }
+ return ps.writeAndCheckpointFragment(frag)
+}
+
+func (ps *partWriterState) selectFlushSamples(flushAll bool) (vFlush, aFlush []bufferedMediaSample) {
if flushAll {
if len(ps.vBuf) > 0 {
lastIdx := len(ps.vBuf) - 1
@@ -622,7 +682,6 @@ func (ps *partWriterState) flushPending(flushAll bool) error {
ps.vBuf = nil
}
- var aFlush []bufferedMediaSample
if ps.initHasAudio && len(ps.aBuf) > 0 {
if flushAll {
lastIdx := len(ps.aBuf) - 1
@@ -660,11 +719,10 @@ func (ps *partWriterState) flushPending(flushAll bool) error {
} else if !ps.initHasAudio {
ps.aBuf = nil
}
+ return vFlush, aFlush
+}
- if len(vFlush) == 0 && len(aFlush) == 0 {
- return nil
- }
-
+func (ps *partWriterState) buildMediaFragment(vFlush, aFlush []bufferedMediaSample) (*mp4.Fragment, error) {
var trackIDs []uint32
if len(vFlush) > 0 {
trackIDs = append(trackIDs, 1)
@@ -676,7 +734,7 @@ func (ps *partWriterState) flushPending(flushAll bool) error {
ps.seqNumber++
frag, err := mp4.CreateMultiTrackFragment(ps.seqNumber, trackIDs)
if err != nil {
- return err
+ return nil, err
}
videoSyncFlags := mp4.SyncSampleFlags
@@ -702,7 +760,7 @@ func (ps *partWriterState) flushPending(flushAll bool) error {
DecodeTime: s.dts,
Data: s.data,
}, 1); err != nil {
- return err
+ return nil, err
}
ps.flushedVideoEndDTS = s.dts + uint64(dur)
ps.flushedVideoDur += uint64(dur)
@@ -722,19 +780,22 @@ func (ps *partWriterState) flushPending(flushAll bool) error {
DecodeTime: s.dts,
Data: s.data,
}, 2); err != nil {
- return err
+ return nil, err
}
ps.flushedAudioEndDTS = s.dts + uint64(dur)
ps.flushedAudioDur += uint64(dur)
ps.minAudioDTS = ps.flushedAudioEndDTS
ps.flushedAnyAudio = true
}
+ return frag, nil
+}
- var fragBuf bytes.Buffer
- if err := frag.Encode(&fragBuf); err != nil {
+func (ps *partWriterState) writeAndCheckpointFragment(frag *mp4.Fragment) error {
+ ps.encodeBuf.Reset()
+ if err := frag.Encode(&ps.encodeBuf); err != nil {
return err
}
- n, err := ps.target.Write(fragBuf.Bytes())
+ n, err := ps.target.Write(ps.encodeBuf.Bytes())
ps.writtenBytes += int64(n)
if err != nil {
return err
@@ -743,7 +804,6 @@ func (ps *partWriterState) flushPending(flushAll bool) error {
return err
}
- // Recompute remaining buffered payload size.
var remBytes int64
for _, s := range ps.vBuf {
remBytes += int64(len(s.data))
@@ -819,11 +879,11 @@ func (ps *partWriterState) writeInitSegment() error {
}
}
- var initBuf bytes.Buffer
- if err := init.Encode(&initBuf); err != nil {
+ ps.encodeBuf.Reset()
+ if err := init.Encode(&ps.encodeBuf); err != nil {
return fmt.Errorf("live: 编码 fMP4 InitSegment 失败: %w", err)
}
- n, err := ps.target.Write(initBuf.Bytes())
+ n, err := ps.target.Write(ps.encodeBuf.Bytes())
ps.writtenBytes += int64(n)
if err != nil {
return err
diff --git a/internal/live/site_provider.go b/internal/live/site_provider.go
new file mode 100644
index 0000000..d8be116
--- /dev/null
+++ b/internal/live/site_provider.go
@@ -0,0 +1,391 @@
+package live
+
+import (
+ "context"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/chialecode/trace/internal/site"
+)
+
+const (
+ defaultDouyinAutoPollInterval = 90 * time.Second
+ // DefaultDouyinLiveGap is the least time between two Douyin live checks.
+ // Douyin has no batch status request, so each account costs a request;
+ // a round checks every account it can at this pace (a 3-minute round:
+ // 30 accounts), the longest unchecked first, and an account's interval
+ // grows past the round only by this gap per further account. The checks
+ // do not take the site's hourly quota, which stays for update checks,
+ // automatic caching and starting recordings (DEC-060 ⑤).
+ DefaultDouyinLiveGap = 6 * time.Second
+)
+
+// LiveRoomAliveChecker is an optional extension on site.LiveProvider for batch room alive checks (e.g. Douyin check_alive).
+type LiveRoomAliveChecker interface {
+ CheckRoomsAlive(ctx context.Context, roomIDs []string) (map[string]bool, error)
+}
+
+// LiveAuthChecker is an optional extension on site.LiveProvider to report whether site credentials are active.
+type LiveAuthChecker interface {
+ HasAuth() bool
+}
+
+// LiveErrorReporter is an optional extension on site.LiveProvider to report automatic background errors.
+type LiveErrorReporter interface {
+ ReportAutomaticError(ctx context.Context, err error)
+}
+
+// WebRIDSyncFunc persists a backfilled or invalidated Douyin web_rid back to subscription storage.
+type WebRIDSyncFunc func(siteID site.ID, uid, webRID string, invalidated bool)
+
+// SiteBackoffChecker reports whether background polling for a given site is currently in backoff.
+type SiteBackoffChecker func(siteID site.ID) (bool, time.Time)
+
+// RegisterSiteProvider registers a cross-site LiveProvider (such as Douyin or Bilibili).
+func (m *Manager) RegisterSiteProvider(provider site.LiveProvider) {
+ if provider == nil {
+ return
+ }
+ m.mu.Lock()
+ m.siteProviders[provider.SiteID()] = provider
+ m.mu.Unlock()
+}
+
+// SetWebRIDSyncFunc sets a callback invoked whenever Douyin live status backfills or invalidates an account's web_rid.
+func (m *Manager) SetWebRIDSyncFunc(fn WebRIDSyncFunc) {
+ m.mu.Lock()
+ m.webRIDSyncFn = fn
+ m.mu.Unlock()
+}
+
+// SetSiteBackoffChecker sets a per-site backoff predicate used by background live polling.
+func (m *Manager) SetSiteBackoffChecker(fn SiteBackoffChecker) {
+ m.mu.Lock()
+ m.siteBackoffFn = fn
+ m.mu.Unlock()
+}
+
+// SetDouyinPollMinInterval overrides the 90s minimum per-account auto-record poll interval (used by unit tests).
+func (m *Manager) SetDouyinPollMinInterval(d time.Duration) {
+ m.mu.Lock()
+ if d >= 0 {
+ m.douyinPollMinInterval = d
+ }
+ m.mu.Unlock()
+}
+
+// SetDouyinLiveGap overrides the least time between two Douyin live checks
+// (used by unit tests; 0 sends them back to back).
+func (m *Manager) SetDouyinLiveGap(d time.Duration) {
+ m.mu.Lock()
+ m.douyinLiveGap = max(d, 0)
+ m.mu.Unlock()
+}
+
+// DouyinLiveGap is the least time between two Douyin live checks.
+func (m *Manager) DouyinLiveGap() time.Duration {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return m.douyinLiveGap
+}
+
+// DouyinLiveCheckEvery estimates how often each of n auto-record Douyin
+// accounts gets its live status checked.
+func (m *Manager) DouyinLiveCheckEvery(n int) time.Duration {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if n <= 0 {
+ return 0
+ }
+ sec := max(m.liveSettings.PollIntervalSeconds, 60)
+ per := m.douyinLiveChecksPerRoundLocked()
+ rounds := (n + per - 1) / per
+ return max(m.douyinPollMinInterval, time.Duration(rounds*sec)*time.Second)
+}
+
+// SetFLVIdleTimeout overrides the 15s per-read idle timeout on HTTP-FLV streams (used by unit tests).
+func (m *Manager) SetFLVIdleTimeout(d time.Duration) {
+ m.mu.Lock()
+ if d > 0 {
+ m.flvIdleTimeout = d
+ }
+ m.mu.Unlock()
+}
+
+func (m *Manager) getSiteProvider(siteID site.ID) (site.LiveProvider, bool) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ p, ok := m.siteProviders[siteID]
+ return p, ok
+}
+
+func (m *Manager) hasSiteAuth(siteID site.ID) bool {
+ if siteID == site.Bilibili {
+ return m.client != nil && m.client.HasAuth()
+ }
+ p, ok := m.getSiteProvider(siteID)
+ if !ok {
+ return false
+ }
+ if checker, ok := p.(LiveAuthChecker); ok {
+ return checker.HasAuth()
+ }
+ return true
+}
+
+func (m *Manager) isSiteInBackoff(siteID site.ID) bool {
+ m.mu.Lock()
+ fn := m.siteBackoffFn
+ m.mu.Unlock()
+ if fn != nil {
+ inBackoff, _ := fn(siteID)
+ return inBackoff
+ }
+ if m.subs != nil {
+ if perSite, ok := any(m.subs).(interface {
+ IsSiteInBackoff(site string) (bool, time.Time)
+ }); ok {
+ inBackoff, _ := perSite.IsSiteInBackoff(string(siteID))
+ return inBackoff
+ }
+ if siteID == site.Bilibili {
+ inBackoff, _ := m.subs.IsInBackoff()
+ return inBackoff
+ }
+ }
+ return false
+}
+
+func (m *Manager) recordSiteAutoStop(siteID site.ID, reason string) {
+ if m.subs == nil {
+ return
+ }
+ if perSite, ok := any(m.subs).(interface {
+ RecordSiteAutomaticStop(site, reason string)
+ }); ok {
+ perSite.RecordSiteAutomaticStop(string(siteID), reason)
+ return
+ }
+ if siteID == site.Bilibili {
+ m.subs.RecordAutomaticStop(reason)
+ }
+}
+
+func (m *Manager) syncWebRID(siteID site.ID, uid, webRID string, invalidated bool) {
+ m.mu.Lock()
+ fn := m.webRIDSyncFn
+ m.mu.Unlock()
+ if fn != nil {
+ fn(siteID, uid, webRID, invalidated)
+ }
+ if m.subs != nil {
+ if updater, ok := any(m.subs).(interface {
+ UpdateAccountWebRID(site, uid, webRID string) error
+ }); ok {
+ _ = updater.UpdateAccountWebRID(string(siteID), uid, webRID)
+ }
+ }
+}
+
+// StartRecordingByKey dispatches live recording start by canonical room/account key or numeric Bilibili room ID.
+func (m *Manager) StartRecordingByKey(ctx context.Context, key string) (RoomState, error) {
+ key = strings.TrimSpace(key)
+ if key == "" {
+ return RoomState{}, &site.Error{Kind: site.ErrKindBadRequest, Message: "无效的直播间标识"}
+ }
+ switch {
+ case strings.HasPrefix(key, "douyin:live:"):
+ rid := strings.TrimSpace(strings.TrimPrefix(key, "douyin:live:"))
+ if rid == "" {
+ return RoomState{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindBadRequest, Message: "无效的直播间标识"}
+ }
+ return m.StartDouyinRecording(ctx, "", rid)
+ case strings.HasPrefix(key, "douyin:user:"):
+ uid := strings.TrimSpace(strings.TrimPrefix(key, "douyin:user:"))
+ if uid == "" {
+ return RoomState{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindBadRequest, Message: "无效的直播间标识"}
+ }
+ return m.StartDouyinRecording(ctx, uid, "")
+ case strings.HasPrefix(key, "douyin:web:"):
+ webRID := strings.TrimSpace(strings.TrimPrefix(key, "douyin:web:"))
+ if webRID == "" {
+ return RoomState{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindBadRequest, Message: "无效的直播间标识"}
+ }
+ return m.StartDouyinRecording(ctx, "", webRID)
+ case strings.HasPrefix(key, "douyin:"):
+ uid := strings.TrimSpace(strings.TrimPrefix(key, "douyin:"))
+ if uid == "" {
+ return RoomState{}, &site.Error{Site: site.Douyin, Kind: site.ErrKindBadRequest, Message: "无效的直播间标识"}
+ }
+ return m.StartDouyinRecording(ctx, uid, "")
+ case strings.HasPrefix(key, "bilibili:live:"):
+ rid, err := strconv.ParseInt(strings.TrimSpace(strings.TrimPrefix(key, "bilibili:live:")), 10, 64)
+ if err != nil || rid <= 0 {
+ return RoomState{}, &site.Error{Site: site.Bilibili, Kind: site.ErrKindBadRequest, Message: "无效的直播间房间号"}
+ }
+ return m.StartRecording(ctx, rid)
+ case strings.HasPrefix(key, "bilibili:user:"), strings.HasPrefix(key, "bilibili:"):
+ rest := strings.TrimPrefix(key, "bilibili:user:")
+ byUIDOnly := strings.HasPrefix(key, "bilibili:user:")
+ if !byUIDOnly {
+ rest = strings.TrimPrefix(key, "bilibili:")
+ }
+ num, err := strconv.ParseInt(strings.TrimSpace(rest), 10, 64)
+ if err != nil || num <= 0 {
+ return RoomState{}, &site.Error{Site: site.Bilibili, Kind: site.ErrKindBadRequest, Message: "无效的直播间标识"}
+ }
+ if !byUIDOnly {
+ m.mu.Lock()
+ _, hasRoom := m.states[num]
+ m.mu.Unlock()
+ if hasRoom {
+ return m.StartRecording(ctx, num)
+ }
+ }
+ rooms, err := m.RefreshForAccounts(ctx, []int64{num})
+ if err != nil {
+ return RoomState{}, err
+ }
+ if len(rooms) == 0 || rooms[0].RoomID <= 0 {
+ return RoomState{}, &site.Error{Site: site.Bilibili, Kind: site.ErrKindUnavailable, Message: "该账号未开通直播间"}
+ }
+ return m.StartRecording(ctx, rooms[0].RoomID)
+ default:
+ if rid, err := strconv.ParseInt(key, 10, 64); err == nil && rid > 0 {
+ m.mu.Lock()
+ _, isDouyinRoom := m.douyinStates["douyin:live:"+key]
+ m.mu.Unlock()
+ if isDouyinRoom {
+ return m.StartDouyinRecording(ctx, "", key)
+ }
+ return m.StartRecording(ctx, rid)
+ }
+ return RoomState{}, &site.Error{Kind: site.ErrKindBadRequest, Message: "无效的直播间标识"}
+ }
+}
+
+// StopRecordingByKey stops an active Bilibili or Douyin live recording by room key, account key, or room ID.
+func (m *Manager) StopRecordingByKey(key string) (RoomState, error) {
+ key = strings.TrimSpace(key)
+ if key == "" {
+ return RoomState{}, &site.Error{Kind: site.ErrKindBadRequest, Message: "无效的直播间标识"}
+ }
+ switch {
+ case strings.HasPrefix(key, "douyin:live:"):
+ rest := strings.TrimSpace(strings.TrimPrefix(key, "douyin:live:"))
+ if rest == "" {
+ return RoomState{Site: string(site.Douyin)}, &site.Error{Site: site.Douyin, Kind: site.ErrKindBadRequest, Message: "缺少抖音直播间号或主播标识"}
+ }
+ return m.StopDouyinRecording(rest)
+ case strings.HasPrefix(key, "douyin:user:"):
+ rest := strings.TrimSpace(strings.TrimPrefix(key, "douyin:user:"))
+ if rest == "" {
+ return RoomState{Site: string(site.Douyin)}, &site.Error{Site: site.Douyin, Kind: site.ErrKindBadRequest, Message: "缺少抖音直播间号或主播标识"}
+ }
+ return m.StopDouyinRecording(rest)
+ case strings.HasPrefix(key, "douyin:web:"):
+ rest := strings.TrimSpace(strings.TrimPrefix(key, "douyin:web:"))
+ if rest == "" {
+ return RoomState{Site: string(site.Douyin)}, &site.Error{Site: site.Douyin, Kind: site.ErrKindBadRequest, Message: "缺少抖音直播间号或主播标识"}
+ }
+ return m.StopDouyinRecording(rest)
+ case strings.HasPrefix(key, "douyin:"):
+ rest := strings.TrimSpace(strings.TrimPrefix(key, "douyin:"))
+ if rest == "" {
+ return RoomState{Site: string(site.Douyin)}, &site.Error{Site: site.Douyin, Kind: site.ErrKindBadRequest, Message: "缺少抖音直播间号或主播标识"}
+ }
+ return m.StopDouyinRecording(rest)
+ case strings.HasPrefix(key, "bilibili:live:"):
+ rid, err := strconv.ParseInt(strings.TrimSpace(strings.TrimPrefix(key, "bilibili:live:")), 10, 64)
+ if err != nil || rid <= 0 {
+ return RoomState{}, &site.Error{Site: site.Bilibili, Kind: site.ErrKindBadRequest, Message: "无效的直播间房间号"}
+ }
+ return m.StopRecording(rid)
+ case strings.HasPrefix(key, "bilibili:user:"), strings.HasPrefix(key, "bilibili:"):
+ byUIDOnly := strings.HasPrefix(key, "bilibili:user:")
+ rest := strings.TrimPrefix(key, "bilibili:user:")
+ if !byUIDOnly {
+ rest = strings.TrimPrefix(key, "bilibili:")
+ }
+ num, err := strconv.ParseInt(strings.TrimSpace(rest), 10, 64)
+ if err != nil || num <= 0 {
+ return RoomState{}, &site.Error{Site: site.Bilibili, Kind: site.ErrKindBadRequest, Message: "无效的直播间标识"}
+ }
+ m.mu.Lock()
+ var matchedRoom int64
+ if !byUIDOnly {
+ if _, ok := m.sessions[num]; ok {
+ matchedRoom = num
+ }
+ }
+ if matchedRoom == 0 {
+ for rid, s := range m.sessions {
+ if s != nil && s.uid == num {
+ matchedRoom = rid
+ break
+ }
+ }
+ }
+ if matchedRoom == 0 {
+ if !byUIDOnly {
+ if st, ok := m.states[num]; ok && st.RoomID > 0 {
+ matchedRoom = st.RoomID
+ }
+ }
+ if matchedRoom == 0 {
+ for _, st := range m.states {
+ if st.UID == num && st.RoomID > 0 {
+ matchedRoom = st.RoomID
+ break
+ }
+ }
+ }
+ }
+ m.mu.Unlock()
+ if matchedRoom > 0 {
+ return m.StopRecording(matchedRoom)
+ }
+ return RoomState{Site: string(site.Bilibili)}, nil
+ default:
+ m.mu.Lock()
+ _, hasDouyin := m.douyinSessions[key]
+ m.mu.Unlock()
+ if hasDouyin {
+ return m.StopDouyinRecording(key)
+ }
+ if rid, err := strconv.ParseInt(key, 10, 64); err == nil && rid > 0 {
+ return m.StopRecording(rid)
+ }
+ return m.StopDouyinRecording(key)
+ }
+}
+
+// LiveCheckTimes returns when each account's live status was last fetched
+// by a check, keyed ":".
+func (m *Manager) LiveCheckTimes() map[string]time.Time {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ out := make(map[string]time.Time, len(m.statusCache)+len(m.douyinLastAutoPoll))
+ for uid, e := range m.statusCache {
+ if !e.fetchedAt.IsZero() {
+ out[string(site.Bilibili)+":"+strconv.FormatInt(uid, 10)] = e.fetchedAt
+ }
+ }
+ for uid, at := range m.douyinLastAutoPoll {
+ out[string(site.Douyin)+":"+uid] = at
+ }
+ return out
+}
+
+// LiveCheckEvery estimates how often an auto-record account of siteID has
+// its live status checked, n being that site's auto-record accounts:
+// Bilibili checks them all each round, Douyin within its budget.
+func (m *Manager) LiveCheckEvery(siteID site.ID, n int) time.Duration {
+ if siteID == site.Douyin {
+ return m.DouyinLiveCheckEvery(n)
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return time.Duration(max(m.liveSettings.PollIntervalSeconds, 60)) * time.Second
+}
diff --git a/internal/live/start_reentry_test.go b/internal/live/start_reentry_test.go
new file mode 100644
index 0000000..973afab
--- /dev/null
+++ b/internal/live/start_reentry_test.go
@@ -0,0 +1,94 @@
+package live
+
+import (
+ "context"
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/chialecode/trace/internal/site"
+ "github.com/chialecode/trace/internal/subscription"
+)
+
+// Starting a Douyin recording for an account that records automatically,
+// with no fresh status in the cache, reads the status without starting a
+// second recording from inside or blocking subsequent status checks and Stop.
+func TestDouyinStartWithoutCachedStatusDoesNotLockItself(t *testing.T) {
+ const (
+ secUID = "MS4wLjABAAAA_start_reentry_auto"
+ roomID = "7400000000000009401"
+ )
+ flv := buildSyntheticFLVBytes(t, "avc", 45)
+ mux := http.NewServeMux()
+ mux.HandleFunc("/live/hold.flv", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "video/x-flv")
+ _, _ = w.Write(flv)
+ if f, ok := w.(http.Flusher); ok {
+ f.Flush()
+ }
+ <-r.Context().Done()
+ })
+ mgr, _, subMgr, srv, _ := setupLiveTestHarness(t, mux)
+ provider := newFakeDouyinLiveProvider()
+ mgr.RegisterSiteProvider(provider)
+ provider.statusFn = func(uid, _ string, _ int) (site.LiveStatus, error) {
+ return site.LiveStatus{Site: site.Douyin, AccountUID: uid, WebRID: "880021", RoomID: roomID, Status: site.LiveStateLive, Title: "自动录制", LiveSince: 1794024000}, nil
+ }
+ provider.streamFn = func(uid, _ string, _ []string, _ int) (site.LiveStreamPlan, error) {
+ return site.LiveStreamPlan{
+ Site: site.Douyin, AccountUID: uid, WebRID: "880021", RoomID: roomID,
+ Status: site.LiveStateLive, Transport: site.LiveTransportHTTPFLV, Format: "flv", Codec: "avc", QualityName: "原画",
+ URLs: []string{srv.URL + "/live/hold.flv"}, Media: site.DouyinLiveTransport("Mozilla/5.0 Test", true),
+ }, nil
+ }
+ if _, err := subMgr.Create("录直播", "", []subscription.AccountRef{{Site: "douyin", UID: secUID, Name: "抖音主播"}}, subscription.SubRules{AutoRecord: true}); err != nil {
+ t.Fatal(err)
+ }
+
+ done := make(chan error, 1)
+ go func() {
+ _, err := mgr.StartDouyinRecording(context.Background(), secUID, "880021")
+ done <- err
+ }()
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatalf("StartDouyinRecording: %v", err)
+ }
+ case <-time.After(5 * time.Second):
+ hung("StartDouyinRecording hung: it locked startMu twice")
+ }
+ if st, ok := mgr.CachedAccountState(site.Douyin, secUID); !ok || !st.Recording {
+ t.Fatalf("account state after the start = %+v %v, want recording", st, ok)
+ }
+ provider.mu.Lock()
+ streams := 0
+ for _, n := range provider.streamCalls {
+ streams += n
+ }
+ provider.mu.Unlock()
+ if streams != 1 {
+ t.Fatalf("stream plan requested %d times, want one recording", streams)
+ }
+
+ // A later check of the same account and quitting both go through.
+ checked := make(chan struct{})
+ go func() {
+ _, _ = mgr.CheckAccountLiveStatus(context.Background(), site.Douyin, secUID, "", true)
+ mgr.Stop()
+ close(checked)
+ }()
+ select {
+ case <-checked:
+ case <-time.After(10 * time.Second):
+ hung("a status check or Stop after the start hung")
+ }
+}
+
+// hung ends the test binary at once. t.Fatal (or a panic in the test)
+// would run the cleanup, which stops the manager and hangs on the same lock;
+// a panic in another goroutine skips it.
+func hung(msg string) {
+ go panic(msg)
+ select {}
+}
diff --git a/internal/live/tempnames_test.go b/internal/live/tempnames_test.go
new file mode 100644
index 0000000..56451e4
--- /dev/null
+++ b/internal/live/tempnames_test.go
@@ -0,0 +1,74 @@
+package live
+
+import (
+ "io/fs"
+ "path/filepath"
+ "sort"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/chialecode/trace/internal/storage"
+)
+
+// watchNames samples every name under root while a test runs.
+// The returned check fails the test for any name that was seen but is
+// neither a temporary name (*.part, .trace-*) nor still present at the end
+// as a finished file (allowed lists names the test itself removed).
+func watchNames(t *testing.T, root string) func(allowed ...string) {
+ t.Helper()
+ var mu sync.Mutex
+ seen := map[string]bool{}
+ stop := make(chan struct{})
+ done := make(chan struct{})
+ walk := func() map[string]bool {
+ out := map[string]bool{}
+ _ = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
+ if err == nil && !d.IsDir() {
+ out[p] = true
+ }
+ return nil
+ })
+ return out
+ }
+ go func() {
+ defer close(done)
+ for {
+ names := walk()
+ mu.Lock()
+ for p := range names {
+ seen[p] = true
+ }
+ mu.Unlock()
+ select {
+ case <-stop:
+ return
+ case <-time.After(time.Millisecond):
+ }
+ }
+ }()
+ return func(allowed ...string) {
+ t.Helper()
+ close(stop)
+ <-done
+ final := walk()
+ ok := map[string]bool{}
+ for _, a := range allowed {
+ ok[a] = true
+ }
+ var bad []string
+ mu.Lock()
+ for p := range seen {
+ name := filepath.Base(p)
+ if final[p] || storage.IsTempName(name) || ok[name] {
+ continue
+ }
+ bad = append(bad, p)
+ }
+ mu.Unlock()
+ sort.Strings(bad)
+ if len(bad) > 0 {
+ t.Fatalf("unfinished files with final-looking names were visible: %v", bad)
+ }
+ }
+}
diff --git a/internal/locales/zh-Hans.json b/internal/locales/zh-Hans.json
index ce686a6..733ab67 100644
--- a/internal/locales/zh-Hans.json
+++ b/internal/locales/zh-Hans.json
@@ -1,6 +1,6 @@
{
"@@locale": "zh-Hans",
"mygo.appName": "TRACE",
- "mygo.appDescription": "哔哩哔哩内容的订阅、缓存与录制",
+ "mygo.appDescription": "哔哩哔哩与抖音内容的订阅、缓存与录制",
"mygo.desktopShortcut": "创建桌面快捷方式"
}
diff --git a/internal/player/audio_sink.go b/internal/player/audio_sink.go
index 064c3ba..9b1c224 100644
--- a/internal/player/audio_sink.go
+++ b/internal/player/audio_sink.go
@@ -8,7 +8,7 @@ import (
)
// AudioSink abstracts audio playback so automated tests, prototypes, uishots, and smoke
-// use NullAudioSink without ever opening a hardware audio device or emitting sound (§6.1).
+// use NullAudioSink without ever opening a hardware audio device or emitting sound.
type AudioSink interface {
Open(dec audio.Decoder) error
Play()
diff --git a/internal/player/danmaku.go b/internal/player/danmaku.go
index 4b5e8b8..ff2cb96 100644
--- a/internal/player/danmaku.go
+++ b/internal/player/danmaku.go
@@ -42,22 +42,48 @@ type PositionedDanmaku struct {
Mode int
}
-// DanmakuEngine provides sub-millisecond frame layout over tens of thousands of danmaku items (PR-3, C22).
+// DanmakuEngine provides sub-millisecond frame layout over tens of thousands of danmaku items.
type DanmakuEngine struct {
items []DanmakuItem
}
+func isSupportedDanmakuMode(mode int) bool {
+ return mode >= 1 && mode <= 6
+}
+
+func clampDanmakuFontSize(fontSize int) float32 {
+ if fontSize <= 0 {
+ return 15
+ }
+ if fontSize < 12 {
+ return 12
+ }
+ if fontSize > 20 {
+ return 20
+ }
+ return float32(fontSize)
+}
+
// NewDanmakuEngine creates a sorted DanmakuEngine from items.
func NewDanmakuEngine(items []DanmakuItem) *DanmakuEngine {
- copied := make([]DanmakuItem, len(items))
- copy(copied, items)
- for i := range copied {
- if copied[i].FontSize <= 0 {
- copied[i].FontSize = 20
+ copied := make([]DanmakuItem, 0, len(items))
+ for _, it := range items {
+ if math.IsNaN(it.TimeSec) || math.IsInf(it.TimeSec, 0) || it.TimeSec < 0 {
+ continue
}
- if copied[i].WidthPx <= 0 {
- copied[i].WidthPx = estimateTextWidth(copied[i].Text, copied[i].FontSize)
+ if it.Mode == 0 {
+ it.Mode = 1
}
+ if !isSupportedDanmakuMode(it.Mode) {
+ continue
+ }
+ if it.FontSize <= 0 {
+ it.FontSize = 15
+ }
+ if it.WidthPx <= 0 {
+ it.WidthPx = estimateTextWidth(it.Text, it.FontSize)
+ }
+ copied = append(copied, it)
}
sort.SliceStable(copied, func(i, j int) bool {
if copied[i].TimeSec != copied[j].TimeSec {
@@ -111,10 +137,13 @@ func ParseDanmakuXML(xmlBytes []byte) (*DanmakuEngine, error) {
continue
}
tSec, err := strconv.ParseFloat(parts[0], 64)
- if err != nil {
+ if err != nil || math.IsNaN(tSec) || math.IsInf(tSec, 0) || tSec < 0 {
continue
}
mode, _ := strconv.Atoi(parts[1])
+ if !isSupportedDanmakuMode(mode) {
+ continue
+ }
fontSize, _ := strconv.Atoi(parts[2])
colVal, _ := strconv.ParseUint(parts[3], 10, 32)
idStr := ""
@@ -144,7 +173,7 @@ func (e *DanmakuEngine) Count() int {
// LayoutFrame computes all visible danmaku positions at playback time tSec.
// Uses binary search over [tSec - DanmakuRollDuration, tSec] and track collision avoidance
-// so 10,000+ items take < 1ms per frame (PR-3, C22).
+// so 10,000+ items take < 1ms per frame.
// Optional density limits how many original entries per second are shown.
// Selection is stable across frames and seeks; omitted density is unlimited.
func (e *DanmakuEngine) LayoutFrame(
@@ -154,7 +183,7 @@ func (e *DanmakuEngine) LayoutFrame(
opacity float64,
density ...string,
) []PositionedDanmaku {
- if e == nil || len(e.items) == 0 || viewportW <= 0 || viewportH <= 0 {
+ if e == nil || len(e.items) == 0 || viewportW <= 0 || viewportH <= 0 || math.IsNaN(tSec) || math.IsInf(tSec, 0) {
return nil
}
if areaRatio <= 0 || areaRatio > 1.0 {
@@ -185,7 +214,14 @@ func (e *DanmakuEngine) LayoutFrame(
var bottomOccupied [36]bool
alpha := uint8(opacity*255.0 + 0.5)
+ initCap := maxTracks * 2
+ if rem := len(e.items) - startIdx; rem < initCap {
+ initCap = rem
+ }
var out []PositionedDanmaku
+ if initCap > 0 {
+ out = make([]PositionedDanmaku, 0, initCap)
+ }
perSecond := 0
if len(density) > 0 {
perSecond = danmakuPerSecond(density[0])
@@ -210,6 +246,7 @@ func (e *DanmakuEngine) LayoutFrame(
B: uint8(it.ColorRGB & 0xFF),
A: alpha,
}
+ fontSize := clampDanmakuFontSize(it.FontSize)
switch it.Mode {
case 4: // Bottom pinned
@@ -240,7 +277,7 @@ func (e *DanmakuEngine) LayoutFrame(
Y: y,
Width: it.WidthPx,
Height: DanmakuTrackHeight,
- FontSize: 15,
+ FontSize: fontSize,
Color: col,
Mode: it.Mode,
})
@@ -273,12 +310,12 @@ func (e *DanmakuEngine) LayoutFrame(
Y: y,
Width: it.WidthPx,
Height: DanmakuTrackHeight,
- FontSize: 15,
+ FontSize: fontSize,
Color: col,
Mode: it.Mode,
})
- default: // Rolling (modes 1, 2, 3)
+ case 1, 2, 3, 6: // Rolling
if elapsed > DanmakuRollDuration {
continue
}
@@ -312,7 +349,7 @@ func (e *DanmakuEngine) LayoutFrame(
Y: y,
Width: it.WidthPx,
Height: DanmakuTrackHeight,
- FontSize: 15,
+ FontSize: fontSize,
Color: col,
Mode: 1,
})
@@ -344,10 +381,7 @@ func danmakuPerSecond(density string) int {
}
func estimateTextWidth(s string, fontSize int) float32 {
- if fontSize <= 0 {
- fontSize = 16
- }
- scale := float32(15.0)
+ scale := clampDanmakuFontSize(fontSize)
var width float32
for _, r := range s {
if r <= 0x7F {
diff --git a/internal/player/live_fmp4.go b/internal/player/live_fmp4.go
index d693b7c..adee097 100644
--- a/internal/player/live_fmp4.go
+++ b/internal/player/live_fmp4.go
@@ -206,8 +206,8 @@ func openLiveFMP4Source(ctx context.Context, path string, opts LivePreviewOption
break
}
if !active {
- _ = f.Close()
if src.initEnd == 0 || len(frags) == 0 {
+ _ = f.Close()
return nil, fmt.Errorf("直播录制尚未写入可预览的媒体分片")
}
break
@@ -384,7 +384,11 @@ func (s *liveFMP4Source) tryParseInit(f *os.File, limit int64) (initEnd int64, s
return 0, false, false, errors.New("moov 超过大小上限")
}
raw := make([]byte, initEnd)
- if _, rErr := f.ReadAt(raw, 0); rErr != nil && rErr != io.EOF {
+ n, rErr := f.ReadAt(raw, 0)
+ if rErr == io.EOF || int64(n) < initEnd {
+ return 0, true, false, nil
+ }
+ if rErr != nil {
return 0, true, false, rErr
}
parsed, dErr := mp4.DecodeFile(bytes.NewReader(raw), mp4.WithDecodeFlags(mp4.DecStartOnMoof))
@@ -511,6 +515,7 @@ func (s *liveFMP4Source) scanFragmentsFrom(f *os.File, limit int64) (added []fmp
// Ensure the companion mdat (plus any tiny intervening box) is also completely flushed on disk.
cur := off + bSize
foundMdat := false
+ orphan := false
var unitEnd int64
for cur < limit {
nt, nsz, _, nComp, nValid := readBoxHeaderAt(f, cur, limit)
@@ -522,13 +527,22 @@ func (s *liveFMP4Source) scanFragmentsFrom(f *os.File, limit int64) (added []fmp
unitEnd = cur + nsz
break
}
- if nt == "free" || nt == "skip" || nt == "prft" || nt == "sidx" {
+ if nt == "free" || nt == "skip" || nt == "prft" || nt == "sidx" || nt == "emsg" {
cur += nsz
continue
}
+ // A complete non-mdat box (e.g., another moof) means this moof has no mdat;
+ // advance past it so scanning cannot stall permanently.
+ orphan = true
break
}
if !foundMdat {
+ if orphan {
+ off = cur
+ s.scannedOff = off
+ s.committedFragEnd = off
+ continue
+ }
return added, false
}
meta := s.inspectMoof(f, off, bSize, unitEnd-off)
@@ -609,10 +623,8 @@ func (s *liveFMP4Source) inspectMoof(f *os.File, moofOff int64, moofSize int64,
if hasTFDT || durTicks > 0 {
startDur := ticksToDuration(startTicks, scale)
endDur := ticksToDuration(startTicks+durTicks, scale)
- if !meta.hasTimeline || (tid == s.videoTrackID) || startDur < meta.startPTS {
- if !meta.hasTimeline || tid == s.videoTrackID {
- meta.startPTS = startDur
- }
+ if !meta.hasTimeline || tid == s.videoTrackID {
+ meta.startPTS = startDur
}
if !meta.hasTimeline || endDur > meta.endPTS {
meta.endPTS = endDur
@@ -690,15 +702,16 @@ func (s *liveFMP4Source) pollLoop() {
}
}
-func (s *liveFMP4Source) subscribe(fn func(committedEnd int64, ended bool, closed bool)) (committedEnd int64, ended bool) {
+func (s *liveFMP4Source) subscribe(fn func(committedEnd int64, ended bool, closed bool)) (committedEnd int64, ended bool, closed bool) {
s.mu.Lock()
committedEnd = s.committedFragEnd
ended = s.ended
- if !s.closed {
+ closed = s.closed
+ if !closed {
s.listeners = append(s.listeners, fn)
}
s.mu.Unlock()
- return committedEnd, ended
+ return committedEnd, ended, closed
}
func (s *liveFMP4Source) AvailableDuration() time.Duration {
diff --git a/internal/player/mf_hw_windows.go b/internal/player/mf_hw_windows.go
index 91e7437..4538d00 100644
--- a/internal/player/mf_hw_windows.go
+++ b/internal/player/mf_hw_windows.go
@@ -8,7 +8,7 @@ import (
"golang.org/x/sys/windows"
)
-// Hardware-accelerated decoding (F-043). A D3D11 device handed to the Source
+// Hardware-accelerated decoding. A D3D11 device handed to the Source
// Reader through an IMFDXGIDeviceManager lets Media Foundation use the GPU
// decoder and the GPU video processor for color conversion and scaling.
// Every step is optional: any failure falls back to the software path.
diff --git a/internal/player/mf_live_windows.go b/internal/player/mf_live_windows.go
index 5a45ab7..ab388ce 100644
--- a/internal/player/mf_live_windows.go
+++ b/internal/player/mf_live_windows.go
@@ -124,10 +124,12 @@ type mfAsyncReadOutcome struct {
}
type mfLiveByteStream struct {
- com mfByteStreamCOMHeader
- comAddr uintptr
- refCount atomic.Int32
- attrs uintptr
+ com mfByteStreamCOMHeader
+ comAddr uintptr
+ refCount atomic.Int32
+ ownerReleased atomic.Bool
+ attrs uintptr
+ mfStarted bool
mu sync.Mutex
cond *sync.Cond
@@ -140,7 +142,6 @@ type mfLiveByteStream struct {
eof bool
closed bool
pendingReads map[uintptr]mfAsyncReadOutcome
- lastOutcome mfAsyncReadOutcome
wg sync.WaitGroup
cleanOnce sync.Once
@@ -181,10 +182,17 @@ func initMFLiveByteStreamVtbl() {
*ppv = this
return hrOK
}
- if *riid == iidIMFAttributes && bs.attrs != 0 {
- _ = vcall(bs.attrs, 1) // AddRef
- *ppv = bs.attrs
- return hrOK
+ if *riid == iidIMFAttributes {
+ bs.mu.Lock()
+ attrs := bs.attrs
+ if attrs != 0 && !bs.closed {
+ _ = vcall(attrs, 1) // AddRef while locked so finalize cannot release concurrently
+ *ppv = attrs
+ bs.mu.Unlock()
+ return hrOK
+ }
+ bs.mu.Unlock()
+ return hrENoIface
}
return hrENoIface
}),
@@ -200,15 +208,7 @@ func initMFLiveByteStreamVtbl() {
if bs == nil {
return 0
}
- rc := bs.refCount.Add(-1)
- if rc <= 0 {
- bs.abort()
- mfLiveStreamMapMu.Lock()
- delete(mfLiveStreamMap, this)
- mfLiveStreamMapMu.Unlock()
- return 0
- }
- return uintptr(rc)
+ return uintptr(bs.releaseRef())
}),
GetCapabilities: syscall.NewCallback(func(this uintptr, pdwCaps *uint32) uintptr {
if pdwCaps == nil {
@@ -323,32 +323,41 @@ func initMFLiveByteStreamVtbl() {
comRelease(asyncRes)
return hrEAbort
}
+ bs.refCount.Add(1)
bs.wg.Add(1)
bs.mu.Unlock()
go func() {
+ defer bs.releaseRef()
defer bs.wg.Done()
var n int
status := hrOK
if cb > 0 {
tmp := make([]byte, int(cb))
n, status = bs.readBlocking(tmp)
- if n > 0 {
+ // Guard native buffer write under bs.mu against concurrent abort/teardown.
+ bs.mu.Lock()
+ if bs.closed {
+ n = 0
+ status = hrEAbort
+ } else if n > 0 {
copy(unsafe.Slice(pb, n), tmp[:n])
}
+ bs.pendingReads[asyncRes] = mfAsyncReadOutcome{n: uint32(n), hr: status}
+ bs.mu.Unlock()
+ } else {
+ bs.mu.Lock()
+ if bs.closed {
+ status = hrEAbort
+ }
+ bs.pendingReads[asyncRes] = mfAsyncReadOutcome{n: 0, hr: status}
+ bs.mu.Unlock()
}
- bs.mu.Lock()
- out := mfAsyncReadOutcome{n: uint32(n), hr: status}
- bs.pendingReads[asyncRes] = out
- bs.lastOutcome = out
- bs.mu.Unlock()
_ = vcall(asyncRes, 6, status) // IMFAsyncResult::SetStatus
_ = vcall(pCallback, 4, asyncRes) // IMFAsyncCallback::Invoke
-
- bs.mu.Lock()
- delete(bs.pendingReads, asyncRes)
- bs.mu.Unlock()
+ // Retain pendingReads[asyncRes] until EndRead consumes it (which MF may
+ // invoke asynchronously after Invoke returns) or finalize cleans leftovers.
comRelease(asyncRes)
}()
return hrOK
@@ -366,8 +375,10 @@ func initMFLiveByteStreamVtbl() {
out, ok := bs.pendingReads[pResult]
if ok {
delete(bs.pendingReads, pResult)
+ } else if bs.closed {
+ out = mfAsyncReadOutcome{n: 0, hr: hrEAbort}
} else {
- out = bs.lastOutcome
+ out = mfAsyncReadOutcome{n: 0, hr: hrEInvalidArg}
}
bs.mu.Unlock()
*pcbRead = out.n
@@ -420,24 +431,40 @@ func initMFLiveByteStreamVtbl() {
func newMFLiveByteStream(src *liveFMP4Source) (*mfLiveByteStream, error) {
initMFLiveByteStreamVtbl()
- f, err := openSharedReadFile(src.path)
- if err != nil {
- return nil, err
- }
+ ensureProcessMTA()
+ var mfErr error
var attrs uintptr
- if hr, _, _ := procMFCreateAttributes.Call(uintptr(unsafe.Pointer(&attrs)), 2); int32(hr) >= 0 && attrs != 0 {
- if mime, mErr := windows.UTF16PtrFromString("video/mp4"); mErr == nil {
- _ = vcall(attrs, 25, uintptr(unsafe.Pointer(&guidMFByteStreamContentType)), uintptr(unsafe.Pointer(mime))) // SetString
+ withThreadMTA(func() {
+ r1, _, _ := procMFStartup.Call(mfVersionWin10, 0)
+ if int32(r1) < 0 {
+ mfErr = fmt.Errorf("mf: MFStartup failed: 0x%08x", uint32(r1))
+ return
}
- if name, nErr := windows.UTF16PtrFromString("live.mp4"); nErr == nil {
- _ = vcall(attrs, 25, uintptr(unsafe.Pointer(&guidMFByteStreamOriginName)), uintptr(unsafe.Pointer(name))) // SetString
+ if hr, _, _ := procMFCreateAttributes.Call(uintptr(unsafe.Pointer(&attrs)), 2); int32(hr) >= 0 && attrs != 0 {
+ if mime, mErr := windows.UTF16PtrFromString("video/mp4"); mErr == nil {
+ _ = vcall(attrs, 25, uintptr(unsafe.Pointer(&guidMFByteStreamContentType)), uintptr(unsafe.Pointer(mime))) // SetString
+ }
+ if name, nErr := windows.UTF16PtrFromString("live.mp4"); nErr == nil {
+ _ = vcall(attrs, 25, uintptr(unsafe.Pointer(&guidMFByteStreamOriginName)), uintptr(unsafe.Pointer(name))) // SetString
+ }
}
+ })
+ if mfErr != nil {
+ return nil, mfErr
+ }
+
+ f, err := openSharedReadFile(src.path)
+ if err != nil {
+ comRelease(attrs)
+ _, _, _ = procMFShutdown.Call()
+ return nil, err
}
bs := &mfLiveByteStream{
com: mfByteStreamCOMHeader{lpVtbl: &mfLiveVtbl},
attrs: attrs,
+ mfStarted: true,
file: f,
realFileCursor: src.startFileOff,
pendingReads: make(map[uintptr]mfAsyncReadOutcome),
@@ -461,13 +488,18 @@ func newMFLiveByteStream(src *liveFMP4Source) (*mfLiveByteStream, error) {
mfLiveStreamMap[bs.comAddr] = bs
mfLiveStreamMapMu.Unlock()
- committedEnd, ended := src.subscribe(func(nextCommitted int64, nextEnded bool, nextClosed bool) {
+ committedEnd, ended, closed := src.subscribe(func(nextCommitted int64, nextEnded bool, nextClosed bool) {
if nextClosed {
bs.abort()
return
}
bs.onSourceUpdate(nextCommitted, nextEnded)
})
+ if closed {
+ bs.abort()
+ bs.releaseOwner()
+ return nil, context.Canceled
+ }
bs.onSourceUpdate(committedEnd, ended)
return bs, nil
}
@@ -622,134 +654,69 @@ func (bs *mfLiveByteStream) abort() {
}
}
-func (bs *mfLiveByteStream) releaseOwner() {
- if bs.comAddr == 0 {
- return
+func (bs *mfLiveByteStream) releaseRef() int32 {
+ rc := bs.refCount.Add(-1)
+ if rc <= 0 {
+ bs.abort()
+ bs.finalize()
+ return 0
}
- comRelease(bs.comAddr)
+ return rc
}
-func (bs *mfLiveByteStream) waitClosed() {
- bs.abort()
- bs.wg.Wait()
+func (bs *mfLiveByteStream) finalize() {
bs.cleanOnce.Do(func() {
mfLiveStreamMapMu.Lock()
delete(mfLiveStreamMap, bs.comAddr)
mfLiveStreamMapMu.Unlock()
- comRelease(bs.attrs)
+
+ bs.mu.Lock()
+ attrs := bs.attrs
bs.attrs = 0
- })
-}
+ clear(bs.pendingReads)
+ mfStarted := bs.mfStarted
+ bs.mfStarted = false
+ bs.mu.Unlock()
-func openLiveMFReader(byteStream uintptr, forVideo bool) (*MFDecoder, error) {
- _, _, _ = procCoInitializeEx.Call(0, coinitMultithreaded)
- r1, _, _ := procMFStartup.Call(mfVersionWin10, 0)
- if int32(r1) < 0 {
- return nil, fmt.Errorf("mf: MFStartup failed: 0x%08x", uint32(r1))
- }
- modes := videoReaderModes
- if !forVideo {
- modes = []readerMode{{name: "audio"}}
- }
- var lastErr error
- for _, mode := range modes {
- dec, err := openLiveMFReaderMode(byteStream, forVideo, mode)
- if err == nil {
- return dec, nil
+ comRelease(attrs)
+ if mfStarted {
+ _, _, _ = procMFShutdown.Call()
}
- lastErr = err
- }
- _, _, _ = procMFShutdown.Call()
- return nil, lastErr
+ })
}
-func openLiveMFReaderMode(byteStream uintptr, forVideo bool, mode readerMode) (*MFDecoder, error) {
- var device, manager uintptr
- if mode.hardware {
- if device, manager = newDXGIDeviceManager(); manager == 0 {
- return nil, fmt.Errorf("mf: no GPU video device")
- }
- }
- release := func() {
- comRelease(manager)
- comRelease(device)
+func (bs *mfLiveByteStream) releaseOwner() {
+ if bs.comAddr == 0 || !bs.ownerReleased.CompareAndSwap(false, true) {
+ return
}
+ _ = bs.releaseRef()
+}
- var attrs uintptr
- hr, _, _ := procMFCreateAttributes.Call(uintptr(unsafe.Pointer(&attrs)), 3)
- if int32(hr) < 0 {
- release()
- return nil, fmt.Errorf("mf: MFCreateAttributes failed: 0x%08x", uint32(hr))
- }
- defer comRelease(attrs)
- switch {
- case mode.advanced:
- _ = comSetUINT32(attrs, &guidMFSourceReaderEnableAdvancedVideoProcessing, 1)
- case forVideo:
- _ = comSetUINT32(attrs, &guidMFSourceReaderEnableVideoProcessing, 1)
- }
- if manager != 0 {
- _ = comSetUINT32(attrs, &guidMFReadWriteEnableHardwareTransforms, 1)
- if err := comSetUnknown(attrs, &guidMFSourceReaderD3DManager, manager); err != nil {
- release()
- return nil, err
- }
- }
+func (bs *mfLiveByteStream) waitReads() {
+ bs.abort()
+ bs.wg.Wait()
+}
- var reader uintptr
- hr, _, _ = procMFCreateSourceReaderFromByteStream.Call(
- byteStream,
- attrs,
- uintptr(unsafe.Pointer(&reader)),
- )
- if int32(hr) < 0 || reader == 0 {
- release()
- return nil, fmt.Errorf("mf: MFCreateSourceReaderFromByteStream failed: 0x%08x", uint32(hr))
- }
+func (bs *mfLiveByteStream) waitClosed() {
+ bs.waitReads()
+ bs.mu.Lock()
+ clear(bs.pendingReads)
+ bs.mu.Unlock()
+}
- dec := &MFDecoder{
- reader: reader,
- hasVideo: forVideo,
- videoFormat: "none",
- device: device,
- manager: manager,
- hardware: manager != 0,
- mode: mode.name,
- sampleRate: 48000,
- channels: 2,
- }
- if forVideo {
- dec.fps = 30.0
- }
- fail := func(err error) (*MFDecoder, error) {
- dec.releaseCOM()
- return nil, err
- }
- _ = vcall(reader, 4, mfSourceReaderAllStreams, 0)
- if forVideo {
- _ = vcall(reader, 4, mfSourceReaderFirstVideoStream, 1)
- if err := dec.configureVideoStream(mode.advanced); err != nil {
- return fail(err)
- }
- dec.sourceHasVideo = true
- var native uintptr
- if hr := vcall(reader, 5, mfSourceReaderFirstAudioStream, 0, uintptr(unsafe.Pointer(&native))); int32(hr) >= 0 && native != 0 {
- comRelease(native)
- dec.hasAudio = true
- }
- } else {
- var videoNative uintptr
- if hr := vcall(reader, 5, mfSourceReaderFirstVideoStream, 0, uintptr(unsafe.Pointer(&videoNative))); int32(hr) >= 0 && videoNative != 0 {
- comRelease(videoNative)
- dec.sourceHasVideo = true
- }
- _ = vcall(reader, 4, mfSourceReaderFirstAudioStream, 1)
- dec.configureAudioStream()
- if !dec.hasAudio {
- return fail(fmt.Errorf("mf: no decodable audio stream"))
+func openLiveMFReader(byteStream uintptr, forVideo bool) (*MFDecoder, error) {
+ return openMFReaderWithFactory(forVideo, false, func(attrs uintptr) (uintptr, error) {
+ var reader uintptr
+ hr, _, _ := procMFCreateSourceReaderFromByteStream.Call(
+ byteStream,
+ attrs,
+ uintptr(unsafe.Pointer(&reader)),
+ )
+ if int32(hr) < 0 || reader == 0 {
+ return 0, fmt.Errorf("mf: MFCreateSourceReaderFromByteStream failed: 0x%08x", uint32(hr))
}
- }
- return dec, nil
+ return reader, nil
+ })
}
type liveMFDecoder struct {
@@ -784,11 +751,18 @@ func openLivePreviewPlatform(ctx context.Context, path string, opts LivePreviewO
return nil, err
}
+ var cancelMu sync.Mutex
+ activeStreams := []*mfLiveByteStream{vbs}
openDone := make(chan struct{})
go func() {
select {
case <-ctx.Done():
- vbs.abort()
+ cancelMu.Lock()
+ streams := append([]*mfLiveByteStream(nil), activeStreams...)
+ cancelMu.Unlock()
+ for _, s := range streams {
+ s.abort()
+ }
src.abort()
case <-openDone:
}
@@ -797,9 +771,12 @@ func openLivePreviewPlatform(ctx context.Context, path string, opts LivePreviewO
videoDec, err := openLiveMFReader(vbs.comPtr(), true)
if err != nil {
close(openDone)
- vbs.releaseOwner()
vbs.waitClosed()
+ vbs.releaseOwner()
_ = src.Close()
+ if ctxErr := ctx.Err(); ctxErr != nil {
+ return nil, ctxErr
+ }
if IsMissingCodecError(err) {
return nil, ErrMissingCodec
}
@@ -808,30 +785,40 @@ func openLivePreviewPlatform(ctx context.Context, path string, opts LivePreviewO
var abs *mfLiveByteStream
var audioDec *MFDecoder
- if src.hasAudio {
+ if ctx.Err() == nil && src.hasAudio {
if aStream, aErr := newMFLiveByteStream(src); aErr == nil {
- if aDec, rErr := openLiveMFReader(aStream.comPtr(), false); rErr == nil {
+ cancelMu.Lock()
+ activeStreams = append(activeStreams, aStream)
+ cancelMu.Unlock()
+ if ctx.Err() != nil {
+ aStream.waitClosed()
+ aStream.releaseOwner()
+ } else if aDec, rErr := openLiveMFReader(aStream.comPtr(), false); rErr == nil {
abs = aStream
audioDec = aDec
} else {
- aStream.releaseOwner()
aStream.waitClosed()
+ aStream.releaseOwner()
}
}
}
close(openDone)
if err := ctx.Err(); err != nil {
+ if abs != nil {
+ abs.waitReads()
+ }
+ vbs.waitReads()
if audioDec != nil {
_ = audioDec.Close()
}
_ = videoDec.Close()
if abs != nil {
- abs.releaseOwner()
abs.waitClosed()
+ abs.releaseOwner()
}
- vbs.releaseOwner()
vbs.waitClosed()
+ vbs.releaseOwner()
_ = src.Close()
return nil, err
}
@@ -1036,6 +1023,15 @@ func (d *liveMFDecoder) abort() {
func (d *liveMFDecoder) Close() error {
d.abort()
d.closeOnce.Do(func() {
+ // Wait for all in-flight BeginRead goroutines to complete with E_ABORT
+ // while IMFSourceReader and native MF buffers are still alive, then
+ // release readers before dropping the owner COM refs on the byte streams.
+ if d.abs != nil {
+ d.abs.waitReads()
+ }
+ if d.vbs != nil {
+ d.vbs.waitReads()
+ }
if d.audio != nil {
_ = d.audio.Close()
}
@@ -1043,12 +1039,12 @@ func (d *liveMFDecoder) Close() error {
_ = d.video.Close()
}
if d.abs != nil {
- d.abs.releaseOwner()
d.abs.waitClosed()
+ d.abs.releaseOwner()
}
if d.vbs != nil {
- d.vbs.releaseOwner()
d.vbs.waitClosed()
+ d.vbs.releaseOwner()
}
if d.src != nil {
_ = d.src.Close()
diff --git a/internal/player/mf_windows.go b/internal/player/mf_windows.go
index b39031b..b5c8892 100644
--- a/internal/player/mf_windows.go
+++ b/internal/player/mf_windows.go
@@ -6,6 +6,7 @@ import (
"fmt"
"image"
"io"
+ "runtime"
"sync"
"syscall"
"time"
@@ -20,17 +21,22 @@ var (
modMFReadWrite = windows.NewLazySystemDLL("mfreadwrite.dll")
procCoInitializeEx = modOle32.NewProc("CoInitializeEx")
+ procCoUninitialize = modOle32.NewProc("CoUninitialize")
procPropVariantClear = modOle32.NewProc("PropVariantClear")
procMFStartup = modMFPlat.NewProc("MFStartup")
procMFShutdown = modMFPlat.NewProc("MFShutdown")
procMFCreateAttributes = modMFPlat.NewProc("MFCreateAttributes")
procMFCreateMediaType = modMFPlat.NewProc("MFCreateMediaType")
procMFCreateSourceReaderFromURL = modMFReadWrite.NewProc("MFCreateSourceReaderFromURL")
+
+ processMTAOnce sync.Once
)
const (
mfVersionWin10 = 0x00020070 // (MF_SDK_VERSION << 16) | MF_API_VERSION
coinitMultithreaded = 0x0
+ hrCOMSOk = 0x00000000
+ hrCOMSFalse = 0x00000001
mfSourceReaderFirstVideoStream = 0xFFFFFFFC
mfSourceReaderFirstAudioStream = 0xFFFFFFFD
@@ -43,6 +49,37 @@ const (
vtUI8 = 21
)
+// ensureProcessMTA keeps one dedicated OS-locked thread initialized in the
+// process-wide COM multi-threaded apartment so implicit MTA remains valid for
+// Media Foundation calls across Go worker threads without leaking per-thread
+// CoInitializeEx counts on Go's M pool.
+func ensureProcessMTA() {
+ processMTAOnce.Do(func() {
+ ready := make(chan struct{})
+ go func() {
+ runtime.LockOSThread()
+ _, _, _ = procCoInitializeEx.Call(0, coinitMultithreaded)
+ close(ready)
+ select {}
+ }()
+ <-ready
+ })
+}
+
+// withThreadMTA runs fn on an OS-locked thread with paired CoInitializeEx /
+// CoUninitialize (skipping CoUninitialize when the calling thread is already
+// initialized in another apartment such as STA).
+func withThreadMTA(fn func()) {
+ ensureProcessMTA()
+ runtime.LockOSThread()
+ defer runtime.UnlockOSThread()
+ hr, _, _ := procCoInitializeEx.Call(0, coinitMultithreaded)
+ if hr == hrCOMSOk || hr == hrCOMSFalse {
+ defer procCoUninitialize.Call()
+ }
+ fn()
+}
+
var (
guidNull = windows.GUID{}
@@ -163,6 +200,7 @@ type MFDecoder struct {
sampleRate int
channels int
audioCarry []float32
+ audioScratch []float32
lastVideoPos time.Duration
lastRequest time.Duration
lastFrame *image.RGBA
@@ -213,28 +251,53 @@ var videoReaderModes = []readerMode{
// openMFReader opens path for its first video stream (forVideo) or its
// first audio stream; every other stream is deselected.
func openMFReader(path string, forVideo bool) (*MFDecoder, error) {
- _, _, _ = procCoInitializeEx.Call(0, coinitMultithreaded)
- r1, _, _ := procMFStartup.Call(mfVersionWin10, 0)
- if int32(r1) < 0 {
- return nil, fmt.Errorf("mf: MFStartup failed: 0x%08x", uint32(r1))
- }
- modes := videoReaderModes
- if !forVideo {
- modes = []readerMode{{name: "audio"}}
+ urlPtr, err := windows.UTF16PtrFromString(path)
+ if err != nil {
+ return nil, err
}
- var lastErr error
- for _, mode := range modes {
- dec, err := openMFReaderMode(path, forVideo, mode)
- if err == nil {
- return dec, nil
+ return openMFReaderWithFactory(forVideo, true, func(attrs uintptr) (uintptr, error) {
+ var reader uintptr
+ hr, _, _ := procMFCreateSourceReaderFromURL.Call(
+ uintptr(unsafe.Pointer(urlPtr)),
+ attrs,
+ uintptr(unsafe.Pointer(&reader)),
+ )
+ if int32(hr) < 0 || reader == 0 {
+ return 0, fmt.Errorf("mf: MFCreateSourceReaderFromURL(%s) failed: 0x%08x", path, uint32(hr))
}
- lastErr = err
- }
- _, _, _ = procMFShutdown.Call()
- return nil, lastErr
+ return reader, nil
+ })
}
-func openMFReaderMode(path string, forVideo bool, mode readerMode) (*MFDecoder, error) {
+func openMFReaderWithFactory(forVideo, queryDur bool, create func(attrs uintptr) (uintptr, error)) (*MFDecoder, error) {
+ var dec *MFDecoder
+ var openErr error
+ withThreadMTA(func() {
+ r1, _, _ := procMFStartup.Call(mfVersionWin10, 0)
+ if int32(r1) < 0 {
+ openErr = fmt.Errorf("mf: MFStartup failed: 0x%08x", uint32(r1))
+ return
+ }
+ modes := videoReaderModes
+ if !forVideo {
+ modes = []readerMode{{name: "audio"}}
+ }
+ var lastErr error
+ for _, mode := range modes {
+ d, err := openMFReaderModeWithFactory(forVideo, queryDur, mode, create)
+ if err == nil {
+ dec = d
+ return
+ }
+ lastErr = err
+ }
+ _, _, _ = procMFShutdown.Call()
+ openErr = lastErr
+ })
+ return dec, openErr
+}
+
+func openMFReaderModeWithFactory(forVideo, queryDur bool, mode readerMode, create func(attrs uintptr) (uintptr, error)) (*MFDecoder, error) {
var device, manager uintptr
if mode.hardware {
if device, manager = newDXGIDeviceManager(); manager == 0 {
@@ -268,21 +331,11 @@ func openMFReaderMode(path string, forVideo bool, mode readerMode) (*MFDecoder,
}
}
- urlPtr, err := windows.UTF16PtrFromString(path)
+ reader, err := create(attrs)
if err != nil {
release()
return nil, err
}
- var reader uintptr
- hr, _, _ = procMFCreateSourceReaderFromURL.Call(
- uintptr(unsafe.Pointer(urlPtr)),
- attrs,
- uintptr(unsafe.Pointer(&reader)),
- )
- if int32(hr) < 0 || reader == 0 {
- release()
- return nil, fmt.Errorf("mf: MFCreateSourceReaderFromURL(%s) failed: 0x%08x", path, uint32(hr))
- }
dec := &MFDecoder{
reader: reader,
@@ -327,7 +380,9 @@ func openMFReaderMode(path string, forVideo bool, mode readerMode) (*MFDecoder,
return fail(fmt.Errorf("mf: no decodable audio stream"))
}
}
- dec.queryDuration()
+ if queryDur {
+ dec.queryDuration()
+ }
return dec, nil
}
@@ -409,10 +464,10 @@ func (d *MFDecoder) configureVideoStream(advanced bool) error {
}
func (d *MFDecoder) configureAudioStream() {
- if err := d.setStreamSubtype(mfSourceReaderFirstAudioStream, &guidMFMediaTypeAudio, &guidMFAudioFormatFloat); err == nil {
+ if err := d.setStreamSubtype(mfSourceReaderFirstAudioStream, &guidMFMediaTypeAudio, &guidMFAudioFormatFloat, 0); err == nil {
d.hasAudio = true
d.audioFormat = "float"
- } else if err := d.setStreamSubtype(mfSourceReaderFirstAudioStream, &guidMFMediaTypeAudio, &guidMFAudioFormatPCM); err == nil {
+ } else if err := d.setStreamSubtype(mfSourceReaderFirstAudioStream, &guidMFMediaTypeAudio, &guidMFAudioFormatPCM, 16); err == nil {
d.hasAudio = true
d.audioFormat = "pcm16"
} else {
@@ -427,6 +482,12 @@ func (d *MFDecoder) configureAudioStream() {
}
defer comRelease(curType)
+ if d.audioFormat == "pcm16" {
+ if bits, err := comGetUINT32(curType, &guidMFMTAudioBitsPerSample); err == nil && bits != 0 && bits != 16 {
+ d.hasAudio = false
+ return
+ }
+ }
if ch, err := comGetUINT32(curType, &guidMFMTAudioNumChannels); err == nil && ch > 0 {
d.channels = int(ch)
}
@@ -454,7 +515,7 @@ func (d *MFDecoder) queryDuration() {
}
}
-func (d *MFDecoder) setStreamSubtype(streamIdx uint32, major, sub *windows.GUID) error {
+func (d *MFDecoder) setStreamSubtype(streamIdx uint32, major, sub *windows.GUID, bitsPerSample uint32) error {
var mt uintptr
hr, _, _ := procMFCreateMediaType.Call(uintptr(unsafe.Pointer(&mt)))
if int32(hr) < 0 || mt == 0 {
@@ -468,6 +529,11 @@ func (d *MFDecoder) setStreamSubtype(streamIdx uint32, major, sub *windows.GUID)
if err := comSetGUID(mt, &guidMFMTSubtype, sub); err != nil {
return err
}
+ if bitsPerSample > 0 {
+ if err := comSetUINT32(mt, &guidMFMTAudioBitsPerSample, bitsPerSample); err != nil {
+ return err
+ }
+ }
hr = vcall(d.reader, 7, uintptr(streamIdx), 0, mt)
if int32(hr) < 0 {
@@ -514,7 +580,17 @@ func (d *MFDecoder) DecodeVideoFrameAt(pos time.Duration, dst *image.RGBA) (*ima
return d.lastFrame, d.lastVideoPos, nil
}
- for tries := 0; tries < 240; tries++ {
+ maxTries := 240
+ if d.fps > 0 {
+ if scaled := int(d.fps * 12); scaled > maxTries {
+ maxTries = scaled
+ }
+ }
+ if maxTries > 900 {
+ maxTries = 900
+ }
+
+ for tries := 0; tries < maxTries; tries++ {
var actualIdx uint32
var flags uint32
var tsHNS int64
@@ -559,7 +635,7 @@ func (d *MFDecoder) DecodeVideoFrameAt(pos time.Duration, dst *image.RGBA) (*ima
}
}
- return d.fallbackFrameLocked(dst, pos), pos, fmt.Errorf("mf: video ReadSample yielded no sample after 64 tries")
+ return d.fallbackFrameLocked(dst, pos), pos, fmt.Errorf("mf: video ReadSample yielded no sample after %d tries", maxTries)
}
func (d *MFDecoder) extractVideoSample(sample uintptr, dst *image.RGBA) *image.RGBA {
@@ -619,7 +695,7 @@ func (d *MFDecoder) extract2DVideoBuffer(buf uintptr, dst *image.RGBA) (*image.R
}
rows := d.height
if d.videoFormat == "nv12" {
- rows = d.height * 3 / 2
+ rows = d.height + (d.height+1)/2
}
start := unsafe.Pointer(scan0)
if pitch < 0 { // bottom-up: the lowest address holds the last row
@@ -662,7 +738,12 @@ func (d *MFDecoder) ReadAudioSamples(out []float32) (int, error) {
written := 0
if len(d.audioCarry) > 0 {
n := copy(out, d.audioCarry)
- d.audioCarry = d.audioCarry[n:]
+ if n == len(d.audioCarry) {
+ d.audioCarry = d.audioCarry[:0]
+ } else {
+ rem := copy(d.audioCarry, d.audioCarry[n:])
+ d.audioCarry = d.audioCarry[:rem]
+ }
written += n
if written == len(out) {
return written, nil
@@ -744,9 +825,13 @@ func (d *MFDecoder) extractAudioFloats(sample uintptr) []float32 {
return nil
}
src := unsafe.Slice((*float32)(unsafe.Pointer(dataPtr)), count)
- copied := make([]float32, count)
- copy(copied, src)
- return copied
+ if cap(d.audioScratch) < count {
+ d.audioScratch = make([]float32, count)
+ } else {
+ d.audioScratch = d.audioScratch[:count]
+ }
+ copy(d.audioScratch, src)
+ return d.audioScratch
}
// 16-bit PCM fallback conversion to float32 [-1.0, 1.0]
@@ -755,11 +840,15 @@ func (d *MFDecoder) extractAudioFloats(sample uintptr) []float32 {
return nil
}
src16 := unsafe.Slice((*int16)(unsafe.Pointer(dataPtr)), count)
- out := make([]float32, count)
+ if cap(d.audioScratch) < count {
+ d.audioScratch = make([]float32, count)
+ } else {
+ d.audioScratch = d.audioScratch[:count]
+ }
for i, s := range src16 {
- out[i] = float32(s) / 32768.0
+ d.audioScratch[i] = float32(s) / 32768.0
}
- return out
+ return d.audioScratch
}
// setVideoOutput requests subtype, at w×h when both are set, in full-range
@@ -833,6 +922,7 @@ func (d *MFDecoder) Close() error {
d.closed = true
d.releaseCOM()
d.audioCarry = nil
+ d.audioScratch = nil
d.lastFrame = nil
_, _, _ = procMFShutdown.Call()
return nil
@@ -853,9 +943,15 @@ func vcall(obj uintptr, index int, args ...uintptr) uintptr {
objPtr := *(*unsafe.Pointer)(unsafe.Pointer(&obj))
vtbl := *(**[64]uintptr)(objPtr)
fn := vtbl[index]
- all := make([]uintptr, 0, len(args)+1)
- all = append(all, obj)
- all = append(all, args...)
+ var stackBuf [12]uintptr
+ var all []uintptr
+ if len(args)+1 <= len(stackBuf) {
+ all = stackBuf[:len(args)+1]
+ } else {
+ all = make([]uintptr, len(args)+1)
+ }
+ all[0] = obj
+ copy(all[1:], args)
r1, _, _ := syscall.SyscallN(fn, all...)
return r1
}
@@ -907,6 +1003,8 @@ type splitDecoder struct {
audio *MFDecoder
}
+func (d *splitDecoder) SampleRate() int { return d.audio.SampleRate() }
+func (d *splitDecoder) Channels() int { return d.audio.Channels() }
func (d *splitDecoder) ReadAudioSamples(buf []float32) (int, error) {
return d.audio.ReadAudioSamples(buf)
}
@@ -952,9 +1050,10 @@ func (d *MFDecoder) PreviewFrameAt(pos time.Duration, dst *image.RGBA) (*image.R
pts := time.Duration(tsHNS * 100)
rgba := d.extractVideoSample(sample, dst)
comRelease(sample)
- // The reader stands after this frame: a later decode at pos
- // goes on from here without seeking again.
- d.lastVideoPos, d.lastFrame = pts, rgba
+ // The reader stands after this frame: update lastRequest to pts so
+ // releasing near pos continues forward while releasing before pts
+ // seeks cleanly instead of returning a stale far-ahead preview frame.
+ d.lastVideoPos, d.lastRequest, d.lastFrame = pts, pts, rgba
return rgba, pts, nil
}
if flags&(mfSourceReaderFlagEndOfStream|mfSourceReaderFlagError) != 0 {
diff --git a/internal/player/player.go b/internal/player/player.go
index 91cf675..734e9e5 100644
--- a/internal/player/player.go
+++ b/internal/player/player.go
@@ -320,12 +320,22 @@ func (c *Controller) SetSubtitles(tracks []SubtitleTrack) {
c.subtitles = make(map[string]SubtitleTrack, len(tracks))
c.subOrder = make([]string, 0, len(tracks))
for _, t := range tracks {
+ t.buildIndex()
c.subtitles[t.Lang] = t
c.subOrder = append(c.subOrder, t.Lang)
}
}
+// IsPlaying reports whether media playback is currently active without computing
+// danmaku or subtitle overlays.
+func (c *Controller) IsPlaying() bool {
+ c.mu.Lock()
+ playing := c.playing && c.dec != nil
+ c.mu.Unlock()
+ return playing
+}
+
// Play starts or resumes playback.
func (c *Controller) Play() {
c.mu.Lock()
@@ -675,19 +685,20 @@ func (c *Controller) Snapshot(viewportW, viewportH float32) StateSnapshot {
dmCount := 0
if c.danmakuEngine != nil {
dmCount = c.danmakuEngine.Count()
- if c.danmakuVisible {
- visibleDm = c.danmakuEngine.LayoutFrame(posSec, viewportW, viewportH, c.danmakuArea, c.danmakuOpacity, c.danmakuDensity)
- }
}
-
activeSub := ""
- if c.activeSubLang != "" {
- if track, ok := c.subtitles[c.activeSubLang]; ok {
- activeSub = ActiveCueAt(track.Cues, posSec)
+ var subOpts []string
+ if viewportW > 1 && viewportH > 1 {
+ if c.danmakuEngine != nil && c.danmakuVisible {
+ visibleDm = c.danmakuEngine.LayoutFrame(posSec, viewportW, viewportH, c.danmakuArea, c.danmakuOpacity, c.danmakuDensity)
}
+ if c.activeSubLang != "" {
+ if track, ok := c.subtitles[c.activeSubLang]; ok {
+ activeSub = track.activeCueAt(posSec)
+ }
+ }
+ subOpts = append([]string(nil), c.subOrder...)
}
-
- subOpts := append([]string(nil), c.subOrder...)
return StateSnapshot{
Open: true,
Playing: c.playing,
diff --git a/internal/player/regression_test.go b/internal/player/regression_test.go
new file mode 100644
index 0000000..6406c2a
--- /dev/null
+++ b/internal/player/regression_test.go
@@ -0,0 +1,328 @@
+package player
+
+import (
+ "bytes"
+ "context"
+ "encoding/binary"
+ "image"
+ "io"
+ "math"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func TestNV12AndBGRAOddDimensionsAndSmallStrideDoNotPanic(t *testing.T) {
+ // Odd width/height NV12 with stride == width (previously panicked on uvRow[uvIdx+1]
+ // for x = width-1 on the last UV row).
+ for _, tc := range []struct {
+ w, h, stride int
+ }{
+ {1, 1, 1},
+ {5, 5, 5},
+ {5, 5, 6},
+ {7, 3, 7},
+ {0, 0, 0},
+ } {
+ ySize := tc.stride * tc.h
+ uvRows := (tc.h + 1) / 2
+ buf := make([]byte, ySize+uvRows*tc.stride)
+ for i := range buf {
+ buf[i] = 128
+ }
+ img := NV12ToRGBA(buf, tc.w, tc.h, tc.stride, nil)
+ if img.Bounds().Dx() != tc.w || img.Bounds().Dy() != tc.h {
+ t.Fatalf("NV12ToRGBA(%dx%d, stride=%d) bounds = %v", tc.w, tc.h, tc.stride, img.Bounds())
+ }
+ }
+
+ // BGRA32ToRGBA with absStride < width*4 must not panic.
+ small := make([]byte, 8*4)
+ img := BGRA32ToRGBA(small, 8, 4, 8, nil)
+ if img.Bounds().Dx() != 8 || img.Bounds().Dy() != 4 {
+ t.Fatalf("BGRA32ToRGBA small stride bounds = %v", img.Bounds())
+ }
+ imgNeg := BGRA32ToRGBA(small, 8, 4, -8, nil)
+ if imgNeg.Bounds().Dx() != 8 || imgNeg.Bounds().Dy() != 4 {
+ t.Fatalf("BGRA32ToRGBA negative small stride bounds = %v", imgNeg.Bounds())
+ }
+ // Zero dimensions must not panic on BGRA32ToRGBA / RGBA32Rows.
+ _ = BGRA32ToRGBA(nil, 0, 0, 0, nil)
+ _ = RGBA32Rows(nil, 0, 0, 0, nil)
+
+ // contiguousStride for odd-height NV12 uses height + (height+1)/2 rows.
+ const oddW, oddH, paddedStride = 7, 5, 16
+ oddRows := oddH + (oddH+1)/2 // 8 rows
+ if got := contiguousStride("nv12", oddW, oddH, oddW, paddedStride*oddRows); got != paddedStride {
+ t.Fatalf("contiguousStride(nv12, %dx%d) = %d, want %d", oddW, oddH, got, paddedStride)
+ }
+}
+
+func TestSubtitleOverlappingCuesNaNAndWebVTTFormatting(t *testing.T) {
+ // Overlapping cues where EndSec is non-monotonic: [0, 10], [1, 2], [5, 8].
+ raw := "\uFEFFWEBVTT\r\n \r\n" +
+ "00:00:00.000 --> 00:00:10.000\r\nLong cue\r\n\t \r\n" +
+ "00:00:01.000 --> 00:00:02.000\r\nShort early\r\n\r\n" +
+ "00:00:05.000 --> 00:00:08.000\r\nMiddle cue\r\n\r\n" +
+ "00:00:NaN --> 00:00:09.000\r\nBad NaN start\r\n\r\n" +
+ "00:00:01.000 --> 00:00:NaN\r\nBad NaN end\r\n\r\n" +
+ "00:00:01.000 --> 00:00:+Inf\r\nBad Inf end\r\n\r\n" +
+ "-00:00:01.000 --> 00:00:03.000\r\nBad neg start\r\n"
+
+ cues := ParseWebVTT([]byte(raw))
+ if len(cues) != 3 {
+ t.Fatalf("expected 3 valid cues (rejecting NaN/Inf/neg), got %d: %+v", len(cues), cues)
+ }
+ wantAt6 := "Long cue\nMiddle cue"
+ if got := ActiveCueAt(cues, 6.0); got != wantAt6 {
+ t.Fatalf("ActiveCueAt(6.0) = %q, want %q", got, wantAt6)
+ }
+ if got := ActiveCueAt(cues, math.NaN()); got != "" {
+ t.Fatalf("ActiveCueAt(NaN) = %q, want empty", got)
+ }
+
+ // Verify indexed SubtitleTrack inside Controller.Snapshot agrees.
+ ctrl := NewController(Options{AudioSink: NewNullAudioSink(), SubtitleLang: "zh-CN"})
+ defer ctrl.Close()
+ if err := ctrl.LoadDecoder("sub.mp4", NewSynthDecoder(64, 36, 20*time.Second, 30)); err != nil {
+ t.Fatal(err)
+ }
+ ctrl.SetSubtitles([]SubtitleTrack{{Lang: "zh-CN", Label: "中文", Cues: cues}})
+ if err := ctrl.Seek(6.0); err != nil {
+ t.Fatal(err)
+ }
+ if got := ctrl.Snapshot(640, 360).ActiveSubtitle; got != wantAt6 {
+ t.Fatalf("Controller.Snapshot(640,360).ActiveSubtitle = %q, want %q", got, wantAt6)
+ }
+ // Snapshot(1, 1) skips overlay/subtitle layout for lightweight tick checks.
+ tiny := ctrl.Snapshot(1, 1)
+ if !tiny.Open || tiny.ActiveSubtitle != "" || len(tiny.SubtitleOptions) != 0 || len(tiny.VisibleDanmaku) != 0 {
+ t.Fatalf("Snapshot(1, 1) should skip overlay computation, got %+v", tiny)
+ }
+}
+
+func TestDanmakuRejectsNaNInfNegAndMode78AndScalesFontSize(t *testing.T) {
+ xmlData := `
+ bad-nan
+ bad-inf
+ bad-neg
+ [0.5,0.5,"advanced-json"]
+ code-danmaku
+ small
+ large
+ `
+
+ eng, err := ParseDanmakuXML([]byte(xmlData))
+ if err != nil {
+ t.Fatalf("ParseDanmakuXML: %v", err)
+ }
+ if eng.Count() != 2 {
+ t.Fatalf("Count() = %d, want 2 (only valid mode 1 entries)", eng.Count())
+ }
+ vis := eng.LayoutFrame(3.0, 1280, 720, 0.5, 0.85)
+ if len(vis) != 2 {
+ t.Fatalf("visible = %d, want 2: %+v", len(vis), vis)
+ }
+ var smallW, largeW float32
+ for _, dm := range vis {
+ if strings.Contains(dm.Text, "advanced") || strings.Contains(dm.Text, "code") {
+ t.Fatalf("unexpected mode 7/8 danmaku leaked into layout: %+v", dm)
+ }
+ if dm.Text == "small" {
+ smallW = dm.Width
+ }
+ if dm.Text == "large" {
+ largeW = dm.Width
+ }
+ }
+ if largeW <= smallW {
+ t.Fatalf("estimateTextWidth should scale with fontSize: small=%v large=%v", smallW, largeW)
+ }
+ // NewDanmakuEngine directly also filters NaN/Inf/neg.
+ direct := NewDanmakuEngine([]DanmakuItem{
+ {ID: "nan", TimeSec: math.NaN(), Mode: 1, Text: "x"},
+ {ID: "neg", TimeSec: -2, Mode: 1, Text: "y"},
+ {ID: "ok", TimeSec: 1, Mode: 1, Text: "ok"},
+ })
+ if direct.Count() != 1 {
+ t.Fatalf("direct NewDanmakuEngine Count() = %d, want 1", direct.Count())
+ }
+}
+
+// cachedFrameDecoder mimics MFDecoder returning the cached lastFrame (which
+// aliases videoWorker.shown) on a small forward/in-place seek, or io.EOF at tail.
+type cachedFrameDecoder struct {
+ *SynthDecoder
+ mu sync.Mutex
+ cached *image.RGBA
+ cachedPTS time.Duration
+ returnEOF atomic.Bool
+ decodeHook func()
+}
+
+func (d *cachedFrameDecoder) DecodeVideoFrameAt(pos time.Duration, dst *image.RGBA) (*image.RGBA, time.Duration, error) {
+ if d.decodeHook != nil {
+ d.decodeHook()
+ }
+ if d.returnEOF.Load() {
+ d.mu.Lock()
+ c, pts := d.cached, d.cachedPTS
+ d.mu.Unlock()
+ return c, pts, io.EOF
+ }
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ if d.cached != nil && d.cachedPTS >= pos {
+ return d.cached, d.cachedPTS, nil
+ }
+ img, pts, err := d.SynthDecoder.DecodeVideoFrameAt(pos, dst)
+ if err == nil && img != nil {
+ d.cached = img
+ d.cachedPTS = pts + 100*time.Millisecond
+ }
+ return img, d.cachedPTS, err
+}
+
+func TestShortSeekCachedFrameAndEOFReleaseHoldImmediately(t *testing.T) {
+ dec := &cachedFrameDecoder{SynthDecoder: NewSynthDecoder(64, 36, 30*time.Second, 30)}
+ sink := NewNullAudioSink()
+ c := NewController(Options{AudioSink: sink})
+ defer c.Close()
+
+ if err := c.LoadDecoder("cache.mp4", dec); err != nil {
+ t.Fatal(err)
+ }
+ if c.IsPlaying() {
+ t.Fatal("IsPlaying() should be false before Play()")
+ }
+ c.Play()
+ if !c.IsPlaying() {
+ t.Fatal("IsPlaying() should be true after Play()")
+ }
+ // Let the worker publish and display the initial frame into w.shown.
+ waitFor(t, "initial shown frame", func() bool {
+ c.Advance(0)
+ c.worker.mu.Lock()
+ shown := c.worker.shown
+ c.worker.mu.Unlock()
+ return shown != nil
+ })
+
+ // Seek to a timestamp <= cachedPTS so DecodeVideoFrameAt returns the exact
+ // buffer currently in w.shown. Audio must resume promptly (<< 1.5s seekHoldLimit).
+ start := time.Now()
+ if err := c.Seek(0.05); err != nil {
+ t.Fatal(err)
+ }
+ waitFor(t, "audio resumed after cached-frame short seek", sink.IsPlaying)
+ if took := time.Since(start); took > 500*time.Millisecond {
+ t.Fatalf("short seek stalled audio for %v (want << %v)", took, seekHoldLimit)
+ }
+
+ // Seeking when decoder reports io.EOF must also release hold immediately.
+ dec.returnEOF.Store(true)
+ startEOF := time.Now()
+ if err := c.Seek(29.95); err != nil {
+ t.Fatal(err)
+ }
+ waitFor(t, "audio resumed after EOF seek", sink.IsPlaying)
+ if took := time.Since(startEOF); took > 500*time.Millisecond {
+ t.Fatalf("EOF seek stalled audio for %v (want << %v)", took, seekHoldLimit)
+ }
+}
+
+func TestControllerCloseSuppressesLateFrameNotify(t *testing.T) {
+ inDecode := make(chan struct{})
+ releaseDecode := make(chan struct{})
+ var notifyAfterClose atomic.Int32
+ var closedFlag atomic.Bool
+
+ dec := &cachedFrameDecoder{
+ SynthDecoder: NewSynthDecoder(64, 36, 30*time.Second, 30),
+ }
+ var hookOnce sync.Once
+ c := NewController(Options{AudioSink: NewNullAudioSink()})
+ if err := c.LoadDecoder("late.mp4", dec); err != nil {
+ t.Fatal(err)
+ }
+ c.SetFrameNotify(func() {
+ if closedFlag.Load() {
+ notifyAfterClose.Add(1)
+ }
+ })
+ dec.decodeHook = func() {
+ hookOnce.Do(func() {
+ close(inDecode)
+ <-releaseDecode
+ })
+ }
+ if err := c.Seek(5.0); err != nil {
+ t.Fatal(err)
+ }
+ <-inDecode
+ closedFlag.Store(true)
+ _ = c.Close()
+ close(releaseDecode)
+ time.Sleep(50 * time.Millisecond)
+ if n := notifyAfterClose.Load(); n != 0 {
+ t.Fatalf("onFrame callback fired %d times after Close()", n)
+ }
+}
+
+func makeRawMP4Box(boxType string, payload []byte) []byte {
+ out := make([]byte, 8+len(payload))
+ binary.BigEndian.PutUint32(out[0:4], uint32(len(out)))
+ copy(out[4:8], boxType)
+ copy(out[8:], payload)
+ return out
+}
+
+func TestLiveFMP4SourceEmsgOrphanMoofAndSubscribeClosed(t *testing.T) {
+ initSeg, frags := buildSyntheticGrowingFMP4Parts(t, true, 0, 0, 2)
+ emsg := makeRawMP4Box("emsg", []byte{0, 0, 0, 0, 't', 'e', 's', 't'})
+ orphanMoof := makeRawMP4Box("moof", []byte{0, 0, 0, 8, 'm', 'f', 'h', 'd'})
+
+ // Inject an emsg between moof and mdat in fragment 0, plus an orphan moof before fragment 1.
+ f0 := frags[0]
+ moofSize := int(binary.BigEndian.Uint32(f0[0:4]))
+ var combined bytes.Buffer
+ combined.Write(initSeg)
+ combined.Write(f0[:moofSize])
+ combined.Write(emsg)
+ combined.Write(f0[moofSize:])
+ combined.Write(orphanMoof)
+ combined.Write(frags[1])
+
+ partPath := filepath.Join(t.TempDir(), "live.mp4.part")
+ if err := os.WriteFile(partPath, combined.Bytes(), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ // Open with IsActive=false (already ended) — must keep src.file open and scan both fragments.
+ src, err := openLiveFMP4Source(context.Background(), partPath, LivePreviewOptions{
+ PollInterval: 10 * time.Millisecond,
+ InitialWait: 2 * time.Second,
+ IsActive: func() bool { return false },
+ })
+ if err != nil {
+ t.Fatalf("openLiveFMP4Source: %v", err)
+ }
+ if src.file == nil {
+ t.Fatal("src.file was closed prematurely when !active with valid fragments")
+ }
+ if src.fragCount < 2 {
+ t.Fatalf("fragCount = %d, want >= 2 (emsg between moof/mdat and orphan moof must not stall scan)", src.fragCount)
+ }
+
+ // Abort src and verify subscribe reports closed == true immediately.
+ src.abort()
+ _, _, closed := src.subscribe(func(int64, bool, bool) {})
+ if !closed {
+ t.Fatal("subscribe() on aborted source must report closed == true")
+ }
+ _ = src.Close()
+}
diff --git a/internal/player/regression_windows_test.go b/internal/player/regression_windows_test.go
new file mode 100644
index 0000000..a231a36
--- /dev/null
+++ b/internal/player/regression_windows_test.go
@@ -0,0 +1,207 @@
+//go:build windows
+
+package player
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+ "unsafe"
+
+ "github.com/chialecode/trace/internal/download"
+)
+
+func TestSplitDecoderDelegatesAudioSampleRateAndChannels(t *testing.T) {
+ video := &MFDecoder{hasVideo: true, hasAudio: true, sampleRate: 48000, channels: 2}
+ audio := &MFDecoder{hasAudio: true, sampleRate: 44100, channels: 1}
+ sd := &splitDecoder{MFDecoder: video, audio: audio}
+
+ if got := sd.SampleRate(); got != 44100 {
+ t.Fatalf("splitDecoder.SampleRate() = %d, want 44100", got)
+ }
+ if got := sd.Channels(); got != 1 {
+ t.Fatalf("splitDecoder.Channels() = %d, want 1", got)
+ }
+}
+
+func TestPreviewFrameAtScrubBackDoesNotReturnStalePreviewFrame(t *testing.T) {
+ tmp := t.TempDir()
+ vPath := filepath.Join(tmp, "video.m4s")
+ aPath := filepath.Join(tmp, "audio.m4s")
+ mp4Path := filepath.Join(tmp, "muxed.mp4")
+
+ // Build a 4-second synthetic MP4 (120 frames at 30fps).
+ vBytes, err := download.BuildSyntheticVideoM4S(120, 30)
+ if err != nil {
+ t.Fatalf("BuildSyntheticVideoM4S: %v", err)
+ }
+ aBytes, err := download.BuildSyntheticAudioM4S(180)
+ if err != nil {
+ t.Fatalf("BuildSyntheticAudioM4S: %v", err)
+ }
+ if err := os.WriteFile(vPath, vBytes, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(aPath, aBytes, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := download.MuxDASHFiles(vPath, aPath, mp4Path); err != nil {
+ t.Fatalf("MuxDASHFiles: %v", err)
+ }
+
+ dec, err := OpenMediaFile(mp4Path)
+ if err != nil {
+ t.Fatalf("OpenMediaFile: %v", err)
+ }
+ defer dec.Close()
+
+ // 1. Decode near start (0.1s).
+ if _, pts0, err := dec.DecodeVideoFrameAt(100*time.Millisecond, nil); err != nil || pts0 > 500*time.Millisecond {
+ t.Fatalf("initial decode pts=%v err=%v", pts0, err)
+ }
+
+ // 2. Scrub far ahead to 3.0s via PreviewFrameAt.
+ previewer, ok := dec.(keyFramePreviewer)
+ if !ok {
+ t.Fatalf("decoder %T does not implement keyFramePreviewer", dec)
+ }
+ if _, prevPTS, err := previewer.PreviewFrameAt(3*time.Second, nil); err != nil {
+ t.Fatalf("PreviewFrameAt(3s): %v", err)
+ } else if prevPTS < 0 {
+ t.Fatalf("invalid preview pts %v", prevPTS)
+ }
+
+ // 3. Release scrub back near 0.2s — must seek back, never return a >2s preview frame.
+ _, ptsBack, err := dec.DecodeVideoFrameAt(200*time.Millisecond, nil)
+ if err != nil {
+ t.Fatalf("DecodeVideoFrameAt(200ms) after scrub-back: %v", err)
+ }
+ if ptsBack > 1*time.Second {
+ t.Fatalf("scrub-back returned stale far-ahead preview frame at %v (want <= 1s)", ptsBack)
+ }
+}
+
+func TestMFLiveByteStreamAbortedSourceAndPendingReadsRetention(t *testing.T) {
+ initSeg, frags := buildSyntheticGrowingFMP4Parts(t, true, 0, 0, 1)
+ partPath := filepath.Join(t.TempDir(), "live.mp4.part")
+ raw := append(append([]byte(nil), initSeg...), frags[0]...)
+ if err := os.WriteFile(partPath, raw, 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ src, err := openLiveFMP4Source(context.Background(), partPath, LivePreviewOptions{
+ PollInterval: 10 * time.Millisecond,
+ InitialWait: 2 * time.Second,
+ IsActive: func() bool { return false },
+ })
+ if err != nil {
+ t.Fatalf("openLiveFMP4Source: %v", err)
+ }
+
+ // Verify newMFLiveByteStream succeeds cleanly even before any other MFStartup,
+ // initializes bs.attrs, and retains pendingReads entries for async EndRead.
+ bs, err := newMFLiveByteStream(src)
+ if err != nil {
+ _ = src.Close()
+ t.Fatalf("newMFLiveByteStream: %v", err)
+ }
+ if bs.attrs == 0 {
+ bs.waitClosed()
+ bs.releaseOwner()
+ _ = src.Close()
+ t.Fatal("expected bs.attrs to be created after MFStartup")
+ }
+
+ // Simulate two overlapping async results and verify EndRead consumes each by key
+ // without falling back to the wrong outcome.
+ const fakeRes1 uintptr = 0x1001
+ const fakeRes2 uintptr = 0x1002
+ bs.mu.Lock()
+ bs.pendingReads[fakeRes1] = mfAsyncReadOutcome{n: 111, hr: hrOK}
+ bs.pendingReads[fakeRes2] = mfAsyncReadOutcome{n: 222, hr: hrOK}
+ bs.mu.Unlock()
+
+ var got2 uint32
+ if hr := vcall(bs.comPtr(), 11, fakeRes2, uintptr(unsafe.Pointer(&got2))); hr != hrOK || got2 != 222 {
+ t.Fatalf("EndRead(fakeRes2) hr=0x%x n=%d, want hrOK/222", hr, got2)
+ }
+ var got1 uint32
+ if hr := vcall(bs.comPtr(), 11, fakeRes1, uintptr(unsafe.Pointer(&got1))); hr != hrOK || got1 != 111 {
+ t.Fatalf("EndRead(fakeRes1) hr=0x%x n=%d, want hrOK/111", hr, got1)
+ }
+ // Unknown pResult must NOT return a stale lastOutcome.
+ var gotUnknown uint32
+ if hr := vcall(bs.comPtr(), 11, 0x9999, uintptr(unsafe.Pointer(&gotUnknown))); hr != hrEInvalidArg || gotUnknown != 0 {
+ t.Fatalf("EndRead(unknown) hr=0x%x n=%d, want hrEInvalidArg/0", hr, gotUnknown)
+ }
+
+ bs.waitClosed()
+ bs.releaseOwner()
+
+ // Aborting src first must make newMFLiveByteStream return immediately (no deadlock).
+ src.abort()
+ if _, err := newMFLiveByteStream(src); err == nil {
+ t.Fatal("expected newMFLiveByteStream on aborted source to fail immediately")
+ }
+ _ = src.Close()
+}
+
+func TestOpenLivePreviewCanceledContextDoesNotDeadlockAndReleasesFile(t *testing.T) {
+ initSeg, frags := buildSyntheticGrowingFMP4Parts(t, true, 0, 0, 2)
+ partPath := filepath.Join(t.TempDir(), "cancel.mp4.part")
+ var raw []byte
+ raw = append(raw, initSeg...)
+ for _, f := range frags {
+ raw = append(raw, f...)
+ }
+ if err := os.WriteFile(partPath, raw, 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ // Open and close immediately across multiple cycles to exercise teardown ordering.
+ for i := 0; i < 3; i++ {
+ dec, err := OpenLivePreview(context.Background(), partPath, LivePreviewOptions{
+ PollInterval: 10 * time.Millisecond,
+ InitialWait: 5 * time.Second,
+ IsActive: func() bool { return true },
+ })
+ if err != nil {
+ t.Fatalf("cycle %d OpenLivePreview: %v", i, err)
+ }
+ if err := dec.Close(); err != nil {
+ t.Fatalf("cycle %d Close: %v", i, err)
+ }
+ }
+
+ // Pre-canceled context returns promptly without hanging.
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ done := make(chan error, 1)
+ go func() {
+ dec, err := OpenLivePreview(ctx, partPath, LivePreviewOptions{
+ PollInterval: 10 * time.Millisecond,
+ InitialWait: 5 * time.Second,
+ IsActive: func() bool { return true },
+ })
+ if dec != nil {
+ _ = dec.Close()
+ }
+ done <- err
+ }()
+ select {
+ case err := <-done:
+ if err == nil {
+ t.Fatal("expected error for canceled context")
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("OpenLivePreview deadlocked on canceled context")
+ }
+
+ // Verify zero lingering file handles on Windows by renaming the .part file.
+ finalPath := filepath.Join(filepath.Dir(partPath), "renamed.mp4")
+ if err := os.Rename(partPath, finalPath); err != nil {
+ t.Fatalf("file handle leaked after Close/cancel: rename failed: %v", err)
+ }
+}
diff --git a/internal/player/seek_test.go b/internal/player/seek_test.go
index a256dbf..cec76a3 100644
--- a/internal/player/seek_test.go
+++ b/internal/player/seek_test.go
@@ -41,10 +41,8 @@ func (d *seekRecorder) PreviewFrameAt(pos time.Duration, dst *image.RGBA) (*imag
return d.SynthDecoder.DecodeVideoFrameAt(pos, dst)
}
-// F-059: a seek moved both readers twice, once from the UI thread and once
-// from the audio sink's goroutine (through SetPosition), so the audio reader
-// jumped under the sink while it read, and the video reader was pulled back
-// to the key frame after the worker had caught up.
+// Seeking moves only the audio reader from the sink while the video worker
+// seeks the video reader itself, avoiding double seeks and reader jumps.
func TestSeekMovesOnlyTheAudioReaderFromTheSink(t *testing.T) {
dec := &seekRecorder{slowDecoder: &slowDecoder{SynthDecoder: NewSynthDecoder(64, 36, 60*time.Second, 30)}}
c := NewController(Options{AudioSink: NewNullAudioSink()})
@@ -70,9 +68,8 @@ func TestSeekMovesOnlyTheAudioReaderFromTheSink(t *testing.T) {
})
}
-// F-059: dragging the progress bar sought audio and video every frame.
-// Now it previews key frames with the audio held, and seeks once on release,
-// resuming playback.
+// Dragging the progress bar previews key frames with audio held, then seeks
+// once on release and resumes playback if it was running.
func TestDraggingTheProgressBarPreviewsThenSeeksOnce(t *testing.T) {
dec := &seekRecorder{slowDecoder: &slowDecoder{SynthDecoder: NewSynthDecoder(64, 36, 60*time.Second, 30)}}
sink := NewNullAudioSink()
@@ -125,9 +122,8 @@ func TestDraggingTheProgressBarPreviewsThenSeeksOnce(t *testing.T) {
}
}
-// F-059: after a seek during playback the sound waited for nothing and ran
-// ahead of a picture still decoding from the key frame. The audio is held
-// until the first frame at the new position is ready.
+// After a seek during playback, audio is held until the first frame at the new
+// position is ready so sound does not run ahead of decoding.
func TestSeekWhilePlayingHoldsAudioForTheFirstFrame(t *testing.T) {
dec := &seekRecorder{slowDecoder: &slowDecoder{SynthDecoder: NewSynthDecoder(64, 36, 60*time.Second, 30), delay: 120 * time.Millisecond}}
sink := NewNullAudioSink()
diff --git a/internal/player/subtitle.go b/internal/player/subtitle.go
index 490044d..dfd5228 100644
--- a/internal/player/subtitle.go
+++ b/internal/player/subtitle.go
@@ -1,6 +1,7 @@
package player
import (
+ "math"
"sort"
"strconv"
"strings"
@@ -15,19 +16,58 @@ type SubtitleCue struct {
// SubtitleTrack holds parsed cues for a single language track.
type SubtitleTrack struct {
- Lang string `json:"lang"`
- Label string `json:"label"`
- Cues []SubtitleCue `json:"cues"`
+ Lang string `json:"lang"`
+ Label string `json:"label"`
+ Cues []SubtitleCue `json:"cues"`
+ maxEnd []float64
}
-// ParseWebVTT parses a WebVTT (.vtt) or SRT (.srt) subtitle payload into sorted SubtitleCues (C22).
+func (t *SubtitleTrack) buildIndex() {
+ if len(t.Cues) == 0 {
+ t.maxEnd = nil
+ return
+ }
+ t.maxEnd = make([]float64, len(t.Cues))
+ best := math.Inf(-1)
+ for i, c := range t.Cues {
+ if c.EndSec > best {
+ best = c.EndSec
+ }
+ t.maxEnd[i] = best
+ }
+}
+
+func (t *SubtitleTrack) activeCueAt(tSec float64) string {
+ if len(t.Cues) == 0 || math.IsNaN(tSec) || math.IsInf(tSec, 0) || tSec < 0 {
+ return ""
+ }
+ if len(t.maxEnd) != len(t.Cues) {
+ return ActiveCueAt(t.Cues, tSec)
+ }
+ idx := sort.Search(len(t.maxEnd), func(i int) bool {
+ return t.maxEnd[i] >= tSec
+ })
+ var active []string
+ for i := idx; i < len(t.Cues); i++ {
+ if t.Cues[i].StartSec > tSec {
+ break
+ }
+ if tSec >= t.Cues[i].StartSec && tSec <= t.Cues[i].EndSec {
+ active = append(active, t.Cues[i].Text)
+ }
+ }
+ return strings.Join(active, "\n")
+}
+
+// ParseWebVTT parses a WebVTT (.vtt) or SRT (.srt) subtitle payload into sorted SubtitleCues.
func ParseWebVTT(raw []byte) []SubtitleCue {
- content := strings.ReplaceAll(string(raw), "\r\n", "\n")
- blocks := strings.Split(content, "\n\n")
+ content := strings.TrimPrefix(string(raw), "\uFEFF")
+ content = strings.ReplaceAll(content, "\r\n", "\n")
+ content = strings.ReplaceAll(content, "\r", "\n")
+ blocks := splitSubtitleBlocks(content)
var cues []SubtitleCue
- for _, block := range blocks {
- lines := strings.Split(strings.TrimSpace(block), "\n")
+ for _, lines := range blocks {
if len(lines) == 0 {
continue
}
@@ -81,19 +121,37 @@ func ParseWebVTT(raw []byte) []SubtitleCue {
return cues
}
+func splitSubtitleBlocks(content string) [][]string {
+ var blocks [][]string
+ var cur []string
+ for _, line := range strings.Split(content, "\n") {
+ if strings.TrimSpace(line) == "" {
+ if len(cur) > 0 {
+ blocks = append(blocks, cur)
+ cur = nil
+ }
+ continue
+ }
+ cur = append(cur, line)
+ }
+ if len(cur) > 0 {
+ blocks = append(blocks, cur)
+ }
+ return blocks
+}
+
// ActiveCueAt returns the active subtitle text at playback timestamp tSec.
+// Cues must be sorted by StartSec (as returned by ParseWebVTT); overlapping
+// cues with non-monotonic EndSec are handled without missing earlier long cues.
func ActiveCueAt(cues []SubtitleCue, tSec float64) string {
- if len(cues) == 0 || tSec < 0 {
+ if len(cues) == 0 || math.IsNaN(tSec) || math.IsInf(tSec, 0) || tSec < 0 {
return ""
}
- idx := sort.Search(len(cues), func(i int) bool {
- return cues[i].EndSec >= tSec
+ endIdx := sort.Search(len(cues), func(i int) bool {
+ return cues[i].StartSec > tSec
})
var active []string
- for i := idx; i < len(cues); i++ {
- if cues[i].StartSec > tSec {
- break
- }
+ for i := 0; i < endIdx; i++ {
if tSec >= cues[i].StartSec && tSec <= cues[i].EndSec {
active = append(active, cues[i].Text)
}
@@ -103,27 +161,44 @@ func ActiveCueAt(cues []SubtitleCue, tSec float64) string {
func parseCueTime(s string) (float64, bool) {
s = strings.TrimSpace(strings.ReplaceAll(s, ",", "."))
+ if s == "" || strings.ContainsAny(s, "+-") {
+ return 0, false
+ }
parts := strings.Split(s, ":")
if len(parts) == 3 {
h, err1 := strconv.ParseFloat(parts[0], 64)
m, err2 := strconv.ParseFloat(parts[1], 64)
sec, err3 := strconv.ParseFloat(parts[2], 64)
- if err1 != nil || err2 != nil || err3 != nil {
+ if err1 != nil || err2 != nil || err3 != nil ||
+ !isValidNonNegFloat(h) || !isValidNonNegFloat(m) || !isValidNonNegFloat(sec) {
+ return 0, false
+ }
+ total := h*3600 + m*60 + sec
+ if !isValidNonNegFloat(total) {
return 0, false
}
- return h*3600 + m*60 + sec, true
+ return total, true
}
if len(parts) == 2 {
m, err1 := strconv.ParseFloat(parts[0], 64)
sec, err2 := strconv.ParseFloat(parts[1], 64)
- if err1 != nil || err2 != nil {
+ if err1 != nil || err2 != nil ||
+ !isValidNonNegFloat(m) || !isValidNonNegFloat(sec) {
return 0, false
}
- return m*60 + sec, true
+ total := m*60 + sec
+ if !isValidNonNegFloat(total) {
+ return 0, false
+ }
+ return total, true
}
return 0, false
}
+func isValidNonNegFloat(v float64) bool {
+ return !math.IsNaN(v) && !math.IsInf(v, 0) && v >= 0
+}
+
var webvttUnescaper = strings.NewReplacer(
"<", "<",
">", ">",
diff --git a/internal/player/synth.go b/internal/player/synth.go
index a75437a..62f2a11 100644
--- a/internal/player/synth.go
+++ b/internal/player/synth.go
@@ -399,6 +399,12 @@ func (d *SynthLiveDecoder) Close() error {
// NV12ToRGBA converts an NV12 YUV 4:2:0 frame buffer into *image.RGBA (BT.709 integer math).
func NV12ToRGBA(nv12 []byte, width, height, stride int, dst *image.RGBA) *image.RGBA {
+ if width <= 0 || height <= 0 {
+ if dst == nil {
+ return image.NewRGBA(image.Rect(0, 0, 0, 0))
+ }
+ return dst
+ }
if stride < width {
stride = width
}
@@ -406,7 +412,8 @@ func NV12ToRGBA(nv12 []byte, width, height, stride int, dst *image.RGBA) *image.
dst = image.NewRGBA(image.Rect(0, 0, width, height))
}
yPlaneSize := stride * height
- if len(nv12) < yPlaneSize+(stride*height)/2 {
+ uvRows := (height + 1) / 2
+ if len(nv12) < yPlaneSize+uvRows*stride {
return dst
}
uvPlane := nv12[yPlaneSize:]
@@ -414,16 +421,22 @@ func NV12ToRGBA(nv12 []byte, width, height, stride int, dst *image.RGBA) *image.
for y := 0; y < height; y++ {
yRow := nv12[y*stride:]
- uvRow := uvPlane[(y/2)*stride:]
+ uvRow := uvPlane[(y/2)*stride : (y/2+1)*stride]
dstRow := pix[y*dst.Stride:]
for x := 0; x < width; x++ {
yv := int(yRow[x]) - 16
if yv < 0 {
yv = 0
}
- uvIdx := (x & ^1)
- u := int(uvRow[uvIdx]) - 128
- v := int(uvRow[uvIdx+1]) - 128
+ uvIdx := x & ^1
+ var u, v int
+ if uvIdx+1 < len(uvRow) {
+ u = int(uvRow[uvIdx]) - 128
+ v = int(uvRow[uvIdx+1]) - 128
+ } else if len(uvRow) >= 2 {
+ u = int(uvRow[len(uvRow)-2]) - 128
+ v = int(uvRow[len(uvRow)-1]) - 128
+ }
c := 298 * yv
r := (c + 459*v + 128) >> 8
@@ -442,6 +455,12 @@ func NV12ToRGBA(nv12 []byte, width, height, stride int, dst *image.RGBA) *image.
// BGRA32ToRGBA converts a Windows MFVideoFormat_RGB32 (BGRA in memory) buffer into *image.RGBA.
func BGRA32ToRGBA(bgra []byte, width, height, stride int, dst *image.RGBA) *image.RGBA {
+ if width <= 0 || height <= 0 {
+ if dst == nil {
+ return image.NewRGBA(image.Rect(0, 0, 0, 0))
+ }
+ return dst
+ }
if stride == 0 {
stride = width * 4
}
@@ -452,7 +471,7 @@ func BGRA32ToRGBA(bgra []byte, width, height, stride int, dst *image.RGBA) *imag
if absStride < 0 {
absStride = -absStride
}
- if len(bgra) < absStride*height {
+ if absStride < width*4 || len(bgra) < absStride*(height-1)+width*4 {
return dst
}
pix := dst.Pix
@@ -489,6 +508,12 @@ func clampByte(v int) uint8 {
// Foundation's ABGR32) row by row, honouring padded or bottom-up rows, and
// makes them opaque: a video frame never shows what is behind it.
func RGBA32Rows(src []byte, width, height, stride int, dst *image.RGBA) *image.RGBA {
+ if width <= 0 || height <= 0 {
+ if dst == nil {
+ return image.NewRGBA(image.Rect(0, 0, 0, 0))
+ }
+ return dst
+ }
if stride == 0 {
stride = width * 4
}
@@ -522,7 +547,7 @@ func RGBA32Rows(src []byte, width, height, stride int, dst *image.RGBA) *image.R
func contiguousStride(format string, width, height, typeStride, length int) int {
rows, minRow := height, width*4
if format == "nv12" {
- rows, minRow = height*3/2, width
+ rows, minRow = height+(height+1)/2, width
}
if rows <= 0 || length%rows != 0 {
return typeStride
diff --git a/internal/player/video_worker.go b/internal/player/video_worker.go
index 751dfdf..415c555 100644
--- a/internal/player/video_worker.go
+++ b/internal/player/video_worker.go
@@ -1,7 +1,9 @@
package player
import (
+ "errors"
"image"
+ "io"
"sync"
"time"
)
@@ -96,6 +98,17 @@ func (w *videoWorker) take() (*image.RGBA, uint64) {
return img, gen
}
+// isShown reports whether img is already the buffer currently displayed on screen.
+func (w *videoWorker) isShown(img *image.RGBA) bool {
+ if img == nil {
+ return false
+ }
+ w.mu.Lock()
+ same := img == w.shown
+ w.mu.Unlock()
+ return same
+}
+
// showing records img as the buffer on screen and recycles the previous one.
func (w *videoWorker) showing(img *image.RGBA) {
w.mu.Lock()
@@ -154,8 +167,15 @@ func (c *Controller) runVideoWorker(w *videoWorker, startGen uint64) {
} else {
img, pts, err = w.dec.DecodeVideoFrameAt(pos, buf)
}
+ select {
+ case <-w.stop:
+ w.putFree(buf)
+ return
+ default:
+ }
+ alreadyShown := err == nil && img != nil && w.isShown(img)
published := false
- if err == nil && img != nil && (pts != lastPTS || gen != lastGen) {
+ if err == nil && img != nil && !alreadyShown && (pts != lastPTS || gen != lastGen) {
published = w.publish(img, gen)
if published {
lastPTS = pts
@@ -165,11 +185,16 @@ func (c *Controller) runVideoWorker(w *videoWorker, startGen uint64) {
w.putFree(buf)
}
lastGen = gen
- if holding && (published || holdOver) {
+ if holding && (published || alreadyShown || errors.Is(err, io.EOF) || holdOver) {
c.releaseHold(gen)
}
if published && !playing && notify != nil {
- notify() // a paused seek: nothing else redraws the window
+ select {
+ case <-w.stop:
+ return
+ default:
+ notify() // a paused seek: nothing else redraws the window
+ }
}
if !playing {
continue
@@ -177,7 +202,7 @@ func (c *Controller) runVideoWorker(w *videoWorker, startGen uint64) {
// Sleep until the decoded frame is due; then the next one is needed.
wait := pts - pos
- if err != nil || !published {
+ if err != nil || (!published && !alreadyShown) {
wait = 4 * time.Millisecond
}
wait = min(max(wait, time.Millisecond), 100*time.Millisecond)
diff --git a/internal/player/video_worker_test.go b/internal/player/video_worker_test.go
index 7992d4c..158067a 100644
--- a/internal/player/video_worker_test.go
+++ b/internal/player/video_worker_test.go
@@ -34,8 +34,8 @@ func waitFor(t *testing.T, what string, cond func() bool) {
}
}
-// F-043: the view calls Advance every frame; with decoding on the UI thread a
-// slow decoder froze the window (13 s per call for a real 4K file).
+// The view calls Advance every frame; decoding off the UI thread prevents a
+// slow decoder from freezing the window.
func TestAdvanceNeverDecodesOnTheUIThread(t *testing.T) {
dec := &slowDecoder{SynthDecoder: NewSynthDecoder(64, 36, 30*time.Second, 30), delay: 150 * time.Millisecond}
c := NewController(Options{AudioSink: NewNullAudioSink()})
diff --git a/internal/remote/client.go b/internal/remote/client.go
new file mode 100644
index 0000000..67f9d4c
--- /dev/null
+++ b/internal/remote/client.go
@@ -0,0 +1,252 @@
+package remote
+
+import (
+ "bytes"
+ "context"
+ "crypto/tls"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+)
+
+// ErrorKind classifies a failed remote request for the desktop's Settings ›
+// 远程 (remote.md §7).
+type ErrorKind string
+
+const (
+ KindUnreachable ErrorKind = "unreachable" // 无法连接
+ KindCertChanged ErrorKind = "cert_changed" // 证书变了
+ KindUnauthorized ErrorKind = "unauthorized" // 令牌错
+ KindRateLimited ErrorKind = "rate_limited" // 暂时拒绝
+ KindVersion ErrorKind = "version" // 版本不同
+ KindRejected ErrorKind = "rejected" // 远程拒绝 Cookie
+ KindRemote ErrorKind = "remote" // 其他远程错误
+)
+
+// Error is a failed remote request.
+type Error struct {
+ Kind ErrorKind
+ Message string
+ ServerVersion string
+ ServerProtocol string
+ LocalVersion string
+ Status int
+}
+
+func (e *Error) Error() string {
+ switch e.Kind {
+ case KindUnreachable:
+ return "无法连接远程:" + e.Message
+ case KindCertChanged:
+ return "远程证书变了:与连接码里的指纹不一致,已拒绝连接。若远程重新 init 过,请粘贴新的连接码"
+ case KindUnauthorized:
+ return "远程拒绝了访问令牌:令牌错误或已更换,请粘贴新的连接码"
+ case KindRateLimited:
+ return "远程暂时拒绝连接:失败次数过多,请 10 分钟后再试"
+ case KindVersion:
+ return fmt.Sprintf("两边版本不同:远程 %s(协议 %s),本机 %s(协议 %s)。请把较旧的一边更新到同一版本", firstNonEmpty(e.ServerVersion, "未知"), firstNonEmpty(e.ServerProtocol, "未知"), firstNonEmpty(e.LocalVersion, "未知"), ProtocolVersion)
+ case KindRejected:
+ return "远程拒绝了 Cookie:" + e.Message
+ default:
+ if e.Message != "" {
+ return "远程出错:" + e.Message
+ }
+ return fmt.Sprintf("远程出错(HTTP %d)", e.Status)
+ }
+}
+
+// KindOf returns the kind of a remote error, or "".
+func KindOf(err error) ErrorKind {
+ var re *Error
+ if errors.As(err, &re) {
+ return re.Kind
+ }
+ return ""
+}
+
+// errFingerprint is returned by the TLS check when the certificate differs.
+var errFingerprint = errors.New("remote: certificate fingerprint mismatch")
+
+// Client talks to one remote over HTTPS, trusting only the certificate
+// whose SHA-256 is the connection's fingerprint.
+type Client struct {
+ conn Connection
+ version string
+ http *http.Client
+}
+
+// NewClient builds a client for conn; version is this build's version,
+// sent with every request.
+func NewClient(conn Connection, version string) (*Client, error) {
+ conn, err := conn.Normalize()
+ if err != nil {
+ return nil, err
+ }
+ want := conn.Fingerprint
+ tlsCfg := &tls.Config{
+ MinVersion: tls.VersionTLS13,
+ // The system's certificate store is not used: the only certificate
+ // trusted is the one pinned by the connection code. Verification is
+ // done in VerifyConnection, before any request byte is sent.
+ InsecureSkipVerify: true, //nolint:gosec // pinned below
+ VerifyConnection: func(cs tls.ConnectionState) error {
+ if len(cs.PeerCertificates) == 0 || Fingerprint(cs.PeerCertificates[0].Raw) != want {
+ return errFingerprint
+ }
+ return nil
+ },
+ }
+ tr := &http.Transport{
+ Proxy: nil,
+ TLSClientConfig: tlsCfg,
+ DialContext: (&net.Dialer{Timeout: 10 * time.Second}).DialContext,
+ TLSHandshakeTimeout: 10 * time.Second,
+ ResponseHeaderTimeout: 30 * time.Second,
+ MaxIdleConns: 2,
+ IdleConnTimeout: 60 * time.Second,
+ ForceAttemptHTTP2: false,
+ }
+ httpClient := &http.Client{
+ Transport: tr,
+ Timeout: 60 * time.Second,
+ // Never follow redirects: prevents downgrade from pinned HTTPS to an
+ // unpinned host or plaintext HTTP.
+ CheckRedirect: func(*http.Request, []*http.Request) error {
+ return http.ErrUseLastResponse
+ },
+ }
+ return &Client{conn: conn, version: version, http: httpClient}, nil
+}
+
+// Connection returns the client's connection.
+func (c *Client) Connection() Connection { return c.conn }
+
+// Close drops idle connections.
+func (c *Client) Close() { c.http.CloseIdleConnections() }
+
+// Status reads GET status.
+func (c *Client) Status(ctx context.Context) (Status, error) {
+ var st Status
+ err := c.do(ctx, http.MethodGet, "status", nil, &st)
+ return st, err
+}
+
+// Subscriptions reads the remote's synced subscription summary.
+func (c *Client) Subscriptions(ctx context.Context) (SubscriptionsInfo, error) {
+ var info SubscriptionsInfo
+ err := c.do(ctx, http.MethodGet, "subscriptions", nil, &info)
+ return info, err
+}
+
+// PutSubscriptions replaces the remote's subscriptions with snapshot (the
+// trace-subscriptions JSON).
+func (c *Client) PutSubscriptions(ctx context.Context, snapshot []byte) (SubscriptionsInfo, error) {
+ var info SubscriptionsInfo
+ err := c.do(ctx, http.MethodPut, "subscriptions", snapshot, &info)
+ return info, err
+}
+
+// PushCredential sends one site's Cookie; the remote checks it before it
+// keeps it.
+func (c *Client) PushCredential(ctx context.Context, siteID string, push CredentialPush) (SiteStatus, error) {
+ body, _ := json.Marshal(push)
+ var st SiteStatus
+ err := c.do(ctx, http.MethodPut, "credentials/"+url.PathEscape(siteID), body, &st)
+ return st, err
+}
+
+// DeleteCredential clears the remote's login of one site.
+func (c *Client) DeleteCredential(ctx context.Context, siteID string) error {
+ return c.do(ctx, http.MethodDelete, "credentials/"+url.PathEscape(siteID), nil, nil)
+}
+
+// RetryUpload makes failed uploads retry at once.
+func (c *Client) RetryUpload(ctx context.Context) error {
+ return c.do(ctx, http.MethodPost, "upload/retry", nil, nil)
+}
+
+func (c *Client) do(ctx context.Context, method, path string, body []byte, out any) error {
+ var rd io.Reader
+ if body != nil {
+ rd = bytes.NewReader(body)
+ }
+ req, err := http.NewRequestWithContext(ctx, method, c.conn.URL+APIPrefix+path, rd)
+ if err != nil {
+ return &Error{Kind: KindUnreachable, Message: "地址不正确"}
+ }
+ req.Header.Set("Authorization", "Bearer "+c.conn.Token)
+ req.Header.Set(HeaderProtocol, ProtocolVersion)
+ req.Header.Set(HeaderVersion, c.version)
+ if body != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ resp, err := c.http.Do(req)
+ if err != nil {
+ return classifyTransport(err)
+ }
+ defer resp.Body.Close()
+ raw, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
+ if err != nil {
+ return &Error{Kind: KindUnreachable, Message: "读取响应中断"}
+ }
+ if resp.StatusCode >= 200 && resp.StatusCode < 300 {
+ if out != nil && len(raw) > 0 {
+ if err := json.Unmarshal(raw, out); err != nil {
+ return &Error{Kind: KindRemote, Message: "响应格式不正确", Status: resp.StatusCode}
+ }
+ }
+ return nil
+ }
+ var eb ErrorBody
+ _ = json.Unmarshal(raw, &eb)
+ e := &Error{LocalVersion: c.version, Status: resp.StatusCode, Message: eb.Error.Message, ServerVersion: firstNonEmpty(eb.Error.ServerVersion, resp.Header.Get(HeaderVersion)), ServerProtocol: firstNonEmpty(eb.Error.ServerProtocol, resp.Header.Get(HeaderProtocol))}
+ switch {
+ case resp.StatusCode == http.StatusUnauthorized:
+ e.Kind = KindUnauthorized
+ case resp.StatusCode == http.StatusTooManyRequests:
+ e.Kind = KindRateLimited
+ case resp.StatusCode == http.StatusConflict && eb.Error.Code == CodeProtocol:
+ e.Kind = KindVersion
+ case eb.Error.Code == CodeCredentialRejected:
+ e.Kind = KindRejected
+ default:
+ e.Kind = KindRemote
+ }
+ return e
+}
+
+func classifyTransport(err error) error {
+ if errors.Is(err, errFingerprint) || strings.Contains(err.Error(), errFingerprint.Error()) {
+ return &Error{Kind: KindCertChanged}
+ }
+ msg := "网络不通或远程没有运行"
+ var nerr net.Error
+ switch {
+ case errors.Is(err, context.DeadlineExceeded) || errors.As(err, &nerr) && nerr.Timeout():
+ msg = "连接超时"
+ case errors.Is(err, context.Canceled):
+ msg = "已取消"
+ case strings.Contains(strings.ToLower(err.Error()), "refused"):
+ msg = "远程拒绝连接(程序没有运行或端口没有放行)"
+ case strings.Contains(strings.ToLower(err.Error()), "no such host"):
+ msg = "找不到这个地址"
+ case strings.Contains(strings.ToLower(err.Error()), "tls") || strings.Contains(strings.ToLower(err.Error()), "certificate"):
+ msg = "安全连接失败"
+ }
+ return &Error{Kind: KindUnreachable, Message: msg}
+}
+
+func firstNonEmpty(vals ...string) string {
+ for _, v := range vals {
+ if strings.TrimSpace(v) != "" {
+ return v
+ }
+ }
+ return ""
+}
diff --git a/internal/remote/client_test.go b/internal/remote/client_test.go
new file mode 100644
index 0000000..7a64e54
--- /dev/null
+++ b/internal/remote/client_test.go
@@ -0,0 +1,76 @@
+package remote
+
+import (
+ "context"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/tls"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "math/big"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func TestClientDoesNotFollowRedirects(t *testing.T) {
+ var targetHits atomic.Int32
+ target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ targetHits.Add(1)
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer target.Close()
+
+ key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now().UTC()
+ tpl := &x509.Certificate{
+ SerialNumber: big.NewInt(1),
+ Subject: pkix.Name{CommonName: "test"},
+ NotBefore: now.Add(-time.Hour),
+ NotAfter: now.Add(time.Hour),
+ KeyUsage: x509.KeyUsageDigitalSignature,
+ ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
+ IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
+ }
+ der, err := x509.CreateCertificate(rand.Reader, tpl, tpl, &key.PublicKey, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, target.URL+"/leaked", http.StatusFound)
+ }))
+ srv.TLS = &tls.Config{
+ MinVersion: tls.VersionTLS13,
+ Certificates: []tls.Certificate{{
+ Certificate: [][]byte{der},
+ PrivateKey: key,
+ }},
+ }
+ srv.StartTLS()
+ defer srv.Close()
+
+ c, err := NewClient(Connection{
+ URL: srv.URL,
+ Token: "0123456789abcdef0123456789abcdef",
+ Fingerprint: Fingerprint(der),
+ }, "1.0.0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer c.Close()
+
+ _, err = c.Status(context.Background())
+ if err == nil {
+ t.Fatal("expected redirect response to fail Status")
+ }
+ if targetHits.Load() != 0 {
+ t.Fatalf("redirect target received %d hits, want 0", targetHits.Load())
+ }
+}
diff --git a/internal/remote/code.go b/internal/remote/code.go
new file mode 100644
index 0000000..273bce4
--- /dev/null
+++ b/internal/remote/code.go
@@ -0,0 +1,101 @@
+package remote
+
+import (
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net"
+ "net/url"
+ "strconv"
+ "strings"
+)
+
+// CodePrefix starts every connection code.
+const CodePrefix = "trace-remote:1:"
+
+// Connection is what the desktop needs to reach one remote: its address,
+// access token and certificate fingerprint, and a name to show.
+type Connection struct {
+ URL string `json:"url"`
+ Token string `json:"token"`
+ Fingerprint string `json:"fingerprint"`
+ Name string `json:"name,omitempty"`
+}
+
+// EncodeCode turns a connection into the code trace-server init prints.
+func EncodeCode(c Connection) string {
+ raw, _ := json.Marshal(c)
+ return CodePrefix + base64.RawURLEncoding.EncodeToString(raw)
+}
+
+// ErrBadCode is returned for a code that is not a TRACE connection code.
+var ErrBadCode = errors.New("连接码不正确,请从远程的 trace-server init 或 token 输出里完整复制")
+
+// DecodeCode parses a connection code and checks its three parts.
+func DecodeCode(code string) (Connection, error) {
+ code = strings.TrimSpace(code)
+ if !strings.HasPrefix(code, CodePrefix) {
+ return Connection{}, ErrBadCode
+ }
+ raw, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(strings.TrimPrefix(code, CodePrefix), "="))
+ if err != nil {
+ return Connection{}, ErrBadCode
+ }
+ var c Connection
+ if err := json.Unmarshal(raw, &c); err != nil {
+ return Connection{}, ErrBadCode
+ }
+ return c.Normalize()
+}
+
+// Normalize checks a connection's address, token and fingerprint and
+// returns them in canonical form.
+func (c Connection) Normalize() (Connection, error) {
+ u, err := NormalizeURL(c.URL)
+ if err != nil {
+ return Connection{}, err
+ }
+ c.URL = u
+ c.Token = strings.TrimSpace(c.Token)
+ if len(c.Token) < 32 || strings.ContainsAny(c.Token, " \t\r\n") {
+ return Connection{}, fmt.Errorf("访问令牌不正确")
+ }
+ fp, ok := NormalizeFingerprint(c.Fingerprint)
+ if !ok {
+ return Connection{}, fmt.Errorf("证书指纹不正确,应是 64 位十六进制")
+ }
+ c.Fingerprint = fp
+ c.Name = strings.TrimSpace(c.Name)
+ return c, nil
+}
+
+// NormalizeURL accepts "host", "host:port" or "https://host[:port]" and
+// returns "https://host:port" (default port 47380).
+func NormalizeURL(raw string) (string, error) {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return "", fmt.Errorf("请填写远程地址")
+ }
+ if !strings.Contains(raw, "://") {
+ raw = "https://" + raw
+ }
+ u, err := url.Parse(raw)
+ if err != nil || u.Host == "" {
+ return "", fmt.Errorf("远程地址不正确")
+ }
+ if !strings.EqualFold(u.Scheme, "https") {
+ return "", fmt.Errorf("远程地址必须是 https")
+ }
+ host, port := u.Hostname(), u.Port()
+ if host == "" {
+ return "", fmt.Errorf("远程地址不正确")
+ }
+ if port == "" {
+ port = strconv.Itoa(DefaultPort)
+ }
+ if n, err := strconv.Atoi(port); err != nil || n <= 0 || n > 65535 {
+ return "", fmt.Errorf("远程端口不正确")
+ }
+ return "https://" + net.JoinHostPort(host, port), nil
+}
diff --git a/internal/remote/protocol.go b/internal/remote/protocol.go
new file mode 100644
index 0000000..f3165f1
--- /dev/null
+++ b/internal/remote/protocol.go
@@ -0,0 +1,221 @@
+// Package remote holds what the desktop app and trace-server share: the
+// protocol types of the remote API, the connection code and the HTTPS
+// client that trusts only the pinned certificate (docs/design/remote.md §3).
+// It depends on the standard library only.
+package remote
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "strings"
+)
+
+// Protocol constants. Both sides are always the same version (DEC-062 ②):
+// a different protocol is refused with 409 and both versions.
+const (
+ ProtocolVersion = "1"
+ HeaderProtocol = "X-Trace-Protocol"
+ HeaderVersion = "X-Trace-Version"
+ DefaultPort = 47380
+ // MaxBodyBytes bounds every request body (snapshot, Cookie).
+ MaxBodyBytes = 1 << 20
+ APIPrefix = "/api/v1/"
+)
+
+// Error codes of the remote API.
+const (
+ CodeUnauthorized = "unauthorized"
+ CodeRateLimited = "rate_limited"
+ CodeProtocol = "protocol"
+ CodeTooLarge = "too_large"
+ CodeBadRequest = "bad_request"
+ CodeCredentialRejected = "credential_rejected"
+ CodeNotFound = "not_found"
+ CodeInternal = "internal"
+)
+
+// ErrorBody is the JSON body of every error response.
+type ErrorBody struct {
+ Error struct {
+ Code string `json:"code"`
+ Message string `json:"message"`
+ ServerVersion string `json:"serverVersion,omitempty"`
+ ServerProtocol string `json:"serverProtocol,omitempty"`
+ ClientVersion string `json:"clientVersion,omitempty"`
+ ClientProtocol string `json:"clientProtocol,omitempty"`
+ RetryAfterSecs int `json:"retryAfterSecs,omitempty"`
+ CredentialState string `json:"credentialState,omitempty"`
+ } `json:"error"`
+}
+
+// Fingerprint is the pinned identity of the remote: the lowercase hex
+// SHA-256 of its leaf certificate (DER).
+func Fingerprint(der []byte) string {
+ sum := sha256.Sum256(der)
+ return hex.EncodeToString(sum[:])
+}
+
+// NormalizeFingerprint accepts a fingerprint with or without colons or
+// spaces, in any case, and returns the 64-character lowercase form.
+func NormalizeFingerprint(raw string) (string, bool) {
+ r := strings.NewReplacer(":", "", " ", "", "-", "")
+ fp := strings.ToLower(r.Replace(strings.TrimSpace(raw)))
+ if len(fp) != 64 {
+ return "", false
+ }
+ if _, err := hex.DecodeString(fp); err != nil {
+ return "", false
+ }
+ return fp, true
+}
+
+// Status is GET status (remote.md §7). It never holds a credential, a
+// signed address or a stream address.
+type Status struct {
+ Version string `json:"version"`
+ Protocol string `json:"protocol"`
+ Node Node `json:"node"`
+ StartedAt string `json:"startedAt"`
+ Now string `json:"now"`
+ Disk DiskStatus `json:"disk"`
+ Sites []SiteStatus `json:"sites"`
+ Subscriptions SubscriptionsInfo `json:"subscriptions"`
+ Checks []CheckRow `json:"checks,omitempty"`
+ Cache CacheStatus `json:"cache"`
+ Recordings []RecordingRow `json:"recordings,omitempty"`
+ Upload UploadStatus `json:"upload"`
+ Errors []ErrorRow `json:"errors,omitempty"`
+ Notes []string `json:"notes,omitempty"`
+ Extra map[string]float64 `json:"extra,omitempty"`
+}
+
+// Node names a TRACE installation.
+type Node struct {
+ ID string `json:"id"`
+ Name string `json:"name,omitempty"`
+}
+
+// DiskStatus is the export folder's space. Warning is set below 5 GiB,
+// Paused below 1 GiB (no new cache task starts).
+type DiskStatus struct {
+ Free uint64 `json:"free"`
+ Total uint64 `json:"total"`
+ Warning bool `json:"warning,omitempty"`
+ Paused bool `json:"paused,omitempty"`
+}
+
+// Site login states on the remote.
+const (
+ SiteValid = "valid" // 有效
+ SiteResync = "resync" // 需要重新同步 Cookie
+ SiteNone = "none" // 没有 Cookie
+ SiteBackoff = "backoff" // 退避到某时
+ SiteUnknown = "unknown" // 无法确认
+)
+
+// SiteStatus is one site's login on the remote.
+type SiteStatus struct {
+ Site string `json:"site"`
+ State string `json:"state"`
+ Uname string `json:"uname,omitempty"`
+ CookieSyncedAt string `json:"cookieSyncedAt,omitempty"`
+ BackoffUntil string `json:"backoffUntil,omitempty"`
+ Message string `json:"message,omitempty"`
+}
+
+// SubscriptionsInfo is the remote's synced subscriptions: counts, the time
+// of the last sync and the hash of the snapshot it applied.
+type SubscriptionsInfo struct {
+ Subscriptions int `json:"subscriptions"`
+ Accounts int `json:"accounts"`
+ SyncedAt string `json:"syncedAt,omitempty"`
+ Hash string `json:"hash,omitempty"`
+}
+
+// CheckRow is one account of the remote's check plan.
+type CheckRow struct {
+ Site string `json:"site"`
+ UID string `json:"uid"`
+ Name string `json:"name"`
+ Subscription string `json:"subscription,omitempty"`
+ LastCheckedAt string `json:"lastCheckedAt,omitempty"`
+ LastResult string `json:"lastResult,omitempty"`
+ NextAt string `json:"nextAt,omitempty"`
+ Baseline bool `json:"baseline,omitempty"`
+ Scheduled bool `json:"scheduled"`
+}
+
+// CacheStatus is the remote's cache tasks.
+type CacheStatus struct {
+ Running int `json:"running"`
+ Queued int `json:"queued"`
+ Recent []TaskRow `json:"recent,omitempty"`
+}
+
+// TaskRow is a recently finished or failed cache task.
+type TaskRow struct {
+ Site string `json:"site"`
+ Title string `json:"title"`
+ Status string `json:"status"`
+ At string `json:"at,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
+// RecordingRow is a live recording in progress on the remote.
+type RecordingRow struct {
+ Site string `json:"site"`
+ Name string `json:"name"`
+ Title string `json:"title,omitempty"`
+ StartedAt string `json:"startedAt,omitempty"`
+ DurationSec int64 `json:"durationSec"`
+ Bytes int64 `json:"bytes"`
+ Segments int `json:"segments"`
+ Incidents int `json:"incidents"`
+}
+
+// Upload modes.
+const (
+ UploadRclone = "rclone"
+ UploadNone = "none"
+)
+
+// Upload error kinds.
+const (
+ UploadErrNotFound = "rclone_missing" // rclone not found
+ UploadErrConfig = "config" // configuration or remote error
+ UploadErrQuota = "quota" // quota or rate limit (e.g. 750 GiB a day)
+ UploadErrNetwork = "network"
+ UploadErrGone = "file_gone" // the local file disappeared before upload
+ UploadErrOther = "other"
+)
+
+// UploadStatus is the remote's built-in upload.
+type UploadStatus struct {
+ Mode string `json:"mode"`
+ Target string `json:"target,omitempty"`
+ DeleteAfter bool `json:"deleteAfter"`
+ QueuedItems int `json:"queuedItems"`
+ QueuedBytes int64 `json:"queuedBytes"`
+ Uploading string `json:"uploading,omitempty"`
+ UploadingSize int64 `json:"uploadingSize,omitempty"`
+ TodayBytes int64 `json:"todayBytes"`
+ TodayFiles int `json:"todayFiles"`
+ LastError string `json:"lastError,omitempty"`
+ LastErrorKind string `json:"lastErrorKind,omitempty"`
+ LastErrorAt string `json:"lastErrorAt,omitempty"`
+ NextRetryAt string `json:"nextRetryAt,omitempty"`
+ GoneFiles int `json:"goneFiles,omitempty"`
+}
+
+// ErrorRow is one of the remote's recent errors (sanitized).
+type ErrorRow struct {
+ At string `json:"at"`
+ Category string `json:"category"`
+ Message string `json:"message"`
+}
+
+// CredentialPush is PUT credentials/{site}: the site Cookie and nothing
+// else; a refresh token is never pushed (DEC-062 ③).
+type CredentialPush struct {
+ Cookie string `json:"cookie"`
+}
diff --git a/internal/remoteserver/config.go b/internal/remoteserver/config.go
new file mode 100644
index 0000000..45f6822
--- /dev/null
+++ b/internal/remoteserver/config.go
@@ -0,0 +1,291 @@
+// Package remoteserver is trace-server's HTTPS API and its setup: the
+// self-signed certificate, the access token (only its hash is stored),
+// failure limiting and the routes that hand requests to the service layer
+// (docs/design/remote.md §2, §3). It never links the desktop UI.
+package remoteserver
+
+import (
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "encoding/pem"
+ "errors"
+ "fmt"
+ "math/big"
+ "net"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/chialecode/trace/internal/credential"
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/remote"
+ "github.com/chialecode/trace/internal/storage"
+ "github.com/chialecode/trace/internal/upload"
+)
+
+// Files of the data directory.
+const (
+ ConfigFile = "server.json"
+ TLSDir = "tls"
+ CertFile = "cert.pem"
+ KeyFile = "key.pem"
+)
+
+// Config is server.json. It never holds the token itself.
+type Config struct {
+ Version int `json:"version"`
+ Listen string `json:"listen"`
+ PublicURL string `json:"publicUrl"`
+ ExportDir string `json:"exportDir"`
+ Node string `json:"node"`
+ Name string `json:"name,omitempty"`
+ TokenHash string `json:"tokenHash"`
+ TokenSetAt string `json:"tokenSetAt"`
+ Upload upload.Config `json:"upload"`
+}
+
+// LoadConfig reads server.json from dataDir.
+func LoadConfig(dataDir string) (Config, error) {
+ raw, err := os.ReadFile(filepath.Join(dataDir, ConfigFile))
+ if err != nil {
+ if os.IsNotExist(err) {
+ return Config{}, fmt.Errorf("%s 里没有 %s:请先运行 trace-server init", dataDir, ConfigFile)
+ }
+ return Config{}, err
+ }
+ var c Config
+ if err := json.Unmarshal(raw, &c); err != nil {
+ return Config{}, fmt.Errorf("%s 格式不正确:%w", ConfigFile, err)
+ }
+ if c.Version != 1 {
+ return Config{}, fmt.Errorf("%s 的版本 %d 不是这个程序的版本", ConfigFile, c.Version)
+ }
+ if strings.TrimSpace(c.Listen) == "" || c.ExportDir == "" || c.TokenHash == "" {
+ return Config{}, fmt.Errorf("%s 不完整:请重新运行 trace-server init", ConfigFile)
+ }
+ if c.Upload, err = c.Upload.Normalize(); err != nil {
+ return Config{}, err
+ }
+ return c, nil
+}
+
+// SaveConfig writes server.json (0600).
+func SaveConfig(dataDir string, c Config) error {
+ return storage.WriteJSONAtomic(filepath.Join(dataDir, ConfigFile), c, 0o600)
+}
+
+// InitOptions are trace-server init's flags.
+type InitOptions struct {
+ DataDir string
+ ExportDir string
+ Listen string // default ":47380"
+ PublicAddress string // host or host:port written into the code
+ Name string
+}
+
+// InitResult is what init prints once.
+type InitResult struct {
+ Config Config
+ Code string
+ Conn remote.Connection
+}
+
+// Init prepares a data directory: folders (0700), node ID, a self-signed
+// certificate, the credential key and an access token. It refuses a data
+// directory that already has server.json.
+func Init(opt InitOptions) (InitResult, error) {
+ if strings.TrimSpace(opt.DataDir) == "" || strings.TrimSpace(opt.ExportDir) == "" {
+ return InitResult{}, errors.New("需要 --data 与 --export")
+ }
+ dataDir, err := filepath.Abs(opt.DataDir)
+ if err != nil {
+ return InitResult{}, err
+ }
+ exportDir, err := filepath.Abs(opt.ExportDir)
+ if err != nil {
+ return InitResult{}, err
+ }
+ if _, err := os.Stat(filepath.Join(dataDir, ConfigFile)); err == nil {
+ return InitResult{}, fmt.Errorf("%s 已经初始化过;要换令牌请用 trace-server token", dataDir)
+ }
+ listen := strings.TrimSpace(opt.Listen)
+ if listen == "" {
+ listen = ":" + strconv.Itoa(remote.DefaultPort)
+ }
+ _, port, err := net.SplitHostPort(listen)
+ if err != nil {
+ return InitResult{}, fmt.Errorf("--listen 不正确:%w", err)
+ }
+ portNum, err := strconv.Atoi(port)
+ if err != nil || portNum < 1 || portNum > 65535 {
+ return InitResult{}, fmt.Errorf("--listen 端口不正确:%q", port)
+ }
+ host := strings.TrimSpace(opt.PublicAddress)
+ if host == "" {
+ host = firstLANAddress()
+ }
+ if _, _, err := net.SplitHostPort(host); err != nil {
+ host = net.JoinHostPort(strings.Trim(host, "[]"), port)
+ }
+ publicURL, err := remote.NormalizeURL("https://" + host)
+ if err != nil {
+ return InitResult{}, err
+ }
+ for _, d := range []string{dataDir, exportDir, filepath.Join(dataDir, TLSDir), filepath.Join(dataDir, "credentials"), filepath.Join(dataDir, "logs")} {
+ if err := os.MkdirAll(d, 0o700); err != nil {
+ return InitResult{}, err
+ }
+ _ = os.Chmod(d, 0o700)
+ }
+ name := strings.TrimSpace(opt.Name)
+ if name == "" {
+ name, _ = os.Hostname()
+ }
+ node, err := library.LoadOrCreateNode(dataDir, name)
+ if err != nil {
+ return InitResult{}, err
+ }
+ fp, err := generateCertificate(filepath.Join(dataDir, TLSDir), hostOnly(host))
+ if err != nil {
+ return InitResult{}, err
+ }
+ if err := credential.EnsureKeyFile(filepath.Join(dataDir, "credentials")); err != nil {
+ return InitResult{}, err
+ }
+ token, hash, err := newToken()
+ if err != nil {
+ return InitResult{}, err
+ }
+ cfg := Config{Version: 1, Listen: listen, PublicURL: publicURL, ExportDir: exportDir, Node: node.Node, Name: name,
+ TokenHash: hash, TokenSetAt: time.Now().UTC().Format(time.RFC3339), Upload: upload.DefaultConfig()}
+ if err := SaveConfig(dataDir, cfg); err != nil {
+ return InitResult{}, err
+ }
+ conn := remote.Connection{URL: publicURL, Token: token, Fingerprint: fp, Name: name}
+ return InitResult{Config: cfg, Code: remote.EncodeCode(conn), Conn: conn}, nil
+}
+
+// RotateToken replaces the token; the old one stops working at once (the
+// running server detects changes to server.json and reloads the token hash).
+func RotateToken(dataDir string) (InitResult, error) {
+ cfg, err := LoadConfig(dataDir)
+ if err != nil {
+ return InitResult{}, err
+ }
+ fp, err := CertificateFingerprint(dataDir)
+ if err != nil {
+ return InitResult{}, err
+ }
+ token, hash, err := newToken()
+ if err != nil {
+ return InitResult{}, err
+ }
+ cfg.TokenHash, cfg.TokenSetAt = hash, time.Now().UTC().Format(time.RFC3339)
+ if err := SaveConfig(dataDir, cfg); err != nil {
+ return InitResult{}, err
+ }
+ conn := remote.Connection{URL: cfg.PublicURL, Token: token, Fingerprint: fp, Name: cfg.Name}
+ return InitResult{Config: cfg, Code: remote.EncodeCode(conn), Conn: conn}, nil
+}
+
+func newToken() (token, hash string, err error) {
+ var raw [32]byte
+ if _, err := rand.Read(raw[:]); err != nil {
+ return "", "", err
+ }
+ token = base64.RawURLEncoding.EncodeToString(raw[:])
+ return token, HashToken(token), nil
+}
+
+// HashToken is the stored form of a token.
+func HashToken(token string) string {
+ sum := sha256.Sum256([]byte(token))
+ return hex.EncodeToString(sum[:])
+}
+
+func hostOnly(hostport string) string {
+ h, _, err := net.SplitHostPort(hostport)
+ if err != nil {
+ return strings.Trim(hostport, "[]")
+ }
+ return h
+}
+
+// firstLANAddress is the first non-loopback IPv4 address, or 127.0.0.1.
+func firstLANAddress() string {
+ addrs, err := net.InterfaceAddrs()
+ if err == nil {
+ for _, a := range addrs {
+ if ipn, ok := a.(*net.IPNet); ok && !ipn.IP.IsLoopback() && ipn.IP.To4() != nil && !ipn.IP.IsLinkLocalUnicast() {
+ return ipn.IP.String()
+ }
+ }
+ }
+ return "127.0.0.1"
+}
+
+// generateCertificate writes a 10-year self-signed ECDSA P-256 certificate
+// and its key (0600) and returns the fingerprint.
+func generateCertificate(dir, host string) (string, error) {
+ key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ if err != nil {
+ return "", err
+ }
+ serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 120))
+ if err != nil {
+ return "", err
+ }
+ now := time.Now().UTC()
+ tpl := &x509.Certificate{
+ SerialNumber: serial,
+ Subject: pkix.Name{CommonName: "trace-server"},
+ NotBefore: now.Add(-time.Hour),
+ NotAfter: now.AddDate(10, 0, 0),
+ KeyUsage: x509.KeyUsageDigitalSignature,
+ ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
+ BasicConstraintsValid: true,
+ DNSNames: []string{"trace-server"},
+ }
+ if ip := net.ParseIP(host); ip != nil {
+ tpl.IPAddresses = []net.IP{ip}
+ } else if host != "" {
+ tpl.DNSNames = append(tpl.DNSNames, host)
+ }
+ der, err := x509.CreateCertificate(rand.Reader, tpl, tpl, &key.PublicKey, key)
+ if err != nil {
+ return "", err
+ }
+ keyDER, err := x509.MarshalECPrivateKey(key)
+ if err != nil {
+ return "", err
+ }
+ if err := storage.WriteFileAtomic(filepath.Join(dir, KeyFile), pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}), 0o600); err != nil {
+ return "", err
+ }
+ if err := storage.WriteFileAtomic(filepath.Join(dir, CertFile), pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o600); err != nil {
+ return "", err
+ }
+ return remote.Fingerprint(der), nil
+}
+
+// CertificateFingerprint reads the certificate of dataDir.
+func CertificateFingerprint(dataDir string) (string, error) {
+ raw, err := os.ReadFile(filepath.Join(dataDir, TLSDir, CertFile))
+ if err != nil {
+ return "", err
+ }
+ block, _ := pem.Decode(raw)
+ if block == nil {
+ return "", errors.New("证书文件格式不正确")
+ }
+ return remote.Fingerprint(block.Bytes), nil
+}
diff --git a/internal/remoteserver/desktop_test.go b/internal/remoteserver/desktop_test.go
new file mode 100644
index 0000000..b36372e
--- /dev/null
+++ b/internal/remoteserver/desktop_test.go
@@ -0,0 +1,289 @@
+package remoteserver
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/chialecode/trace/internal/appdirs"
+ "github.com/chialecode/trace/internal/remote"
+ "github.com/chialecode/trace/internal/service"
+ "github.com/chialecode/trace/internal/subscription"
+)
+
+// pairHarness is a desktop backend connected to a real remote API (the
+// remote's backend in remote mode), both on the same fake site.
+type pairHarness struct {
+ desktop *service.Backend
+ remote *service.Backend
+ server *Server
+ https *httptest.Server
+ down atomic.Bool
+ code string
+ bili *fakeBili
+}
+
+func newPair(t *testing.T) *pairHarness {
+ t.Helper()
+ dataDir, res := initServer(t)
+ p := &pairHarness{bili: newFakeBili(t)}
+ p.remote = remoteBackend(t, dataDir, p.bili)
+ cfg, _ := LoadConfig(dataDir)
+ p.server = New(Options{DataDir: dataDir, TokenHash: cfg.TokenHash, Service: p.remote})
+ tlsCfg, err := TLSConfig(dataDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ p.https = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if p.down.Load() {
+ http.Error(w, "down", http.StatusBadGateway)
+ return
+ }
+ p.server.ServeHTTP(w, r)
+ }))
+ p.https.TLS = tlsCfg
+ p.https.StartTLS()
+ t.Cleanup(p.https.Close)
+ conn := res.Conn
+ conn.URL = p.https.URL
+ p.code = remote.EncodeCode(conn)
+
+ tmp := t.TempDir()
+ loc, err := appdirs.ResolveWithOptions(appdirs.Options{Channel: "dev", ForceMode: "portable", DataDir: filepath.Join(tmp, "data"), CacheDir: filepath.Join(tmp, "cache")})
+ if err != nil {
+ t.Fatal(err)
+ }
+ bo := service.Options{Locations: loc, Desktop: service.NewMockDesktop(), DisableBgWorkers: true}
+ p.bili.options(&bo)
+ p.desktop, err = service.NewBackend(bo)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = p.desktop.Close() })
+ return p
+}
+
+func (p *pairHarness) remoteSite(t *testing.T) remote.SiteStatus {
+ t.Helper()
+ for _, r := range p.server.Status().Sites {
+ if r.Site == "bilibili" {
+ return r
+ }
+ }
+ t.Fatal("no bilibili row")
+ return remote.SiteStatus{}
+}
+
+func waitFor(t *testing.T, what string, cond func() bool) {
+ t.Helper()
+ deadline := time.Now().Add(10 * time.Second)
+ for !cond() {
+ if time.Now().After(deadline) {
+ t.Fatalf("timed out waiting for %s", what)
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+}
+
+// The desktop connects with a code, keeps the token out of
+// settings.json, and maps each failure to its own message.
+func TestDesktopConnectAndErrorKinds(t *testing.T) {
+ p := newPair(t)
+ ctx := context.Background()
+ if _, err := p.desktop.RemoteStatus(ctx); err != service.ErrNoRemote {
+ t.Fatalf("status before connecting = %v, want ErrNoRemote", err)
+ }
+ view, err := p.desktop.ConnectRemote(ctx, service.RemoteConnectInput{Code: p.code})
+ if err != nil {
+ t.Fatalf("ConnectRemote: %v", err)
+ }
+ if view.Connection.Name != "测试远程" || view.Status.Version == "" {
+ t.Fatalf("view = %+v", view)
+ }
+ conn, _ := remote.DecodeCode(p.code)
+ s := p.desktop.GetSettings()
+ if len(s.Remote.Connections) != 1 || s.Remote.Connections[0].Fingerprint != conn.Fingerprint {
+ t.Fatalf("saved connection = %+v", s.Remote)
+ }
+ if raw := mustReadSettings(t, p.desktop); strings.Contains(raw, conn.Token) {
+ t.Fatal("settings.json contains the token")
+ }
+
+ // A wrong token is not saved.
+ bad := conn
+ bad.URL = p.https.URL
+ bad.Token = strings.Repeat("z", 43)
+ if _, err := p.desktop.ConnectRemote(ctx, service.RemoteConnectInput{Code: remote.EncodeCode(bad)}); remote.KindOf(err) != remote.KindUnauthorized {
+ t.Fatalf("wrong token: %v", err)
+ }
+ if info, _ := p.desktop.RemoteConnection(); info.Fingerprint != conn.Fingerprint {
+ t.Fatal("a failed connect replaced the saved connection")
+ }
+
+ // Version and rate-limit answers from a server (synthetic responses).
+ answers := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if strings.HasSuffix(r.URL.Path, "/status") {
+ w.WriteHeader(http.StatusConflict)
+ _, _ = w.Write([]byte(`{"error":{"code":"protocol","message":"x","serverVersion":"9.9.9","serverProtocol":"2"}}`))
+ return
+ }
+ w.WriteHeader(http.StatusTooManyRequests)
+ _, _ = w.Write([]byte(`{"error":{"code":"rate_limited","message":"x","retryAfterSecs":600}}`))
+ }))
+ defer answers.Close()
+ c, _ := remote.NewClient(remote.Connection{URL: answers.URL, Token: conn.Token, Fingerprint: remote.Fingerprint(answers.Certificate().Raw)}, "1.2.3")
+ defer c.Close()
+ _, err = c.Status(ctx)
+ var re *remote.Error
+ if remote.KindOf(err) != remote.KindVersion || !asRemoteErr(err, &re) || re.ServerVersion != "9.9.9" || re.LocalVersion != "1.2.3" || !strings.Contains(err.Error(), "9.9.9") || !strings.Contains(err.Error(), "1.2.3") {
+ t.Fatalf("version error = %v", err)
+ }
+ if _, err := c.Subscriptions(ctx); remote.KindOf(err) != remote.KindRateLimited {
+ t.Fatalf("rate limited = %v", err)
+ }
+
+ if err := p.desktop.RemoveRemote(); err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := p.desktop.RemoteConnection(); ok {
+ t.Fatal("RemoveRemote kept the connection")
+ }
+}
+
+// A local login pushes the Cookie to the remote automatically; a
+// push that cannot reach the remote is kept as "Cookie 待同步" and sent on
+// the next retry; a Cookie the remote rejects is not retried.
+func TestDesktopPushesCookieAfterLoginAndRetriesPending(t *testing.T) {
+ p := newPair(t)
+ ctx := context.Background()
+ if _, err := p.desktop.ConnectRemote(ctx, service.RemoteConnectInput{Code: p.code}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := p.desktop.ImportCookie(ctx, sentinelCookie(), ""); err != nil {
+ t.Fatalf("local login: %v", err)
+ }
+ waitFor(t, "the automatic push", func() bool { return p.remoteSite(t).State == remote.SiteValid })
+ if acc := p.remote.AccountStatus(); acc.Source != service.CredentialSourceRemotePush || acc.HasRefreshToken {
+ t.Fatalf("remote credential = %+v, want pushed without a refresh token", acc)
+ }
+
+ p.down.Store(true)
+ if _, err := p.desktop.PushCredentialToRemote(ctx, "bilibili"); err == nil {
+ t.Fatal("push to a down remote succeeded")
+ }
+ if info, _ := p.desktop.RemoteConnection(); len(info.PendingCookies) != 1 || info.PendingCookies[0] != "bilibili" {
+ t.Fatalf("pending = %+v, want bilibili", info.PendingCookies)
+ }
+ if p.desktop.RetryPendingRemoteCookies(ctx) {
+ t.Fatal("retry while down reported success")
+ }
+ p.down.Store(false)
+ if !p.desktop.RetryPendingRemoteCookies(ctx) {
+ t.Fatal("retry after the remote came back did not push")
+ }
+ if info, _ := p.desktop.RemoteConnection(); len(info.PendingCookies) != 0 {
+ t.Fatalf("pending after a successful retry = %+v", info.PendingCookies)
+ }
+
+ // The remote's site check refuses the Cookie: the reason comes back,
+ // the remote keeps its login and nothing stays pending.
+ p.bili.expired.Store(true)
+ _, err := p.desktop.PushCredentialToRemote(ctx, "bilibili")
+ if remote.KindOf(err) != remote.KindRejected || !strings.Contains(err.Error(), "远程拒绝了 Cookie") {
+ t.Fatalf("rejected push = %v", err)
+ }
+ if info, _ := p.desktop.RemoteConnection(); len(info.PendingCookies) != 0 {
+ t.Fatalf("a rejected Cookie stays pending: %+v", info.PendingCookies)
+ }
+ if acc := p.remote.AccountStatus(); !acc.LoggedIn {
+ t.Fatal("the rejected push removed the remote's login")
+ }
+
+ if err := p.desktop.ClearRemoteCredential(ctx, "bilibili"); err != nil {
+ t.Fatal(err)
+ }
+ if p.remoteSite(t).State != remote.SiteNone {
+ t.Fatal("清除远程登录 kept the remote's login")
+ }
+}
+
+// 有改动未同步 follows the snapshot hash: a sync makes both sides
+// equal; a rename makes them differ; a refreshed account name does not.
+// The remote replaces its subscriptions with the desktop's.
+func TestDesktopSyncStateFollowsSnapshotHash(t *testing.T) {
+ p := newPair(t)
+ ctx := context.Background()
+ if _, err := p.desktop.ConnectRemote(ctx, service.RemoteConnectInput{Code: p.code}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := p.desktop.ImportCookie(ctx, sentinelCookie(), ""); err != nil {
+ t.Fatal(err)
+ }
+ sub, err := p.desktop.CreateSubscription("合成订阅", "", []subscription.AccountRef{{Site: "bilibili", UID: "1001", Name: "UP"}}, subscription.DefaultSubRules())
+ if err != nil {
+ t.Fatal(err)
+ }
+ view, err := p.desktop.RemoteStatus(ctx)
+ if err != nil || view.InSync {
+ t.Fatalf("before sync: InSync=%v err=%v", view.InSync, err)
+ }
+ info, err := p.desktop.SyncSubscriptionsToRemote(ctx)
+ if err != nil || info.Subscriptions != 1 || info.Accounts != 1 {
+ t.Fatalf("sync = %+v, %v", info, err)
+ }
+ view, _ = p.desktop.RemoteStatus(ctx)
+ if !view.InSync || view.LocalHash != view.Status.Subscriptions.Hash {
+ t.Fatalf("after sync: %+v", view)
+ }
+ remoteSubs, _ := p.remote.ListSubscriptions()
+ if len(remoteSubs) != 1 || remoteSubs[0].ID != sub.ID || remoteSubs[0].Name != "合成订阅" {
+ t.Fatalf("remote subscriptions = %+v", remoteSubs)
+ }
+
+ if err := p.desktop.SubscriptionManager().UpdateAccountSnapshot("bilibili", "1001", "UP 新名字", "", ""); err != nil {
+ t.Fatal(err)
+ }
+ if view, _ = p.desktop.RemoteStatus(ctx); !view.InSync {
+ t.Fatal("a refreshed account name marked the subscriptions as changed")
+ }
+ sub.Name = "改过的名字"
+ if _, err := p.desktop.UpsertSubscription(sub); err != nil {
+ t.Fatal(err)
+ }
+ if view, _ = p.desktop.RemoteStatus(ctx); view.InSync {
+ t.Fatal("a rename did not mark the subscriptions as changed")
+ }
+ if err := p.desktop.DeleteSubscription(sub.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := p.desktop.SyncSubscriptionsToRemote(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if remoteSubs, _ = p.remote.ListSubscriptions(); len(remoteSubs) != 0 {
+ t.Fatalf("a sync of no subscriptions left %d on the remote", len(remoteSubs))
+ }
+}
+
+func asRemoteErr(err error, out **remote.Error) bool {
+ re, ok := err.(*remote.Error)
+ if ok {
+ *out = re
+ }
+ return ok
+}
+
+func mustReadSettings(t *testing.T, b *service.Backend) string {
+ t.Helper()
+ raw, err := os.ReadFile(filepath.Join(b.Locations().DataDir, "settings.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(raw)
+}
diff --git a/internal/remoteserver/disk_linux.go b/internal/remoteserver/disk_linux.go
new file mode 100644
index 0000000..8cb2227
--- /dev/null
+++ b/internal/remoteserver/disk_linux.go
@@ -0,0 +1,21 @@
+//go:build linux
+
+package remoteserver
+
+import "golang.org/x/sys/unix"
+
+// DiskSpace reports the free (available to this user) and total bytes of
+// the file system holding dir.
+func DiskSpace(dir string) Disk {
+ return func() (uint64, uint64, error) {
+ var st unix.Statfs_t
+ if err := unix.Statfs(dir, &st); err != nil {
+ return 0, 0, err
+ }
+ unit := uint64(st.Frsize)
+ if unit == 0 {
+ unit = uint64(st.Bsize)
+ }
+ return uint64(st.Bavail) * unit, uint64(st.Blocks) * unit, nil
+ }
+}
diff --git a/internal/remoteserver/disk_other.go b/internal/remoteserver/disk_other.go
new file mode 100644
index 0000000..3d720a7
--- /dev/null
+++ b/internal/remoteserver/disk_other.go
@@ -0,0 +1,17 @@
+//go:build !windows && !linux
+
+package remoteserver
+
+import "golang.org/x/sys/unix"
+
+// DiskSpace reports the free (available to this user) and total bytes of
+// the file system holding dir.
+func DiskSpace(dir string) Disk {
+ return func() (uint64, uint64, error) {
+ var st unix.Statfs_t
+ if err := unix.Statfs(dir, &st); err != nil {
+ return 0, 0, err
+ }
+ return uint64(st.Bavail) * uint64(st.Bsize), uint64(st.Blocks) * uint64(st.Bsize), nil
+ }
+}
diff --git a/internal/remoteserver/disk_windows.go b/internal/remoteserver/disk_windows.go
new file mode 100644
index 0000000..d5a4c31
--- /dev/null
+++ b/internal/remoteserver/disk_windows.go
@@ -0,0 +1,21 @@
+//go:build windows
+
+package remoteserver
+
+import "golang.org/x/sys/windows"
+
+// DiskSpace reports the free (available to this user) and total bytes of
+// the volume holding dir.
+func DiskSpace(dir string) Disk {
+ return func() (uint64, uint64, error) {
+ ptr, err := windows.UTF16PtrFromString(dir)
+ if err != nil {
+ return 0, 0, err
+ }
+ var free, total, totalFree uint64
+ if err := windows.GetDiskFreeSpaceEx(ptr, &free, &total, &totalFree); err != nil {
+ return 0, 0, err
+ }
+ return free, total, nil
+ }
+}
diff --git a/internal/remoteserver/run.go b/internal/remoteserver/run.go
new file mode 100644
index 0000000..d215bf6
--- /dev/null
+++ b/internal/remoteserver/run.go
@@ -0,0 +1,122 @@
+package remoteserver
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "net"
+ "time"
+
+ "github.com/chialecode/trace/internal/appdirs"
+ "github.com/chialecode/trace/internal/service"
+ "github.com/chialecode/trace/internal/upload"
+)
+
+// RunOptions configure trace-server run.
+type RunOptions struct {
+ DataDir string
+ // Listener replaces listening on server.json's address (tests).
+ Listener net.Listener
+ // Backend adjusts the backend options (tests point the site clients at
+ // fake sites here).
+ Backend func(*service.Options)
+ // LogMirror receives the log lines too (standard error under systemd).
+ LogMirror io.Writer
+ // UploadEnv is rclone's environment; the process's when nil.
+ UploadEnv []string
+ // Ready is called with the listening address once requests are served.
+ Ready func(addr string)
+ // ExitTimeout bounds the finishing of tasks and recordings (30 s).
+ ExitTimeout time.Duration
+}
+
+// Run starts the backend in remote mode, the uploader and the HTTPS API,
+// and serves until ctx ends; then it finishes like 退出 in the tray (tasks
+// paused, recordings finalized) within ExitTimeout and returns nil.
+func Run(ctx context.Context, opt RunOptions) error {
+ cfg, err := LoadConfig(opt.DataDir)
+ if err != nil {
+ return err
+ }
+ lock, err := appdirs.LockDataDir(opt.DataDir)
+ if err != nil {
+ return fmt.Errorf("数据目录正被另一个 trace-server 使用:%w", err)
+ }
+ defer lock.Release()
+ tlsCfg, err := TLSConfig(opt.DataDir)
+ if err != nil {
+ return fmt.Errorf("读取证书失败:%w", err)
+ }
+ if opt.ExitTimeout <= 0 {
+ opt.ExitTimeout = 30 * time.Second
+ }
+
+ bo := service.Options{
+ Locations: service.RemoteLocations(opt.DataDir, cfg.ExportDir),
+ Desktop: service.NewMockDesktop(),
+ Profile: service.ProfileRemote,
+ NodeName: cfg.Name,
+ LogMirror: opt.LogMirror,
+ }
+ if opt.Backend != nil {
+ opt.Backend(&bo)
+ }
+ backend, err := service.NewBackend(bo)
+ if err != nil {
+ return err
+ }
+ disk := DiskSpace(cfg.ExportDir)
+ backend.SetCacheGate(CacheGate(disk))
+
+ up, err := upload.New(upload.Options{
+ Config: cfg.Upload, Library: backend.LibraryStore(), DB: backend.LibraryDB(), DataDir: opt.DataDir,
+ Busy: backend.ItemBusy, Env: opt.UploadEnv, Logf: backend.Logf,
+ })
+ if err != nil {
+ _ = backend.Close()
+ return err
+ }
+ backend.LibraryStore().OnSaved(up.Notify)
+ upCtx, stopUpload := context.WithCancel(context.Background())
+ go up.Run(upCtx)
+
+ ln := opt.Listener
+ if ln == nil {
+ ln, err = net.Listen("tcp", cfg.Listen)
+ if err != nil {
+ stopUpload()
+ up.Wait()
+ _ = backend.Close()
+ return fmt.Errorf("无法监听 %s:%w", cfg.Listen, err)
+ }
+ }
+ srv := New(Options{DataDir: opt.DataDir, TokenHash: cfg.TokenHash, Service: backend, Uploader: up, Disk: disk, Logf: backend.Logf})
+ backend.Logf("trace-server listening: %s upload=%s", ln.Addr().String(), cfg.Upload.Mode)
+ serveCtx, stopServe := context.WithCancel(context.Background())
+ served := make(chan error, 1)
+ go func() { served <- srv.Serve(serveCtx, ln, tlsCfg) }()
+ if opt.Ready != nil {
+ opt.Ready(ln.Addr().String())
+ }
+
+ var serveErr error
+ select {
+ case <-ctx.Done():
+ case serveErr = <-served:
+ }
+ backend.Logf("trace-server stopping")
+ stopServe()
+ if serveErr == nil {
+ serveErr = <-served
+ }
+ if !backend.ExitGracefully(opt.ExitTimeout) {
+ backend.Logf("trace-server: tasks did not finish within %s", opt.ExitTimeout)
+ }
+ stopUpload()
+ up.Wait()
+ closeErr := backend.Close()
+ if serveErr != nil {
+ return serveErr
+ }
+ return closeErr
+}
diff --git a/internal/remoteserver/server.go b/internal/remoteserver/server.go
new file mode 100644
index 0000000..cc141aa
--- /dev/null
+++ b/internal/remoteserver/server.go
@@ -0,0 +1,492 @@
+package remoteserver
+
+import (
+ "context"
+ "crypto/subtle"
+ "crypto/tls"
+ "encoding/json"
+ "errors"
+ "io"
+ "log"
+ "math"
+ "net"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/chialecode/trace/internal/appdirs"
+ "github.com/chialecode/trace/internal/remote"
+ "github.com/chialecode/trace/internal/site"
+ "github.com/chialecode/trace/internal/upload"
+)
+
+// Service is what the API needs from the backend (implemented by
+// *service.Backend in remote mode).
+type Service interface {
+ ServerStatus() remote.Status
+ ServerSubscriptions() remote.SubscriptionsInfo
+ ApplyRemoteSnapshot(raw []byte) (remote.SubscriptionsInfo, error)
+ AcceptPushedCredential(ctx context.Context, siteID, cookie string) (remote.SiteStatus, error)
+ ClearPushedCredential(siteID string) error
+}
+
+// Uploader is the upload part of the API.
+type Uploader interface {
+ Status() remote.UploadStatus
+ RetryNow()
+}
+
+// Disk reports the export folder's free and total bytes.
+type Disk func() (free, total uint64, err error)
+
+// Space thresholds of the export folder (remote.md §6.2).
+const (
+ DiskWarnBytes = 5 << 30
+ DiskPauseBytes = 1 << 30
+)
+
+// Failure limiting: 5 failures from one address within a minute block it
+// for 10 minutes.
+const (
+ failWindow = time.Minute
+ failLimit = 5
+ blockFor = 10 * time.Minute
+ maxTrackedIPs = 10000
+ pruneInterval = time.Minute
+)
+
+// Server is the HTTPS API.
+type Server struct {
+ dataDir string
+ svc Service
+ up Uploader
+ disk Disk
+ now func() time.Time
+ logf func(format string, args ...any)
+
+ mu sync.Mutex
+ tokenHash string
+ cfgInfo os.FileInfo
+ failures map[string][]time.Time
+ blocked map[string]time.Time
+ lastPrune time.Time
+ requests int
+}
+
+// Options configure a Server.
+type Options struct {
+ DataDir string
+ TokenHash string
+ Service Service
+ Uploader Uploader
+ Disk Disk
+ Now func() time.Time
+ Logf func(format string, args ...any)
+}
+
+// New builds the API.
+func New(opt Options) *Server {
+ if opt.Now == nil {
+ opt.Now = time.Now
+ }
+ if opt.Logf == nil {
+ opt.Logf = func(string, ...any) {}
+ }
+ return &Server{dataDir: opt.DataDir, svc: opt.Service, up: opt.Uploader, disk: opt.Disk, now: opt.Now, logf: opt.Logf,
+ tokenHash: opt.TokenHash, failures: map[string][]time.Time{}, blocked: map[string]time.Time{}}
+}
+
+// Requests counts the HTTP requests that reached the handler (tests).
+func (s *Server) Requests() int {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.requests
+}
+
+// TLSConfig loads the certificate of dataDir (TLS 1.3 only).
+func TLSConfig(dataDir string) (*tls.Config, error) {
+ cert, err := tls.LoadX509KeyPair(filepath.Join(dataDir, TLSDir, CertFile), filepath.Join(dataDir, TLSDir, KeyFile))
+ if err != nil {
+ return nil, err
+ }
+ return &tls.Config{MinVersion: tls.VersionTLS13, Certificates: []tls.Certificate{cert}}, nil
+}
+
+// HTTPServer wraps the handler with the timeouts of the API.
+func (s *Server) HTTPServer(tlsCfg *tls.Config) *http.Server {
+ return &http.Server{
+ Handler: s,
+ TLSConfig: tlsCfg,
+ ReadHeaderTimeout: 10 * time.Second,
+ ReadTimeout: 30 * time.Second,
+ WriteTimeout: 30 * time.Second,
+ IdleTimeout: 60 * time.Second,
+ MaxHeaderBytes: 16 << 10,
+ // Handshake failures (a client pinned to another certificate, scans)
+ // go to the run log, not to standard error unformatted.
+ ErrorLog: log.New(logWriter{s.logf}, "", 0),
+ }
+}
+
+// Serve accepts TLS connections on ln until ctx ends.
+func (s *Server) Serve(ctx context.Context, ln net.Listener, tlsCfg *tls.Config) error {
+ hs := s.HTTPServer(tlsCfg)
+ errc := make(chan error, 1)
+ go func() { errc <- hs.Serve(tls.NewListener(ln, tlsCfg)) }()
+ select {
+ case <-ctx.Done():
+ sctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ if err := hs.Shutdown(sctx); err != nil {
+ _ = hs.Close()
+ }
+ <-errc
+ return nil
+ case err := <-errc:
+ if errors.Is(err, http.ErrServerClosed) {
+ return nil
+ }
+ return err
+ }
+}
+
+func clientIP(r *http.Request) string {
+ // X-Forwarded-For is never trusted: the API is reached directly.
+ host, _, err := net.SplitHostPort(r.RemoteAddr)
+ if err != nil {
+ return r.RemoteAddr
+ }
+ return host
+}
+
+func writeJSON(w http.ResponseWriter, code int, v any) {
+ w.Header().Set("Content-Type", "application/json; charset=utf-8")
+ w.Header().Set("Cache-Control", "no-store")
+ w.WriteHeader(code)
+ _ = json.NewEncoder(w).Encode(v)
+}
+
+func writeError(w http.ResponseWriter, code int, errCode, msg string, fill func(*remote.ErrorBody)) {
+ var body remote.ErrorBody
+ body.Error.Code, body.Error.Message = errCode, msg
+ if fill != nil {
+ fill(&body)
+ }
+ writeJSON(w, code, body)
+}
+
+// blockedLocked reports whether ip is blocked now and the remaining seconds.
+func (s *Server) blockedLocked(ip string, now time.Time) (bool, int) {
+ until, ok := s.blocked[ip]
+ if !ok {
+ return false, 0
+ }
+ if now.Before(until) {
+ rem := int(math.Ceil(until.Sub(now).Seconds()))
+ if rem < 1 {
+ rem = 1
+ }
+ return true, rem
+ }
+ delete(s.blocked, ip)
+ delete(s.failures, ip)
+ return false, 0
+}
+
+func (s *Server) pruneLimitersLocked(now time.Time, force bool) {
+ if !force && !s.lastPrune.IsZero() && now.Sub(s.lastPrune) < pruneInterval {
+ return
+ }
+ s.lastPrune = now
+ for k, until := range s.blocked {
+ if !now.Before(until) {
+ delete(s.blocked, k)
+ }
+ }
+ for k, times := range s.failures {
+ kept := times[:0]
+ for _, t := range times {
+ if now.Sub(t) < failWindow {
+ kept = append(kept, t)
+ }
+ }
+ if len(kept) == 0 {
+ delete(s.failures, k)
+ } else {
+ s.failures[k] = kept
+ }
+ }
+}
+
+func (s *Server) evictOldestLimiterLocked() {
+ // Prefer evicting an unblocked IP with the oldest failure timestamp.
+ var victim string
+ var oldest time.Time
+ for k, times := range s.failures {
+ if _, isBlocked := s.blocked[k]; isBlocked {
+ continue
+ }
+ last := times[len(times)-1]
+ if victim == "" || last.Before(oldest) {
+ victim, oldest = k, last
+ }
+ }
+ if victim != "" {
+ delete(s.failures, victim)
+ return
+ }
+ for k, until := range s.blocked {
+ if victim == "" || until.Before(oldest) {
+ victim, oldest = k, until
+ }
+ }
+ if victim != "" {
+ delete(s.blocked, victim)
+ delete(s.failures, victim)
+ }
+}
+
+func (s *Server) recordFailure(ip string, now time.Time) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.pruneLimitersLocked(now, len(s.failures) >= maxTrackedIPs || len(s.blocked) >= maxTrackedIPs)
+ if _, exists := s.failures[ip]; !exists {
+ for len(s.failures) >= maxTrackedIPs || len(s.blocked) >= maxTrackedIPs {
+ s.evictOldestLimiterLocked()
+ }
+ }
+ var kept []time.Time
+ for _, t := range s.failures[ip] {
+ if now.Sub(t) < failWindow {
+ kept = append(kept, t)
+ }
+ }
+ kept = append(kept, now)
+ s.failures[ip] = kept
+ if len(kept) >= failLimit {
+ s.blocked[ip] = now.Add(blockFor)
+ }
+}
+
+func (s *Server) reloadTokenHash(force bool) string {
+ s.mu.Lock()
+ hash := s.tokenHash
+ prevInfo := s.cfgInfo
+ s.mu.Unlock()
+ if s.dataDir == "" {
+ return hash
+ }
+ cfgPath := filepath.Join(s.dataDir, ConfigFile)
+ st, err := os.Stat(cfgPath)
+ if err != nil {
+ return hash
+ }
+ unchanged := prevInfo != nil && os.SameFile(prevInfo, st) &&
+ st.ModTime().Equal(prevInfo.ModTime()) && st.Size() == prevInfo.Size()
+ if unchanged && !force {
+ return hash
+ }
+ if cfg, err := LoadConfig(s.dataDir); err == nil {
+ hash = cfg.TokenHash
+ s.mu.Lock()
+ s.tokenHash = hash
+ s.cfgInfo = st
+ s.mu.Unlock()
+ }
+ return hash
+}
+
+// tokenOK compares in constant time against the stored hash; server.json is
+// stat-checked so `trace-server token` takes effect at once without re-reading
+// and parsing the config on every request.
+func (s *Server) tokenOK(token string) bool {
+ if token == "" {
+ return false
+ }
+ got := HashToken(token)
+ hash := s.reloadTokenHash(false)
+ if subtle.ConstantTimeCompare([]byte(got), []byte(hash)) == 1 {
+ return true
+ }
+ // On mismatch, re-read once in case server.json was updated in-place within
+ // the same filesystem mtime tick.
+ if s.dataDir != "" {
+ fresh := s.reloadTokenHash(true)
+ if fresh != hash && subtle.ConstantTimeCompare([]byte(got), []byte(fresh)) == 1 {
+ return true
+ }
+ }
+ return false
+}
+
+// ServeHTTP authenticates, checks the protocol and routes.
+func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ now := s.now()
+ ip := clientIP(r)
+ s.mu.Lock()
+ s.requests++
+ blocked, retryAfter := s.blockedLocked(ip, now)
+ s.mu.Unlock()
+ version := appdirs.BuildInfo().Version
+ w.Header().Set(remote.HeaderProtocol, remote.ProtocolVersion)
+ w.Header().Set(remote.HeaderVersion, version)
+ if blocked {
+ writeError(w, http.StatusTooManyRequests, remote.CodeRateLimited, "失败次数过多,请稍后再试", func(b *remote.ErrorBody) { b.Error.RetryAfterSecs = retryAfter })
+ return
+ }
+ if !strings.HasPrefix(r.URL.Path, remote.APIPrefix) {
+ s.recordFailure(ip, now)
+ writeError(w, http.StatusNotFound, remote.CodeNotFound, "没有这个地址", nil)
+ return
+ }
+ auth := r.Header.Get("Authorization")
+ token, ok := strings.CutPrefix(auth, "Bearer ")
+ if !ok || !s.tokenOK(strings.TrimSpace(token)) {
+ s.recordFailure(ip, now)
+ writeError(w, http.StatusUnauthorized, remote.CodeUnauthorized, "访问令牌不正确", nil)
+ return
+ }
+ if p := r.Header.Get(remote.HeaderProtocol); p != remote.ProtocolVersion {
+ cv := r.Header.Get(remote.HeaderVersion)
+ writeError(w, http.StatusConflict, remote.CodeProtocol, "两边的协议版本不同", func(b *remote.ErrorBody) {
+ b.Error.ServerVersion, b.Error.ServerProtocol = version, remote.ProtocolVersion
+ b.Error.ClientVersion, b.Error.ClientProtocol = cv, p
+ })
+ return
+ }
+ var body []byte
+ if r.Body != nil {
+ raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, remote.MaxBodyBytes))
+ if err != nil {
+ var mbe *http.MaxBytesError
+ if errors.As(err, &mbe) {
+ writeError(w, http.StatusRequestEntityTooLarge, remote.CodeTooLarge, "请求内容超过 1 MiB", nil)
+ return
+ }
+ writeError(w, http.StatusBadRequest, remote.CodeBadRequest, "请求内容读取失败", nil)
+ return
+ }
+ body = raw
+ }
+ s.route(w, r, body)
+}
+
+func (s *Server) route(w http.ResponseWriter, r *http.Request, body []byte) {
+ path := strings.TrimPrefix(r.URL.Path, remote.APIPrefix)
+ switch {
+ case path == "status" && r.Method == http.MethodGet:
+ writeJSON(w, http.StatusOK, s.Status())
+ case path == "subscriptions" && r.Method == http.MethodGet:
+ writeJSON(w, http.StatusOK, s.svc.ServerSubscriptions())
+ case path == "subscriptions" && r.Method == http.MethodPut:
+ info, err := s.svc.ApplyRemoteSnapshot(body)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, remote.CodeBadRequest, "订阅同步失败:"+err.Error(), nil)
+ return
+ }
+ writeJSON(w, http.StatusOK, info)
+ case strings.HasPrefix(path, "credentials/") && (r.Method == http.MethodPut || r.Method == http.MethodDelete):
+ siteID := strings.ToLower(strings.TrimPrefix(path, "credentials/"))
+ if siteID != string(site.Bilibili) && siteID != string(site.Douyin) {
+ writeError(w, http.StatusNotFound, remote.CodeNotFound, "不支持这个站点", nil)
+ return
+ }
+ if r.Method == http.MethodDelete {
+ if err := s.svc.ClearPushedCredential(siteID); err != nil {
+ writeError(w, http.StatusInternalServerError, remote.CodeInternal, "清除登录失败", nil)
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]string{"site": siteID, "state": remote.SiteNone})
+ return
+ }
+ var push remote.CredentialPush
+ if err := json.Unmarshal(body, &push); err != nil || strings.TrimSpace(push.Cookie) == "" {
+ writeError(w, http.StatusBadRequest, remote.CodeBadRequest, "请求里没有 Cookie", nil)
+ return
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second)
+ defer cancel()
+ st, err := s.svc.AcceptPushedCredential(ctx, siteID, push.Cookie)
+ if err != nil {
+ // The site's reason, never the Cookie.
+ writeError(w, http.StatusUnprocessableEntity, remote.CodeCredentialRejected, credentialReason(err), nil)
+ return
+ }
+ writeJSON(w, http.StatusOK, st)
+ case path == "upload/retry" && r.Method == http.MethodPost:
+ if s.up != nil {
+ s.up.RetryNow()
+ }
+ writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
+ default:
+ writeError(w, http.StatusNotFound, remote.CodeNotFound, "没有这个接口", nil)
+ }
+}
+
+func credentialReason(err error) string {
+ var se *site.Error
+ if errors.As(err, &se) && strings.TrimSpace(se.Message) != "" {
+ return se.Message
+ }
+ switch site.KindOf(err) {
+ case site.ErrKindAuthRequired:
+ return "站点确认这个 Cookie 未登录或已失效"
+ case site.ErrKindRiskControl, site.ErrKindRateLimited:
+ return "站点暂时限制了远程的请求,请稍后再同步"
+ case site.ErrKindNetwork:
+ return "远程连不上站点,请检查远程的网络"
+ }
+ return "站点校验没有通过"
+}
+
+// Status is the full status: the backend's, the upload and the disk.
+func (s *Server) Status() remote.Status {
+ st := s.svc.ServerStatus()
+ if s.up != nil {
+ st.Upload = s.up.Status()
+ } else {
+ st.Upload = remote.UploadStatus{Mode: remote.UploadNone}
+ }
+ if s.disk != nil {
+ if free, total, err := s.disk(); err == nil {
+ st.Disk = remote.DiskStatus{Free: free, Total: total, Warning: free < DiskWarnBytes, Paused: free < DiskPauseBytes}
+ } else {
+ s.logf("disk space check failed: %v", err)
+ st.Disk = remote.DiskStatus{Warning: true, Paused: true}
+ }
+ }
+ return st
+}
+
+// CacheGate is the backend's gate for new cache tasks: closed while the
+// export folder has less than 1 GiB free or cannot be queried.
+func CacheGate(disk Disk) func() error {
+ return func() error {
+ if disk == nil {
+ return nil
+ }
+ free, _, err := disk()
+ if err != nil {
+ return errors.New("无法读取导出目录剩余空间,暂停新的缓存任务")
+ }
+ if free < DiskPauseBytes {
+ return errors.New("导出目录剩余空间不足 1 GiB,暂停新的缓存任务")
+ }
+ return nil
+ }
+}
+
+var _ Uploader = (*upload.Uploader)(nil)
+
+// logWriter hands net/http's error lines to the run log.
+type logWriter struct {
+ logf func(format string, args ...any)
+}
+
+func (w logWriter) Write(p []byte) (int, error) {
+ w.logf("https: %s", strings.TrimSpace(string(p)))
+ return len(p), nil
+}
diff --git a/internal/remoteserver/server_test.go b/internal/remoteserver/server_test.go
new file mode 100644
index 0000000..f820fbe
--- /dev/null
+++ b/internal/remoteserver/server_test.go
@@ -0,0 +1,637 @@
+package remoteserver
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/chialecode/trace/internal/appdirs"
+ "github.com/chialecode/trace/internal/credential"
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/remote"
+ "github.com/chialecode/trace/internal/service"
+ "github.com/chialecode/trace/internal/site/bilibili"
+ "github.com/chialecode/trace/internal/subscription"
+ "github.com/chialecode/trace/internal/upload"
+ "github.com/chialecode/trace/internal/upload/fakerclone"
+)
+
+func TestMain(m *testing.M) {
+ if fakerclone.Enabled() {
+ os.Exit(fakerclone.Main(os.Args[1:]))
+ }
+ os.Exit(m.Run())
+}
+
+// Synthetic secrets: none of them may appear in a log, a status or a file
+// in plain text.
+const (
+ sentinelSess = "SENTINEL_SESS_6b1d0c"
+ sentinelCSRF = "SENTINEL_CSRF_91c2aa"
+)
+
+func sentinelCookie() string {
+ return "SESSDATA=" + sentinelSess + "; bili_jct=" + sentinelCSRF + "; DedeUserID=778899"
+}
+
+func initServer(t *testing.T) (dataDir string, res InitResult) {
+ t.Helper()
+ root := t.TempDir()
+ dataDir = filepath.Join(root, "data")
+ res, err := Init(InitOptions{DataDir: dataDir, ExportDir: filepath.Join(root, "export"), Listen: "127.0.0.1:47380", PublicAddress: "127.0.0.1", Name: "测试远程"})
+ if err != nil {
+ t.Fatalf("Init: %v", err)
+ }
+ return dataDir, res
+}
+
+// Init writes private files, stores only the token's hash and
+// prints a code that decodes to the same connection; token rotation makes
+// the old token fail at once.
+func TestInitPrivateFilesCodeAndTokenRotation(t *testing.T) {
+ dataDir, res := initServer(t)
+ conn, err := remote.DecodeCode(res.Code)
+ if err != nil {
+ t.Fatalf("DecodeCode: %v", err)
+ }
+ if conn != res.Conn || conn.Token == "" || len(conn.Token) < 40 {
+ t.Fatalf("code connection = %+v, want %+v with a 32-byte token", conn, res.Conn)
+ }
+ fp, err := CertificateFingerprint(dataDir)
+ if err != nil || fp != conn.Fingerprint {
+ t.Fatalf("fingerprint = %q (%v), code has %q", fp, err, conn.Fingerprint)
+ }
+ raw, err := os.ReadFile(filepath.Join(dataDir, ConfigFile))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(string(raw), conn.Token) {
+ t.Fatal("server.json contains the token itself")
+ }
+ cfg, err := LoadConfig(dataDir)
+ if err != nil || cfg.TokenHash != HashToken(conn.Token) || cfg.Upload.Mode != remote.UploadNone {
+ t.Fatalf("config = %+v (%v)", cfg, err)
+ }
+ if _, err := Init(InitOptions{DataDir: dataDir, ExportDir: cfg.ExportDir}); err == nil {
+ t.Fatal("a second init over an initialized data directory must fail")
+ }
+ if runtime.GOOS != "windows" {
+ for _, p := range []string{ConfigFile, filepath.Join(TLSDir, KeyFile), filepath.Join(TLSDir, CertFile), filepath.Join("credentials", credential.KeyFileName)} {
+ st, err := os.Stat(filepath.Join(dataDir, p))
+ if err != nil || st.Mode().Perm() != 0o600 {
+ t.Fatalf("%s mode = %v (%v), want 0600", p, st.Mode().Perm(), err)
+ }
+ }
+ for _, d := range []string{"", TLSDir, "credentials"} {
+ st, err := os.Stat(filepath.Join(dataDir, d))
+ if err != nil || st.Mode().Perm() != 0o700 {
+ t.Fatalf("dir %q mode = %v (%v), want 0700", d, st.Mode().Perm(), err)
+ }
+ }
+ }
+
+ s := New(Options{DataDir: dataDir, TokenHash: cfg.TokenHash, Service: &fakeService{}})
+ if !s.tokenOK(conn.Token) || s.tokenOK("") || s.tokenOK(conn.Token+"x") {
+ t.Fatal("token check before rotation is wrong")
+ }
+ rot, err := RotateToken(dataDir)
+ if err != nil {
+ t.Fatalf("RotateToken: %v", err)
+ }
+ if rot.Conn.Token == conn.Token || rot.Conn.Fingerprint != conn.Fingerprint || rot.Conn.URL != conn.URL {
+ t.Fatalf("rotated connection = %+v", rot.Conn)
+ }
+ if s.tokenOK(conn.Token) {
+ t.Fatal("the old token still works after rotation")
+ }
+ if !s.tokenOK(rot.Conn.Token) {
+ t.Fatal("the new token does not work on the running server")
+ }
+}
+
+type fakeService struct {
+ mu sync.Mutex
+ puts int
+ pushes []string
+ rejectAs error
+}
+
+func (f *fakeService) ServerStatus() remote.Status {
+ return remote.Status{Version: "test", Protocol: remote.ProtocolVersion}
+}
+func (f *fakeService) ServerSubscriptions() remote.SubscriptionsInfo {
+ return remote.SubscriptionsInfo{}
+}
+func (f *fakeService) ApplyRemoteSnapshot(raw []byte) (remote.SubscriptionsInfo, error) {
+ f.mu.Lock()
+ f.puts++
+ f.mu.Unlock()
+ if _, err := subscription.ParseSnapshot(raw); err != nil {
+ return remote.SubscriptionsInfo{}, err
+ }
+ return remote.SubscriptionsInfo{Hash: "h"}, nil
+}
+func (f *fakeService) AcceptPushedCredential(_ context.Context, siteID, _ string) (remote.SiteStatus, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.rejectAs != nil {
+ return remote.SiteStatus{}, f.rejectAs
+ }
+ f.pushes = append(f.pushes, siteID)
+ return remote.SiteStatus{Site: siteID, State: remote.SiteValid}, nil
+}
+func (f *fakeService) ClearPushedCredential(string) error { return nil }
+
+type apiHarness struct {
+ t *testing.T
+ srv *httptest.Server
+ s *Server
+ token string
+ clock atomic.Int64
+}
+
+func newAPIHarness(t *testing.T, svc Service, disk Disk) *apiHarness {
+ t.Helper()
+ dataDir, res := initServer(t)
+ cfg, _ := LoadConfig(dataDir)
+ h := &apiHarness{t: t, token: res.Conn.Token}
+ h.clock.Store(time.Date(2026, 11, 19, 8, 0, 0, 0, time.UTC).UnixNano())
+ h.s = New(Options{DataDir: dataDir, TokenHash: cfg.TokenHash, Service: svc, Disk: disk, Now: func() time.Time { return time.Unix(0, h.clock.Load()) }})
+ h.srv = httptest.NewServer(h.s)
+ t.Cleanup(h.srv.Close)
+ return h
+}
+
+func (h *apiHarness) do(method, path, token, protocol string, body []byte) (int, remote.ErrorBody) {
+ h.t.Helper()
+ req, _ := http.NewRequest(method, h.srv.URL+path, bytes.NewReader(body))
+ if token != "" {
+ req.Header.Set("Authorization", "Bearer "+token)
+ }
+ if protocol != "" {
+ req.Header.Set(remote.HeaderProtocol, protocol)
+ }
+ req.Header.Set(remote.HeaderVersion, "0.0.0-client")
+ resp, err := h.srv.Client().Do(req)
+ if err != nil {
+ h.t.Fatalf("%s %s: %v", method, path, err)
+ }
+ defer resp.Body.Close()
+ raw, _ := io.ReadAll(resp.Body)
+ var eb remote.ErrorBody
+ _ = json.Unmarshal(raw, &eb)
+ if resp.Header.Get(remote.HeaderProtocol) != remote.ProtocolVersion {
+ h.t.Fatalf("response without the protocol header: %v", resp.Header)
+ }
+ return resp.StatusCode, eb
+}
+
+// Wrong tokens are 401 and five failures within a minute block the
+// address for ten minutes (even with the right token); oversized bodies
+// are 413; a different protocol is 409 with both versions.
+func TestAPIAuthFailureLimitBodyLimitAndProtocol(t *testing.T) {
+ svc := &fakeService{}
+ h := newAPIHarness(t, svc, nil)
+ p := remote.ProtocolVersion
+ if code, _ := h.do("GET", "/api/v1/status", h.token, p, nil); code != 200 {
+ t.Fatalf("status with the right token = %d", code)
+ }
+ if code, _ := h.do("GET", "/api/v1/status", "", p, nil); code != 401 {
+ t.Fatalf("no token = %d, want 401", code)
+ }
+ if code, _ := h.do("GET", "/", h.token, p, nil); code != 404 {
+ t.Fatalf("outside the API = %d, want 404", code)
+ }
+ for i := 0; i < 3; i++ {
+ if code, _ := h.do("GET", "/api/v1/status", "wrong-token", p, nil); code != 401 {
+ t.Fatalf("wrong token = %d, want 401", code)
+ }
+ }
+ // Five failures in a minute: blocked even with the right token.
+ code, eb := h.do("GET", "/api/v1/status", h.token, p, nil)
+ if code != 429 || eb.Error.Code != remote.CodeRateLimited || eb.Error.RetryAfterSecs != 600 {
+ t.Fatalf("after five failures = %d %+v, want 429", code, eb)
+ }
+ h.clock.Add(int64(9 * time.Minute))
+ if code, eb := h.do("GET", "/api/v1/status", h.token, p, nil); code != 429 || eb.Error.RetryAfterSecs != 60 {
+ t.Fatalf("after 9 minutes = %d %+v, want still 429 with retryAfter=60", code, eb)
+ }
+ h.clock.Add(int64(time.Minute + time.Second))
+ if code, _ := h.do("GET", "/api/v1/status", h.token, p, nil); code != 200 {
+ t.Fatalf("after 10 minutes = %d, want 200", code)
+ }
+
+ big := bytes.Repeat([]byte("x"), remote.MaxBodyBytes+1)
+ if code, eb := h.do("PUT", "/api/v1/subscriptions", h.token, p, big); code != 413 || eb.Error.Code != remote.CodeTooLarge {
+ t.Fatalf("oversized body = %d %+v, want 413", code, eb)
+ }
+ if svc.puts != 0 {
+ t.Fatal("an oversized snapshot reached the service")
+ }
+ code, eb = h.do("GET", "/api/v1/status", h.token, "999", nil)
+ if code != 409 || eb.Error.Code != remote.CodeProtocol || eb.Error.ServerProtocol != remote.ProtocolVersion || eb.Error.ClientProtocol != "999" || eb.Error.ClientVersion != "0.0.0-client" || eb.Error.ServerVersion == "" {
+ t.Fatalf("protocol mismatch = %d %+v", code, eb)
+ }
+}
+
+// A client pinned to another certificate fails the handshake
+// before any request reaches the handler; the right fingerprint works and
+// a version difference names both versions.
+func TestClientPinsCertificateBeforeAnyRequest(t *testing.T) {
+ dataDir, res := initServer(t)
+ _, other := initServer(t)
+ cfg, _ := LoadConfig(dataDir)
+ s := New(Options{DataDir: dataDir, TokenHash: cfg.TokenHash, Service: &fakeService{}})
+ tlsCfg, err := TLSConfig(dataDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan error, 1)
+ go func() { done <- s.Serve(ctx, ln, tlsCfg) }()
+ t.Cleanup(func() { cancel(); <-done })
+ url := "https://" + ln.Addr().String()
+
+ bad, _ := remote.NewClient(remote.Connection{URL: url, Token: res.Conn.Token, Fingerprint: other.Conn.Fingerprint}, "1.0.0")
+ defer bad.Close()
+ _, err = bad.Status(context.Background())
+ if remote.KindOf(err) != remote.KindCertChanged {
+ t.Fatalf("pinned to another certificate: err = %v (kind %q), want cert_changed", err, remote.KindOf(err))
+ }
+ if n := s.Requests(); n != 0 {
+ t.Fatalf("handler saw %d requests through a rejected certificate", n)
+ }
+
+ good, _ := remote.NewClient(remote.Connection{URL: url, Token: res.Conn.Token, Fingerprint: res.Conn.Fingerprint}, "1.0.0")
+ defer good.Close()
+ if _, err := good.Status(context.Background()); err != nil {
+ t.Fatalf("Status with the right fingerprint: %v", err)
+ }
+ wrongToken, _ := remote.NewClient(remote.Connection{URL: url, Token: strings.Repeat("w", 43), Fingerprint: res.Conn.Fingerprint}, "1.0.0")
+ defer wrongToken.Close()
+ if _, err := wrongToken.Status(context.Background()); remote.KindOf(err) != remote.KindUnauthorized {
+ t.Fatalf("wrong token: %v, want unauthorized", err)
+ }
+ closed, _ := remote.NewClient(remote.Connection{URL: "https://127.0.0.1:1", Token: res.Conn.Token, Fingerprint: res.Conn.Fingerprint}, "1.0.0")
+ defer closed.Close()
+ if _, err := closed.Status(context.Background()); remote.KindOf(err) != remote.KindUnreachable {
+ t.Fatalf("closed port: %v, want unreachable", err)
+ }
+}
+
+// fakeBili answers nav for synthetic Cookies; expired=true makes every
+// Cookie expire.
+type fakeBili struct {
+ srv *httptest.Server
+ reqs atomic.Int64
+ expired atomic.Bool
+}
+
+func newFakeBili(t *testing.T) *fakeBili {
+ t.Helper()
+ f := &fakeBili{}
+ f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ f.reqs.Add(1)
+ w.Header().Set("Content-Type", "application/json")
+ switch r.URL.Path {
+ case "/x/web-interface/nav":
+ ck := r.Header.Get("Cookie")
+ if f.expired.Load() || !strings.Contains(ck, "SESSDATA=") || strings.Contains(ck, "SESSDATA=expired") {
+ _, _ = fmt.Fprint(w, `{"code":-101,"message":"账号未登录","data":{"isLogin":false}}`)
+ return
+ }
+ _, _ = fmt.Fprint(w, `{"code":0,"data":{"isLogin":true,"mid":778899,"uname":"合成远程用户","face":"","wbi_img":{"img_url":"https://i0.hdslb.com/bfs/wbi/7cd084941338484aae1ad9425b84077c.png","sub_url":"https://i0.hdslb.com/bfs/wbi/4932caff0ff746eab6f01bf08b70ac45.png"}}}`)
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ t.Cleanup(f.srv.Close)
+ return f
+}
+
+func (f *fakeBili) options(bo *service.Options) {
+ u := f.srv.URL
+ bo.BilibiliOpts = bilibili.ClientOptions{
+ Endpoints: bilibili.Endpoints{APIBase: u, PassportBase: u, WWWBase: u, SpaceBase: u, DynamicBase: u, LiveAPIBase: u, LiveWebBase: u},
+ PacingInterval: -1,
+ AllowLocalhost: true,
+ }
+}
+
+func remoteBackend(t *testing.T, dataDir string, bili *fakeBili) *service.Backend {
+ t.Helper()
+ cfg, err := LoadConfig(dataDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ bo := service.Options{Locations: service.RemoteLocations(dataDir, cfg.ExportDir), Desktop: service.NewMockDesktop(), Profile: service.ProfileRemote, NodeName: cfg.Name, DisableBgWorkers: true}
+ bili.options(&bo)
+ b, err := service.NewBackend(bo)
+ if err != nil {
+ t.Fatalf("NewBackend: %v", err)
+ }
+ t.Cleanup(func() { _ = b.Close() })
+ return b
+}
+
+// A pushed Cookie is checked with the site before it replaces the
+// stored one; a rejected push keeps the old login and returns the site's
+// reason; a pushed login that expires shows as 需要重新同步.
+func TestCredentialPushVerifiesBeforeSaving(t *testing.T) {
+ dataDir, res := initServer(t)
+ bili := newFakeBili(t)
+ b := remoteBackend(t, dataDir, bili)
+ cfg, _ := LoadConfig(dataDir)
+ s := New(Options{DataDir: dataDir, TokenHash: cfg.TokenHash, Service: b})
+ h := httptest.NewServer(s)
+ t.Cleanup(h.Close)
+
+ push := func(cookie string) (int, remote.ErrorBody, []byte) {
+ body, _ := json.Marshal(remote.CredentialPush{Cookie: cookie})
+ req, _ := http.NewRequest("PUT", h.URL+"/api/v1/credentials/bilibili", bytes.NewReader(body))
+ req.Header.Set("Authorization", "Bearer "+res.Conn.Token)
+ req.Header.Set(remote.HeaderProtocol, remote.ProtocolVersion)
+ resp, err := h.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ raw, _ := io.ReadAll(resp.Body)
+ var eb remote.ErrorBody
+ _ = json.Unmarshal(raw, &eb)
+ return resp.StatusCode, eb, raw
+ }
+
+ code, _, raw := push(sentinelCookie())
+ if code != 200 {
+ t.Fatalf("valid push = %d %s", code, raw)
+ }
+ var st remote.SiteStatus
+ _ = json.Unmarshal(raw, &st)
+ if st.State != remote.SiteValid || st.Uname != "合成远程用户" || st.CookieSyncedAt == "" {
+ t.Fatalf("pushed site status = %+v", st)
+ }
+ if strings.Contains(string(raw), sentinelSess) {
+ t.Fatal("the response echoes the Cookie")
+ }
+ acc := b.AccountStatus()
+ if !acc.LoggedIn || acc.Source != service.CredentialSourceRemotePush {
+ t.Fatalf("stored credential = %+v, want logged in with source remote_push", acc)
+ }
+ before := bili.reqs.Load()
+
+ code, eb, raw := push("SESSDATA=expired; bili_jct=x")
+ if code != 422 || eb.Error.Code != remote.CodeCredentialRejected || eb.Error.Message == "" {
+ t.Fatalf("rejected push = %d %s", code, raw)
+ }
+ if bili.reqs.Load() == before {
+ t.Fatal("the rejected Cookie was not checked with the site")
+ }
+ if acc := b.AccountStatus(); !acc.LoggedIn || acc.Mid != 778899 {
+ t.Fatalf("a rejected push replaced the stored login: %+v", acc)
+ }
+
+ bili.expired.Store(true)
+ _, _ = b.VerifyAccount(context.Background())
+ var row remote.SiteStatus
+ for _, r := range s.Status().Sites {
+ if r.Site == "bilibili" {
+ row = r
+ }
+ }
+ if row.State != remote.SiteResync || row.Message == "" {
+ t.Fatalf("expired pushed login = %+v, want resync", row)
+ }
+}
+
+// Trace-server run end to end over loopback HTTPS: sync a
+// snapshot, push a Cookie, read the status, upload an item through the
+// fake rclone, stop on cancel. The token and the Cookie appear in no log,
+// status or file.
+func TestRunEndToEndWithoutLeakingSecrets(t *testing.T) {
+ dataDir, res := initServer(t)
+ cfg, _ := LoadConfig(dataDir)
+ root := filepath.Dir(dataDir)
+ cloud := filepath.Join(root, "cloud")
+ rlog := filepath.Join(root, "rclone.log")
+ cfg.Upload = upload.Config{Mode: remote.UploadRclone, Remote: "fake:trace", Rclone: os.Args[0], DeleteAfterUpload: true}
+ if err := SaveConfig(dataDir, cfg); err != nil {
+ t.Fatal(err)
+ }
+ bili := newFakeBili(t)
+
+ // An item already in the export folder (a finished cache of a previous
+ // run) is uploaded and removed after the upload.
+ {
+ b := remoteBackend(t, dataDir, bili)
+ itemDir := filepath.Join(cfg.ExportDir, "bilibili", "1001_UP", "videos", "video_e2e")
+ _ = os.MkdirAll(itemDir, 0o700)
+ _ = os.WriteFile(filepath.Join(itemDir, "P01.mp4"), []byte("video"), 0o600)
+ if _, err := b.LibraryStore().SaveItem(itemDir, library.ItemMetadata{ID: "e2e", Site: "bilibili", Kind: "video", Title: "t", Author: library.ItemAuthor{Mid: 1001, Name: "UP"},
+ Media: []library.MediaFile{{Role: "video", Path: "P01.mp4", Bytes: 5}}}); err != nil {
+ t.Fatal(err)
+ }
+ _ = b.Close()
+ }
+
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var logBuf syncBuffer
+ ctx, cancel := context.WithCancel(context.Background())
+ ready := make(chan string, 1)
+ done := make(chan error, 1)
+ stopped := false
+ t.Cleanup(func() {
+ if !stopped {
+ cancel()
+ <-done
+ }
+ })
+ go func() {
+ done <- Run(ctx, RunOptions{
+ DataDir: dataDir, Listener: ln, Backend: bili.options, LogMirror: &logBuf,
+ UploadEnv: append(os.Environ(), "TRACE_FAKE_RCLONE=1", "TRACE_FAKE_RCLONE_ROOT="+cloud, "TRACE_FAKE_RCLONE_LOG="+rlog),
+ Ready: func(addr string) { ready <- addr },
+ ExitTimeout: 10 * time.Second,
+ })
+ }()
+ var addr string
+ select {
+ case addr = <-ready:
+ case err := <-done:
+ stopped = true
+ t.Fatalf("Run returned early: %v", err)
+ case <-time.After(20 * time.Second):
+ t.Fatal("Run did not become ready")
+ }
+ conn := res.Conn
+ conn.URL = "https://" + addr
+ c, err := remote.NewClient(conn, appdirs.BuildInfo().Version)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer c.Close()
+ bg := context.Background()
+
+ snap := subscription.Snapshot{Format: subscription.SnapshotFormat, Version: subscription.SnapshotVersion,
+ Rules: []subscription.CacheRule{{ID: "r1", Name: "合成规则", FullCache: true}},
+ Subscriptions: []subscription.SnapshotSubscription{{ID: "s1", Name: "合成订阅", RuleID: "r1", Accounts: []subscription.SnapshotAccount{{Site: "bilibili", UID: "1001", Name: "UP"}}}}}
+ raw, _ := json.Marshal(snap)
+ info, err := c.PutSubscriptions(bg, raw)
+ if err != nil {
+ t.Fatalf("PutSubscriptions: %v", err)
+ }
+ if info.Hash != snap.Hash() || info.Subscriptions != 1 || info.Accounts != 1 {
+ t.Fatalf("synced info = %+v, want hash %s", info, snap.Hash())
+ }
+ if _, err := c.PushCredential(bg, "bilibili", remote.CredentialPush{Cookie: sentinelCookie()}); err != nil {
+ t.Fatalf("PushCredential: %v", err)
+ }
+
+ var st remote.Status
+ deadline := time.Now().Add(20 * time.Second)
+ for {
+ st, err = c.Status(bg)
+ if err != nil {
+ t.Fatalf("Status: %v", err)
+ }
+ gone := !exists(filepath.Join(cfg.ExportDir, "bilibili", "1001_UP", "videos", "video_e2e"))
+ if (gone && st.Upload.TodayFiles > 0) || time.Now().After(deadline) {
+ break
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+ if st.Upload.Mode != remote.UploadRclone || st.Upload.TodayFiles == 0 {
+ t.Fatalf("upload status = %+v, want the item uploaded", st.Upload)
+ }
+ if !exists(filepath.Join(cloud, "trace", "bilibili", "1001_UP", "videos", "video_e2e", "P01.mp4")) || exists(filepath.Join(cfg.ExportDir, "bilibili", "1001_UP", "videos", "video_e2e", "P01.mp4")) {
+ raw, _ := os.ReadFile(rlog)
+ t.Logf("rclone: %s", raw)
+ t.Fatal("the item was not moved to the cloud folder")
+ }
+ if len(st.Sites) == 0 || st.Sites[0].State != remote.SiteValid {
+ t.Fatalf("sites = %+v", st.Sites)
+ }
+ if len(st.Notes) == 0 {
+ t.Fatal("a rule with 全部缓存 must be noted as not run on the remote")
+ }
+ stRaw, _ := json.Marshal(st)
+
+ cancel()
+ select {
+ case err := <-done:
+ stopped = true
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ case <-time.After(30 * time.Second):
+ t.Fatal("Run did not stop after cancel")
+ }
+
+ secrets := []string{res.Conn.Token, sentinelSess, sentinelCSRF}
+ check := func(where string, data []byte) {
+ for _, s := range secrets {
+ if bytes.Contains(data, []byte(s)) {
+ t.Errorf("%s contains a secret %q", where, s[:8])
+ }
+ }
+ }
+ check("status", stRaw)
+ check("log mirror", []byte(logBuf.String()))
+ _ = filepath.Walk(root, func(p string, info os.FileInfo, err error) error {
+ if err != nil || info.IsDir() {
+ return nil
+ }
+ data, _ := os.ReadFile(p)
+ check(p, data)
+ return nil
+ })
+ if logBuf.String() == "" {
+ t.Fatal("the log mirror received nothing")
+ }
+}
+
+func exists(p string) bool { _, err := os.Stat(p); return err == nil }
+
+type syncBuffer struct {
+ mu sync.Mutex
+ b bytes.Buffer
+}
+
+func (s *syncBuffer) Write(p []byte) (int, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.b.Write(p)
+}
+
+func (s *syncBuffer) String() string {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.b.String()
+}
+
+func TestRateLimiterPrunesAndCapsTrackedIPs(t *testing.T) {
+ now := time.Date(2026, 11, 20, 0, 0, 0, 0, time.UTC)
+ s := New(Options{Service: &fakeService{}, Now: func() time.Time { return now }})
+ for i := 0; i < maxTrackedIPs+50; i++ {
+ s.recordFailure(fmt.Sprintf("10.%d.%d.%d", (i>>16)&255, (i>>8)&255, i&255), now)
+ }
+ s.mu.Lock()
+ gotLen := len(s.failures)
+ s.mu.Unlock()
+ if gotLen > maxTrackedIPs {
+ t.Fatalf("tracked failures = %d, want <= %d", gotLen, maxTrackedIPs)
+ }
+ // Advance past failWindow + pruneInterval and confirm expired entries are pruned.
+ now = now.Add(2 * time.Minute)
+ s.recordFailure("192.0.2.1", now)
+ s.mu.Lock()
+ afterPrune := len(s.failures)
+ s.mu.Unlock()
+ if afterPrune != 1 {
+ t.Fatalf("tracked failures after prune = %d, want 1", afterPrune)
+ }
+}
+
+func TestDiskErrorFailsClosedInStatusAndCacheGate(t *testing.T) {
+ failDisk := func() (uint64, uint64, error) { return 0, 0, os.ErrNotExist }
+ s := New(Options{Service: &fakeService{}, Disk: failDisk})
+ st := s.Status()
+ if !st.Disk.Warning || !st.Disk.Paused {
+ t.Fatalf("Status().Disk on error = %+v, want Warning=true Paused=true", st.Disk)
+ }
+ if err := CacheGate(failDisk)(); err == nil {
+ t.Fatal("CacheGate on disk error = nil, want non-nil pause error")
+ }
+}
+
+func TestInitValidatesBeforeCreatingDirs(t *testing.T) {
+ root := t.TempDir()
+ dataDir := filepath.Join(root, "data")
+ exportDir := filepath.Join(root, "export")
+ if _, err := Init(InitOptions{DataDir: dataDir, ExportDir: exportDir, Listen: ":notaport"}); err == nil {
+ t.Fatal("Init accepted non-numeric port")
+ }
+ if exists(dataDir) || exists(exportDir) {
+ t.Fatal("Init created directories despite invalid --listen")
+ }
+}
diff --git a/internal/service/account.go b/internal/service/account.go
index 9df583e..f033ea3 100644
--- a/internal/service/account.go
+++ b/internal/service/account.go
@@ -181,16 +181,12 @@ func (b *Backend) AccountFolders(ctx context.Context, siteID, kind string) ([]Ac
for i := 0; i < 5; i++ {
page, err := b.douyin.CollectFolders(ctx, cursor)
if err != nil {
- if i == 0 {
- return nil, b.accountFail(sid, kind, err)
- }
- b.accountFail(sid, kind, err)
- break
+ return nil, b.accountFail(sid, kind, err)
}
for _, f := range page.Folders {
out = append(out, AccountFolder{ID: f.ID, Title: f.Name, Count: f.Count})
}
- if !page.HasMore {
+ if !page.HasMore || page.NextCursor == "" || page.NextCursor == cursor {
break
}
cursor = page.NextCursor
@@ -397,7 +393,7 @@ func (b *Backend) douyinAccountPage(ctx context.Context, kind, folderID, raw str
it.BrowserURL = safeBrowserURL("https://www.douyin.com/video/" + w.ID)
} else {
it.Kind, it.CacheKey = AccountItemWork, card.CacheKey
- it.OpenURL = firstNonEmptyStr(safeBrowserURL(card.CanonicalURL), "https://www.douyin.com/video/"+w.ID)
+ it.OpenURL = firstNonEmpty(safeBrowserURL(card.CanonicalURL), "https://www.douyin.com/video/"+w.ID)
it.BrowserURL = it.OpenURL
}
out.Items = append(out.Items, it)
@@ -529,12 +525,3 @@ func firstLine(s string) string {
}
return s
}
-
-func firstNonEmptyStr(values ...string) string {
- for _, v := range values {
- if strings.TrimSpace(v) != "" {
- return v
- }
- }
- return ""
-}
diff --git a/internal/service/account_works.go b/internal/service/account_works.go
index 1facaf1..f05ff0a 100644
--- a/internal/service/account_works.go
+++ b/internal/service/account_works.go
@@ -103,7 +103,7 @@ type fullCacheCandidate struct {
// queue itself walks the works newest first, skips what is cached and caches
// the rest slowly. It returns the queue IDs it started.
func (b *Backend) startDueFullCacheSweeps(ctx context.Context, now time.Time) []string {
- if b.subs == nil || b.queue == nil || b.requireAnyLogin() != nil {
+ if b.profile == ProfileRemote || b.subs == nil || b.queue == nil || b.requireAnyLogin() != nil {
return nil
}
subs, err := b.subs.List()
diff --git a/internal/service/auth.go b/internal/service/auth.go
new file mode 100644
index 0000000..5d14ea7
--- /dev/null
+++ b/internal/service/auth.go
@@ -0,0 +1,436 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/chialecode/trace/internal/credential"
+ "github.com/chialecode/trace/internal/site"
+ "github.com/chialecode/trace/internal/site/bilibili"
+)
+
+// HasAnyLogin reports whether at least one supported site has an active credential.
+func (b *Backend) HasAnyLogin() bool {
+ return (b.cred != nil && b.cred.HasActiveCredential()) ||
+ (b.douyinCred != nil && b.douyinCred.HasActiveCredential())
+}
+
+func (b *Backend) requireAnyLogin() error {
+ if b.HasAnyLogin() {
+ return nil
+ }
+ return &site.Error{
+ Kind: site.ErrKindAuthRequired,
+ Message: "请先登录哔哩哔哩或抖音账号",
+ }
+}
+
+func (b *Backend) requireSiteLogin(siteID site.ID) error {
+ switch siteID {
+ case site.Bilibili:
+ if b.cred != nil && b.cred.HasActiveCredential() {
+ return nil
+ }
+ return &site.Error{
+ Site: site.Bilibili,
+ Kind: site.ErrKindAuthRequired,
+ Message: "请先登录哔哩哔哩账号",
+ }
+ case site.Douyin:
+ if b.douyinCred != nil && b.douyinCred.HasActiveCredential() {
+ return nil
+ }
+ return &site.Error{
+ Site: site.Douyin,
+ Kind: site.ErrKindAuthRequired,
+ Message: "请先在设置中粘贴 Cookie 登录抖音",
+ }
+ default:
+ return &site.Error{
+ Site: siteID,
+ Kind: site.ErrKindAuthRequired,
+ Message: "请先登录对应站点账号",
+ }
+ }
+}
+
+func normalizeSiteID(raw string) (site.ID, error) {
+ switch strings.ToLower(strings.TrimSpace(raw)) {
+ case "", string(site.Bilibili):
+ return site.Bilibili, nil
+ case string(site.Douyin):
+ return site.Douyin, nil
+ default:
+ return "", &site.Error{
+ Kind: site.ErrKindBadRequest,
+ Message: "不支持的站点标识: " + strings.TrimSpace(raw),
+ }
+ }
+}
+
+// AccountStatus returns the desensitized Bilibili account status (never exposing raw cookies or tokens).
+func (b *Backend) AccountStatus() credential.Status {
+ return b.cred.Status()
+}
+
+// Statuses returns desensitized credential status snapshots for all supported sites.
+func (b *Backend) Statuses() map[string]credential.Status {
+ if b.credMgr == nil {
+ return map[string]credential.Status{}
+ }
+ return b.credMgr.Statuses()
+}
+
+// StatusOf returns the desensitized credential status for a specific site ("bilibili" or "douyin").
+func (b *Backend) StatusOf(siteID string) credential.Status {
+ if b.credMgr == nil {
+ return credential.Status{}
+ }
+ return b.credMgr.Status(siteID)
+}
+
+// Renewal summarizes automatic session renewal availability and last-renewed state for siteID.
+func (b *Backend) Renewal(siteID string) RenewalStatus {
+ id, err := normalizeSiteID(siteID)
+ if err != nil {
+ return RenewalStatus{Site: strings.TrimSpace(siteID), Available: false, Reason: err.Error()}
+ }
+ if b.profile == ProfileRemote {
+ return RenewalStatus{Site: string(id), Available: false, Reason: "由本地续期"}
+ }
+ if id == site.Douyin {
+ return RenewalStatus{
+ Site: string(site.Douyin),
+ Available: false,
+ Reason: "不可用,粘贴的 Cookie 与浏览器共用会话;过期后请重新粘贴",
+ }
+ }
+ st := b.cred.Status()
+ if !st.LoggedIn {
+ return RenewalStatus{
+ Site: string(site.Bilibili),
+ Available: false,
+ Reason: "未登录",
+ }
+ }
+ if st.Source == "qr" && st.HasRefreshToken {
+ var lastErr string
+ if st.State == "refresh_failed" {
+ lastErr = st.Message
+ }
+ return RenewalStatus{
+ Site: string(site.Bilibili),
+ Available: true,
+ LastRenewedAt: st.LastRenewedAt,
+ LastError: lastErr,
+ }
+ }
+ return RenewalStatus{
+ Site: string(site.Bilibili),
+ Available: false,
+ Reason: "不可用:粘贴的 Cookie 与浏览器共用会话,续期会让浏览器那边掉线。过期后请重新粘贴,或改用扫码登录",
+ LastRenewedAt: st.LastRenewedAt,
+ }
+}
+
+// BootstrapAuth verifies existing credentials per-site on startup without cross-site interference:
+// - Logged-out sites are skipped with zero network requests.
+// - Expired credentials pause only that site's active tasks and recordings.
+// - Transient network or risk-control errors mark status "unknown" while keeping credentials usable.
+func (b *Backend) BootstrapAuth(ctx context.Context) (credential.Status, error) {
+ biliOut, biliErr := b.verifyBootstrapSite(
+ ctx,
+ site.Bilibili,
+ b.cred,
+ b.bili.VerifyCredential,
+ func(err error) bool { return bilibili.IsKind(err, bilibili.ErrKindAuthRequired) },
+ "哔哩哔哩登录已失效,任务已暂停",
+ "无法确认登录状态,请重试",
+ )
+ _, dyErr := b.verifyBootstrapSite(
+ ctx,
+ site.Douyin,
+ b.douyinCred,
+ b.douyin.VerifyCredential,
+ func(err error) bool { return site.IsKind(err, site.ErrKindAuthRequired) },
+ "抖音登录已失效,任务已暂停",
+ "无法确认抖音登录状态,请稍后重试",
+ )
+ return biliOut, errors.Join(biliErr, dyErr)
+}
+
+func (b *Backend) verifyBootstrapSite(
+ ctx context.Context,
+ siteID site.ID,
+ store *credential.Store,
+ verify func(context.Context) (credential.Status, error),
+ isAuthErr func(error) bool,
+ expiredMsg, unknownMsg string,
+) (credential.Status, error) {
+ st := store.Status()
+ if st.State == "logged_out" || !st.LoggedIn {
+ return st, nil
+ }
+ verified, err := verify(ctx)
+ if err != nil && isAuthErr(err) {
+ b.pauseSiteActiveWork(siteID, "auth_required", expiredMsg)
+ } else if err != nil {
+ var stateErr error
+ verified, stateErr = store.MarkState("unknown", unknownMsg)
+ err = errors.Join(err, stateErr)
+ if stateErr != nil {
+ verified = store.Status()
+ }
+ } else if !verified.LoggedIn {
+ b.pauseSiteActiveWork(siteID, "auth_required", expiredMsg)
+ }
+ b.events.PublishSite(EventAccountChanged, string(siteID), verified.State)
+ return verified, err
+}
+
+// VerifyAccount queries Bilibili /x/web-interface/nav to refresh account profile and login state.
+func (b *Backend) VerifyAccount(ctx context.Context) (credential.Status, error) {
+ st, err := b.bili.VerifyCredential(ctx)
+ if err != nil && bilibili.IsKind(err, bilibili.ErrKindAuthRequired) {
+ b.pauseSiteActiveWork(site.Bilibili, "auth_required", "哔哩哔哩登录已失效,任务已暂停")
+ }
+ b.events.PublishSite(EventAccountChanged, string(site.Bilibili), st.State)
+ return st, err
+}
+
+// VerifySiteAccount verifies the stored credential for the specified site ("bilibili" or "douyin").
+func (b *Backend) VerifySiteAccount(ctx context.Context, siteID string) (credential.Status, error) {
+ id, err := normalizeSiteID(siteID)
+ if err != nil {
+ return credential.Status{}, err
+ }
+ if id == site.Bilibili {
+ return b.VerifyAccount(ctx)
+ }
+ st, vErr := b.douyin.VerifyCredential(ctx)
+ if vErr != nil && site.IsKind(vErr, site.ErrKindAuthRequired) {
+ b.pauseSiteActiveWork(site.Douyin, "auth_required", "抖音登录已失效,任务已暂停")
+ }
+ b.events.PublishSite(EventAccountChanged, string(site.Douyin), st.State)
+ return st, vErr
+}
+
+// StartQRLogin starts a new QR code login session and invalidates any previous QR session.
+func (b *Backend) StartQRLogin(ctx context.Context) (bilibili.QRSession, error) {
+ sess, err := b.bili.StartQR(ctx)
+ if err != nil {
+ b.logError("StartQRLogin", err)
+ return bilibili.QRSession{}, err
+ }
+ b.logInfo("QR login started: flow=" + sess.FlowID)
+ return sess, nil
+}
+
+// PollQRLogin polls the status of the active QR login flow.
+func (b *Backend) PollQRLogin(ctx context.Context, flowID string) (bilibili.QRPollResult, error) {
+ prevAuthPaused := b.snapshotAuthPausedQueueIDs(site.Bilibili)
+ prev := b.cred.Status()
+ res, err := b.bili.PollQR(ctx, flowID)
+ if err != nil {
+ b.logError("PollQRLogin", err)
+ return bilibili.QRPollResult{}, err
+ }
+ if res.State == "confirmed" {
+ b.bili.ClearCaches()
+ select {
+ case b.renewalWake <- struct{}{}:
+ default:
+ }
+ switched := prev.LoggedIn && prev.Mid != 0 && prev.Mid != res.Account.Mid
+ b.logInfo(fmt.Sprintf("QR login confirmed: mid=%d", res.Account.Mid))
+ b.finishSiteLogin(site.Bilibili, true, "logged_in", switched, prevAuthPaused)
+ }
+ return res, nil
+}
+
+// CancelQRLogin cancels the QR login flow so late responses never write credentials.
+func (b *Backend) CancelQRLogin(flowID string) {
+ b.bili.CancelQR(flowID)
+ b.logInfo("QR login canceled: flow=" + flowID)
+}
+
+// ImportCookie validates a manual Bilibili Cookie string against /x/web-interface/nav first,
+// and only persists the credential if verification succeeds.
+func (b *Backend) ImportCookie(ctx context.Context, rawCookie, rawRefreshToken string) (credential.Status, error) {
+ prevAuthPaused := b.snapshotAuthPausedQueueIDs(site.Bilibili)
+ prev := b.cred.Status()
+ st, err := b.bili.LoginWithCookie(ctx, rawCookie, rawRefreshToken)
+ if err != nil {
+ b.logError("ImportCookie", err)
+ return b.cred.Status(), err
+ }
+ // Note: bilibili.Client.LoginWithCookie already invokes SetAccountReplacingHandler
+ // when replacing a different logged-in account, so we do not pause a second time here.
+ switched := prev.LoggedIn && prev.Mid != 0 && prev.Mid != st.Mid
+ b.logInfo(fmt.Sprintf("manual cookie imported: state=%s mid=%d", st.State, st.Mid))
+ b.finishSiteLogin(site.Bilibili, st.LoggedIn, st.State, switched, prevAuthPaused)
+ return st, nil
+}
+
+// LoginWithCookie validates and imports a pasted Cookie for the target site ("bilibili" or "douyin").
+func (b *Backend) LoginWithCookie(ctx context.Context, siteID, rawCookie, rawRefreshToken string) (credential.Status, error) {
+ id, err := normalizeSiteID(siteID)
+ if err != nil {
+ return credential.Status{}, err
+ }
+ if id == site.Bilibili {
+ return b.ImportCookie(ctx, rawCookie, rawRefreshToken)
+ }
+ prevAuthPaused := b.snapshotAuthPausedQueueIDs(site.Douyin)
+ prev := b.douyinCred.Status()
+ st, lErr := b.douyin.LoginWithCookie(ctx, rawCookie)
+ if lErr != nil {
+ b.logError("LoginWithCookie.Douyin", lErr)
+ return b.douyinCred.Status(), lErr
+ }
+ switched := prev.LoggedIn && prev.SecUID != "" && prev.SecUID != st.SecUID
+ if switched {
+ b.pauseSiteActiveWork(site.Douyin, "auth_required", "抖音登录账号已变更,任务已暂停")
+ }
+ b.logInfo(fmt.Sprintf("douyin cookie imported: state=%s uid=%s", st.State, firstNonEmpty(st.UniqueID, st.UID)))
+ b.finishSiteLogin(site.Douyin, st.LoggedIn, st.State, switched, prevAuthPaused)
+ return st, nil
+}
+
+func (b *Backend) finishSiteLogin(siteID site.ID, loggedIn bool, state string, switched bool, prevAuthPaused []string) {
+ if loggedIn {
+ if switched {
+ b.resumeAuthPausedQueueIDs(siteID, prevAuthPaused)
+ } else if b.queue != nil {
+ b.queue.resumeAuthPausedForSite(siteID)
+ }
+ }
+ b.events.PublishSite(EventAccountChanged, string(siteID), state)
+ if loggedIn {
+ b.afterLocalLogin(siteID)
+ }
+}
+
+// RefreshCookie runs the 5-step Bilibili Cookie renewal flow (or resumes confirmation if pending).
+func (b *Backend) RefreshCookie(ctx context.Context) (credential.Status, error) {
+ if err := b.requireDesktop(); err != nil {
+ return b.cred.Status(), err
+ }
+ before := b.cred.CookieHeader()
+ st, err := b.bili.CheckAndRefreshCookie(ctx)
+ if err != nil {
+ b.logError("RefreshCookie", err)
+ } else if st.LoggedIn && b.queue != nil {
+ b.queue.resumeAuthPausedForSite(site.Bilibili)
+ }
+ if err == nil && st.LoggedIn && b.cred.CookieHeader() != before {
+ // Renewal replaced the Cookie; the old one stops working, so the
+ // remote gets the new one (DEC-062 ③).
+ b.afterLocalLogin(site.Bilibili)
+ }
+ b.events.PublishSite(EventAccountChanged, string(site.Bilibili), st.State)
+ return st, err
+}
+
+// Logout pauses Bilibili active tasks and live recordings, cancels any active QR login flow, and clears Bilibili credentials.
+func (b *Backend) Logout() (credential.Status, error) {
+ b.pauseSiteActiveWork(site.Bilibili, "auth_required", "已退出哔哩哔哩登录,任务已暂停")
+ err := b.bili.LogoutCredential()
+ st := b.cred.Status()
+ if err != nil {
+ b.logError("Logout", err)
+ } else {
+ b.logInfo("bilibili account logged out and credentials cleared")
+ }
+ b.events.PublishSite(EventAccountChanged, string(site.Bilibili), st.State)
+ return st, err
+}
+
+// LogoutSite pauses active work belonging ONLY to siteID and clears that site's stored credential.
+func (b *Backend) LogoutSite(siteID string) (credential.Status, error) {
+ id, err := normalizeSiteID(siteID)
+ if err != nil {
+ return credential.Status{}, err
+ }
+ if id == site.Bilibili {
+ return b.Logout()
+ }
+ b.pauseSiteActiveWork(site.Douyin, "auth_required", "已退出抖音登录,任务已暂停")
+ lErr := b.douyin.LogoutCredential()
+ st := b.douyinCred.Status()
+ if lErr != nil {
+ b.logError("LogoutSite.Douyin", lErr)
+ } else {
+ b.logInfo("douyin account logged out and credentials cleared")
+ }
+ b.events.PublishSite(EventAccountChanged, string(site.Douyin), st.State)
+ return st, lErr
+}
+
+func (b *Backend) runRenewalLoop(ctx context.Context) {
+ defer b.bgWg.Done()
+ // Wait 1 minute after startup before the first automatic renewal check.
+ initialTimer := time.NewTimer(time.Minute)
+ select {
+ case <-ctx.Done():
+ initialTimer.Stop()
+ return
+ case <-b.renewalWake:
+ initialTimer.Stop()
+ // Wait 1 minute after QR login confirmation
+ t2 := time.NewTimer(time.Minute)
+ select {
+ case <-ctx.Done():
+ t2.Stop()
+ return
+ case <-t2.C:
+ }
+ case <-initialTimer.C:
+ }
+
+ for {
+ if ctx.Err() != nil {
+ return
+ }
+ b.tryScheduledRenewal(ctx)
+
+ timer := time.NewTimer(12 * time.Hour)
+ select {
+ case <-ctx.Done():
+ timer.Stop()
+ return
+ case <-b.renewalWake:
+ timer.Stop()
+ t2 := time.NewTimer(time.Minute)
+ select {
+ case <-ctx.Done():
+ t2.Stop()
+ return
+ case <-t2.C:
+ }
+ case <-timer.C:
+ }
+ }
+}
+
+func (b *Backend) tryScheduledRenewal(ctx context.Context) {
+ st := b.cred.Status()
+ if !st.LoggedIn {
+ return
+ }
+ if st.Source != "qr" {
+ return
+ }
+ if b.subs != nil {
+ if inBackoff, _ := b.subs.IsInBackoff(); inBackoff {
+ return
+ }
+ if !b.subs.CanUseQuotaTokens(8) {
+ return
+ }
+ }
+ _, _ = b.RefreshCookie(bilibili.WithAutomaticRequests(ctx, "renewal"))
+}
diff --git a/internal/service/avatars.go b/internal/service/avatars.go
index e63d515..e139b3b 100644
--- a/internal/service/avatars.go
+++ b/internal/service/avatars.go
@@ -8,28 +8,23 @@ import (
"path/filepath"
"regexp"
"strings"
- "sync"
"time"
"github.com/chialecode/trace/internal/site"
+ "github.com/chialecode/trace/internal/storage"
"github.com/chialecode/trace/internal/subscription"
)
// Subscribed accounts' avatars, kept as small local PNGs under
// /avatars/. Douyin avatar URLs carry query strings (some signed and
-// expiring), so subscriptions.json never stores them and the avatar was lost
-// at the next start; a Bilibili subscription made from a user page had no
-// avatar URL at all until its first check (2026-11-15 feedback). Both sites
-// now keep a local copy, which the interface prefers. The file name is a hash
-// of site and account id; no URL is written. Only files matching avatarFileRe
-// are ever removed.
+// expiring), so subscriptions.json never stores them; both sites keep a local
+// copy preferred by the UI. The file name is a hash of site and account id; no
+// URL is written. Only files matching avatarFileRe are ever removed.
const avatarRefreshAge = 7 * 24 * time.Hour
var avatarFileRe = regexp.MustCompile(`^(bilibili|douyin)-[0-9a-f]{20}\.png$`)
-var avatarInflight sync.Map // file name -> struct{}
-
func (b *Backend) avatarDir() string {
if b.loc.DataDir == "" {
return ""
@@ -60,59 +55,66 @@ func (b *Backend) AccountAvatarPath(siteID, uid string) string {
return path
}
-// rememberAccountAvatar keeps a local copy of a subscribed account's avatar
-// in the background when it is missing or older than a week.
-func (b *Backend) rememberAccountAvatar(siteID, uid, rawFace string) {
+// rememberAvatar fetches and atomically saves a local PNG avatar in the background
+// when it is missing or older than avatarRefreshAge, enforcing INV-07 per-site login
+// before issuing any CDN request.
+func (b *Backend) rememberAvatar(siteID, uid, rawFace string, defaultBilibili bool, onSaved func(normSite string)) {
normSite := strings.ToLower(strings.TrimSpace(siteID))
- if normSite == "" {
+ if normSite == "" && defaultBilibili {
normSite = string(site.Bilibili)
}
- if strings.TrimSpace(rawFace) == "" {
+ if (normSite != string(site.Bilibili) && normSite != string(site.Douyin)) || strings.TrimSpace(rawFace) == "" {
+ return
+ }
+ sid := site.ID(normSite)
+ if b.requireSiteLogin(sid) != nil {
return
}
name, dir := avatarFileName(normSite, uid), b.avatarDir()
if name == "" || dir == "" {
return
}
- if (normSite == string(site.Douyin) && b.douyin == nil) || (normSite == string(site.Bilibili) && b.bili == nil) {
+ if (sid == site.Douyin && b.douyin == nil) || (sid == site.Bilibili && b.bili == nil) {
return
}
path := filepath.Join(dir, name)
if info, err := os.Stat(path); err == nil && time.Since(info.ModTime()) < avatarRefreshAge {
return
}
- if _, busy := avatarInflight.LoadOrStore(name, struct{}{}); busy {
+ if _, busy := b.avatarInflight.LoadOrStore(name, struct{}{}); busy {
return
}
- ctx := b.bgCtx
- if ctx == nil {
- ctx = context.Background()
- }
- b.bgWg.Add(1)
- go func() {
- defer b.bgWg.Done()
- defer avatarInflight.Delete(name)
+ started := b.goBg(func(ctx context.Context) {
+ defer b.avatarInflight.Delete(name)
fetchCtx, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
- thumb := b.fetchHistoryThumbForSite(fetchCtx, site.ID(normSite), "avatar", rawFace)
+ thumb := b.fetchHistoryThumbForSite(fetchCtx, sid, "avatar", rawFace)
if len(thumb.Data) == 0 || fetchCtx.Err() != nil {
return
}
if err := os.MkdirAll(dir, 0o700); err != nil {
return
}
- tmp, err := os.CreateTemp(dir, ".avatar-*.tmp")
- if err != nil {
+ if err := storage.WriteFileAtomic(path, thumb.Data, 0o600); err != nil {
return
}
- _, werr := tmp.Write(thumb.Data)
- cerr := tmp.Close()
- if werr != nil || cerr != nil || os.Rename(tmp.Name(), path) != nil {
- _ = os.Remove(tmp.Name())
- return
+ if onSaved != nil {
+ onSaved(normSite)
}
- b.events.Publish(EventSubscriptionChecked, "avatar")
- }()
+ })
+ if !started {
+ b.avatarInflight.Delete(name)
+ }
+}
+
+// rememberAccountAvatar keeps a local copy of a subscribed account's avatar
+// in the background when it is missing or older than a week.
+func (b *Backend) rememberAccountAvatar(siteID, uid, rawFace string) {
+ b.rememberAvatar(siteID, uid, rawFace, true, func(string) {
+ if b.events != nil {
+ b.events.Publish(EventSubscriptionChecked, "avatar")
+ }
+ })
}
func (b *Backend) rememberAccountAvatars(accounts []subscription.AccountRef) {
@@ -124,56 +126,11 @@ func (b *Backend) rememberAccountAvatars(accounts []subscription.AccountRef) {
// rememberQueueAvatar caches a local PNG copy of a queue account's avatar (for Bilibili or Douyin)
// so cache-queue.json never needs to store remote avatar URLs or query strings.
func (b *Backend) rememberQueueAvatar(siteID, uid, rawFace string) {
- normSite := strings.ToLower(strings.TrimSpace(siteID))
- if (normSite != string(site.Bilibili) && normSite != string(site.Douyin)) || strings.TrimSpace(rawFace) == "" {
- return
- }
- name, dir := avatarFileName(normSite, uid), b.avatarDir()
- if name == "" || dir == "" {
- return
- }
- if normSite == string(site.Douyin) && b.douyin == nil {
- return
- }
- if normSite == string(site.Bilibili) && b.bili == nil {
- return
- }
- path := filepath.Join(dir, name)
- if info, err := os.Stat(path); err == nil && time.Since(info.ModTime()) < avatarRefreshAge {
- return
- }
- if _, busy := avatarInflight.LoadOrStore(name, struct{}{}); busy {
- return
- }
- ctx := b.bgCtx
- if ctx == nil {
- ctx = context.Background()
- }
- b.bgWg.Add(1)
- go func() {
- defer b.bgWg.Done()
- defer avatarInflight.Delete(name)
- fetchCtx, cancel := context.WithTimeout(ctx, 20*time.Second)
- defer cancel()
- thumb := b.fetchHistoryThumbForSite(fetchCtx, site.ID(normSite), "avatar", rawFace)
- if len(thumb.Data) == 0 || fetchCtx.Err() != nil {
- return
- }
- if err := os.MkdirAll(dir, 0o700); err != nil {
- return
- }
- tmp, err := os.CreateTemp(dir, ".avatar-*.tmp")
- if err != nil {
- return
- }
- _, werr := tmp.Write(thumb.Data)
- cerr := tmp.Close()
- if werr != nil || cerr != nil || os.Rename(tmp.Name(), path) != nil {
- _ = os.Remove(tmp.Name())
- return
+ b.rememberAvatar(siteID, uid, rawFace, false, func(normSite string) {
+ if b.events != nil {
+ b.events.PublishSite(EventCacheQueueUpdated, normSite, "avatar")
}
- b.events.PublishSite(EventCacheQueueUpdated, normSite, "avatar")
- }()
+ })
}
// pruneAccountAvatars removes local avatars of accounts no subscription or cache queue task uses.
diff --git a/internal/service/backend.go b/internal/service/backend.go
index 8d9e889..3f7ec54 100644
--- a/internal/service/backend.go
+++ b/internal/service/backend.go
@@ -1,28 +1,19 @@
package service
import (
- "bytes"
"context"
"database/sql"
"errors"
"fmt"
- "image"
- _ "image/gif"
- _ "image/jpeg"
- "image/png"
"io"
- "net/url"
"os"
"path/filepath"
- "regexp"
+ "runtime"
"strconv"
"strings"
"sync"
"time"
- "golang.org/x/image/draw"
- _ "golang.org/x/image/webp"
-
"github.com/chialecode/trace/internal/appdirs"
"github.com/chialecode/trace/internal/credential"
"github.com/chialecode/trace/internal/download"
@@ -38,296 +29,6 @@ import (
"github.com/chialecode/trace/internal/update"
)
-// Options configures the TRACE Backend service.
-type Options struct {
- Locations appdirs.Locations
- BilibiliOpts bilibili.ClientOptions
- DouyinOpts douyin.ClientOptions
- Desktop Desktop
- DisableBgWorkers bool
- CacheQueueClock CacheQueueClock
- CacheQueueRand CacheQueueRand
- CacheQueuePacing *CacheQueuePacing
- InstalledDevVersion func() string
-}
-
-// OpenLinkResult contains the resolved target and fetched detail payload for UI navigation.
-type OpenLinkResult struct {
- Site string `json:"site,omitempty"`
- SiteTarget *site.ResolveTarget `json:"siteTarget,omitempty"`
- Target bilibili.ResolveTarget `json:"target"`
- Video *bilibili.VideoDetail `json:"video,omitempty"`
- User *bilibili.UserSpace `json:"user,omitempty"`
- UserVideos *bilibili.UserVideosPage `json:"userVideos,omitempty"`
- UserDynamicsError string `json:"userDynamicsError,omitempty"`
- UserVideosError string `json:"userVideosError,omitempty"`
- UserDynamics *bilibili.UserDynamicsPage `json:"userDynamics,omitempty"`
- Dynamic *bilibili.DynamicItem `json:"dynamic,omitempty"`
- LiveRoom *live.RoomState `json:"liveRoom,omitempty"`
- DouyinWork *DouyinWorkView `json:"douyinWork,omitempty"`
- DouyinUser *DouyinUserView `json:"douyinUser,omitempty"`
- DouyinUserWorks *DouyinUserWorksPage `json:"douyinUserWorks,omitempty"`
- DouyinUserWorksError string `json:"douyinUserWorksError,omitempty"`
- DouyinLive *DouyinLiveView `json:"douyinLive,omitempty"`
- CachedItem *library.ItemMetadata `json:"cachedItem,omitempty"`
- // HistoryThumbs names the images of the recent-parse entry. OpenLink
- // records the entry without waiting for them; FetchHistoryThumbs adds
- // them afterwards, so opening a link waits only for its metadata.
- HistoryThumbs *HistoryThumbJob `json:"-"`
-}
-
-// HistoryThumbJob is the deferred thumbnail work of one recent-parse entry.
-type HistoryThumbJob struct {
- Site string
- Kind string
- ID string
- AvatarURL string
- CoverURL string
-}
-
-// Diagnostics provides a sanitized runtime status snapshot for the Settings/Diagnostics view and smoke tests.
-type Diagnostics struct {
- Version string `json:"version"`
- Commit string `json:"commit,omitempty"`
- BuildTime string `json:"buildTime,omitempty"`
- AppName string `json:"appName"`
- DisplayName string `json:"displayName"`
- Channel string `json:"channel"`
- Mode string `json:"mode"`
- DataDir string `json:"dataDir"`
- CacheDir string `json:"cacheDir"`
- LogsDir string `json:"logsDir"`
- Account credential.Status `json:"account"`
- Accounts map[string]credential.Status `json:"accounts,omitempty"`
- LibraryCount int `json:"libraryCount"`
- TaskCount int `json:"taskCount"`
- SubscriptionCnt int `json:"subscriptionCount"`
- LiveRoomCount int `json:"liveRoomCount"`
- IndexStatus string `json:"indexStatus,omitempty"`
- SubscriptionCheckStatus string `json:"subscriptionCheckStatus,omitempty"`
- AutoCacheStatus string `json:"autoCacheStatus,omitempty"`
- LiveRecordStatus string `json:"liveRecordStatus,omitempty"`
- CorruptRecovered []string `json:"corruptRecovered,omitempty"`
- RecentEvents []Event `json:"recentEvents,omitempty"`
-}
-
-// AuthService defines authentication and renewal operations across supported sites.
-type AuthService interface {
- HasAnyLogin() bool
- Statuses() map[string]credential.Status
- StatusOf(siteID string) credential.Status
- Renewal(siteID string) RenewalStatus
- VerifySiteAccount(ctx context.Context, siteID string) (credential.Status, error)
- LoginWithCookie(ctx context.Context, siteID, rawCookie, rawRefreshToken string) (credential.Status, error)
- LogoutSite(siteID string) (credential.Status, error)
- AccountStatus() credential.Status
- BootstrapAuth(ctx context.Context) (credential.Status, error)
- VerifyAccount(ctx context.Context) (credential.Status, error)
- StartQRLogin(ctx context.Context) (bilibili.QRSession, error)
- PollQRLogin(ctx context.Context, flowID string) (bilibili.QRPollResult, error)
- CancelQRLogin(flowID string)
- ImportCookie(ctx context.Context, rawCookie, rawRefreshToken string) (credential.Status, error)
- RefreshCookie(ctx context.Context) (credential.Status, error)
- Logout() (credential.Status, error)
-}
-
-// ParseService defines link resolution and creator/video/note browsing operations.
-type ParseService interface {
- Resolve(ctx context.Context, rawInput string) (site.ResolveTarget, error)
- OpenLink(ctx context.Context, rawInput string) (*OpenLinkResult, error)
- DouyinWork(ctx context.Context, awemeID string) (*DouyinWorkView, error)
- DouyinUser(ctx context.Context, secUID string) (*DouyinUserView, error)
- DouyinUserWorks(ctx context.Context, secUID, cursor string) (*DouyinUserWorksPage, error)
- DouyinLive(ctx context.Context, webRID string) (*DouyinLiveView, error)
- StagePreviewMedia(ctx context.Context, siteID, rawURL, ext string) (string, error)
- FetchHistoryThumbs(ctx context.Context, job HistoryThumbJob) error
- FetchImage(ctx context.Context, rawURL string) ([]byte, error)
- UserDynamicsPage(ctx context.Context, mid int64, offset string) (bilibili.UserDynamicsPage, error)
- UserVideosPage(ctx context.Context, mid int64, page int) (bilibili.UserVideosPage, error)
-}
-
-// HistoryService defines recent parse history operations.
-type HistoryService interface {
- ListHistory() []storage.HistoryEntry
- ClearHistory() error
- RemoveHistory(kind, id string) error
- RemoveHistoryForSite(siteID, kind, id string) error
- HistoryThumbPath(name string) (string, error)
-}
-
-// 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)
- EnqueueDynamicCache(ctx context.Context, req download.DynamicEnqueueRequest) (download.Task, error)
- CacheDouyinWork(ctx context.Context, awemeID string) (download.Task, error)
- ListCacheQueue() []CacheQueueTask
- FindCacheQueueTask(siteID, user, list string) (CacheQueueTask, bool)
- EnqueueCacheQueue(ctx context.Context, req CacheQueueRequest) (CacheQueueTask, error)
- PauseCacheQueue(id string) (CacheQueueTask, error)
- ResumeCacheQueue(id string) (CacheQueueTask, error)
- CancelCacheQueue(id string) (CacheQueueTask, error)
- // RemoveCacheQueue deletes a finished cache queue task from the list;
- // RemoveFinishedCacheQueues deletes all of them. Cached items stay.
- RemoveCacheQueue(id string) error
- RemoveFinishedCacheQueues() (int, error)
- CacheSupplement(ctx context.Context, bvid string) (download.Task, error)
- Upgrade(ctx context.Context, key string) (download.Task, error)
- ListDownloadTasks() ([]download.Task, error)
- TaskDetail(taskID string) (download.TaskDetail, bool, error)
- PauseTask(taskID string) (download.Task, error)
- ResumeTask(taskID string) (download.Task, error)
- RetryTask(taskID string) (download.Task, error)
- CancelTask(taskID string) (download.Task, error)
- RemoveTask(taskID string) error
- RemoveFinishedTasks() (int, error)
- States(keys []string) map[string]library.DotState
- UpgradeCandidates(limit int) ([]library.ItemMetadata, error)
- CheckUpgradeKeys(ctx context.Context, keys []string, force bool) ([]library.ItemMetadata, error)
- CheckQualityUpgrade(ctx context.Context) ([]library.ItemMetadata, error)
-}
-
-// FeedService defines home feed pagination and anchor persistence operations.
-type FeedService interface {
- QueryFeed(filter library.FeedFilter) ([]library.FeedEntry, error)
- FeedPage(req library.FeedPageRequest) (library.FeedPageResult, error)
- Anchor() uistate.FeedAnchor
- SaveAnchor(anchor uistate.FeedAnchor) error
- NewerCount(anchor uistate.FeedAnchor) (int, error)
-}
-
-// LibraryService defines local media library, safe deletion, and whitelist path operations.
-type LibraryService interface {
- LibraryStatistics() (library.Statistics, error)
- ListLibraryItems(filter library.FeedFilter) ([]library.ItemMetadata, error)
- GetLibraryItem(keyOrID string) (library.ItemMetadata, bool, error)
- MediaPath(key, relPath string) (string, error)
- PlanDelete(key string) (library.DeletePlan, error)
- Delete(key string) error
- DeleteLibraryItem(itemKey string, deleteFiles bool) error
- RebuildLibraryIndex() (library.RebuildReport, error)
- // RefreshLibrary rescans the library folders for files deleted or changed
- // outside TRACE (presence and size, no hashing) and reports what changed.
- RefreshLibrary() (library.RebuildReport, error)
- AddLibraryRoot(selectedDir string) (library.AddRootReport, error)
- MigrateCacheDir(newDir string, moveExisting bool) (library.RebuildReport, error)
- OpenItemFolder(itemKey string) error
-}
-
-// SettingsService defines settings, UI state, and directory management operations.
-type SettingsService interface {
- Locations() appdirs.Locations
- GetSettings() settings.Settings
- UpdateSettings(next settings.Settings) (settings.Settings, error)
- GetUIState() uistate.State
- UpdateUIState(next uistate.State) (uistate.State, error)
- // MutateUIState changes ui-state.json under its lock, so a write from
- // another goroutine (the updater) between reading and writing is kept.
- MutateUIState(fn func(*uistate.State)) (uistate.State, error)
- GetUpdateHistory() update.History
- RecordUpdateCheck(rec update.CheckRecord) error
- RecordAppUpdate(rec update.UpdateRecord) error
- InstalledDevVersion() string
- OpenDataFolder(target string) error
-}
-
-// SubscriptionService defines multi-account subscription CRUD and binding operations.
-type SubscriptionService interface {
- ListSubscriptions() ([]subscription.Subscription, error)
- UpsertSubscription(sub subscription.Subscription) (subscription.Subscription, error)
- CreateSubscription(name, note string, accounts []subscription.AccountRef, rules subscription.SubRules) (subscription.Subscription, error)
- LinkSubscriptionAccount(subID, site, uid, name, face string) (subscription.Subscription, error)
- LinkSubscriptionAccountRef(subID string, acct subscription.AccountRef) (subscription.Subscription, error)
- UnlinkSubscriptionAccount(subID, site, uid string) (subscription.Subscription, error)
- MoveSubscriptionAccount(site, uid, toSubID string) (subscription.Subscription, error)
- SetSubscriptionRules(subID string, rules subscription.SubRules) (subscription.Subscription, error)
- // Shared cache rules: subscriptions choose one by ID.
- ListCacheRules() []subscription.CacheRule
- SubscriptionAccountWorks() map[string]AccountWorks
- SaveCacheRule(rule subscription.CacheRule) (subscription.CacheRule, error)
- DeleteCacheRule(id string) error
- SetSubscriptionRule(subID, ruleID string) (subscription.Subscription, error)
- SetSubscriptionsRule(ruleID string, subIDs []string) error
- PreviewAccount(ctx context.Context, input string) (subscription.AccountRef, *subscription.Subscription, error)
- OwnerOfAccount(site, uid string) (subscription.Subscription, bool)
- // AccountAvatarPath is the local copy of a subscribed account's avatar, or "".
- AccountAvatarPath(site, uid string) string
- DeleteSubscription(subIDOrMid string) error
- ExportOPML(path string) error
- ImportOPML(path string) (int, error)
-}
-
-// UpdateService defines subscription update checking, listing, and scheduler diagnostics.
-type UpdateService interface {
- ListSubscriptionUpdatesPage(subID string, limit, offset int) ([]subscription.UpdateItem, error)
- ListSubscriptionUpdates(subID string) ([]subscription.UpdateItem, error)
- CheckSubscriptionsNow(ctx context.Context, targetMid int64) (subscription.CheckSummary, error)
- CheckSubscription(ctx context.Context, subID string) (subscription.CheckSummary, error)
- CheckAccount(ctx context.Context, subID, siteName, uid string) (subscription.CheckSummary, error)
- CancelSubscriptionCheck()
- SchedulerStatuses() map[string]SiteSchedulerStatus
- // CheckPlan is Tasks › 检查计划: each account's last and next checks.
- CheckPlan() []AccountCheckRow
-}
-
-// FollowingService defines read-only following group and creator import operations.
-type FollowingService interface {
- RelationTags(ctx context.Context) ([]bilibili.RelationTag, error)
- RelationFollowings(ctx context.Context, tagID int64, pn, ps int) ([]bilibili.FollowingUser, error)
- ImportCreators(users []bilibili.FollowingUser, scope, autoCache string, liveNotify, liveAutoRecord bool) (int, error)
-}
-
-// LiveService defines live status polling and stream recording operations across sites.
-type LiveService interface {
- ListLiveRooms() []live.RoomState
- ListLiveAccounts() []LiveAccountState
- LiveStatus(ctx context.Context, uids []int64) ([]live.RoomState, error)
- LiveStatuses(ctx context.Context, accountKeys []string) ([]LiveAccountState, error)
- PollLiveNow(ctx context.Context) ([]live.RoomState, error)
- OpenLiveRoomInBrowser(roomID int64) error
- OpenLiveInBrowser(siteID, roomOrWebRID string) error
- StartLiveRecording(ctx context.Context, roomID int64) (live.RoomState, error)
- StartLiveRecordingByAccount(ctx context.Context, accountKey string) (LiveAccountState, error)
- StartLiveRecordingByRoom(ctx context.Context, siteID, roomOrWebRID string) (LiveAccountState, error)
- StopLiveRecording(roomID int64) (live.RoomState, error)
- StopLiveRecordingByKey(recKey string) (LiveAccountState, error)
- // ClearLiveIncidents deletes the incident records of a finished live
- // session; the recording itself is kept.
- ClearLiveIncidents(itemKey, siteID, roomID, uid string) error
- LiveRecordingPreview(recKey string) (LiveRecordingPreviewInfo, bool)
-}
-
-// AppService defines application lifecycle, event subscription, and diagnostics operations.
-type AppService interface {
- Close() error
- SubscribeEvents(fn func(Event)) func()
- Desktop() Desktop
- DiagnosticsSnapshot() Diagnostics
- RecentLogs(maxLines int) ([]string, error)
- // LogUserError records an error the UI showed to the user, so every
- // visible error also appears in the run log.
- LogUserError(err error)
- PauseAllActiveWork()
-}
-
-// BackendAPI composes all TRACE domain service interfaces for the UI layer.
-type BackendAPI interface {
- AuthService
- ParseService
- HistoryService
- CacheService
- FeedService
- LibraryService
- SettingsService
- SubscriptionService
- UpdateService
- FollowingService
- AccountService
- LiveService
- AppService
-}
-
-var _ BackendAPI = (*Backend)(nil)
-
// Backend coordinates all TRACE domain packages without importing any UI framework.
type Backend struct {
loc appdirs.Locations
@@ -354,16 +55,28 @@ type Backend struct {
bgCtx context.Context
bgCancel context.CancelFunc
renewalWake chan struct{}
+ bgMu sync.Mutex
+ bgClosing bool
bgWg sync.WaitGroup
logMu sync.Mutex
lastUserError string
lastUserErrorAt time.Time
settingsMu sync.Mutex
+ syncStateMu sync.Mutex
+ avatarInflight sync.Map
logPath string
previewDir string
corruptFiles []string
updateHistory *update.HistoryStore
installedDevVersion func() string
+ profile Profile
+ logMirror io.Writer
+ recentErrors []RecentError
+ startedAt time.Time
+ remote *remoteLink
+ cacheGate func() error
+ transferOnce sync.Once
+ transferState *transferJobs
}
// NewBackend initializes all storage, credential, site, library, download, subscription, and live components.
@@ -406,6 +119,13 @@ func NewBackend(opts Options) (*Backend, error) {
corruptBackups = append(corruptBackups, setBackup)
}
curSettings := setStore.Get()
+ if opts.Profile == ProfileRemote {
+ if forced, changed := remoteSettings(curSettings, loc.DefaultCacheDir); changed {
+ if updated, uErr := setStore.Update(forced); uErr == nil {
+ curSettings = updated
+ }
+ }
+ }
// Every site request follows Settings → 网络 (DEC-046 ⑤); an unusable
// stored address falls back to the system's proxy.
if err := site.SetProxy(curSettings.Network.ProxyMode, curSettings.Network.ProxyURL); err != nil {
@@ -451,10 +171,33 @@ func NewBackend(opts Options) (*Backend, error) {
credStore := credMgr.Store(credential.SiteBilibili)
douyinCredStore := credMgr.Store(credential.SiteDouyin)
+ var (
+ db *sql.DB
+ updatesDB *sql.DB
+ bgCancel context.CancelFunc
+ initOK bool
+ )
+ defer func() {
+ if initOK {
+ return
+ }
+ if bgCancel != nil {
+ bgCancel()
+ }
+ if updatesDB != nil {
+ _ = updatesDB.Close()
+ }
+ if db != nil {
+ _ = db.Close()
+ }
+ }()
+
dbPath := filepath.Join(loc.DataDir, "library.db")
_, dbStatErr := os.Stat(dbPath)
dbWasMissing := os.IsNotExist(dbStatErr)
- db, dbRec, dbBackup, err := storage.OpenSQLite(dbPath)
+ var dbRec bool
+ var dbBackup string
+ db, dbRec, dbBackup, err = storage.OpenSQLite(dbPath)
if err != nil {
return nil, err
}
@@ -462,31 +205,35 @@ func NewBackend(opts Options) (*Backend, error) {
corruptBackups = append(corruptBackups, dbBackup)
}
if _, err := storage.CheckSQLiteSchema(db, "library.db", schemaVersion("library.db")); err != nil {
- _ = db.Close()
return nil, err
}
updatesDBPath := filepath.Join(loc.DataDir, "updates.db")
- updatesDB, updatesRec, updatesBackup, err := storage.OpenSQLite(updatesDBPath)
+ var updatesRec bool
+ var updatesBackup string
+ updatesDB, updatesRec, updatesBackup, err = storage.OpenSQLite(updatesDBPath)
if err != nil {
- _ = db.Close()
return nil, err
}
if updatesRec && updatesBackup != "" {
corruptBackups = append(corruptBackups, updatesBackup)
}
if _, err := storage.CheckSQLiteSchema(updatesDB, "updates.db", schemaVersion("updates.db")); err != nil {
- _ = updatesDB.Close()
- _ = db.Close()
return nil, err
}
libStore, err := library.OpenWithDataDir(db, curSettings.CacheDir, loc.DataDir)
if err != nil {
- _ = updatesDB.Close()
- _ = db.Close()
return nil, err
}
+ if opts.Profile == ProfileRemote {
+ // On the remote, completed items are uploaded and deleted from the
+ // export folder; keep their index rows so auto-cache never re-downloads them.
+ libStore.SetAllowMovedFiles(true)
+ }
+ if node, nErr := library.LoadOrCreateNode(loc.DataDir, nodeName(opts.NodeName)); nErr == nil {
+ libStore.SetNode(node)
+ }
// If SQLite was recreated or did not exist on disk before startup, scan CacheDir to rebuild index from item.json files.
if dbRec || dbWasMissing {
@@ -504,9 +251,13 @@ func NewBackend(opts Options) (*Backend, error) {
_ = os.MkdirAll(previewDir, 0o700)
evBus := newEventBus()
- bgCtx, bgCancel := context.WithCancel(context.Background())
+ var bgCtx context.Context
+ bgCtx, bgCancel = context.WithCancel(context.Background())
b := &Backend{
+ profile: opts.Profile,
+ logMirror: opts.LogMirror,
+ startedAt: time.Now(),
loc: loc,
db: db,
updatesDB: updatesDB,
@@ -522,13 +273,12 @@ func NewBackend(opts Options) (*Backend, error) {
bgCtx: bgCtx,
bgCancel: bgCancel,
renewalWake: make(chan struct{}, 1),
+ remote: &remoteLink{},
logPath: filepath.Join(loc.LogsDir, "trace.log"),
previewDir: previewDir,
corruptFiles: corruptBackups,
}
if err := b.initUpdateHistory(opts); err != nil {
- _ = updatesDB.Close()
- _ = db.Close()
return nil, err
}
@@ -569,8 +319,6 @@ func NewBackend(opts Options) (*Backend, error) {
}
})
if err != nil {
- _ = updatesDB.Close()
- _ = db.Close()
return nil, err
}
b.dl = dlMgr
@@ -586,8 +334,6 @@ func NewBackend(opts Options) (*Backend, error) {
evBus.Publish(EventSubscriptionChecked, fmt.Sprintf("checked=%d", sum.CheckedCreators))
})
if err != nil {
- _ = updatesDB.Close()
- _ = db.Close()
return nil, err
}
b.subs = subMgr
@@ -597,8 +343,6 @@ func NewBackend(opts Options) (*Backend, error) {
queuePath := filepath.Join(loc.DataDir, cacheQueueFileName)
queueMgr, queueLoadBackup, err := newCacheQueueManager(b, queuePath, opts.CacheQueueClock, opts.CacheQueueRand, opts.CacheQueuePacing)
if err != nil {
- _ = updatesDB.Close()
- _ = db.Close()
return nil, err
}
if queueLoadBackup != "" {
@@ -607,13 +351,9 @@ func NewBackend(opts Options) (*Backend, error) {
b.queue = queueMgr
// Every table of both databases now has the layout of this build.
if err := storage.StampSQLiteSchema(db, schemaVersion("library.db")); err != nil {
- _ = updatesDB.Close()
- _ = db.Close()
return nil, err
}
if err := storage.StampSQLiteSchema(updatesDB, schemaVersion("updates.db")); err != nil {
- _ = updatesDB.Close()
- _ = db.Close()
return nil, err
}
@@ -639,7 +379,7 @@ func NewBackend(opts Options) (*Backend, error) {
b.live = liveMgr
biliClient.SetAccountReplacingHandler(func() {
- b.pauseSiteActiveWork(site.Bilibili, "auth_required", "哔哩哔哩登录账号已变更,任务已暂停")
+ b.pauseSiteActiveWorkAsync(site.Bilibili, "auth_required", "哔哩哔哩登录账号已变更,任务已暂停")
})
biliClient.SetAutomaticRequestHandlers(subMgr.AutomaticRequestAllowed, subMgr.RecordAutomaticStop)
dyClient.SetAutomaticRequestHandlers(
@@ -655,10 +395,18 @@ func NewBackend(opts Options) (*Backend, error) {
return b.credMgr.HasActiveCredential(string(siteID))
})
subMgr.RegisterAutoCacheEnqueuer(site.Douyin, func(ctx context.Context, item subscription.UpdateItem) (string, error) {
- t, err := b.enqueueDouyinWorkWithSource(ctx, item.DynID, "auto")
+ // The update came from the subscribed account's works list: a
+ // co-creation by someone else goes to that account's folder.
+ t, err := b.enqueueDouyinWorkWithSource(ctx, item.DynID, "auto", item.UID, b.subscribedAccountName(site.Douyin, item.UID))
return t.TaskID, err
})
- subMgr.SetOnAuthorAvatar(b.rememberAccountAvatar)
+ if opts.Profile != ProfileRemote {
+ subMgr.SetOnAuthorAvatar(b.rememberAccountAvatar)
+ } else {
+ // No new cache task starts while the export folder is almost full
+ // (remote.md §6.2); the remote has no avatars or recent parses.
+ subMgr.SetAutoCacheGate(b.remoteCacheGate)
+ }
subMgr.SetOnLiveHint(func(acc subscription.AccountRef, roomID string, webRID string) {
if strings.EqualFold(acc.Site, string(site.Douyin)) {
liveMgr.ObserveAccountLiveHint(site.Douyin, acc.UID, webRID, roomID)
@@ -682,12 +430,12 @@ func NewBackend(opts Options) (*Backend, error) {
return err
})
biliClient.SetAuthExpiredHandler(func() {
- b.pauseSiteActiveWork(site.Bilibili, "auth_required", "哔哩哔哩登录已失效,任务已暂停")
+ b.pauseSiteActiveWorkAsync(site.Bilibili, "auth_required", "哔哩哔哩登录已失效,任务已暂停")
evBus.PublishSite(EventAccountChanged, string(site.Bilibili), "expired")
})
dyClient.SetAuthExpiredHandler(func(reason string) {
msg := firstNonEmpty(reason, "抖音登录已失效,任务已暂停")
- b.pauseSiteActiveWork(site.Douyin, "auth_required", msg)
+ b.pauseSiteActiveWorkAsync(site.Douyin, "auth_required", msg)
evBus.PublishSite(EventAccountChanged, string(site.Douyin), "expired")
})
@@ -696,23 +444,27 @@ func NewBackend(opts Options) (*Backend, error) {
if !opts.DisableBgWorkers {
if err := dlMgr.Start(bgCtx); err != nil {
- bgCancel()
- _ = updatesDB.Close()
- _ = db.Close()
return nil, err
}
subMgr.Start(bgCtx)
liveMgr.Start(bgCtx)
- queueMgr.Start(bgCtx)
- b.pruneAccountAvatars()
- b.bgWg.Add(1)
- go b.runRenewalLoop(bgCtx)
- b.bgWg.Add(1)
- go b.runFullCacheLoop(bgCtx)
+ if opts.Profile != ProfileRemote {
+ // The remote never renews (Cookies are renewed only by the
+ // desktop, DEC-062 ③) and never runs 全部缓存 (remote.md §4).
+ queueMgr.Start(bgCtx)
+ b.pruneAccountAvatars()
+ b.bgWg.Add(1)
+ go b.runRenewalLoop(bgCtx)
+ b.bgWg.Add(1)
+ go b.runFullCacheLoop(bgCtx)
+ b.bgWg.Add(1)
+ go b.runRemoteCookieRetry(bgCtx)
+ }
b.bgWg.Add(1)
go func() { defer b.bgWg.Done(); _, _ = b.BootstrapAuth(bgCtx) }()
}
+ initOK = true
return b, nil
}
@@ -723,8 +475,26 @@ func schemaVersion(name string) int {
return 1
}
-// pauseSiteActiveWork pauses active download tasks and stops active live recordings
-// belonging ONLY to targetSite, leaving other sites' active tasks and recordings untouched.
+// goBg spawns a tracked background goroutine bound to b.bgCtx.
+// Returns false without spawning once Close has begun.
+func (b *Backend) goBg(fn func(ctx context.Context)) bool {
+ b.bgMu.Lock()
+ if b.bgClosing || b.bgCtx == nil || b.bgCtx.Err() != nil {
+ b.bgMu.Unlock()
+ return false
+ }
+ b.bgWg.Add(1)
+ ctx := b.bgCtx
+ b.bgMu.Unlock()
+ go func() {
+ defer b.bgWg.Done()
+ fn(ctx)
+ }()
+ return true
+}
+
+// pauseSiteActiveWork pauses active download tasks, cache queues, and stops active
+// live recordings belonging ONLY to targetSite, leaving other sites untouched.
func (b *Backend) pauseSiteActiveWork(targetSite site.ID, reasonCode, reasonMsg string) {
if b.dl != nil {
b.dl.PauseForSite(targetSite, reasonCode, reasonMsg)
@@ -737,105 +507,30 @@ func (b *Backend) pauseSiteActiveWork(targetSite site.ID, reasonCode, reasonMsg
}
}
-func (b *Backend) syncDouyinAccountWebRID(secUID, webRID string) {
- secUID = strings.TrimSpace(secUID)
- webRID = strings.TrimSpace(webRID)
- if secUID == "" || webRID == "" || b.subs == nil {
- return
- }
- _ = b.subs.UpdateAccountWebRID(string(site.Douyin), secUID, webRID)
-}
-
-func (b *Backend) lookupAccountWebRID(secUID string) string {
- secUID = strings.TrimSpace(secUID)
- if secUID == "" {
- return ""
- }
- if b.douyin != nil {
- if w := b.douyin.CachedWebRID(secUID); w != "" {
- return w
- }
- }
- if b.subs != nil {
- if _, acc, ok := b.subs.GetAccount(string(site.Douyin), secUID); ok && acc.WebRID != "" {
- return acc.WebRID
- }
- }
- return ""
-}
-
-func (b *Backend) startDouyinLiveRecording(ctx context.Context, uid string, webRID string) (LiveAccountState, error) {
- rs, err := b.live.StartDouyinRecording(ctx, uid, webRID)
- return mapRoomToAccountState(rs), err
-}
-
-func (b *Backend) runRenewalLoop(ctx context.Context) {
- defer b.bgWg.Done()
- // Wait 1 minute after startup before the first automatic renewal check.
- initialTimer := time.NewTimer(time.Minute)
- select {
- case <-ctx.Done():
- initialTimer.Stop()
- return
- case <-b.renewalWake:
- initialTimer.Stop()
- // Wait 1 minute after QR login confirmation
- t2 := time.NewTimer(time.Minute)
- select {
- case <-ctx.Done():
- t2.Stop()
- return
- case <-t2.C:
- }
- case <-initialTimer.C:
- }
-
- for {
- if ctx.Err() != nil {
- return
- }
- b.tryScheduledRenewal(ctx)
-
- timer := time.NewTimer(12 * time.Hour)
- select {
- case <-ctx.Done():
- timer.Stop()
- return
- case <-b.renewalWake:
- timer.Stop()
- t2 := time.NewTimer(time.Minute)
- select {
- case <-ctx.Done():
- t2.Stop()
- return
- case <-t2.C:
- }
- case <-timer.C:
- }
- }
-}
-
-func (b *Backend) tryScheduledRenewal(ctx context.Context) {
- st := b.cred.Status()
- if !st.LoggedIn {
- return
+// pauseSiteActiveWorkAsync pauses downloads and cache queues synchronously, and
+// stops active live recordings for targetSite asynchronously on a tracked goroutine.
+// Used from site client callbacks (auth expiry / account replacement) where the
+// caller may hold a site client lock or run on a recording goroutine itself.
+func (b *Backend) pauseSiteActiveWorkAsync(targetSite site.ID, reasonCode, reasonMsg string) {
+ if b.dl != nil {
+ b.dl.PauseForSite(targetSite, reasonCode, reasonMsg)
}
- if st.Source != "qr" {
- return
+ if b.queue != nil {
+ b.queue.pauseForSite(targetSite, reasonCode, reasonMsg)
}
- if b.subs != nil {
- if inBackoff, _ := b.subs.IsInBackoff(); inBackoff {
- return
- }
- if !b.subs.CanUseQuotaTokens(8) {
- return
- }
+ if b.live != nil {
+ liveMgr := b.live
+ b.goBg(func(context.Context) {
+ liveMgr.StopForSite(targetSite, reasonCode)
+ })
}
- _, _ = b.RefreshCookie(bilibili.WithAutomaticRequests(ctx, "renewal"))
}
// Close stops background workers, removes temporary media previews, and closes SQLite databases.
func (b *Backend) Close() error {
+ b.bgMu.Lock()
+ b.bgClosing = true
+ b.bgMu.Unlock()
if b.bgCancel != nil {
b.bgCancel()
}
@@ -852,16 +547,24 @@ func (b *Backend) Close() error {
if b.dl != nil {
b.dl.Stop()
}
+ if b.remote != nil {
+ b.remote.closeClient()
+ }
if b.previewDir != "" {
_ = os.RemoveAll(b.previewDir)
}
+ var errs []error
if b.updatesDB != nil {
- _ = b.updatesDB.Close()
+ if err := b.updatesDB.Close(); err != nil {
+ errs = append(errs, err)
+ }
}
if b.db != nil {
- return b.db.Close()
+ if err := b.db.Close(); err != nil {
+ errs = append(errs, err)
+ }
}
- return nil
+ return errors.Join(errs...)
}
// SubscribeEvents registers an event listener and returns an unsubscribe function.
@@ -932,14 +635,18 @@ func (b *Backend) GetSettings() settings.Settings {
// UpdateSettings validates and persists settings, propagating changes to managers.
func (b *Backend) UpdateSettings(next settings.Settings) (settings.Settings, error) {
b.settingsMu.Lock()
- defer b.settingsMu.Unlock()
prev := b.settings.Get()
+ if b.profile == ProfileRemote {
+ next, _ = remoteSettings(next, prev.CacheDir)
+ }
preview, err := b.settings.PreviewUpdate(next)
if err != nil {
+ b.settingsMu.Unlock()
return prev, err
}
if preview.Network.ProxyMode == site.ProxyCustom {
if _, err := site.ParseProxyURL(preview.Network.ProxyURL); err != nil {
+ b.settingsMu.Unlock()
return prev, &site.Error{Kind: site.ErrKindBadRequest, Message: err.Error()}
}
}
@@ -949,18 +656,21 @@ func (b *Backend) UpdateSettings(next settings.Settings) (settings.Settings, err
updated, err = b.settings.Update(preview)
return err
}
- if !strings.EqualFold(prev.CacheDir, preview.CacheDir) {
+ if !samePath(prev.CacheDir, preview.CacheDir) {
err = b.lib.ChangeCacheDir(preview.CacheDir, persist)
} else {
err = persist()
}
if err != nil {
+ b.settingsMu.Unlock()
return prev, err
}
_ = site.SetProxy(updated.Network.ProxyMode, updated.Network.ProxyURL) // checked above; applies at once
b.dl.UpdateSettings(updated.Download)
b.subs.UpdateSettings(updated.Subscription)
b.live.UpdateSettings(updated.Live)
+ b.settingsMu.Unlock()
+
b.events.Publish(EventSettingsChanged, "updated")
return updated, nil
}
@@ -975,154 +685,6 @@ func (b *Backend) UpdateUIState(next uistate.State) (uistate.State, error) {
return b.uiState.Update(next)
}
-// AccountStatus returns the desensitized Bilibili account status (never exposing raw cookies or tokens).
-func (b *Backend) AccountStatus() credential.Status {
- return b.cred.Status()
-}
-
-// BootstrapAuth verifies existing credentials per-site on startup without cross-site interference:
-// - Logged-out sites are skipped with zero network requests.
-// - Expired credentials pause only that site's active tasks and recordings.
-// - Transient network or risk-control errors mark status "unknown" while keeping credentials usable.
-func (b *Backend) BootstrapAuth(ctx context.Context) (credential.Status, error) {
- var biliOut credential.Status
- var allErr error
-
- biliSt := b.cred.Status()
- biliOut = biliSt
- if biliSt.State != "logged_out" && biliSt.LoggedIn {
- verified, err := b.bili.VerifyCredential(ctx)
- if err != nil && bilibili.IsKind(err, bilibili.ErrKindAuthRequired) {
- b.pauseSiteActiveWork(site.Bilibili, "auth_required", "哔哩哔哩登录已失效,任务已暂停")
- } else if err != nil {
- var stateErr error
- verified, stateErr = b.cred.MarkState("unknown", "无法确认登录状态,请重试")
- err = errors.Join(err, stateErr)
- if stateErr != nil {
- verified = b.cred.Status()
- }
- } else if !verified.LoggedIn {
- b.pauseSiteActiveWork(site.Bilibili, "auth_required", "哔哩哔哩登录已失效,任务已暂停")
- }
- biliOut = verified
- allErr = errors.Join(allErr, err)
- b.events.PublishSite(EventAccountChanged, string(site.Bilibili), verified.State)
- }
-
- dySt := b.douyinCred.Status()
- if dySt.State != "logged_out" && dySt.LoggedIn {
- dyVerified, dyErr := b.douyin.VerifyCredential(ctx)
- if dyErr != nil && site.IsKind(dyErr, site.ErrKindAuthRequired) {
- b.pauseSiteActiveWork(site.Douyin, "auth_required", "抖音登录已失效,任务已暂停")
- } else if dyErr != nil {
- var stateErr error
- dyVerified, stateErr = b.douyinCred.MarkState("unknown", "无法确认抖音登录状态,请稍后重试")
- dyErr = errors.Join(dyErr, stateErr)
- if stateErr != nil {
- dyVerified = b.douyinCred.Status()
- }
- } else if !dyVerified.LoggedIn {
- b.pauseSiteActiveWork(site.Douyin, "auth_required", "抖音登录已失效,任务已暂停")
- }
- allErr = errors.Join(allErr, dyErr)
- b.events.PublishSite(EventAccountChanged, string(site.Douyin), dyVerified.State)
- }
-
- return biliOut, allErr
-}
-
-// VerifyAccount queries Bilibili /x/web-interface/nav to refresh account profile and login state.
-func (b *Backend) VerifyAccount(ctx context.Context) (credential.Status, error) {
- st, err := b.bili.VerifyCredential(ctx)
- if err != nil && bilibili.IsKind(err, bilibili.ErrKindAuthRequired) {
- b.pauseSiteActiveWork(site.Bilibili, "auth_required", "哔哩哔哩登录已失效,任务已暂停")
- }
- b.events.PublishSite(EventAccountChanged, string(site.Bilibili), st.State)
- return st, err
-}
-
-// StartQRLogin starts a new QR code login session and invalidates any previous QR session.
-func (b *Backend) StartQRLogin(ctx context.Context) (bilibili.QRSession, error) {
- sess, err := b.bili.StartQR(ctx)
- if err != nil {
- b.logError("StartQRLogin", err)
- return bilibili.QRSession{}, err
- }
- b.logInfo("QR login started: flow=" + sess.FlowID)
- return sess, nil
-}
-
-// PollQRLogin polls the status of the active QR login flow.
-func (b *Backend) PollQRLogin(ctx context.Context, flowID string) (bilibili.QRPollResult, error) {
- prevAuthPaused := b.snapshotAuthPausedQueueIDs(site.Bilibili)
- prev := b.cred.Status()
- res, err := b.bili.PollQR(ctx, flowID)
- if err != nil {
- b.logError("PollQRLogin", err)
- return bilibili.QRPollResult{}, err
- }
- if res.State == "confirmed" {
- b.bili.ClearCaches()
- select {
- case b.renewalWake <- struct{}{}:
- default:
- }
- switched := prev.LoggedIn && prev.Mid != 0 && prev.Mid != res.Account.Mid
- if switched {
- b.resumeAuthPausedQueueIDs(site.Bilibili, prevAuthPaused)
- } else if b.queue != nil {
- b.queue.resumeAuthPausedForSite(site.Bilibili)
- }
- b.logInfo(fmt.Sprintf("QR login confirmed: mid=%d", res.Account.Mid))
- b.events.PublishSite(EventAccountChanged, string(site.Bilibili), "logged_in")
- }
- return res, nil
-}
-
-// CancelQRLogin cancels the QR login flow so late responses never write credentials.
-func (b *Backend) CancelQRLogin(flowID string) {
- b.bili.CancelQR(flowID)
- b.logInfo("QR login canceled: flow=" + flowID)
-}
-
-// ImportCookie validates a manual Bilibili Cookie string against /x/web-interface/nav first,
-// and only persists the credential if verification succeeds.
-func (b *Backend) ImportCookie(ctx context.Context, rawCookie, rawRefreshToken string) (credential.Status, error) {
- prevAuthPaused := b.snapshotAuthPausedQueueIDs(site.Bilibili)
- prev := b.cred.Status()
- st, err := b.bili.LoginWithCookie(ctx, rawCookie, rawRefreshToken)
- if err != nil {
- b.logError("ImportCookie", err)
- return b.cred.Status(), err
- }
- switched := prev.LoggedIn && prev.Mid != 0 && prev.Mid != st.Mid
- if switched {
- b.pauseSiteActiveWork(site.Bilibili, "auth_required", "哔哩哔哩登录账号已变更,任务已暂停")
- }
- if st.LoggedIn {
- if switched {
- b.resumeAuthPausedQueueIDs(site.Bilibili, prevAuthPaused)
- } else if b.queue != nil {
- b.queue.resumeAuthPausedForSite(site.Bilibili)
- }
- }
- b.logInfo(fmt.Sprintf("manual cookie imported: state=%s mid=%d", st.State, st.Mid))
- b.events.PublishSite(EventAccountChanged, string(site.Bilibili), st.State)
- return st, nil
-}
-
-// RefreshCookie runs the 5-step Bilibili Cookie renewal flow (or resumes confirmation if pending).
-func (b *Backend) RefreshCookie(ctx context.Context) (credential.Status, error) {
- st, err := b.bili.CheckAndRefreshCookie(ctx)
- if err != nil {
- b.logError("RefreshCookie", err)
- } else if st.LoggedIn && b.queue != nil {
- b.queue.resumeAuthPausedForSite(site.Bilibili)
- }
- b.events.PublishSite(EventAccountChanged, string(site.Bilibili), st.State)
- return st, err
-}
-
// MutateUIState changes fields of ui-state.json under its lock.
func (b *Backend) MutateUIState(fn func(*uistate.State)) (uistate.State, error) {
return b.uiState.Mutate(fn)
@@ -1185,1687 +747,41 @@ func (b *Backend) PauseForExit() {
b.logInfo("work paused for exit")
}
-// PauseAllActiveWork pauses running and queued download tasks and stops active live recordings across all sites.
+// PauseAllActiveWork pauses active download tasks, cache queues, and live
+// recordings for sites that currently have no active credential, leaving
+// still-authenticated sites running undisturbed.
func (b *Backend) PauseAllActiveWork() {
- if b.queue != nil {
- for _, sid := range []site.ID{site.Bilibili, site.Douyin} {
- if b.credMgr != nil && b.credMgr.HasActiveCredential(string(sid)) {
- b.queue.pauseForSite(sid, "app_closed", "已暂停(应用关闭)")
- } else {
- b.queue.pauseForSite(sid, "auth_required", "登录状态已变更,任务已暂停")
- }
+ for _, sid := range site.All() {
+ if b.credMgr == nil || !b.credMgr.HasActiveCredential(string(sid)) {
+ b.pauseSiteActiveWork(sid, "auth_required", "登录状态已变更,任务已暂停")
}
}
- if b.dl != nil {
- b.dl.PauseAll("auth_required", "登录状态已变更,任务已暂停")
- }
- if b.live != nil {
- b.live.StopForSite(site.Bilibili, "auth_required")
- b.live.StopForSite(site.Douyin, "auth_required")
- }
}
-// Logout pauses Bilibili active tasks and live recordings, cancels any active QR login flow, and clears Bilibili credentials.
-func (b *Backend) Logout() (credential.Status, error) {
- b.pauseSiteActiveWork(site.Bilibili, "auth_required", "已退出哔哩哔哩登录,任务已暂停")
- err := b.bili.LogoutCredential()
- st := b.cred.Status()
- if err != nil {
- b.logError("Logout", err)
- } else {
- b.logInfo("bilibili account logged out and credentials cleared")
- }
- b.events.PublishSite(EventAccountChanged, string(site.Bilibili), st.State)
- return st, err
-}
-
-// OpenLink resolves user input across supported sites after enforcing per-site login gates,
-// fetches detail metadata, records sanitized navigation history, and returns OpenLinkResult.
-func (b *Backend) OpenLink(ctx context.Context, rawInput string) (*OpenLinkResult, error) {
- if err := b.requireAnyLogin(); err != nil {
- return nil, err
- }
- siteID, normalizedInput, err := b.registry.DetectSite(rawInput)
- if err != nil {
- return nil, err
- }
- if err := b.requireSiteLogin(siteID); err != nil {
- return nil, err
- }
-
- if siteID == site.Douyin {
- return b.openDouyinLink(ctx, normalizedInput)
- }
-
- target, err := b.bili.ResolveLink(ctx, normalizedInput)
- if err != nil {
- b.logError("OpenLink.Resolve", err)
- return nil, err
- }
-
- siteTarget, _ := b.biliAdapter.Resolve(ctx, target.CanonicalURL)
- if siteTarget.Kind == "" {
- siteTarget = site.ResolveTarget{
- Site: site.Bilibili,
- Kind: target.Kind,
- ID: target.ID,
- NumericAID: target.AID,
- Page: target.Page,
- NumericRoomID: target.RoomID,
- NumericMid: target.Mid,
- CanonicalURL: target.CanonicalURL,
- Unsupported: target.Unsupported,
- Reason: target.Reason,
- }
- }
- out := &OpenLinkResult{
- Site: string(site.Bilibili),
- SiteTarget: &siteTarget,
- Target: target,
- }
-
- switch target.Kind {
- case "video":
- vd, err := b.bili.VideoDetail(ctx, target.ID)
- if err != nil {
- b.logError("OpenLink.VideoDetail", err)
- return nil, err
- }
- out.Video = &vd
- if item, ok, _ := b.lib.GetItem(vd.BVID); ok {
- out.CachedItem = &item
- }
- if err := b.lib.UpsertFeedEntry(library.FeedEntry{
- Site: "bilibili",
- Kind: "video",
- RawID: vd.BVID,
- Mid: vd.Author.Mid,
- AuthorName: vd.Author.Name,
- AuthorFace: vd.Author.Face,
- Title: vd.Title,
- Summary: vd.Desc,
- CoverURL: vd.Cover,
- CanonicalURL: vd.CanonicalURL,
- PubTs: vd.PubTs,
- }); err != nil {
- return nil, &bilibili.SiteError{Site: site.Bilibili, Kind: "storage", Message: "解析记录写入失败", Err: err}
- }
- out.HistoryThumbs = &HistoryThumbJob{Site: "bilibili", Kind: "video", ID: vd.BVID, AvatarURL: vd.Author.Face, CoverURL: vd.Cover}
- if err := b.history.Record(storage.HistoryEntry{
- Site: "bilibili",
- Kind: "video",
- ID: vd.BVID,
- Title: vd.Title,
- Subtitle: vd.Author.Name,
- CanonicalURL: vd.CanonicalURL,
- DurationText: formatHistoryDuration(vd.Duration),
- }); err != nil {
- return nil, &bilibili.SiteError{Site: site.Bilibili, Kind: "storage", Message: "历史记录写入失败", Err: err}
- }
-
- case "user":
- space, err := b.bili.UserCard(ctx, target.Mid)
- if err != nil {
- b.logError("OpenLink.UserCard", err)
- return nil, err
- }
- out.User = &space
- b.recordAccountWorks(site.Bilibili, strconv.FormatInt(space.Mid, 10), space.ArchiveCount)
- if dyns, dErr := b.bili.UserDynamics(ctx, target.Mid, ""); dErr == nil {
- out.UserDynamics = &dyns
- } else {
- b.logError("OpenLink.UserDynamics", dErr)
- out.UserDynamicsError = dErr.Error()
- }
- userID := fmt.Sprintf("%d", space.Mid)
- out.HistoryThumbs = &HistoryThumbJob{Site: "bilibili", Kind: "user", ID: userID, AvatarURL: space.Face}
- if err := b.history.Record(storage.HistoryEntry{
- Site: "bilibili",
- Kind: "user",
- ID: userID,
- Title: space.Name,
- Subtitle: space.Sign,
- CanonicalURL: space.CanonicalURL,
- }); err != nil {
- return nil, &bilibili.SiteError{Site: site.Bilibili, Kind: "storage", Message: "历史记录写入失败", Err: err}
- }
-
- case "dynamic":
- dyn, err := b.bili.DynamicDetail(ctx, target.ID)
- if err != nil {
- b.logError("OpenLink.DynamicDetail", err)
- return nil, err
- }
- out.Dynamic = &dyn
- if item, ok, _ := b.lib.GetItem(library.CanonicalItemKey("bilibili", "dynamic", dyn.ID)); ok {
- out.CachedItem = &item
- }
- var coverURL string
- if len(dyn.Images) > 0 {
- coverURL = dyn.Images[0].URL
- } else if len(dyn.Videos) > 0 {
- coverURL = dyn.Videos[0].Cover
- }
- if err := b.lib.UpsertFeedEntry(library.FeedEntry{
- Site: "bilibili",
- Kind: "dynamic",
- RawID: dyn.ID,
- Mid: dyn.Author.Mid,
- AuthorName: dyn.Author.Name,
- AuthorFace: dyn.Author.Face,
- Title: dyn.Title,
- Summary: dyn.Text,
- CoverURL: coverURL,
- CanonicalURL: dyn.CanonicalURL,
- PubTs: dyn.PubTs,
- }); err != nil {
- return nil, &bilibili.SiteError{Site: site.Bilibili, Kind: "storage", Message: "解析记录写入失败", Err: err}
- }
- out.HistoryThumbs = &HistoryThumbJob{Site: "bilibili", Kind: "dynamic", ID: dyn.ID, AvatarURL: dyn.Author.Face, CoverURL: coverURL}
- if err := b.history.Record(storage.HistoryEntry{
- Site: "bilibili",
- Kind: "dynamic",
- ID: dyn.ID,
- Title: dyn.Title,
- Subtitle: dyn.Author.Name,
- CanonicalURL: dyn.CanonicalURL,
- }); err != nil {
- return nil, &bilibili.SiteError{Site: site.Bilibili, Kind: "storage", Message: "历史记录写入失败", Err: err}
- }
-
- case "live":
- room, err := b.live.OpenRoom(ctx, target.RoomID)
- if err != nil {
- b.logError("OpenLink.LiveRoom", err)
- return nil, err
- }
- out.LiveRoom = &room
- space, err := b.bili.UserCard(ctx, room.UID)
- if err != nil {
- return nil, err
- }
- out.User = &space
- b.recordAccountWorks(site.Bilibili, strconv.FormatInt(space.Mid, 10), space.ArchiveCount)
- if dyns, dErr := b.bili.UserDynamics(ctx, room.UID, ""); dErr == nil {
- out.UserDynamics = &dyns
- } else {
- out.UserDynamicsError = dErr.Error()
- }
- liveID := fmt.Sprintf("live:%d", room.RoomID)
- out.HistoryThumbs = &HistoryThumbJob{Site: "bilibili", Kind: "live", ID: liveID, AvatarURL: space.Face, CoverURL: room.Cover}
- if err := b.history.Record(storage.HistoryEntry{
- Site: "bilibili",
- Kind: "live",
- ID: liveID,
- Title: room.Title,
- Subtitle: room.Uname,
- CanonicalURL: fmt.Sprintf("https://live.bilibili.com/%d", room.RoomID),
- }); err != nil {
- return nil, &bilibili.SiteError{Site: site.Bilibili, Kind: "storage", Message: "历史记录写入失败", Err: err}
- }
+// OpenDataFolder opens the DataDir, CacheDir, or LogsDir via Desktop.
+func (b *Backend) OpenDataFolder(target string) error {
+ switch target {
+ case "cache":
+ return b.desktop.OpenPath(b.lib.CacheDir())
+ case "logs":
+ return b.desktop.OpenPath(b.loc.LogsDir)
+ default:
+ return b.desktop.OpenPath(b.loc.DataDir)
}
-
- return out, nil
}
-func (b *Backend) openDouyinLink(ctx context.Context, normalizedInput string) (*OpenLinkResult, error) {
- target, err := b.douyin.ResolveLink(ctx, normalizedInput)
- if err != nil {
- b.logError("OpenLink.DouyinResolve", err)
- return nil, err
- }
- out := &OpenLinkResult{
- Site: string(site.Douyin),
- SiteTarget: &target,
- Target: bilibili.ResolveTarget{
- Kind: target.Kind,
- ID: target.ID,
- CanonicalURL: target.CanonicalURL,
- Unsupported: target.Unsupported,
- Reason: target.Reason,
- },
- }
-
- switch target.Kind {
- case "video", "note":
- wv, err := b.DouyinWork(ctx, target.ID)
- if err != nil {
- return nil, err
- }
- out.DouyinWork = wv
- out.CachedItem = wv.CachedItem
- feedKind := "video"
- histKind := "video"
- if wv.Kind == douyin.WorkKindNote {
- feedKind = "dynamic"
- histKind = "note"
- }
- out.Target.Kind = histKind
- out.SiteTarget.Kind = histKind
- if err := b.lib.UpsertFeedEntry(library.FeedEntry{
- Site: "douyin",
- Kind: feedKind,
- RawID: wv.ID,
- AuthorUID: wv.Author.SecUID,
- AuthorName: wv.Author.Nickname,
- AuthorFace: wv.Author.AvatarURL,
- Title: wv.Title,
- Summary: wv.Desc,
- CoverURL: wv.CoverURL,
- CanonicalURL: wv.CanonicalURL,
- PubTs: wv.CreateTime,
- }); err != nil {
- return nil, &site.Error{Site: site.Douyin, Kind: "storage", Message: "解析记录写入失败", Err: err}
- }
- out.HistoryThumbs = &HistoryThumbJob{
- Site: "douyin",
- Kind: histKind,
- ID: wv.ID,
- AvatarURL: wv.Author.AvatarURL,
- CoverURL: wv.CoverURL,
- }
- if err := b.history.Record(storage.HistoryEntry{
- Site: "douyin",
- Kind: histKind,
- ID: wv.ID,
- Title: wv.Title,
- Subtitle: wv.Author.Nickname,
- CanonicalURL: wv.CanonicalURL,
- DurationText: formatHistoryDuration(wv.DurationSec),
- }); err != nil {
- return nil, &site.Error{Site: site.Douyin, Kind: "storage", Message: "历史记录写入失败", Err: err}
- }
-
- case "user":
- secUID := firstNonEmpty(target.SecUID, target.ID)
- uv, err := b.DouyinUser(ctx, secUID)
- if err != nil {
- return nil, err
- }
- out.DouyinUser = uv
- out.Target.ID = uv.SecUID
- out.SiteTarget.ID = uv.SecUID
- out.SiteTarget.SecUID = uv.SecUID
- out.DouyinUserWorks, out.DouyinUserWorksError = b.firstDouyinUserWorks(ctx, uv)
- out.HistoryThumbs = &HistoryThumbJob{
- Site: "douyin",
- Kind: "user",
- ID: uv.SecUID,
- AvatarURL: uv.AvatarURL,
- }
- if err := b.history.Record(storage.HistoryEntry{
- Site: "douyin",
- Kind: "user",
- ID: uv.SecUID,
- Title: uv.Nickname,
- Subtitle: uv.Signature,
- CanonicalURL: uv.CanonicalURL,
- }); err != nil {
- return nil, &site.Error{Site: site.Douyin, Kind: "storage", Message: "历史记录写入失败", Err: err}
- }
-
- case "live":
- webRID := firstNonEmpty(target.WebRID, target.ID)
- lv, err := b.DouyinLive(ctx, webRID)
- if err != nil {
- return nil, err
- }
- out.DouyinLive = lv
- if lv.OwnerSecUID != "" {
- if uv, uErr := b.DouyinUser(ctx, lv.OwnerSecUID); uErr == nil {
- if lv.State != nil {
- uv.LiveRoom = lv.State
- if lv.LiveStatus == 1 {
- uv.LiveStatus = 1
- }
- }
- out.DouyinUser = uv
- out.DouyinUserWorks, out.DouyinUserWorksError = b.firstDouyinUserWorks(ctx, uv)
- }
- }
- liveID := "live:" + lv.WebRID
- out.HistoryThumbs = &HistoryThumbJob{
- Site: "douyin",
- Kind: "live",
- ID: liveID,
- AvatarURL: lv.OwnerAvatar,
- CoverURL: lv.CoverURL,
- }
- if err := b.history.Record(storage.HistoryEntry{
- Site: "douyin",
- Kind: "live",
- ID: liveID,
- Title: firstNonEmpty(lv.Title, lv.OwnerName+"的直播间"),
- Subtitle: lv.OwnerName,
- CanonicalURL: lv.CanonicalURL,
- }); err != nil {
- return nil, &site.Error{Site: site.Douyin, Kind: "storage", Message: "历史记录写入失败", Err: err}
+func firstNonEmpty(values ...string) string {
+ for _, v := range values {
+ if strings.TrimSpace(v) != "" {
+ return v
}
}
-
- return out, nil
-}
-
-func formatHistoryDuration(seconds int) string {
- if seconds <= 0 {
- return ""
- }
- h := seconds / 3600
- m := (seconds % 3600) / 60
- s := seconds % 60
- if h > 0 {
- return fmt.Sprintf("%d:%02d:%02d", h, m, s)
- }
- return fmt.Sprintf("%02d:%02d", m, s)
+ return ""
}
-// FetchHistoryThumbs downloads and stores the thumbnails of a recent-parse
-// entry after OpenLink returned. Image failures leave the placeholder; an
-// entry removed meanwhile gets nothing.
-func (b *Backend) FetchHistoryThumbs(ctx context.Context, job HistoryThumbJob) error {
- jobSite, err := normalizeSiteID(job.Site)
- if err != nil {
- return err
- }
- if err := b.requireSiteLogin(jobSite); err != nil {
- return err
- }
- if b.history == nil {
- return nil
- }
- var thumbs []storage.HistoryThumbnail
- for _, want := range []struct{ role, url string }{{"avatar", job.AvatarURL}, {"cover", job.CoverURL}} {
- if t := b.fetchHistoryThumbForSite(ctx, jobSite, want.role, want.url); len(t.Data) > 0 {
- thumbs = append(thumbs, t)
- }
- }
- if job.Kind == "user" && b.subs != nil {
- if _, ok := b.subs.OwnerOf(string(jobSite), job.ID); ok {
- b.rememberAccountAvatar(string(jobSite), job.ID, job.AvatarURL)
- }
- }
- if len(thumbs) == 0 {
- return nil
- }
- return b.history.AttachThumbs(string(jobSite), job.Kind, job.ID, thumbs...)
-}
-
-func (b *Backend) fetchHistoryThumb(ctx context.Context, role, rawURL string) storage.HistoryThumbnail {
- return b.fetchHistoryThumbForSite(ctx, site.Bilibili, role, rawURL)
-}
-
-func (b *Backend) fetchHistoryThumbForSite(ctx context.Context, siteID site.ID, role, rawURL string) storage.HistoryThumbnail {
- rawURL = strings.TrimSpace(rawURL)
- if rawURL == "" || b.history == nil {
- return storage.HistoryThumbnail{}
- }
- if strings.HasPrefix(rawURL, "http://") && !strings.HasPrefix(rawURL, "http://127.0.0.1") && !strings.HasPrefix(rawURL, "http://localhost") {
- rawURL = "https://" + strings.TrimPrefix(rawURL, "http://")
- }
- var raw []byte
- var err error
- switch siteID {
- case site.Douyin:
- if b.douyin == nil {
- return storage.HistoryThumbnail{}
- }
- raw, _, err = b.douyin.FetchImageLimited(ctx, rawURL, storage.MaxHistoryThumbBytes)
- default:
- if b.bili == nil {
- return storage.HistoryThumbnail{}
- }
- raw, err = b.bili.FetchImageLimited(ctx, rawURL, storage.MaxHistoryThumbBytes)
- }
- if err != nil || len(raw) == 0 || len(raw) > storage.MaxHistoryThumbBytes {
- return storage.HistoryThumbnail{}
- }
- cfg, _, err := image.DecodeConfig(bytes.NewReader(raw))
- if err != nil || cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width)*int64(cfg.Height) > 24_000_000 {
- return storage.HistoryThumbnail{}
- }
- img, _, err := image.Decode(bytes.NewReader(raw))
- if err != nil {
- return storage.HistoryThumbnail{}
- }
- w, h := cfg.Width, cfg.Height
- maxSide := 640
- if role == "avatar" {
- maxSide = 128
- }
- if w > maxSide {
- h, w = max(1, h*maxSide/w), maxSide
- }
- if h > maxSide {
- w, h = max(1, w*maxSide/h), maxSide
- }
- small := image.NewRGBA(image.Rect(0, 0, w, h))
- draw.ApproxBiLinear.Scale(small, small.Bounds(), img, img.Bounds(), draw.Src, nil)
- var encoded bytes.Buffer
- if err := png.Encode(&encoded, small); err != nil {
- return storage.HistoryThumbnail{}
- }
- return storage.HistoryThumbnail{Role: role, Ext: ".png", Data: encoded.Bytes()}
-}
-
-// HistoryThumbPath resolves a local cached parse-history thumbnail inside /thumbs/.
-func (b *Backend) HistoryThumbPath(name string) (string, error) {
- if err := b.requireAnyLogin(); err != nil {
- return "", err
- }
- if b.history == nil {
- return "", fmt.Errorf("service: history store unavailable")
- }
- return b.history.ThumbPath(name)
-}
-
-// ListHistory returns the recent sanitized navigation history entries.
-func (b *Backend) ListHistory() []storage.HistoryEntry {
- if b.requireAnyLogin() != nil {
- return nil
- }
- return b.history.List()
-}
-
-// ClearHistory clears the navigation history.
-func (b *Backend) ClearHistory() error {
- if err := b.requireAnyLogin(); err != nil {
- return err
- }
- return b.history.Clear()
-}
-
-// EnqueueVideoCache enqueues Bilibili video parts for local caching.
-func (b *Backend) EnqueueVideoCache(ctx context.Context, req download.VideoEnqueueRequest) ([]download.Task, error) {
- if err := b.requireSiteLogin(site.Bilibili); err != nil {
- return nil, err
- }
- tasks, err := b.dl.EnqueueVideo(ctx, req)
- if err != nil {
- b.logError("EnqueueVideoCache", err)
- return nil, err
- }
- b.events.PublishSite(EventTaskUpdated, string(site.Bilibili), "enqueued:video:"+req.BVID)
- return tasks, nil
-}
-
-// EnqueueDynamicCache enqueues a Bilibili dynamic post for local caching.
-func (b *Backend) EnqueueDynamicCache(ctx context.Context, req download.DynamicEnqueueRequest) (download.Task, error) {
- if err := b.requireSiteLogin(site.Bilibili); err != nil {
- return download.Task{}, err
- }
- task, err := b.dl.EnqueueDynamic(ctx, req)
- if err != nil {
- b.logError("EnqueueDynamicCache", err)
- return download.Task{}, err
- }
- b.events.PublishSite(EventTaskUpdated, string(site.Bilibili), "enqueued:dynamic:"+req.DynamicID)
- return task, nil
-}
-
-// 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.requireSiteLogin(site.Bilibili); err != nil {
- return download.Task{}, err
- }
- task, err := b.dl.CacheSupplement(ctx, bvid)
- if err != nil {
- b.logError("CacheSupplement", err)
- return download.Task{}, err
- }
- b.events.PublishSite(EventTaskUpdated, string(site.Bilibili), "enqueued:supplement:"+bvid)
- return task, nil
-}
-
-// Upgrade enqueues a quality upgrade download task for a cached Bilibili video item.
-func (b *Backend) Upgrade(ctx context.Context, key string) (download.Task, error) {
- if err := b.requireSiteLogin(site.Bilibili); err != nil {
- return download.Task{}, err
- }
- task, err := b.dl.Upgrade(ctx, key)
- if err != nil {
- b.logError("Upgrade", err)
- return download.Task{}, err
- }
- b.events.PublishSite(EventTaskUpdated, string(site.Bilibili), "enqueued:upgrade:"+key)
- return task, nil
-}
-
-// ListDownloadTasks returns all download tasks across sites.
-func (b *Backend) ListDownloadTasks() ([]download.Task, error) {
- if err := b.requireAnyLogin(); err != nil {
- return nil, err
- }
- return b.dl.ListTasks()
-}
-
-// TaskDetail returns per-file progress and sanitized attempt history for a download task.
-func (b *Backend) TaskDetail(taskID string) (download.TaskDetail, bool, error) {
- if err := b.requireAnyLogin(); err != nil {
- return download.TaskDetail{}, false, err
- }
- return b.dl.TaskDetail(taskID)
-}
-
-// PauseTask pauses a download task.
-func (b *Backend) PauseTask(taskID string) (download.Task, error) {
- if err := b.requireAnyLogin(); err != nil {
- return download.Task{}, err
- }
- return b.dl.Pause(taskID)
-}
-
-func (b *Backend) requireTaskSiteLogin(taskID string) error {
- if err := b.requireAnyLogin(); err != nil {
- return err
- }
- if detail, ok, err := b.dl.TaskDetail(taskID); err == nil && ok {
- tSite, sErr := normalizeSiteID(detail.Task.Site)
- if sErr != nil {
- return sErr
- }
- return b.requireSiteLogin(tSite)
- }
- return nil
-}
-
-// ResumeTask resumes a paused download task after verifying its owning site is logged in.
-func (b *Backend) ResumeTask(taskID string) (download.Task, error) {
- if err := b.requireTaskSiteLogin(taskID); err != nil {
- return download.Task{}, err
- }
- return b.dl.Resume(taskID)
-}
-
-// RetryTask retries a failed or partial download task after verifying its owning site is logged in.
-func (b *Backend) RetryTask(taskID string) (download.Task, error) {
- if err := b.requireTaskSiteLogin(taskID); err != nil {
- return download.Task{}, err
- }
- return b.dl.Retry(taskID)
-}
-
-// CancelTask cancels a download task and removes incomplete .part files.
-func (b *Backend) CancelTask(taskID string) (download.Task, error) {
- if err := b.requireAnyLogin(); err != nil {
- return download.Task{}, err
- }
- return b.dl.Cancel(taskID)
-}
-
-// RemoveTask deletes a finished task record; cached files stay in the library.
-func (b *Backend) RemoveTask(taskID string) error {
- if err := b.requireAnyLogin(); err != nil {
- return err
- }
- if err := b.dl.Remove(taskID); err != nil {
- return err
- }
- b.events.Publish(EventTaskUpdated, "removed:"+taskID)
- return nil
-}
-
-// RemoveFinishedTasks clears every completed or canceled task record.
-func (b *Backend) RemoveFinishedTasks() (int, error) {
- if err := b.requireAnyLogin(); err != nil {
- return 0, err
- }
- n, err := b.dl.RemoveFinished()
- if n > 0 {
- b.events.Publish(EventTaskUpdated, "removed:finished")
- }
- return n, err
-}
-
-// QueryFeed queries the unified feed (cached + online-discovered items) ordered by pub_ts DESC.
-func (b *Backend) QueryFeed(filter library.FeedFilter) ([]library.FeedEntry, error) {
- if err := b.requireAnyLogin(); err != nil {
- return nil, err
- }
- return b.lib.QueryFeed(filter)
-}
-
-// FeedPage queries a keyset-paginated page of the home feed.
-func (b *Backend) FeedPage(req library.FeedPageRequest) (library.FeedPageResult, error) {
- if err := b.requireAnyLogin(); err != nil {
- return library.FeedPageResult{}, err
- }
- return b.lib.FeedPage(req)
-}
-
-// Anchor returns the persisted home feed reading anchor from ui-state.json.
-func (b *Backend) Anchor() uistate.FeedAnchor {
- if b.requireAnyLogin() != nil {
- return uistate.FeedAnchor{}
- }
- return b.uiState.Get().Anchor
-}
-
-// SaveAnchor persists the home feed reading anchor into ui-state.json.
-func (b *Backend) SaveAnchor(anchor uistate.FeedAnchor) error {
- if err := b.requireAnyLogin(); err != nil {
- return err
- }
- _, err := b.uiState.Mutate(func(st *uistate.State) { st.Anchor = anchor })
- return err
-}
-
-// NewerCount returns the number of feed entries strictly newer than anchor.
-func (b *Backend) NewerCount(anchor uistate.FeedAnchor) (int, error) {
- if err := b.requireAnyLogin(); err != nil {
- return 0, err
- }
- return b.lib.NewerCachedCount(anchor.PubTs, anchor.Key)
-}
-
-// ListLibraryItems returns locally cached items matching filter.
-func (b *Backend) ListLibraryItems(filter library.FeedFilter) ([]library.ItemMetadata, error) {
- if err := b.requireAnyLogin(); err != nil {
- return nil, err
- }
- return b.lib.ListItems(filter)
-}
-
-// GetLibraryItem returns a single cached item by itemKey or rawID.
-func (b *Backend) GetLibraryItem(keyOrID string) (library.ItemMetadata, bool, error) {
- if err := b.requireAnyLogin(); err != nil {
- return library.ItemMetadata{}, false, err
- }
- return b.lib.GetItem(keyOrID)
-}
-
-// MediaPath validates and resolves a registered relative file path within a cached item.
-func (b *Backend) MediaPath(key, relPath string) (string, error) {
- if err := b.requireAnyLogin(); err != nil {
- return "", err
- }
- return b.lib.MediaPath(key, relPath)
-}
-
-// States computes the canonical cache status dots for the given item keys.
-func (b *Backend) States(keys []string) map[string]library.DotState {
- if b.requireAnyLogin() != nil {
- out := make(map[string]library.DotState, len(keys))
- for _, key := range keys {
- out[key] = library.DotState{Key: key, Dot: "none", Label: "登录后查看缓存状态"}
- }
- return out
- }
- out := b.lib.States(keys)
- activeProgress := make(map[string]float64)
- latest := make(map[string]download.Task)
- if tasks, err := b.dl.ListTasks(); err == nil {
- for _, t := range tasks {
- for _, key := range []string{t.ItemKey, t.TargetID} {
- if key == "" {
- continue
- }
- if _, exists := latest[key]; !exists {
- latest[key] = t
- }
- }
- if t.Status == "queued" || t.Status == "downloading" || t.Status == "muxing" || t.Status == "running" {
- prog := t.Progress
- if prog == 0 && t.TotalBytes > 0 {
- prog = float64(t.BytesDownloaded) / float64(t.TotalBytes)
- }
- if t.ItemKey != "" {
- activeProgress[t.ItemKey] = prog
- }
- if t.TargetID != "" {
- activeProgress[t.TargetID] = prog
- }
- }
- }
- }
- for _, k := range keys {
- if prog, active := activeProgress[k]; active {
- out[k] = library.DotState{
- Key: k,
- Dot: "ring",
- Label: "缓存中",
- Progress: prog,
- }
- continue
- }
- if task, exists := latest[k]; exists {
- switch task.Status {
- case "paused", "partial":
- dot := out[k]
- dot.Dot, dot.Label = "yellow", "部分缓存,重试可继续"
- if task.Status == "paused" {
- dot.Label = "已暂停,可继续"
- }
- out[k] = dot
- case "failed":
- dot := out[k]
- dot.Dot, dot.Label = "red", "缓存失败,可重试"
- out[k] = dot
- }
- }
- }
- return out
-}
-
-// PlanDelete computes the safe file deletion plan for an item key.
-func (b *Backend) PlanDelete(key string) (library.DeletePlan, error) {
- if err := b.requireAnyLogin(); err != nil {
- return library.DeletePlan{}, err
- }
- return b.lib.PlanDelete(key)
-}
-
-// Delete executes a safe manifest-only file deletion for an item key.
-func (b *Backend) Delete(key string) error {
- return b.DeleteLibraryItem(key, true)
-}
-
-// RebuildLibraryIndex scans CacheDir for item.json files and rebuilds the SQLite index.
-func (b *Backend) RebuildLibraryIndex() (library.RebuildReport, error) {
- if err := b.requireAnyLogin(); err != nil {
- return library.RebuildReport{}, err
- }
- rep, err := b.lib.RebuildIndex()
- if len(rep.CorruptBackedUp) > 0 {
- b.logMu.Lock()
- b.corruptFiles = append(b.corruptFiles, rep.CorruptBackedUp...)
- b.logMu.Unlock()
- }
- b.events.Publish(EventLibraryChanged, "rebuilt")
- return rep, err
-}
-
-// RefreshLibrary is the media library's "刷新": a quick rescan that drops
-// items whose folder was deleted and marks items with missing files. Only
-// local files are read; no site request is made.
-func (b *Backend) RefreshLibrary() (library.RebuildReport, error) {
- if err := b.requireAnyLogin(); err != nil {
- return library.RebuildReport{}, err
- }
- rep, err := b.lib.RefreshIndex()
- if len(rep.CorruptBackedUp) > 0 {
- b.logMu.Lock()
- b.corruptFiles = append(b.corruptFiles, rep.CorruptBackedUp...)
- b.logMu.Unlock()
- }
- if err != nil {
- b.logError("RefreshLibrary", err)
- } else {
- b.logInfo(fmt.Sprintf("library refresh: scanned=%d removed=%d newly_missing=%d", rep.Scanned, len(rep.Removed), len(rep.NewlyMissing)))
- }
- b.events.Publish(EventLibraryChanged, "refreshed")
- return rep, err
-}
-
-// AddLibraryRoot adds an existing cache root or legacy trace-data directory and indexes its manifests.
-func (b *Backend) AddLibraryRoot(selectedDir string) (library.AddRootReport, error) {
- if err := b.requireAnyLogin(); err != nil {
- return library.AddRootReport{}, err
- }
- rep, err := b.lib.AddLibraryRoot(selectedDir)
- if err == nil {
- b.events.Publish(EventLibraryChanged, "root_added")
- }
- return rep, err
-}
-
-// DeleteLibraryItem removes an item from the index and optionally deletes its registered files from disk.
-func (b *Backend) DeleteLibraryItem(itemKey string, deleteFiles bool) error {
- if err := b.requireAnyLogin(); err != nil {
- return err
- }
- if err := b.lib.DeleteItem(itemKey, deleteFiles); err != nil {
- return err
- }
- b.events.Publish(EventLibraryChanged, "deleted:"+itemKey)
- return nil
-}
-
-// MigrateCacheDir changes the active cache directory, optionally moves existing files, and updates settings.json.
-func (b *Backend) MigrateCacheDir(newDir string, moveExisting bool) (library.RebuildReport, error) {
- if err := b.requireAnyLogin(); err != nil {
- return library.RebuildReport{}, err
- }
- if !moveExisting {
- cur := b.settings.Get()
- cur.CacheRoot, cur.CacheDir = newDir, newDir
- _, err := b.UpdateSettings(cur)
- return library.RebuildReport{}, err
- }
- b.settingsMu.Lock()
- defer b.settingsMu.Unlock()
- cur := b.settings.Get()
- cur.CacheDir, cur.CacheRoot = newDir, newDir
- cur, err := b.settings.PreviewUpdate(cur)
- if err != nil {
- return library.RebuildReport{}, err
- }
- var rep library.RebuildReport
- err = b.dl.WithIdleTasks(func() error {
- var migrationErr error
- rep, migrationErr = b.lib.MigrateCacheDirWithPersistence(newDir, true, func() error { _, err := b.settings.Update(cur); return err })
- return migrationErr
- })
- if err != nil {
- return rep, err
- }
- b.events.Publish(EventLibraryChanged, "migrated")
- return rep, nil
-}
-
-// UpgradeCandidates returns up to limit cached Bilibili video items ordered by oldest UpgradeCheckedAt.
-func (b *Backend) UpgradeCandidates(limit int) ([]library.ItemMetadata, error) {
- if err := b.requireAnyLogin(); err != nil {
- return nil, err
- }
- return b.lib.UpgradeCandidates(limit)
-}
-
-// CheckUpgradeKeys checks the specified Bilibili video keys (or up to 50 candidates when empty) for quality upgrades.
-func (b *Backend) CheckUpgradeKeys(ctx context.Context, keys []string, force bool) ([]library.ItemMetadata, error) {
- if err := b.requireSiteLogin(site.Bilibili); err != nil {
- return nil, err
- }
- dlCfg := b.settings.Get().Download
- opts := bilibili.PlaySelectionOptions{
- CodecOrder: append([]string(nil), dlCfg.CodecOrder...),
- PreferredCodec: dlCfg.PreferredVideoCodec,
- PreferLosslessAudio: dlCfg.PreferLosslessAudio,
- PreferDolbyAudio: dlCfg.PreferDolbyAudio,
- TargetQn: 127,
- }
- items, err := b.lib.CheckUpgradeKeys(ctx, b.bili, keys, force, opts)
- if err != nil {
- b.logError("CheckUpgradeKeys", err)
- return items, err
- }
- b.events.PublishSite(EventLibraryChanged, string(site.Bilibili), "upgrade_checked")
- return items, nil
-}
-
-// CheckQualityUpgrade checks cached Bilibili videos against PlayURL for higher video/audio quality.
-func (b *Backend) CheckQualityUpgrade(ctx context.Context) ([]library.ItemMetadata, error) {
- return b.CheckUpgradeKeys(ctx, nil, true)
-}
-
-// ListSubscriptions returns all creator subscriptions.
-func (b *Backend) ListSubscriptions() ([]subscription.Subscription, error) {
- if err := b.requireAnyLogin(); err != nil {
- return nil, err
- }
- return b.subs.List()
-}
-
-// UpsertSubscription creates or updates a creator subscription.
-func (b *Backend) UpsertSubscription(sub subscription.Subscription) (subscription.Subscription, error) {
- if err := b.requireAnyLogin(); err != nil {
- return subscription.Subscription{}, err
- }
- res, err := b.subs.Upsert(sub)
- if err == nil {
- // A user page subscribes with only Mid and Face; the stored accounts
- // then carry that face. Raw input accounts win when given.
- if len(sub.Accounts) > 0 {
- b.rememberAccountAvatars(sub.Accounts)
- } else {
- b.rememberAccountAvatars(res.Accounts)
- }
- b.events.Publish(EventSubscriptionChecked, "upserted")
- }
- return res, err
-}
-
-// CreateSubscription creates a new multi-account subscription.
-func (b *Backend) CreateSubscription(name, note string, accounts []subscription.AccountRef, rules subscription.SubRules) (subscription.Subscription, error) {
- if err := b.requireAnyLogin(); err != nil {
- return subscription.Subscription{}, err
- }
- res, err := b.subs.Create(name, note, accounts, rules)
- if err == nil {
- // The input still has the raw avatar URL; a stored Douyin one is dropped.
- b.rememberAccountAvatars(accounts)
- b.events.Publish(EventSubscriptionChecked, "created")
- }
- return res, err
-}
-
-// LinkSubscriptionAccount links an account to an existing subscription.
-func (b *Backend) LinkSubscriptionAccount(subID, siteID, uid, name, face string) (subscription.Subscription, error) {
- if err := b.requireAnyLogin(); err != nil {
- return subscription.Subscription{}, err
- }
- res, err := b.subs.Link(subID, siteID, uid, name, face)
- if err == nil {
- b.rememberAccountAvatar(siteID, uid, face)
- b.events.Publish(EventSubscriptionChecked, "linked")
- }
- return res, err
-}
-
-// UnlinkSubscriptionAccount removes an account from a subscription.
-func (b *Backend) UnlinkSubscriptionAccount(subID, siteID, uid string) (subscription.Subscription, error) {
- if err := b.requireAnyLogin(); err != nil {
- return subscription.Subscription{}, err
- }
- res, err := b.subs.Unlink(subID, siteID, uid)
- if err == nil {
- b.pruneAccountAvatars()
- b.events.Publish(EventSubscriptionChecked, "unlinked")
- }
- return res, err
-}
-
-// MoveSubscriptionAccount atomically moves an account from its current subscription to toSubID.
-func (b *Backend) MoveSubscriptionAccount(siteID, uid, toSubID string) (subscription.Subscription, error) {
- if err := b.requireAnyLogin(); err != nil {
- return subscription.Subscription{}, err
- }
- res, err := b.subs.Move(siteID, uid, toSubID)
- if err == nil {
- b.events.Publish(EventSubscriptionChecked, "moved")
- }
- return res, err
-}
-
-// SetSubscriptionRules updates per-subscription rules and manages AutoCache.Since.
-func (b *Backend) SetSubscriptionRules(subID string, rules subscription.SubRules) (subscription.Subscription, error) {
- if err := b.requireAnyLogin(); err != nil {
- return subscription.Subscription{}, err
- }
- res, err := b.subs.SetRules(subID, rules)
- if err == nil {
- b.events.Publish(EventSubscriptionChecked, "rules_updated")
- }
- return res, err
-}
-
-// ListCacheRules returns the shared cache rules, the built-in one first.
-func (b *Backend) ListCacheRules() []subscription.CacheRule {
- return b.subs.ListRules()
-}
-
-// SaveCacheRule creates or edits a shared rule and applies it to every subscription that uses it.
-func (b *Backend) SaveCacheRule(rule subscription.CacheRule) (subscription.CacheRule, error) {
- if err := b.requireAnyLogin(); err != nil {
- return subscription.CacheRule{}, err
- }
- res, err := b.subs.SaveRule(rule)
- if err == nil {
- b.events.Publish(EventSubscriptionChecked, "rules_updated")
- }
- return res, err
-}
-
-// DeleteCacheRule removes a shared rule; its subscriptions use the default.
-func (b *Backend) DeleteCacheRule(id string) error {
- if err := b.requireAnyLogin(); err != nil {
- return err
- }
- err := b.subs.DeleteRule(id)
- if err == nil {
- b.events.Publish(EventSubscriptionChecked, "rules_updated")
- }
- return err
-}
-
-// SetSubscriptionRule makes a subscription use a shared rule.
-func (b *Backend) SetSubscriptionRule(subID, ruleID string) (subscription.Subscription, error) {
- if err := b.requireAnyLogin(); err != nil {
- return subscription.Subscription{}, err
- }
- res, err := b.subs.SetSubscriptionRule(subID, ruleID)
- if err == nil {
- b.events.Publish(EventSubscriptionChecked, "rules_updated")
- }
- return res, err
-}
-
-// SetSubscriptionsRule assigns a shared rule to the selected subscriptions in one batch;
-// unselected subscriptions that previously used a non-default rule fall back to DefaultRuleID.
-func (b *Backend) SetSubscriptionsRule(ruleID string, subIDs []string) error {
- if err := b.requireAnyLogin(); err != nil {
- return err
- }
- err := b.subs.SetSubscriptionsRule(ruleID, subIDs)
- if err == nil {
- b.events.Publish(EventSubscriptionChecked, "rules_updated")
- }
- return err
-}
-
-// PreviewAccount resolves a Bilibili or Douyin account input and checks whether it is already owned by a subscription.
-func (b *Backend) PreviewAccount(ctx context.Context, input string) (subscription.AccountRef, *subscription.Subscription, error) {
- if err := b.requireAnyLogin(); err != nil {
- return subscription.AccountRef{}, nil, err
- }
- siteID, normalized, err := b.registry.DetectSite(input)
- if err != nil {
- return subscription.AccountRef{}, nil, err
- }
- if err := b.requireSiteLogin(siteID); err != nil {
- return subscription.AccountRef{}, nil, err
- }
-
- if siteID == site.Douyin {
- target, rErr := b.douyin.ResolveLink(ctx, normalized)
- if rErr != nil {
- return subscription.AccountRef{}, nil, rErr
- }
- var secUID string
- switch target.Kind {
- case "user":
- secUID = firstNonEmpty(target.SecUID, target.ID)
- case "live":
- lv, lErr := b.DouyinLive(ctx, firstNonEmpty(target.WebRID, target.ID))
- if lErr != nil {
- return subscription.AccountRef{}, nil, lErr
- }
- secUID = lv.OwnerSecUID
- default:
- return subscription.AccountRef{}, nil, &site.Error{
- Site: site.Douyin,
- Kind: site.ErrKindBadRequest,
- Message: "请粘贴抖音用户主页链接、分享文本或 sec_uid",
- }
- }
- uv, uErr := b.DouyinUser(ctx, secUID)
- if uErr != nil {
- return subscription.AccountRef{}, nil, uErr
- }
- acc := subscription.AccountRef{
- Site: string(site.Douyin),
- UID: uv.SecUID,
- UniqueID: uv.UniqueID,
- WebRID: uv.WebRID,
- Name: uv.Nickname,
- Face: uv.AvatarURL,
- AddedAt: time.Now().UTC().Format(time.RFC3339),
- }
- return b.subs.PreviewResolvedAccount(acc)
- }
-
- target, err := b.bili.ResolveLink(ctx, normalized)
- if err != nil {
- return subscription.AccountRef{}, nil, err
- }
- if target.Kind != "user" {
- return subscription.AccountRef{}, nil, fmt.Errorf("请粘贴用户主页链接或 UID")
- }
- card, err := b.bili.UserCard(ctx, target.Mid)
- if err != nil {
- return subscription.AccountRef{}, nil, err
- }
- uidStr := fmt.Sprintf("%d", card.Mid)
- acc := subscription.AccountRef{
- Site: "bilibili",
- UID: uidStr,
- Name: card.Name,
- Face: card.Face,
- AddedAt: time.Now().UTC().Format(time.RFC3339),
- }
- if owner, owned := b.subs.OwnerOf("bilibili", uidStr); owned {
- return acc, &owner, nil
- }
- return acc, nil, nil
-}
-
-// OwnerOfAccount returns the subscription owning (site, uid), if any.
-func (b *Backend) OwnerOfAccount(siteID, uid string) (subscription.Subscription, bool) {
- if b.requireAnyLogin() != nil {
- return subscription.Subscription{}, false
- }
- return b.subs.OwnerOf(siteID, uid)
-}
-
-// ListSubscriptionUpdates returns discovered update items for a subscription.
-func (b *Backend) ListSubscriptionUpdates(subID string) ([]subscription.UpdateItem, error) {
- if err := b.requireAnyLogin(); err != nil {
- return nil, err
- }
- return b.subs.ListUpdates(subID)
-}
-
-// DeleteSubscription removes a creator subscription.
-func (b *Backend) DeleteSubscription(subIDOrMid string) error {
- if err := b.requireAnyLogin(); err != nil {
- return err
- }
- err := b.subs.Delete(subIDOrMid)
- if err == nil {
- b.pruneAccountAvatars()
- b.events.Publish(EventSubscriptionChecked, "deleted")
- }
- return err
-}
-
-// CheckSubscriptionsNow triggers an immediate incremental check for targetMid (or 0 for all enabled).
-func (b *Backend) CheckSubscriptionsNow(ctx context.Context, targetMid int64) (subscription.CheckSummary, error) {
- if err := b.requireAnyLogin(); err != nil {
- return subscription.CheckSummary{}, err
- }
- if targetMid > 0 {
- if err := b.requireSiteLogin(site.Bilibili); err != nil {
- return subscription.CheckSummary{}, err
- }
- }
- return b.subs.CheckNow(ctx, targetMid)
-}
-
-// ExportOPML writes all subscriptions as an OPML 2.0 XML file to path.
-func (b *Backend) ExportOPML(path string) error {
- if err := b.requireAnyLogin(); err != nil {
- return err
- }
- subs, err := b.subs.List()
- if err != nil {
- return err
- }
- xmlBytes, err := subscription.ExportOPML(subs, time.Now())
- if err != nil {
- return err
- }
- return storage.WriteFileAtomic(path, xmlBytes, 0o600)
-}
-
-// ImportOPML imports creator subscriptions from an OPML 2.0 XML file at path.
-func (b *Backend) ImportOPML(path string) (int, error) {
- if err := b.requireAnyLogin(); err != nil {
- return 0, err
- }
- raw, err := os.ReadFile(path)
- if err != nil {
- return 0, err
- }
- creators, err := subscription.ParseOPML(raw)
- if err != nil {
- return 0, err
- }
- users := make([]bilibili.FollowingUser, 0, len(creators))
- for _, c := range creators {
- users = append(users, bilibili.FollowingUser{
- Mid: c.Mid,
- Uname: c.Uname,
- })
- }
- n, err := b.subs.ImportCreators(users, "both", "inherit", true, false)
- if err == nil {
- b.events.Publish(EventSubscriptionChecked, "opml_imported")
- }
- return n, err
-}
-
-// RelationTags returns the logged-in user's Bilibili following groups.
-func (b *Backend) RelationTags(ctx context.Context) ([]bilibili.RelationTag, error) {
- if err := b.requireSiteLogin(site.Bilibili); err != nil {
- return nil, err
- }
- return b.bili.RelationTags(ctx)
-}
-
-// RelationFollowings returns a page of Bilibili followings (either for a specific tagID > 0 or all followings when tagID == 0).
-func (b *Backend) RelationFollowings(ctx context.Context, tagID int64, pn, ps int) ([]bilibili.FollowingUser, error) {
- if err := b.requireSiteLogin(site.Bilibili); err != nil {
- return nil, err
- }
- if tagID != 0 {
- mid := b.cred.Status().Mid
- return b.bili.RelationTagUsers(ctx, mid, tagID, pn, ps)
- }
- page, err := b.bili.RelationFollowings(ctx, 0, pn, ps)
- if err != nil {
- return nil, err
- }
- return page.Items, nil
-}
-
-// ImportCreators imports selected Bilibili creators into subscriptions idempotently.
-func (b *Backend) ImportCreators(users []bilibili.FollowingUser, scope, autoCache string, liveNotify, liveAutoRecord bool) (int, error) {
- if err := b.requireSiteLogin(site.Bilibili); err != nil {
- return 0, err
- }
- n, err := b.subs.ImportCreators(users, scope, autoCache, liveNotify, liveAutoRecord)
- if err == nil {
- b.events.Publish(EventSubscriptionChecked, "imported")
- }
- return n, err
-}
-
-// ListLiveRooms returns the current live status and recording state of all Bilibili rooms.
-func (b *Backend) ListLiveRooms() []live.RoomState {
- if b.requireAnyLogin() != nil {
- return nil
- }
- return b.live.ListRooms()
-}
-
-// PollLiveNow triggers an immediate live status batch poll.
-func (b *Backend) PollLiveNow(ctx context.Context) ([]live.RoomState, error) {
- if err := b.requireAnyLogin(); err != nil {
- return nil, err
- }
- return b.live.PollNow(ctx)
-}
-
-// OpenLiveRoomInBrowser opens a Bilibili live room in the external browser via Desktop.
-func (b *Backend) OpenLiveRoomInBrowser(roomID int64) error {
- if err := b.requireAnyLogin(); err != nil {
- return err
- }
- if roomID <= 0 {
- return fmt.Errorf("service: invalid roomID %d", roomID)
- }
- return b.desktop.OpenExternalURL(fmt.Sprintf("https://live.bilibili.com/%d", roomID))
-}
-
-// StartLiveRecording starts recording a Bilibili live room.
-func (b *Backend) StartLiveRecording(ctx context.Context, roomID int64) (live.RoomState, error) {
- if err := b.requireSiteLogin(site.Bilibili); err != nil {
- return live.RoomState{}, err
- }
- return b.live.StartRecording(ctx, roomID)
-}
-
-// StopLiveRecording stops an active Bilibili live room recording and finalizes item.json.
-func (b *Backend) StopLiveRecording(roomID int64) (live.RoomState, error) {
- if err := b.requireAnyLogin(); err != nil {
- return live.RoomState{}, err
- }
- return b.live.StopRecording(roomID)
-}
-
-// OpenItemFolder opens or reveals a cached item's folder on disk via Desktop.
-func (b *Backend) OpenItemFolder(itemKey string) error {
- if err := b.requireAnyLogin(); err != nil {
- return err
- }
- item, ok, err := b.lib.GetItem(itemKey)
- if err != nil {
- return err
- }
- if !ok || item.ItemDir == "" {
- return fmt.Errorf("service: item folder not found for %s", itemKey)
- }
- return b.desktop.OpenPath(item.ItemDir)
-}
-
-// OpenDataFolder opens the DataDir, CacheDir, or LogsDir via Desktop.
-func (b *Backend) OpenDataFolder(target string) error {
- switch target {
- case "cache":
- return b.desktop.OpenPath(b.lib.CacheDir())
- case "logs":
- return b.desktop.OpenPath(b.loc.LogsDir)
- default:
- return b.desktop.OpenPath(b.loc.DataDir)
- }
-}
-
-// DiagnosticsSnapshot returns a sanitized runtime summary without any secret values.
-func (b *Backend) DiagnosticsSnapshot() Diagnostics {
- stats, indexErr := b.lib.Statistics()
- tasks, tasksErr := b.dl.ListTasks()
- subs, subsErr := b.subs.List()
- rooms := b.live.ListRooms()
-
- b.logMu.Lock()
- corrupt := append([]string(nil), b.corruptFiles...)
- b.logMu.Unlock()
-
- indexStatus := fmt.Sprintf("正常(已索引 %d 项)", stats.Items)
- if indexErr != nil {
- indexStatus = "读取索引失败:" + b.sanitizeLogLine(indexErr.Error())
- } else if len(corrupt) > 0 {
- indexStatus = fmt.Sprintf("已保留 %d 个损坏文件,当前已索引 %d 项", len(corrupt), stats.Items)
- }
- subCheckStatus := fmt.Sprintf("空闲(共 %d 个订阅)", len(subs))
- if b.subs != nil {
- if progress, checking := b.subs.CheckProgress(); checking {
- subCheckStatus = fmt.Sprintf("正在检查更新 %d / %d", progress.CheckedCreators, progress.TotalCreators)
- } else if inBackoff, until := b.subs.IsInBackoff(); inBackoff {
- subCheckStatus = fmt.Sprintf("风控退避中(暂停至 %s)", until.Local().Format("15:04"))
- }
- }
- if subsErr != nil {
- subCheckStatus = "读取订阅失败:" + b.sanitizeLogLine(subsErr.Error())
- }
- var runningTasks, queuedTasks, autoTasks int
- for _, t := range tasks {
- switch t.Status {
- case "running":
- runningTasks++
- case "queued":
- queuedTasks++
- }
- if t.Source == "auto" && (t.Status == "running" || t.Status == "queued") {
- autoTasks++
- }
- }
- autoCacheStatus := "空闲"
- if runningTasks > 0 || queuedTasks > 0 {
- autoCacheStatus = fmt.Sprintf("进行中 %d · 排队 %d(自动缓存 %d)", runningTasks, queuedTasks, autoTasks)
- }
- if tasksErr != nil {
- autoCacheStatus = "读取任务失败:" + b.sanitizeLogLine(tasksErr.Error())
- }
- var recordingRooms, liveRooms int
- for _, r := range rooms {
- if r.LiveStatus == 1 {
- liveRooms++
- }
- if r.Recording {
- recordingRooms++
- }
- }
- liveRecordStatus := "空闲"
- if recordingRooms > 0 || liveRooms > 0 {
- liveRecordStatus = fmt.Sprintf("录制中 %d 路 · 直播中 %d 个房间", recordingRooms, liveRooms)
- }
-
- build := appdirs.BuildInfo()
- return Diagnostics{
- Version: build.Version,
- Commit: build.Commit,
- BuildTime: build.BuildTime,
- AppName: b.loc.AppName,
- DisplayName: b.loc.DisplayName,
- Channel: b.loc.Channel,
- Mode: b.loc.Mode,
- DataDir: b.loc.DataDir,
- CacheDir: b.lib.CacheDir(),
- LogsDir: b.loc.LogsDir,
- Account: b.cred.Status(),
- Accounts: b.Statuses(),
- LibraryCount: stats.Items,
- TaskCount: len(tasks),
- SubscriptionCnt: len(subs),
- LiveRoomCount: len(rooms),
- IndexStatus: indexStatus,
- SubscriptionCheckStatus: subCheckStatus,
- AutoCacheStatus: autoCacheStatus,
- LiveRecordStatus: liveRecordStatus,
- CorruptRecovered: corrupt,
- RecentEvents: b.events.Recent(),
- }
-}
-
-const runtimeLogReadLimit = 1 << 20
-
-// RecentLogs reads at most 1 MiB from the end of trace.log and returns at most
-// 500 sanitized lines. An incomplete oldest line is discarded.
-func (b *Backend) RecentLogs(maxLines int) ([]string, error) {
- if maxLines <= 0 || maxLines > 500 {
- maxLines = 500
- }
- if b.logPath == "" {
- return nil, nil
- }
- b.logMu.Lock()
- defer b.logMu.Unlock()
- f, err := os.Open(b.logPath)
- if err != nil {
- if os.IsNotExist(err) {
- return nil, nil
- }
- return nil, err
- }
- defer f.Close()
- info, err := f.Stat()
- if err != nil {
- return nil, err
- }
- if !info.Mode().IsRegular() {
- return nil, fmt.Errorf("运行日志不是普通文件")
- }
- start := max(int64(0), info.Size()-runtimeLogReadLimit)
- raw := make([]byte, info.Size()-start)
- n, err := f.ReadAt(raw, start)
- if err != nil && !errors.Is(err, io.EOF) {
- return nil, err
- }
- raw = raw[:n]
- if start > 0 {
- if newline := bytes.IndexByte(raw, '\n'); newline >= 0 {
- raw = raw[newline+1:]
- } else {
- raw = nil
- }
- }
- rawLines := strings.Split(strings.ReplaceAll(string(raw), "\r\n", "\n"), "\n")
- var out []string
- for _, ln := range rawLines {
- ln = strings.TrimSpace(ln)
- if ln == "" {
- continue
- }
- out = append(out, b.sanitizeLogLine(ln))
- }
- if len(out) > maxLines {
- out = out[len(out)-maxLines:]
- }
- return out, nil
-}
-
-var runtimeLogSecretField = regexp.MustCompile(`(?i)\b(?:cookie|authorization|sessdata|bili_jct|dedeuserid|dedeuserid__ckmd5|sid|ac_time_value|refresh_token|pending_old_refresh_token|access_key|auth_key|w_rid|upsig|wssecret|wstime|deadline|bwsv|sessionid|sessionid_ss|sid_tt|uid_tt|uid_tt_ss|sid_guard|odin_tt|passport_csrf_token|passport_csrf_token_default|ttwid|uifid|uifid_temp|mstoken|s_v_web_id|__ac_nonce|__ac_signature|a_bogus|x-bogus|x-signature|x-secsdk-web-signature|x-secsdk-csrf-token)["'\\]*\s*[=:]|[?&]e=`)
-var runtimeLogURL = regexp.MustCompile(`(?i)https?://[^\s"<>]+`)
-var runtimeLogPercentEscape = regexp.MustCompile(`(?i)%[0-9a-f]{2}`)
-
-func (b *Backend) redactStoredSecrets(s string) string {
- if b.credMgr != nil {
- return b.credMgr.RedactString(s)
- }
- if b.cred != nil {
- return b.cred.RedactString(s)
- }
- return s
-}
-
-func (b *Backend) sanitizeLogLine(msg string) string {
- sanitized := b.redactStoredSecrets(msg)
- decoded := sanitized
- for i := 0; i < 3; i++ {
- if runtimeLogSecretField.MatchString(decoded) {
- return "[REDACTED_LOG_LINE]"
- }
- for _, rawURL := range runtimeLogURL.FindAllString(decoded, -1) {
- if strings.Contains(rawURL, "?") {
- return "[REDACTED_LOG_LINE]"
- }
- }
- if b.redactStoredSecrets(decoded) != decoded {
- return "[REDACTED_LOG_LINE]"
- }
- next, err := url.QueryUnescape(decoded)
- if err != nil {
- // A progress value such as "50%" must not prevent redaction of an
- // encoded credential elsewhere on the same line.
- next = runtimeLogPercentEscape.ReplaceAllStringFunc(decoded, func(escape string) string {
- value, _ := url.QueryUnescape(escape)
- return value
- })
- }
- if next == decoded {
- break
- }
- decoded = next
- }
- return sanitized
-}
-
-// Logf writes an informational line to trace.log.
-func (b *Backend) Logf(format string, args ...any) {
- b.logInfo(fmt.Sprintf(format, args...))
-}
-
-func (b *Backend) logInfo(msg string) {
- b.writeLogLine("INFO", msg)
-}
-
-func (b *Backend) logError(op string, err error) {
- if err == nil {
- return
- }
- b.writeLogLine("ERROR", op+": "+err.Error()+siteErrorDetail(err))
-}
-
-// LogUserError logs an error the UI displayed. The same line within a minute
-// is written once, so a page that keeps failing does not flood the log.
-func (b *Backend) LogUserError(err error) {
- if err == nil {
- return
- }
- line := "ui: " + err.Error() + siteErrorDetail(err)
- now := time.Now()
- b.logMu.Lock()
- repeated := line == b.lastUserError && now.Sub(b.lastUserErrorAt) < time.Minute
- if !repeated {
- b.lastUserError, b.lastUserErrorAt = line, now
- }
- b.logMu.Unlock()
- if !repeated {
- b.writeLogLine("ERROR", line)
- }
-}
-
-// siteErrorDetail adds what the user-facing message leaves out: the endpoint
-// path (never its query, which can carry signatures) and, for a response that
-// did not match the expected fields, the decoder's reason (field and type).
-func siteErrorDetail(err error) string {
- var se *site.Error
- if !errors.As(err, &se) {
- return ""
- }
- var detail string
- if se.Endpoint != "" {
- if u, perr := url.Parse(se.Endpoint); perr == nil && u.Path != "" {
- detail += " endpoint=" + u.Path
- }
- }
- if se.Kind == site.ErrKindSchemaChanged && se.Err != nil {
- cause := []rune(se.Err.Error())
- if len(cause) > 240 { // Go prints a whole anonymous struct type here
- cause = append(cause[:240], '…')
- }
- detail += " cause=" + string(cause)
- }
- return detail
-}
-
-func (b *Backend) writeLogLine(level, msg string) {
- if b.logPath == "" {
- return
- }
- sanitized := b.sanitizeLogLine(msg)
- line := fmt.Sprintf("%s [%s] %s\n", time.Now().UTC().Format(time.RFC3339), level, sanitized)
-
- b.logMu.Lock()
- defer b.logMu.Unlock()
- f, err := os.OpenFile(b.logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
- if err != nil {
- return
- }
- _, _ = f.WriteString(line)
- _ = f.Close()
-}
-
-// FetchImage fetches a whitelisted Bilibili or Douyin cover/avatar/note image without sending Cookie.
-func (b *Backend) FetchImage(ctx context.Context, rawURL string) ([]byte, error) {
- if err := b.requireAnyLogin(); err != nil {
- return nil, err
- }
- imgSite := b.detectImageSite(rawURL)
- if err := b.requireSiteLogin(imgSite); err != nil {
- return nil, err
- }
- if imgSite == site.Douyin {
- data, _, err := b.douyin.FetchImage(ctx, rawURL)
- return data, err
- }
- return b.bili.FetchImage(ctx, rawURL)
-}
-
-func (b *Backend) RemoveHistory(kind, id string) error {
- if err := b.requireAnyLogin(); err != nil {
- return err
- }
- return b.history.Remove(kind, id)
-}
-
-func (b *Backend) CheckSubscription(ctx context.Context, subID string) (subscription.CheckSummary, error) {
- if err := b.requireAnyLogin(); err != nil {
- return subscription.CheckSummary{}, err
- }
- return b.subs.CheckSubscription(ctx, subID)
-}
-
-// CheckAccount checks one account of a subscription for updates at once.
-func (b *Backend) CheckAccount(ctx context.Context, subID, siteName, uid string) (subscription.CheckSummary, error) {
- if err := b.requireSiteLogin(site.ID(siteName)); err != nil {
- return subscription.CheckSummary{}, err
- }
- return b.subs.CheckAccount(ctx, subID, siteName, uid)
-}
-
-func (b *Backend) CancelSubscriptionCheck() { b.subs.CancelCheck() }
-
-func firstNonEmpty(values ...string) string {
- for _, v := range values {
- if strings.TrimSpace(v) != "" {
- return v
- }
- }
- return ""
-}
-
-// taskStatusLog remembers the last logged status of each download task.
-// Progress updates arrive about once a second while a task runs; the log
-// records only status changes so it stays readable (2026-11-15 log review).
-type taskStatusLog struct {
- mu sync.Mutex
- last map[string]string
-}
-
-func newTaskStatusLog() *taskStatusLog {
- return &taskStatusLog{last: map[string]string{}}
-}
-
-// changed reports whether status differs from the last one logged for id.
-func (l *taskStatusLog) changed(id, status string) bool {
- l.mu.Lock()
- defer l.mu.Unlock()
- if l.last[id] == status {
- return false
- }
- if status == "completed" || status == "canceled" {
- delete(l.last, id)
- } else {
- l.last[id] = status
- }
- return true
-}
-
-// firstDouyinUserWorks loads the first page of a user's works for the user
-// page. A private account still shows its works to the followers it approved,
-// which the signed-in account may be (the web page then lists them, 2026-11-16
-// feedback), so the works are always asked for: when they come back the page
-// shows them (IsPrivate is cleared, PrivateVisible set); otherwise it says the
-// account is private, without an error.
-func (b *Backend) firstDouyinUserWorks(ctx context.Context, uv *DouyinUserView) (*DouyinUserWorksPage, string) {
- wp, err := b.DouyinUserWorks(ctx, uv.SecUID, "")
- if uv.IsPrivate {
- if err == nil && wp != nil && len(wp.Works) > 0 {
- uv.IsPrivate = false
- uv.PrivateVisible = true
- return wp, ""
- }
- // Only an empty list or a refusal means the works are not visible;
- // risk control, rate limits, an expired login or the network are
- // reported as they are, with a retry.
- if err == nil || site.IsKind(err, site.ErrKindForbidden) || site.IsKind(err, site.ErrKindUnavailable) {
- return nil, ""
- }
- return nil, err.Error()
- }
- if err != nil {
- return nil, err.Error()
+func samePath(a, b string) bool {
+ if runtime.GOOS == "windows" {
+ return strings.EqualFold(a, b)
}
- return wp, ""
+ return a == b
}
diff --git a/internal/service/batch_cache.go b/internal/service/batch_cache.go
index 9a2bc6a..932c56e 100644
--- a/internal/service/batch_cache.go
+++ b/internal/service/batch_cache.go
@@ -15,10 +15,11 @@ import (
type queuePartEnqueuer func(ctx context.Context) ([]string, error)
type queueEnqueued struct {
- taskIDs []string
- itemKey string
- title string
- nextParts []queuePartEnqueuer
+ taskIDs []string
+ itemKey string
+ title string
+ nextParts []queuePartEnqueuer
+ pendingPages []int
}
// queueCandidate is one post from a creator's user page list that the background
@@ -81,7 +82,7 @@ func cacheQueueListLabel(siteID, list string) string {
}
func (b *Backend) buildQueueLoadedAndPager(siteID site.ID, list, normUser string, req CacheQueueRequest) ([]queueCandidate, queuePager, error) {
- pager, err := b.buildQueuePager(siteID, list, normUser)
+ pager, err := b.buildQueuePager(siteID, list, normUser, req.UserName)
if err != nil {
return nil, nil, err
}
@@ -97,13 +98,15 @@ func (b *Backend) buildQueueLoadedAndPager(siteID site.ID, list, normUser string
}
case siteID == site.Douyin:
for _, w := range req.Works {
- loaded = append(loaded, b.workQueueCandidate(w))
+ loaded = append(loaded, b.workQueueCandidate(w, normUser, req.UserName))
}
}
return loaded, pager, nil
}
-func (b *Backend) buildQueuePager(siteID site.ID, list, normUser string) (queuePager, error) {
+// buildQueuePager pages the queue's list; userName is the account's name,
+// recorded on co-creations cached for them.
+func (b *Backend) buildQueuePager(siteID site.ID, list, normUser, userName string) (queuePager, error) {
switch {
case siteID == site.Bilibili && list == "videos":
mid, err := strconv.ParseInt(normUser, 10, 64)
@@ -157,9 +160,16 @@ func (b *Backend) buildQueuePager(siteID site.ID, list, normUser string) (queueP
if err != nil {
return nil, "", false, err
}
+ if res.UncertainEmpty {
+ return nil, "", false, &site.Error{
+ Site: site.Douyin,
+ Kind: site.ErrKindRiskControl,
+ Message: firstNonEmpty(res.UncertainReason, "抖音返回空作品列表,可能被拦截或登录已失效"),
+ }
+ }
out := make([]queueCandidate, 0, len(res.Works))
for _, w := range res.Works {
- out = append(out, b.workQueueCandidate(w))
+ out = append(out, b.workQueueCandidate(w, secUID, userName))
}
return out, res.NextCursor, res.HasMore && res.NextCursor != "", nil
}, nil
@@ -214,39 +224,60 @@ func (b *Backend) videoQueueCandidate(bvid, fallbackTitle string, forMid int64)
ids = append(ids, t.TaskID)
}
var nextParts []queuePartEnqueuer
+ var pendingPages []int
if len(vd.Pages) > 1 && b.GetSettings().Download.MultiPart != "first" {
for _, vp := range vd.Pages[1:] {
pageNum := vp.Page
- nextParts = append(nextParts, func(partCtx context.Context) ([]string, error) {
- ptasks, perr := b.EnqueueVideoCache(partCtx, download.VideoEnqueueRequest{
- BVID: cleanID,
- Detail: &detailCopy,
- Pages: []int{pageNum},
- Source: "queue",
- ForMid: forMid,
- })
- if perr != nil {
- return nil, perr
- }
- var pids []string
- for _, pt := range ptasks {
- pids = append(pids, pt.TaskID)
- }
- return pids, nil
- })
+ pendingPages = append(pendingPages, pageNum)
+ nextParts = append(nextParts, b.makeBilibiliPartEnqueuer(cleanID, &detailCopy, pageNum, forMid))
}
}
title := firstNonEmpty(vd.Title, fallbackTitle, cleanID)
return queueEnqueued{
- taskIDs: ids,
- itemKey: itemKey,
- title: trimQueueSummaryTitle(title),
- nextParts: nextParts,
+ taskIDs: ids,
+ itemKey: itemKey,
+ title: trimQueueSummaryTitle(title),
+ nextParts: nextParts,
+ pendingPages: pendingPages,
}, nil
},
}
}
+func (b *Backend) makeBilibiliPartEnqueuer(bvid string, detail *bilibili.VideoDetail, pageNum int, forMid int64) queuePartEnqueuer {
+ return func(partCtx context.Context) ([]string, error) {
+ ptasks, perr := b.EnqueueVideoCache(partCtx, download.VideoEnqueueRequest{
+ BVID: bvid,
+ Detail: detail,
+ Pages: []int{pageNum},
+ Source: "queue",
+ ForMid: forMid,
+ })
+ if perr != nil {
+ return nil, perr
+ }
+ pids := make([]string, 0, len(ptasks))
+ for _, pt := range ptasks {
+ pids = append(pids, pt.TaskID)
+ }
+ return pids, nil
+ }
+}
+
+func (b *Backend) buildBilibiliPartEnqueuers(bvid string, pages []int, forMid int64) []queuePartEnqueuer {
+ bvid = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(bvid), "bilibili:video:"))
+ if bvid == "" || len(pages) == 0 {
+ return nil
+ }
+ out := make([]queuePartEnqueuer, 0, len(pages))
+ for _, p := range pages {
+ if p > 0 {
+ out = append(out, b.makeBilibiliPartEnqueuer(bvid, nil, p, forMid))
+ }
+ }
+ return out
+}
+
func (b *Backend) dynamicQueueCandidate(d bilibili.DynamicItem) queueCandidate {
item := d
cleanID := strings.TrimSpace(d.ID)
@@ -256,8 +287,9 @@ func (b *Backend) dynamicQueueCandidate(d bilibili.DynamicItem) queueCandidate {
}
title := trimQueueSummaryTitle(firstNonEmpty(d.Title, d.Text, cleanID))
return queueCandidate{
- key: itemKey,
- title: title,
+ key: itemKey,
+ title: title,
+ uncacheable: strings.EqualFold(strings.TrimSpace(d.Type), "DYNAMIC_TYPE_LIVE_RCMD"),
enqueue: func(ctx context.Context) (queueEnqueued, error) {
t, err := b.EnqueueDynamicCache(ctx, download.DynamicEnqueueRequest{
DynamicID: item.ID,
@@ -276,7 +308,9 @@ func (b *Backend) dynamicQueueCandidate(d bilibili.DynamicItem) queueCandidate {
}
}
-func (b *Backend) workQueueCandidate(w DouyinWorkCardDTO) queueCandidate {
+// workQueueCandidate enqueues one work from account forUID's works list; a
+// co-creation by someone else is stored under forUID's folder (DEC-063).
+func (b *Backend) workQueueCandidate(w DouyinWorkCardDTO, forUID, forName string) queueCandidate {
id := strings.TrimSpace(w.ID)
key := w.CacheKey
if key == "" && id != "" {
@@ -288,7 +322,7 @@ func (b *Backend) workQueueCandidate(w DouyinWorkCardDTO) queueCandidate {
title: title,
uncacheable: w.Uncacheable || w.Kind == "unsupported",
enqueue: func(ctx context.Context) (queueEnqueued, error) {
- t, err := b.enqueueDouyinWorkWithSource(ctx, id, "queue")
+ t, err := b.enqueueDouyinWorkWithSource(ctx, id, "queue", forUID, forName)
if err != nil {
return queueEnqueued{}, err
}
diff --git a/internal/service/batch_cache_test.go b/internal/service/batch_cache_test.go
index 2831465..30de052 100644
--- a/internal/service/batch_cache_test.go
+++ b/internal/service/batch_cache_test.go
@@ -404,3 +404,32 @@ func TestEnqueueCacheQueueValidatesRequestAndLoadedList(t *testing.T) {
t.Fatalf("loaded-only completion mismatch: %+v", done)
}
}
+
+func TestDynamicQueueCandidateSkipsLiveRcmd(t *testing.T) {
+ clock := newFakeQueueClock(time.Date(2026, 5, 1, 10, 0, 0, 0, time.UTC))
+ b := newBatchTestBackend(t, clock)
+
+ liveCand := b.dynamicQueueCandidate(bilibili.DynamicItem{
+ ID: "1272800651797069830",
+ Type: "DYNAMIC_TYPE_LIVE_RCMD",
+ Text: "暂不支持完整展示的动态类型 (DYNAMIC_TYPE_LIVE_RCMD)",
+ })
+ if !liveCand.uncacheable {
+ t.Fatalf("DYNAMIC_TYPE_LIVE_RCMD should be marked uncacheable")
+ }
+
+ liveCandLower := b.dynamicQueueCandidate(bilibili.DynamicItem{
+ ID: "1272800651797069831",
+ Type: " dynamic_type_live_rcmd ",
+ })
+ if !liveCandLower.uncacheable {
+ t.Fatalf("lowercase/padded DYNAMIC_TYPE_LIVE_RCMD should be marked uncacheable")
+ }
+
+ for _, typ := range []string{"DYNAMIC_TYPE_DRAW", "DYNAMIC_TYPE_FORWARD", "DYNAMIC_TYPE_AV", "DYNAMIC_TYPE_WORD"} {
+ cand := b.dynamicQueueCandidate(bilibili.DynamicItem{ID: "1001", Type: typ})
+ if cand.uncacheable {
+ t.Fatalf("type %s should remain cacheable", typ)
+ }
+ }
+}
diff --git a/internal/service/browsing.go b/internal/service/browsing.go
deleted file mode 100644
index de47a03..0000000
--- a/internal/service/browsing.go
+++ /dev/null
@@ -1,1005 +0,0 @@
-package service
-
-import (
- "context"
- "crypto/sha256"
- "fmt"
- "net/url"
- "os"
- "path/filepath"
- "strconv"
- "strings"
- "time"
-
- "github.com/chialecode/trace/internal/credential"
- "github.com/chialecode/trace/internal/download"
- "github.com/chialecode/trace/internal/library"
- "github.com/chialecode/trace/internal/live"
- "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/storage"
- "github.com/chialecode/trace/internal/subscription"
-)
-
-const maxPreviewMediaBytes = 64 * 1024 * 1024 // 64 MiB safety cap for uncached note BGM / clip preview
-
-// HasAnyLogin reports whether at least one supported site has an active credential.
-func (b *Backend) HasAnyLogin() bool {
- return (b.cred != nil && b.cred.HasActiveCredential()) ||
- (b.douyinCred != nil && b.douyinCred.HasActiveCredential())
-}
-
-func (b *Backend) requireAnyLogin() error {
- if b.HasAnyLogin() {
- return nil
- }
- return &site.Error{
- Kind: site.ErrKindAuthRequired,
- Message: "请先登录哔哩哔哩或抖音账号",
- }
-}
-
-func (b *Backend) requireSiteLogin(siteID site.ID) error {
- switch siteID {
- case site.Bilibili:
- if b.cred != nil && b.cred.HasActiveCredential() {
- return nil
- }
- return &site.Error{
- Site: site.Bilibili,
- Kind: site.ErrKindAuthRequired,
- Message: "请先登录哔哩哔哩账号",
- }
- case site.Douyin:
- if b.douyinCred != nil && b.douyinCred.HasActiveCredential() {
- return nil
- }
- return &site.Error{
- Site: site.Douyin,
- Kind: site.ErrKindAuthRequired,
- Message: "请先在设置中粘贴 Cookie 登录抖音",
- }
- default:
- return &site.Error{
- Site: siteID,
- Kind: site.ErrKindAuthRequired,
- Message: "请先登录对应站点账号",
- }
- }
-}
-
-// requireLogin preserves compatibility for local-only operations gated on >= 1 active site login.
-func (b *Backend) requireLogin() error {
- return b.requireAnyLogin()
-}
-
-func normalizeSiteID(raw string) (site.ID, error) {
- switch strings.ToLower(strings.TrimSpace(raw)) {
- case "", string(site.Bilibili):
- return site.Bilibili, nil
- case string(site.Douyin):
- return site.Douyin, nil
- default:
- return "", &site.Error{
- Kind: site.ErrKindBadRequest,
- Message: "不支持的站点标识: " + strings.TrimSpace(raw),
- }
- }
-}
-
-// Statuses returns desensitized credential status snapshots for all supported sites.
-func (b *Backend) Statuses() map[string]credential.Status {
- if b.credMgr == nil {
- return map[string]credential.Status{}
- }
- return b.credMgr.Statuses()
-}
-
-// StatusOf returns the desensitized credential status for a specific site ("bilibili" or "douyin").
-func (b *Backend) StatusOf(siteID string) credential.Status {
- if b.credMgr == nil {
- return credential.Status{}
- }
- return b.credMgr.Status(siteID)
-}
-
-// Renewal summarizes automatic session renewal availability and last-renewed state for siteID.
-func (b *Backend) Renewal(siteID string) RenewalStatus {
- id, err := normalizeSiteID(siteID)
- if err != nil {
- return RenewalStatus{Site: strings.TrimSpace(siteID), Available: false, Reason: err.Error()}
- }
- if id == site.Douyin {
- return RenewalStatus{
- Site: string(site.Douyin),
- Available: false,
- Reason: "不可用,粘贴的 Cookie 与浏览器共用会话;过期后请重新粘贴",
- }
- }
- st := b.cred.Status()
- if !st.LoggedIn {
- return RenewalStatus{
- Site: string(site.Bilibili),
- Available: false,
- Reason: "未登录",
- }
- }
- if st.Source == "qr" && st.HasRefreshToken {
- var lastErr string
- if st.State == "refresh_failed" {
- lastErr = st.Message
- }
- return RenewalStatus{
- Site: string(site.Bilibili),
- Available: true,
- LastRenewedAt: st.LastRenewedAt,
- LastError: lastErr,
- }
- }
- return RenewalStatus{
- Site: string(site.Bilibili),
- Available: false,
- Reason: "不可用:粘贴的 Cookie 与浏览器共用会话,续期会让浏览器那边掉线。过期后请重新粘贴,或改用扫码登录",
- LastRenewedAt: st.LastRenewedAt,
- }
-}
-
-// VerifySiteAccount verifies the stored credential for the specified site ("bilibili" or "douyin").
-func (b *Backend) VerifySiteAccount(ctx context.Context, siteID string) (credential.Status, error) {
- id, err := normalizeSiteID(siteID)
- if err != nil {
- return credential.Status{}, err
- }
- if id == site.Bilibili {
- return b.VerifyAccount(ctx)
- }
- st, vErr := b.douyin.VerifyCredential(ctx)
- if vErr != nil && site.IsKind(vErr, site.ErrKindAuthRequired) {
- b.pauseSiteActiveWork(site.Douyin, "auth_required", "抖音登录已失效,任务已暂停")
- }
- b.events.PublishSite(EventAccountChanged, string(site.Douyin), st.State)
- return st, vErr
-}
-
-// LoginWithCookie validates and imports a pasted Cookie for the target site ("bilibili" or "douyin").
-func (b *Backend) LoginWithCookie(ctx context.Context, siteID, rawCookie, rawRefreshToken string) (credential.Status, error) {
- id, err := normalizeSiteID(siteID)
- if err != nil {
- return credential.Status{}, err
- }
- if id == site.Bilibili {
- return b.ImportCookie(ctx, rawCookie, rawRefreshToken)
- }
- prevAuthPaused := b.snapshotAuthPausedQueueIDs(site.Douyin)
- prev := b.douyinCred.Status()
- st, lErr := b.douyin.LoginWithCookie(ctx, rawCookie)
- if lErr != nil {
- b.logError("LoginWithCookie.Douyin", lErr)
- return b.douyinCred.Status(), lErr
- }
- switched := prev.LoggedIn && prev.SecUID != "" && prev.SecUID != st.SecUID
- if switched {
- b.pauseSiteActiveWork(site.Douyin, "auth_required", "抖音登录账号已变更,任务已暂停")
- }
- if st.LoggedIn {
- if switched {
- b.resumeAuthPausedQueueIDs(site.Douyin, prevAuthPaused)
- } else if b.queue != nil {
- b.queue.resumeAuthPausedForSite(site.Douyin)
- }
- }
- b.logInfo(fmt.Sprintf("douyin cookie imported: state=%s uid=%s", st.State, firstNonEmpty(st.UniqueID, st.UID)))
- b.events.PublishSite(EventAccountChanged, string(site.Douyin), st.State)
- return st, nil
-}
-
-// LogoutSite pauses active work belonging ONLY to siteID and clears that site's stored credential.
-func (b *Backend) LogoutSite(siteID string) (credential.Status, error) {
- id, err := normalizeSiteID(siteID)
- if err != nil {
- return credential.Status{}, err
- }
- if id == site.Bilibili {
- return b.Logout()
- }
- b.pauseSiteActiveWork(site.Douyin, "auth_required", "已退出抖音登录,任务已暂停")
- lErr := b.douyin.LogoutCredential()
- st := b.douyinCred.Status()
- if lErr != nil {
- b.logError("LogoutSite.Douyin", lErr)
- } else {
- b.logInfo("douyin account logged out and credentials cleared")
- }
- b.events.PublishSite(EventAccountChanged, string(site.Douyin), st.State)
- return st, lErr
-}
-
-// Resolve dispatches user input via site.Registry after enforcing per-site login gates with zero pre-auth network requests.
-func (b *Backend) Resolve(ctx context.Context, rawInput string) (site.ResolveTarget, error) {
- if err := b.requireAnyLogin(); err != nil {
- return site.ResolveTarget{}, err
- }
- siteID, normalized, err := b.registry.DetectSite(rawInput)
- if err != nil {
- return site.ResolveTarget{}, err
- }
- if err := b.requireSiteLogin(siteID); err != nil {
- return site.ResolveTarget{}, err
- }
- res, ok := b.registry.Resolver(siteID)
- if !ok {
- return site.ResolveTarget{}, &site.Error{
- Site: siteID,
- Kind: site.ErrKindUnavailable,
- Unsupported: true,
- Message: fmt.Sprintf("当前尚未启用 %s 站点解析器", siteID.DisplayName()),
- }
- }
- target, err := res.Resolve(ctx, normalized)
- if err != nil {
- return target, err
- }
- if target.Site == "" {
- target.Site = siteID
- }
- return target, nil
-}
-
-func (b *Backend) preferredDouyinCodec() string {
- dl := b.settings.Get().Download
- for _, c := range dl.CodecOrder {
- switch strings.ToLower(strings.TrimSpace(c)) {
- case "hevc", "h265", "bytevc1":
- return "hevc"
- case "avc", "h264":
- return "avc"
- }
- }
- if strings.EqualFold(dl.PreferredVideoCodec, "hevc") {
- return "hevc"
- }
- return "avc"
-}
-
-// DouyinWork fetches and maps a single Douyin video or image/mixed note post.
-func (b *Backend) DouyinWork(ctx context.Context, awemeID string) (*DouyinWorkView, error) {
- if err := b.requireSiteLogin(site.Douyin); err != nil {
- return nil, err
- }
- detail, err := b.douyin.GetWorkDetail(ctx, awemeID, douyin.StreamSelectOptions{
- PreferredCodec: b.preferredDouyinCodec(),
- })
- if err != nil {
- b.logError("DouyinWork", err)
- return nil, err
- }
- var cached *library.ItemMetadata
- cacheKey := douyinCacheKeyForKind(detail.Kind, detail.ID)
- if cacheKey != "" {
- if item, ok, _ := b.lib.GetItem(cacheKey); ok {
- cached = &item
- }
- }
- if detail.Author.SecUID != "" && detail.Author.WebRID != "" {
- b.syncDouyinAccountWebRID(detail.Author.SecUID, detail.Author.WebRID)
- }
- return mapDouyinWorkView(detail, cached), nil
-}
-
-// DouyinUser fetches a Douyin creator's profile and maps optional live banner state.
-func (b *Backend) DouyinUser(ctx context.Context, secUID string) (*DouyinUserView, error) {
- if err := b.requireSiteLogin(site.Douyin); err != nil {
- return nil, err
- }
- targetSecUID := strings.TrimSpace(secUID)
- if targetSecUID == "" || strings.EqualFold(targetSecUID, "self") || targetSecUID == "/user/self" {
- targetSecUID = b.douyinCred.Status().SecUID
- if targetSecUID == "" {
- selfProf, sErr := b.douyin.GetSelfProfile(ctx)
- if sErr != nil {
- return nil, sErr
- }
- targetSecUID = selfProf.SecUID
- }
- }
- prof, err := b.douyin.GetUserProfile(ctx, targetSecUID)
- if err != nil {
- b.logError("DouyinUser", err)
- return nil, err
- }
- if b.subs != nil {
- _ = b.subs.UpdateAccountSnapshot(string(site.Douyin), prof.SecUID, prof.Nickname, prof.AvatarURL, prof.UniqueID)
- }
- b.recordAccountWorks(site.Douyin, prof.SecUID, prof.AwemeCount)
- if prof.WebRID != "" {
- b.syncDouyinAccountWebRID(prof.SecUID, prof.WebRID)
- }
- if b.live != nil && (prof.WebRID != "" || prof.RoomID != "") {
- b.live.ObserveAccountLiveHint(site.Douyin, prof.SecUID, prof.WebRID, prof.RoomID)
- }
- var liveState *LiveAccountState
- if prof.LiveStatus == 1 {
- st := LiveAccountState{
- Site: string(site.Douyin),
- AccountKey: formatAccountKey(site.Douyin, prof.SecUID),
- UID: prof.SecUID,
- RoomID: prof.RoomID,
- WebRID: prof.WebRID,
- Uname: prof.Nickname,
- Face: prof.AvatarURL,
- LiveStatus: 1,
- StatusText: "直播中",
- Transport: string(site.LiveTransportHTTPFLV),
- }
- if prof.RoomID != "" {
- st.RecordingKey = "douyin:live:" + prof.RoomID
- }
- if prof.WebRID != "" && b.live != nil {
- if rs, lErr := b.live.CheckAccountLiveStatus(ctx, site.Douyin, prof.SecUID, prof.WebRID, false); lErr == nil {
- mapped := mapRoomToAccountState(rs)
- if mapped.Uname == "" {
- mapped.Uname = prof.Nickname
- }
- if mapped.Face == "" {
- mapped.Face = prof.AvatarURL
- }
- st = mapped
- }
- }
- liveState = &st
- }
- return mapDouyinUserView(prof, liveState), nil
-}
-
-// DouyinUserWorks fetches one paginated grid page of a Douyin creator's works.
-func (b *Backend) DouyinUserWorks(ctx context.Context, secUID, cursor string) (*DouyinUserWorksPage, error) {
- if err := b.requireSiteLogin(site.Douyin); err != nil {
- return nil, err
- }
- page, err := b.douyin.ListUserPosts(ctx, douyin.UserPostsRequest{
- SecUID: strings.TrimSpace(secUID),
- MaxCursor: strings.TrimSpace(cursor),
- StreamOptions: douyin.StreamSelectOptions{PreferredCodec: b.preferredDouyinCodec()},
- })
- if err != nil {
- b.logError("DouyinUserWorks", err)
- return nil, err
- }
- cards := make([]DouyinWorkCardDTO, 0, len(page.Works))
- for _, w := range page.Works {
- cards = append(cards, mapDouyinWorkCard(w))
- }
- return &DouyinUserWorksPage{
- Works: cards,
- NextCursor: page.NextCursor,
- HasMore: page.HasMore,
- UncertainEmpty: page.UncertainEmpty,
- UncertainReason: page.UncertainReason,
- }, nil
-}
-
-// DouyinLive queries a Douyin live room by web_rid and returns normalized room and anchor state.
-func (b *Backend) DouyinLive(ctx context.Context, webRID string) (*DouyinLiveView, error) {
- if err := b.requireSiteLogin(site.Douyin); err != nil {
- return nil, err
- }
- detail, err := b.douyin.EnterLiveRoom(ctx, strings.TrimSpace(webRID), "")
- if err != nil {
- b.logError("DouyinLive", err)
- return nil, err
- }
- prefWebRID := detail.PreferredWebRID()
- if detail.OwnerSecUID != "" && prefWebRID != "" {
- b.syncDouyinAccountWebRID(detail.OwnerSecUID, prefWebRID)
- }
- if b.live != nil && detail.OwnerSecUID != "" {
- b.live.ObserveAccountLiveHint(site.Douyin, detail.OwnerSecUID, prefWebRID, detail.RoomID)
- }
- liveStatus := 0
- statusText := "未开播"
- if detail.RoomStatus == 2 {
- liveStatus = 1
- if detail.AudioOnly {
- statusText = "纯语音直播"
- } else {
- statusText = "直播中"
- }
- }
- acctState := &LiveAccountState{
- Site: string(site.Douyin),
- AccountKey: formatAccountKey(site.Douyin, detail.OwnerSecUID),
- RecordingKey: detail.LiveDedupeKey(),
- UID: detail.OwnerSecUID,
- RoomID: detail.RoomID,
- WebRID: prefWebRID,
- Uname: detail.OwnerNickname,
- Face: detail.OwnerAvatar,
- Title: detail.Title,
- Cover: detail.CoverURL,
- AreaName: detail.AreaName,
- LiveStatus: liveStatus,
- LiveSince: detail.LiveSince,
- StatusText: statusText,
- Transport: string(site.LiveTransportHTTPFLV),
- AudioOnly: detail.AudioOnly,
- }
- if b.live != nil && detail.OwnerSecUID != "" {
- if cached, ok := b.live.CachedAccountState(site.Douyin, detail.OwnerSecUID); ok && cached.Recording {
- acctState.Recording = true
- if cached.Transport != "" {
- acctState.Transport = cached.Transport
- }
- acctState.AudioOnly = acctState.AudioOnly || cached.AudioOnly
- acctState.RecordSession = cached.RecordSession
- acctState.RecordDurationSec = cached.RecordDurationSec
- acctState.RecordSpeedBps = cached.RecordSpeedBps
- acctState.RecordBytes = cached.RecordBytes
- acctState.RecordSegments = cached.RecordSegments
- acctState.RecordItemDir = cached.RecordItemDir
- acctState.RecordPartPath = firstNonEmpty(cached.RecordPartPath, resolveRecordingPartPath(cached.RecordItemDir))
- acctState.RecordPartIndex = cached.RecordPartIndex
- acctState.RecordPartBytes = cached.RecordPartBytes
- acctState.RecordPartReady = cached.RecordPartReady
- acctState.PreviewSupported = cached.PreviewSupported
- acctState.PreviewReason = cached.PreviewReason
- }
- }
- canonicalURL := "https://live.douyin.com/" + prefWebRID
- return &DouyinLiveView{
- OwnerSecUID: detail.OwnerSecUID,
- OwnerUID: detail.OwnerUID,
- OwnerName: detail.OwnerNickname,
- OwnerAvatar: detail.OwnerAvatar,
- WebRID: prefWebRID,
- RoomID: detail.RoomID,
- LiveStatus: liveStatus,
- StatusText: statusText,
- Title: detail.Title,
- CoverURL: detail.CoverURL,
- AreaName: detail.AreaName,
- LiveSince: detail.LiveSince,
- AudioOnly: detail.AudioOnly,
- CanonicalURL: canonicalURL,
- State: acctState,
- }, nil
-}
-
-// StagePreviewMedia downloads a whitelisted CDN audio/video clip (e.g. uncached Douyin note BGM
-// or note video page) without sending Cookie into /cache/preview/ and returns its local file path
-// for playback via internal/player.
-func (b *Backend) StagePreviewMedia(ctx context.Context, siteID, rawURL, ext string) (string, error) {
- id, err := normalizeSiteID(siteID)
- if err != nil {
- return "", err
- }
- if err := b.requireSiteLogin(id); err != nil {
- return "", err
- }
- rawURL = strings.TrimSpace(rawURL)
- if rawURL == "" {
- return "", &site.Error{Site: id, Kind: site.ErrKindBadRequest, Message: "媒体预览地址为空"}
- }
- var data []byte
- switch id {
- case site.Douyin:
- var fetchErr error
- data, _, fetchErr = b.douyin.FetchImageLimited(ctx, rawURL, maxPreviewMediaBytes)
- if fetchErr != nil {
- return "", fetchErr
- }
- case site.Bilibili:
- var fetchErr error
- data, fetchErr = b.bili.FetchImageLimited(ctx, rawURL, maxPreviewMediaBytes)
- if fetchErr != nil {
- return "", fetchErr
- }
- }
- safeExt := ".mp4"
- switch strings.ToLower(strings.TrimSpace(ext)) {
- case ".mp3", "mp3":
- safeExt = ".mp3"
- case ".m4a", "m4a":
- safeExt = ".m4a"
- case ".aac", "aac":
- safeExt = ".aac"
- case ".ogg", "ogg":
- safeExt = ".ogg"
- case ".wav", "wav":
- safeExt = ".wav"
- }
- sum := sha256.Sum256([]byte(string(id) + "\x00" + rawURL))
- fileName := fmt.Sprintf("preview_%s_%x%s", string(id), sum[:16], safeExt)
- fullPath := filepath.Join(b.previewDir, fileName)
- if err := storage.WriteFileAtomic(fullPath, data, 0o600); err != nil {
- return "", err
- }
- return fullPath, nil
-}
-
-// CacheDouyinWork enqueues a Douyin video or mixed note work for local caching.
-func (b *Backend) CacheDouyinWork(ctx context.Context, awemeID string) (download.Task, error) {
- if err := b.requireSiteLogin(site.Douyin); err != nil {
- return download.Task{}, err
- }
- return b.enqueueDouyinWorkWithSource(ctx, awemeID, "manual")
-}
-
-func (b *Backend) enqueueDouyinWorkWithSource(ctx context.Context, awemeID, source string) (download.Task, error) {
- if err := b.requireSiteLogin(site.Douyin); err != nil {
- return download.Task{}, err
- }
- t, err := b.dl.EnqueueDouyinWork(ctx, download.DouyinWorkEnqueueRequest{
- AwemeID: strings.TrimSpace(awemeID),
- Source: source,
- })
- if err != nil {
- b.logError("CacheDouyinWork", err)
- return download.Task{}, err
- }
- b.events.PublishSite(EventTaskUpdated, string(site.Douyin), "enqueued:"+t.TargetID)
- return t, nil
-}
-
-// RemoveHistoryForSite deletes a single recent-parse history item scoped to (siteID, kind, id).
-func (b *Backend) RemoveHistoryForSite(siteID, kind, id string) error {
- if err := b.requireAnyLogin(); err != nil {
- return err
- }
- return b.history.RemoveBySite(siteID, kind, id)
-}
-
-// LinkSubscriptionAccountRef links an AccountRef (preserving Douyin UniqueID and WebRID) to a subscription.
-func (b *Backend) LinkSubscriptionAccountRef(subID string, acct subscription.AccountRef) (subscription.Subscription, error) {
- if err := b.requireAnyLogin(); err != nil {
- return subscription.Subscription{}, err
- }
- res, err := b.subs.LinkAccount(subID, acct)
- if err == nil {
- b.rememberAccountAvatar(acct.Site, acct.UID, acct.Face)
- b.events.Publish(EventSubscriptionChecked, "linked")
- }
- return res, err
-}
-
-func formatBackoffLevelText(level int) string {
- switch {
- case level <= 1:
- return "15 分钟"
- case level == 2:
- return "30 分钟"
- case level == 3:
- return "1 小时"
- case level == 4:
- return "2 小时"
- default:
- return "6 小时"
- }
-}
-
-// SchedulerStatuses returns per-site scheduled check timing and backoff state for Settings -> 订阅与直播.
-func (b *Backend) SchedulerStatuses() map[string]SiteSchedulerStatus {
- out := make(map[string]SiteSchedulerStatus, 2)
- var states map[string]subscription.SchedulerState
- if b.subs != nil {
- states = b.subs.ListSiteSchedulerStates()
- }
- for _, id := range site.All() {
- key := string(id)
- label := "哔哩哔哩"
- if id == site.Douyin {
- label = "抖音"
- }
- st := SiteSchedulerStatus{
- Site: key,
- DisplayName: label,
- }
- if b.subs != nil {
- raw := states[key]
- st.LastError = raw.LastStopReason
- if inBackoff, until := b.subs.IsSiteInBackoff(key); inBackoff {
- lvlText := formatBackoffLevelText(raw.BackoffLevel)
- st.BackingOff = true
- st.CurrentInterval = lvlText
- st.BackoffUntil = until.UTC().Format("2006-01-02T15:04:05Z07:00")
- st.BackoffSummary = fmt.Sprintf("%s:因风控放慢到 %s,%s 恢复", label, lvlText, until.Local().Format("1 月 2 日 15:04"))
- }
- }
- out[key] = st
- }
- return out
-}
-
-// AccountCheckRow is a row of Tasks › 检查计划: an account's update checks
-// and, when its subscription records broadcasts, its live checks.
-type AccountCheckRow struct {
- subscription.AccountCheckPlan
- // LiveCheckedAt is the last live status check (RFC 3339), "" if none
- // in this run; LiveEverySec how often one comes, about.
- LiveCheckedAt string `json:"liveCheckedAt,omitempty"`
- LiveEverySec int `json:"liveEverySec,omitempty"`
-}
-
-// CheckPlan lists every subscribed account with its last update check and
-// the scheduled round expected to check it next, plus the live checks of
-// accounts whose subscriptions record broadcasts.
-func (b *Backend) CheckPlan() []AccountCheckRow {
- if b.subs == nil || b.requireAnyLogin() != nil {
- return nil
- }
- plans := b.subs.CheckPlan()
- var liveAt map[string]time.Time
- if b.live != nil {
- liveAt = b.live.LiveCheckTimes()
- }
- autoRecord := map[string]int{}
- for _, p := range plans {
- if p.AutoRecord {
- autoRecord[p.Site]++
- }
- }
- out := make([]AccountCheckRow, 0, len(plans))
- for _, p := range plans {
- row := AccountCheckRow{AccountCheckPlan: p}
- if p.AutoRecord && b.live != nil {
- if at, ok := liveAt[p.Site+":"+p.UID]; ok {
- row.LiveCheckedAt = at.UTC().Format(time.RFC3339)
- }
- row.LiveEverySec = int(b.live.LiveCheckEvery(site.ID(p.Site), autoRecord[p.Site]).Seconds())
- }
- out = append(out, row)
- }
- return out
-}
-
-// ListLiveAccounts returns unified live & recording states across all tracked rooms/accounts.
-func (b *Backend) ListLiveAccounts() []LiveAccountState {
- if b.requireAnyLogin() != nil {
- return nil
- }
- rooms := b.live.ListRooms()
- out := make([]LiveAccountState, 0, len(rooms))
- for _, r := range rooms {
- out = append(out, mapBilibiliRoomToAccountState(r))
- }
- return out
-}
-
-// LiveStatuses refreshes live status for a mixed slice of ":" account keys.
-func (b *Backend) LiveStatuses(ctx context.Context, accountKeys []string) ([]LiveAccountState, error) {
- if err := b.requireAnyLogin(); err != nil {
- return nil, err
- }
- var biliUIDs []int64
- var douyinUIDs []string
- for _, rawKey := range accountKeys {
- siteID, uid, err := site.ParseAccountKey(rawKey)
- if err != nil {
- continue
- }
- switch siteID {
- case site.Bilibili:
- if mid, mErr := strconv.ParseInt(uid, 10, 64); mErr == nil && mid > 0 {
- biliUIDs = append(biliUIDs, mid)
- }
- case site.Douyin:
- douyinUIDs = append(douyinUIDs, uid)
- }
- }
-
- var out []LiveAccountState
- var firstErr error
-
- if len(biliUIDs) > 0 {
- if err := b.requireSiteLogin(site.Bilibili); err != nil {
- firstErr = err
- } else if rooms, err := b.live.RefreshForAccounts(ctx, biliUIDs); err != nil {
- firstErr = err
- } else {
- for _, r := range rooms {
- out = append(out, mapBilibiliRoomToAccountState(r))
- }
- }
- }
-
- if len(douyinUIDs) > 0 {
- if err := b.requireSiteLogin(site.Douyin); err != nil {
- if firstErr == nil {
- firstErr = err
- }
- } else {
- for _, secUID := range douyinUIDs {
- cachedWebRID := b.lookupAccountWebRID(secUID)
- rs, err := b.live.CheckAccountLiveStatus(ctx, site.Douyin, secUID, cachedWebRID, false)
- if err != nil {
- if firstErr == nil {
- firstErr = err
- }
- continue
- }
- out = append(out, mapRoomToAccountState(rs))
- }
- }
- }
-
- return out, firstErr
-}
-
-// StartLiveRecordingByAccount starts live recording for a ":" creator account.
-func (b *Backend) StartLiveRecordingByAccount(ctx context.Context, accountKey string) (LiveAccountState, error) {
- siteID, uid, err := site.ParseAccountKey(accountKey)
- if err != nil {
- return LiveAccountState{}, err
- }
- if err := b.requireSiteLogin(siteID); err != nil {
- return LiveAccountState{}, err
- }
- if siteID == site.Bilibili {
- mid, _ := strconv.ParseInt(uid, 10, 64)
- rooms, rErr := b.live.RefreshForAccounts(ctx, []int64{mid})
- if rErr != nil {
- return LiveAccountState{}, rErr
- }
- if len(rooms) == 0 || rooms[0].RoomID <= 0 {
- return LiveAccountState{}, &site.Error{Site: site.Bilibili, Kind: site.ErrKindUnavailable, Message: "该账号未开通直播间"}
- }
- rs, sErr := b.live.StartRecording(ctx, rooms[0].RoomID)
- return mapRoomToAccountState(rs), sErr
- }
- return b.startDouyinLiveRecording(ctx, uid, b.lookupAccountWebRID(uid))
-}
-
-// StartLiveRecordingByRoom starts live recording given an explicit site and roomID/webRID.
-func (b *Backend) StartLiveRecordingByRoom(ctx context.Context, siteID, roomOrWebRID string) (LiveAccountState, error) {
- id, err := normalizeSiteID(siteID)
- if err != nil {
- return LiveAccountState{}, err
- }
- if err := b.requireSiteLogin(id); err != nil {
- return LiveAccountState{}, err
- }
- if id == site.Bilibili {
- roomID, pErr := strconv.ParseInt(strings.TrimSpace(roomOrWebRID), 10, 64)
- if pErr != nil || roomID <= 0 {
- return LiveAccountState{}, &site.Error{Site: site.Bilibili, Kind: site.ErrKindBadRequest, Message: "无效的直播间号"}
- }
- rs, sErr := b.live.StartRecording(ctx, roomID)
- return mapRoomToAccountState(rs), sErr
- }
- return b.startDouyinLiveRecording(ctx, "", strings.TrimSpace(roomOrWebRID))
-}
-
-// StopLiveRecordingByKey stops an active live recording by canonical recording key (":live:" or decimal roomID).
-func (b *Backend) StopLiveRecordingByKey(recKey string) (LiveAccountState, error) {
- if err := b.requireAnyLogin(); err != nil {
- return LiveAccountState{}, err
- }
- rs, err := b.live.StopRecordingByKey(strings.TrimSpace(recKey))
- return mapRoomToAccountState(rs), err
-}
-
-// LiveRecordingPreview returns an in-memory snapshot of an active or recent live recording session for preview playback.
-func (b *Backend) LiveRecordingPreview(recKey string) (LiveRecordingPreviewInfo, bool) {
- if b.requireAnyLogin() != nil || b.live == nil {
- return LiveRecordingPreviewInfo{}, false
- }
- target := strings.TrimSpace(recKey)
- if target == "" {
- return LiveRecordingPreviewInfo{}, false
- }
- if p, ok := b.live.RecordingPreview(target); ok {
- roomID := strings.TrimSpace(p.RoomIDStr)
- if roomID == "" && p.RoomID > 0 {
- roomID = strconv.FormatInt(p.RoomID, 10)
- }
- return LiveRecordingPreviewInfo{
- RecordingKey: p.RecordingKey,
- Site: p.Site,
- AccountUID: p.AccountUID,
- RoomID: roomID,
- WebRID: p.WebRID,
- Uname: p.Uname,
- Title: p.Title,
- Codec: p.Codec,
- Quality: p.Quality,
- QualityName: p.QualityName,
- Transport: p.Transport,
- AudioOnly: p.AudioOnly,
- Recording: p.Recording,
- PartPath: p.PartPath,
- PartIndex: p.PartIndex,
- PartBytes: p.PartBytes,
- PartDurationSec: p.PartDurationSec,
- PartReady: p.PartReady,
- PreviewSupported: p.PreviewSupported,
- PreviewReason: p.PreviewReason,
- ItemDir: p.ItemDir,
- DurationSec: p.DurationSec,
- SpeedBps: p.SpeedBps,
- BytesWritten: p.BytesWritten,
- Segments: p.Segments,
- Incidents: append([]library.LiveIncident(nil), p.Incidents...),
- StopReason: p.StopReason,
- LastError: p.LastError,
- }, true
- }
- for _, st := range b.ListLiveAccounts() {
- if st.RecordingKey != target && st.AccountKey != target && st.RoomID != target && st.UID != target && st.WebRID != target {
- continue
- }
- partPath := st.RecordPartPath
- if partPath == "" && st.RecordItemDir != "" {
- partPath = resolveRecordingPartPath(st.RecordItemDir)
- }
- var partBytes int64 = st.RecordPartBytes
- if partBytes <= 0 && partPath != "" {
- if info, err := os.Stat(partPath); err == nil {
- partBytes = info.Size()
- }
- }
- partReady := st.RecordPartReady || partBytes > 0
- supported := st.PreviewSupported || (st.Recording && partPath != "")
- return LiveRecordingPreviewInfo{
- RecordingKey: st.RecordingKey,
- Site: st.Site,
- AccountUID: st.UID,
- RoomID: st.RoomID,
- WebRID: st.WebRID,
- Uname: st.Uname,
- Title: st.Title,
- Codec: st.Codec,
- QualityName: st.QualityName,
- Transport: st.Transport,
- AudioOnly: st.AudioOnly,
- Recording: st.Recording,
- PartPath: partPath,
- PartIndex: st.RecordPartIndex,
- PartBytes: partBytes,
- PartReady: partReady,
- PreviewSupported: supported,
- PreviewReason: st.PreviewReason,
- ItemDir: st.RecordItemDir,
- DurationSec: st.RecordDurationSec,
- SpeedBps: st.RecordSpeedBps,
- BytesWritten: st.RecordBytes,
- Segments: st.RecordSegments,
- Incidents: append([]library.LiveIncident(nil), st.Incidents...),
- StopReason: st.StopReason,
- LastError: st.LastError,
- }, true
- }
- return LiveRecordingPreviewInfo{}, false
-}
-
-// OpenLiveInBrowser opens a Bilibili roomID or Douyin web_rid in the external system browser.
-func (b *Backend) OpenLiveInBrowser(siteID, roomOrWebRID string) error {
- if err := b.requireAnyLogin(); err != nil {
- return err
- }
- id, err := normalizeSiteID(siteID)
- if err != nil {
- return err
- }
- clean := strings.TrimSpace(roomOrWebRID)
- for _, r := range clean {
- if r < '0' || r > '9' {
- return &site.Error{Site: id, Kind: site.ErrKindBadRequest, Message: "无效的直播间号"}
- }
- }
- if clean == "" || clean == "0" {
- return &site.Error{Site: id, Kind: site.ErrKindBadRequest, Message: "无效的直播间号"}
- }
- if id == site.Douyin {
- return b.desktop.OpenExternalURL("https://live.douyin.com/" + clean)
- }
- return b.desktop.OpenExternalURL("https://live.bilibili.com/" + clean)
-}
-
-func (b *Backend) LibraryStatistics() (library.Statistics, error) {
- if err := b.requireAnyLogin(); err != nil {
- return library.Statistics{}, err
- }
- return b.lib.Statistics()
-}
-
-func (b *Backend) ListSubscriptionUpdatesPage(subID string, limit, offset int) ([]subscription.UpdateItem, error) {
- if err := b.requireAnyLogin(); err != nil {
- return nil, err
- }
- return b.subs.ListUpdatesPage(subID, limit, offset)
-}
-
-func (b *Backend) UserDynamicsPage(ctx context.Context, mid int64, offset string) (bilibili.UserDynamicsPage, error) {
- if err := b.requireSiteLogin(site.Bilibili); err != nil {
- return bilibili.UserDynamicsPage{}, err
- }
- return b.bili.UserDynamics(ctx, mid, offset)
-}
-
-func (b *Backend) UserVideosPage(ctx context.Context, mid int64, page int) (bilibili.UserVideosPage, error) {
- if err := b.requireSiteLogin(site.Bilibili); err != nil {
- return bilibili.UserVideosPage{}, err
- }
- res, err := b.bili.UserVideos(ctx, mid, page, 30, "pubdate", "")
- if err == nil && page <= 1 {
- b.recordAccountWorks(site.Bilibili, strconv.FormatInt(mid, 10), res.Total)
- }
- return res, err
-}
-
-// LiveStatus is a read-only refresh of visible Bilibili accounts, with a 60s cache.
-// It never starts automatic recordings in response to a UI request.
-func (b *Backend) LiveStatus(ctx context.Context, uids []int64) ([]live.RoomState, error) {
- if err := b.requireSiteLogin(site.Bilibili); err != nil {
- return nil, err
- }
- return b.live.RefreshForAccounts(ctx, uids)
-}
-
-func (b *Backend) detectImageSite(rawURL string) site.ID {
- u, err := url.Parse(strings.TrimSpace(rawURL))
- if err != nil || u.Host == "" {
- return site.Bilibili
- }
- host := strings.ToLower(u.Hostname())
- if site.MatchDomainSuffix(host, site.DefaultDouyinMediaHosts()) {
- return site.Douyin
- }
- if id, ok := site.DetectHostSite(host); ok {
- return id
- }
- if host == "127.0.0.1" || host == "localhost" || host == "::1" {
- if b.douyin != nil {
- ep := b.douyin.Endpoints()
- for _, candidate := range []string{ep.ProfileSelf, ep.AwemeDetail, ep.LiveWebEnter} {
- if cu, cErr := url.Parse(candidate); cErr == nil && strings.EqualFold(cu.Host, u.Host) {
- if strings.HasPrefix(u.Path, "/bfs/") {
- return site.Bilibili
- }
- return site.Douyin
- }
- }
- }
- if strings.HasPrefix(u.Path, "/douyin") || strings.HasPrefix(u.Path, "/obj/") || strings.HasPrefix(u.Path, "/tos-") {
- return site.Douyin
- }
- if b.douyinCred != nil && b.douyinCred.HasActiveCredential() && (b.cred == nil || !b.cred.HasActiveCredential()) {
- return site.Douyin
- }
- }
- return site.Bilibili
-}
-
-// ClearLiveIncidents deletes the recorded incidents of a finished live session
-// (Tasks › 录制异常): the item's live.incidents when itemKey names a finished
-// recording, and the in-memory list of matching rooms that are not recording.
-// The recording files are kept. A session still recording is refused.
-func (b *Backend) ClearLiveIncidents(itemKey, siteID, roomID, uid string) error {
- itemKey = strings.TrimSpace(itemKey)
- changed := false
- if itemKey != "" && b.lib != nil {
- item, ok, err := b.lib.GetItem(itemKey)
- if err != nil {
- return err
- }
- if ok && item.Kind == "live" {
- if item.Status == "recording" {
- return &site.Error{Kind: site.ErrKindBadRequest, Message: "这场直播还在录制,结束后才能删除异常记录"}
- }
- if item.Live != nil && len(item.Live.Incidents) > 0 {
- item.Live.Incidents = nil
- if _, err := b.lib.SaveItem(item.ItemDir, item); err != nil {
- return err
- }
- changed = true
- }
- }
- }
- if b.live != nil && b.live.ClearIdleIncidents(siteID, roomID, uid) {
- changed = true
- }
- if changed && b.events != nil {
- b.events.Publish(EventLibraryChanged, "incidents_cleared")
- }
- return nil
-}
diff --git a/internal/service/cache_queue.go b/internal/service/cache_queue.go
deleted file mode 100644
index c32621d..0000000
--- a/internal/service/cache_queue.go
+++ /dev/null
@@ -1,1984 +0,0 @@
-package service
-
-import (
- "context"
- "crypto/sha256"
- "encoding/hex"
- "encoding/json"
- "fmt"
- "math/rand/v2"
- "os"
- "path/filepath"
- "regexp"
- "slices"
- "strings"
- "sync"
- "time"
-
- "github.com/chialecode/trace/internal/site"
- "github.com/chialecode/trace/internal/site/bilibili"
- "github.com/chialecode/trace/internal/storage"
-)
-
-const (
- CacheQueueQueued = "queued"
- CacheQueueRunning = "running"
- CacheQueueWaiting = "waiting"
- CacheQueueWaitingBackoff = "waiting_backoff"
- CacheQueuePaused = "paused"
- CacheQueueCompleted = "completed"
- CacheQueueStopped = "stopped"
-
- cacheQueueFileName = "cache-queue.json"
- cacheQueueSchemaVersion = 1
- maxCacheQueueRecentItems = 30
-)
-
-// CacheQueuePacing centralizes all conservative anti-risk-control delays and thresholds (Q-017).
-type CacheQueuePacing struct {
- ItemMinDelay time.Duration
- ItemMaxDelay time.Duration
- LongRestMinItems int
- LongRestMaxItems int
- LongRestMinDelay time.Duration
- LongRestMaxDelay time.Duration
- BackoffCoolMinDelay time.Duration
- BackoffCoolMaxDelay time.Duration
- StartupMinDelay time.Duration
- StartupMaxDelay time.Duration
-}
-
-// DefaultCacheQueuePacing defines the default Q-017 pacing intervals for background list caching.
-var DefaultCacheQueuePacing = CacheQueuePacing{
- ItemMinDelay: 40 * time.Second,
- ItemMaxDelay: 150 * time.Second,
- LongRestMinItems: 15,
- LongRestMaxItems: 25,
- LongRestMinDelay: 10 * time.Minute,
- LongRestMaxDelay: 25 * time.Minute,
- BackoffCoolMinDelay: 10 * time.Minute,
- BackoffCoolMaxDelay: 30 * time.Minute,
- StartupMinDelay: 1 * time.Minute,
- StartupMaxDelay: 5 * time.Minute,
-}
-
-// CacheQueueClock abstracts wall clock and timers so tests run deterministically with zero real sleeps.
-type CacheQueueClock interface {
- Now() time.Time
- NewTimer(d time.Duration) CacheQueueTimer
-}
-
-// CacheQueueTimer is a single-shot timer created by CacheQueueClock.
-type CacheQueueTimer interface {
- C() <-chan time.Time
- Stop() bool
-}
-
-// CacheQueueRand returns a pseudo-random integer in [0, n) for n > 0.
-type CacheQueueRand func(n int) int
-
-type realCacheQueueClock struct{}
-
-type realCacheQueueTimer struct {
- t *time.Timer
-}
-
-func (realCacheQueueClock) Now() time.Time {
- return time.Now()
-}
-
-func (realCacheQueueClock) NewTimer(d time.Duration) CacheQueueTimer {
- return &realCacheQueueTimer{t: time.NewTimer(d)}
-}
-
-func (rt *realCacheQueueTimer) C() <-chan time.Time {
- return rt.t.C
-}
-
-func (rt *realCacheQueueTimer) Stop() bool {
- return rt.t.Stop()
-}
-
-// CacheQueueRequest asks to enqueue an entire creator list ("dynamics", "videos", or "works")
-// for conservative newest-to-oldest background caching.
-type CacheQueueRequest struct {
- Site string `json:"site"`
- List string `json:"list"`
- User string `json:"user"`
- UserName string `json:"userName"`
- AvatarURL string `json:"avatarUrl"`
- Dynamics []bilibili.DynamicItem `json:"-"`
- Videos []bilibili.UserVideoItem `json:"-"`
- Works []DouyinWorkCardDTO `json:"-"`
- Cursor string `json:"cursor"`
- HasMore bool `json:"hasMore"`
- // Origin is QueueOriginFullCache when a full-cache rule started the run
- // (DEC-061); empty for "全部缓存" on a user page.
- Origin string `json:"origin,omitempty"`
-}
-
-// QueueOriginFullCache marks a queue run started by a full-cache rule (DEC-061).
-const QueueOriginFullCache = "full_cache"
-
-// CacheQueueRecentItem summarizes one item cached by a queue run so the detail panel can open it locally.
-type CacheQueueRecentItem struct {
- ItemKey string `json:"itemKey"`
- Title string `json:"title"`
- CachedAt string `json:"cachedAt"`
-}
-
-// CacheQueueTask is the UI-facing DTO for one creator list background cache queue task.
-type CacheQueueTask struct {
- ID string `json:"id"`
- Site string `json:"site"`
- User string `json:"user"`
- UserName string `json:"userName"`
- AvatarPath string `json:"avatarPath,omitempty"`
- List string `json:"list"`
- ListLabel string `json:"listLabel"`
- Origin string `json:"origin,omitempty"`
- Status string `json:"status"`
- StatusText string `json:"statusText"`
- PauseReason string `json:"pauseReason,omitempty"`
- StopReason string `json:"stopReason,omitempty"`
- Cursor string `json:"cursor,omitempty"`
- HasMore bool `json:"hasMore"`
- CachedCount int `json:"cachedCount"`
- SkippedCount int `json:"skippedCount"`
- ActiveDownloadID string `json:"activeDownloadId,omitempty"`
- ActiveItemKey string `json:"activeItemKey,omitempty"`
- ActiveTitle string `json:"activeTitle,omitempty"`
- RecentItems []CacheQueueRecentItem `json:"recentItems,omitempty"`
- NextRunAt string `json:"nextRunAt,omitempty"`
- CreatedAt string `json:"createdAt"`
- UpdatedAt string `json:"updatedAt"`
-}
-
-type cacheQueueFile struct {
- Version int `json:"version"`
- Tasks []cacheQueueRecord `json:"tasks"`
-}
-
-type cacheQueueRecord struct {
- ID string `json:"id"`
- Site string `json:"site"`
- User string `json:"user"`
- UserName string `json:"userName,omitempty"`
- AvatarKey string `json:"avatarKey,omitempty"`
- List string `json:"list"`
- Origin string `json:"origin,omitempty"`
- Cursor string `json:"cursor,omitempty"`
- HasMore bool `json:"hasMore"`
- ProcessedKeys []string `json:"processedKeys,omitempty"`
- CachedCount int `json:"cachedCount"`
- SkippedCount int `json:"skippedCount"`
- SinceRestCount int `json:"sinceRestCount,omitempty"`
- RestThreshold int `json:"restThreshold,omitempty"`
- ActiveDownloadIDs []string `json:"activeDownloadIds,omitempty"`
- ActiveItemKey string `json:"activeItemKey,omitempty"`
- ActiveTitle string `json:"activeTitle,omitempty"`
- RecentItems []CacheQueueRecentItem `json:"recentItems,omitempty"`
- Status string `json:"status"`
- PauseReason string `json:"pauseReason,omitempty"`
- StopReason string `json:"stopReason,omitempty"`
- NextRunAt string `json:"nextRunAt,omitempty"`
- CreatedAt string `json:"createdAt"`
- UpdatedAt string `json:"updatedAt"`
-}
-
-type cacheQueueRuntime struct {
- pager queuePager
- pageItems []queueCandidate
- pageIdx int
- pageNextCursor string
- pageNextHasMore bool
- pageLoaded bool
- seenKeys map[string]bool
- nextPartEnqueuers []queuePartEnqueuer
- resumePendingDownloads bool
- stepCancel context.CancelFunc
-}
-
-type cacheQueueEntry struct {
- rec cacheQueueRecord
- rt cacheQueueRuntime
-}
-
-type cacheQueueManager struct {
- b *Backend
- path string
- clock CacheQueueClock
- rng CacheQueueRand
- pacing CacheQueuePacing
-
- mu sync.Mutex
- tasks []*cacheQueueEntry
- dirty bool
- fileExists bool
- started bool
- stopCancel context.CancelFunc
- siteWake map[site.ID]chan struct{}
- wg sync.WaitGroup
-}
-
-var (
- queueFullURLPattern = regexp.MustCompile(`(?i)https?://[^\s"'<>]+`)
- queueQueryTailPattern = regexp.MustCompile(`\?[A-Za-z0-9_.-]+=[^\s"'<>]*`)
- queueSecretKVPattern = regexp.MustCompile(`(?i)\b(?:cookie|authorization|sessdata|bili_jct|dedeuserid|dedeuserid__ckmd5|sid|ac_time_value|refresh_token|pending_old_refresh_token|access_key|auth_key|w_rid|upsig|wssecret|wstime|deadline|bwsv|sessionid|sessionid_ss|sid_tt|uid_tt|uid_tt_ss|sid_guard|odin_tt|passport_csrf_token|passport_csrf_token_default|ttwid|uifid|uifid_temp|mstoken|s_v_web_id|__ac_nonce|__ac_signature|a_bogus|x-bogus|x-expires|x-signature|x-secsdk-web-signature|x-secsdk-csrf-token|token|sign)["'\\]*\s*[=:][^\s;"'<>]*`)
-)
-
-// guardCacheQueueSchema checks /cache-queue.json before databases open:
-// files written by a newer schema version are refused; corrupt files are backed up.
-func guardCacheQueueSchema(dataDir string) (string, error) {
- if strings.TrimSpace(dataDir) == "" {
- return "", nil
- }
- path := filepath.Join(dataDir, cacheQueueFileName)
- raw, err := os.ReadFile(path)
- if os.IsNotExist(err) {
- return "", nil
- }
- if err != nil {
- return "", err
- }
- var probe struct {
- Version int `json:"version"`
- }
- if jErr := json.Unmarshal(raw, &probe); jErr != nil {
- backup, bErr := storage.BackupCorruptFile(path)
- if bErr != nil {
- return "", bErr
- }
- _ = os.Remove(path)
- return backup, nil
- }
- if probe.Version > cacheQueueSchemaVersion {
- return "", &storage.NewerDataError{
- File: cacheQueueFileName,
- Found: probe.Version,
- Supported: cacheQueueSchemaVersion,
- }
- }
- return "", nil
-}
-
-func newCacheQueueManager(b *Backend, path string, clock CacheQueueClock, rng CacheQueueRand, pacing *CacheQueuePacing) (*cacheQueueManager, string, error) {
- if clock == nil {
- clock = realCacheQueueClock{}
- }
- if rng == nil {
- rng = rand.IntN
- }
- cfg := DefaultCacheQueuePacing
- if pacing != nil {
- cfg = *pacing
- }
- m := &cacheQueueManager{
- b: b,
- path: path,
- clock: clock,
- rng: rng,
- pacing: cfg,
- siteWake: map[site.ID]chan struct{}{
- site.Bilibili: make(chan struct{}, 1),
- site.Douyin: make(chan struct{}, 1),
- },
- }
- backup, err := m.loadFromDiskLocked()
- if err != nil {
- return nil, backup, err
- }
- return m, backup, nil
-}
-
-func (m *cacheQueueManager) loadFromDiskLocked() (string, error) {
- if strings.TrimSpace(m.path) == "" {
- return "", nil
- }
- raw, err := os.ReadFile(m.path)
- if os.IsNotExist(err) {
- return "", nil
- }
- if err != nil {
- return "", err
- }
- var doc cacheQueueFile
- if jErr := json.Unmarshal(raw, &doc); jErr != nil {
- backup, bErr := storage.BackupCorruptFile(m.path)
- if bErr != nil {
- return "", bErr
- }
- _ = os.Remove(m.path)
- return backup, nil
- }
- if doc.Version > cacheQueueSchemaVersion {
- return "", &storage.NewerDataError{
- File: cacheQueueFileName,
- Found: doc.Version,
- Supported: cacheQueueSchemaVersion,
- }
- }
- m.fileExists = true
- m.tasks = make([]*cacheQueueEntry, 0, len(doc.Tasks))
- for _, r := range doc.Tasks {
- clean := sanitizeQueueRecord(r)
- if clean.ID == "" || clean.Site == "" || clean.User == "" || clean.List == "" {
- continue
- }
- seen := make(map[string]bool, len(clean.ProcessedKeys))
- for _, k := range clean.ProcessedKeys {
- if k != "" {
- seen[k] = true
- }
- }
- m.tasks = append(m.tasks, &cacheQueueEntry{
- rec: clean,
- rt: cacheQueueRuntime{
- seenKeys: seen,
- resumePendingDownloads: len(clean.ActiveDownloadIDs) > 0,
- },
- })
- }
- return "", nil
-}
-
-func (m *cacheQueueManager) sanitizeText(s string) string {
- if m != nil && m.b != nil {
- s = m.b.redactStoredSecrets(s)
- }
- return sanitizeQueueText(s)
-}
-
-func sanitizeQueueText(s string) string {
- s = strings.TrimSpace(s)
- if s == "" {
- return ""
- }
- s = queueFullURLPattern.ReplaceAllString(s, "")
- s = queueQueryTailPattern.ReplaceAllString(s, "")
- s = queueSecretKVPattern.ReplaceAllString(s, "")
- return strings.Join(strings.Fields(s), " ")
-}
-
-func sanitizeCursor(c string) string {
- c = strings.TrimSpace(c)
- if strings.ContainsAny(c, "?=&;:/\\ \t\r\n") {
- return ""
- }
- return c
-}
-
-func sanitizeItemKey(k string) string {
- k = strings.TrimSpace(k)
- if strings.ContainsAny(k, "?=&;/\\ \t\r\n") || strings.Contains(k, "://") {
- return ""
- }
- return k
-}
-
-func sanitizeQueueRecord(r cacheQueueRecord) cacheQueueRecord {
- siteID, list, normUser, err := normalizeCacheQueueTarget(r.Site, r.List, r.User)
- if err != nil {
- return cacheQueueRecord{}
- }
- r.Site = string(siteID)
- r.List = list
- r.User = normUser
- r.ID = sanitizeCursor(r.ID)
- r.UserName = sanitizeQueueText(r.UserName)
- if r.Origin != QueueOriginFullCache {
- r.Origin = ""
- }
- if !avatarFileRe.MatchString(r.AvatarKey) {
- r.AvatarKey = ""
- }
- r.Cursor = sanitizeCursor(r.Cursor)
- r.ActiveItemKey = sanitizeItemKey(r.ActiveItemKey)
- r.ActiveTitle = sanitizeQueueText(r.ActiveTitle)
- r.StopReason = sanitizeQueueText(r.StopReason)
- r.PauseReason = sanitizeCursor(r.PauseReason)
- r.NextRunAt = sanitizeCursorFallbackRFC3339(r.NextRunAt)
- r.CreatedAt = sanitizeCursorFallbackRFC3339(r.CreatedAt)
- r.UpdatedAt = sanitizeCursorFallbackRFC3339(r.UpdatedAt)
-
- var cleanProcessed []string
- for _, k := range r.ProcessedKeys {
- if ck := sanitizeItemKey(k); ck != "" && !slices.Contains(cleanProcessed, ck) {
- cleanProcessed = append(cleanProcessed, ck)
- }
- }
- r.ProcessedKeys = cleanProcessed
-
- var cleanDL []string
- for _, id := range r.ActiveDownloadIDs {
- if cid := sanitizeCursor(id); cid != "" && !slices.Contains(cleanDL, cid) {
- cleanDL = append(cleanDL, cid)
- }
- }
- r.ActiveDownloadIDs = cleanDL
-
- var cleanRecent []CacheQueueRecentItem
- for _, item := range r.RecentItems {
- ck := sanitizeItemKey(item.ItemKey)
- if ck == "" {
- continue
- }
- cleanRecent = append(cleanRecent, CacheQueueRecentItem{
- ItemKey: ck,
- Title: sanitizeQueueText(item.Title),
- CachedAt: sanitizeCursorFallbackRFC3339(item.CachedAt),
- })
- if len(cleanRecent) >= maxCacheQueueRecentItems {
- break
- }
- }
- r.RecentItems = cleanRecent
-
- switch r.Status {
- case CacheQueueQueued, CacheQueueRunning, CacheQueueWaiting, CacheQueueWaitingBackoff,
- CacheQueuePaused, CacheQueueCompleted, CacheQueueStopped:
- default:
- r.Status = CacheQueueStopped
- if r.StopReason == "" {
- r.StopReason = "未知状态,已停止"
- }
- }
- return r
-}
-
-func sanitizeCursorFallbackRFC3339(v string) string {
- v = strings.TrimSpace(v)
- if v == "" {
- return ""
- }
- if t, err := time.Parse(time.RFC3339, v); err == nil {
- return t.UTC().Format(time.RFC3339)
- }
- return ""
-}
-
-func isUnfinishedQueueStatus(status string) bool {
- return status != CacheQueueCompleted && status != CacheQueueStopped
-}
-
-func (m *cacheQueueManager) saveLocked() error {
- if strings.TrimSpace(m.path) == "" {
- return nil
- }
- if len(m.tasks) == 0 && !m.fileExists {
- return nil
- }
- doc := cacheQueueFile{
- Version: cacheQueueSchemaVersion,
- Tasks: make([]cacheQueueRecord, 0, len(m.tasks)),
- }
- for _, e := range m.tasks {
- rec := sanitizeQueueRecord(e.rec)
- rec.UserName = m.sanitizeText(rec.UserName)
- rec.ActiveTitle = m.sanitizeText(rec.ActiveTitle)
- rec.StopReason = m.sanitizeText(rec.StopReason)
- for i := range rec.RecentItems {
- rec.RecentItems[i].Title = m.sanitizeText(rec.RecentItems[i].Title)
- }
- doc.Tasks = append(doc.Tasks, rec)
- }
- if err := storage.WriteJSONAtomic(m.path, doc, 0o600); err != nil {
- return err
- }
- m.fileExists = true
- m.dirty = false
- return nil
-}
-
-func (m *cacheQueueManager) avatarKeys() []string {
- m.mu.Lock()
- defer m.mu.Unlock()
- var out []string
- for _, e := range m.tasks {
- if e.rec.AvatarKey != "" && avatarFileRe.MatchString(e.rec.AvatarKey) {
- out = append(out, e.rec.AvatarKey)
- }
- }
- return out
-}
-
-func (m *cacheQueueManager) randIntInclusiveLocked(minVal, maxVal int) int {
- if maxVal <= minVal {
- return minVal
- }
- n := maxVal - minVal + 1
- v := m.rng(n)
- if v < 0 {
- v = 0
- } else if v >= n {
- v = n - 1
- }
- return minVal + v
-}
-
-func (m *cacheQueueManager) randDurationLocked(minD, maxD time.Duration) time.Duration {
- if maxD <= minD {
- return minD
- }
- diff := maxD - minD
- if diff >= time.Second && minD%time.Second == 0 && maxD%time.Second == 0 {
- spanSec := int(diff / time.Second)
- return minD + time.Duration(m.randIntInclusiveLocked(0, spanSec))*time.Second
- }
- spanMs := int(diff / time.Millisecond)
- if spanMs <= 0 {
- return minD
- }
- return minD + time.Duration(m.randIntInclusiveLocked(0, spanMs))*time.Millisecond
-}
-
-func (m *cacheQueueManager) pickRestThresholdLocked() int {
- return m.randIntInclusiveLocked(m.pacing.LongRestMinItems, m.pacing.LongRestMaxItems)
-}
-
-func (m *cacheQueueManager) nowRFC3339() string {
- return m.clock.Now().UTC().Format(time.RFC3339)
-}
-
-func makeCacheQueueID(siteID, list, user string) string {
- sum := sha256.Sum256([]byte(siteID + ":" + list + ":" + user))
- return "cq_" + hex.EncodeToString(sum[:8])
-}
-
-func (m *cacheQueueManager) statusTextLocked(rec cacheQueueRecord) string {
- switch rec.Status {
- case CacheQueueQueued:
- return "排队中"
- case CacheQueueRunning:
- return "进行中"
- case CacheQueueWaiting:
- if rec.StopReason != "" {
- return rec.StopReason
- }
- return "等待下一条"
- case CacheQueueWaitingBackoff:
- if rec.StopReason != "" {
- return rec.StopReason
- }
- return "等待站点退避结束"
- case CacheQueuePaused:
- if rec.PauseReason == "auth_required" {
- return firstNonEmpty(rec.StopReason, "登录已失效,重新登录后自动继续")
- }
- if rec.PauseReason == "app_closed" {
- return "已暂停(应用关闭)"
- }
- return firstNonEmpty(rec.StopReason, "已暂停")
- case CacheQueueCompleted:
- return "已完成(已到列表末尾)"
- case CacheQueueStopped:
- return firstNonEmpty(rec.StopReason, "已停止")
- default:
- return rec.Status
- }
-}
-
-func (m *cacheQueueManager) toDTOLocked(e *cacheQueueEntry) CacheQueueTask {
- rec := e.rec
- var activeDL string
- if len(rec.ActiveDownloadIDs) > 0 {
- activeDL = rec.ActiveDownloadIDs[0]
- }
- var avatarPath string
- if m.b != nil {
- avatarPath = m.b.AccountAvatarPath(rec.Site, rec.User)
- }
- recent := make([]CacheQueueRecentItem, len(rec.RecentItems))
- copy(recent, rec.RecentItems)
- userName := rec.UserName
- if userName == "" {
- userName = rec.User
- }
- return CacheQueueTask{
- ID: rec.ID,
- Site: rec.Site,
- User: rec.User,
- UserName: userName,
- AvatarPath: avatarPath,
- List: rec.List,
- ListLabel: queueListLabel(rec),
- Origin: rec.Origin,
- Status: rec.Status,
- StatusText: m.statusTextLocked(rec),
- PauseReason: rec.PauseReason,
- StopReason: rec.StopReason,
- Cursor: rec.Cursor,
- HasMore: rec.HasMore,
- CachedCount: rec.CachedCount,
- SkippedCount: rec.SkippedCount,
- ActiveDownloadID: activeDL,
- ActiveItemKey: rec.ActiveItemKey,
- ActiveTitle: rec.ActiveTitle,
- RecentItems: recent,
- NextRunAt: rec.NextRunAt,
- CreatedAt: rec.CreatedAt,
- UpdatedAt: rec.UpdatedAt,
- }
-}
-
-func (m *cacheQueueManager) notifyStateLocked(rec cacheQueueRecord) {
- if m.b == nil {
- return
- }
- m.b.logInfo(fmt.Sprintf("cache_queue.%s.%s id=%s state=%s cached=%d skipped=%d",
- rec.Site, rec.List, rec.ID, rec.Status, rec.CachedCount, rec.SkippedCount))
- if m.b.events != nil {
- m.b.events.PublishSite(EventCacheQueueUpdated, rec.Site, rec.ID+":"+rec.Status)
- }
-}
-
-func (m *cacheQueueManager) wakeSite(siteID site.ID) {
- if ch, ok := m.siteWake[siteID]; ok {
- select {
- case ch <- struct{}{}:
- default:
- }
- }
-}
-
-func (m *cacheQueueManager) onDownloadUpdated(siteName string) {
- if sid, err := normalizeSiteID(siteName); err == nil {
- m.wakeSite(sid)
- }
-}
-
-// Start launches the independent per-site queue workers and schedules the 1–5m startup delay
-// for any unfinished tasks recovered from the previous session.
-func (m *cacheQueueManager) Start(ctx context.Context) {
- m.mu.Lock()
- if m.started {
- m.mu.Unlock()
- return
- }
- loopCtx, cancel := context.WithCancel(ctx)
- m.stopCancel = cancel
- m.started = true
-
- now := m.clock.Now().UTC()
- changed := false
- for _, sid := range []site.ID{site.Bilibili, site.Douyin} {
- loggedIn := m.hasSiteLogin(sid)
- assignedActive := false
- for _, e := range m.tasks {
- if e.rec.Site != string(sid) || !isUnfinishedQueueStatus(e.rec.Status) {
- continue
- }
- if e.rec.Status == CacheQueuePaused && e.rec.PauseReason == "user" {
- continue
- }
- if !loggedIn {
- if e.rec.Status != CacheQueuePaused || e.rec.PauseReason != "auth_required" {
- e.rec.Status = CacheQueuePaused
- e.rec.PauseReason = "auth_required"
- e.rec.StopReason = "未登录或登录已失效,重新登录后自动继续"
- e.rec.NextRunAt = ""
- e.rec.UpdatedAt = now.Format(time.RFC3339)
- e.rt.resumePendingDownloads = len(e.rec.ActiveDownloadIDs) > 0
- changed = true
- }
- continue
- }
- if e.rec.Status == CacheQueuePaused && e.rec.PauseReason == "auth_required" {
- // A task paused for an expired login resumes on the next login event (or by hand),
- // not merely because some credential is present at startup.
- continue
- }
-
- e.rt.resumePendingDownloads = len(e.rec.ActiveDownloadIDs) > 0
- if !assignedActive {
- assignedActive = true
- startupUntil := now.Add(m.randDurationLocked(m.pacing.StartupMinDelay, m.pacing.StartupMaxDelay))
- if e.rec.Status == CacheQueueWaitingBackoff {
- if existing, err := time.Parse(time.RFC3339, e.rec.NextRunAt); err != nil || existing.Before(startupUntil) {
- e.rec.NextRunAt = startupUntil.Format(time.RFC3339)
- }
- } else {
- if existing, err := time.Parse(time.RFC3339, e.rec.NextRunAt); err == nil && existing.After(startupUntil) {
- startupUntil = existing
- }
- e.rec.Status = CacheQueueWaiting
- e.rec.PauseReason = ""
- e.rec.StopReason = "应用启动后等待继续"
- e.rec.NextRunAt = startupUntil.Format(time.RFC3339)
- }
- e.rec.UpdatedAt = now.Format(time.RFC3339)
- changed = true
- } else if e.rec.Status != CacheQueueQueued {
- e.rec.Status = CacheQueueQueued
- e.rec.PauseReason = ""
- e.rec.StopReason = ""
- e.rec.NextRunAt = ""
- e.rec.UpdatedAt = now.Format(time.RFC3339)
- changed = true
- }
- }
- }
- if changed {
- _ = m.saveLocked()
- }
- m.mu.Unlock()
-
- for _, sid := range []site.ID{site.Bilibili, site.Douyin} {
- siteCopy := sid
- m.wg.Add(1)
- go func() {
- defer m.wg.Done()
- m.runSiteLoop(loopCtx, siteCopy)
- }()
- }
-}
-
-// Stop halts background queue workers cleanly and flushes state to disk for restart recovery.
-func (m *cacheQueueManager) Stop() {
- m.mu.Lock()
- cancel := m.stopCancel
- m.stopCancel = nil
- m.started = false
- for _, e := range m.tasks {
- if e.rt.stepCancel != nil {
- e.rt.stepCancel()
- e.rt.stepCancel = nil
- }
- }
- m.mu.Unlock()
-
- if cancel != nil {
- cancel()
- }
- m.wg.Wait()
-
- m.mu.Lock()
- _ = m.saveLocked()
- m.mu.Unlock()
-}
-
-func (m *cacheQueueManager) pauseForExit() {
- m.Stop()
- m.mu.Lock()
- defer m.mu.Unlock()
- now := m.nowRFC3339()
- changed := false
- for _, e := range m.tasks {
- if !isUnfinishedQueueStatus(e.rec.Status) {
- continue
- }
- if e.rec.Status == CacheQueuePaused {
- continue
- }
- if e.rec.Status == CacheQueueWaitingBackoff {
- // Keep waiting_backoff intact across exit so backoff cooldown is never shortened.
- continue
- }
- e.rec.Status = CacheQueuePaused
- e.rec.PauseReason = "app_closed"
- e.rec.StopReason = "已暂停(应用关闭)"
- e.rec.UpdatedAt = now
- changed = true
- }
- if changed {
- _ = m.saveLocked()
- }
-}
-
-func (m *cacheQueueManager) pauseForSite(siteID site.ID, reasonCode, reasonMsg string) {
- m.mu.Lock()
- now := m.nowRFC3339()
- changed := false
- var notify []cacheQueueRecord
- for _, e := range m.tasks {
- if e.rec.Site != string(siteID) || !isUnfinishedQueueStatus(e.rec.Status) {
- continue
- }
- if e.rec.Status == CacheQueuePaused && e.rec.PauseReason == "user" {
- continue
- }
- if e.rt.stepCancel != nil {
- e.rt.stepCancel()
- e.rt.stepCancel = nil
- }
- if reasonCode == "app_closed" && e.rec.Status == CacheQueueWaitingBackoff {
- continue
- }
- e.rec.Status = CacheQueuePaused
- e.rec.PauseReason = sanitizeCursor(reasonCode)
- e.rec.StopReason = sanitizeQueueText(reasonMsg)
- if reasonCode != "app_closed" {
- e.rec.NextRunAt = ""
- }
- e.rec.UpdatedAt = now
- e.rt.resumePendingDownloads = len(e.rec.ActiveDownloadIDs) > 0
- changed = true
- notify = append(notify, e.rec)
- }
- if changed {
- _ = m.saveLocked()
- for _, r := range notify {
- m.notifyStateLocked(r)
- }
- }
- m.mu.Unlock()
- m.wakeSite(siteID)
-}
-
-func (m *cacheQueueManager) snapshotAuthPausedIDs(siteID site.ID) []string {
- m.mu.Lock()
- defer m.mu.Unlock()
- var ids []string
- for _, e := range m.tasks {
- if e.rec.Site == string(siteID) && e.rec.Status == CacheQueuePaused && e.rec.PauseReason == "auth_required" {
- ids = append(ids, e.rec.ID)
- }
- }
- return ids
-}
-
-func (m *cacheQueueManager) resumeAuthPausedForSite(siteID site.ID) {
- m.resumeAuthPausedFilter(siteID, nil)
-}
-
-func (m *cacheQueueManager) resumeAuthPausedIDs(siteID site.ID, allowed []string) {
- if len(allowed) == 0 {
- return
- }
- m.resumeAuthPausedFilter(siteID, allowed)
-}
-
-func (m *cacheQueueManager) resumeAuthPausedFilter(siteID site.ID, onlyIDs []string) {
- m.mu.Lock()
- now := m.nowRFC3339()
- changed := false
- var notify []cacheQueueRecord
- for _, e := range m.tasks {
- if e.rec.Site != string(siteID) || e.rec.Status != CacheQueuePaused || e.rec.PauseReason != "auth_required" {
- continue
- }
- if onlyIDs != nil && !slices.Contains(onlyIDs, e.rec.ID) {
- continue
- }
- e.rec.Status = CacheQueueQueued
- e.rec.PauseReason = ""
- e.rec.StopReason = ""
- e.rec.NextRunAt = ""
- e.rec.UpdatedAt = now
- e.rt.resumePendingDownloads = len(e.rec.ActiveDownloadIDs) > 0
- changed = true
- notify = append(notify, e.rec)
- }
- if changed {
- _ = m.saveLocked()
- for _, r := range notify {
- m.notifyStateLocked(r)
- }
- }
- m.mu.Unlock()
- if changed {
- m.wakeSite(siteID)
- }
-}
-
-func (m *cacheQueueManager) hasSiteLogin(siteID site.ID) bool {
- if m.b == nil || m.b.credMgr == nil {
- return false
- }
- return m.b.credMgr.HasActiveCredential(string(siteID))
-}
-
-func (m *cacheQueueManager) siteBackoffOrQuotaEnd(siteID site.ID, now time.Time) (bool, time.Time) {
- if m.b == nil || m.b.subs == nil {
- return false, time.Time{}
- }
- nowUTC := now.UTC()
- var blocked bool
- var end time.Time
-
- if inBackoff, until := m.b.subs.IsSiteInBackoff(string(siteID)); inBackoff && until.After(nowUTC) {
- blocked = true
- end = until.UTC()
- }
- if !m.b.subs.CanUseSiteQuotaTokens(string(siteID), 1) {
- blocked = true
- st := m.b.subs.GetSiteSchedulerState(string(siteID))
- cutoff := nowUTC.Add(-time.Hour).Unix()
- var oldest int64
- for _, ts := range st.TokenTimestamps {
- if ts > cutoff && (oldest == 0 || ts < oldest) {
- oldest = ts
- }
- }
- quotaEnd := nowUTC.Add(time.Hour)
- if oldest > 0 {
- quotaEnd = time.Unix(oldest+3600, 0).UTC()
- }
- if quotaEnd.After(end) {
- end = quotaEnd
- }
- }
- return blocked, end
-}
-
-func (m *cacheQueueManager) backoffResumeTimeLocked(siteID site.ID, now time.Time) time.Time {
- nowUTC := now.UTC()
- _, baseEnd := m.siteBackoffOrQuotaEnd(siteID, nowUTC)
- if baseEnd.Before(nowUTC) {
- baseEnd = nowUTC
- }
- cool := m.randDurationLocked(m.pacing.BackoffCoolMinDelay, m.pacing.BackoffCoolMaxDelay)
- return baseEnd.Add(cool)
-}
-
-func backoffReasonText(kind string) string {
- switch kind {
- case site.ErrKindRiskControl:
- return "遇到站点风控,等待退避结束"
- case site.ErrKindRateLimited:
- return "遇到站点限流,等待退避结束"
- case site.ErrKindQuota:
- return "本小时自动请求额度已用完,等待额度恢复"
- default:
- return "站点处于退避期,等待退避结束"
- }
-}
-
-func isBackoffOrQuotaKind(kind string) bool {
- switch kind {
- case site.ErrKindRiskControl, site.ErrKindRateLimited, site.ErrKindQuota, site.ErrKindBackoff:
- return true
- }
- return false
-}
-
-func (m *cacheQueueManager) enterWaitingBackoffLocked(e *cacheQueueEntry, siteID site.ID, kind string) {
- if (kind == site.ErrKindRiskControl || kind == site.ErrKindRateLimited) && m.b != nil && m.b.subs != nil {
- if inBackoff, _ := m.b.subs.IsSiteInBackoff(string(siteID)); !inBackoff {
- m.b.subs.RecordSiteAutomaticStop(string(siteID), kind)
- }
- }
- now := m.clock.Now().UTC()
- resumeAt := m.backoffResumeTimeLocked(siteID, now)
- e.rec.Status = CacheQueueWaitingBackoff
- e.rec.PauseReason = ""
- e.rec.StopReason = backoffReasonText(kind)
- e.rec.NextRunAt = resumeAt.Format(time.RFC3339)
- e.rec.UpdatedAt = now.Format(time.RFC3339)
- e.rt.resumePendingDownloads = len(e.rec.ActiveDownloadIDs) > 0
- _ = m.saveLocked()
- m.notifyStateLocked(e.rec)
-}
-
-func (m *cacheQueueManager) selectActiveSiteEntryLocked(siteID site.ID) *cacheQueueEntry {
- for _, e := range m.tasks {
- if e.rec.Site != string(siteID) {
- continue
- }
- switch e.rec.Status {
- case CacheQueueRunning, CacheQueueWaiting, CacheQueueWaitingBackoff:
- return e
- }
- }
- for _, e := range m.tasks {
- if e.rec.Site != string(siteID) || e.rec.Status != CacheQueueQueued {
- continue
- }
- if !m.hasSiteLogin(siteID) {
- e.rec.Status = CacheQueuePaused
- e.rec.PauseReason = "auth_required"
- e.rec.StopReason = "未登录或登录已失效,重新登录后自动继续"
- e.rec.NextRunAt = ""
- e.rec.UpdatedAt = m.nowRFC3339()
- _ = m.saveLocked()
- m.notifyStateLocked(e.rec)
- continue
- }
- if e.rec.RestThreshold <= 0 {
- e.rec.RestThreshold = m.pickRestThresholdLocked()
- }
- e.rec.Status = CacheQueueRunning
- e.rec.PauseReason = ""
- e.rec.StopReason = ""
- e.rec.NextRunAt = ""
- e.rec.UpdatedAt = m.nowRFC3339()
- _ = m.saveLocked()
- m.notifyStateLocked(e.rec)
- return e
- }
- return nil
-}
-
-func (m *cacheQueueManager) runSiteLoop(ctx context.Context, siteID site.ID) {
- wakeCh := m.siteWake[siteID]
- for {
- if ctx.Err() != nil {
- return
- }
-
- m.mu.Lock()
- entry := m.selectActiveSiteEntryLocked(siteID)
- if entry == nil {
- m.mu.Unlock()
- select {
- case <-ctx.Done():
- return
- case <-wakeCh:
- continue
- }
- }
-
- // Phase A: Scheduled wait (inter-item delay, long rest, startup delay, or backoff cooldown).
- if entry.rec.Status == CacheQueueWaiting || entry.rec.Status == CacheQueueWaitingBackoff {
- nextAt, pErr := time.Parse(time.RFC3339, entry.rec.NextRunAt)
- now := m.clock.Now().UTC()
- if pErr == nil && now.Before(nextAt) {
- select {
- case <-wakeCh:
- default:
- }
- waitDur := nextAt.Sub(now)
- tm := m.clock.NewTimer(waitDur)
- m.mu.Unlock()
-
- select {
- case <-ctx.Done():
- tm.Stop()
- return
- case <-wakeCh:
- tm.Stop()
- continue
- case <-tm.C():
- }
- continue
- }
-
- if !m.hasSiteLogin(siteID) {
- m.mu.Unlock()
- m.pauseForSite(siteID, "auth_required", "未登录或登录已失效,重新登录后自动继续")
- continue
- }
- if blocked, _ := m.siteBackoffOrQuotaEnd(siteID, m.clock.Now()); blocked {
- kind := site.ErrKindBackoff
- if !m.b.subs.CanUseSiteQuotaTokens(string(siteID), 1) {
- kind = site.ErrKindQuota
- }
- m.enterWaitingBackoffLocked(entry, siteID, kind)
- m.mu.Unlock()
- continue
- }
- entry.rec.Status = CacheQueueRunning
- entry.rec.PauseReason = ""
- entry.rec.StopReason = ""
- entry.rec.NextRunAt = ""
- entry.rec.UpdatedAt = m.nowRFC3339()
- _ = m.saveLocked()
- m.notifyStateLocked(entry.rec)
- }
-
- if !m.hasSiteLogin(siteID) {
- m.mu.Unlock()
- m.pauseForSite(siteID, "auth_required", "未登录或登录已失效,重新登录后自动继续")
- continue
- }
-
- // Phase B: Monitor or resume the single active derived download item.
- if len(entry.rec.ActiveDownloadIDs) > 0 {
- activeIDs := append([]string(nil), entry.rec.ActiveDownloadIDs...)
- needResume := entry.rt.resumePendingDownloads
- entry.rt.resumePendingDownloads = false
- m.mu.Unlock()
-
- if needResume && m.b != nil && m.b.dl != nil {
- for _, dlID := range activeIDs {
- if t, ok, err := m.b.dl.GetTask(dlID); err == nil && ok && t.Status == "paused" {
- _, _ = m.b.dl.Resume(dlID)
- }
- }
- }
-
- stillRunning := false
- var authStopped bool
- var backoffKind string
- var appClosed bool
- var userPaused bool
- allSucceeded := true
-
- if m.b != nil && m.b.dl != nil {
- for _, dlID := range activeIDs {
- t, ok, err := m.b.dl.GetTask(dlID)
- if err != nil || !ok {
- allSucceeded = false
- continue
- }
- switch t.Status {
- case "queued", "running", "downloading", "muxing":
- stillRunning = true
- case "completed":
- // Part succeeded.
- case "partial":
- if m.b != nil && m.b.lib != nil {
- checkKey := firstNonEmpty(t.ItemKey, entry.rec.ActiveItemKey)
- if _, exists, lErr := m.b.lib.GetItem(checkKey); lErr != nil || !exists {
- allSucceeded = false
- }
- }
- case "paused":
- allSucceeded = false
- switch {
- case t.PauseReason == "auth_required" || t.ErrorKind == site.ErrKindAuthRequired:
- authStopped = true
- case t.PauseReason == "risk_control" || isBackoffOrQuotaKind(t.PauseReason) || isBackoffOrQuotaKind(t.ErrorKind):
- backoffKind = firstNonEmpty(t.ErrorKind, t.PauseReason)
- case t.PauseReason == "app_closed":
- appClosed = true
- default:
- userPaused = true
- }
- default: // "failed", "canceled"
- allSucceeded = false
- if t.ErrorKind == site.ErrKindAuthRequired {
- authStopped = true
- } else if isBackoffOrQuotaKind(t.ErrorKind) {
- backoffKind = t.ErrorKind
- }
- }
- }
- }
-
- if stillRunning {
- select {
- case <-ctx.Done():
- return
- case <-wakeCh:
- continue
- }
- }
- if appClosed || ctx.Err() != nil {
- return
- }
-
- m.mu.Lock()
- if entry.rec.Status != CacheQueueRunning || !slices.Equal(entry.rec.ActiveDownloadIDs, activeIDs) {
- m.mu.Unlock()
- continue
- }
- if authStopped {
- m.mu.Unlock()
- m.pauseForSite(siteID, "auth_required", "登录已失效,重新登录后自动继续")
- continue
- }
- if backoffKind != "" {
- m.enterWaitingBackoffLocked(entry, siteID, backoffKind)
- m.mu.Unlock()
- continue
- }
- if userPaused {
- entry.rec.Status = CacheQueuePaused
- entry.rec.PauseReason = "user"
- entry.rec.StopReason = "已手动暂停"
- entry.rec.NextRunAt = ""
- entry.rec.UpdatedAt = m.nowRFC3339()
- entry.rt.resumePendingDownloads = true
- _ = m.saveLocked()
- m.notifyStateLocked(entry.rec)
- m.mu.Unlock()
- continue
- }
-
- // If this was a multi-part video with remaining parts, enqueue the next part before marking the video done.
- if allSucceeded && len(entry.rt.nextPartEnqueuers) > 0 {
- nextPart := entry.rt.nextPartEnqueuers[0]
- stepCtx, stepCancel := context.WithCancel(site.WithAutomaticRequests(ctx, "cache_queue"))
- entry.rt.stepCancel = stepCancel
- m.mu.Unlock()
-
- pids, pErr := nextPart(stepCtx)
-
- m.mu.Lock()
- stepCancel()
- if entry.rt.stepCancel != nil {
- entry.rt.stepCancel = nil
- }
- if entry.rec.Status != CacheQueueRunning || ctx.Err() != nil {
- m.mu.Unlock()
- continue
- }
- if pErr != nil {
- kind := site.KindOf(pErr)
- if kind == site.ErrKindAuthRequired {
- m.mu.Unlock()
- m.pauseForSite(siteID, "auth_required", "登录已失效,重新登录后自动继续")
- continue
- }
- if isBackoffOrQuotaKind(kind) {
- m.enterWaitingBackoffLocked(entry, siteID, kind)
- m.mu.Unlock()
- continue
- }
- entry.rt.nextPartEnqueuers = nil
- m.finishItemOutcomeLocked(entry, false)
- m.mu.Unlock()
- continue
- }
- entry.rt.nextPartEnqueuers = entry.rt.nextPartEnqueuers[1:]
- entry.rec.ActiveDownloadIDs = pids
- entry.rec.UpdatedAt = m.nowRFC3339()
- _ = m.saveLocked()
- m.mu.Unlock()
- continue
- }
-
- m.finishItemOutcomeLocked(entry, allSucceeded)
- m.mu.Unlock()
- continue
- }
-
- // Phase C: Inspect candidates or fetch next page, skipping cached/uncacheable items without waiting.
- m.advanceCandidateStep(ctx, siteID, entry)
- }
-}
-
-func (m *cacheQueueManager) finishItemOutcomeLocked(entry *cacheQueueEntry, cached bool) {
- nowStr := m.nowRFC3339()
- itemKey := entry.rec.ActiveItemKey
- title := entry.rec.ActiveTitle
- entry.rec.ActiveDownloadIDs = nil
- entry.rec.ActiveItemKey = ""
- entry.rec.ActiveTitle = ""
- entry.rt.nextPartEnqueuers = nil
-
- if itemKey != "" && !slices.Contains(entry.rec.ProcessedKeys, itemKey) {
- entry.rec.ProcessedKeys = append(entry.rec.ProcessedKeys, itemKey)
- }
-
- if cached {
- entry.rec.CachedCount++
- entry.rec.SinceRestCount++
- if itemKey != "" {
- if title == "" && m.b != nil && m.b.lib != nil {
- if meta, ok, err := m.b.lib.GetItem(itemKey); err == nil && ok && meta.Title != "" {
- title = trimQueueSummaryTitle(meta.Title)
- }
- }
- 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]
- }
- }
- } else {
- entry.rec.SkippedCount++
- }
-
- // If the current page buffer is exhausted and there are no further pages, complete immediately.
- if entry.rt.pageLoaded && entry.rt.pageIdx >= len(entry.rt.pageItems) && !entry.rt.pageNextHasMore {
- entry.rec.Cursor = sanitizeCursor(entry.rt.pageNextCursor)
- entry.rec.HasMore = false
- entry.rec.ProcessedKeys = nil
- entry.rt.pageLoaded = false
- entry.rt.pageItems = nil
- entry.rt.pageIdx = 0
- entry.rec.Status = CacheQueueCompleted
- entry.rec.PauseReason = ""
- entry.rec.StopReason = ""
- entry.rec.NextRunAt = ""
- entry.rec.UpdatedAt = nowStr
- _ = m.saveLocked()
- m.notifyStateLocked(entry.rec)
- return
- }
-
- if entry.rec.RestThreshold <= 0 {
- entry.rec.RestThreshold = m.pickRestThresholdLocked()
- }
- 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)
- }
- nextAt := m.clock.Now().UTC().Add(delay)
- entry.rec.Status = CacheQueueWaiting
- entry.rec.PauseReason = ""
- entry.rec.StopReason = reason
- entry.rec.NextRunAt = nextAt.Format(time.RFC3339)
- entry.rec.UpdatedAt = nowStr
- _ = m.saveLocked()
- m.notifyStateLocked(entry.rec)
-}
-
-func (m *cacheQueueManager) advanceCandidateStep(ctx context.Context, siteID site.ID, entry *cacheQueueEntry) {
- // Caller holds m.mu on entry; this method unlocks m.mu before returning!
- if entry.rt.pager == nil && m.b != nil {
- pager, err := m.b.buildQueuePager(siteID, entry.rec.List, entry.rec.User)
- if err != nil {
- entry.rec.Status = CacheQueueStopped
- entry.rec.StopReason = sanitizeQueueText(err.Error())
- entry.rec.UpdatedAt = m.nowRFC3339()
- _ = m.saveLocked()
- m.notifyStateLocked(entry.rec)
- m.mu.Unlock()
- return
- }
- entry.rt.pager = pager
- }
-
- // Exhausted current buffered page? Advance persistent cursor.
- if entry.rt.pageLoaded && entry.rt.pageIdx >= len(entry.rt.pageItems) {
- entry.rec.Cursor = sanitizeCursor(entry.rt.pageNextCursor)
- entry.rec.HasMore = entry.rt.pageNextHasMore
- entry.rec.ProcessedKeys = nil
- entry.rt.pageLoaded = false
- entry.rt.pageItems = nil
- entry.rt.pageIdx = 0
- entry.rec.UpdatedAt = m.nowRFC3339()
- if !entry.rec.HasMore {
- entry.rec.Status = CacheQueueCompleted
- entry.rec.PauseReason = ""
- entry.rec.StopReason = ""
- entry.rec.NextRunAt = ""
- _ = m.saveLocked()
- m.notifyStateLocked(entry.rec)
- m.mu.Unlock()
- return
- }
- _ = m.saveLocked()
- }
-
- // Fetch next page if no buffered page is loaded.
- if !entry.rt.pageLoaded {
- if !entry.rec.HasMore {
- entry.rec.Status = CacheQueueCompleted
- entry.rec.PauseReason = ""
- entry.rec.StopReason = ""
- entry.rec.NextRunAt = ""
- entry.rec.UpdatedAt = m.nowRFC3339()
- _ = m.saveLocked()
- m.notifyStateLocked(entry.rec)
- m.mu.Unlock()
- return
- }
- if blocked, _ := m.siteBackoffOrQuotaEnd(siteID, m.clock.Now()); blocked {
- kind := site.ErrKindBackoff
- if !m.b.subs.CanUseSiteQuotaTokens(string(siteID), 1) {
- kind = site.ErrKindQuota
- }
- m.enterWaitingBackoffLocked(entry, siteID, kind)
- m.mu.Unlock()
- return
- }
-
- cursor := entry.rec.Cursor
- pager := entry.rt.pager
- stepCtx, stepCancel := context.WithCancel(site.WithAutomaticRequests(ctx, "cache_queue"))
- entry.rt.stepCancel = stepCancel
- m.mu.Unlock()
-
- items, nextCursor, nextMore, err := pager(stepCtx, cursor)
-
- m.mu.Lock()
- stepCancel()
- if entry.rt.stepCancel != nil {
- entry.rt.stepCancel = nil
- }
- if entry.rec.Status != CacheQueueRunning || ctx.Err() != nil {
- m.mu.Unlock()
- return
- }
- if err != nil {
- kind := site.KindOf(err)
- if kind == site.ErrKindAuthRequired {
- m.mu.Unlock()
- m.pauseForSite(siteID, "auth_required", "登录已失效,重新登录后自动继续")
- return
- }
- if isBackoffOrQuotaKind(kind) {
- m.enterWaitingBackoffLocked(entry, siteID, kind)
- m.mu.Unlock()
- return
- }
- entry.rec.Status = CacheQueueStopped
- entry.rec.StopReason = sanitizeQueueText("读取列表失败:" + err.Error())
- entry.rec.NextRunAt = ""
- entry.rec.UpdatedAt = m.nowRFC3339()
- _ = m.saveLocked()
- m.notifyStateLocked(entry.rec)
- m.mu.Unlock()
- return
- }
- if len(items) == 0 {
- entry.rec.Cursor = sanitizeCursor(nextCursor)
- entry.rec.HasMore = false
- entry.rec.ProcessedKeys = nil
- entry.rec.Status = CacheQueueCompleted
- entry.rec.PauseReason = ""
- entry.rec.StopReason = ""
- entry.rec.NextRunAt = ""
- entry.rec.UpdatedAt = m.nowRFC3339()
- _ = m.saveLocked()
- m.notifyStateLocked(entry.rec)
- m.mu.Unlock()
- return
- }
- entry.rt.pageItems = items
- entry.rt.pageIdx = 0
- entry.rt.pageNextCursor = nextCursor
- entry.rt.pageNextHasMore = nextMore
- entry.rt.pageLoaded = true
- }
-
- // Scan buffered page items: skip cached/uncacheable items immediately without waiting.
- var keysToCheck []string
- for i := entry.rt.pageIdx; i < len(entry.rt.pageItems); i++ {
- if k := entry.rt.pageItems[i].key; k != "" {
- keysToCheck = append(keysToCheck, k)
- }
- }
- var states map[string]string
- if m.b != nil && len(keysToCheck) > 0 {
- rawStates := m.b.States(keysToCheck)
- states = make(map[string]string, len(rawStates))
- for k, st := range rawStates {
- states[k] = st.Dot
- }
- }
-
- skippedAny := false
- for entry.rt.pageIdx < len(entry.rt.pageItems) {
- cand := entry.rt.pageItems[entry.rt.pageIdx]
- if cand.key == "" {
- entry.rt.pageIdx++
- entry.rec.SkippedCount++
- skippedAny = true
- continue
- }
- if entry.rt.seenKeys[cand.key] || slices.Contains(entry.rec.ProcessedKeys, cand.key) {
- entry.rt.seenKeys[cand.key] = true
- entry.rt.pageIdx++
- continue
- }
- dot := states[cand.key]
- alreadyCachedOrActive := dot == "green" || dot == "yellow" || dot == "ring"
- if cand.uncacheable || alreadyCachedOrActive {
- entry.rt.seenKeys[cand.key] = true
- entry.rt.pageIdx++
- entry.rec.SkippedCount++
- if !slices.Contains(entry.rec.ProcessedKeys, cand.key) {
- entry.rec.ProcessedKeys = append(entry.rec.ProcessedKeys, cand.key)
- }
- skippedAny = true
- continue
- }
-
- // Found an uncached candidate! Check backoff/quota before calling cand.enqueue.
- if blocked, _ := m.siteBackoffOrQuotaEnd(siteID, m.clock.Now()); blocked {
- if skippedAny {
- entry.rec.UpdatedAt = m.nowRFC3339()
- }
- kind := site.ErrKindBackoff
- if !m.b.subs.CanUseSiteQuotaTokens(string(siteID), 1) {
- kind = site.ErrKindQuota
- }
- m.enterWaitingBackoffLocked(entry, siteID, kind)
- m.mu.Unlock()
- return
- }
-
- stepCtx, stepCancel := context.WithCancel(site.WithAutomaticRequests(ctx, "cache_queue"))
- entry.rt.stepCancel = stepCancel
- if skippedAny {
- entry.rec.UpdatedAt = m.nowRFC3339()
- _ = m.saveLocked()
- skippedAny = false
- }
- m.mu.Unlock()
-
- enq, err := cand.enqueue(stepCtx)
-
- m.mu.Lock()
- stepCancel()
- if entry.rt.stepCancel != nil {
- entry.rt.stepCancel = nil
- }
- if entry.rec.Status != CacheQueueRunning || ctx.Err() != nil {
- m.mu.Unlock()
- return
- }
- if err != nil {
- kind := site.KindOf(err)
- if kind == site.ErrKindAuthRequired {
- m.mu.Unlock()
- m.pauseForSite(siteID, "auth_required", "登录已失效,重新登录后自动继续")
- return
- }
- if isBackoffOrQuotaKind(kind) {
- m.enterWaitingBackoffLocked(entry, siteID, kind)
- m.mu.Unlock()
- return
- }
- // Ordinary per-item failure (e.g. deleted/unavailable). The attempt already sent
- // site requests, so count it as skipped and keep the normal random gap before the
- // next candidate: a run of failing items must not turn into back-to-back requests.
- entry.rt.seenKeys[cand.key] = true
- entry.rt.pageIdx++
- entry.rec.ActiveItemKey = cand.key
- entry.rec.ActiveTitle = ""
- m.finishItemOutcomeLocked(entry, false)
- m.mu.Unlock()
- return
- }
-
- // Enqueue succeeded!
- entry.rt.seenKeys[cand.key] = true
- entry.rt.pageIdx++
- entry.rec.ActiveItemKey = sanitizeItemKey(firstNonEmpty(enq.itemKey, cand.key))
- entry.rec.ActiveTitle = sanitizeQueueText(firstNonEmpty(enq.title, cand.title))
- if len(enq.taskIDs) == 0 {
- // Synchronous completion (used by synthetic candidate tests with no async download task).
- m.finishItemOutcomeLocked(entry, true)
- m.mu.Unlock()
- return
- }
- entry.rec.ActiveDownloadIDs = append([]string(nil), enq.taskIDs...)
- entry.rt.nextPartEnqueuers = enq.nextParts
- entry.rt.resumePendingDownloads = false
- entry.rec.UpdatedAt = m.nowRFC3339()
- _ = m.saveLocked()
- m.notifyStateLocked(entry.rec)
- m.mu.Unlock()
- return
- }
-
- if skippedAny {
- entry.rec.UpdatedAt = m.nowRFC3339()
- _ = m.saveLocked()
- m.notifyStateLocked(entry.rec)
- }
- m.mu.Unlock()
-}
-
-// ListCacheQueue returns all background cache queue tasks in queue order.
-func (b *Backend) ListCacheQueue() []CacheQueueTask {
- if b.requireAnyLogin() != nil || b.queue == nil {
- return nil
- }
- b.queue.mu.Lock()
- defer b.queue.mu.Unlock()
- out := make([]CacheQueueTask, 0, len(b.queue.tasks))
- for _, e := range b.queue.tasks {
- out = append(out, b.queue.toDTOLocked(e))
- }
- return out
-}
-
-// FindCacheQueueTask reports whether (siteID, user, list) already has an unfinished task in the cache queue.
-func (b *Backend) FindCacheQueueTask(siteID, user, list string) (CacheQueueTask, bool) {
- if b.requireAnyLogin() != nil || b.queue == nil {
- return CacheQueueTask{}, false
- }
- normSite, normList, normUser, err := normalizeCacheQueueTarget(siteID, list, user)
- if err != nil {
- return CacheQueueTask{}, false
- }
- b.queue.mu.Lock()
- defer b.queue.mu.Unlock()
- for _, e := range b.queue.tasks {
- if e.rec.Site == string(normSite) && e.rec.User == normUser && e.rec.List == normList && isUnfinishedQueueStatus(e.rec.Status) {
- return b.queue.toDTOLocked(e), true
- }
- }
- return CacheQueueTask{}, false
-}
-
-// EnqueueCacheQueue creates or deduplicates a background cache queue task for one creator's list.
-func (b *Backend) EnqueueCacheQueue(ctx context.Context, req CacheQueueRequest) (CacheQueueTask, error) {
- _ = ctx
- normSite, normList, normUser, err := normalizeCacheQueueTarget(req.Site, req.List, req.User)
- if err != nil {
- return CacheQueueTask{}, err
- }
- if err := b.requireSiteLogin(normSite); err != nil {
- return CacheQueueTask{}, err
- }
- loaded, pager, err := b.buildQueueLoadedAndPager(normSite, normList, normUser, req)
- if err != nil {
- return CacheQueueTask{}, err
- }
- if strings.TrimSpace(req.AvatarURL) != "" {
- b.rememberQueueAvatar(string(normSite), normUser, req.AvatarURL)
- }
- return b.enqueueCacheQueueWithPager(normSite, normList, normUser, req, loaded, pager)
-}
-
-// queueListLabel names the list; a run a full-cache rule started says so.
-func queueListLabel(rec cacheQueueRecord) string {
- label := cacheQueueListLabel(rec.Site, rec.List)
- if rec.Origin == QueueOriginFullCache {
- return "定期全部缓存 · " + label
- }
- return label
-}
-
-func queueOrigin(o string) string {
- if o == QueueOriginFullCache {
- return o
- }
- return ""
-}
-
-func (b *Backend) enqueueCacheQueueWithPager(
- normSite site.ID,
- normList, normUser string,
- req CacheQueueRequest,
- loaded []queueCandidate,
- pager queuePager,
-) (CacheQueueTask, error) {
- if b.queue == nil {
- return CacheQueueTask{}, fmt.Errorf("service: cache queue not initialized")
- }
- m := b.queue
- m.mu.Lock()
-
- now := m.nowRFC3339()
- avatarKey := avatarFileName(string(normSite), normUser)
- cleanName := sanitizeQueueText(req.UserName)
-
- // 1. Deduplicate if an unfinished task already exists for (site, user, list).
- for _, e := range m.tasks {
- if e.rec.Site == string(normSite) && e.rec.User == normUser && e.rec.List == normList && isUnfinishedQueueStatus(e.rec.Status) {
- changed := false
- if cleanName != "" && e.rec.UserName != cleanName {
- e.rec.UserName = cleanName
- changed = true
- }
- if avatarKey != "" && e.rec.AvatarKey != avatarKey {
- e.rec.AvatarKey = avatarKey
- changed = true
- }
- if changed {
- e.rec.UpdatedAt = now
- _ = m.saveLocked()
- }
- dto := m.toDTOLocked(e)
- m.mu.Unlock()
- return dto, nil
- }
- }
-
- // 2. Remove any previous finished (completed/stopped) entry for the same (site, user, list) so restarting keeps one clean entry.
- createdAt := now
- taskID := makeCacheQueueID(string(normSite), normList, normUser)
- for i, e := range m.tasks {
- if e.rec.Site == string(normSite) && e.rec.User == normUser && e.rec.List == normList {
- if cleanName == "" {
- cleanName = e.rec.UserName
- }
- taskID = e.rec.ID
- m.tasks = append(m.tasks[:i], m.tasks[i+1:]...)
- break
- }
- }
-
- rec := cacheQueueRecord{
- ID: taskID,
- Site: string(normSite),
- User: normUser,
- UserName: cleanName,
- AvatarKey: avatarKey,
- List: normList,
- Origin: queueOrigin(req.Origin),
- Cursor: "",
- HasMore: true,
- RestThreshold: m.pickRestThresholdLocked(),
- Status: CacheQueueQueued,
- CreatedAt: createdAt,
- UpdatedAt: now,
- }
- rt := cacheQueueRuntime{
- pager: pager,
- seenKeys: make(map[string]bool),
- }
- if len(loaded) > 0 {
- rt.pageItems = loaded
- rt.pageIdx = 0
- rt.pageNextCursor = sanitizeCursor(req.Cursor)
- rt.pageNextHasMore = req.HasMore && (normSite == site.Bilibili && normList == "videos" || rt.pageNextCursor != "")
- rt.pageLoaded = true
- } else if cleanCur := sanitizeCursor(req.Cursor); cleanCur != "" {
- rec.Cursor = cleanCur
- rec.HasMore = req.HasMore
- }
-
- entry := &cacheQueueEntry{rec: rec, rt: rt}
- m.tasks = append(m.tasks, entry)
- if err := m.saveLocked(); err != nil {
- m.mu.Unlock()
- return CacheQueueTask{}, err
- }
- m.notifyStateLocked(entry.rec)
- dto := m.toDTOLocked(entry)
- m.mu.Unlock()
-
- m.wakeSite(normSite)
- return dto, nil
-}
-
-// PauseCacheQueue pauses an unfinished background cache queue task and any derived download task in flight.
-func (b *Backend) PauseCacheQueue(id string) (CacheQueueTask, error) {
- if err := b.requireAnyLogin(); err != nil {
- return CacheQueueTask{}, err
- }
- if b.queue == nil {
- return CacheQueueTask{}, &site.Error{Kind: site.ErrKindUnavailable, Message: "未找到该缓存队列任务"}
- }
- target := strings.TrimSpace(id)
- m := b.queue
- m.mu.Lock()
- var found *cacheQueueEntry
- for _, e := range m.tasks {
- if e.rec.ID == target {
- found = e
- break
- }
- }
- if found == nil {
- m.mu.Unlock()
- return CacheQueueTask{}, &site.Error{Kind: site.ErrKindUnavailable, Message: "未找到该缓存队列任务"}
- }
- if !isUnfinishedQueueStatus(found.rec.Status) {
- m.mu.Unlock()
- return CacheQueueTask{}, &site.Error{Kind: site.ErrKindBadRequest, Message: "该缓存队列任务已结束"}
- }
- if found.rt.stepCancel != nil {
- found.rt.stepCancel()
- found.rt.stepCancel = nil
- }
- activeIDs := append([]string(nil), found.rec.ActiveDownloadIDs...)
- found.rec.Status = CacheQueuePaused
- found.rec.PauseReason = "user"
- found.rec.StopReason = "已手动暂停"
- found.rec.NextRunAt = ""
- found.rec.UpdatedAt = m.nowRFC3339()
- found.rt.resumePendingDownloads = len(activeIDs) > 0
- if err := m.saveLocked(); err != nil {
- m.mu.Unlock()
- return CacheQueueTask{}, err
- }
- m.notifyStateLocked(found.rec)
- dto := m.toDTOLocked(found)
- siteID := site.ID(found.rec.Site)
- m.mu.Unlock()
-
- if b.dl != nil {
- for _, dlID := range activeIDs {
- if t, ok, err := b.dl.GetTask(dlID); err == nil && ok && (t.Status == "queued" || t.Status == "running") {
- _, _ = b.dl.Pause(dlID)
- }
- }
- }
- m.wakeSite(siteID)
- return dto, nil
-}
-
-// ResumeCacheQueue resumes a paused background cache queue task on its site.
-func (b *Backend) ResumeCacheQueue(id string) (CacheQueueTask, error) {
- if b.queue == nil {
- return CacheQueueTask{}, &site.Error{Kind: site.ErrKindUnavailable, Message: "未找到该缓存队列任务"}
- }
- target := strings.TrimSpace(id)
- m := b.queue
- m.mu.Lock()
- var found *cacheQueueEntry
- for _, e := range m.tasks {
- if e.rec.ID == target {
- found = e
- break
- }
- }
- if found == nil {
- m.mu.Unlock()
- return CacheQueueTask{}, &site.Error{Kind: site.ErrKindUnavailable, Message: "未找到该缓存队列任务"}
- }
- siteID := site.ID(found.rec.Site)
- m.mu.Unlock()
-
- if err := b.requireSiteLogin(siteID); err != nil {
- return CacheQueueTask{}, err
- }
-
- m.mu.Lock()
- if !isUnfinishedQueueStatus(found.rec.Status) {
- m.mu.Unlock()
- return CacheQueueTask{}, &site.Error{Kind: site.ErrKindBadRequest, Message: "该缓存队列任务已结束,请重新加入队列"}
- }
- if found.rec.Status != CacheQueuePaused {
- dto := m.toDTOLocked(found)
- m.mu.Unlock()
- return dto, nil
- }
- found.rec.Status = CacheQueueQueued
- found.rec.PauseReason = ""
- found.rec.StopReason = ""
- found.rec.NextRunAt = ""
- found.rec.UpdatedAt = m.nowRFC3339()
- found.rt.resumePendingDownloads = len(found.rec.ActiveDownloadIDs) > 0
- if err := m.saveLocked(); err != nil {
- m.mu.Unlock()
- return CacheQueueTask{}, err
- }
- m.notifyStateLocked(found.rec)
- dto := m.toDTOLocked(found)
- m.mu.Unlock()
-
- m.wakeSite(siteID)
- return dto, nil
-}
-
-// CancelCacheQueue stops scheduling a background cache queue task and cancels its single unfinished
-// derived download task (if any) without ever deleting items already cached in the local media library.
-func (b *Backend) CancelCacheQueue(id string) (CacheQueueTask, error) {
- if err := b.requireAnyLogin(); err != nil {
- return CacheQueueTask{}, err
- }
- if b.queue == nil {
- return CacheQueueTask{}, &site.Error{Kind: site.ErrKindUnavailable, Message: "未找到该缓存队列任务"}
- }
- target := strings.TrimSpace(id)
- m := b.queue
- m.mu.Lock()
- var found *cacheQueueEntry
- for _, e := range m.tasks {
- if e.rec.ID == target {
- found = e
- break
- }
- }
- if found == nil {
- m.mu.Unlock()
- return CacheQueueTask{}, &site.Error{Kind: site.ErrKindUnavailable, Message: "未找到该缓存队列任务"}
- }
- if !isUnfinishedQueueStatus(found.rec.Status) {
- dto := m.toDTOLocked(found)
- m.mu.Unlock()
- return dto, nil
- }
- if found.rt.stepCancel != nil {
- found.rt.stepCancel()
- found.rt.stepCancel = nil
- }
- activeIDs := append([]string(nil), found.rec.ActiveDownloadIDs...)
- siteID := site.ID(found.rec.Site)
- found.rt.nextPartEnqueuers = nil
- found.rt.resumePendingDownloads = false
- found.rec.ActiveDownloadIDs = nil
- found.rec.ActiveItemKey = ""
- found.rec.ActiveTitle = ""
- found.rec.Status = CacheQueueStopped
- found.rec.PauseReason = ""
- found.rec.StopReason = "已取消"
- found.rec.NextRunAt = ""
- found.rec.UpdatedAt = m.nowRFC3339()
- if err := m.saveLocked(); err != nil {
- m.mu.Unlock()
- return CacheQueueTask{}, err
- }
- m.notifyStateLocked(found.rec)
- dto := m.toDTOLocked(found)
- m.mu.Unlock()
-
- if b.dl != nil {
- for _, dlID := range activeIDs {
- if t, ok, err := b.dl.GetTask(dlID); err == nil && ok && t.Status != "completed" && t.Status != "partial" && t.Status != "canceled" {
- _, _ = b.dl.Cancel(dlID)
- }
- }
- }
- b.pruneAccountAvatars()
- m.wakeSite(siteID)
- return dto, nil
-}
-
-// RemoveCacheQueue deletes a finished (completed, canceled or stopped) cache
-// queue task from the task list. Unfinished tasks must be canceled first.
-// Items it cached stay in the media library.
-func (b *Backend) RemoveCacheQueue(id string) error {
- _, err := b.removeCacheQueues(func(rec cacheQueueRecord) bool { return rec.ID == strings.TrimSpace(id) }, true)
- return err
-}
-
-// RemoveFinishedCacheQueues deletes every finished cache queue task and
-// returns how many were removed.
-func (b *Backend) RemoveFinishedCacheQueues() (int, error) {
- return b.removeCacheQueues(func(rec cacheQueueRecord) bool { return !isUnfinishedQueueStatus(rec.Status) }, false)
-}
-
-func (b *Backend) removeCacheQueues(match func(cacheQueueRecord) bool, single bool) (int, error) {
- if b.queue == nil {
- if single {
- return 0, &site.Error{Kind: site.ErrKindUnavailable, Message: "未找到该缓存队列任务"}
- }
- return 0, nil
- }
- m := b.queue
- m.mu.Lock()
- kept := make([]*cacheQueueEntry, 0, len(m.tasks))
- var removed []cacheQueueRecord
- for _, e := range m.tasks {
- if !match(e.rec) {
- kept = append(kept, e)
- continue
- }
- if isUnfinishedQueueStatus(e.rec.Status) {
- if single {
- m.mu.Unlock()
- return 0, &site.Error{Kind: site.ErrKindBadRequest, Message: "缓存队列还在进行,请先取消再移除"}
- }
- kept = append(kept, e)
- continue
- }
- removed = append(removed, e.rec)
- }
- if len(removed) == 0 {
- m.mu.Unlock()
- if single {
- return 0, &site.Error{Kind: site.ErrKindUnavailable, Message: "未找到该缓存队列任务"}
- }
- return 0, nil
- }
- prev := m.tasks
- m.tasks = kept
- if err := m.saveLocked(); err != nil {
- m.tasks = prev
- m.mu.Unlock()
- return 0, err
- }
- for _, rec := range removed {
- rec.Status = "removed"
- m.notifyStateLocked(rec)
- }
- m.mu.Unlock()
- b.pruneAccountAvatars()
- return len(removed), nil
-}
-
-func (b *Backend) snapshotAuthPausedQueueIDs(siteID site.ID) []string {
- if b.queue == nil {
- return nil
- }
- return b.queue.snapshotAuthPausedIDs(siteID)
-}
-
-func (b *Backend) resumeAuthPausedQueueIDs(siteID site.ID, ids []string) {
- if b.queue != nil {
- b.queue.resumeAuthPausedIDs(siteID, ids)
- }
-}
diff --git a/internal/service/cache_queue_api.go b/internal/service/cache_queue_api.go
new file mode 100644
index 0000000..dedddfc
--- /dev/null
+++ b/internal/service/cache_queue_api.go
@@ -0,0 +1,467 @@
+package service
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/chialecode/trace/internal/site"
+)
+
+// ListCacheQueue returns all background cache queue tasks in queue order.
+func (b *Backend) ListCacheQueue() []CacheQueueTask {
+ if b.requireAnyLogin() != nil || b.queue == nil {
+ return nil
+ }
+ b.queue.mu.Lock()
+ defer b.queue.mu.Unlock()
+ out := make([]CacheQueueTask, 0, len(b.queue.tasks))
+ for _, e := range b.queue.tasks {
+ out = append(out, b.queue.toDTOLocked(e))
+ }
+ return out
+}
+
+// FindCacheQueueTask reports whether (siteID, user, list) already has an unfinished task in the cache queue.
+func (b *Backend) FindCacheQueueTask(siteID, user, list string) (CacheQueueTask, bool) {
+ if b.requireAnyLogin() != nil || b.queue == nil {
+ return CacheQueueTask{}, false
+ }
+ normSite, normList, normUser, err := normalizeCacheQueueTarget(siteID, list, user)
+ if err != nil {
+ return CacheQueueTask{}, false
+ }
+ b.queue.mu.Lock()
+ defer b.queue.mu.Unlock()
+ for _, e := range b.queue.tasks {
+ if e.rec.Site == string(normSite) && e.rec.User == normUser && e.rec.List == normList && isUnfinishedQueueStatus(e.rec.Status) {
+ return b.queue.toDTOLocked(e), true
+ }
+ }
+ return CacheQueueTask{}, false
+}
+
+// EnqueueCacheQueue creates or deduplicates a background cache queue task for one creator's list.
+func (b *Backend) EnqueueCacheQueue(ctx context.Context, req CacheQueueRequest) (CacheQueueTask, error) {
+ _ = ctx
+ if err := b.requireDesktop(); err != nil {
+ return CacheQueueTask{}, err
+ }
+ normSite, normList, normUser, err := normalizeCacheQueueTarget(req.Site, req.List, req.User)
+ if err != nil {
+ return CacheQueueTask{}, err
+ }
+ if err := b.requireSiteLogin(normSite); err != nil {
+ return CacheQueueTask{}, err
+ }
+ loaded, pager, err := b.buildQueueLoadedAndPager(normSite, normList, normUser, req)
+ if err != nil {
+ return CacheQueueTask{}, err
+ }
+ if strings.TrimSpace(req.AvatarURL) != "" {
+ b.rememberQueueAvatar(string(normSite), normUser, req.AvatarURL)
+ }
+ return b.enqueueCacheQueueWithPager(normSite, normList, normUser, req, loaded, pager)
+}
+
+// queueListLabel names the list; a run a full-cache rule started says so.
+func queueListLabel(rec cacheQueueRecord) string {
+ label := cacheQueueListLabel(rec.Site, rec.List)
+ if rec.Origin == QueueOriginFullCache {
+ return "定期全部缓存 · " + label
+ }
+ return label
+}
+
+func queueOrigin(o string) string {
+ if o == QueueOriginFullCache {
+ return o
+ }
+ return ""
+}
+
+func (b *Backend) enqueueCacheQueueWithPager(
+ normSite site.ID,
+ normList, normUser string,
+ req CacheQueueRequest,
+ loaded []queueCandidate,
+ pager queuePager,
+) (CacheQueueTask, error) {
+ if b.queue == nil {
+ return CacheQueueTask{}, fmt.Errorf("service: cache queue not initialized")
+ }
+ m := b.queue
+ m.mu.Lock()
+
+ now := m.nowRFC3339()
+ avatarKey := avatarFileName(string(normSite), normUser)
+ cleanName := sanitizeQueueText(req.UserName)
+
+ // 1. Deduplicate if an unfinished task already exists for (site, user, list).
+ for _, e := range m.tasks {
+ if e.rec.Site == string(normSite) && e.rec.User == normUser && e.rec.List == normList && isUnfinishedQueueStatus(e.rec.Status) {
+ changed := false
+ if cleanName != "" && e.rec.UserName != cleanName {
+ e.rec.UserName = cleanName
+ changed = true
+ }
+ if avatarKey != "" && e.rec.AvatarKey != avatarKey {
+ e.rec.AvatarKey = avatarKey
+ changed = true
+ }
+ if changed {
+ e.rec.UpdatedAt = now
+ m.saveLoggedLocked("dedup_update")
+ }
+ dto := m.toDTOLocked(e)
+ m.mu.Unlock()
+ return dto, nil
+ }
+ }
+
+ // 2. Remove any previous finished (completed/stopped) entry for the same (site, user, list) so restarting keeps one clean entry.
+ prevTasks := append([]*cacheQueueEntry(nil), m.tasks...)
+ createdAt := now
+ taskID := makeCacheQueueID(string(normSite), normList, normUser)
+ for i, e := range m.tasks {
+ if e.rec.Site == string(normSite) && e.rec.User == normUser && e.rec.List == normList {
+ if cleanName == "" {
+ cleanName = e.rec.UserName
+ }
+ taskID = e.rec.ID
+ m.tasks = append(m.tasks[:i], m.tasks[i+1:]...)
+ break
+ }
+ }
+
+ rec := cacheQueueRecord{
+ ID: taskID,
+ Site: string(normSite),
+ User: normUser,
+ UserName: cleanName,
+ AvatarKey: avatarKey,
+ List: normList,
+ Origin: queueOrigin(req.Origin),
+ Cursor: "",
+ HasMore: true,
+ RestThreshold: m.pickRestThresholdLocked(),
+ Status: CacheQueueQueued,
+ CreatedAt: createdAt,
+ UpdatedAt: now,
+ }
+ rt := cacheQueueRuntime{
+ pager: pager,
+ seenKeys: make(map[string]bool),
+ }
+ if len(loaded) > 0 {
+ rt.pageItems = loaded
+ rt.pageIdx = 0
+ rt.pageNextCursor = sanitizeCursor(req.Cursor)
+ rt.pageNextHasMore = req.HasMore && (normSite == site.Bilibili && normList == "videos" || rt.pageNextCursor != "")
+ rt.pageLoaded = true
+ } else if cleanCur := sanitizeCursor(req.Cursor); cleanCur != "" {
+ rec.Cursor = cleanCur
+ rec.HasMore = req.HasMore
+ }
+
+ entry := &cacheQueueEntry{rec: rec, rt: rt}
+ 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(normSite)
+ return dto, nil
+}
+
+// PauseCacheQueue pauses an unfinished background cache queue task and any derived download task in flight.
+func (b *Backend) PauseCacheQueue(id string) (CacheQueueTask, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return CacheQueueTask{}, err
+ }
+ if b.queue == nil {
+ return CacheQueueTask{}, &site.Error{Kind: site.ErrKindUnavailable, Message: "未找到该缓存队列任务"}
+ }
+ target := strings.TrimSpace(id)
+ m := b.queue
+ m.mu.Lock()
+ var found *cacheQueueEntry
+ for _, e := range m.tasks {
+ if e.rec.ID == target {
+ found = e
+ break
+ }
+ }
+ if found == nil {
+ m.mu.Unlock()
+ return CacheQueueTask{}, &site.Error{Kind: site.ErrKindUnavailable, Message: "未找到该缓存队列任务"}
+ }
+ if !isUnfinishedQueueStatus(found.rec.Status) {
+ m.mu.Unlock()
+ return CacheQueueTask{}, &site.Error{Kind: site.ErrKindBadRequest, Message: "该缓存队列任务已结束"}
+ }
+ prevRec := found.rec
+ prevResume := found.rt.resumePendingDownloads
+ activeIDs := append([]string(nil), found.rec.ActiveDownloadIDs...)
+ found.rec.Status = CacheQueuePaused
+ found.rec.PauseReason = "user"
+ found.rec.StopReason = "已手动暂停"
+ found.rec.NextRunAt = ""
+ found.rec.UpdatedAt = m.nowRFC3339()
+ found.rt.resumePendingDownloads = len(activeIDs) > 0
+ if err := m.saveLocked(); err != nil {
+ found.rec = prevRec
+ found.rt.resumePendingDownloads = prevResume
+ m.mu.Unlock()
+ return CacheQueueTask{}, err
+ }
+ if found.rt.stepCancel != nil {
+ found.rt.stepCancel()
+ found.rt.stepCancel = nil
+ }
+ notifyRec := found.rec
+ dto := m.toDTOLocked(found)
+ siteID := site.ID(found.rec.Site)
+ m.mu.Unlock()
+
+ m.notifyState(notifyRec)
+ if b.dl != nil {
+ for _, dlID := range activeIDs {
+ if t, ok, err := b.dl.GetTask(dlID); err == nil && ok && (t.Status == "queued" || t.Status == "running") {
+ _, _ = b.dl.Pause(dlID)
+ }
+ }
+ }
+ m.wakeSite(siteID)
+ return dto, nil
+}
+
+// ResumeCacheQueue resumes a paused background cache queue task on its site.
+func (b *Backend) ResumeCacheQueue(id string) (CacheQueueTask, error) {
+ if err := b.requireDesktop(); err != nil {
+ return CacheQueueTask{}, err
+ }
+ if err := b.requireAnyLogin(); err != nil {
+ return CacheQueueTask{}, err
+ }
+ if b.queue == nil {
+ return CacheQueueTask{}, &site.Error{Kind: site.ErrKindUnavailable, Message: "未找到该缓存队列任务"}
+ }
+ target := strings.TrimSpace(id)
+ m := b.queue
+ m.mu.Lock()
+ var siteID site.ID
+ var found bool
+ for _, e := range m.tasks {
+ if e.rec.ID == target {
+ siteID = site.ID(e.rec.Site)
+ found = true
+ break
+ }
+ }
+ m.mu.Unlock()
+ if !found {
+ return CacheQueueTask{}, &site.Error{Kind: site.ErrKindUnavailable, Message: "未找到该缓存队列任务"}
+ }
+
+ if err := b.requireSiteLogin(siteID); err != nil {
+ return CacheQueueTask{}, err
+ }
+
+ m.mu.Lock()
+ var entry *cacheQueueEntry
+ for _, e := range m.tasks {
+ if e.rec.ID == target {
+ entry = e
+ break
+ }
+ }
+ if entry == nil {
+ m.mu.Unlock()
+ return CacheQueueTask{}, &site.Error{Kind: site.ErrKindUnavailable, Message: "未找到该缓存队列任务"}
+ }
+ if !isUnfinishedQueueStatus(entry.rec.Status) {
+ m.mu.Unlock()
+ return CacheQueueTask{}, &site.Error{Kind: site.ErrKindBadRequest, Message: "该缓存队列任务已结束,请重新加入队列"}
+ }
+ if entry.rec.Status != CacheQueuePaused {
+ dto := m.toDTOLocked(entry)
+ m.mu.Unlock()
+ return dto, nil
+ }
+ prevRec := entry.rec
+ prevResume := entry.rt.resumePendingDownloads
+ entry.rec.Status = CacheQueueQueued
+ entry.rec.PauseReason = ""
+ entry.rec.StopReason = ""
+ entry.rec.NextRunAt = ""
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ entry.rt.resumePendingDownloads = len(entry.rec.ActiveDownloadIDs) > 0
+ if err := m.saveLocked(); err != nil {
+ entry.rec = prevRec
+ entry.rt.resumePendingDownloads = prevResume
+ m.mu.Unlock()
+ return CacheQueueTask{}, err
+ }
+ notifyRec := entry.rec
+ dto := m.toDTOLocked(entry)
+ m.mu.Unlock()
+
+ m.notifyState(notifyRec)
+ m.wakeSite(siteID)
+ return dto, nil
+}
+
+// CancelCacheQueue stops scheduling a background cache queue task and cancels its single unfinished
+// derived download task (if any) without ever deleting items already cached in the local media library.
+func (b *Backend) CancelCacheQueue(id string) (CacheQueueTask, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return CacheQueueTask{}, err
+ }
+ if b.queue == nil {
+ return CacheQueueTask{}, &site.Error{Kind: site.ErrKindUnavailable, Message: "未找到该缓存队列任务"}
+ }
+ target := strings.TrimSpace(id)
+ m := b.queue
+ m.mu.Lock()
+ var found *cacheQueueEntry
+ for _, e := range m.tasks {
+ if e.rec.ID == target {
+ found = e
+ break
+ }
+ }
+ if found == nil {
+ m.mu.Unlock()
+ return CacheQueueTask{}, &site.Error{Kind: site.ErrKindUnavailable, Message: "未找到该缓存队列任务"}
+ }
+ if !isUnfinishedQueueStatus(found.rec.Status) {
+ dto := m.toDTOLocked(found)
+ m.mu.Unlock()
+ return dto, nil
+ }
+ prevRec := found.rec
+ prevParts := found.rt.nextPartEnqueuers
+ prevResume := found.rt.resumePendingDownloads
+ activeIDs := append([]string(nil), found.rec.ActiveDownloadIDs...)
+ siteID := site.ID(found.rec.Site)
+ found.rt.nextPartEnqueuers = nil
+ found.rt.resumePendingDownloads = false
+ found.rec.ActiveDownloadIDs = nil
+ found.rec.ActivePendingPages = nil
+ found.rec.ActiveItemKey = ""
+ found.rec.ActiveTitle = ""
+ found.rec.Status = CacheQueueStopped
+ found.rec.PauseReason = ""
+ found.rec.StopReason = "已取消"
+ found.rec.NextRunAt = ""
+ found.rec.UpdatedAt = m.nowRFC3339()
+ if err := m.saveLocked(); err != nil {
+ found.rec = prevRec
+ found.rt.nextPartEnqueuers = prevParts
+ found.rt.resumePendingDownloads = prevResume
+ m.mu.Unlock()
+ return CacheQueueTask{}, err
+ }
+ if found.rt.stepCancel != nil {
+ found.rt.stepCancel()
+ found.rt.stepCancel = nil
+ }
+ notifyRec := found.rec
+ dto := m.toDTOLocked(found)
+ m.mu.Unlock()
+
+ m.notifyState(notifyRec)
+ if b.dl != nil {
+ for _, dlID := range activeIDs {
+ if t, ok, err := b.dl.GetTask(dlID); err == nil && ok && t.Status != "completed" && t.Status != "partial" && t.Status != "canceled" {
+ _, _ = b.dl.Cancel(dlID)
+ }
+ }
+ }
+ b.pruneAccountAvatars()
+ m.wakeSite(siteID)
+ return dto, nil
+}
+
+// RemoveCacheQueue deletes a finished (completed, canceled or stopped) cache
+// queue task from the task list. Unfinished tasks must be canceled first.
+// Items it cached stay in the media library.
+func (b *Backend) RemoveCacheQueue(id string) error {
+ _, err := b.removeCacheQueues(func(rec cacheQueueRecord) bool { return rec.ID == strings.TrimSpace(id) }, true)
+ return err
+}
+
+// RemoveFinishedCacheQueues deletes every finished cache queue task and
+// returns how many were removed.
+func (b *Backend) RemoveFinishedCacheQueues() (int, error) {
+ return b.removeCacheQueues(func(rec cacheQueueRecord) bool { return !isUnfinishedQueueStatus(rec.Status) }, false)
+}
+
+func (b *Backend) removeCacheQueues(match func(cacheQueueRecord) bool, single bool) (int, error) {
+ if b.queue == nil {
+ if single {
+ return 0, &site.Error{Kind: site.ErrKindUnavailable, Message: "未找到该缓存队列任务"}
+ }
+ return 0, nil
+ }
+ m := b.queue
+ m.mu.Lock()
+ kept := make([]*cacheQueueEntry, 0, len(m.tasks))
+ var removed []cacheQueueRecord
+ for _, e := range m.tasks {
+ if !match(e.rec) {
+ kept = append(kept, e)
+ continue
+ }
+ if isUnfinishedQueueStatus(e.rec.Status) {
+ if single {
+ m.mu.Unlock()
+ return 0, &site.Error{Kind: site.ErrKindBadRequest, Message: "缓存队列还在进行,请先取消再移除"}
+ }
+ kept = append(kept, e)
+ continue
+ }
+ rec := e.rec
+ rec.Status = "removed"
+ removed = append(removed, rec)
+ }
+ if len(removed) == 0 {
+ m.mu.Unlock()
+ if single {
+ return 0, &site.Error{Kind: site.ErrKindUnavailable, Message: "未找到该缓存队列任务"}
+ }
+ return 0, nil
+ }
+ prev := m.tasks
+ m.tasks = kept
+ if err := m.saveLocked(); err != nil {
+ m.tasks = prev
+ m.mu.Unlock()
+ return 0, err
+ }
+ m.mu.Unlock()
+
+ m.notifyStates(removed)
+ b.pruneAccountAvatars()
+ return len(removed), nil
+}
+
+func (b *Backend) snapshotAuthPausedQueueIDs(siteID site.ID) []string {
+ if b.queue == nil {
+ return nil
+ }
+ return b.queue.snapshotAuthPausedIDs(siteID)
+}
+
+func (b *Backend) resumeAuthPausedQueueIDs(siteID site.ID, ids []string) {
+ if b.queue != nil {
+ b.queue.resumeAuthPausedIDs(siteID, ids)
+ }
+}
diff --git a/internal/service/cache_queue_completion_test.go b/internal/service/cache_queue_completion_test.go
new file mode 100644
index 0000000..0b54bcb
--- /dev/null
+++ b/internal/service/cache_queue_completion_test.go
@@ -0,0 +1,86 @@
+package service
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/site"
+)
+
+// A cache queue (全部缓存) caches items of the list that are cached but
+// incomplete: partial, complete with missing records, or with expected pages
+// lacking a file. It skips complete items, items that only have a better
+// quality available and paused ones (dev 2026-11-20: partial notes were
+// never retried by 全部缓存).
+func TestCacheQueueCompletesIncompleteItems(t *testing.T) {
+ clock := newFakeQueueClock(time.Date(2026, 5, 1, 10, 0, 0, 0, time.UTC))
+ b := newBatchTestBackend(t, clock)
+
+ save := func(id string, meta library.ItemMetadata) {
+ t.Helper()
+ dir := filepath.Join(b.lib.CacheDir(), "bilibili", "1", "dynamics", id)
+ _ = os.MkdirAll(dir, 0o700)
+ meta.Version, meta.ID, meta.RawID, meta.Site, meta.Kind = 1, id, id, "bilibili", "dynamic"
+ meta.Author = library.ItemAuthor{Site: "bilibili", UID: "1", Mid: 1}
+ if _, err := b.lib.SaveItem(dir, meta); err != nil {
+ t.Fatal(err)
+ }
+ }
+ save("BVcomplete", library.ItemMetadata{Status: "complete"})
+ save("BVpartial", library.ItemMetadata{Status: "partial", Missing: []library.MissingRecord{{Item: "P02", Reason: "网络中断"}}})
+ save("BVmissing", library.ItemMetadata{Status: "complete", Missing: []library.MissingRecord{{Item: "danmaku", Reason: "弹幕下载失败"}}})
+ save("BVpages", library.ItemMetadata{Status: "complete", ExpectedPages: []int{1, 2}, Parts: []library.VideoPartRecord{{Page: 1, File: "P01.mp4"}}})
+ save("BVupgrade", library.ItemMetadata{Status: "complete", UpgradeAvailable: true})
+ save("BVpaused", library.ItemMetadata{Status: "paused"})
+
+ var mu sync.Mutex
+ var queued []string
+ cand := func(id string) queueCandidate {
+ key := library.CanonicalItemKey("bilibili", "dynamic", id)
+ return queueCandidate{key: key, title: id, enqueue: func(context.Context) (queueEnqueued, error) {
+ mu.Lock()
+ queued = append(queued, id)
+ mu.Unlock()
+ return queueEnqueued{itemKey: key, title: id}, nil
+ }}
+ }
+ ids := []string{"BVcomplete", "BVpartial", "BVmissing", "BVpages", "BVupgrade", "BVpaused", "BVnew"}
+ var loaded []queueCandidate
+ for _, id := range ids {
+ loaded = append(loaded, cand(id))
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ b.queue.Start(ctx)
+ if _, err := b.enqueueCacheQueueWithPager(site.Bilibili, "dynamics", "1", CacheQueueRequest{Site: "bilibili", List: "dynamics", User: "1", UserName: "测试UP"}, loaded,
+ func(context.Context, string) ([]queueCandidate, string, bool, error) { return nil, "", false, nil }); err != nil {
+ t.Fatal(err)
+ }
+ // One gap after each cached item but the last.
+ for step := 0; step < 3; step++ {
+ dur, _ := clock.WaitForPendingTimer(t, 2*time.Second)
+ clock.Advance(dur)
+ }
+ var final CacheQueueTask
+ for deadline := time.Now().Add(2 * time.Second); time.Now().Before(deadline); time.Sleep(5 * time.Millisecond) {
+ if list := b.ListCacheQueue(); len(list) == 1 && list[0].Status == CacheQueueCompleted {
+ final = list[0]
+ break
+ }
+ }
+ mu.Lock()
+ got := fmt.Sprint(queued)
+ mu.Unlock()
+ if want := fmt.Sprint([]string{"BVpartial", "BVmissing", "BVpages", "BVnew"}); got != want {
+ t.Fatalf("queued = %s, want %s", got, want)
+ }
+ if final.CachedCount != 4 || final.SkippedCount != 3 {
+ t.Fatalf("summary = cached %d skipped %d (status %q)", final.CachedCount, final.SkippedCount, final.Status)
+ }
+}
diff --git a/internal/service/cache_queue_store.go b/internal/service/cache_queue_store.go
new file mode 100644
index 0000000..206a1a7
--- /dev/null
+++ b/internal/service/cache_queue_store.go
@@ -0,0 +1,663 @@
+package service
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "math/rand/v2"
+ "os"
+ "path/filepath"
+ "regexp"
+ "slices"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/chialecode/trace/internal/site"
+ "github.com/chialecode/trace/internal/site/bilibili"
+ "github.com/chialecode/trace/internal/storage"
+)
+
+const (
+ CacheQueueQueued = "queued"
+ CacheQueueRunning = "running"
+ CacheQueueWaiting = "waiting"
+ CacheQueueWaitingBackoff = "waiting_backoff"
+ CacheQueuePaused = "paused"
+ CacheQueueCompleted = "completed"
+ CacheQueueStopped = "stopped"
+
+ cacheQueueFileName = "cache-queue.json"
+ cacheQueueSchemaVersion = 1
+ maxCacheQueueRecentItems = 30
+)
+
+// CacheQueuePacing centralizes all conservative anti-risk-control delays and thresholds (Q-017).
+type CacheQueuePacing struct {
+ ItemMinDelay time.Duration
+ ItemMaxDelay time.Duration
+ LongRestMinItems int
+ LongRestMaxItems int
+ LongRestMinDelay time.Duration
+ LongRestMaxDelay time.Duration
+ BackoffCoolMinDelay time.Duration
+ BackoffCoolMaxDelay time.Duration
+ StartupMinDelay time.Duration
+ StartupMaxDelay time.Duration
+}
+
+// DefaultCacheQueuePacing defines the default Q-017 pacing intervals for background list caching.
+var DefaultCacheQueuePacing = CacheQueuePacing{
+ ItemMinDelay: 40 * time.Second,
+ ItemMaxDelay: 150 * time.Second,
+ LongRestMinItems: 15,
+ LongRestMaxItems: 25,
+ LongRestMinDelay: 10 * time.Minute,
+ LongRestMaxDelay: 25 * time.Minute,
+ BackoffCoolMinDelay: 10 * time.Minute,
+ BackoffCoolMaxDelay: 30 * time.Minute,
+ StartupMinDelay: 1 * time.Minute,
+ StartupMaxDelay: 5 * time.Minute,
+}
+
+// CacheQueueClock abstracts wall clock and timers so tests run deterministically with zero real sleeps.
+type CacheQueueClock interface {
+ Now() time.Time
+ NewTimer(d time.Duration) CacheQueueTimer
+}
+
+// CacheQueueTimer is a single-shot timer created by CacheQueueClock.
+type CacheQueueTimer interface {
+ C() <-chan time.Time
+ Stop() bool
+}
+
+// CacheQueueRand returns a pseudo-random integer in [0, n) for n > 0.
+type CacheQueueRand func(n int) int
+
+type realCacheQueueClock struct{}
+
+type realCacheQueueTimer struct {
+ t *time.Timer
+}
+
+func (realCacheQueueClock) Now() time.Time {
+ return time.Now()
+}
+
+func (realCacheQueueClock) NewTimer(d time.Duration) CacheQueueTimer {
+ return &realCacheQueueTimer{t: time.NewTimer(d)}
+}
+
+func (rt *realCacheQueueTimer) C() <-chan time.Time {
+ return rt.t.C
+}
+
+func (rt *realCacheQueueTimer) Stop() bool {
+ return rt.t.Stop()
+}
+
+// CacheQueueRequest asks to enqueue an entire creator list ("dynamics", "videos", or "works")
+// for conservative newest-to-oldest background caching.
+type CacheQueueRequest struct {
+ Site string `json:"site"`
+ List string `json:"list"`
+ User string `json:"user"`
+ UserName string `json:"userName"`
+ AvatarURL string `json:"avatarUrl"`
+ Dynamics []bilibili.DynamicItem `json:"-"`
+ Videos []bilibili.UserVideoItem `json:"-"`
+ Works []DouyinWorkCardDTO `json:"-"`
+ Cursor string `json:"cursor"`
+ HasMore bool `json:"hasMore"`
+ // Origin is QueueOriginFullCache when a full-cache rule started the run
+ // (DEC-061); empty for "全部缓存" on a user page.
+ Origin string `json:"origin,omitempty"`
+}
+
+// QueueOriginFullCache marks a queue run started by a full-cache rule (DEC-061).
+const QueueOriginFullCache = "full_cache"
+
+// CacheQueueRecentItem summarizes one item cached by a queue run so the detail panel can open it locally.
+type CacheQueueRecentItem struct {
+ ItemKey string `json:"itemKey"`
+ Title string `json:"title"`
+ CachedAt string `json:"cachedAt"`
+}
+
+// CacheQueueTask is the UI-facing DTO for one creator list background cache queue task.
+type CacheQueueTask struct {
+ ID string `json:"id"`
+ Site string `json:"site"`
+ User string `json:"user"`
+ UserName string `json:"userName"`
+ AvatarPath string `json:"avatarPath,omitempty"`
+ List string `json:"list"`
+ ListLabel string `json:"listLabel"`
+ Origin string `json:"origin,omitempty"`
+ Status string `json:"status"`
+ StatusText string `json:"statusText"`
+ PauseReason string `json:"pauseReason,omitempty"`
+ StopReason string `json:"stopReason,omitempty"`
+ Cursor string `json:"cursor,omitempty"`
+ HasMore bool `json:"hasMore"`
+ CachedCount int `json:"cachedCount"`
+ SkippedCount int `json:"skippedCount"`
+ ActiveDownloadID string `json:"activeDownloadId,omitempty"`
+ ActiveItemKey string `json:"activeItemKey,omitempty"`
+ ActiveTitle string `json:"activeTitle,omitempty"`
+ RecentItems []CacheQueueRecentItem `json:"recentItems,omitempty"`
+ NextRunAt string `json:"nextRunAt,omitempty"`
+ CreatedAt string `json:"createdAt"`
+ UpdatedAt string `json:"updatedAt"`
+}
+
+type cacheQueueFile struct {
+ Version int `json:"version"`
+ Tasks []cacheQueueRecord `json:"tasks"`
+}
+
+type cacheQueueRecord struct {
+ ID string `json:"id"`
+ Site string `json:"site"`
+ User string `json:"user"`
+ UserName string `json:"userName,omitempty"`
+ AvatarKey string `json:"avatarKey,omitempty"`
+ List string `json:"list"`
+ Origin string `json:"origin,omitempty"`
+ Cursor string `json:"cursor,omitempty"`
+ HasMore bool `json:"hasMore"`
+ ProcessedKeys []string `json:"processedKeys,omitempty"`
+ CachedCount int `json:"cachedCount"`
+ SkippedCount int `json:"skippedCount"`
+ SinceRestCount int `json:"sinceRestCount,omitempty"`
+ RestThreshold int `json:"restThreshold,omitempty"`
+ ActiveDownloadIDs []string `json:"activeDownloadIds,omitempty"`
+ ActivePendingPages []int `json:"activePendingPages,omitempty"`
+ ActiveItemKey string `json:"activeItemKey,omitempty"`
+ ActiveTitle string `json:"activeTitle,omitempty"`
+ RecentItems []CacheQueueRecentItem `json:"recentItems,omitempty"`
+ Status string `json:"status"`
+ PauseReason string `json:"pauseReason,omitempty"`
+ StopReason string `json:"stopReason,omitempty"`
+ NextRunAt string `json:"nextRunAt,omitempty"`
+ CreatedAt string `json:"createdAt"`
+ UpdatedAt string `json:"updatedAt"`
+}
+
+type cacheQueueRuntime struct {
+ pager queuePager
+ pageItems []queueCandidate
+ pageIdx int
+ pageNextCursor string
+ pageNextHasMore bool
+ pageLoaded bool
+ seenKeys map[string]bool
+ nextPartEnqueuers []queuePartEnqueuer
+ resumePendingDownloads bool
+ stepCancel context.CancelFunc
+}
+
+type cacheQueueEntry struct {
+ rec cacheQueueRecord
+ rt cacheQueueRuntime
+}
+
+type cacheQueueManager struct {
+ b *Backend
+ path string
+ clock CacheQueueClock
+ rng CacheQueueRand
+ pacing CacheQueuePacing
+
+ mu sync.Mutex
+ tasks []*cacheQueueEntry
+ fileExists bool
+ started bool
+ stopCancel context.CancelFunc
+ siteWake map[site.ID]chan struct{}
+ wg sync.WaitGroup
+}
+
+var (
+ queueFullURLPattern = regexp.MustCompile(`(?i)https?://[^\s"'<>]+`)
+ queueQueryTailPattern = regexp.MustCompile(`\?[A-Za-z0-9_.-]+=[^\s"'<>]*`)
+ queueSecretKVPattern = regexp.MustCompile(`(?i)\b(?:` + secretKeyNamesPattern + `)["'\\]*\s*[=:][^\s;"'<>]*|\btrace-remote:\S+|\bbearer\s+\S+`)
+)
+
+// guardCacheQueueSchema checks /cache-queue.json before databases open:
+// files written by a newer schema version are refused; corrupt files are backed up.
+func guardCacheQueueSchema(dataDir string) (string, error) {
+ if strings.TrimSpace(dataDir) == "" {
+ return "", nil
+ }
+ path := filepath.Join(dataDir, cacheQueueFileName)
+ raw, err := os.ReadFile(path)
+ if os.IsNotExist(err) {
+ return "", nil
+ }
+ if err != nil {
+ return "", err
+ }
+ var probe struct {
+ Version int `json:"version"`
+ }
+ if jErr := json.Unmarshal(raw, &probe); jErr != nil {
+ backup, bErr := storage.BackupCorruptFile(path)
+ if bErr != nil {
+ return "", bErr
+ }
+ _ = os.Remove(path)
+ return backup, nil
+ }
+ if probe.Version > cacheQueueSchemaVersion {
+ return "", &storage.NewerDataError{
+ File: cacheQueueFileName,
+ Found: probe.Version,
+ Supported: cacheQueueSchemaVersion,
+ }
+ }
+ return "", nil
+}
+
+func newCacheQueueManager(b *Backend, path string, clock CacheQueueClock, rng CacheQueueRand, pacing *CacheQueuePacing) (*cacheQueueManager, string, error) {
+ if clock == nil {
+ clock = realCacheQueueClock{}
+ }
+ if rng == nil {
+ rng = rand.IntN
+ }
+ cfg := DefaultCacheQueuePacing
+ if pacing != nil {
+ cfg = *pacing
+ }
+ m := &cacheQueueManager{
+ b: b,
+ path: path,
+ clock: clock,
+ rng: rng,
+ pacing: cfg,
+ siteWake: map[site.ID]chan struct{}{
+ site.Bilibili: make(chan struct{}, 1),
+ site.Douyin: make(chan struct{}, 1),
+ },
+ }
+ backup, err := m.loadFromDiskLocked()
+ if err != nil {
+ return nil, backup, err
+ }
+ return m, backup, nil
+}
+
+func (m *cacheQueueManager) loadFromDiskLocked() (string, error) {
+ if strings.TrimSpace(m.path) == "" {
+ return "", nil
+ }
+ raw, err := os.ReadFile(m.path)
+ if os.IsNotExist(err) {
+ return "", nil
+ }
+ if err != nil {
+ return "", err
+ }
+ var doc cacheQueueFile
+ if jErr := json.Unmarshal(raw, &doc); jErr != nil {
+ backup, bErr := storage.BackupCorruptFile(m.path)
+ if bErr != nil {
+ return "", bErr
+ }
+ _ = os.Remove(m.path)
+ return backup, nil
+ }
+ if doc.Version > cacheQueueSchemaVersion {
+ return "", &storage.NewerDataError{
+ File: cacheQueueFileName,
+ Found: doc.Version,
+ Supported: cacheQueueSchemaVersion,
+ }
+ }
+ m.fileExists = true
+ m.tasks = make([]*cacheQueueEntry, 0, len(doc.Tasks))
+ for _, r := range doc.Tasks {
+ clean := sanitizeQueueRecord(r)
+ if clean.ID == "" || clean.Site == "" || clean.User == "" || clean.List == "" {
+ continue
+ }
+ seen := make(map[string]bool, len(clean.ProcessedKeys))
+ for _, k := range clean.ProcessedKeys {
+ if k != "" {
+ seen[k] = true
+ }
+ }
+ m.tasks = append(m.tasks, &cacheQueueEntry{
+ rec: clean,
+ rt: cacheQueueRuntime{
+ seenKeys: seen,
+ resumePendingDownloads: len(clean.ActiveDownloadIDs) > 0,
+ },
+ })
+ }
+ return "", nil
+}
+
+func (m *cacheQueueManager) sanitizeText(s string) string {
+ if m != nil && m.b != nil {
+ s = m.b.redactStoredSecrets(s)
+ }
+ return sanitizeQueueText(s)
+}
+
+func sanitizeQueueText(s string) string {
+ s = strings.TrimSpace(s)
+ if s == "" {
+ return ""
+ }
+ s = queueFullURLPattern.ReplaceAllString(s, "")
+ s = queueQueryTailPattern.ReplaceAllString(s, "")
+ s = queueSecretKVPattern.ReplaceAllString(s, "")
+ return strings.Join(strings.Fields(s), " ")
+}
+
+func sanitizeCursor(c string) string {
+ c = strings.TrimSpace(c)
+ if strings.ContainsAny(c, "?=&;:/\\ \t\r\n") {
+ return ""
+ }
+ return c
+}
+
+func sanitizeItemKey(k string) string {
+ k = strings.TrimSpace(k)
+ if strings.ContainsAny(k, "?=&;/\\ \t\r\n") || strings.Contains(k, "://") {
+ return ""
+ }
+ return k
+}
+
+func sanitizeQueueRecord(r cacheQueueRecord) cacheQueueRecord {
+ siteID, list, normUser, err := normalizeCacheQueueTarget(r.Site, r.List, r.User)
+ if err != nil {
+ return cacheQueueRecord{}
+ }
+ r.Site = string(siteID)
+ r.List = list
+ r.User = normUser
+ r.ID = sanitizeCursor(r.ID)
+ r.UserName = sanitizeQueueText(r.UserName)
+ if r.Origin != QueueOriginFullCache {
+ r.Origin = ""
+ }
+ if !avatarFileRe.MatchString(r.AvatarKey) {
+ r.AvatarKey = ""
+ }
+ r.Cursor = sanitizeCursor(r.Cursor)
+ r.ActiveItemKey = sanitizeItemKey(r.ActiveItemKey)
+ r.ActiveTitle = sanitizeQueueText(r.ActiveTitle)
+ r.StopReason = sanitizeQueueText(r.StopReason)
+ r.PauseReason = sanitizeCursor(r.PauseReason)
+ r.NextRunAt = sanitizeCursorFallbackRFC3339(r.NextRunAt)
+ r.CreatedAt = sanitizeCursorFallbackRFC3339(r.CreatedAt)
+ r.UpdatedAt = sanitizeCursorFallbackRFC3339(r.UpdatedAt)
+
+ var cleanProcessed []string
+ for _, k := range r.ProcessedKeys {
+ if ck := sanitizeItemKey(k); ck != "" && !slices.Contains(cleanProcessed, ck) {
+ cleanProcessed = append(cleanProcessed, ck)
+ }
+ }
+ r.ProcessedKeys = cleanProcessed
+
+ var cleanDL []string
+ for _, id := range r.ActiveDownloadIDs {
+ if cid := sanitizeCursor(id); cid != "" && !slices.Contains(cleanDL, cid) {
+ cleanDL = append(cleanDL, cid)
+ }
+ }
+ r.ActiveDownloadIDs = cleanDL
+
+ var cleanPages []int
+ for _, p := range r.ActivePendingPages {
+ if p > 0 && !slices.Contains(cleanPages, p) {
+ cleanPages = append(cleanPages, p)
+ }
+ }
+ r.ActivePendingPages = cleanPages
+
+ var cleanRecent []CacheQueueRecentItem
+ for _, item := range r.RecentItems {
+ ck := sanitizeItemKey(item.ItemKey)
+ if ck == "" {
+ continue
+ }
+ cleanRecent = append(cleanRecent, CacheQueueRecentItem{
+ ItemKey: ck,
+ Title: sanitizeQueueText(item.Title),
+ CachedAt: sanitizeCursorFallbackRFC3339(item.CachedAt),
+ })
+ if len(cleanRecent) >= maxCacheQueueRecentItems {
+ break
+ }
+ }
+ r.RecentItems = cleanRecent
+
+ switch r.Status {
+ case CacheQueueQueued, CacheQueueRunning, CacheQueueWaiting, CacheQueueWaitingBackoff,
+ CacheQueuePaused, CacheQueueCompleted, CacheQueueStopped:
+ default:
+ r.Status = CacheQueueStopped
+ if r.StopReason == "" {
+ r.StopReason = "未知状态,已停止"
+ }
+ }
+ return r
+}
+
+func sanitizeCursorFallbackRFC3339(v string) string {
+ v = strings.TrimSpace(v)
+ if v == "" {
+ return ""
+ }
+ if t, err := time.Parse(time.RFC3339, v); err == nil {
+ return t.UTC().Format(time.RFC3339)
+ }
+ return ""
+}
+
+func isUnfinishedQueueStatus(status string) bool {
+ return status != CacheQueueCompleted && status != CacheQueueStopped
+}
+
+func (m *cacheQueueManager) saveLocked() error {
+ if strings.TrimSpace(m.path) == "" {
+ return nil
+ }
+ if len(m.tasks) == 0 && !m.fileExists {
+ return nil
+ }
+ doc := cacheQueueFile{
+ Version: cacheQueueSchemaVersion,
+ Tasks: make([]cacheQueueRecord, 0, len(m.tasks)),
+ }
+ for _, e := range m.tasks {
+ rec := sanitizeQueueRecord(e.rec)
+ rec.UserName = m.sanitizeText(rec.UserName)
+ rec.ActiveTitle = m.sanitizeText(rec.ActiveTitle)
+ rec.StopReason = m.sanitizeText(rec.StopReason)
+ for i := range rec.RecentItems {
+ rec.RecentItems[i].Title = m.sanitizeText(rec.RecentItems[i].Title)
+ }
+ doc.Tasks = append(doc.Tasks, rec)
+ }
+ if err := storage.WriteJSONAtomic(m.path, doc, 0o600); err != nil {
+ return err
+ }
+ m.fileExists = true
+ return nil
+}
+
+func (m *cacheQueueManager) saveLoggedLocked(op string) {
+ if err := m.saveLocked(); err != nil && m.b != nil {
+ m.b.logError("cache_queue."+op, err)
+ }
+}
+
+func (m *cacheQueueManager) avatarKeys() []string {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ var out []string
+ for _, e := range m.tasks {
+ if e.rec.AvatarKey != "" && avatarFileRe.MatchString(e.rec.AvatarKey) {
+ out = append(out, e.rec.AvatarKey)
+ }
+ }
+ return out
+}
+
+func (m *cacheQueueManager) randIntInclusiveLocked(minVal, maxVal int) int {
+ if maxVal <= minVal {
+ return minVal
+ }
+ n := maxVal - minVal + 1
+ v := m.rng(n)
+ if v < 0 {
+ v = 0
+ } else if v >= n {
+ v = n - 1
+ }
+ return minVal + v
+}
+
+func (m *cacheQueueManager) randDurationLocked(minD, maxD time.Duration) time.Duration {
+ if maxD <= minD {
+ return minD
+ }
+ diff := maxD - minD
+ if diff >= time.Second && minD%time.Second == 0 && maxD%time.Second == 0 {
+ spanSec := int(diff / time.Second)
+ return minD + time.Duration(m.randIntInclusiveLocked(0, spanSec))*time.Second
+ }
+ spanMs := int(diff / time.Millisecond)
+ if spanMs <= 0 {
+ return minD
+ }
+ return minD + time.Duration(m.randIntInclusiveLocked(0, spanMs))*time.Millisecond
+}
+
+func (m *cacheQueueManager) pickRestThresholdLocked() int {
+ return m.randIntInclusiveLocked(m.pacing.LongRestMinItems, m.pacing.LongRestMaxItems)
+}
+
+func (m *cacheQueueManager) nowRFC3339() string {
+ return m.clock.Now().UTC().Format(time.RFC3339)
+}
+
+func makeCacheQueueID(siteID, list, user string) string {
+ sum := sha256.Sum256([]byte(siteID + ":" + list + ":" + user))
+ return "cq_" + hex.EncodeToString(sum[:8])
+}
+
+func bilibiliVideoIDFromItemKey(itemKey string) (string, bool) {
+ const prefix = "bilibili:video:"
+ if !strings.HasPrefix(itemKey, prefix) {
+ return "", false
+ }
+ bvid := strings.TrimSpace(strings.TrimPrefix(itemKey, prefix))
+ return bvid, bvid != ""
+}
+
+func (m *cacheQueueManager) statusTextLocked(rec cacheQueueRecord) string {
+ switch rec.Status {
+ case CacheQueueQueued:
+ return "排队中"
+ case CacheQueueRunning:
+ return "进行中"
+ case CacheQueueWaiting:
+ if rec.StopReason != "" {
+ return rec.StopReason
+ }
+ return "等待下一条"
+ case CacheQueueWaitingBackoff:
+ if rec.StopReason != "" {
+ return rec.StopReason
+ }
+ return "等待站点退避结束"
+ case CacheQueuePaused:
+ if rec.PauseReason == "auth_required" {
+ return firstNonEmpty(rec.StopReason, "登录已失效,重新登录后自动继续")
+ }
+ if rec.PauseReason == "app_closed" {
+ return "已暂停(应用关闭)"
+ }
+ return firstNonEmpty(rec.StopReason, "已暂停")
+ case CacheQueueCompleted:
+ return "已完成(已到列表末尾)"
+ case CacheQueueStopped:
+ return firstNonEmpty(rec.StopReason, "已停止")
+ default:
+ return rec.Status
+ }
+}
+
+func (m *cacheQueueManager) toDTOLocked(e *cacheQueueEntry) CacheQueueTask {
+ rec := e.rec
+ var activeDL string
+ if len(rec.ActiveDownloadIDs) > 0 {
+ activeDL = rec.ActiveDownloadIDs[0]
+ }
+ var avatarPath string
+ if m.b != nil {
+ avatarPath = m.b.AccountAvatarPath(rec.Site, rec.User)
+ }
+ recent := make([]CacheQueueRecentItem, len(rec.RecentItems))
+ copy(recent, rec.RecentItems)
+ userName := rec.UserName
+ if userName == "" {
+ userName = rec.User
+ }
+ return CacheQueueTask{
+ ID: rec.ID,
+ Site: rec.Site,
+ User: rec.User,
+ UserName: userName,
+ AvatarPath: avatarPath,
+ List: rec.List,
+ ListLabel: queueListLabel(rec),
+ Origin: rec.Origin,
+ Status: rec.Status,
+ StatusText: m.statusTextLocked(rec),
+ PauseReason: rec.PauseReason,
+ StopReason: rec.StopReason,
+ Cursor: rec.Cursor,
+ HasMore: rec.HasMore,
+ CachedCount: rec.CachedCount,
+ SkippedCount: rec.SkippedCount,
+ ActiveDownloadID: activeDL,
+ ActiveItemKey: rec.ActiveItemKey,
+ ActiveTitle: rec.ActiveTitle,
+ RecentItems: recent,
+ NextRunAt: rec.NextRunAt,
+ CreatedAt: rec.CreatedAt,
+ UpdatedAt: rec.UpdatedAt,
+ }
+}
+
+// notifyState logs and publishes a queue state transition.
+// Caller MUST NOT hold m.mu so synchronous event subscribers can safely query queue APIs.
+func (m *cacheQueueManager) notifyState(rec cacheQueueRecord) {
+ if m.b == nil {
+ return
+ }
+ m.b.logInfo(fmt.Sprintf("cache_queue.%s.%s id=%s state=%s cached=%d skipped=%d",
+ rec.Site, rec.List, rec.ID, rec.Status, rec.CachedCount, rec.SkippedCount))
+ if m.b.events != nil {
+ m.b.events.PublishSite(EventCacheQueueUpdated, rec.Site, rec.ID+":"+rec.Status)
+ }
+}
+
+func (m *cacheQueueManager) notifyStates(recs []cacheQueueRecord) {
+ for _, r := range recs {
+ m.notifyState(r)
+ }
+}
diff --git a/internal/service/cache_queue_worker.go b/internal/service/cache_queue_worker.go
new file mode 100644
index 0000000..608456c
--- /dev/null
+++ b/internal/service/cache_queue_worker.go
@@ -0,0 +1,1051 @@
+package service
+
+import (
+ "context"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/site"
+)
+
+func (m *cacheQueueManager) wakeSite(siteID site.ID) {
+ if ch, ok := m.siteWake[siteID]; ok {
+ select {
+ case ch <- struct{}{}:
+ default:
+ }
+ }
+}
+
+func (m *cacheQueueManager) onDownloadUpdated(siteName string) {
+ if sid, err := normalizeSiteID(siteName); err == nil {
+ m.wakeSite(sid)
+ }
+}
+
+// Start launches the independent per-site queue workers and schedules the 1–5m startup delay
+// for any unfinished tasks recovered from the previous session.
+func (m *cacheQueueManager) Start(ctx context.Context) {
+ m.mu.Lock()
+ if m.started {
+ m.mu.Unlock()
+ return
+ }
+ loopCtx, cancel := context.WithCancel(ctx)
+ m.stopCancel = cancel
+ m.started = true
+
+ now := m.clock.Now().UTC()
+ changed := false
+ for _, sid := range []site.ID{site.Bilibili, site.Douyin} {
+ loggedIn := m.hasSiteLogin(sid)
+ assignedActive := false
+ for _, e := range m.tasks {
+ if e.rec.Site != string(sid) || !isUnfinishedQueueStatus(e.rec.Status) {
+ continue
+ }
+ if e.rec.Status == CacheQueuePaused && e.rec.PauseReason == "user" {
+ continue
+ }
+ if !loggedIn {
+ if e.rec.Status != CacheQueuePaused || e.rec.PauseReason != "auth_required" {
+ e.rec.Status = CacheQueuePaused
+ e.rec.PauseReason = "auth_required"
+ e.rec.StopReason = "未登录或登录已失效,重新登录后自动继续"
+ e.rec.NextRunAt = ""
+ e.rec.UpdatedAt = now.Format(time.RFC3339)
+ e.rt.resumePendingDownloads = len(e.rec.ActiveDownloadIDs) > 0
+ changed = true
+ }
+ continue
+ }
+ if e.rec.Status == CacheQueuePaused && e.rec.PauseReason == "auth_required" {
+ // A task paused for an expired login resumes on the next login event (or by hand),
+ // not merely because some credential is present at startup.
+ continue
+ }
+
+ e.rt.resumePendingDownloads = len(e.rec.ActiveDownloadIDs) > 0
+ if !assignedActive {
+ assignedActive = true
+ startupUntil := now.Add(m.randDurationLocked(m.pacing.StartupMinDelay, m.pacing.StartupMaxDelay))
+ if e.rec.Status == CacheQueueWaitingBackoff {
+ if existing, err := time.Parse(time.RFC3339, e.rec.NextRunAt); err != nil || existing.Before(startupUntil) {
+ e.rec.NextRunAt = startupUntil.Format(time.RFC3339)
+ }
+ } else {
+ if existing, err := time.Parse(time.RFC3339, e.rec.NextRunAt); err == nil && existing.After(startupUntil) {
+ startupUntil = existing
+ }
+ e.rec.Status = CacheQueueWaiting
+ e.rec.PauseReason = ""
+ e.rec.StopReason = "应用启动后等待继续"
+ e.rec.NextRunAt = startupUntil.Format(time.RFC3339)
+ }
+ e.rec.UpdatedAt = now.Format(time.RFC3339)
+ changed = true
+ } else if e.rec.Status != CacheQueueQueued {
+ e.rec.Status = CacheQueueQueued
+ e.rec.PauseReason = ""
+ e.rec.StopReason = ""
+ e.rec.NextRunAt = ""
+ e.rec.UpdatedAt = now.Format(time.RFC3339)
+ changed = true
+ }
+ }
+ }
+ if changed {
+ m.saveLoggedLocked("start")
+ }
+ m.mu.Unlock()
+
+ for _, sid := range []site.ID{site.Bilibili, site.Douyin} {
+ siteCopy := sid
+ m.wg.Add(1)
+ go func() {
+ defer m.wg.Done()
+ m.runSiteLoop(loopCtx, siteCopy)
+ }()
+ }
+}
+
+// Stop halts background queue workers cleanly and flushes state to disk for restart recovery.
+func (m *cacheQueueManager) Stop() {
+ m.mu.Lock()
+ cancel := m.stopCancel
+ m.stopCancel = nil
+ m.started = false
+ for _, e := range m.tasks {
+ if e.rt.stepCancel != nil {
+ e.rt.stepCancel()
+ e.rt.stepCancel = nil
+ }
+ }
+ m.mu.Unlock()
+
+ if cancel != nil {
+ cancel()
+ }
+ m.wg.Wait()
+
+ m.mu.Lock()
+ m.saveLoggedLocked("stop")
+ m.mu.Unlock()
+}
+
+func (m *cacheQueueManager) pauseForExit() {
+ m.Stop()
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ now := m.nowRFC3339()
+ changed := false
+ for _, e := range m.tasks {
+ if !isUnfinishedQueueStatus(e.rec.Status) {
+ continue
+ }
+ if e.rec.Status == CacheQueuePaused {
+ continue
+ }
+ if e.rec.Status == CacheQueueWaitingBackoff {
+ // Keep waiting_backoff intact across exit so backoff cooldown is never shortened.
+ continue
+ }
+ e.rec.Status = CacheQueuePaused
+ e.rec.PauseReason = "app_closed"
+ e.rec.StopReason = "已暂停(应用关闭)"
+ e.rec.UpdatedAt = now
+ changed = true
+ }
+ if changed {
+ m.saveLoggedLocked("pause_for_exit")
+ }
+}
+
+func (m *cacheQueueManager) pauseForSite(siteID site.ID, reasonCode, reasonMsg string) {
+ m.mu.Lock()
+ now := m.nowRFC3339()
+ changed := false
+ var notify []cacheQueueRecord
+ for _, e := range m.tasks {
+ if e.rec.Site != string(siteID) || !isUnfinishedQueueStatus(e.rec.Status) {
+ continue
+ }
+ if e.rec.Status == CacheQueuePaused && e.rec.PauseReason == "user" {
+ continue
+ }
+ if e.rt.stepCancel != nil {
+ e.rt.stepCancel()
+ e.rt.stepCancel = nil
+ }
+ if reasonCode == "app_closed" && e.rec.Status == CacheQueueWaitingBackoff {
+ continue
+ }
+ e.rec.Status = CacheQueuePaused
+ e.rec.PauseReason = sanitizeCursor(reasonCode)
+ e.rec.StopReason = sanitizeQueueText(reasonMsg)
+ if reasonCode != "app_closed" {
+ e.rec.NextRunAt = ""
+ }
+ e.rec.UpdatedAt = now
+ e.rt.resumePendingDownloads = len(e.rec.ActiveDownloadIDs) > 0
+ changed = true
+ notify = append(notify, e.rec)
+ }
+ if changed {
+ m.saveLoggedLocked("pause_for_site")
+ }
+ m.mu.Unlock()
+ m.notifyStates(notify)
+ m.wakeSite(siteID)
+}
+
+func (m *cacheQueueManager) snapshotAuthPausedIDs(siteID site.ID) []string {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ var ids []string
+ for _, e := range m.tasks {
+ if e.rec.Site == string(siteID) && e.rec.Status == CacheQueuePaused && e.rec.PauseReason == "auth_required" {
+ ids = append(ids, e.rec.ID)
+ }
+ }
+ return ids
+}
+
+func (m *cacheQueueManager) resumeAuthPausedForSite(siteID site.ID) {
+ m.resumeAuthPausedFilter(siteID, nil)
+}
+
+func (m *cacheQueueManager) resumeAuthPausedIDs(siteID site.ID, allowed []string) {
+ if len(allowed) == 0 {
+ return
+ }
+ m.resumeAuthPausedFilter(siteID, allowed)
+}
+
+func (m *cacheQueueManager) resumeAuthPausedFilter(siteID site.ID, onlyIDs []string) {
+ m.mu.Lock()
+ now := m.nowRFC3339()
+ changed := false
+ var notify []cacheQueueRecord
+ for _, e := range m.tasks {
+ if e.rec.Site != string(siteID) || e.rec.Status != CacheQueuePaused || e.rec.PauseReason != "auth_required" {
+ continue
+ }
+ if onlyIDs != nil && !slices.Contains(onlyIDs, e.rec.ID) {
+ continue
+ }
+ e.rec.Status = CacheQueueQueued
+ e.rec.PauseReason = ""
+ e.rec.StopReason = ""
+ e.rec.NextRunAt = ""
+ e.rec.UpdatedAt = now
+ e.rt.resumePendingDownloads = len(e.rec.ActiveDownloadIDs) > 0
+ changed = true
+ notify = append(notify, e.rec)
+ }
+ if changed {
+ m.saveLoggedLocked("resume_auth_paused")
+ }
+ m.mu.Unlock()
+ m.notifyStates(notify)
+ if changed {
+ m.wakeSite(siteID)
+ }
+}
+
+func (m *cacheQueueManager) hasSiteLogin(siteID site.ID) bool {
+ if m.b == nil || m.b.credMgr == nil {
+ return false
+ }
+ return m.b.credMgr.HasActiveCredential(string(siteID))
+}
+
+func (m *cacheQueueManager) siteBackoffOrQuotaEnd(siteID site.ID, now time.Time) (bool, time.Time) {
+ if m.b == nil || m.b.subs == nil {
+ return false, time.Time{}
+ }
+ nowUTC := now.UTC()
+ var blocked bool
+ var end time.Time
+
+ if inBackoff, until := m.b.subs.IsSiteInBackoff(string(siteID)); inBackoff && until.After(nowUTC) {
+ blocked = true
+ end = until.UTC()
+ }
+ if !m.b.subs.CanUseSiteQuotaTokens(string(siteID), 1) {
+ blocked = true
+ st := m.b.subs.GetSiteSchedulerState(string(siteID))
+ cutoff := nowUTC.Add(-time.Hour).Unix()
+ var oldest int64
+ for _, ts := range st.TokenTimestamps {
+ if ts > cutoff && (oldest == 0 || ts < oldest) {
+ oldest = ts
+ }
+ }
+ quotaEnd := nowUTC.Add(time.Hour)
+ if oldest > 0 {
+ quotaEnd = time.Unix(oldest+3600, 0).UTC()
+ }
+ if quotaEnd.After(end) {
+ end = quotaEnd
+ }
+ }
+ return blocked, end
+}
+
+func (m *cacheQueueManager) backoffResumeTimeLocked(siteID site.ID, now time.Time) time.Time {
+ nowUTC := now.UTC()
+ _, baseEnd := m.siteBackoffOrQuotaEnd(siteID, nowUTC)
+ if baseEnd.Before(nowUTC) {
+ baseEnd = nowUTC
+ }
+ cool := m.randDurationLocked(m.pacing.BackoffCoolMinDelay, m.pacing.BackoffCoolMaxDelay)
+ return baseEnd.Add(cool)
+}
+
+func backoffReasonText(kind string) string {
+ switch kind {
+ case site.ErrKindRiskControl:
+ return "遇到站点风控,等待退避结束"
+ case site.ErrKindRateLimited:
+ return "遇到站点限流,等待退避结束"
+ case site.ErrKindQuota:
+ return "本小时自动请求额度已用完,等待额度恢复"
+ default:
+ return "站点处于退避期,等待退避结束"
+ }
+}
+
+func isBackoffOrQuotaKind(kind string) bool {
+ switch kind {
+ case site.ErrKindRiskControl, site.ErrKindRateLimited, site.ErrKindQuota, site.ErrKindBackoff:
+ return true
+ }
+ return false
+}
+
+func (m *cacheQueueManager) enterWaitingBackoffLocked(e *cacheQueueEntry, siteID site.ID, kind string) cacheQueueRecord {
+ if (kind == site.ErrKindRiskControl || kind == site.ErrKindRateLimited) && m.b != nil && m.b.subs != nil {
+ if inBackoff, _ := m.b.subs.IsSiteInBackoff(string(siteID)); !inBackoff {
+ m.b.subs.RecordSiteAutomaticStop(string(siteID), kind)
+ }
+ }
+ now := m.clock.Now().UTC()
+ resumeAt := m.backoffResumeTimeLocked(siteID, now)
+ e.rec.Status = CacheQueueWaitingBackoff
+ e.rec.PauseReason = ""
+ e.rec.StopReason = backoffReasonText(kind)
+ e.rec.NextRunAt = resumeAt.Format(time.RFC3339)
+ e.rec.UpdatedAt = now.Format(time.RFC3339)
+ e.rt.resumePendingDownloads = len(e.rec.ActiveDownloadIDs) > 0
+ m.saveLoggedLocked("enter_backoff")
+ return e.rec
+}
+
+func (m *cacheQueueManager) selectActiveSiteEntryLocked(siteID site.ID) (*cacheQueueEntry, []cacheQueueRecord) {
+ for _, e := range m.tasks {
+ if e.rec.Site != string(siteID) {
+ continue
+ }
+ switch e.rec.Status {
+ case CacheQueueRunning, CacheQueueWaiting, CacheQueueWaitingBackoff:
+ return e, nil
+ }
+ }
+ var notify []cacheQueueRecord
+ for _, e := range m.tasks {
+ if e.rec.Site != string(siteID) || e.rec.Status != CacheQueueQueued {
+ continue
+ }
+ if !m.hasSiteLogin(siteID) {
+ e.rec.Status = CacheQueuePaused
+ e.rec.PauseReason = "auth_required"
+ e.rec.StopReason = "未登录或登录已失效,重新登录后自动继续"
+ e.rec.NextRunAt = ""
+ e.rec.UpdatedAt = m.nowRFC3339()
+ m.saveLoggedLocked("select_auth_pause")
+ notify = append(notify, e.rec)
+ continue
+ }
+ if e.rec.RestThreshold <= 0 {
+ e.rec.RestThreshold = m.pickRestThresholdLocked()
+ }
+ e.rec.Status = CacheQueueRunning
+ e.rec.PauseReason = ""
+ e.rec.StopReason = ""
+ e.rec.NextRunAt = ""
+ e.rec.UpdatedAt = m.nowRFC3339()
+ m.saveLoggedLocked("select_running")
+ notify = append(notify, e.rec)
+ return e, notify
+ }
+ return nil, notify
+}
+
+func (m *cacheQueueManager) runSiteLoop(ctx context.Context, siteID site.ID) {
+ wakeCh := m.siteWake[siteID]
+ for {
+ if ctx.Err() != nil {
+ return
+ }
+
+ m.mu.Lock()
+ entry, pendingNotify := m.selectActiveSiteEntryLocked(siteID)
+ if entry == nil {
+ m.mu.Unlock()
+ m.notifyStates(pendingNotify)
+ select {
+ case <-ctx.Done():
+ return
+ case <-wakeCh:
+ continue
+ }
+ }
+ if len(pendingNotify) > 0 {
+ m.mu.Unlock()
+ m.notifyStates(pendingNotify)
+ continue
+ }
+
+ // Phase A: Scheduled wait (inter-item delay, long rest, startup delay, or backoff cooldown).
+ if entry.rec.Status == CacheQueueWaiting || entry.rec.Status == CacheQueueWaitingBackoff {
+ nextAt, pErr := time.Parse(time.RFC3339, entry.rec.NextRunAt)
+ now := m.clock.Now().UTC()
+ if pErr == nil && now.Before(nextAt) {
+ select {
+ case <-wakeCh:
+ default:
+ }
+ waitDur := nextAt.Sub(now)
+ tm := m.clock.NewTimer(waitDur)
+ m.mu.Unlock()
+
+ select {
+ case <-ctx.Done():
+ tm.Stop()
+ return
+ case <-wakeCh:
+ tm.Stop()
+ continue
+ case <-tm.C():
+ }
+ continue
+ }
+
+ if !m.hasSiteLogin(siteID) {
+ m.mu.Unlock()
+ m.pauseForSite(siteID, "auth_required", "未登录或登录已失效,重新登录后自动继续")
+ continue
+ }
+ if blocked, _ := m.siteBackoffOrQuotaEnd(siteID, m.clock.Now()); blocked {
+ kind := site.ErrKindBackoff
+ if !m.b.subs.CanUseSiteQuotaTokens(string(siteID), 1) {
+ kind = site.ErrKindQuota
+ }
+ rec := m.enterWaitingBackoffLocked(entry, siteID, kind)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ continue
+ }
+ entry.rec.Status = CacheQueueRunning
+ entry.rec.PauseReason = ""
+ entry.rec.StopReason = ""
+ entry.rec.NextRunAt = ""
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ m.saveLoggedLocked("wake_running")
+ rec := entry.rec
+ m.mu.Unlock()
+ m.notifyState(rec)
+ continue
+ }
+
+ if !m.hasSiteLogin(siteID) {
+ m.mu.Unlock()
+ m.pauseForSite(siteID, "auth_required", "未登录或登录已失效,重新登录后自动继续")
+ continue
+ }
+
+ // Phase B: Monitor or resume the single active derived download item.
+ if len(entry.rec.ActiveDownloadIDs) > 0 {
+ activeIDs := append([]string(nil), entry.rec.ActiveDownloadIDs...)
+ activeItemKey := entry.rec.ActiveItemKey
+ needResume := entry.rt.resumePendingDownloads
+ entry.rt.resumePendingDownloads = false
+ m.mu.Unlock()
+
+ if needResume && m.b != nil && m.b.dl != nil {
+ for _, dlID := range activeIDs {
+ if t, ok, err := m.b.dl.GetTask(dlID); err == nil && ok && t.Status == "paused" {
+ _, _ = m.b.dl.Resume(dlID)
+ }
+ }
+ }
+
+ stillRunning := false
+ var authStopped bool
+ var backoffKind string
+ var appClosed bool
+ var userPaused bool
+ allSucceeded := true
+
+ if m.b != nil && m.b.dl != nil {
+ for _, dlID := range activeIDs {
+ t, ok, err := m.b.dl.GetTask(dlID)
+ if err != nil || !ok {
+ allSucceeded = false
+ continue
+ }
+ switch t.Status {
+ case "queued", "running", "downloading", "muxing":
+ stillRunning = true
+ case "completed":
+ // Part succeeded.
+ case "partial":
+ if m.b != nil && m.b.lib != nil {
+ checkKey := firstNonEmpty(t.ItemKey, activeItemKey)
+ if _, exists, lErr := m.b.lib.GetItem(checkKey); lErr != nil || !exists {
+ allSucceeded = false
+ }
+ }
+ case "paused":
+ allSucceeded = false
+ switch {
+ case t.PauseReason == "auth_required" || t.ErrorKind == site.ErrKindAuthRequired:
+ authStopped = true
+ case t.PauseReason == "risk_control" || isBackoffOrQuotaKind(t.PauseReason) || isBackoffOrQuotaKind(t.ErrorKind):
+ backoffKind = firstNonEmpty(t.ErrorKind, t.PauseReason)
+ case t.PauseReason == "app_closed":
+ appClosed = true
+ default:
+ userPaused = true
+ }
+ default: // "failed", "canceled"
+ allSucceeded = false
+ if t.ErrorKind == site.ErrKindAuthRequired {
+ authStopped = true
+ } else if isBackoffOrQuotaKind(t.ErrorKind) {
+ backoffKind = t.ErrorKind
+ }
+ }
+ }
+ }
+
+ if stillRunning {
+ select {
+ case <-ctx.Done():
+ return
+ case <-wakeCh:
+ continue
+ }
+ }
+ if ctx.Err() != nil {
+ return
+ }
+ if appClosed {
+ m.mu.Lock()
+ var notify *cacheQueueRecord
+ if entry.rec.Status == CacheQueueRunning && slices.Equal(entry.rec.ActiveDownloadIDs, activeIDs) {
+ entry.rec.Status = CacheQueuePaused
+ entry.rec.PauseReason = "app_closed"
+ entry.rec.StopReason = "已暂停(应用关闭)"
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ entry.rt.resumePendingDownloads = true
+ m.saveLoggedLocked("pause_app_closed")
+ r := entry.rec
+ notify = &r
+ }
+ m.mu.Unlock()
+ if notify != nil {
+ m.notifyState(*notify)
+ }
+ continue
+ }
+
+ m.mu.Lock()
+ if entry.rec.Status != CacheQueueRunning || !slices.Equal(entry.rec.ActiveDownloadIDs, activeIDs) {
+ m.mu.Unlock()
+ continue
+ }
+ if authStopped {
+ m.mu.Unlock()
+ m.pauseForSite(siteID, "auth_required", "登录已失效,重新登录后自动继续")
+ continue
+ }
+ if backoffKind != "" {
+ rec := m.enterWaitingBackoffLocked(entry, siteID, backoffKind)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ continue
+ }
+ if userPaused {
+ entry.rec.Status = CacheQueuePaused
+ entry.rec.PauseReason = "user"
+ entry.rec.StopReason = "已手动暂停"
+ entry.rec.NextRunAt = ""
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ entry.rt.resumePendingDownloads = true
+ m.saveLoggedLocked("pause_user_dl")
+ rec := entry.rec
+ m.mu.Unlock()
+ m.notifyState(rec)
+ continue
+ }
+
+ // Reconstruct remaining multi-part video enqueuers across app restarts from persisted page numbers.
+ if allSucceeded && len(entry.rt.nextPartEnqueuers) == 0 && len(entry.rec.ActivePendingPages) > 0 && m.b != nil {
+ if bvid, ok := bilibiliVideoIDFromItemKey(entry.rec.ActiveItemKey); ok {
+ entry.rt.nextPartEnqueuers = m.b.buildBilibiliPartEnqueuers(bvid, entry.rec.ActivePendingPages, queueForMid(entry.rec.User))
+ } else {
+ entry.rec.ActivePendingPages = nil
+ }
+ }
+
+ // If this was a multi-part video with remaining parts, enqueue the next part before marking the video done.
+ if allSucceeded && len(entry.rt.nextPartEnqueuers) > 0 {
+ m.advanceMultiPartLocked(ctx, siteID, entry)
+ continue
+ }
+
+ rec := m.finishItemOutcomeLocked(entry, allSucceeded)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ continue
+ }
+
+ // Phase C: Inspect candidates or fetch next page, skipping cached/uncacheable items without waiting.
+ m.advanceCandidateStep(ctx, siteID, entry)
+ }
+}
+
+// advanceMultiPartLocked enqueues remaining parts of a multi-part video one by one.
+// Caller holds m.mu on entry; this method unlocks m.mu before returning.
+func (m *cacheQueueManager) advanceMultiPartLocked(ctx context.Context, siteID site.ID, entry *cacheQueueEntry) {
+ for len(entry.rt.nextPartEnqueuers) > 0 {
+ nextPart := entry.rt.nextPartEnqueuers[0]
+ stepCtx, stepCancel := context.WithCancel(site.WithAutomaticRequests(ctx, "cache_queue"))
+ entry.rt.stepCancel = stepCancel
+ m.mu.Unlock()
+
+ pids, pErr := nextPart(stepCtx)
+
+ m.mu.Lock()
+ stepCancel()
+ if entry.rt.stepCancel != nil {
+ entry.rt.stepCancel = nil
+ }
+ if entry.rec.Status != CacheQueueRunning || ctx.Err() != nil {
+ m.mu.Unlock()
+ return
+ }
+ if pErr != nil {
+ kind := site.KindOf(pErr)
+ if kind == site.ErrKindAuthRequired {
+ m.mu.Unlock()
+ m.pauseForSite(siteID, "auth_required", "登录已失效,重新登录后自动继续")
+ return
+ }
+ if isBackoffOrQuotaKind(kind) {
+ rec := m.enterWaitingBackoffLocked(entry, siteID, kind)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+ entry.rt.nextPartEnqueuers = nil
+ entry.rec.ActivePendingPages = nil
+ rec := m.finishItemOutcomeLocked(entry, false)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+ entry.rt.nextPartEnqueuers = entry.rt.nextPartEnqueuers[1:]
+ if len(entry.rec.ActivePendingPages) > 0 {
+ entry.rec.ActivePendingPages = entry.rec.ActivePendingPages[1:]
+ }
+ if len(pids) > 0 {
+ entry.rec.ActiveDownloadIDs = pids
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ m.saveLoggedLocked("next_part")
+ m.mu.Unlock()
+ return
+ }
+ }
+ // Every remaining part was already complete / produced zero download tasks.
+ rec := m.finishItemOutcomeLocked(entry, true)
+ m.mu.Unlock()
+ m.notifyState(rec)
+}
+
+func (m *cacheQueueManager) finishItemOutcomeLocked(entry *cacheQueueEntry, cached bool) cacheQueueRecord {
+ nowStr := m.nowRFC3339()
+ itemKey := entry.rec.ActiveItemKey
+ title := entry.rec.ActiveTitle
+ entry.rec.ActiveDownloadIDs = nil
+ entry.rec.ActivePendingPages = nil
+ entry.rec.ActiveItemKey = ""
+ entry.rec.ActiveTitle = ""
+ entry.rt.nextPartEnqueuers = nil
+
+ if itemKey != "" && !slices.Contains(entry.rec.ProcessedKeys, itemKey) {
+ entry.rec.ProcessedKeys = append(entry.rec.ProcessedKeys, itemKey)
+ }
+
+ if cached {
+ entry.rec.CachedCount++
+ entry.rec.SinceRestCount++
+ if itemKey != "" {
+ if title == "" && m.b != nil && m.b.lib != nil {
+ if meta, ok, err := m.b.lib.GetItem(itemKey); err == nil && ok && meta.Title != "" {
+ title = trimQueueSummaryTitle(meta.Title)
+ }
+ }
+ 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]
+ }
+ }
+ } else {
+ entry.rec.SkippedCount++
+ }
+
+ // If the current page buffer is exhausted and there are no further pages, complete immediately.
+ if entry.rt.pageLoaded && entry.rt.pageIdx >= len(entry.rt.pageItems) && !entry.rt.pageNextHasMore {
+ entry.rec.Cursor = sanitizeCursor(entry.rt.pageNextCursor)
+ entry.rec.HasMore = false
+ entry.rec.ProcessedKeys = nil
+ entry.rt.pageLoaded = false
+ entry.rt.pageItems = nil
+ entry.rt.pageIdx = 0
+ entry.rec.Status = CacheQueueCompleted
+ entry.rec.PauseReason = ""
+ entry.rec.StopReason = ""
+ entry.rec.NextRunAt = ""
+ entry.rec.UpdatedAt = nowStr
+ m.saveLoggedLocked("complete_item")
+ return entry.rec
+ }
+
+ if entry.rec.RestThreshold <= 0 {
+ entry.rec.RestThreshold = m.pickRestThresholdLocked()
+ }
+ 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)
+ }
+ nextAt := m.clock.Now().UTC().Add(delay)
+ entry.rec.Status = CacheQueueWaiting
+ entry.rec.PauseReason = ""
+ entry.rec.StopReason = reason
+ entry.rec.NextRunAt = nextAt.Format(time.RFC3339)
+ entry.rec.UpdatedAt = nowStr
+ m.saveLoggedLocked("wait_next")
+ return entry.rec
+}
+
+func (m *cacheQueueManager) advanceCandidateStep(ctx context.Context, siteID site.ID, entry *cacheQueueEntry) {
+ // Caller holds m.mu on entry; this method unlocks m.mu before returning!
+ if entry.rt.pager == nil && m.b != nil {
+ pager, err := m.b.buildQueuePager(siteID, entry.rec.List, entry.rec.User, entry.rec.UserName)
+ if err != nil {
+ entry.rec.Status = CacheQueueStopped
+ entry.rec.StopReason = sanitizeQueueText(err.Error())
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ m.saveLoggedLocked("build_pager_err")
+ rec := entry.rec
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+ entry.rt.pager = pager
+ }
+
+ // Exhausted current buffered page? Advance persistent cursor.
+ if entry.rt.pageLoaded && entry.rt.pageIdx >= len(entry.rt.pageItems) {
+ entry.rec.Cursor = sanitizeCursor(entry.rt.pageNextCursor)
+ entry.rec.HasMore = entry.rt.pageNextHasMore
+ entry.rec.ProcessedKeys = nil
+ entry.rt.pageLoaded = false
+ entry.rt.pageItems = nil
+ entry.rt.pageIdx = 0
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ if !entry.rec.HasMore {
+ entry.rec.Status = CacheQueueCompleted
+ entry.rec.PauseReason = ""
+ entry.rec.StopReason = ""
+ entry.rec.NextRunAt = ""
+ m.saveLoggedLocked("complete_page")
+ rec := entry.rec
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+ m.saveLoggedLocked("advance_cursor")
+ }
+
+ // Fetch next page if no buffered page is loaded.
+ if !entry.rt.pageLoaded {
+ if !entry.rec.HasMore {
+ entry.rec.Status = CacheQueueCompleted
+ entry.rec.PauseReason = ""
+ entry.rec.StopReason = ""
+ entry.rec.NextRunAt = ""
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ m.saveLoggedLocked("complete_no_more")
+ rec := entry.rec
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+ if blocked, _ := m.siteBackoffOrQuotaEnd(siteID, m.clock.Now()); blocked {
+ kind := site.ErrKindBackoff
+ if !m.b.subs.CanUseSiteQuotaTokens(string(siteID), 1) {
+ kind = site.ErrKindQuota
+ }
+ rec := m.enterWaitingBackoffLocked(entry, siteID, kind)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+
+ cursor := entry.rec.Cursor
+ pager := entry.rt.pager
+ stepCtx, stepCancel := context.WithCancel(site.WithAutomaticRequests(ctx, "cache_queue"))
+ entry.rt.stepCancel = stepCancel
+ m.mu.Unlock()
+
+ items, nextCursor, nextMore, err := pager(stepCtx, cursor)
+
+ m.mu.Lock()
+ stepCancel()
+ if entry.rt.stepCancel != nil {
+ entry.rt.stepCancel = nil
+ }
+ if entry.rec.Status != CacheQueueRunning || ctx.Err() != nil {
+ m.mu.Unlock()
+ return
+ }
+ if err != nil {
+ kind := site.KindOf(err)
+ if kind == site.ErrKindAuthRequired {
+ m.mu.Unlock()
+ m.pauseForSite(siteID, "auth_required", "登录已失效,重新登录后自动继续")
+ return
+ }
+ if isBackoffOrQuotaKind(kind) {
+ rec := m.enterWaitingBackoffLocked(entry, siteID, kind)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+ entry.rec.Status = CacheQueueStopped
+ entry.rec.StopReason = sanitizeQueueText("读取列表失败:" + err.Error())
+ entry.rec.NextRunAt = ""
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ m.saveLoggedLocked("pager_err")
+ rec := entry.rec
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+ if len(items) == 0 {
+ cleanNext := sanitizeCursor(nextCursor)
+ if nextMore && cleanNext != "" && cleanNext != entry.rec.Cursor {
+ entry.rec.Cursor = cleanNext
+ entry.rec.HasMore = true
+ entry.rec.ProcessedKeys = nil
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ m.saveLoggedLocked("advance_empty_page")
+ m.mu.Unlock()
+ return
+ }
+ entry.rec.Cursor = cleanNext
+ entry.rec.HasMore = false
+ entry.rec.ProcessedKeys = nil
+ entry.rec.Status = CacheQueueCompleted
+ entry.rec.PauseReason = ""
+ entry.rec.StopReason = ""
+ entry.rec.NextRunAt = ""
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ m.saveLoggedLocked("complete_empty_page")
+ rec := entry.rec
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+ entry.rt.pageItems = items
+ entry.rt.pageIdx = 0
+ entry.rt.pageNextCursor = nextCursor
+ entry.rt.pageNextHasMore = nextMore
+ entry.rt.pageLoaded = true
+ }
+
+ // Scan buffered page items: skip cached/uncacheable items immediately without waiting.
+ var keysToCheck []string
+ for i := entry.rt.pageIdx; i < len(entry.rt.pageItems); i++ {
+ if k := entry.rt.pageItems[i].key; k != "" {
+ keysToCheck = append(keysToCheck, k)
+ }
+ }
+ var states map[string]library.DotState
+ if m.b != nil && len(keysToCheck) > 0 {
+ states = m.b.States(keysToCheck)
+ }
+
+ skippedAny := false
+ for entry.rt.pageIdx < len(entry.rt.pageItems) {
+ cand := entry.rt.pageItems[entry.rt.pageIdx]
+ if cand.key == "" {
+ entry.rt.pageIdx++
+ entry.rec.SkippedCount++
+ skippedAny = true
+ continue
+ }
+ if entry.rt.seenKeys[cand.key] || slices.Contains(entry.rec.ProcessedKeys, cand.key) {
+ entry.rt.seenKeys[cand.key] = true
+ entry.rt.pageIdx++
+ continue
+ }
+ if cand.uncacheable || !m.b.queueShouldCache(cand.key, states[cand.key]) {
+ entry.rt.seenKeys[cand.key] = true
+ entry.rt.pageIdx++
+ entry.rec.SkippedCount++
+ if !slices.Contains(entry.rec.ProcessedKeys, cand.key) {
+ entry.rec.ProcessedKeys = append(entry.rec.ProcessedKeys, cand.key)
+ }
+ skippedAny = true
+ continue
+ }
+
+ // Found an uncached candidate! Check backoff/quota before calling cand.enqueue.
+ if blocked, _ := m.siteBackoffOrQuotaEnd(siteID, m.clock.Now()); blocked {
+ if skippedAny {
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ }
+ kind := site.ErrKindBackoff
+ if !m.b.subs.CanUseSiteQuotaTokens(string(siteID), 1) {
+ kind = site.ErrKindQuota
+ }
+ rec := m.enterWaitingBackoffLocked(entry, siteID, kind)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+
+ stepCtx, stepCancel := context.WithCancel(site.WithAutomaticRequests(ctx, "cache_queue"))
+ entry.rt.stepCancel = stepCancel
+ if skippedAny {
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ m.saveLoggedLocked("skip_candidates")
+ skippedAny = false
+ }
+ m.mu.Unlock()
+
+ enq, err := cand.enqueue(stepCtx)
+
+ m.mu.Lock()
+ stepCancel()
+ if entry.rt.stepCancel != nil {
+ entry.rt.stepCancel = nil
+ }
+ if entry.rec.Status != CacheQueueRunning || ctx.Err() != nil {
+ m.mu.Unlock()
+ return
+ }
+ if err != nil {
+ kind := site.KindOf(err)
+ if kind == site.ErrKindAuthRequired {
+ m.mu.Unlock()
+ m.pauseForSite(siteID, "auth_required", "登录已失效,重新登录后自动继续")
+ return
+ }
+ if isBackoffOrQuotaKind(kind) {
+ rec := m.enterWaitingBackoffLocked(entry, siteID, kind)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+ // Ordinary per-item failure (e.g. deleted/unavailable). The attempt already sent
+ // site requests, so count it as skipped and keep the normal random gap before the
+ // next candidate: a run of failing items must not turn into back-to-back requests.
+ entry.rt.seenKeys[cand.key] = true
+ entry.rt.pageIdx++
+ entry.rec.ActiveItemKey = cand.key
+ entry.rec.ActiveTitle = ""
+ rec := m.finishItemOutcomeLocked(entry, false)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+
+ // Enqueue succeeded!
+ entry.rt.seenKeys[cand.key] = true
+ entry.rt.pageIdx++
+ entry.rec.ActiveItemKey = sanitizeItemKey(firstNonEmpty(enq.itemKey, cand.key))
+ entry.rec.ActiveTitle = sanitizeQueueText(firstNonEmpty(enq.title, cand.title))
+ if len(enq.taskIDs) == 0 {
+ // Synchronous completion (used by synthetic candidate tests with no async download task).
+ rec := m.finishItemOutcomeLocked(entry, true)
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+ entry.rec.ActiveDownloadIDs = append([]string(nil), enq.taskIDs...)
+ entry.rec.ActivePendingPages = append([]int(nil), enq.pendingPages...)
+ entry.rt.nextPartEnqueuers = enq.nextParts
+ entry.rt.resumePendingDownloads = false
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ m.saveLoggedLocked("enqueued_item")
+ rec := entry.rec
+ m.mu.Unlock()
+ m.notifyState(rec)
+ return
+ }
+
+ var notify *cacheQueueRecord
+ if skippedAny {
+ entry.rec.UpdatedAt = m.nowRFC3339()
+ m.saveLoggedLocked("skip_page")
+ r := entry.rec
+ notify = &r
+ }
+ m.mu.Unlock()
+ if notify != nil {
+ m.notifyState(*notify)
+ }
+}
+
+// queueShouldCache tells whether a cache queue (全部缓存, 定期全部缓存)
+// caches an item of the list: one not cached yet or failed, and one cached
+// but incomplete (partial, missing records, pages without a file), whose
+// missing parts caching again fills while valid files are kept. Items being
+// cached, complete ones, paused tasks (continued from the task page) and
+// items that only have a better quality available are skipped.
+func (b *Backend) queueShouldCache(key string, st library.DotState) bool {
+ switch st.Dot {
+ case "ring", "green":
+ return false
+ case "yellow":
+ if strings.HasPrefix(st.Label, "已暂停") || b == nil || b.lib == nil {
+ return false
+ }
+ meta, ok, err := b.lib.GetItem(key)
+ if err != nil {
+ return false
+ }
+ // A partial task without an indexed item yet still needs caching.
+ return !ok || library.NeedsCompletion(meta)
+ }
+ return true
+}
diff --git a/internal/service/desktop.go b/internal/service/desktop.go
index 7c5e099..56fd444 100644
--- a/internal/service/desktop.go
+++ b/internal/service/desktop.go
@@ -2,6 +2,7 @@ package service
import (
"fmt"
+ "net/url"
"os"
"os/exec"
"runtime"
@@ -11,13 +12,44 @@ import (
// Desktop abstracts OS shell actions (opening URLs, folders, or revealing files).
// Automated tests, prototypes, uishots, and smoke runs use MockDesktop or TRACE_QUIET
-// so no external browser or Explorer window is ever launched (§6.4).
+// so no external browser or Explorer window is ever launched.
type Desktop interface {
OpenExternalURL(rawURL string) error
OpenPath(path string) error
RevealPath(path string) error
}
+// validateExternalURL ensures only safe HTTP/HTTPS URLs with a non-empty host
+// and no embedded credentials or control characters are passed to the OS URL handler.
+func validateExternalURL(rawURL string) (string, error) {
+ trimmed := strings.TrimSpace(rawURL)
+ if trimmed == "" {
+ return "", fmt.Errorf("empty url")
+ }
+ for _, r := range trimmed {
+ if r < 0x20 || r == 0x7f || r == ' ' || r == '\t' {
+ return "", fmt.Errorf("invalid url: contains whitespace or control character")
+ }
+ }
+ if strings.HasPrefix(trimmed, `\\`) {
+ return "", fmt.Errorf("invalid url: UNC path rejected")
+ }
+ u, err := url.Parse(trimmed)
+ if err != nil {
+ return "", fmt.Errorf("invalid url: %w", err)
+ }
+ if !strings.EqualFold(u.Scheme, "https") && !strings.EqualFold(u.Scheme, "http") {
+ return "", fmt.Errorf("unsupported url scheme: %q", u.Scheme)
+ }
+ if u.Host == "" || u.Hostname() == "" {
+ return "", fmt.Errorf("invalid url: missing host")
+ }
+ if u.User != nil {
+ return "", fmt.Errorf("invalid url: userinfo not allowed")
+ }
+ return u.String(), nil
+}
+
// RecordedAction represents a shell action captured by MockDesktop.
type RecordedAction struct {
Kind string `json:"kind"` // "url", "open_path", "reveal_path"
@@ -35,11 +67,12 @@ func NewMockDesktop() *MockDesktop {
}
func (m *MockDesktop) OpenExternalURL(rawURL string) error {
- if strings.TrimSpace(rawURL) == "" {
- return fmt.Errorf("empty url")
+ clean, err := validateExternalURL(rawURL)
+ if err != nil {
+ return err
}
m.mu.Lock()
- m.actions = append(m.actions, RecordedAction{Kind: "url", Target: rawURL})
+ m.actions = append(m.actions, RecordedAction{Kind: "url", Target: clean})
m.mu.Unlock()
return nil
}
@@ -84,32 +117,53 @@ func NewDefaultDesktop() Desktop {
return &OSDesktop{fallback: NewMockDesktop()}
}
+func startAndRelease(name string, args ...string) error {
+ cmd := exec.Command(name, args...)
+ if err := cmd.Start(); err != nil {
+ return err
+ }
+ if cmd.Process != nil {
+ _ = cmd.Process.Release()
+ }
+ return nil
+}
+
func (d *OSDesktop) OpenExternalURL(rawURL string) error {
+ clean, err := validateExternalURL(rawURL)
+ if err != nil {
+ return err
+ }
if os.Getenv("TRACE_QUIET") != "" {
- return d.fallback.OpenExternalURL(rawURL)
+ return d.fallback.OpenExternalURL(clean)
}
if runtime.GOOS == "windows" {
- return exec.Command("rundll32.exe", "url.dll,FileProtocolHandler", rawURL).Start()
+ return startAndRelease("rundll32.exe", "url.dll,FileProtocolHandler", clean)
}
- return d.fallback.OpenExternalURL(rawURL)
+ return d.fallback.OpenExternalURL(clean)
}
func (d *OSDesktop) OpenPath(path string) error {
+ if strings.TrimSpace(path) == "" {
+ return fmt.Errorf("empty path")
+ }
if os.Getenv("TRACE_QUIET") != "" {
return d.fallback.OpenPath(path)
}
if runtime.GOOS == "windows" {
- return exec.Command("explorer.exe", path).Start()
+ return startAndRelease("explorer.exe", path)
}
return d.fallback.OpenPath(path)
}
func (d *OSDesktop) RevealPath(path string) error {
+ if strings.TrimSpace(path) == "" {
+ return fmt.Errorf("empty path")
+ }
if os.Getenv("TRACE_QUIET") != "" {
return d.fallback.RevealPath(path)
}
if runtime.GOOS == "windows" {
- return exec.Command("explorer.exe", "/select,", path).Start()
+ return startAndRelease("explorer.exe", "/select,", path)
}
return d.fallback.RevealPath(path)
}
diff --git a/internal/service/dev_install_windows.go b/internal/service/dev_install_windows.go
index e7bc1cf..2b2d502 100644
--- a/internal/service/dev_install_windows.go
+++ b/internal/service/dev_install_windows.go
@@ -3,8 +3,6 @@
package service
import (
- "errors"
-
"github.com/chialecode/trace/internal/update"
"golang.org/x/sys/windows/registry"
)
@@ -20,7 +18,7 @@ func ReadSystemInstalledDevVersion() string {
func readRegistryDisplayVersion(root registry.Key, subkey string) string {
k, err := registry.OpenKey(root, subkey, registry.QUERY_VALUE)
- if errors.Is(err, registry.ErrNotExist) || err != nil {
+ if err != nil {
return ""
}
defer k.Close()
diff --git a/internal/service/douyin_auth_test.go b/internal/service/douyin_auth_test.go
index aebdaed..491ceee 100644
--- a/internal/service/douyin_auth_test.go
+++ b/internal/service/douyin_auth_test.go
@@ -497,8 +497,19 @@ func TestPerSiteExpiryAndLogoutIsolation(t *testing.T) {
if err != nil || !ok || biliDetail.Task.Status != "queued" {
t.Fatalf("expected dl-bili-active to remain queued, got %+v (ok=%v err=%v)", biliDetail.Task, ok, err)
}
- if activeTasks, activeRecs := h.backend.ActiveWork(); activeTasks != 1 || activeRecs != 1 {
- t.Fatalf("expected ActiveWork=(1, 1) after Douyin expiry (Bilibili task+recording untouched), got (%d, %d)", activeTasks, activeRecs)
+ // Auth expiry stops live recordings asynchronously to avoid self-deadlock
+ // when triggered from a live recording or site-client lock; wait briefly for StopForSite.
+ var activeTasks, activeRecs int
+ deadline := time.Now().Add(2 * time.Second)
+ for {
+ activeTasks, activeRecs = h.backend.ActiveWork()
+ if activeTasks == 1 && activeRecs == 1 {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("expected ActiveWork=(1, 1) after Douyin expiry (Bilibili task+recording untouched), got (%d, %d)", activeTasks, activeRecs)
+ }
+ time.Sleep(10 * time.Millisecond)
}
for _, acct := range h.backend.ListLiveAccounts() {
if acct.Site == "douyin" && acct.Recording {
diff --git a/internal/service/douyin_planner.go b/internal/service/douyin_planner.go
index 99f6db6..e3266b6 100644
--- a/internal/service/douyin_planner.go
+++ b/internal/service/douyin_planner.go
@@ -28,6 +28,13 @@ func (p *douyinWorkPlanner) ReportAutomaticError(ctx context.Context, err error)
}
}
+func (p *douyinWorkPlanner) ResolvePlayRedirect(ctx context.Context, playURL string) (string, error) {
+ if err := p.backend.requireSiteLogin(site.Douyin); err != nil {
+ return "", err
+ }
+ return p.backend.douyin.ResolvePlayRedirect(ctx, playURL)
+}
+
func (p *douyinWorkPlanner) PlanWorkDownload(ctx context.Context, targetID string, opts download.WorkPlanOptions) (download.WorkDownloadPlan, error) {
if err := p.backend.requireSiteLogin(site.Douyin); err != nil {
return download.WorkDownloadPlan{}, err
@@ -94,6 +101,7 @@ func (p *douyinWorkPlanner) PlanWorkDownload(ctx context.Context, targetID strin
}
}
plan.VideoURLs = append([]string(nil), selected.URLs...)
+ plan.NeedSetToken = selected.NeedSetToken
plan.VideoGear = selected.GearName
plan.QualityName = selected.QualityLabel
plan.Codec = selected.Codec
@@ -128,6 +136,7 @@ func (p *douyinWorkPlanner) PlanWorkDownload(ctx context.Context, targetID strin
}
if pg.VideoStream != nil {
item.VideoURLs = append([]string(nil), pg.VideoStream.URLs...)
+ item.NeedSetToken = pg.VideoStream.NeedSetToken
item.DurationSec = pg.VideoStream.DurationSec
item.Gear = pg.VideoStream.GearName
item.QualityName = pg.VideoStream.QualityLabel
diff --git a/internal/service/dto.go b/internal/service/dto.go
index 1c247a7..a26992f 100644
--- a/internal/service/dto.go
+++ b/internal/service/dto.go
@@ -437,73 +437,21 @@ func formatAccountKey(siteID site.ID, uid string) string {
}
func mapRoomToAccountState(rs live.RoomState) LiveAccountState {
- if strings.EqualFold(rs.Site, string(site.Douyin)) {
- uidStr := strings.TrimSpace(rs.AccountUID)
- accountKey := ""
- if uidStr != "" {
- accountKey = formatAccountKey(site.Douyin, uidStr)
- }
- roomStr := strings.TrimSpace(rs.RoomIDStr)
- if roomStr == "" && rs.RoomID > 0 {
- roomStr = strconv.FormatInt(rs.RoomID, 10)
- }
- recKey := strings.TrimSpace(rs.RoomKey)
- if recKey == "" && roomStr != "" {
- recKey = "douyin:live:" + roomStr
- }
- audioOnly := rs.AudioOnly || rs.LiveState == site.LiveStateAudioOnly
- liveStatus := rs.LiveStatus
- if audioOnly {
- liveStatus = 1
- }
- transport := firstNonEmpty(rs.Transport, string(site.LiveTransportHTTPFLV))
- partPath := firstNonEmpty(rs.RecordPartPath, resolveRecordingPartPath(rs.RecordItemDir))
- return LiveAccountState{
- Site: string(site.Douyin),
- AccountKey: accountKey,
- RecordingKey: recKey,
- UID: uidStr,
- RoomID: roomStr,
- WebRID: rs.WebRID,
- Uname: rs.Uname,
- Face: rs.Face,
- Title: rs.Title,
- Cover: rs.Cover,
- AreaName: rs.AreaName,
- NoRoom: rs.LiveState == site.LiveStateNone,
- LiveStatus: liveStatus,
- LiveSince: rs.LiveSince,
- StatusText: rs.StatusText,
- QualityName: rs.QualityName,
- Codec: rs.Codec,
- Transport: transport,
- AudioOnly: audioOnly,
- Recording: rs.Recording,
- RecordSession: rs.RecordSession,
- RecordDurationSec: rs.RecordDurationSec,
- RecordSpeedBps: rs.RecordSpeedBps,
- RecordBytes: rs.RecordBytes,
- RecordSegments: rs.RecordSegments,
- RecordItemDir: rs.RecordItemDir,
- RecordPartPath: partPath,
- RecordPartIndex: rs.RecordPartIndex,
- RecordPartBytes: rs.RecordPartBytes,
- RecordPartReady: rs.RecordPartReady,
- PreviewSupported: rs.PreviewSupported,
- PreviewReason: rs.PreviewReason,
- StopReason: rs.StopReason,
- LastError: rs.LastError,
- UpdatedAt: rs.UpdatedAt,
- }
+ isDouyin := strings.EqualFold(rs.Site, string(site.Douyin))
+ siteID := site.Bilibili
+ if isDouyin {
+ siteID = site.Douyin
}
uidStr := strings.TrimSpace(rs.AccountUID)
- accountKey := ""
- if rs.UID > 0 {
+ var mid int64
+ if !isDouyin && rs.UID > 0 {
uidStr = strconv.FormatInt(rs.UID, 10)
+ mid = rs.UID
}
+ accountKey := ""
if uidStr != "" {
- accountKey = formatAccountKey(site.Bilibili, uidStr)
+ accountKey = formatAccountKey(siteID, uidStr)
}
roomStr := strings.TrimSpace(rs.RoomIDStr)
if roomStr == "" && rs.RoomID > 0 {
@@ -511,35 +459,64 @@ func mapRoomToAccountState(rs live.RoomState) LiveAccountState {
}
recKey := strings.TrimSpace(rs.RoomKey)
if recKey == "" && roomStr != "" {
- recKey = "bilibili:live:" + roomStr
+ recKey = string(siteID) + ":live:" + roomStr
+ }
+
+ var (
+ noRoom bool
+ audioOnly bool
+ liveStatus int
+ statusText string
+ transport string
+ webRID string
+ )
+ if isDouyin {
+ audioOnly = rs.AudioOnly || rs.LiveState == site.LiveStateAudioOnly
+ liveStatus = rs.LiveStatus
+ if audioOnly {
+ liveStatus = 1
+ }
+ noRoom = rs.LiveState == site.LiveStateNone
+ statusText = rs.StatusText
+ transport = firstNonEmpty(rs.Transport, string(site.LiveTransportHTTPFLV))
+ webRID = rs.WebRID
+ } else {
+ audioOnly = rs.AudioOnly
+ liveStatus = rs.LiveStatus
+ noRoom = rs.RoomID <= 0
+ statusText = rs.StatusText
+ if noRoom && statusText == "" {
+ statusText = "未开通直播间"
+ }
+ transport = firstNonEmpty(rs.Transport, string(site.LiveTransportHLSFMP4))
}
- noRoom := rs.RoomID <= 0
- statusText := rs.StatusText
- if noRoom && statusText == "" {
- statusText = "未开通直播间"
+
+ partPath := rs.RecordPartPath
+ if partPath == "" && rs.Recording {
+ partPath = resolveRecordingPartPath(rs.RecordItemDir)
}
- transport := firstNonEmpty(rs.Transport, string(site.LiveTransportHLSFMP4))
- partPath := firstNonEmpty(rs.RecordPartPath, resolveRecordingPartPath(rs.RecordItemDir))
+
return LiveAccountState{
- Site: string(site.Bilibili),
+ Site: string(siteID),
AccountKey: accountKey,
RecordingKey: recKey,
UID: uidStr,
- Mid: rs.UID,
+ Mid: mid,
RoomID: roomStr,
+ WebRID: webRID,
Uname: rs.Uname,
Face: rs.Face,
Title: rs.Title,
Cover: rs.Cover,
AreaName: rs.AreaName,
NoRoom: noRoom,
- LiveStatus: rs.LiveStatus,
+ LiveStatus: liveStatus,
LiveSince: rs.LiveSince,
StatusText: statusText,
QualityName: rs.QualityName,
Codec: rs.Codec,
Transport: transport,
- AudioOnly: rs.AudioOnly,
+ AudioOnly: audioOnly,
Recording: rs.Recording,
RecordSession: rs.RecordSession,
RecordDurationSec: rs.RecordDurationSec,
@@ -560,71 +537,6 @@ func mapRoomToAccountState(rs live.RoomState) LiveAccountState {
}
}
-func mapBilibiliRoomToAccountState(rs live.RoomState) LiveAccountState {
- return mapRoomToAccountState(rs)
-}
-
-func mapSiteLiveStatusToAccountState(st site.LiveStatus) LiveAccountState {
- siteStr := string(st.Site)
- if siteStr == "" {
- siteStr = string(site.Douyin)
- }
- accountKey := ""
- if st.AccountUID != "" {
- accountKey = formatAccountKey(site.ID(siteStr), st.AccountUID)
- }
- recKey := ""
- if st.RoomID != "" {
- recKey = siteStr + ":live:" + st.RoomID
- }
- liveStatus := 0
- statusText := "未开播"
- noRoom := false
- audioOnly := false
- switch st.Status {
- case site.LiveStateLive:
- liveStatus = 1
- statusText = "直播中"
- case site.LiveStateAudioOnly:
- liveStatus = 1
- audioOnly = true
- statusText = "纯语音直播"
- case site.LiveStateRound:
- liveStatus = 2
- statusText = "轮播中"
- case site.LiveStateNone:
- noRoom = true
- statusText = "未开通直播间"
- default:
- statusText = "未开播"
- }
- transport := string(site.LiveTransportHTTPFLV)
- if st.Site == site.Bilibili {
- transport = string(site.LiveTransportHLSFMP4)
- }
- return LiveAccountState{
- Site: siteStr,
- AccountKey: accountKey,
- RecordingKey: recKey,
- UID: st.AccountUID,
- RoomID: st.RoomID,
- WebRID: st.WebRID,
- Uname: st.Uname,
- Face: st.Face,
- Title: st.Title,
- Cover: st.Cover,
- AreaName: st.AreaName,
- NoRoom: noRoom,
- LiveStatus: liveStatus,
- LiveSince: st.LiveSince,
- StatusText: statusText,
- QualityName: st.QualityName,
- Codec: st.Codec,
- Transport: transport,
- AudioOnly: audioOnly,
- }
-}
-
func resolveRecordingPartPath(itemDir string) string {
dir := strings.TrimSpace(itemDir)
if dir == "" {
diff --git a/internal/service/events.go b/internal/service/events.go
index d811518..6267a20 100644
--- a/internal/service/events.go
+++ b/internal/service/events.go
@@ -16,6 +16,8 @@ const (
EventLibraryChanged EventType = "library.changed"
EventSubscriptionChecked EventType = "subscription.checked"
EventLiveUpdated EventType = "live.updated"
+ // EventTransferUpdated is an import or export job's progress.
+ EventTransferUpdated EventType = "transfer.updated"
)
// Event carries a backend state change notification.
diff --git a/internal/service/fixes_regression_test.go b/internal/service/fixes_regression_test.go
new file mode 100644
index 0000000..af4d62d
--- /dev/null
+++ b/internal/service/fixes_regression_test.go
@@ -0,0 +1,1114 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/live"
+ "github.com/chialecode/trace/internal/remote"
+ "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/subscription"
+ "github.com/chialecode/trace/internal/transfer"
+)
+
+func seedBiliLogin(t *testing.T, b *Backend) {
+ t.Helper()
+ if _, err := b.cred.SaveManual("SESSDATA=s; bili_jct=j; DedeUserID=1", ""); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func seedDouyinLogin(t *testing.T, b *Backend) {
+ t.Helper()
+ if _, err := b.douyinCred.SaveDouyinManual("sessionid=s; ttwid=t"); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestExternalURLValidationRejectsUnsafeSchemes(t *testing.T) {
+ desk := NewMockDesktop()
+ rejected := []string{
+ "",
+ " ",
+ "file:///C:/Windows/System32/cmd.exe",
+ `\\evil-host\share\payload.exe`,
+ "javascript:alert(1)",
+ "ms-msdt:/id",
+ "https://user:pass@example.com/path",
+ "https://example.com/has space",
+ "https://example.com/line\nbreak",
+ "http:///missing-host",
+ }
+ for _, raw := range rejected {
+ if err := desk.OpenExternalURL(raw); err == nil {
+ t.Errorf("OpenExternalURL(%q) succeeded, want rejection", raw)
+ }
+ }
+ allowed := []string{
+ "https://live.bilibili.com/12345",
+ "https://live.douyin.com/998877",
+ "http://127.0.0.1:8080/ok",
+ }
+ for _, raw := range allowed {
+ if err := desk.OpenExternalURL(raw); err != nil {
+ t.Errorf("OpenExternalURL(%q) failed: %v", raw, err)
+ }
+ }
+ if len(desk.Actions()) != len(allowed) {
+ t.Fatalf("expected %d recorded external URL actions, got %d", len(allowed), len(desk.Actions()))
+ }
+}
+
+func TestAvatarFetchRespectsPerSiteAuthGate(t *testing.T) {
+ var hits atomic.Int32
+ pngBytes := historyThumbnailPNG(t, 16, 16)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hits.Add(1)
+ w.Header().Set("Content-Type", "image/png")
+ _, _ = w.Write(pngBytes)
+ }))
+ defer srv.Close()
+
+ b, err := NewBackend(Options{
+ Locations: testLocations(t),
+ BilibiliOpts: bilibili.ClientOptions{AllowLocalhost: true, PacingInterval: -1},
+ DouyinOpts: douyin.ClientOptions{AllowLocalhost: true, MinInterval: -1, JitterMax: -1},
+ Desktop: NewMockDesktop(),
+ DisableBgWorkers: true,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Only Bilibili is logged in; Douyin is logged out.
+ seedBiliLogin(t, b)
+ if _, err := b.CreateSubscription("dy-creator", "", []subscription.AccountRef{
+ {Site: "douyin", UID: "sec_dy_1", Name: "DY", Face: srv.URL + "/avatar.png"},
+ }, subscription.SubRules{}); err != nil {
+ t.Fatal(err)
+ }
+ b.rememberAccountAvatar("douyin", "sec_dy_1", srv.URL+"/avatar.png")
+ if err := b.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if got := hits.Load(); got != 0 {
+ t.Fatalf("expected 0 avatar requests for logged-out Douyin site, got %d", got)
+ }
+}
+
+func TestEventPublishDoesNotHoldServiceOrQueueLocks(t *testing.T) {
+ clk := newFakeQueueClock(time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC))
+ b := newBatchTestBackend(t, clk)
+ defer b.Close()
+
+ var settingsEvents atomic.Int32
+ var queueEvents atomic.Int32
+ var lockHeldDuringSettings atomic.Bool
+
+ unsub := b.SubscribeEvents(func(ev Event) {
+ switch ev.Type {
+ case EventSettingsChanged:
+ settingsEvents.Add(1)
+ if !b.settingsMu.TryLock() {
+ lockHeldDuringSettings.Store(true)
+ } else {
+ b.settingsMu.Unlock()
+ }
+ _ = b.GetSettings()
+ case EventCacheQueueUpdated:
+ queueEvents.Add(1)
+ // Re-entering queue APIs synchronously inside the event callback must not deadlock.
+ _ = b.ListCacheQueue()
+ _, _ = b.FindCacheQueueTask("bilibili", "1001", "videos")
+ }
+ })
+ defer unsub()
+
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ cur := b.GetSettings()
+ cur.Download.MaxConcurrentTasks = 2
+ if _, err := b.UpdateSettings(cur); err != nil {
+ t.Errorf("UpdateSettings: %v", err)
+ return
+ }
+ pager := func(context.Context, string) ([]queueCandidate, string, bool, error) {
+ return nil, "", false, nil
+ }
+ task, err := b.enqueueCacheQueueWithPager(site.Bilibili, "videos", "1001", CacheQueueRequest{
+ Site: "bilibili", List: "videos", User: "1001", UserName: "UP",
+ }, []queueCandidate{{key: "bilibili:video:BV1TEST0001", uncacheable: true}}, pager)
+ if err != nil {
+ t.Errorf("enqueue: %v", err)
+ return
+ }
+ if _, err := b.PauseCacheQueue(task.ID); err != nil {
+ t.Errorf("PauseCacheQueue: %v", err)
+ return
+ }
+ if _, err := b.ResumeCacheQueue(task.ID); err != nil {
+ t.Errorf("ResumeCacheQueue: %v", err)
+ return
+ }
+ if _, err := b.CancelCacheQueue(task.ID); err != nil {
+ t.Errorf("CancelCacheQueue: %v", err)
+ return
+ }
+ if err := b.RemoveCacheQueue(task.ID); err != nil {
+ t.Errorf("RemoveCacheQueue: %v", err)
+ return
+ }
+ }()
+
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ t.Fatal("deadlock detected while publishing settings or cache-queue events")
+ }
+ if lockHeldDuringSettings.Load() {
+ t.Fatal("settingsMu was still held while publishing EventSettingsChanged")
+ }
+ if settingsEvents.Load() == 0 || queueEvents.Load() < 5 {
+ t.Fatalf("expected events observed, got settings=%d queue=%d", settingsEvents.Load(), queueEvents.Load())
+ }
+}
+
+func TestDouyinUncertainEmptyTriggersBackoffAndEmptyHasMoreAdvances(t *testing.T) {
+ // Part 1: Douyin UncertainEmpty from page 1 must return ErrKindRiskControl -> waiting_backoff, NOT completed.
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"status_code":0,"aweme_list":[],"has_more":0,"max_cursor":0}`))
+ }))
+ defer srv.Close()
+
+ clk := newFakeQueueClock(time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC))
+ b, err := NewBackend(Options{
+ Locations: testLocations(t),
+ DouyinOpts: douyin.ClientOptions{
+ AllowLocalhost: true,
+ MinInterval: -1,
+ JitterMax: -1,
+ Endpoints: douyin.Endpoints{
+ AwemePost: srv.URL + "/aweme/post",
+ },
+ },
+ Desktop: NewMockDesktop(),
+ DisableBgWorkers: true,
+ CacheQueueClock: clk,
+ CacheQueueRand: func(int) int { return 0 },
+ CacheQueuePacing: &CacheQueuePacing{
+ ItemMinDelay: time.Second,
+ ItemMaxDelay: time.Second,
+ LongRestMinItems: 50,
+ LongRestMaxItems: 50,
+ LongRestMinDelay: time.Second,
+ LongRestMaxDelay: time.Second,
+ BackoffCoolMinDelay: time.Minute,
+ BackoffCoolMaxDelay: time.Minute,
+ StartupMinDelay: time.Second,
+ StartupMaxDelay: time.Second,
+ },
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer b.Close()
+ seedDouyinLogin(t, b)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ b.queue.Start(ctx)
+
+ task, err := b.EnqueueCacheQueue(ctx, CacheQueueRequest{
+ Site: "douyin", List: "works", User: "MS4wLjABAAAA_synth_uncertain_01", UserName: "Creator",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ got := waitQueuePredicate(t, b, task.ID, "waiting_backoff on UncertainEmpty", func(q CacheQueueTask) bool {
+ return q.Status == CacheQueueWaitingBackoff || q.Status == CacheQueueCompleted
+ })
+ if got.Status != CacheQueueWaitingBackoff {
+ t.Fatalf("expected UncertainEmpty page to trigger waiting_backoff, got %q (%s)", got.Status, got.StopReason)
+ }
+
+ // Part 2: Non-empty next page behind an empty filtered page with HasMore=true must advance cursor, not complete.
+ var pageCalls atomic.Int32
+ var cachedPage2 atomic.Bool
+ pager := func(_ context.Context, cursor string) ([]queueCandidate, string, bool, error) {
+ n := pageCalls.Add(1)
+ if n == 1 && cursor == "" {
+ return nil, "cursor_page_2", true, nil
+ }
+ if cursor == "cursor_page_2" {
+ return []queueCandidate{{
+ key: "bilibili:video:BV1PAGE20001",
+ title: "Page 2 video",
+ enqueue: func(context.Context) (queueEnqueued, error) {
+ cachedPage2.Store(true)
+ return queueEnqueued{itemKey: "bilibili:video:BV1PAGE20001", title: "Page 2 video"}, nil
+ },
+ }}, "", false, nil
+ }
+ return nil, "", false, nil
+ }
+ seedBiliLogin(t, b)
+ t2, err := b.enqueueCacheQueueWithPager(site.Bilibili, "videos", "2002", CacheQueueRequest{
+ Site: "bilibili", List: "videos", User: "2002", UserName: "BiliUP",
+ }, nil, pager)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got2 := waitQueuePredicate(t, b, t2.ID, "complete after advancing empty page", func(q CacheQueueTask) bool {
+ return q.Status == CacheQueueCompleted
+ })
+ if !cachedPage2.Load() || got2.CachedCount != 1 {
+ t.Fatalf("expected queue to advance past empty page and cache page 2, got cached=%d pageCalls=%d", got2.CachedCount, pageCalls.Load())
+ }
+}
+
+func TestDouyinLiveIncidentsPreservedAndStoppedPartNotProbed(t *testing.T) {
+ itemDir := t.TempDir()
+ partFile := filepath.Join(itemDir, "part-001.flv.part")
+ if err := os.WriteFile(partFile, []byte("synthetic-flv-bytes"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ incident := library.LiveIncident{Kind: library.LiveIncidentReconnect, At: "2026-11-20T00:00:00Z", Count: 2}
+
+ stopped := mapRoomToAccountState(live.RoomState{
+ Site: "douyin",
+ AccountUID: "sec_1",
+ RoomIDStr: "777",
+ Recording: false,
+ RecordItemDir: itemDir,
+ Incidents: []library.LiveIncident{incident},
+ })
+ if len(stopped.Incidents) != 1 || stopped.Incidents[0].Count != 2 {
+ t.Fatalf("expected Douyin incidents copied, got %+v", stopped.Incidents)
+ }
+ if stopped.RecordPartPath != "" {
+ t.Fatalf("stopped room must not probe disk for .part, got %q", stopped.RecordPartPath)
+ }
+
+ recording := mapRoomToAccountState(live.RoomState{
+ Site: "douyin",
+ AccountUID: "sec_1",
+ RoomIDStr: "777",
+ Recording: true,
+ RecordItemDir: itemDir,
+ Incidents: []library.LiveIncident{incident},
+ })
+ if recording.RecordPartPath != partFile {
+ t.Fatalf("active recording expected RecordPartPath=%q, got %q", partFile, recording.RecordPartPath)
+ }
+}
+
+func TestCacheQueueSurvivesAppClosedDownloadWithoutExitingLoop(t *testing.T) {
+ clk := newFakeQueueClock(time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC))
+ b := newBatchTestBackend(t, clk)
+ defer b.Close()
+
+ now := clk.Now().UTC().Format(time.RFC3339)
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ b.queue.Start(ctx)
+
+ // First task enqueues a download that immediately becomes paused with app_closed.
+ t1, err := b.enqueueCacheQueueWithPager(site.Bilibili, "videos", "3001", CacheQueueRequest{
+ Site: "bilibili", List: "videos", User: "3001", UserName: "UP1",
+ }, []queueCandidate{{
+ key: "bilibili:video:BV1CLOSED01",
+ enqueue: func(context.Context) (queueEnqueued, error) {
+ if _, err := b.db.Exec(
+ `INSERT INTO download_tasks (task_id, site, kind, target_id, item_key, status, pause_reason, created_at, updated_at)
+ VALUES ('dl-app-closed', 'bilibili', 'video', 'BV1CLOSED01', 'bilibili:video:BV1CLOSED01', 'paused', 'app_closed', ?, ?)`,
+ now, now,
+ ); err != nil {
+ return queueEnqueued{}, err
+ }
+ return queueEnqueued{taskIDs: []string{"dl-app-closed"}, itemKey: "bilibili:video:BV1CLOSED01", title: "Closed"}, nil
+ },
+ }}, func(context.Context, string) ([]queueCandidate, string, bool, error) { return nil, "", false, nil })
+ if err != nil {
+ t.Fatal(err)
+ }
+ got1 := waitQueuePredicate(t, b, t1.ID, "paused with app_closed", func(q CacheQueueTask) bool {
+ return q.Status == CacheQueuePaused && q.PauseReason == "app_closed"
+ })
+ if got1.Status != CacheQueuePaused {
+ t.Fatalf("t1 status = %q, want paused", got1.Status)
+ }
+
+ // Second task on the SAME site must still execute — proving runSiteLoop did not exit.
+ t2, err := b.enqueueCacheQueueWithPager(site.Bilibili, "videos", "3002", CacheQueueRequest{
+ Site: "bilibili", List: "videos", User: "3002", UserName: "UP2",
+ }, []queueCandidate{{
+ key: "bilibili:video:BV1NEXT0002",
+ enqueue: func(context.Context) (queueEnqueued, error) {
+ return queueEnqueued{itemKey: "bilibili:video:BV1NEXT0002", title: "Next"}, nil
+ },
+ }}, func(context.Context, string) ([]queueCandidate, string, bool, error) { return nil, "", false, nil })
+ if err != nil {
+ t.Fatal(err)
+ }
+ got2 := waitQueuePredicate(t, b, t2.ID, "completed while loop stayed alive", func(q CacheQueueTask) bool {
+ return q.Status == CacheQueueCompleted
+ })
+ if got2.CachedCount != 1 {
+ t.Fatalf("expected second queue task to complete with CachedCount=1, got %+v", got2)
+ }
+}
+
+func TestMultiPartVideoPersistsPendingPagesAcrossRestart(t *testing.T) {
+ loc := testLocations(t)
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/x/web-interface/nav", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": 0,
+ "data": map[string]any{
+ "isLogin": true,
+ "mid": 1,
+ "uname": "bili",
+ "wbi_img": map[string]any{
+ "img_url": "https://i0.hdslb.com/bfs/wbi/7cd084941338484aae1ad9425b84077c.png",
+ "sub_url": "https://i0.hdslb.com/bfs/wbi/4932caff0ff746eab6f01bf08b70ac45.png",
+ },
+ },
+ })
+ })
+ viewHandler := func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": 0,
+ "data": map[string]any{
+ "bvid": "BV1MULTI0001",
+ "aid": 1001,
+ "title": "Two Part Video",
+ "owner": map[string]any{"mid": 77, "name": "UP77"},
+ "pages": []map[string]any{
+ {"cid": 101, "page": 1, "part": "P1", "duration": 10},
+ {"cid": 102, "page": 2, "part": "P2", "duration": 10},
+ },
+ },
+ })
+ }
+ mux.HandleFunc("/x/web-interface/view", viewHandler)
+ mux.HandleFunc("/x/web-interface/wbi/view", viewHandler)
+ mux.HandleFunc("/x/player/wbi/playurl", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{"code": -404, "message": "not used"})
+ })
+ srv := httptest.NewServer(mux)
+ defer srv.Close()
+
+ clk := newFakeQueueClock(time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC))
+ pacing := &CacheQueuePacing{
+ ItemMinDelay: time.Second,
+ ItemMaxDelay: time.Second,
+ LongRestMinItems: 50,
+ LongRestMaxItems: 50,
+ LongRestMinDelay: time.Second,
+ LongRestMaxDelay: time.Second,
+ BackoffCoolMinDelay: time.Minute,
+ BackoffCoolMaxDelay: time.Minute,
+ StartupMinDelay: time.Second,
+ StartupMaxDelay: time.Second,
+ }
+ openB := func() *Backend {
+ b, err := NewBackend(Options{
+ Locations: loc,
+ BilibiliOpts: bilibili.ClientOptions{
+ AllowLocalhost: true,
+ PacingInterval: -1,
+ Endpoints: bilibili.Endpoints{
+ APIBase: srv.URL,
+ WWWBase: srv.URL,
+ },
+ },
+ Desktop: NewMockDesktop(),
+ DisableBgWorkers: true,
+ CacheQueueClock: clk,
+ CacheQueueRand: func(int) int { return 0 },
+ CacheQueuePacing: pacing,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+ }
+
+ b1 := openB()
+ seedBiliLogin(t, b1)
+ // Seed a download task representing P1 completed, and persist a queue record with ActivePendingPages=[2].
+ now := clk.Now().UTC().Format(time.RFC3339)
+ if _, err := b1.db.Exec(
+ `INSERT INTO download_tasks (task_id, site, kind, target_id, item_key, status, created_at, updated_at)
+ VALUES ('dl-p1', 'bilibili', 'video', 'BV1MULTI0001', 'bilibili:video:BV1MULTI0001', 'completed', ?, ?)`,
+ now, now,
+ ); err != nil {
+ t.Fatal(err)
+ }
+
+ b1.queue.mu.Lock()
+ b1.queue.tasks = append(b1.queue.tasks, &cacheQueueEntry{
+ rec: cacheQueueRecord{
+ ID: "cq_multipart_restart",
+ Site: "bilibili",
+ User: "77",
+ UserName: "UP77",
+ List: "videos",
+ HasMore: false,
+ ActiveDownloadIDs: []string{"dl-p1"},
+ ActivePendingPages: []int{2},
+ ActiveItemKey: "bilibili:video:BV1MULTI0001",
+ ActiveTitle: "Two Part Video",
+ Status: CacheQueueRunning,
+ CreatedAt: now,
+ UpdatedAt: now,
+ },
+ rt: cacheQueueRuntime{seenKeys: map[string]bool{}},
+ })
+ if err := b1.queue.saveLocked(); err != nil {
+ t.Fatal(err)
+ }
+ b1.queue.mu.Unlock()
+ if err := b1.Close(); err != nil {
+ t.Fatal(err)
+ }
+
+ // Verify activePendingPages survived serialization to cache-queue.json.
+ raw, err := os.ReadFile(filepath.Join(loc.DataDir, cacheQueueFileName))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var persisted cacheQueueFile
+ if err := json.Unmarshal(raw, &persisted); err != nil || len(persisted.Tasks) != 1 || len(persisted.Tasks[0].ActivePendingPages) != 1 || persisted.Tasks[0].ActivePendingPages[0] != 2 {
+ t.Fatalf("expected activePendingPages=[2] persisted in cache-queue.json, got err=%v tasks=%+v", err, persisted.Tasks)
+ }
+
+ // Restart into a brand-new Backend (in-memory nextPartEnqueuers is empty).
+ b2 := openB()
+ defer b2.Close()
+
+ b2.queue.mu.Lock()
+ if len(b2.queue.tasks) != 1 || len(b2.queue.tasks[0].rec.ActivePendingPages) != 1 || b2.queue.tasks[0].rec.ActivePendingPages[0] != 2 {
+ t.Fatalf("expected ActivePendingPages=[2] after restart, got %+v", b2.queue.tasks)
+ }
+ b2.queue.mu.Unlock()
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ b2.queue.Start(ctx)
+ clk.WaitForPendingTimer(t, 2*time.Second)
+ clk.Advance(2 * time.Second)
+
+ // Wait until b2 processes P1 completion and enqueues P2 (creating a new download task for BV1MULTI0001).
+ deadline := time.Now().Add(3 * time.Second)
+ var sawP2Task bool
+ for time.Now().Before(deadline) {
+ tasks, _ := b2.ListDownloadTasks()
+ for _, dt := range tasks {
+ if dt.TaskID != "dl-p1" && dt.TargetID == "BV1MULTI0001" {
+ sawP2Task = true
+ break
+ }
+ }
+ if sawP2Task {
+ break
+ }
+ time.Sleep(15 * time.Millisecond)
+ }
+ if !sawP2Task {
+ t.Fatal("expected restarted queue worker to reconstruct and enqueue page 2")
+ }
+}
+
+func TestRemoteProfileIsolationAndAllowMovedFiles(t *testing.T) {
+ var hits atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hits.Add(1)
+ w.WriteHeader(http.StatusInternalServerError)
+ }))
+ defer srv.Close()
+
+ b, err := NewBackend(Options{
+ Locations: testLocations(t),
+ Profile: ProfileRemote,
+ BilibiliOpts: bilibili.ClientOptions{AllowLocalhost: true, PacingInterval: -1},
+ DouyinOpts: douyin.ClientOptions{AllowLocalhost: true, MinInterval: -1, JitterMax: -1, Endpoints: douyin.Endpoints{ProfileOther: srv.URL + "/profile"}},
+ Desktop: NewMockDesktop(),
+ DisableBgWorkers: false,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer b.Close()
+
+ if !b.LibraryStore().AllowMovedFiles() {
+ t.Fatal("expected ProfileRemote to enable libStore.AllowMovedFiles()")
+ }
+ b.queue.mu.Lock()
+ queueStarted := b.queue.started
+ b.queue.mu.Unlock()
+ if queueStarted {
+ t.Fatal("ProfileRemote must never start cacheQueueManager background workers")
+ }
+
+ seedDouyinLogin(t, b)
+ if _, err := b.subs.Create("creator", "", []subscription.AccountRef{{Site: "douyin", UID: "sec_fc"}}, subscription.SubRules{FullCache: true}); err != nil {
+ t.Fatal(err)
+ }
+ if ids := b.startDueFullCacheSweeps(context.Background(), time.Now()); len(ids) != 0 {
+ t.Fatalf("ProfileRemote startDueFullCacheSweeps started %v, want nil", ids)
+ }
+ if hits.Load() != 0 {
+ t.Fatalf("ProfileRemote full cache sweep sent %d network requests, want 0", hits.Load())
+ }
+}
+
+func TestPauseAllActiveWorkPreservesAuthenticatedSite(t *testing.T) {
+ clk := newFakeQueueClock(time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC))
+ b := newBatchTestBackend(t, clk)
+ defer b.Close()
+ seedDouyinLogin(t, b)
+
+ now := clk.Now().UTC().Format(time.RFC3339)
+ for _, row := range []struct{ id, site, target string }{
+ {"dl-bili", "bilibili", "BV1KEEP0001"},
+ {"dl-dy", "douyin", "735000001"},
+ } {
+ if _, err := b.db.Exec(
+ `INSERT INTO download_tasks (task_id, site, kind, target_id, status, created_at, updated_at)
+ VALUES (?, ?, 'video', ?, 'queued', ?, ?)`,
+ row.id, row.site, row.target, now, now,
+ ); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ pager := func(context.Context, string) ([]queueCandidate, string, bool, error) { return nil, "", false, nil }
+ qBili, err := b.enqueueCacheQueueWithPager(site.Bilibili, "videos", "100", CacheQueueRequest{
+ Site: "bilibili", List: "videos", User: "100",
+ }, nil, pager)
+ if err != nil {
+ t.Fatal(err)
+ }
+ qDy, err := b.enqueueCacheQueueWithPager(site.Douyin, "works", "sec_100", CacheQueueRequest{
+ Site: "douyin", List: "works", User: "sec_100",
+ }, nil, pager)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // Expire ONLY Douyin; Bilibili remains logged in.
+ if _, err := b.douyinCred.MarkState("expired", "expired"); err != nil {
+ t.Fatal(err)
+ }
+ b.PauseAllActiveWork()
+
+ biliDL, ok, err := b.TaskDetail("dl-bili")
+ if err != nil || !ok || biliDL.Task.Status != "queued" {
+ t.Fatalf("expected Bilibili download untouched (queued), got %+v ok=%v err=%v", biliDL.Task, ok, err)
+ }
+ dyDL, ok, err := b.TaskDetail("dl-dy")
+ if err != nil || !ok || dyDL.Task.Status != "paused" || dyDL.Task.PauseReason != "auth_required" {
+ t.Fatalf("expected Douyin download paused (auth_required), got %+v ok=%v err=%v", dyDL.Task, ok, err)
+ }
+ qList := b.ListCacheQueue()
+ for _, q := range qList {
+ if q.ID == qBili.ID && q.Status != CacheQueueQueued {
+ t.Fatalf("expected Bilibili cache queue untouched (queued), got %+v", q)
+ }
+ if q.ID == qDy.ID && (q.Status != CacheQueuePaused || q.PauseReason != "auth_required") {
+ t.Fatalf("expected Douyin cache queue paused (auth_required), got %+v", q)
+ }
+ }
+}
+
+func TestRemoteSyncStateConcurrencyAndServerStatusWhenLoggedOut(t *testing.T) {
+ b, err := NewBackend(Options{
+ Locations: testLocations(t),
+ Profile: ProfileRemote,
+ Desktop: NewMockDesktop(),
+ DisableBgWorkers: true,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer b.Close()
+
+ if _, err := b.subs.Create("CreatorA", "", []subscription.AccountRef{{Site: "bilibili", UID: "42", Name: "UP42"}}, subscription.SubRules{}); err != nil {
+ t.Fatal(err)
+ }
+ // Neither site is logged in: ServerStatus must STILL populate Checks from local subscriptions.
+ st := b.ServerStatus()
+ if len(st.Checks) != 1 || st.Checks[0].UID != "42" {
+ t.Fatalf("expected ServerStatus().Checks populated while logged out, got %+v", st.Checks)
+ }
+
+ // Concurrent syncState updates must not clobber each other's fields.
+ var wg sync.WaitGroup
+ wg.Add(2)
+ go func() {
+ defer wg.Done()
+ for i := 0; i < 20; i++ {
+ _, _ = b.mutateSyncState(func(s *syncState) {
+ s.Hash = fmt.Sprintf("hash-%d", i)
+ })
+ }
+ }()
+ go func() {
+ defer wg.Done()
+ for i := 0; i < 20; i++ {
+ _, _ = b.mutateSyncState(func(s *syncState) {
+ if s.CookieSyncedAt == nil {
+ s.CookieSyncedAt = map[string]string{}
+ }
+ s.CookieSyncedAt["bilibili"] = fmt.Sprintf("2026-11-20T00:00:%02dZ", i)
+ })
+ }
+ }()
+ wg.Wait()
+
+ final := b.loadSyncState()
+ if final.Hash != "hash-19" || final.CookieSyncedAt["bilibili"] != "2026-11-20T00:00:19Z" {
+ t.Fatalf("lost concurrent syncState update: %+v", final)
+ }
+}
+
+func TestConnectRemotePreservesOldTokenOnFailureAndCloseClosesClient(t *testing.T) {
+ const goodToken = "SYNTH_GOOD_TOKEN_AAA_1234567890_EXTRA"
+ srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("Authorization") != "Bearer "+goodToken {
+ w.WriteHeader(http.StatusUnauthorized)
+ return
+ }
+ _ = json.NewEncoder(w).Encode(remote.Status{Version: "0.1.0", Protocol: remote.ProtocolVersion})
+ }))
+ defer srv.Close()
+ fp := remote.Fingerprint(srv.Certificate().Raw)
+
+ b, err := NewBackend(Options{
+ Locations: testLocations(t),
+ Desktop: NewMockDesktop(),
+ DisableBgWorkers: true,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer b.Close()
+
+ ctx := context.Background()
+ if _, err := b.ConnectRemote(ctx, RemoteConnectInput{URL: srv.URL, Token: goodToken, Fingerprint: fp}); err != nil {
+ t.Fatalf("initial ConnectRemote: %v", err)
+ }
+ // Attempting to connect to a broken address must fail AND leave the previous connection/token intact.
+ if _, err := b.ConnectRemote(ctx, RemoteConnectInput{URL: "https://127.0.0.1:1", Token: "SYNTH_BAD_TOKEN_1234567890_EXTRA_99", Fingerprint: fp}); err == nil {
+ t.Fatal("expected ConnectRemote to invalid address to fail")
+ }
+ if _, err := b.RemoteStatus(ctx); err != nil {
+ t.Fatalf("previous remote connection broken after failed ConnectRemote: %v", err)
+ }
+ if err := b.Close(); err != nil {
+ t.Fatal(err)
+ }
+ b.remote.mu.Lock()
+ c := b.remote.client
+ b.remote.mu.Unlock()
+ if c != nil {
+ t.Fatal("expected Backend.Close to close and clear remote client")
+ }
+}
+
+func TestLogRedactionCoversRemoteTokensCSRFAndQRCodeKey(t *testing.T) {
+ b := &Backend{
+ logPath: filepath.Join(t.TempDir(), "trace.log"),
+ remote: &remoteLink{token: "SYNTH_ACTIVE_RAW_REMOTE_TOKEN_999"},
+ }
+ sentinels := []struct{ line, secret string }{
+ {"api err csrf=SYNTH_CSRF_SECRET_1", "SYNTH_CSRF_SECRET_1"},
+ {"qr poll qrcode_key=SYNTH_QR_SECRET_2", "SYNTH_QR_SECRET_2"},
+ {"auth token=SYNTH_TOK_SECRET_3", "SYNTH_TOK_SECRET_3"},
+ {"header Bearer SYNTH_BEARER_SECRET_4", "SYNTH_BEARER_SECRET_4"},
+ {"remote trace-remote:1:SYNTH_REMOTE_SECRET_5 failed", "SYNTH_REMOTE_SECRET_5"},
+ {"raw leak SYNTH_ACTIVE_RAW_REMOTE_TOKEN_999 here", "SYNTH_ACTIVE_RAW_REMOTE_TOKEN_999"},
+ }
+ for _, tc := range sentinels {
+ b.logInfo(tc.line)
+ }
+ raw, err := os.ReadFile(b.logPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ text := string(raw)
+ for _, tc := range sentinels {
+ if strings.Contains(text, tc.secret) {
+ t.Fatalf("trace.log leaked secret %q from line %q", tc.secret, tc.line)
+ }
+ }
+ lines, err := b.RecentLogs(500)
+ if err != nil {
+ t.Fatal(err)
+ }
+ joined := strings.Join(lines, "\n")
+ for _, tc := range sentinels {
+ if strings.Contains(joined, tc.secret) {
+ t.Fatalf("RecentLogs leaked secret %q", tc.secret)
+ }
+ }
+}
+
+func TestTransferJobsConcurrencyCleanupAndCloseSafety(t *testing.T) {
+ b, err := NewBackend(Options{
+ Locations: testLocations(t),
+ Desktop: NewMockDesktop(),
+ DisableBgWorkers: true,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ srcDir := t.TempDir()
+ job, err := b.StartImportScan(srcDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if job.ID == "" || job.Status != TransferScanning {
+ t.Fatalf("unexpected initial scan job: %+v", job)
+ }
+
+ // Poll concurrently while scan finishes to exercise transfer mutex & cloning.
+ deadline := time.Now().Add(3 * time.Second)
+ var ready bool
+ for time.Now().Before(deadline) {
+ for _, j := range b.TransferJobs() {
+ if j.ID == job.ID && j.Status == TransferReady {
+ ready = true
+ break
+ }
+ }
+ if ready {
+ break
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ if !ready {
+ t.Fatal("scan job did not reach TransferReady")
+ }
+
+ runJob, err := b.StartImport(job.ID, transfer.Choices{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if runJob.FinishedAt != "" {
+ t.Fatalf("StartImport must clear previous scan FinishedAt, got %q", runJob.FinishedAt)
+ }
+
+ deadline = time.Now().Add(3 * time.Second)
+ var done bool
+ for time.Now().Before(deadline) {
+ for _, j := range b.TransferJobs() {
+ if j.ID == job.ID && j.Status == TransferDone {
+ done = true
+ break
+ }
+ }
+ if done {
+ break
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ if !done {
+ t.Fatal("import job did not finish")
+ }
+ if _, ok := b.ImportPlan(job.ID); ok {
+ t.Fatal("expected scanned plan to be cleared after import finished")
+ }
+
+ // Closing backend must safely reject new background transfer jobs without panicking on WaitGroup.
+ if err := b.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := b.StartImportScan(srcDir); err == nil {
+ t.Fatal("expected StartImportScan after Close to return an error")
+ }
+}
+
+func TestLiveStatusesAndStartRecordingFilterRequestedBilibiliUID(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("/room/v1/Room/get_status_info_by_uids", func(w http.ResponseWriter, r *http.Request) {
+ // Return room for uid 100 ONLY; uid 200 has no live room.
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": 0,
+ "data": map[string]any{
+ "100": map[string]any{
+ "uid": 100, "room_id": 1001, "live_status": 1, "uname": "Streamer100", "title": "Live100",
+ },
+ },
+ })
+ })
+ srv := httptest.NewServer(mux)
+ defer srv.Close()
+
+ b, err := NewBackend(Options{
+ Locations: testLocations(t),
+ BilibiliOpts: bilibili.ClientOptions{
+ AllowLocalhost: true,
+ PacingInterval: -1,
+ Endpoints: bilibili.Endpoints{
+ LiveAPIBase: srv.URL,
+ },
+ },
+ Desktop: NewMockDesktop(),
+ DisableBgWorkers: true,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer b.Close()
+ seedBiliLogin(t, b)
+ ctx := context.Background()
+ // Warm cache with uid 100 (room 1001).
+ if _, err := b.LiveStatus(ctx, []int64{100}); err != nil {
+ t.Fatal(err)
+ }
+ // Requesting status for uid 200 must NOT return uid 100.
+ got, err := b.LiveStatuses(ctx, []string{"bilibili:200"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, st := range got {
+ if st.UID != "200" {
+ t.Fatalf("LiveStatuses(bilibili:200) leaked unrelated room: %+v", st)
+ }
+ }
+ // Starting recording for uid 200 (no room) must fail with ErrKindUnavailable, NOT hijack room 1001.
+ _, err = b.StartLiveRecordingByAccount(ctx, "bilibili:200")
+ if !site.IsKind(err, site.ErrKindUnavailable) {
+ t.Fatalf("StartLiveRecordingByAccount(bilibili:200) err = %v, want ErrKindUnavailable", err)
+ }
+}
+
+func TestAccountReplacementAndAuthExpiryDoNotDeadlockWithActiveLiveRecording(t *testing.T) {
+ // Custom fake Bilibili server whose /nav echoes DedeUserID from Cookie so we can switch between two accounts.
+ mux := http.NewServeMux()
+ mux.HandleFunc("/x/web-interface/nav", func(w http.ResponseWriter, r *http.Request) {
+ mid := int64(10001)
+ uname := "AcctA"
+ if strings.Contains(r.Header.Get("Cookie"), "DedeUserID=10002") {
+ mid = 10002
+ uname = "AcctB"
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": 0,
+ "data": map[string]any{"isLogin": true, "mid": mid, "uname": uname},
+ })
+ })
+ var srvURL string
+ mux.HandleFunc("/room/v1/Room/room_init", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": 0,
+ "data": map[string]any{"room_id": 223344, "short_id": 223, "uid": 8888, "live_status": 1, "live_time": 1710000000},
+ })
+ })
+ mux.HandleFunc("/room/v1/Room/get_status_info_by_uids", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": 0,
+ "data": map[string]any{
+ "8888": map[string]any{"uid": 8888, "room_id": 223344, "uname": "Streamer", "title": "LiveRoom", "live_status": 1, "live_time": 1710000000},
+ },
+ })
+ })
+ mux.HandleFunc("/room/v1/Room/get_info", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": 0,
+ "data": map[string]any{"room_id": 223344, "uid": 8888, "live_status": 1, "title": "LiveRoom"},
+ })
+ })
+ mux.HandleFunc("/xlive/web-room/v2/index/getRoomPlayInfo", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "code": 0,
+ "data": map[string]any{
+ "room_id": 223344,
+ "uid": 8888,
+ "live_status": 1,
+ "playurl_info": map[string]any{
+ "playurl": map[string]any{
+ "g_qn_desc": []map[string]any{{"qn": 10000, "desc": "原画"}},
+ "stream": []map[string]any{{
+ "protocol_name": "http_hls",
+ "format": []map[string]any{{
+ "format_name": "fmp4",
+ "codec": []map[string]any{{
+ "codec_name": "avc",
+ "current_qn": 10000,
+ "accept_qn": []int{10000},
+ "base_url": "/live/bili.m3u8",
+ "url_info": []map[string]any{{"host": srvURL, "extra": ""}},
+ }},
+ }},
+ }},
+ },
+ },
+ },
+ })
+ })
+ mux.HandleFunc("/live/bili.m3u8", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/vnd.apple.mpegurl")
+ w.WriteHeader(http.StatusOK)
+ if flusher, ok := w.(http.Flusher); ok {
+ flusher.Flush()
+ }
+ <-r.Context().Done()
+ })
+ srv := httptest.NewServer(mux)
+ srvURL = srv.URL
+ defer srv.Close()
+
+ b, err := NewBackend(Options{
+ Locations: testLocations(t),
+ BilibiliOpts: bilibili.ClientOptions{
+ AllowLocalhost: true,
+ PacingInterval: -1,
+ Endpoints: bilibili.Endpoints{
+ APIBase: srv.URL,
+ LiveAPIBase: srv.URL,
+ LiveWebBase: srv.URL,
+ },
+ },
+ Desktop: NewMockDesktop(),
+ DisableBgWorkers: true,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer b.Close()
+
+ ctx := context.Background()
+ if _, err := b.ImportCookie(ctx, "SESSDATA=SYNTH_SESS_A; bili_jct=SYNTH_JCT_A; DedeUserID=10001", ""); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := b.StartLiveRecording(ctx, 223344); err != nil {
+ t.Fatal(err)
+ }
+
+ // Replace with another Bilibili account while recording is active: SetAccountReplacingHandler
+ // runs while bilibili.Client holds sequenceMu.Lock() and must not deadlock waiting on StopForSite.
+ done := make(chan error, 1)
+ go func() {
+ _, err := b.ImportCookie(ctx, "SESSDATA=SYNTH_SESS_B; bili_jct=SYNTH_JCT_B; DedeUserID=10002", "")
+ done <- err
+ }()
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatalf("ImportCookie account replacement failed: %v", err)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("ImportCookie deadlocked with active live recording")
+ }
+
+ // Wait briefly for the async live stop to finish.
+ deadline := time.Now().Add(2 * time.Second)
+ for {
+ _, recs := b.ActiveWork()
+ if recs == 0 {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("expected active recording stopped after account replacement, still %d", recs)
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+func TestPrunePreviewDirEvictsOldestFilesAndKeepsLatest(t *testing.T) {
+ dir := t.TempDir()
+ base := time.Date(2026, 11, 20, 10, 0, 0, 0, time.UTC)
+ var paths []string
+ for i := 0; i < 6; i++ {
+ p := filepath.Join(dir, fmt.Sprintf("preview_%02d.mp4", i))
+ if err := os.WriteFile(p, make([]byte, 100), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ mt := base.Add(time.Duration(i) * time.Minute)
+ _ = os.Chtimes(p, mt, mt)
+ paths = append(paths, p)
+ }
+ prunePreviewDir(dir, paths[5], 350, 3)
+
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(entries) != 3 {
+ t.Fatalf("expected 3 preview files remaining, got %d", len(entries))
+ }
+ if _, err := os.Stat(paths[5]); err != nil {
+ t.Fatalf("newest keepPath was removed: %v", err)
+ }
+ if _, err := os.Stat(paths[0]); !os.IsNotExist(err) {
+ t.Fatalf("oldest preview file was not pruned")
+ }
+}
+
+func TestCheckAccountNormalizesSiteID(t *testing.T) {
+ b, err := NewBackend(Options{
+ Locations: testLocations(t),
+ Desktop: NewMockDesktop(),
+ DisableBgWorkers: true,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer b.Close()
+ seedBiliLogin(t, b)
+
+ _, err = b.CheckAccount(context.Background(), "sub-1", " DOUYIN ", "sec_1")
+ assertSiteAuthRequired(t, err, site.Douyin)
+}
+
+func TestMigrateCacheDirRejectsWhenLiveRecordingActive(t *testing.T) {
+ h := newDualSiteTestHarness(t)
+ ctx := context.Background()
+ if _, err := h.backend.ImportCookie(ctx, "SESSDATA=SYNTH_SESS_A; bili_jct=SYNTH_JCT_A; DedeUserID=778899", ""); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := h.backend.StartLiveRecording(ctx, 223344); err != nil {
+ t.Fatal(err)
+ }
+ _, err := h.backend.MigrateCacheDir(filepath.Join(t.TempDir(), "new-cache"), true)
+ if !site.IsKind(err, site.ErrKindBadRequest) {
+ t.Fatalf("expected ErrKindBadRequest migrating cache during active live recording, got %v", err)
+ }
+}
+
+func TestDiagnosticsReportsMultiSiteBackoff(t *testing.T) {
+ b, err := NewBackend(Options{
+ Locations: testLocations(t),
+ Desktop: NewMockDesktop(),
+ DisableBgWorkers: true,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer b.Close()
+
+ b.subs.RecordSiteAutomaticStop(string(site.Douyin), site.ErrKindRiskControl)
+ diag := b.DiagnosticsSnapshot()
+ if !strings.Contains(diag.SubscriptionCheckStatus, "风控退避中") || !strings.Contains(diag.SubscriptionCheckStatus, "抖音") {
+ t.Fatalf("expected DiagnosticsSnapshot to surface Douyin backoff, got %q", diag.SubscriptionCheckStatus)
+ }
+}
diff --git a/internal/service/interfaces.go b/internal/service/interfaces.go
new file mode 100644
index 0000000..1a3624c
--- /dev/null
+++ b/internal/service/interfaces.go
@@ -0,0 +1,321 @@
+package service
+
+import (
+ "context"
+ "io"
+
+ "github.com/chialecode/trace/internal/appdirs"
+ "github.com/chialecode/trace/internal/credential"
+ "github.com/chialecode/trace/internal/download"
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/live"
+ "github.com/chialecode/trace/internal/settings"
+ "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/storage"
+ "github.com/chialecode/trace/internal/subscription"
+ "github.com/chialecode/trace/internal/uistate"
+ "github.com/chialecode/trace/internal/update"
+)
+
+// Options configures the TRACE Backend service.
+type Options struct {
+ Locations appdirs.Locations
+ BilibiliOpts bilibili.ClientOptions
+ DouyinOpts douyin.ClientOptions
+ Desktop Desktop
+ DisableBgWorkers bool
+ CacheQueueClock CacheQueueClock
+ CacheQueueRand CacheQueueRand
+ CacheQueuePacing *CacheQueuePacing
+ InstalledDevVersion func() string
+ // Profile is ProfileDesktop (the default) or ProfileRemote, the headless
+ // trace-server (docs/design/remote.md §2, §4).
+ Profile Profile
+ // NodeName names this installation in item.json's cachedBy; the
+ // computer's name when empty.
+ NodeName string
+ // LogMirror also receives every line written to trace.log (the remote
+ // writes them to standard error for journald).
+ LogMirror io.Writer
+}
+
+// OpenLinkResult contains the resolved target and fetched detail payload for UI navigation.
+type OpenLinkResult struct {
+ Site string `json:"site,omitempty"`
+ SiteTarget *site.ResolveTarget `json:"siteTarget,omitempty"`
+ Target bilibili.ResolveTarget `json:"target"`
+ Video *bilibili.VideoDetail `json:"video,omitempty"`
+ User *bilibili.UserSpace `json:"user,omitempty"`
+ UserVideos *bilibili.UserVideosPage `json:"userVideos,omitempty"`
+ UserDynamicsError string `json:"userDynamicsError,omitempty"`
+ UserVideosError string `json:"userVideosError,omitempty"`
+ UserDynamics *bilibili.UserDynamicsPage `json:"userDynamics,omitempty"`
+ Dynamic *bilibili.DynamicItem `json:"dynamic,omitempty"`
+ LiveRoom *live.RoomState `json:"liveRoom,omitempty"`
+ DouyinWork *DouyinWorkView `json:"douyinWork,omitempty"`
+ DouyinUser *DouyinUserView `json:"douyinUser,omitempty"`
+ DouyinUserWorks *DouyinUserWorksPage `json:"douyinUserWorks,omitempty"`
+ DouyinUserWorksError string `json:"douyinUserWorksError,omitempty"`
+ DouyinLive *DouyinLiveView `json:"douyinLive,omitempty"`
+ CachedItem *library.ItemMetadata `json:"cachedItem,omitempty"`
+ // HistoryThumbs names the images of the recent-parse entry. OpenLink
+ // records the entry without waiting for them; FetchHistoryThumbs adds
+ // them afterwards, so opening a link waits only for its metadata.
+ HistoryThumbs *HistoryThumbJob `json:"-"`
+}
+
+// HistoryThumbJob is the deferred thumbnail work of one recent-parse entry.
+type HistoryThumbJob struct {
+ Site string
+ Kind string
+ ID string
+ AvatarURL string
+ CoverURL string
+}
+
+// Diagnostics provides a sanitized runtime status snapshot for the Settings/Diagnostics view and smoke tests.
+type Diagnostics struct {
+ Version string `json:"version"`
+ Commit string `json:"commit,omitempty"`
+ BuildTime string `json:"buildTime,omitempty"`
+ AppName string `json:"appName"`
+ DisplayName string `json:"displayName"`
+ Channel string `json:"channel"`
+ Mode string `json:"mode"`
+ DataDir string `json:"dataDir"`
+ CacheDir string `json:"cacheDir"`
+ LogsDir string `json:"logsDir"`
+ Account credential.Status `json:"account"`
+ Accounts map[string]credential.Status `json:"accounts,omitempty"`
+ LibraryCount int `json:"libraryCount"`
+ TaskCount int `json:"taskCount"`
+ SubscriptionCnt int `json:"subscriptionCount"`
+ LiveRoomCount int `json:"liveRoomCount"`
+ IndexStatus string `json:"indexStatus,omitempty"`
+ SubscriptionCheckStatus string `json:"subscriptionCheckStatus,omitempty"`
+ AutoCacheStatus string `json:"autoCacheStatus,omitempty"`
+ LiveRecordStatus string `json:"liveRecordStatus,omitempty"`
+ CorruptRecovered []string `json:"corruptRecovered,omitempty"`
+ RecentEvents []Event `json:"recentEvents,omitempty"`
+}
+
+// AuthService defines authentication and renewal operations across supported sites.
+type AuthService interface {
+ HasAnyLogin() bool
+ Statuses() map[string]credential.Status
+ StatusOf(siteID string) credential.Status
+ Renewal(siteID string) RenewalStatus
+ VerifySiteAccount(ctx context.Context, siteID string) (credential.Status, error)
+ LoginWithCookie(ctx context.Context, siteID, rawCookie, rawRefreshToken string) (credential.Status, error)
+ LogoutSite(siteID string) (credential.Status, error)
+ AccountStatus() credential.Status
+ BootstrapAuth(ctx context.Context) (credential.Status, error)
+ VerifyAccount(ctx context.Context) (credential.Status, error)
+ StartQRLogin(ctx context.Context) (bilibili.QRSession, error)
+ PollQRLogin(ctx context.Context, flowID string) (bilibili.QRPollResult, error)
+ CancelQRLogin(flowID string)
+ ImportCookie(ctx context.Context, rawCookie, rawRefreshToken string) (credential.Status, error)
+ RefreshCookie(ctx context.Context) (credential.Status, error)
+ Logout() (credential.Status, error)
+}
+
+// ParseService defines link resolution and creator/video/note browsing operations.
+type ParseService interface {
+ Resolve(ctx context.Context, rawInput string) (site.ResolveTarget, error)
+ OpenLink(ctx context.Context, rawInput string) (*OpenLinkResult, error)
+ DouyinWork(ctx context.Context, awemeID string) (*DouyinWorkView, error)
+ DouyinUser(ctx context.Context, secUID string) (*DouyinUserView, error)
+ DouyinUserWorks(ctx context.Context, secUID, cursor string) (*DouyinUserWorksPage, error)
+ DouyinLive(ctx context.Context, webRID string) (*DouyinLiveView, error)
+ StagePreviewMedia(ctx context.Context, siteID, rawURL, ext string) (string, error)
+ FetchHistoryThumbs(ctx context.Context, job HistoryThumbJob) error
+ FetchImage(ctx context.Context, rawURL string) ([]byte, error)
+ UserDynamicsPage(ctx context.Context, mid int64, offset string) (bilibili.UserDynamicsPage, error)
+ UserVideosPage(ctx context.Context, mid int64, page int) (bilibili.UserVideosPage, error)
+}
+
+// HistoryService defines recent parse history operations.
+type HistoryService interface {
+ ListHistory() []storage.HistoryEntry
+ ClearHistory() error
+ RemoveHistory(kind, id string) error
+ RemoveHistoryForSite(siteID, kind, id string) error
+ HistoryThumbPath(name string) (string, error)
+}
+
+// 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)
+ EnqueueDynamicCache(ctx context.Context, req download.DynamicEnqueueRequest) (download.Task, error)
+ CacheDouyinWork(ctx context.Context, awemeID string) (download.Task, error)
+ CacheDouyinWorkFor(ctx context.Context, awemeID, forUID, forName string) (download.Task, error)
+ ListCacheQueue() []CacheQueueTask
+ FindCacheQueueTask(siteID, user, list string) (CacheQueueTask, bool)
+ EnqueueCacheQueue(ctx context.Context, req CacheQueueRequest) (CacheQueueTask, error)
+ PauseCacheQueue(id string) (CacheQueueTask, error)
+ ResumeCacheQueue(id string) (CacheQueueTask, error)
+ CancelCacheQueue(id string) (CacheQueueTask, error)
+ // RemoveCacheQueue deletes a finished cache queue task from the list;
+ // RemoveFinishedCacheQueues deletes all of them. Cached items stay.
+ RemoveCacheQueue(id string) error
+ RemoveFinishedCacheQueues() (int, error)
+ CacheSupplement(ctx context.Context, bvid string) (download.Task, error)
+ Upgrade(ctx context.Context, key string) (download.Task, error)
+ ListDownloadTasks() ([]download.Task, error)
+ TaskDetail(taskID string) (download.TaskDetail, bool, error)
+ PauseTask(taskID string) (download.Task, error)
+ ResumeTask(taskID string) (download.Task, error)
+ RetryTask(taskID string) (download.Task, error)
+ CancelTask(taskID string) (download.Task, error)
+ RemoveTask(taskID string) error
+ RemoveFinishedTasks() (int, error)
+ States(keys []string) map[string]library.DotState
+ UpgradeCandidates(limit int) ([]library.ItemMetadata, error)
+ CheckUpgradeKeys(ctx context.Context, keys []string, force bool) ([]library.ItemMetadata, error)
+ CheckQualityUpgrade(ctx context.Context) ([]library.ItemMetadata, error)
+}
+
+// FeedService defines home feed pagination and anchor persistence operations.
+type FeedService interface {
+ QueryFeed(filter library.FeedFilter) ([]library.FeedEntry, error)
+ FeedPage(req library.FeedPageRequest) (library.FeedPageResult, error)
+ Anchor() uistate.FeedAnchor
+ SaveAnchor(anchor uistate.FeedAnchor) error
+ NewerCount(anchor uistate.FeedAnchor) (int, error)
+}
+
+// LibraryService defines local media library, safe deletion, and whitelist path operations.
+type LibraryService interface {
+ LibraryStatistics() (library.Statistics, error)
+ ListLibraryItems(filter library.FeedFilter) ([]library.ItemMetadata, error)
+ GetLibraryItem(keyOrID string) (library.ItemMetadata, bool, error)
+ MediaPath(key, relPath string) (string, error)
+ PlanDelete(key string) (library.DeletePlan, error)
+ Delete(key string) error
+ DeleteLibraryItem(itemKey string, deleteFiles bool) error
+ RebuildLibraryIndex() (library.RebuildReport, error)
+ // RefreshLibrary rescans the library folders for files deleted or changed
+ // outside TRACE (presence and size, no hashing) and reports what changed.
+ RefreshLibrary() (library.RebuildReport, error)
+ AddLibraryRoot(selectedDir string) (library.AddRootReport, error)
+ MigrateCacheDir(newDir string, moveExisting bool) (library.RebuildReport, error)
+ OpenItemFolder(itemKey string) error
+}
+
+// SettingsService defines settings, UI state, and directory management operations.
+type SettingsService interface {
+ Locations() appdirs.Locations
+ GetSettings() settings.Settings
+ UpdateSettings(next settings.Settings) (settings.Settings, error)
+ GetUIState() uistate.State
+ UpdateUIState(next uistate.State) (uistate.State, error)
+ // MutateUIState changes ui-state.json under its lock, so a write from
+ // another goroutine (the updater) between reading and writing is kept.
+ MutateUIState(fn func(*uistate.State)) (uistate.State, error)
+ GetUpdateHistory() update.History
+ RecordUpdateCheck(rec update.CheckRecord) error
+ RecordAppUpdate(rec update.UpdateRecord) error
+ InstalledDevVersion() string
+ OpenDataFolder(target string) error
+}
+
+// SubscriptionService defines multi-account subscription CRUD and binding operations.
+type SubscriptionService interface {
+ ListSubscriptions() ([]subscription.Subscription, error)
+ UpsertSubscription(sub subscription.Subscription) (subscription.Subscription, error)
+ CreateSubscription(name, note string, accounts []subscription.AccountRef, rules subscription.SubRules) (subscription.Subscription, error)
+ LinkSubscriptionAccount(subID, site, uid, name, face string) (subscription.Subscription, error)
+ LinkSubscriptionAccountRef(subID string, acct subscription.AccountRef) (subscription.Subscription, error)
+ UnlinkSubscriptionAccount(subID, site, uid string) (subscription.Subscription, error)
+ MoveSubscriptionAccount(site, uid, toSubID string) (subscription.Subscription, error)
+ SetSubscriptionRules(subID string, rules subscription.SubRules) (subscription.Subscription, error)
+ // Shared cache rules: subscriptions choose one by ID.
+ ListCacheRules() []subscription.CacheRule
+ SubscriptionAccountWorks() map[string]AccountWorks
+ SaveCacheRule(rule subscription.CacheRule) (subscription.CacheRule, error)
+ DeleteCacheRule(id string) error
+ SetSubscriptionRule(subID, ruleID string) (subscription.Subscription, error)
+ SetSubscriptionsRule(ruleID string, subIDs []string) error
+ PreviewAccount(ctx context.Context, input string) (subscription.AccountRef, *subscription.Subscription, error)
+ OwnerOfAccount(site, uid string) (subscription.Subscription, bool)
+ // AccountAvatarPath is the local copy of a subscribed account's avatar, or "".
+ AccountAvatarPath(site, uid string) string
+ DeleteSubscription(subIDOrMid string) error
+}
+
+// UpdateService defines subscription update checking, listing, and scheduler diagnostics.
+type UpdateService interface {
+ ListSubscriptionUpdatesPage(subID string, limit, offset int) ([]subscription.UpdateItem, error)
+ ListSubscriptionUpdates(subID string) ([]subscription.UpdateItem, error)
+ CheckSubscriptionsNow(ctx context.Context, targetMid int64) (subscription.CheckSummary, error)
+ CheckSubscription(ctx context.Context, subID string) (subscription.CheckSummary, error)
+ CheckAccount(ctx context.Context, subID, siteName, uid string) (subscription.CheckSummary, error)
+ CancelSubscriptionCheck()
+ SchedulerStatuses() map[string]SiteSchedulerStatus
+ // CheckPlan is Tasks › 检查计划: each account's last and next checks.
+ CheckPlan() []AccountCheckRow
+}
+
+// FollowingService defines read-only following group and creator import operations.
+type FollowingService interface {
+ RelationTags(ctx context.Context) ([]bilibili.RelationTag, error)
+ RelationFollowings(ctx context.Context, tagID int64, pn, ps int) ([]bilibili.FollowingUser, error)
+ ImportCreators(users []bilibili.FollowingUser, scope, autoCache string, liveNotify, liveAutoRecord bool) (int, error)
+}
+
+// LiveService defines live status polling and stream recording operations across sites.
+type LiveService interface {
+ ListLiveRooms() []live.RoomState
+ ListLiveAccounts() []LiveAccountState
+ LiveStatus(ctx context.Context, uids []int64) ([]live.RoomState, error)
+ LiveStatuses(ctx context.Context, accountKeys []string) ([]LiveAccountState, error)
+ PollLiveNow(ctx context.Context) ([]live.RoomState, error)
+ OpenLiveRoomInBrowser(roomID int64) error
+ OpenLiveInBrowser(siteID, roomOrWebRID string) error
+ StartLiveRecording(ctx context.Context, roomID int64) (live.RoomState, error)
+ StartLiveRecordingByAccount(ctx context.Context, accountKey string) (LiveAccountState, error)
+ StartLiveRecordingByRoom(ctx context.Context, siteID, roomOrWebRID string) (LiveAccountState, error)
+ StopLiveRecording(roomID int64) (live.RoomState, error)
+ StopLiveRecordingByKey(recKey string) (LiveAccountState, error)
+ // ClearLiveIncidents deletes the incident records of a finished live
+ // session; the recording itself is kept.
+ ClearLiveIncidents(itemKey, siteID, roomID, uid string) error
+ LiveRecordingPreview(recKey string) (LiveRecordingPreviewInfo, bool)
+}
+
+// AppService defines application lifecycle, event subscription, and diagnostics operations.
+type AppService interface {
+ Close() error
+ SubscribeEvents(fn func(Event)) func()
+ Desktop() Desktop
+ DiagnosticsSnapshot() Diagnostics
+ RecentLogs(maxLines int) ([]string, error)
+ // LogUserError records an error the UI showed to the user, so every
+ // visible error also appears in the run log.
+ LogUserError(err error)
+ PauseAllActiveWork()
+}
+
+// BackendAPI composes all TRACE domain service interfaces for the UI layer.
+type BackendAPI interface {
+ AuthService
+ ParseService
+ HistoryService
+ CacheService
+ FeedService
+ LibraryService
+ SettingsService
+ SubscriptionService
+ UpdateService
+ FollowingService
+ AccountService
+ LiveService
+ AppService
+ RemoteService
+ SubscriptionTransferService
+ TransferService
+}
+
+var _ BackendAPI = (*Backend)(nil)
diff --git a/internal/service/library_service.go b/internal/service/library_service.go
new file mode 100644
index 0000000..1460ca7
--- /dev/null
+++ b/internal/service/library_service.go
@@ -0,0 +1,519 @@
+package service
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "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/uistate"
+)
+
+// EnqueueVideoCache enqueues Bilibili video parts for local caching.
+func (b *Backend) EnqueueVideoCache(ctx context.Context, req download.VideoEnqueueRequest) ([]download.Task, error) {
+ if err := b.requireDesktop(); err != nil {
+ return nil, err
+ }
+ if err := b.requireSiteLogin(site.Bilibili); err != nil {
+ return nil, err
+ }
+ tasks, err := b.dl.EnqueueVideo(ctx, req)
+ if err != nil {
+ b.logError("EnqueueVideoCache", err)
+ return nil, err
+ }
+ b.events.PublishSite(EventTaskUpdated, string(site.Bilibili), "enqueued:video:"+req.BVID)
+ return tasks, nil
+}
+
+// EnqueueDynamicCache enqueues a Bilibili dynamic post for local caching.
+func (b *Backend) EnqueueDynamicCache(ctx context.Context, req download.DynamicEnqueueRequest) (download.Task, error) {
+ if err := b.requireDesktop(); err != nil {
+ return download.Task{}, err
+ }
+ if err := b.requireSiteLogin(site.Bilibili); err != nil {
+ return download.Task{}, err
+ }
+ task, err := b.dl.EnqueueDynamic(ctx, req)
+ if err != nil {
+ b.logError("EnqueueDynamicCache", err)
+ return download.Task{}, err
+ }
+ b.events.PublishSite(EventTaskUpdated, string(site.Bilibili), "enqueued:dynamic:"+req.DynamicID)
+ return task, nil
+}
+
+// CacheDouyinWork enqueues a Douyin video or mixed note work for local caching.
+func (b *Backend) CacheDouyinWork(ctx context.Context, awemeID string) (download.Task, error) {
+ if err := b.requireDesktop(); err != nil {
+ return download.Task{}, err
+ }
+ if err := b.requireSiteLogin(site.Douyin); err != nil {
+ return download.Task{}, err
+ }
+ return b.enqueueDouyinWorkWithSource(ctx, awemeID, "manual", "", "")
+}
+
+// CacheDouyinWorkFor caches a work from account forUID's works list (their
+// user page): a co-creation by someone else is stored under forUID's folder
+// (DEC-063).
+func (b *Backend) CacheDouyinWorkFor(ctx context.Context, awemeID, forUID, forName string) (download.Task, error) {
+ if err := b.requireDesktop(); err != nil {
+ return download.Task{}, err
+ }
+ if err := b.requireSiteLogin(site.Douyin); err != nil {
+ return download.Task{}, err
+ }
+ return b.enqueueDouyinWorkWithSource(ctx, awemeID, "manual", forUID, forName)
+}
+
+// enqueueDouyinWorkWithSource enqueues a work; forUID is the account whose
+// works list it came from (empty when unknown, e.g. a parsed link).
+func (b *Backend) enqueueDouyinWorkWithSource(ctx context.Context, awemeID, source, forUID, forName string) (download.Task, error) {
+ if err := b.requireSiteLogin(site.Douyin); err != nil {
+ return download.Task{}, err
+ }
+ t, err := b.dl.EnqueueDouyinWork(ctx, download.DouyinWorkEnqueueRequest{
+ AwemeID: strings.TrimSpace(awemeID),
+ Source: source,
+ ForUID: strings.TrimSpace(forUID),
+ ForName: strings.TrimSpace(forName),
+ })
+ if err != nil {
+ b.logError("CacheDouyinWork", err)
+ return download.Task{}, err
+ }
+ b.events.PublishSite(EventTaskUpdated, string(site.Douyin), "enqueued:"+t.TargetID)
+ return t, nil
+}
+
+// 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 {
+ return download.Task{}, err
+ }
+ if err := b.requireSiteLogin(site.Bilibili); err != nil {
+ return download.Task{}, err
+ }
+ task, err := b.dl.CacheSupplement(ctx, bvid)
+ if err != nil {
+ b.logError("CacheSupplement", err)
+ return download.Task{}, err
+ }
+ b.events.PublishSite(EventTaskUpdated, string(site.Bilibili), "enqueued:supplement:"+bvid)
+ return task, nil
+}
+
+// Upgrade enqueues a quality upgrade download task for a cached Bilibili video item.
+func (b *Backend) Upgrade(ctx context.Context, key string) (download.Task, error) {
+ if err := b.requireDesktop(); err != nil {
+ return download.Task{}, err
+ }
+ if err := b.requireSiteLogin(site.Bilibili); err != nil {
+ return download.Task{}, err
+ }
+ task, err := b.dl.Upgrade(ctx, key)
+ if err != nil {
+ b.logError("Upgrade", err)
+ return download.Task{}, err
+ }
+ b.events.PublishSite(EventTaskUpdated, string(site.Bilibili), "enqueued:upgrade:"+key)
+ return task, nil
+}
+
+// ListDownloadTasks returns all download tasks across sites.
+func (b *Backend) ListDownloadTasks() ([]download.Task, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return nil, err
+ }
+ return b.dl.ListTasks()
+}
+
+// TaskDetail returns per-file progress and sanitized attempt history for a download task.
+func (b *Backend) TaskDetail(taskID string) (download.TaskDetail, bool, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return download.TaskDetail{}, false, err
+ }
+ return b.dl.TaskDetail(taskID)
+}
+
+// PauseTask pauses a download task.
+func (b *Backend) PauseTask(taskID string) (download.Task, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return download.Task{}, err
+ }
+ return b.dl.Pause(taskID)
+}
+
+func (b *Backend) requireTaskSiteLogin(taskID string) error {
+ if err := b.requireAnyLogin(); err != nil {
+ return err
+ }
+ detail, ok, err := b.dl.TaskDetail(taskID)
+ if err != nil {
+ return err
+ }
+ if ok {
+ tSite, sErr := normalizeSiteID(detail.Task.Site)
+ if sErr != nil {
+ return sErr
+ }
+ return b.requireSiteLogin(tSite)
+ }
+ return nil
+}
+
+// ResumeTask resumes a paused download task after verifying its owning site is logged in.
+func (b *Backend) ResumeTask(taskID string) (download.Task, error) {
+ if err := b.requireTaskSiteLogin(taskID); err != nil {
+ return download.Task{}, err
+ }
+ return b.dl.Resume(taskID)
+}
+
+// RetryTask retries a failed or partial download task after verifying its owning site is logged in.
+func (b *Backend) RetryTask(taskID string) (download.Task, error) {
+ if err := b.requireTaskSiteLogin(taskID); err != nil {
+ return download.Task{}, err
+ }
+ return b.dl.Retry(taskID)
+}
+
+// CancelTask cancels a download task and removes incomplete .part files.
+func (b *Backend) CancelTask(taskID string) (download.Task, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return download.Task{}, err
+ }
+ return b.dl.Cancel(taskID)
+}
+
+// RemoveTask deletes a finished task record; cached files stay in the library.
+func (b *Backend) RemoveTask(taskID string) error {
+ if err := b.requireAnyLogin(); err != nil {
+ return err
+ }
+ if err := b.dl.Remove(taskID); err != nil {
+ return err
+ }
+ b.events.Publish(EventTaskUpdated, "removed:"+taskID)
+ return nil
+}
+
+// RemoveFinishedTasks clears every completed or canceled task record.
+func (b *Backend) RemoveFinishedTasks() (int, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return 0, err
+ }
+ n, err := b.dl.RemoveFinished()
+ if n > 0 {
+ b.events.Publish(EventTaskUpdated, "removed:finished")
+ }
+ return n, err
+}
+
+// QueryFeed queries the unified feed (cached + online-discovered items) ordered by pub_ts DESC.
+func (b *Backend) QueryFeed(filter library.FeedFilter) ([]library.FeedEntry, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return nil, err
+ }
+ return b.lib.QueryFeed(filter)
+}
+
+// FeedPage queries a keyset-paginated page of the home feed.
+func (b *Backend) FeedPage(req library.FeedPageRequest) (library.FeedPageResult, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return library.FeedPageResult{}, err
+ }
+ return b.lib.FeedPage(req)
+}
+
+// Anchor returns the persisted home feed reading anchor from ui-state.json.
+func (b *Backend) Anchor() uistate.FeedAnchor {
+ if b.requireAnyLogin() != nil {
+ return uistate.FeedAnchor{}
+ }
+ return b.uiState.Get().Anchor
+}
+
+// SaveAnchor persists the home feed reading anchor into ui-state.json.
+func (b *Backend) SaveAnchor(anchor uistate.FeedAnchor) error {
+ if err := b.requireAnyLogin(); err != nil {
+ return err
+ }
+ _, err := b.uiState.Mutate(func(st *uistate.State) { st.Anchor = anchor })
+ return err
+}
+
+// NewerCount returns the number of feed entries strictly newer than anchor.
+func (b *Backend) NewerCount(anchor uistate.FeedAnchor) (int, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return 0, err
+ }
+ return b.lib.NewerCachedCount(anchor.PubTs, anchor.Key)
+}
+
+// LibraryStatistics returns local library counts and total size.
+func (b *Backend) LibraryStatistics() (library.Statistics, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return library.Statistics{}, err
+ }
+ return b.lib.Statistics()
+}
+
+// ListLibraryItems returns locally cached items matching filter.
+func (b *Backend) ListLibraryItems(filter library.FeedFilter) ([]library.ItemMetadata, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return nil, err
+ }
+ return b.lib.ListItems(filter)
+}
+
+// GetLibraryItem returns a single cached item by itemKey or rawID.
+func (b *Backend) GetLibraryItem(keyOrID string) (library.ItemMetadata, bool, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return library.ItemMetadata{}, false, err
+ }
+ return b.lib.GetItem(keyOrID)
+}
+
+// MediaPath validates and resolves a registered relative file path within a cached item.
+func (b *Backend) MediaPath(key, relPath string) (string, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return "", err
+ }
+ return b.lib.MediaPath(key, relPath)
+}
+
+// States computes the canonical cache status dots for the given item keys.
+func (b *Backend) States(keys []string) map[string]library.DotState {
+ if b.requireAnyLogin() != nil {
+ out := make(map[string]library.DotState, len(keys))
+ for _, key := range keys {
+ out[key] = library.DotState{Key: key, Dot: "none", Label: "登录后查看缓存状态"}
+ }
+ return out
+ }
+ out := b.lib.States(keys)
+ activeProgress := make(map[string]float64)
+ latest := make(map[string]download.Task)
+ if tasks, err := b.dl.ListTasks(); err == nil {
+ for _, t := range tasks {
+ for _, key := range []string{t.ItemKey, t.TargetID} {
+ if key == "" {
+ continue
+ }
+ if _, exists := latest[key]; !exists {
+ latest[key] = t
+ }
+ }
+ if t.Status == "queued" || t.Status == "downloading" || t.Status == "muxing" || t.Status == "running" {
+ prog := t.Progress
+ if prog == 0 && t.TotalBytes > 0 {
+ prog = float64(t.BytesDownloaded) / float64(t.TotalBytes)
+ }
+ if t.ItemKey != "" {
+ activeProgress[t.ItemKey] = prog
+ }
+ if t.TargetID != "" {
+ activeProgress[t.TargetID] = prog
+ }
+ }
+ }
+ }
+ for _, k := range keys {
+ if prog, active := activeProgress[k]; active {
+ out[k] = library.DotState{
+ Key: k,
+ Dot: "ring",
+ Label: "缓存中",
+ Progress: prog,
+ }
+ continue
+ }
+ if task, exists := latest[k]; exists {
+ switch task.Status {
+ case "paused", "partial":
+ dot := out[k]
+ dot.Dot, dot.Label = "yellow", "部分缓存,重试可继续"
+ if task.Status == "paused" {
+ dot.Label = "已暂停,可继续"
+ }
+ out[k] = dot
+ case "failed":
+ dot := out[k]
+ dot.Dot, dot.Label = "red", "缓存失败,可重试"
+ out[k] = dot
+ }
+ }
+ }
+ return out
+}
+
+// PlanDelete computes the safe file deletion plan for an item key.
+func (b *Backend) PlanDelete(key string) (library.DeletePlan, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return library.DeletePlan{}, err
+ }
+ return b.lib.PlanDelete(key)
+}
+
+// Delete executes a safe manifest-only file deletion for an item key.
+func (b *Backend) Delete(key string) error {
+ return b.DeleteLibraryItem(key, true)
+}
+
+// RebuildLibraryIndex scans CacheDir for item.json files and rebuilds the SQLite index.
+func (b *Backend) RebuildLibraryIndex() (library.RebuildReport, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return library.RebuildReport{}, err
+ }
+ rep, err := b.lib.RebuildIndex()
+ if len(rep.CorruptBackedUp) > 0 {
+ b.logMu.Lock()
+ b.corruptFiles = append(b.corruptFiles, rep.CorruptBackedUp...)
+ b.logMu.Unlock()
+ }
+ b.events.Publish(EventLibraryChanged, "rebuilt")
+ return rep, err
+}
+
+// RefreshLibrary is the media library's "刷新": a quick rescan that drops
+// items whose folder was deleted and marks items with missing files. Only
+// local files are read; no site request is made.
+func (b *Backend) RefreshLibrary() (library.RebuildReport, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return library.RebuildReport{}, err
+ }
+ rep, err := b.lib.RefreshIndex()
+ if len(rep.CorruptBackedUp) > 0 {
+ b.logMu.Lock()
+ b.corruptFiles = append(b.corruptFiles, rep.CorruptBackedUp...)
+ b.logMu.Unlock()
+ }
+ if err != nil {
+ b.logError("RefreshLibrary", err)
+ } else {
+ b.logInfo(fmt.Sprintf("library refresh: scanned=%d removed=%d newly_missing=%d", rep.Scanned, len(rep.Removed), len(rep.NewlyMissing)))
+ }
+ b.events.Publish(EventLibraryChanged, "refreshed")
+ return rep, err
+}
+
+// AddLibraryRoot adds an existing cache root or legacy trace-data directory and indexes its manifests.
+func (b *Backend) AddLibraryRoot(selectedDir string) (library.AddRootReport, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return library.AddRootReport{}, err
+ }
+ rep, err := b.lib.AddLibraryRoot(selectedDir)
+ if err == nil {
+ b.events.Publish(EventLibraryChanged, "root_added")
+ }
+ return rep, err
+}
+
+// DeleteLibraryItem removes an item from the index and optionally deletes its registered files from disk.
+func (b *Backend) DeleteLibraryItem(itemKey string, deleteFiles bool) error {
+ if err := b.requireAnyLogin(); err != nil {
+ return err
+ }
+ if err := b.lib.DeleteItem(itemKey, deleteFiles); err != nil {
+ return err
+ }
+ b.events.Publish(EventLibraryChanged, "deleted:"+itemKey)
+ return nil
+}
+
+// MigrateCacheDir changes the active cache directory, optionally moves existing files, and updates settings.json.
+func (b *Backend) MigrateCacheDir(newDir string, moveExisting bool) (library.RebuildReport, error) {
+ if err := b.requireDesktop(); err != nil {
+ return library.RebuildReport{}, err
+ }
+ if err := b.requireAnyLogin(); err != nil {
+ return library.RebuildReport{}, err
+ }
+ if !moveExisting {
+ cur := b.settings.Get()
+ cur.CacheRoot, cur.CacheDir = newDir, newDir
+ _, err := b.UpdateSettings(cur)
+ return library.RebuildReport{}, err
+ }
+ if _, recordings := b.ActiveWork(); recordings > 0 {
+ return library.RebuildReport{}, &site.Error{Kind: site.ErrKindBadRequest, Message: "有直播正在录制,请先停止录制后再迁移缓存目录"}
+ }
+ if b.hasActiveTransferJobs() {
+ return library.RebuildReport{}, &site.Error{Kind: site.ErrKindBadRequest, Message: "有导入或导出任务正在进行,请等待完成后再迁移缓存目录"}
+ }
+ b.settingsMu.Lock()
+ cur := b.settings.Get()
+ cur.CacheDir, cur.CacheRoot = newDir, newDir
+ cur, err := b.settings.PreviewUpdate(cur)
+ if err != nil {
+ b.settingsMu.Unlock()
+ return library.RebuildReport{}, err
+ }
+ var rep library.RebuildReport
+ err = b.dl.WithIdleTasks(func() error {
+ var migrationErr error
+ rep, migrationErr = b.lib.MigrateCacheDirWithPersistence(newDir, true, func() error { _, err := b.settings.Update(cur); return err })
+ return migrationErr
+ })
+ b.settingsMu.Unlock()
+ if err != nil {
+ return rep, err
+ }
+ b.events.Publish(EventLibraryChanged, "migrated")
+ return rep, nil
+}
+
+// UpgradeCandidates returns up to limit cached Bilibili video items ordered by oldest UpgradeCheckedAt.
+func (b *Backend) UpgradeCandidates(limit int) ([]library.ItemMetadata, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return nil, err
+ }
+ return b.lib.UpgradeCandidates(limit)
+}
+
+// CheckUpgradeKeys checks the specified Bilibili video keys (or up to 50 candidates when empty) for quality upgrades.
+func (b *Backend) CheckUpgradeKeys(ctx context.Context, keys []string, force bool) ([]library.ItemMetadata, error) {
+ if err := b.requireSiteLogin(site.Bilibili); err != nil {
+ return nil, err
+ }
+ dlCfg := b.settings.Get().Download
+ opts := bilibili.PlaySelectionOptions{
+ CodecOrder: append([]string(nil), dlCfg.CodecOrder...),
+ PreferredCodec: dlCfg.PreferredVideoCodec,
+ PreferLosslessAudio: dlCfg.PreferLosslessAudio,
+ PreferDolbyAudio: dlCfg.PreferDolbyAudio,
+ TargetQn: 127,
+ }
+ items, err := b.lib.CheckUpgradeKeys(ctx, b.bili, keys, force, opts)
+ if err != nil {
+ b.logError("CheckUpgradeKeys", err)
+ return items, err
+ }
+ b.events.PublishSite(EventLibraryChanged, string(site.Bilibili), "upgrade_checked")
+ return items, nil
+}
+
+// CheckQualityUpgrade checks cached Bilibili videos against PlayURL for higher video/audio quality.
+func (b *Backend) CheckQualityUpgrade(ctx context.Context) ([]library.ItemMetadata, error) {
+ return b.CheckUpgradeKeys(ctx, nil, true)
+}
+
+// OpenItemFolder opens or reveals a cached item's folder on disk via Desktop.
+func (b *Backend) OpenItemFolder(itemKey string) error {
+ if err := b.requireAnyLogin(); err != nil {
+ return err
+ }
+ item, ok, err := b.lib.GetItem(itemKey)
+ if err != nil {
+ return err
+ }
+ if !ok || item.ItemDir == "" {
+ return fmt.Errorf("service: item folder not found for %s", itemKey)
+ }
+ return b.desktop.OpenPath(item.ItemDir)
+}
diff --git a/internal/service/live_service.go b/internal/service/live_service.go
new file mode 100644
index 0000000..6e06ab4
--- /dev/null
+++ b/internal/service/live_service.go
@@ -0,0 +1,395 @@
+package service
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/live"
+ "github.com/chialecode/trace/internal/site"
+)
+
+// ListLiveRooms returns the current live status and recording state of all tracked rooms.
+func (b *Backend) ListLiveRooms() []live.RoomState {
+ if b.requireAnyLogin() != nil {
+ return nil
+ }
+ return b.live.ListRooms()
+}
+
+// ListLiveAccounts returns unified live & recording states across all tracked rooms/accounts.
+func (b *Backend) ListLiveAccounts() []LiveAccountState {
+ if b.requireAnyLogin() != nil {
+ return nil
+ }
+ rooms := b.live.ListRooms()
+ out := make([]LiveAccountState, 0, len(rooms))
+ for _, r := range rooms {
+ out = append(out, mapRoomToAccountState(r))
+ }
+ return out
+}
+
+// LiveStatus refreshes live status for visible Bilibili accounts, with a 60s cache.
+// For subscribed accounts with auto-record enabled, the underlying live manager
+// may start recording automatically; unsubscribed accounts are read-only.
+func (b *Backend) LiveStatus(ctx context.Context, uids []int64) ([]live.RoomState, error) {
+ if err := b.requireSiteLogin(site.Bilibili); err != nil {
+ return nil, err
+ }
+ return b.live.RefreshForAccounts(ctx, uids)
+}
+
+// LiveStatuses refreshes live status for a mixed slice of ":" account keys.
+func (b *Backend) LiveStatuses(ctx context.Context, accountKeys []string) ([]LiveAccountState, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return nil, err
+ }
+ var biliUIDs []int64
+ var douyinUIDs []string
+ for _, rawKey := range accountKeys {
+ siteID, uid, err := site.ParseAccountKey(rawKey)
+ if err != nil {
+ continue
+ }
+ switch siteID {
+ case site.Bilibili:
+ if mid, mErr := strconv.ParseInt(uid, 10, 64); mErr == nil && mid > 0 {
+ biliUIDs = append(biliUIDs, mid)
+ }
+ case site.Douyin:
+ douyinUIDs = append(douyinUIDs, uid)
+ }
+ }
+
+ var out []LiveAccountState
+ var firstErr error
+
+ if len(biliUIDs) > 0 {
+ if err := b.requireSiteLogin(site.Bilibili); err != nil {
+ firstErr = err
+ } else if rooms, err := b.live.RefreshForAccounts(ctx, biliUIDs); err != nil {
+ firstErr = err
+ } else {
+ wantUIDs := make(map[int64]struct{}, len(biliUIDs))
+ for _, uid := range biliUIDs {
+ wantUIDs[uid] = struct{}{}
+ }
+ for _, r := range rooms {
+ if r.Site != "" && !strings.EqualFold(r.Site, string(site.Bilibili)) {
+ continue
+ }
+ if _, ok := wantUIDs[r.UID]; !ok {
+ continue
+ }
+ out = append(out, mapRoomToAccountState(r))
+ }
+ }
+ }
+
+ if len(douyinUIDs) > 0 {
+ if err := b.requireSiteLogin(site.Douyin); err != nil {
+ if firstErr == nil {
+ firstErr = err
+ }
+ } else {
+ for _, secUID := range douyinUIDs {
+ cachedWebRID := b.lookupAccountWebRID(secUID)
+ rs, err := b.live.CheckAccountLiveStatus(ctx, site.Douyin, secUID, cachedWebRID, false)
+ if err != nil {
+ if firstErr == nil {
+ firstErr = err
+ }
+ continue
+ }
+ out = append(out, mapRoomToAccountState(rs))
+ }
+ }
+ }
+
+ return out, firstErr
+}
+
+// PollLiveNow triggers an immediate live status batch poll.
+func (b *Backend) PollLiveNow(ctx context.Context) ([]live.RoomState, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return nil, err
+ }
+ return b.live.PollNow(ctx)
+}
+
+// OpenLiveRoomInBrowser opens a Bilibili live room in the external browser via Desktop.
+func (b *Backend) OpenLiveRoomInBrowser(roomID int64) error {
+ if err := b.requireAnyLogin(); err != nil {
+ return err
+ }
+ if roomID <= 0 {
+ return fmt.Errorf("service: invalid roomID %d", roomID)
+ }
+ return b.desktop.OpenExternalURL(fmt.Sprintf("https://live.bilibili.com/%d", roomID))
+}
+
+// OpenLiveInBrowser opens a Bilibili roomID or Douyin web_rid in the external system browser.
+func (b *Backend) OpenLiveInBrowser(siteID, roomOrWebRID string) error {
+ if err := b.requireAnyLogin(); err != nil {
+ return err
+ }
+ id, err := normalizeSiteID(siteID)
+ if err != nil {
+ return err
+ }
+ clean := strings.TrimSpace(roomOrWebRID)
+ for _, r := range clean {
+ if r < '0' || r > '9' {
+ return &site.Error{Site: id, Kind: site.ErrKindBadRequest, Message: "无效的直播间号"}
+ }
+ }
+ if clean == "" || clean == "0" {
+ return &site.Error{Site: id, Kind: site.ErrKindBadRequest, Message: "无效的直播间号"}
+ }
+ if id == site.Douyin {
+ return b.desktop.OpenExternalURL("https://live.douyin.com/" + clean)
+ }
+ return b.desktop.OpenExternalURL("https://live.bilibili.com/" + clean)
+}
+
+// StartLiveRecording starts recording a Bilibili live room.
+func (b *Backend) StartLiveRecording(ctx context.Context, roomID int64) (live.RoomState, error) {
+ if err := b.requireSiteLogin(site.Bilibili); err != nil {
+ return live.RoomState{}, err
+ }
+ return b.live.StartRecording(ctx, roomID)
+}
+
+// StartLiveRecordingByAccount starts live recording for a ":" creator account.
+func (b *Backend) StartLiveRecordingByAccount(ctx context.Context, accountKey string) (LiveAccountState, error) {
+ siteID, uid, err := site.ParseAccountKey(accountKey)
+ if err != nil {
+ return LiveAccountState{}, err
+ }
+ if err := b.requireSiteLogin(siteID); err != nil {
+ return LiveAccountState{}, err
+ }
+ if siteID == site.Bilibili {
+ mid, mErr := strconv.ParseInt(uid, 10, 64)
+ if mErr != nil || mid <= 0 {
+ return LiveAccountState{}, &site.Error{Site: site.Bilibili, Kind: site.ErrKindBadRequest, Message: "无效的哔哩哔哩账号 UID"}
+ }
+ rooms, rErr := b.live.RefreshForAccounts(ctx, []int64{mid})
+ if rErr != nil {
+ return LiveAccountState{}, rErr
+ }
+ var targetRoomID int64
+ for _, r := range rooms {
+ if (r.Site == "" || strings.EqualFold(r.Site, string(site.Bilibili))) && r.UID == mid && r.RoomID > 0 {
+ targetRoomID = r.RoomID
+ break
+ }
+ }
+ if targetRoomID <= 0 {
+ return LiveAccountState{}, &site.Error{Site: site.Bilibili, Kind: site.ErrKindUnavailable, Message: "该账号未开通直播间"}
+ }
+ rs, sErr := b.live.StartRecording(ctx, targetRoomID)
+ return mapRoomToAccountState(rs), sErr
+ }
+ return b.startDouyinLiveRecording(ctx, uid, b.lookupAccountWebRID(uid))
+}
+
+// StartLiveRecordingByRoom starts live recording given an explicit site and roomID/webRID.
+func (b *Backend) StartLiveRecordingByRoom(ctx context.Context, siteID, roomOrWebRID string) (LiveAccountState, error) {
+ id, err := normalizeSiteID(siteID)
+ if err != nil {
+ return LiveAccountState{}, err
+ }
+ if err := b.requireSiteLogin(id); err != nil {
+ return LiveAccountState{}, err
+ }
+ if id == site.Bilibili {
+ roomID, pErr := strconv.ParseInt(strings.TrimSpace(roomOrWebRID), 10, 64)
+ if pErr != nil || roomID <= 0 {
+ return LiveAccountState{}, &site.Error{Site: site.Bilibili, Kind: site.ErrKindBadRequest, Message: "无效的直播间号"}
+ }
+ rs, sErr := b.live.StartRecording(ctx, roomID)
+ return mapRoomToAccountState(rs), sErr
+ }
+ return b.startDouyinLiveRecording(ctx, "", strings.TrimSpace(roomOrWebRID))
+}
+
+// StopLiveRecording stops an active Bilibili live room recording and finalizes item.json.
+func (b *Backend) StopLiveRecording(roomID int64) (live.RoomState, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return live.RoomState{}, err
+ }
+ return b.live.StopRecording(roomID)
+}
+
+// StopLiveRecordingByKey stops an active live recording by canonical recording key (":live:" or decimal roomID).
+func (b *Backend) StopLiveRecordingByKey(recKey string) (LiveAccountState, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return LiveAccountState{}, err
+ }
+ rs, err := b.live.StopRecordingByKey(strings.TrimSpace(recKey))
+ return mapRoomToAccountState(rs), err
+}
+
+// LiveRecordingPreview returns an in-memory snapshot of an active or recent live recording session for preview playback.
+func (b *Backend) LiveRecordingPreview(recKey string) (LiveRecordingPreviewInfo, bool) {
+ if b.requireAnyLogin() != nil || b.live == nil {
+ return LiveRecordingPreviewInfo{}, false
+ }
+ target := strings.TrimSpace(recKey)
+ if target == "" {
+ return LiveRecordingPreviewInfo{}, false
+ }
+ if p, ok := b.live.RecordingPreview(target); ok {
+ roomID := strings.TrimSpace(p.RoomIDStr)
+ if roomID == "" && p.RoomID > 0 {
+ roomID = strconv.FormatInt(p.RoomID, 10)
+ }
+ return LiveRecordingPreviewInfo{
+ RecordingKey: p.RecordingKey,
+ Site: p.Site,
+ AccountUID: p.AccountUID,
+ RoomID: roomID,
+ WebRID: p.WebRID,
+ Uname: p.Uname,
+ Title: p.Title,
+ Codec: p.Codec,
+ Quality: p.Quality,
+ QualityName: p.QualityName,
+ Transport: p.Transport,
+ AudioOnly: p.AudioOnly,
+ Recording: p.Recording,
+ PartPath: p.PartPath,
+ PartIndex: p.PartIndex,
+ PartBytes: p.PartBytes,
+ PartDurationSec: p.PartDurationSec,
+ PartReady: p.PartReady,
+ PreviewSupported: p.PreviewSupported,
+ PreviewReason: p.PreviewReason,
+ ItemDir: p.ItemDir,
+ DurationSec: p.DurationSec,
+ SpeedBps: p.SpeedBps,
+ BytesWritten: p.BytesWritten,
+ Segments: p.Segments,
+ Incidents: append([]library.LiveIncident(nil), p.Incidents...),
+ StopReason: p.StopReason,
+ LastError: p.LastError,
+ }, true
+ }
+ for _, st := range b.ListLiveAccounts() {
+ if st.RecordingKey != target && st.AccountKey != target && st.RoomID != target && st.UID != target && st.WebRID != target {
+ continue
+ }
+ partPath := st.RecordPartPath
+ if partPath == "" && st.Recording && st.RecordItemDir != "" {
+ partPath = resolveRecordingPartPath(st.RecordItemDir)
+ }
+ partBytes := st.RecordPartBytes
+ if partBytes <= 0 && partPath != "" {
+ if info, err := os.Stat(partPath); err == nil {
+ partBytes = info.Size()
+ }
+ }
+ partReady := st.RecordPartReady || partBytes > 0
+ supported := st.PreviewSupported || (st.Recording && partPath != "" && !st.AudioOnly)
+ return LiveRecordingPreviewInfo{
+ RecordingKey: st.RecordingKey,
+ Site: st.Site,
+ AccountUID: st.UID,
+ RoomID: st.RoomID,
+ WebRID: st.WebRID,
+ Uname: st.Uname,
+ Title: st.Title,
+ Codec: st.Codec,
+ QualityName: st.QualityName,
+ Transport: st.Transport,
+ AudioOnly: st.AudioOnly,
+ Recording: st.Recording,
+ PartPath: partPath,
+ PartIndex: st.RecordPartIndex,
+ PartBytes: partBytes,
+ PartReady: partReady,
+ PreviewSupported: supported,
+ PreviewReason: st.PreviewReason,
+ ItemDir: st.RecordItemDir,
+ DurationSec: st.RecordDurationSec,
+ SpeedBps: st.RecordSpeedBps,
+ BytesWritten: st.RecordBytes,
+ Segments: st.RecordSegments,
+ Incidents: append([]library.LiveIncident(nil), st.Incidents...),
+ StopReason: st.StopReason,
+ LastError: st.LastError,
+ }, true
+ }
+ return LiveRecordingPreviewInfo{}, false
+}
+
+// ClearLiveIncidents deletes the recorded incidents of a finished live session
+// (Tasks › 录制异常): the item's live.incidents when itemKey names a finished
+// recording, and the in-memory list of matching rooms that are not recording.
+// The recording files are kept. A session still recording is refused.
+func (b *Backend) ClearLiveIncidents(itemKey, siteID, roomID, uid string) error {
+ itemKey = strings.TrimSpace(itemKey)
+ changed := false
+ if itemKey != "" && b.lib != nil {
+ item, ok, err := b.lib.GetItem(itemKey)
+ if err != nil {
+ return err
+ }
+ if ok && item.Kind == "live" {
+ if item.Status == "recording" {
+ return &site.Error{Kind: site.ErrKindBadRequest, Message: "这场直播还在录制,结束后才能删除异常记录"}
+ }
+ if item.Live != nil && len(item.Live.Incidents) > 0 {
+ item.Live.Incidents = nil
+ if _, err := b.lib.SaveItem(item.ItemDir, item); err != nil {
+ return err
+ }
+ changed = true
+ }
+ }
+ }
+ if b.live != nil && b.live.ClearIdleIncidents(siteID, roomID, uid) {
+ changed = true
+ }
+ if changed && b.events != nil {
+ b.events.Publish(EventLibraryChanged, "incidents_cleared")
+ }
+ return nil
+}
+
+func (b *Backend) startDouyinLiveRecording(ctx context.Context, uid string, webRID string) (LiveAccountState, error) {
+ rs, err := b.live.StartDouyinRecording(ctx, uid, webRID)
+ return mapRoomToAccountState(rs), err
+}
+
+func (b *Backend) syncDouyinAccountWebRID(secUID, webRID string) {
+ secUID = strings.TrimSpace(secUID)
+ webRID = strings.TrimSpace(webRID)
+ if secUID == "" || webRID == "" || b.subs == nil {
+ return
+ }
+ _ = b.subs.UpdateAccountWebRID(string(site.Douyin), secUID, webRID)
+}
+
+func (b *Backend) lookupAccountWebRID(secUID string) string {
+ secUID = strings.TrimSpace(secUID)
+ if secUID == "" {
+ return ""
+ }
+ if b.douyin != nil {
+ if w := b.douyin.CachedWebRID(secUID); w != "" {
+ return w
+ }
+ }
+ if b.subs != nil {
+ if _, acc, ok := b.subs.GetAccount(string(site.Douyin), secUID); ok && acc.WebRID != "" {
+ return acc.WebRID
+ }
+ }
+ return ""
+}
diff --git a/internal/service/logging.go b/internal/service/logging.go
new file mode 100644
index 0000000..6848a2b
--- /dev/null
+++ b/internal/service/logging.go
@@ -0,0 +1,338 @@
+package service
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "net/url"
+ "os"
+ "regexp"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/chialecode/trace/internal/appdirs"
+ "github.com/chialecode/trace/internal/site"
+)
+
+// DiagnosticsSnapshot returns a sanitized runtime summary without any secret values.
+func (b *Backend) DiagnosticsSnapshot() Diagnostics {
+ stats, indexErr := b.lib.Statistics()
+ tasks, tasksErr := b.dl.ListTasks()
+ subs, subsErr := b.subs.List()
+ rooms := b.live.ListRooms()
+
+ b.logMu.Lock()
+ corrupt := append([]string(nil), b.corruptFiles...)
+ b.logMu.Unlock()
+
+ indexStatus := fmt.Sprintf("正常(已索引 %d 项)", stats.Items)
+ if indexErr != nil {
+ indexStatus = "读取索引失败:" + b.sanitizeLogLine(indexErr.Error())
+ } else if len(corrupt) > 0 {
+ indexStatus = fmt.Sprintf("已保留 %d 个损坏文件,当前已索引 %d 项", len(corrupt), stats.Items)
+ }
+ subCheckStatus := fmt.Sprintf("空闲(共 %d 个订阅)", len(subs))
+ if b.subs != nil {
+ if progress, checking := b.subs.CheckProgress(); checking {
+ subCheckStatus = fmt.Sprintf("正在检查更新 %d / %d", progress.CheckedCreators, progress.TotalCreators)
+ } else {
+ var backoffParts []string
+ for _, id := range site.All() {
+ if inBackoff, until := b.subs.IsSiteInBackoff(string(id)); inBackoff {
+ backoffParts = append(backoffParts, fmt.Sprintf("%s至 %s", id.DisplayName(), until.Local().Format("15:04")))
+ }
+ }
+ if len(backoffParts) > 0 {
+ subCheckStatus = "风控退避中(暂停 " + strings.Join(backoffParts, " · ") + ")"
+ }
+ }
+ }
+ if subsErr != nil {
+ subCheckStatus = "读取订阅失败:" + b.sanitizeLogLine(subsErr.Error())
+ }
+ var runningTasks, queuedTasks, autoTasks int
+ for _, t := range tasks {
+ switch t.Status {
+ case "running":
+ runningTasks++
+ case "queued":
+ queuedTasks++
+ }
+ if t.Source == "auto" && (t.Status == "running" || t.Status == "queued") {
+ autoTasks++
+ }
+ }
+ autoCacheStatus := "空闲"
+ if runningTasks > 0 || queuedTasks > 0 {
+ autoCacheStatus = fmt.Sprintf("进行中 %d · 排队 %d(自动缓存 %d)", runningTasks, queuedTasks, autoTasks)
+ }
+ if tasksErr != nil {
+ autoCacheStatus = "读取任务失败:" + b.sanitizeLogLine(tasksErr.Error())
+ }
+ var recordingRooms, liveRooms int
+ for _, r := range rooms {
+ if r.LiveStatus == 1 {
+ liveRooms++
+ }
+ if r.Recording {
+ recordingRooms++
+ }
+ }
+ liveRecordStatus := "空闲"
+ if recordingRooms > 0 || liveRooms > 0 {
+ liveRecordStatus = fmt.Sprintf("录制中 %d 路 · 直播中 %d 个房间", recordingRooms, liveRooms)
+ }
+
+ build := appdirs.BuildInfo()
+ return Diagnostics{
+ Version: build.Version,
+ Commit: build.Commit,
+ BuildTime: build.BuildTime,
+ AppName: b.loc.AppName,
+ DisplayName: b.loc.DisplayName,
+ Channel: b.loc.Channel,
+ Mode: b.loc.Mode,
+ DataDir: b.loc.DataDir,
+ CacheDir: b.lib.CacheDir(),
+ LogsDir: b.loc.LogsDir,
+ Account: b.cred.Status(),
+ Accounts: b.Statuses(),
+ LibraryCount: stats.Items,
+ TaskCount: len(tasks),
+ SubscriptionCnt: len(subs),
+ LiveRoomCount: len(rooms),
+ IndexStatus: indexStatus,
+ SubscriptionCheckStatus: subCheckStatus,
+ AutoCacheStatus: autoCacheStatus,
+ LiveRecordStatus: liveRecordStatus,
+ CorruptRecovered: corrupt,
+ RecentEvents: b.events.Recent(),
+ }
+}
+
+const runtimeLogReadLimit = 1 << 20
+
+// RecentLogs reads at most 1 MiB from the end of trace.log and returns at most
+// 500 sanitized lines. An incomplete oldest line is discarded.
+func (b *Backend) RecentLogs(maxLines int) ([]string, error) {
+ if maxLines <= 0 || maxLines > 500 {
+ maxLines = 500
+ }
+ if b.logPath == "" {
+ return nil, nil
+ }
+ b.logMu.Lock()
+ defer b.logMu.Unlock()
+ f, err := os.Open(b.logPath)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil, nil
+ }
+ return nil, err
+ }
+ defer f.Close()
+ info, err := f.Stat()
+ if err != nil {
+ return nil, err
+ }
+ if !info.Mode().IsRegular() {
+ return nil, fmt.Errorf("运行日志不是普通文件")
+ }
+ start := max(int64(0), info.Size()-runtimeLogReadLimit)
+ raw := make([]byte, info.Size()-start)
+ n, err := f.ReadAt(raw, start)
+ if err != nil && !errors.Is(err, io.EOF) {
+ return nil, err
+ }
+ raw = raw[:n]
+ if start > 0 {
+ if newline := bytes.IndexByte(raw, '\n'); newline >= 0 {
+ raw = raw[newline+1:]
+ } else {
+ raw = nil
+ }
+ }
+ rawLines := strings.Split(strings.ReplaceAll(string(raw), "\r\n", "\n"), "\n")
+ var out []string
+ for _, ln := range rawLines {
+ ln = strings.TrimSpace(ln)
+ if ln == "" {
+ continue
+ }
+ out = append(out, b.sanitizeLogLine(ln))
+ }
+ if len(out) > maxLines {
+ out = out[len(out)-maxLines:]
+ }
+ return out, nil
+}
+
+// secretKeyNamesPattern is the single source of truth for secret parameter and
+// cookie field names redacted across runtime logs and persisted queue text.
+const secretKeyNamesPattern = `cookie|authorization|sessdata|bili_jct|dedeuserid|dedeuserid__ckmd5|sid|ac_time_value|refresh_token|pending_old_refresh_token|access_key|auth_key|csrf|qrcode_key|token|sign|x-expires|w_rid|upsig|wssecret|wstime|deadline|bwsv|sessionid|sessionid_ss|sid_tt|uid_tt|uid_tt_ss|sid_guard|odin_tt|passport_csrf_token|passport_csrf_token_default|ttwid|uifid|uifid_temp|mstoken|s_v_web_id|__ac_nonce|__ac_signature|a_bogus|x-bogus|x-signature|x-secsdk-web-signature|x-secsdk-csrf-token`
+
+var (
+ runtimeLogSecretField = regexp.MustCompile(`(?i)\b(?:` + secretKeyNamesPattern + `)["'\\]*\s*[=:]|[?&]e=|\btrace-remote:\S+|\bbearer\s+\S+`)
+ runtimeLogURL = regexp.MustCompile(`(?i)https?://[^\s"<>]+`)
+ runtimeLogPercentEscape = regexp.MustCompile(`(?i)%[0-9a-f]{2}`)
+)
+
+func (b *Backend) redactStoredSecrets(s string) string {
+ if b.credMgr != nil {
+ s = b.credMgr.RedactString(s)
+ } else if b.cred != nil {
+ s = b.cred.RedactString(s)
+ }
+ if b.remote != nil {
+ if tok := b.remote.activeToken(); tok != "" {
+ s = strings.ReplaceAll(s, tok, "[REDACTED]")
+ }
+ }
+ return s
+}
+
+func (b *Backend) sanitizeLogLine(msg string) string {
+ sanitized := b.redactStoredSecrets(msg)
+ decoded := sanitized
+ for i := 0; i < 3; i++ {
+ if runtimeLogSecretField.MatchString(decoded) {
+ return "[REDACTED_LOG_LINE]"
+ }
+ for _, rawURL := range runtimeLogURL.FindAllString(decoded, -1) {
+ if strings.Contains(rawURL, "?") {
+ return "[REDACTED_LOG_LINE]"
+ }
+ }
+ if b.redactStoredSecrets(decoded) != decoded {
+ return "[REDACTED_LOG_LINE]"
+ }
+ next, err := url.QueryUnescape(decoded)
+ if err != nil {
+ // A progress value such as "50%" must not prevent redaction of an
+ // encoded credential elsewhere on the same line.
+ next = runtimeLogPercentEscape.ReplaceAllStringFunc(decoded, func(escape string) string {
+ value, _ := url.QueryUnescape(escape)
+ return value
+ })
+ }
+ if next == decoded {
+ break
+ }
+ decoded = next
+ }
+ return sanitized
+}
+
+// Logf writes an informational line to trace.log.
+func (b *Backend) Logf(format string, args ...any) {
+ b.logInfo(fmt.Sprintf(format, args...))
+}
+
+func (b *Backend) logInfo(msg string) {
+ b.writeLogLine("INFO", msg)
+}
+
+func (b *Backend) logError(op string, err error) {
+ if err == nil {
+ return
+ }
+ b.writeLogLine("ERROR", op+": "+err.Error()+siteErrorDetail(err))
+}
+
+// LogUserError logs an error the UI displayed. The same line within a minute
+// is written once, so a page that keeps failing does not flood the log.
+func (b *Backend) LogUserError(err error) {
+ if err == nil {
+ return
+ }
+ line := "ui: " + err.Error() + siteErrorDetail(err)
+ now := time.Now()
+ b.logMu.Lock()
+ repeated := line == b.lastUserError && now.Sub(b.lastUserErrorAt) < time.Minute
+ if !repeated {
+ b.lastUserError, b.lastUserErrorAt = line, now
+ }
+ b.logMu.Unlock()
+ if !repeated {
+ b.writeLogLine("ERROR", line)
+ }
+}
+
+// siteErrorDetail adds what the user-facing message leaves out: the endpoint
+// path (never its query, which can carry signatures) and, for a response that
+// did not match the expected fields, the decoder's reason (field and type).
+func siteErrorDetail(err error) string {
+ var se *site.Error
+ if !errors.As(err, &se) {
+ return ""
+ }
+ var detail string
+ if se.Endpoint != "" {
+ if u, perr := url.Parse(se.Endpoint); perr == nil && u.Path != "" {
+ detail += " endpoint=" + u.Path
+ }
+ }
+ if se.Kind == site.ErrKindSchemaChanged && se.Err != nil {
+ cause := []rune(se.Err.Error())
+ if len(cause) > 240 { // Go prints a whole anonymous struct type here
+ cause = append(cause[:240], '…')
+ }
+ detail += " cause=" + string(cause)
+ }
+ return detail
+}
+
+func (b *Backend) writeLogLine(level, msg string) {
+ if b.logPath == "" {
+ return
+ }
+ sanitized := b.sanitizeLogLine(msg)
+ line := fmt.Sprintf("%s [%s] %s\n", time.Now().UTC().Format(time.RFC3339), level, sanitized)
+
+ b.logMu.Lock()
+ defer b.logMu.Unlock()
+ if level == "ERROR" {
+ b.recentErrors = append(b.recentErrors, RecentError{At: time.Now().UTC().Format(time.RFC3339), Message: sanitized})
+ if len(b.recentErrors) > maxRecentErrors {
+ b.recentErrors = b.recentErrors[len(b.recentErrors)-maxRecentErrors:]
+ }
+ }
+ if b.logMirror != nil {
+ _, _ = io.WriteString(b.logMirror, line)
+ }
+ f, err := os.OpenFile(b.logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
+ if err != nil {
+ return
+ }
+ _, _ = f.WriteString(line)
+ _ = f.Close()
+}
+
+// taskStatusLog remembers the last logged status of each download task.
+// Progress updates arrive about once a second while a task runs; the log
+// records only status changes so it stays readable.
+type taskStatusLog struct {
+ mu sync.Mutex
+ last map[string]string
+}
+
+func newTaskStatusLog() *taskStatusLog {
+ return &taskStatusLog{last: map[string]string{}}
+}
+
+// changed reports whether status differs from the last one logged for id.
+func (l *taskStatusLog) changed(id, status string) bool {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ if l.last[id] == status {
+ return false
+ }
+ if status == "completed" || status == "canceled" {
+ delete(l.last, id)
+ } else {
+ l.last[id] = status
+ }
+ return true
+}
diff --git a/internal/service/open_link.go b/internal/service/open_link.go
new file mode 100644
index 0000000..ab7363e
--- /dev/null
+++ b/internal/service/open_link.go
@@ -0,0 +1,960 @@
+package service
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "fmt"
+ "image"
+ _ "image/gif"
+ _ "image/jpeg"
+ "image/png"
+ "net/url"
+ "os"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+
+ "golang.org/x/image/draw"
+ _ "golang.org/x/image/webp"
+
+ "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/storage"
+)
+
+const (
+ maxPreviewMediaBytes = 64 * 1024 * 1024 // 64 MiB safety cap for uncached note BGM / clip preview
+ maxPreviewDirBytes = 256 * 1024 * 1024 // 256 MiB total cache budget for preview directory
+ maxPreviewDirFiles = 32 // max staged preview files kept simultaneously
+)
+
+// Resolve dispatches user input via site.Registry after enforcing per-site login gates with zero pre-auth network requests.
+func (b *Backend) Resolve(ctx context.Context, rawInput string) (site.ResolveTarget, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return site.ResolveTarget{}, err
+ }
+ siteID, normalized, err := b.registry.DetectSite(rawInput)
+ if err != nil {
+ return site.ResolveTarget{}, err
+ }
+ if err := b.requireSiteLogin(siteID); err != nil {
+ return site.ResolveTarget{}, err
+ }
+ res, ok := b.registry.Resolver(siteID)
+ if !ok {
+ return site.ResolveTarget{}, &site.Error{
+ Site: siteID,
+ Kind: site.ErrKindUnavailable,
+ Unsupported: true,
+ Message: fmt.Sprintf("当前尚未启用 %s 站点解析器", siteID.DisplayName()),
+ }
+ }
+ target, err := res.Resolve(ctx, normalized)
+ if err != nil {
+ return target, err
+ }
+ if target.Site == "" {
+ target.Site = siteID
+ }
+ return target, nil
+}
+
+// OpenLink resolves user input across supported sites after enforcing per-site login gates,
+// fetches detail metadata, records sanitized navigation history, and returns OpenLinkResult.
+func (b *Backend) OpenLink(ctx context.Context, rawInput string) (*OpenLinkResult, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return nil, err
+ }
+ siteID, normalizedInput, err := b.registry.DetectSite(rawInput)
+ if err != nil {
+ return nil, err
+ }
+ if err := b.requireSiteLogin(siteID); err != nil {
+ return nil, err
+ }
+
+ if siteID == site.Douyin {
+ return b.openDouyinLink(ctx, normalizedInput)
+ }
+
+ target, err := b.bili.ResolveLink(ctx, normalizedInput)
+ if err != nil {
+ b.logError("OpenLink.Resolve", err)
+ return nil, err
+ }
+
+ var roomStr string
+ if target.RoomID > 0 {
+ roomStr = strconv.FormatInt(target.RoomID, 10)
+ }
+ siteTarget := site.ResolveTarget{
+ Site: site.Bilibili,
+ Kind: target.Kind,
+ ID: target.ID,
+ RoomID: roomStr,
+ NumericAID: target.AID,
+ Page: target.Page,
+ NumericRoomID: target.RoomID,
+ NumericMid: target.Mid,
+ CanonicalURL: target.CanonicalURL,
+ Unsupported: target.Unsupported,
+ Reason: target.Reason,
+ }
+ out := &OpenLinkResult{
+ Site: string(site.Bilibili),
+ SiteTarget: &siteTarget,
+ Target: target,
+ }
+
+ switch target.Kind {
+ case "video":
+ vd, err := b.bili.VideoDetail(ctx, target.ID)
+ if err != nil {
+ b.logError("OpenLink.VideoDetail", err)
+ return nil, err
+ }
+ out.Video = &vd
+ if item, ok, _ := b.lib.GetItem(vd.BVID); ok {
+ out.CachedItem = &item
+ }
+ if err := b.lib.UpsertFeedEntry(library.FeedEntry{
+ Site: "bilibili",
+ Kind: "video",
+ RawID: vd.BVID,
+ Mid: vd.Author.Mid,
+ AuthorName: vd.Author.Name,
+ AuthorFace: vd.Author.Face,
+ Title: vd.Title,
+ Summary: vd.Desc,
+ CoverURL: vd.Cover,
+ CanonicalURL: vd.CanonicalURL,
+ PubTs: vd.PubTs,
+ }); err != nil {
+ return nil, &bilibili.SiteError{Site: site.Bilibili, Kind: "storage", Message: "解析记录写入失败", Err: err}
+ }
+ out.HistoryThumbs = &HistoryThumbJob{Site: "bilibili", Kind: "video", ID: vd.BVID, AvatarURL: vd.Author.Face, CoverURL: vd.Cover}
+ if err := b.history.Record(storage.HistoryEntry{
+ Site: "bilibili",
+ Kind: "video",
+ ID: vd.BVID,
+ Title: vd.Title,
+ Subtitle: vd.Author.Name,
+ CanonicalURL: vd.CanonicalURL,
+ DurationText: formatHistoryDuration(vd.Duration),
+ }); err != nil {
+ return nil, &bilibili.SiteError{Site: site.Bilibili, Kind: "storage", Message: "历史记录写入失败", Err: err}
+ }
+
+ case "user":
+ space, err := b.bili.UserCard(ctx, target.Mid)
+ if err != nil {
+ b.logError("OpenLink.UserCard", err)
+ return nil, err
+ }
+ out.User = &space
+ b.recordAccountWorks(site.Bilibili, strconv.FormatInt(space.Mid, 10), space.ArchiveCount)
+ if dyns, dErr := b.bili.UserDynamics(ctx, target.Mid, ""); dErr == nil {
+ out.UserDynamics = &dyns
+ } else {
+ b.logError("OpenLink.UserDynamics", dErr)
+ out.UserDynamicsError = dErr.Error()
+ }
+ userID := fmt.Sprintf("%d", space.Mid)
+ out.HistoryThumbs = &HistoryThumbJob{Site: "bilibili", Kind: "user", ID: userID, AvatarURL: space.Face}
+ if err := b.history.Record(storage.HistoryEntry{
+ Site: "bilibili",
+ Kind: "user",
+ ID: userID,
+ Title: space.Name,
+ Subtitle: space.Sign,
+ CanonicalURL: space.CanonicalURL,
+ }); err != nil {
+ return nil, &bilibili.SiteError{Site: site.Bilibili, Kind: "storage", Message: "历史记录写入失败", Err: err}
+ }
+
+ case "dynamic":
+ dyn, err := b.bili.DynamicDetail(ctx, target.ID)
+ if err != nil {
+ b.logError("OpenLink.DynamicDetail", err)
+ return nil, err
+ }
+ out.Dynamic = &dyn
+ if item, ok, _ := b.lib.GetItem(library.CanonicalItemKey("bilibili", "dynamic", dyn.ID)); ok {
+ out.CachedItem = &item
+ }
+ var coverURL string
+ if len(dyn.Images) > 0 {
+ coverURL = dyn.Images[0].URL
+ } else if len(dyn.Videos) > 0 {
+ coverURL = dyn.Videos[0].Cover
+ }
+ if err := b.lib.UpsertFeedEntry(library.FeedEntry{
+ Site: "bilibili",
+ Kind: "dynamic",
+ RawID: dyn.ID,
+ Mid: dyn.Author.Mid,
+ AuthorName: dyn.Author.Name,
+ AuthorFace: dyn.Author.Face,
+ Title: dyn.Title,
+ Summary: dyn.Text,
+ CoverURL: coverURL,
+ CanonicalURL: dyn.CanonicalURL,
+ PubTs: dyn.PubTs,
+ }); err != nil {
+ return nil, &bilibili.SiteError{Site: site.Bilibili, Kind: "storage", Message: "解析记录写入失败", Err: err}
+ }
+ out.HistoryThumbs = &HistoryThumbJob{Site: "bilibili", Kind: "dynamic", ID: dyn.ID, AvatarURL: dyn.Author.Face, CoverURL: coverURL}
+ if err := b.history.Record(storage.HistoryEntry{
+ Site: "bilibili",
+ Kind: "dynamic",
+ ID: dyn.ID,
+ Title: dyn.Title,
+ Subtitle: dyn.Author.Name,
+ CanonicalURL: dyn.CanonicalURL,
+ }); err != nil {
+ return nil, &bilibili.SiteError{Site: site.Bilibili, Kind: "storage", Message: "历史记录写入失败", Err: err}
+ }
+
+ case "live":
+ room, err := b.live.OpenRoom(ctx, target.RoomID)
+ if err != nil {
+ b.logError("OpenLink.LiveRoom", err)
+ return nil, err
+ }
+ out.LiveRoom = &room
+ space, err := b.bili.UserCard(ctx, room.UID)
+ if err != nil {
+ b.logError("OpenLink.LiveUserCard", err)
+ return nil, err
+ }
+ out.User = &space
+ b.recordAccountWorks(site.Bilibili, strconv.FormatInt(space.Mid, 10), space.ArchiveCount)
+ if dyns, dErr := b.bili.UserDynamics(ctx, room.UID, ""); dErr == nil {
+ out.UserDynamics = &dyns
+ } else {
+ b.logError("OpenLink.LiveUserDynamics", dErr)
+ out.UserDynamicsError = dErr.Error()
+ }
+ liveID := fmt.Sprintf("live:%d", room.RoomID)
+ out.HistoryThumbs = &HistoryThumbJob{Site: "bilibili", Kind: "live", ID: liveID, AvatarURL: space.Face, CoverURL: room.Cover}
+ if err := b.history.Record(storage.HistoryEntry{
+ Site: "bilibili",
+ Kind: "live",
+ ID: liveID,
+ Title: room.Title,
+ Subtitle: room.Uname,
+ CanonicalURL: fmt.Sprintf("https://live.bilibili.com/%d", room.RoomID),
+ }); err != nil {
+ return nil, &bilibili.SiteError{Site: site.Bilibili, Kind: "storage", Message: "历史记录写入失败", Err: err}
+ }
+ }
+
+ return out, nil
+}
+
+func (b *Backend) openDouyinLink(ctx context.Context, normalizedInput string) (*OpenLinkResult, error) {
+ target, err := b.douyin.ResolveLink(ctx, normalizedInput)
+ if err != nil {
+ b.logError("OpenLink.DouyinResolve", err)
+ return nil, err
+ }
+ out := &OpenLinkResult{
+ Site: string(site.Douyin),
+ SiteTarget: &target,
+ Target: bilibili.ResolveTarget{
+ Kind: target.Kind,
+ ID: target.ID,
+ CanonicalURL: target.CanonicalURL,
+ Unsupported: target.Unsupported,
+ Reason: target.Reason,
+ },
+ }
+
+ switch target.Kind {
+ case "video", "note":
+ wv, err := b.DouyinWork(ctx, target.ID)
+ if err != nil {
+ return nil, err
+ }
+ out.DouyinWork = wv
+ out.CachedItem = wv.CachedItem
+ feedKind := "video"
+ histKind := "video"
+ if wv.Kind == douyin.WorkKindNote {
+ feedKind = "dynamic"
+ histKind = "note"
+ }
+ out.Target.Kind = histKind
+ out.SiteTarget.Kind = histKind
+ if err := b.lib.UpsertFeedEntry(library.FeedEntry{
+ Site: "douyin",
+ Kind: feedKind,
+ RawID: wv.ID,
+ AuthorUID: wv.Author.SecUID,
+ AuthorName: wv.Author.Nickname,
+ AuthorFace: wv.Author.AvatarURL,
+ Title: wv.Title,
+ Summary: wv.Desc,
+ CoverURL: wv.CoverURL,
+ CanonicalURL: wv.CanonicalURL,
+ PubTs: wv.CreateTime,
+ }); err != nil {
+ return nil, &site.Error{Site: site.Douyin, Kind: "storage", Message: "解析记录写入失败", Err: err}
+ }
+ out.HistoryThumbs = &HistoryThumbJob{
+ Site: "douyin",
+ Kind: histKind,
+ ID: wv.ID,
+ AvatarURL: wv.Author.AvatarURL,
+ CoverURL: wv.CoverURL,
+ }
+ if err := b.history.Record(storage.HistoryEntry{
+ Site: "douyin",
+ Kind: histKind,
+ ID: wv.ID,
+ Title: wv.Title,
+ Subtitle: wv.Author.Nickname,
+ CanonicalURL: wv.CanonicalURL,
+ DurationText: formatHistoryDuration(wv.DurationSec),
+ }); err != nil {
+ return nil, &site.Error{Site: site.Douyin, Kind: "storage", Message: "历史记录写入失败", Err: err}
+ }
+
+ case "user":
+ secUID := firstNonEmpty(target.SecUID, target.ID)
+ uv, err := b.DouyinUser(ctx, secUID)
+ if err != nil {
+ return nil, err
+ }
+ out.DouyinUser = uv
+ out.Target.ID = uv.SecUID
+ out.SiteTarget.ID = uv.SecUID
+ out.SiteTarget.SecUID = uv.SecUID
+ out.DouyinUserWorks, out.DouyinUserWorksError = b.firstDouyinUserWorks(ctx, uv)
+ out.HistoryThumbs = &HistoryThumbJob{
+ Site: "douyin",
+ Kind: "user",
+ ID: uv.SecUID,
+ AvatarURL: uv.AvatarURL,
+ }
+ if err := b.history.Record(storage.HistoryEntry{
+ Site: "douyin",
+ Kind: "user",
+ ID: uv.SecUID,
+ Title: uv.Nickname,
+ Subtitle: uv.Signature,
+ CanonicalURL: uv.CanonicalURL,
+ }); err != nil {
+ return nil, &site.Error{Site: site.Douyin, Kind: "storage", Message: "历史记录写入失败", Err: err}
+ }
+
+ case "live":
+ webRID := firstNonEmpty(target.WebRID, target.ID)
+ lv, err := b.DouyinLive(ctx, webRID)
+ if err != nil {
+ return nil, err
+ }
+ out.DouyinLive = lv
+ if lv.OwnerSecUID != "" {
+ if uv, uErr := b.DouyinUser(ctx, lv.OwnerSecUID); uErr == nil {
+ if lv.State != nil {
+ uv.LiveRoom = lv.State
+ if lv.LiveStatus == 1 {
+ uv.LiveStatus = 1
+ }
+ }
+ out.DouyinUser = uv
+ out.DouyinUserWorks, out.DouyinUserWorksError = b.firstDouyinUserWorks(ctx, uv)
+ }
+ }
+ liveID := "live:" + lv.WebRID
+ out.HistoryThumbs = &HistoryThumbJob{
+ Site: "douyin",
+ Kind: "live",
+ ID: liveID,
+ AvatarURL: lv.OwnerAvatar,
+ CoverURL: lv.CoverURL,
+ }
+ if err := b.history.Record(storage.HistoryEntry{
+ Site: "douyin",
+ Kind: "live",
+ ID: liveID,
+ Title: firstNonEmpty(lv.Title, lv.OwnerName+"的直播间"),
+ Subtitle: lv.OwnerName,
+ CanonicalURL: lv.CanonicalURL,
+ }); err != nil {
+ return nil, &site.Error{Site: site.Douyin, Kind: "storage", Message: "历史记录写入失败", Err: err}
+ }
+ }
+
+ return out, nil
+}
+
+// firstDouyinUserWorks loads the first page of a user's works for the user
+// page. A private account still shows its works to the followers it approved,
+// which the signed-in account may be, so the works are always asked for: when
+// they come back the page shows them (IsPrivate is cleared, PrivateVisible set);
+// otherwise it says the account is private, without an error.
+func (b *Backend) firstDouyinUserWorks(ctx context.Context, uv *DouyinUserView) (*DouyinUserWorksPage, string) {
+ wp, err := b.DouyinUserWorks(ctx, uv.SecUID, "")
+ if uv.IsPrivate {
+ if err == nil && wp != nil && len(wp.Works) > 0 {
+ uv.IsPrivate = false
+ uv.PrivateVisible = true
+ return wp, ""
+ }
+ // Only an empty list or a refusal means the works are not visible;
+ // risk control, rate limits, an expired login or the network are
+ // reported as they are, with a retry.
+ if err == nil || site.IsKind(err, site.ErrKindForbidden) || site.IsKind(err, site.ErrKindUnavailable) {
+ return nil, ""
+ }
+ return nil, err.Error()
+ }
+ if err != nil {
+ return nil, err.Error()
+ }
+ return wp, ""
+}
+
+func formatHistoryDuration(seconds int) string {
+ if seconds <= 0 {
+ return ""
+ }
+ h := seconds / 3600
+ m := (seconds % 3600) / 60
+ s := seconds % 60
+ if h > 0 {
+ return fmt.Sprintf("%d:%02d:%02d", h, m, s)
+ }
+ return fmt.Sprintf("%02d:%02d", m, s)
+}
+
+// FetchHistoryThumbs downloads and stores the thumbnails of a recent-parse
+// entry after OpenLink returned. Image failures leave the placeholder; an
+// entry removed meanwhile gets nothing.
+func (b *Backend) FetchHistoryThumbs(ctx context.Context, job HistoryThumbJob) error {
+ jobSite, err := normalizeSiteID(job.Site)
+ if err != nil {
+ return err
+ }
+ if err := b.requireSiteLogin(jobSite); err != nil {
+ return err
+ }
+ if b.history == nil {
+ return nil
+ }
+ var thumbs []storage.HistoryThumbnail
+ for _, want := range []struct{ role, url string }{{"avatar", job.AvatarURL}, {"cover", job.CoverURL}} {
+ if t := b.fetchHistoryThumbForSite(ctx, jobSite, want.role, want.url); len(t.Data) > 0 {
+ thumbs = append(thumbs, t)
+ }
+ }
+ if job.Kind == "user" && b.subs != nil {
+ if _, ok := b.subs.OwnerOf(string(jobSite), job.ID); ok {
+ b.rememberAccountAvatar(string(jobSite), job.ID, job.AvatarURL)
+ }
+ }
+ if len(thumbs) == 0 {
+ return nil
+ }
+ return b.history.AttachThumbs(string(jobSite), job.Kind, job.ID, thumbs...)
+}
+
+func (b *Backend) fetchHistoryThumb(ctx context.Context, role, rawURL string) storage.HistoryThumbnail {
+ return b.fetchHistoryThumbForSite(ctx, site.Bilibili, role, rawURL)
+}
+
+func (b *Backend) fetchHistoryThumbForSite(ctx context.Context, siteID site.ID, role, rawURL string) storage.HistoryThumbnail {
+ rawURL = strings.TrimSpace(rawURL)
+ if rawURL == "" || b.history == nil || b.requireSiteLogin(siteID) != nil {
+ return storage.HistoryThumbnail{}
+ }
+ if strings.HasPrefix(rawURL, "http://") && !strings.HasPrefix(rawURL, "http://127.0.0.1") && !strings.HasPrefix(rawURL, "http://localhost") {
+ rawURL = "https://" + strings.TrimPrefix(rawURL, "http://")
+ }
+ var raw []byte
+ var err error
+ switch siteID {
+ case site.Douyin:
+ if b.douyin == nil {
+ return storage.HistoryThumbnail{}
+ }
+ raw, _, err = b.douyin.FetchImageLimited(ctx, rawURL, storage.MaxHistoryThumbBytes)
+ default:
+ if b.bili == nil {
+ return storage.HistoryThumbnail{}
+ }
+ raw, err = b.bili.FetchImageLimited(ctx, rawURL, storage.MaxHistoryThumbBytes)
+ }
+ if err != nil || len(raw) == 0 || len(raw) > storage.MaxHistoryThumbBytes {
+ return storage.HistoryThumbnail{}
+ }
+ cfg, _, err := image.DecodeConfig(bytes.NewReader(raw))
+ if err != nil || cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width)*int64(cfg.Height) > 24_000_000 {
+ return storage.HistoryThumbnail{}
+ }
+ img, _, err := image.Decode(bytes.NewReader(raw))
+ if err != nil {
+ return storage.HistoryThumbnail{}
+ }
+ w, h := cfg.Width, cfg.Height
+ maxSide := 640
+ if role == "avatar" {
+ maxSide = 128
+ }
+ if w > maxSide {
+ h, w = max(1, h*maxSide/w), maxSide
+ }
+ if h > maxSide {
+ w, h = max(1, w*maxSide/h), maxSide
+ }
+ small := image.NewRGBA(image.Rect(0, 0, w, h))
+ draw.ApproxBiLinear.Scale(small, small.Bounds(), img, img.Bounds(), draw.Src, nil)
+ var encoded bytes.Buffer
+ if err := png.Encode(&encoded, small); err != nil {
+ return storage.HistoryThumbnail{}
+ }
+ return storage.HistoryThumbnail{Role: role, Ext: ".png", Data: encoded.Bytes()}
+}
+
+// HistoryThumbPath resolves a local cached parse-history thumbnail inside /thumbs/.
+func (b *Backend) HistoryThumbPath(name string) (string, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return "", err
+ }
+ if b.history == nil {
+ return "", fmt.Errorf("service: history store unavailable")
+ }
+ return b.history.ThumbPath(name)
+}
+
+// ListHistory returns the recent sanitized navigation history entries.
+func (b *Backend) ListHistory() []storage.HistoryEntry {
+ if b.requireAnyLogin() != nil {
+ return nil
+ }
+ return b.history.List()
+}
+
+// ClearHistory clears the navigation history.
+func (b *Backend) ClearHistory() error {
+ if err := b.requireAnyLogin(); err != nil {
+ return err
+ }
+ return b.history.Clear()
+}
+
+// RemoveHistory removes a single history entry by kind and id.
+func (b *Backend) RemoveHistory(kind, id string) error {
+ if err := b.requireAnyLogin(); err != nil {
+ return err
+ }
+ return b.history.Remove(kind, id)
+}
+
+// RemoveHistoryForSite deletes a single recent-parse history item scoped to (siteID, kind, id).
+func (b *Backend) RemoveHistoryForSite(siteID, kind, id string) error {
+ if err := b.requireAnyLogin(); err != nil {
+ return err
+ }
+ return b.history.RemoveBySite(siteID, kind, id)
+}
+
+// FetchImage fetches a whitelisted Bilibili or Douyin cover/avatar/note image without sending Cookie.
+func (b *Backend) FetchImage(ctx context.Context, rawURL string) ([]byte, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return nil, err
+ }
+ imgSite := b.detectImageSite(rawURL)
+ if err := b.requireSiteLogin(imgSite); err != nil {
+ return nil, err
+ }
+ if imgSite == site.Douyin {
+ data, _, err := b.douyin.FetchImage(ctx, rawURL)
+ return data, err
+ }
+ return b.bili.FetchImage(ctx, rawURL)
+}
+
+func (b *Backend) detectImageSite(rawURL string) site.ID {
+ u, err := url.Parse(strings.TrimSpace(rawURL))
+ if err != nil || u.Host == "" {
+ return site.Bilibili
+ }
+ host := strings.ToLower(u.Hostname())
+ if site.MatchDomainSuffix(host, site.DefaultDouyinMediaHosts()) {
+ return site.Douyin
+ }
+ if id, ok := site.DetectHostSite(host); ok {
+ return id
+ }
+ if host == "127.0.0.1" || host == "localhost" || host == "::1" {
+ if b.douyin != nil {
+ ep := b.douyin.Endpoints()
+ for _, candidate := range []string{ep.ProfileSelf, ep.AwemeDetail, ep.LiveWebEnter} {
+ if cu, cErr := url.Parse(candidate); cErr == nil && strings.EqualFold(cu.Host, u.Host) {
+ if strings.HasPrefix(u.Path, "/bfs/") {
+ return site.Bilibili
+ }
+ return site.Douyin
+ }
+ }
+ }
+ if strings.HasPrefix(u.Path, "/douyin") || strings.HasPrefix(u.Path, "/obj/") || strings.HasPrefix(u.Path, "/tos-") {
+ return site.Douyin
+ }
+ if b.douyinCred != nil && b.douyinCred.HasActiveCredential() && (b.cred == nil || !b.cred.HasActiveCredential()) {
+ return site.Douyin
+ }
+ }
+ return site.Bilibili
+}
+
+func (b *Backend) UserDynamicsPage(ctx context.Context, mid int64, offset string) (bilibili.UserDynamicsPage, error) {
+ if err := b.requireSiteLogin(site.Bilibili); err != nil {
+ return bilibili.UserDynamicsPage{}, err
+ }
+ return b.bili.UserDynamics(ctx, mid, offset)
+}
+
+func (b *Backend) UserVideosPage(ctx context.Context, mid int64, page int) (bilibili.UserVideosPage, error) {
+ if err := b.requireSiteLogin(site.Bilibili); err != nil {
+ return bilibili.UserVideosPage{}, err
+ }
+ res, err := b.bili.UserVideos(ctx, mid, page, 30, "pubdate", "")
+ if err == nil && page <= 1 {
+ b.recordAccountWorks(site.Bilibili, strconv.FormatInt(mid, 10), res.Total)
+ }
+ return res, err
+}
+
+func (b *Backend) preferredDouyinCodec() string {
+ dl := b.settings.Get().Download
+ for _, c := range dl.CodecOrder {
+ switch strings.ToLower(strings.TrimSpace(c)) {
+ case "hevc", "h265", "bytevc1":
+ return "hevc"
+ case "avc", "h264":
+ return "avc"
+ }
+ }
+ if strings.EqualFold(dl.PreferredVideoCodec, "hevc") {
+ return "hevc"
+ }
+ return "avc"
+}
+
+// DouyinWork fetches and maps a single Douyin video or image/mixed note post.
+func (b *Backend) DouyinWork(ctx context.Context, awemeID string) (*DouyinWorkView, error) {
+ if err := b.requireSiteLogin(site.Douyin); err != nil {
+ return nil, err
+ }
+ detail, err := b.douyin.GetWorkDetail(ctx, awemeID, douyin.StreamSelectOptions{
+ PreferredCodec: b.preferredDouyinCodec(),
+ })
+ if err != nil {
+ b.logError("DouyinWork", err)
+ return nil, err
+ }
+ var cached *library.ItemMetadata
+ cacheKey := douyinCacheKeyForKind(detail.Kind, detail.ID)
+ if cacheKey != "" {
+ if item, ok, _ := b.lib.GetItem(cacheKey); ok {
+ cached = &item
+ }
+ }
+ if detail.Author.SecUID != "" && detail.Author.WebRID != "" {
+ b.syncDouyinAccountWebRID(detail.Author.SecUID, detail.Author.WebRID)
+ }
+ return mapDouyinWorkView(detail, cached), nil
+}
+
+// DouyinUser fetches a Douyin creator's profile and maps optional live banner state.
+func (b *Backend) DouyinUser(ctx context.Context, secUID string) (*DouyinUserView, error) {
+ if err := b.requireSiteLogin(site.Douyin); err != nil {
+ return nil, err
+ }
+ targetSecUID := strings.TrimSpace(secUID)
+ if targetSecUID == "" || strings.EqualFold(targetSecUID, "self") || targetSecUID == "/user/self" {
+ targetSecUID = b.douyinCred.Status().SecUID
+ if targetSecUID == "" {
+ selfProf, sErr := b.douyin.GetSelfProfile(ctx)
+ if sErr != nil {
+ return nil, sErr
+ }
+ targetSecUID = selfProf.SecUID
+ }
+ }
+ prof, err := b.douyin.GetUserProfile(ctx, targetSecUID)
+ if err != nil {
+ b.logError("DouyinUser", err)
+ return nil, err
+ }
+ if b.subs != nil {
+ _ = b.subs.UpdateAccountSnapshot(string(site.Douyin), prof.SecUID, prof.Nickname, prof.AvatarURL, prof.UniqueID)
+ }
+ b.recordAccountWorks(site.Douyin, prof.SecUID, prof.AwemeCount)
+ if prof.WebRID != "" {
+ b.syncDouyinAccountWebRID(prof.SecUID, prof.WebRID)
+ }
+ if b.live != nil && (prof.WebRID != "" || prof.RoomID != "") {
+ b.live.ObserveAccountLiveHint(site.Douyin, prof.SecUID, prof.WebRID, prof.RoomID)
+ }
+ var liveState *LiveAccountState
+ if prof.LiveStatus == 1 {
+ st := LiveAccountState{
+ Site: string(site.Douyin),
+ AccountKey: formatAccountKey(site.Douyin, prof.SecUID),
+ UID: prof.SecUID,
+ RoomID: prof.RoomID,
+ WebRID: prof.WebRID,
+ Uname: prof.Nickname,
+ Face: prof.AvatarURL,
+ LiveStatus: 1,
+ StatusText: "直播中",
+ Transport: string(site.LiveTransportHTTPFLV),
+ }
+ if prof.RoomID != "" {
+ st.RecordingKey = "douyin:live:" + prof.RoomID
+ }
+ if prof.WebRID != "" && b.live != nil {
+ if rs, lErr := b.live.CheckAccountLiveStatus(ctx, site.Douyin, prof.SecUID, prof.WebRID, false); lErr == nil {
+ mapped := mapRoomToAccountState(rs)
+ if mapped.Uname == "" {
+ mapped.Uname = prof.Nickname
+ }
+ if mapped.Face == "" {
+ mapped.Face = prof.AvatarURL
+ }
+ st = mapped
+ }
+ }
+ liveState = &st
+ }
+ return mapDouyinUserView(prof, liveState), nil
+}
+
+// DouyinUserWorks fetches one paginated grid page of a Douyin creator's works.
+func (b *Backend) DouyinUserWorks(ctx context.Context, secUID, cursor string) (*DouyinUserWorksPage, error) {
+ if err := b.requireSiteLogin(site.Douyin); err != nil {
+ return nil, err
+ }
+ page, err := b.douyin.ListUserPosts(ctx, douyin.UserPostsRequest{
+ SecUID: strings.TrimSpace(secUID),
+ MaxCursor: strings.TrimSpace(cursor),
+ StreamOptions: douyin.StreamSelectOptions{PreferredCodec: b.preferredDouyinCodec()},
+ })
+ if err != nil {
+ b.logError("DouyinUserWorks", err)
+ return nil, err
+ }
+ cards := make([]DouyinWorkCardDTO, 0, len(page.Works))
+ for _, w := range page.Works {
+ cards = append(cards, mapDouyinWorkCard(w))
+ }
+ return &DouyinUserWorksPage{
+ Works: cards,
+ NextCursor: page.NextCursor,
+ HasMore: page.HasMore,
+ UncertainEmpty: page.UncertainEmpty,
+ UncertainReason: page.UncertainReason,
+ }, nil
+}
+
+// DouyinLive queries a Douyin live room by web_rid and returns normalized room and anchor state.
+func (b *Backend) DouyinLive(ctx context.Context, webRID string) (*DouyinLiveView, error) {
+ if err := b.requireSiteLogin(site.Douyin); err != nil {
+ return nil, err
+ }
+ detail, err := b.douyin.EnterLiveRoom(ctx, strings.TrimSpace(webRID), "")
+ if err != nil {
+ b.logError("DouyinLive", err)
+ return nil, err
+ }
+ prefWebRID := detail.PreferredWebRID()
+ if detail.OwnerSecUID != "" && prefWebRID != "" {
+ b.syncDouyinAccountWebRID(detail.OwnerSecUID, prefWebRID)
+ }
+ if b.live != nil && detail.OwnerSecUID != "" {
+ b.live.ObserveAccountLiveHint(site.Douyin, detail.OwnerSecUID, prefWebRID, detail.RoomID)
+ }
+ liveStatus := 0
+ statusText := "未开播"
+ if detail.RoomStatus == 2 {
+ liveStatus = 1
+ if detail.AudioOnly {
+ statusText = "纯语音直播"
+ } else {
+ statusText = "直播中"
+ }
+ }
+ acctState := &LiveAccountState{
+ Site: string(site.Douyin),
+ AccountKey: formatAccountKey(site.Douyin, detail.OwnerSecUID),
+ RecordingKey: detail.LiveDedupeKey(),
+ UID: detail.OwnerSecUID,
+ RoomID: detail.RoomID,
+ WebRID: prefWebRID,
+ Uname: detail.OwnerNickname,
+ Face: detail.OwnerAvatar,
+ Title: detail.Title,
+ Cover: detail.CoverURL,
+ AreaName: detail.AreaName,
+ LiveStatus: liveStatus,
+ LiveSince: detail.LiveSince,
+ StatusText: statusText,
+ Transport: string(site.LiveTransportHTTPFLV),
+ AudioOnly: detail.AudioOnly,
+ }
+ if b.live != nil && detail.OwnerSecUID != "" {
+ if cached, ok := b.live.CachedAccountState(site.Douyin, detail.OwnerSecUID); ok {
+ if len(cached.Incidents) > 0 {
+ acctState.Incidents = append([]library.LiveIncident(nil), cached.Incidents...)
+ }
+ if cached.Recording {
+ acctState.Recording = true
+ if cached.Transport != "" {
+ acctState.Transport = cached.Transport
+ }
+ acctState.AudioOnly = acctState.AudioOnly || cached.AudioOnly
+ acctState.RecordSession = cached.RecordSession
+ acctState.RecordDurationSec = cached.RecordDurationSec
+ acctState.RecordSpeedBps = cached.RecordSpeedBps
+ acctState.RecordBytes = cached.RecordBytes
+ acctState.RecordSegments = cached.RecordSegments
+ acctState.RecordItemDir = cached.RecordItemDir
+ acctState.RecordPartPath = firstNonEmpty(cached.RecordPartPath, resolveRecordingPartPath(cached.RecordItemDir))
+ acctState.RecordPartIndex = cached.RecordPartIndex
+ acctState.RecordPartBytes = cached.RecordPartBytes
+ acctState.RecordPartReady = cached.RecordPartReady
+ acctState.PreviewSupported = cached.PreviewSupported
+ acctState.PreviewReason = cached.PreviewReason
+ }
+ }
+ }
+ canonicalURL := "https://live.douyin.com/" + prefWebRID
+ return &DouyinLiveView{
+ OwnerSecUID: detail.OwnerSecUID,
+ OwnerUID: detail.OwnerUID,
+ OwnerName: detail.OwnerNickname,
+ OwnerAvatar: detail.OwnerAvatar,
+ WebRID: prefWebRID,
+ RoomID: detail.RoomID,
+ LiveStatus: liveStatus,
+ StatusText: statusText,
+ Title: detail.Title,
+ CoverURL: detail.CoverURL,
+ AreaName: detail.AreaName,
+ LiveSince: detail.LiveSince,
+ AudioOnly: detail.AudioOnly,
+ CanonicalURL: canonicalURL,
+ State: acctState,
+ }, nil
+}
+
+// StagePreviewMedia downloads a whitelisted CDN audio/video clip (e.g. uncached Douyin note BGM
+// or note video page) without sending Cookie into /cache/preview/ and returns its local file path
+// for playback via internal/player.
+func (b *Backend) StagePreviewMedia(ctx context.Context, siteID, rawURL, ext string) (string, error) {
+ id, err := normalizeSiteID(siteID)
+ if err != nil {
+ return "", err
+ }
+ if err := b.requireSiteLogin(id); err != nil {
+ return "", err
+ }
+ rawURL = strings.TrimSpace(rawURL)
+ if rawURL == "" {
+ return "", &site.Error{Site: id, Kind: site.ErrKindBadRequest, Message: "媒体预览地址为空"}
+ }
+ var data []byte
+ switch id {
+ case site.Douyin:
+ var fetchErr error
+ data, _, fetchErr = b.douyin.FetchImageLimited(ctx, rawURL, maxPreviewMediaBytes)
+ if fetchErr != nil {
+ return "", fetchErr
+ }
+ case site.Bilibili:
+ var fetchErr error
+ data, fetchErr = b.bili.FetchImageLimited(ctx, rawURL, maxPreviewMediaBytes)
+ if fetchErr != nil {
+ return "", fetchErr
+ }
+ }
+ safeExt := ".mp4"
+ switch strings.ToLower(strings.TrimSpace(ext)) {
+ case ".mp3", "mp3":
+ safeExt = ".mp3"
+ case ".m4a", "m4a":
+ safeExt = ".m4a"
+ case ".aac", "aac":
+ safeExt = ".aac"
+ case ".ogg", "ogg":
+ safeExt = ".ogg"
+ case ".wav", "wav":
+ safeExt = ".wav"
+ }
+ sum := sha256.Sum256([]byte(string(id) + "\x00" + rawURL))
+ fileName := fmt.Sprintf("preview_%s_%x%s", string(id), sum[:16], safeExt)
+ fullPath := filepath.Join(b.previewDir, fileName)
+ if err := storage.WriteFileAtomic(fullPath, data, 0o600); err != nil {
+ return "", err
+ }
+ prunePreviewDir(b.previewDir, fullPath, maxPreviewDirBytes, maxPreviewDirFiles)
+ return fullPath, nil
+}
+
+func prunePreviewDir(dir, keepPath string, maxBytes int64, maxFiles int) {
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ return
+ }
+ type stagedFile struct {
+ path string
+ size int64
+ modTime time.Time
+ }
+ var files []stagedFile
+ var totalBytes int64
+ for _, e := range entries {
+ if e.IsDir() {
+ continue
+ }
+ info, err := e.Info()
+ if err != nil || !info.Mode().IsRegular() {
+ continue
+ }
+ p := filepath.Join(dir, e.Name())
+ files = append(files, stagedFile{path: p, size: info.Size(), modTime: info.ModTime()})
+ totalBytes += info.Size()
+ }
+ if totalBytes <= maxBytes && len(files) <= maxFiles {
+ return
+ }
+ sort.Slice(files, func(i, j int) bool {
+ if !files[i].modTime.Equal(files[j].modTime) {
+ return files[i].modTime.Before(files[j].modTime)
+ }
+ return files[i].path < files[j].path
+ })
+ remaining := len(files)
+ for _, f := range files {
+ if totalBytes <= maxBytes && remaining <= maxFiles {
+ break
+ }
+ if samePath(f.path, keepPath) {
+ continue
+ }
+ if os.Remove(f.path) == nil {
+ totalBytes -= f.size
+ remaining--
+ }
+ }
+}
diff --git a/internal/service/remote_client.go b/internal/service/remote_client.go
new file mode 100644
index 0000000..589c593
--- /dev/null
+++ b/internal/service/remote_client.go
@@ -0,0 +1,426 @@
+package service
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "path/filepath"
+ "slices"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/chialecode/trace/internal/appdirs"
+ "github.com/chialecode/trace/internal/credential"
+ "github.com/chialecode/trace/internal/remote"
+ "github.com/chialecode/trace/internal/settings"
+ "github.com/chialecode/trace/internal/site"
+)
+
+// RemoteService is the desktop's side of the remote (Settings › 远程,
+// docs/design/remote.md §3, §5, §7). Only one remote is kept for now.
+type RemoteService interface {
+ RemoteConnection() (RemoteConnectionInfo, bool)
+ ConnectRemote(ctx context.Context, in RemoteConnectInput) (RemoteView, error)
+ RemoveRemote() error
+ RemoteStatus(ctx context.Context) (RemoteView, error)
+ SyncSubscriptionsToRemote(ctx context.Context) (remote.SubscriptionsInfo, error)
+ PushCredentialToRemote(ctx context.Context, siteID string) (remote.SiteStatus, error)
+ ClearRemoteCredential(ctx context.Context, siteID string) error
+ RetryRemoteUpload(ctx context.Context) error
+ LocalSnapshotHash() string
+}
+
+var _ RemoteService = (*Backend)(nil)
+
+// RemoteConnectInput is a pasted connection code, or the three parts typed
+// separately.
+type RemoteConnectInput struct {
+ Code string `json:"code,omitempty"`
+ URL string `json:"url,omitempty"`
+ Token string `json:"-"`
+ Fingerprint string `json:"fingerprint,omitempty"`
+}
+
+// RemoteConnectionInfo is the saved connection (never the token).
+type RemoteConnectionInfo struct {
+ ID string `json:"id"`
+ Name string `json:"name,omitempty"`
+ URL string `json:"url"`
+ Fingerprint string `json:"fingerprint"`
+ PendingCookies []string `json:"pendingCookies,omitempty"`
+}
+
+// RemoteView is one read of the remote for Settings › 远程.
+type RemoteView struct {
+ Connection RemoteConnectionInfo `json:"connection"`
+ Status remote.Status `json:"status"`
+ LocalHash string `json:"localHash"`
+ InSync bool `json:"inSync"`
+ FetchedAt string `json:"fetchedAt"`
+}
+
+// ErrNoRemote is returned when no remote is connected.
+var ErrNoRemote = errors.New("还没有连接远程")
+
+type remoteLink struct {
+ mu sync.Mutex
+ keyHash string
+ token string
+ client *remote.Client
+}
+
+func (r *remoteLink) activeToken() string {
+ if r == nil {
+ return ""
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return r.token
+}
+
+func (r *remoteLink) closeClient() {
+ if r == nil {
+ return
+ }
+ r.mu.Lock()
+ if r.client != nil {
+ r.client.Close()
+ r.client = nil
+ }
+ r.keyHash = ""
+ r.token = ""
+ r.mu.Unlock()
+}
+
+// remoteClientFactory builds the client; tests replace it.
+var remoteClientFactory = func(conn remote.Connection, version string) (*remote.Client, error) {
+ return remote.NewClient(conn, version)
+}
+
+func (b *Backend) remoteTokenPath(id string) string {
+ return filepath.Join(b.loc.CredentialsDir, "remote-"+id+".bin")
+}
+
+// RemoteConnection returns the saved connection.
+func (b *Backend) RemoteConnection() (RemoteConnectionInfo, bool) {
+ rs := b.settings.Get().Remote
+ if len(rs.Connections) == 0 {
+ return RemoteConnectionInfo{}, false
+ }
+ c := rs.Connections[0]
+ info := RemoteConnectionInfo{ID: c.ID, Name: c.Name, URL: c.URL, Fingerprint: c.Fingerprint}
+ for _, p := range rs.PendingCookies {
+ info.PendingCookies = append(info.PendingCookies, p.Site)
+ }
+ return info, true
+}
+
+func (b *Backend) remoteClient() (*remote.Client, RemoteConnectionInfo, error) {
+ info, ok := b.RemoteConnection()
+ if !ok {
+ return nil, RemoteConnectionInfo{}, ErrNoRemote
+ }
+ token, ok, err := credential.LoadSecret(b.remoteTokenPath(info.ID), credential.RemoteTokenEntropy)
+ if err != nil {
+ return nil, info, err
+ }
+ if !ok {
+ return nil, info, errors.New("远程的访问令牌读不出来了,请重新粘贴连接码")
+ }
+ if b.remote == nil {
+ b.remote = &remoteLink{}
+ }
+ b.remote.mu.Lock()
+ defer b.remote.mu.Unlock()
+ sum := sha256.Sum256([]byte(info.ID + "|" + info.URL + "|" + info.Fingerprint + "|" + string(token)))
+ keyHash := hex.EncodeToString(sum[:])
+ b.remote.token = string(token)
+ if b.remote.client != nil && b.remote.keyHash == keyHash {
+ return b.remote.client, info, nil
+ }
+ if b.remote.client != nil {
+ b.remote.client.Close()
+ b.remote.client = nil
+ }
+ c, err := remoteClientFactory(remote.Connection{URL: info.URL, Token: string(token), Fingerprint: info.Fingerprint, Name: info.Name}, appdirs.BuildInfo().Version)
+ if err != nil {
+ return nil, info, err
+ }
+ b.remote.client, b.remote.keyHash = c, keyHash
+ return c, info, nil
+}
+
+// ConnectRemote checks the connection by reading the remote's status and
+// saves it only when that works: the address, name and fingerprint in
+// settings.json, the token in the credential store.
+func (b *Backend) ConnectRemote(ctx context.Context, in RemoteConnectInput) (RemoteView, error) {
+ var conn remote.Connection
+ var err error
+ if strings.TrimSpace(in.Code) != "" {
+ conn, err = remote.DecodeCode(in.Code)
+ } else {
+ conn, err = remote.Connection{URL: in.URL, Token: in.Token, Fingerprint: in.Fingerprint}.Normalize()
+ }
+ if err != nil {
+ return RemoteView{}, err
+ }
+ client, err := remoteClientFactory(conn, appdirs.BuildInfo().Version)
+ if err != nil {
+ return RemoteView{}, err
+ }
+ st, err := client.Status(ctx)
+ if err != nil {
+ client.Close()
+ return RemoteView{}, err
+ }
+ client.Close()
+ id := newRemoteID()
+ prev, hadPrev := b.RemoteConnection()
+ if err := credential.SaveSecret(b.remoteTokenPath(id), credential.RemoteTokenEntropy, []byte(conn.Token)); err != nil {
+ return RemoteView{}, err
+ }
+ name := firstNonEmpty(conn.Name, st.Node.Name)
+ if _, err := b.mutateRemoteSettings(func(rs *settings.RemoteSettings) {
+ rs.Connections = []settings.RemoteConnection{{ID: id, Name: name, URL: conn.URL, Fingerprint: conn.Fingerprint, AddedAt: time.Now().UTC().Format(time.RFC3339)}}
+ rs.PendingCookies = nil
+ }); err != nil {
+ _ = credential.DeleteSecret(b.remoteTokenPath(id))
+ return RemoteView{}, err
+ }
+ // Only remove the previous token and reset the cached client after the new
+ // settings and token have been durably saved.
+ if b.remote != nil {
+ b.remote.closeClient()
+ b.remote.mu.Lock()
+ b.remote.token = conn.Token
+ b.remote.mu.Unlock()
+ }
+ if hadPrev && prev.ID != "" && prev.ID != id {
+ _ = credential.DeleteSecret(b.remoteTokenPath(prev.ID))
+ }
+ b.logInfo("remote connected: version=" + st.Version)
+ return b.remoteView(st), nil
+}
+
+// RemoveRemote forgets the connection and deletes its token. The remote
+// itself is not changed (its Cookies stay until cleared there).
+func (b *Backend) RemoveRemote() error {
+ info, ok := b.RemoteConnection()
+ if !ok {
+ return nil
+ }
+ if b.remote != nil {
+ b.remote.closeClient()
+ }
+ if _, err := b.mutateRemoteSettings(func(rs *settings.RemoteSettings) {
+ rs.Connections = nil
+ rs.PendingCookies = nil
+ }); err != nil {
+ return err
+ }
+ b.logInfo("remote removed")
+ return credential.DeleteSecret(b.remoteTokenPath(info.ID))
+}
+
+func (b *Backend) remoteView(st remote.Status) RemoteView {
+ info, _ := b.RemoteConnection()
+ local := b.LocalSnapshotHash()
+ return RemoteView{Connection: info, Status: st, LocalHash: local, InSync: local != "" && local == st.Subscriptions.Hash, FetchedAt: time.Now().UTC().Format(time.RFC3339)}
+}
+
+// RemoteStatus reads the remote's status; pending Cookie pushes are retried
+// after a successful read.
+func (b *Backend) RemoteStatus(ctx context.Context) (RemoteView, error) {
+ client, _, err := b.remoteClient()
+ if err != nil {
+ return RemoteView{}, err
+ }
+ st, err := client.Status(ctx)
+ if err != nil {
+ return RemoteView{}, err
+ }
+ if b.retryPendingRemoteCookies(ctx) {
+ if again, err := client.Status(ctx); err == nil {
+ st = again
+ }
+ }
+ return b.remoteView(st), nil
+}
+
+// SyncSubscriptionsToRemote replaces the remote's subscriptions with the
+// local ones (the desktop is the only source, Q-022 item 4).
+func (b *Backend) SyncSubscriptionsToRemote(ctx context.Context) (remote.SubscriptionsInfo, error) {
+ client, _, err := b.remoteClient()
+ if err != nil {
+ return remote.SubscriptionsInfo{}, err
+ }
+ snap, err := b.SubscriptionSnapshot()
+ if err != nil {
+ return remote.SubscriptionsInfo{}, err
+ }
+ raw, err := marshalSnapshot(snap)
+ if err != nil {
+ return remote.SubscriptionsInfo{}, err
+ }
+ info, err := client.PutSubscriptions(ctx, raw)
+ if err != nil {
+ b.logError("SyncSubscriptionsToRemote", err)
+ return info, err
+ }
+ b.logInfo(fmt.Sprintf("subscriptions synced to the remote: subscriptions=%d accounts=%d", info.Subscriptions, info.Accounts))
+ return info, nil
+}
+
+// PushCredentialToRemote sends one site's Cookie (never a refresh token).
+// A push that fails for a reason other than the remote rejecting the
+// Cookie is remembered and retried later.
+func (b *Backend) PushCredentialToRemote(ctx context.Context, siteID string) (remote.SiteStatus, error) {
+ id, err := normalizeSiteID(siteID)
+ if err != nil {
+ return remote.SiteStatus{}, err
+ }
+ store := b.credMgr.Store(string(id))
+ if store == nil || !store.HasActiveCredential() {
+ return remote.SiteStatus{}, fmt.Errorf("本地还没有登录%s", id.DisplayName())
+ }
+ client, _, err := b.remoteClient()
+ if err != nil {
+ return remote.SiteStatus{}, err
+ }
+ st, err := client.PushCredential(ctx, string(id), remote.CredentialPush{Cookie: store.CookieHeader()})
+ if err != nil {
+ if remote.KindOf(err) != remote.KindRejected {
+ b.markRemoteCookiePending(string(id), true)
+ }
+ b.logError("PushCredentialToRemote", err)
+ return st, err
+ }
+ b.markRemoteCookiePending(string(id), false)
+ b.logInfo("cookie pushed to the remote: site=" + string(id))
+ return st, nil
+}
+
+// ClearRemoteCredential clears the remote's login of one site (远程的
+// “清除远程登录”); logging out locally does not do this.
+func (b *Backend) ClearRemoteCredential(ctx context.Context, siteID string) error {
+ id, err := normalizeSiteID(siteID)
+ if err != nil {
+ return err
+ }
+ client, _, err := b.remoteClient()
+ if err != nil {
+ return err
+ }
+ if err := client.DeleteCredential(ctx, string(id)); err != nil {
+ return err
+ }
+ b.markRemoteCookiePending(string(id), false)
+ return nil
+}
+
+// RetryRemoteUpload makes the remote retry failed uploads now.
+func (b *Backend) RetryRemoteUpload(ctx context.Context) error {
+ client, _, err := b.remoteClient()
+ if err != nil {
+ return err
+ }
+ return client.RetryUpload(ctx)
+}
+
+func (b *Backend) mutateRemoteSettings(fn func(*settings.RemoteSettings)) (settings.Settings, error) {
+ b.settingsMu.Lock()
+ defer b.settingsMu.Unlock()
+ cur := b.settings.Get()
+ fn(&cur.Remote)
+ return b.settings.Update(cur)
+}
+
+func (b *Backend) markRemoteCookiePending(siteID string, pending bool) {
+ if _, ok := b.RemoteConnection(); !ok {
+ return
+ }
+ cur := b.settings.Get().Remote.PendingCookies
+ has := slices.ContainsFunc(cur, func(p settings.PendingCookie) bool { return p.Site == siteID })
+ if has == pending {
+ return
+ }
+ if _, err := b.mutateRemoteSettings(func(rs *settings.RemoteSettings) {
+ rs.PendingCookies = slices.DeleteFunc(rs.PendingCookies, func(p settings.PendingCookie) bool { return p.Site == siteID })
+ if pending {
+ rs.PendingCookies = append(rs.PendingCookies, settings.PendingCookie{Site: siteID, Since: time.Now().UTC().Format(time.RFC3339)})
+ }
+ }); err != nil {
+ b.logError("markRemoteCookiePending", err)
+ }
+ b.events.Publish(EventSettingsChanged, "remote")
+}
+
+// retryPendingRemoteCookies pushes the sites marked "Cookie 待同步"; it
+// reports whether anything was pushed.
+func (b *Backend) retryPendingRemoteCookies(ctx context.Context) bool {
+ info, ok := b.RemoteConnection()
+ if !ok || len(info.PendingCookies) == 0 {
+ return false
+ }
+ pushed := false
+ for _, s := range info.PendingCookies {
+ if _, err := b.PushCredentialToRemote(ctx, s); err == nil {
+ pushed = true
+ } else if remote.KindOf(err) == remote.KindRejected {
+ // The remote checked and refused it: retrying the same Cookie
+ // would not help; the next local login pushes again.
+ b.markRemoteCookiePending(s, false)
+ }
+ }
+ return pushed
+}
+
+// RetryPendingRemoteCookies is the background retry of "Cookie 待同步"
+// (every 10 minutes); exported for tests.
+func (b *Backend) RetryPendingRemoteCookies(ctx context.Context) bool {
+ return b.retryPendingRemoteCookies(ctx)
+}
+
+// runRemoteCookieRetry retries pending Cookie pushes every 10 minutes. It
+// sends nothing while nothing is pending (Settings › 远程 closed means no
+// other remote request, remote.md §7).
+func (b *Backend) runRemoteCookieRetry(ctx context.Context) {
+ defer b.bgWg.Done()
+ t := time.NewTicker(10 * time.Minute)
+ defer t.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-t.C:
+ b.retryPendingRemoteCookies(ctx)
+ }
+ }
+}
+
+// afterLocalLogin pushes a site's new Cookie to the remote after a local
+// login or renewal (remote.md §5), in the background. Nothing happens when
+// no remote is connected, or on the remote itself.
+func (b *Backend) afterLocalLogin(id site.ID) {
+ if b.profile == ProfileRemote {
+ return
+ }
+ if _, ok := b.RemoteConnection(); !ok {
+ return
+ }
+ b.goBg(func(bgCtx context.Context) {
+ ctx, cancel := context.WithTimeout(bgCtx, 2*time.Minute)
+ defer cancel()
+ _, _ = b.PushCredentialToRemote(ctx, string(id))
+ })
+}
+
+func newRemoteID() string {
+ var rnd [8]byte
+ _, _ = rand.Read(rnd[:])
+ return hex.EncodeToString(rnd[:])
+}
diff --git a/internal/service/remote_profile.go b/internal/service/remote_profile.go
new file mode 100644
index 0000000..ea3941a
--- /dev/null
+++ b/internal/service/remote_profile.go
@@ -0,0 +1,162 @@
+package service
+
+import (
+ "database/sql"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/chialecode/trace/internal/appdirs"
+ "github.com/chialecode/trace/internal/settings"
+ "github.com/chialecode/trace/internal/site"
+)
+
+// Profile selects what a Backend runs: the desktop app or the headless
+// remote trace-server (docs/design/remote.md §2).
+type Profile string
+
+const (
+ // ProfileDesktop is the Windows desktop app (the default).
+ ProfileDesktop Profile = ""
+ // ProfileRemote is trace-server: it checks the synced subscriptions,
+ // caches their new content by rule and records lives. It never renews
+ // Cookies, never runs 全部缓存 and has no manual caching (remote.md §4).
+ ProfileRemote Profile = "remote"
+)
+
+// CredentialSourceRemotePush marks a credential the desktop pushed to the
+// remote; the remote never renews it (DEC-062 ③).
+const CredentialSourceRemotePush = "remote_push"
+
+// ErrRemoteUnsupported is returned by the operations the remote does not
+// offer: manual caching, 全部缓存 and Cookie renewal.
+var ErrRemoteUnsupported = &site.Error{Kind: site.ErrKindBadRequest, Message: "远程版只缓存订阅的新内容与录制,不提供这个操作"}
+
+const maxRecentErrors = 20
+
+// RecentError is one of the last errors written to the run log, already
+// sanitized like the log line (remote.md §7).
+type RecentError struct {
+ At string `json:"at"`
+ Message string `json:"message"`
+}
+
+// IsRemote reports whether the backend runs as trace-server.
+func (b *Backend) IsRemote() bool { return b.profile == ProfileRemote }
+
+// StartedAt is when the backend started.
+func (b *Backend) StartedAt() time.Time { return b.startedAt }
+
+// RecentErrors returns the last errors of the run log, oldest first.
+func (b *Backend) RecentErrors() []RecentError {
+ b.logMu.Lock()
+ defer b.logMu.Unlock()
+ return append([]RecentError(nil), b.recentErrors...)
+}
+
+// SetCacheGate installs the check the remote runs before automatic caching
+// starts a task (the export folder's free space, remote.md §6.2).
+func (b *Backend) SetCacheGate(fn func() error) {
+ b.settingsMu.Lock()
+ b.cacheGate = fn
+ b.settingsMu.Unlock()
+}
+
+func (b *Backend) remoteCacheGate() error {
+ b.settingsMu.Lock()
+ gate := b.cacheGate
+ b.settingsMu.Unlock()
+ if gate == nil {
+ return nil
+ }
+ return gate()
+}
+
+// requireDesktop rejects the operations the remote does not offer.
+func (b *Backend) requireDesktop() error {
+ if b.profile == ProfileRemote {
+ return ErrRemoteUnsupported
+ }
+ return nil
+}
+
+// remoteSettings forces what the remote keeps fixed: the save location is
+// the export folder, and scheduled checking is always on (each
+// subscription's rule decides whether it is checked, remote.md §4).
+func remoteSettings(s settings.Settings, exportDir string) (settings.Settings, bool) {
+ exportDir = filepath.Clean(exportDir)
+ changed := false
+ if filepath.Clean(s.CacheDir) != exportDir || filepath.Clean(s.CacheRoot) != exportDir {
+ s.CacheDir, s.CacheRoot = exportDir, exportDir
+ changed = true
+ }
+ if !s.Subscription.Enabled {
+ s.Subscription.Enabled = true
+ changed = true
+ }
+ if !s.ScheduledCheck {
+ s.ScheduledCheck = true
+ changed = true
+ }
+ return s, changed
+}
+
+func nodeName(name string) string {
+ if n := strings.TrimSpace(name); n != "" {
+ return n
+ }
+ if h, err := os.Hostname(); err == nil {
+ return strings.TrimSpace(h)
+ }
+ return ""
+}
+
+// LibraryDB is library.db; trace-server keeps its upload records there.
+func (b *Backend) LibraryDB() *sql.DB { return b.db }
+
+// ItemBusy reports whether an item is still being written: a cache task for
+// it is queued or running, or a recording writes into its folder. The
+// uploader leaves such items alone (remote.md §6.2).
+func (b *Backend) ItemBusy(itemKey string) bool {
+ if b.dl != nil {
+ if tasks, err := b.dl.ListTasks(); err == nil {
+ for _, t := range tasks {
+ if t.ItemKey == itemKey && (t.Status == "running" || t.Status == "queued") {
+ return true
+ }
+ }
+ }
+ }
+ if b.live != nil {
+ meta, ok, err := b.lib.GetItem(itemKey)
+ if err == nil && ok && meta.Kind == "live" {
+ for _, r := range b.live.ListRooms() {
+ if r.Recording && r.RecordItemDir != "" && strings.EqualFold(filepath.Clean(r.RecordItemDir), filepath.Clean(meta.ItemDir)) {
+ return true
+ }
+ }
+ }
+ }
+ return false
+}
+
+// RemoteLocations are the directories of trace-server: everything under
+// the data directory given on the command line, the export folder as the
+// save location (remote.md §2).
+func RemoteLocations(dataDir, exportDir string) appdirs.Locations {
+ return appdirs.Locations{
+ Mode: "remote",
+ Channel: appdirs.EffectiveChannel(""),
+ AppName: "trace-server",
+ DisplayName: "trace-server",
+ Identifier: "io.github.chialecode.trace-server",
+ InstallDir: dataDir,
+ DataDir: dataDir,
+ DefaultCacheDir: exportDir,
+ CredentialsDir: filepath.Join(dataDir, "credentials"),
+ LogsDir: filepath.Join(dataDir, "logs"),
+ TempDir: filepath.Join(dataDir, "tmp"),
+ LockFile: filepath.Join(dataDir, "app.lock"),
+ }
+}
diff --git a/internal/service/remote_profile_test.go b/internal/service/remote_profile_test.go
new file mode 100644
index 0000000..0997a57
--- /dev/null
+++ b/internal/service/remote_profile_test.go
@@ -0,0 +1,176 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+
+ "github.com/chialecode/trace/internal/download"
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/site/bilibili"
+ "github.com/chialecode/trace/internal/subscription"
+)
+
+// countingBili answers nav for any SESSDATA and counts the requests by
+// path; everything else is 404.
+func countingBili(t *testing.T) (*httptest.Server, *siteCounts) {
+ t.Helper()
+ c := &siteCounts{}
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ c.total.Add(1)
+ if strings.Contains(r.URL.Path, "cookie") || strings.Contains(r.URL.Path, "refresh") || strings.Contains(r.URL.Path, "correspond") {
+ c.renewal.Add(1)
+ }
+ if r.URL.Path == "/x/web-interface/nav" && strings.Contains(r.Header.Get("Cookie"), "SESSDATA=") {
+ _, _ = w.Write([]byte(`{"code":0,"data":{"isLogin":true,"mid":778899,"uname":"合成远程用户","wbi_img":{"img_url":"https://i0.hdslb.com/bfs/wbi/7cd084941338484aae1ad9425b84077c.png","sub_url":"https://i0.hdslb.com/bfs/wbi/4932caff0ff746eab6f01bf08b70ac45.png"}}}`))
+ return
+ }
+ http.NotFound(w, r)
+ }))
+ t.Cleanup(srv.Close)
+ return srv, c
+}
+
+type siteCounts struct{ total, renewal atomic.Int64 }
+
+func remoteTestBackend(t *testing.T, srvURL string) (*Backend, string) {
+ t.Helper()
+ root := t.TempDir()
+ export := filepath.Join(root, "export")
+ b, err := NewBackend(Options{
+ Locations: RemoteLocations(filepath.Join(root, "data"), export),
+ Desktop: NewMockDesktop(),
+ Profile: ProfileRemote,
+ NodeName: "测试节点",
+ BilibiliOpts: bilibili.ClientOptions{
+ Endpoints: bilibili.Endpoints{APIBase: srvURL, PassportBase: srvURL, WWWBase: srvURL, SpaceBase: srvURL, DynamicBase: srvURL, LiveAPIBase: srvURL, LiveWebBase: srvURL},
+ PacingInterval: -1, AllowLocalhost: true,
+ },
+ DisableBgWorkers: true,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = b.Close() })
+ return b, export
+}
+
+// On the remote there is no renewal, 全部缓存 never builds a queue,
+// manual caching returns a clear error, scheduled checking stays on and the
+// save location is the export folder.
+func TestRemoteProfileHasNoRenewalNoFullCacheAndChecksOn(t *testing.T) {
+ srv, counts := countingBili(t)
+ b, export := remoteTestBackend(t, srv.URL)
+ ctx := context.Background()
+
+ s := b.GetSettings()
+ if !s.ScheduledCheck || !s.Subscription.Enabled || filepath.Clean(s.CacheDir) != filepath.Clean(export) {
+ t.Fatalf("remote settings = check %v/%v cache %q", s.ScheduledCheck, s.Subscription.Enabled, s.CacheDir)
+ }
+ s.ScheduledCheck, s.Subscription.Enabled, s.CacheDir = false, false, filepath.Join(t.TempDir(), "elsewhere")
+ if got, err := b.UpdateSettings(s); err != nil || !got.ScheduledCheck || !got.Subscription.Enabled || filepath.Clean(got.CacheDir) != filepath.Clean(export) {
+ t.Fatalf("settings after trying to turn checks off = %+v %v", got.ScheduledCheck, err)
+ }
+
+ if _, err := b.AcceptPushedCredential(ctx, "bilibili", "SESSDATA=synthetic; bili_jct=x"); err != nil {
+ t.Fatalf("AcceptPushedCredential: %v", err)
+ }
+ snap := subscription.Snapshot{Format: subscription.SnapshotFormat, Version: subscription.SnapshotVersion,
+ Rules: []subscription.CacheRule{{ID: "full", Name: "全部", ScheduledCheck: true, AutoCache: true, FullCache: true}},
+ Subscriptions: []subscription.SnapshotSubscription{{ID: "s1", Name: "合成", RuleID: "full", Accounts: []subscription.SnapshotAccount{{Site: "bilibili", UID: "1001"}}}}}
+ raw, _ := json.Marshal(snap)
+ if _, err := b.ApplyRemoteSnapshot(raw); err != nil {
+ t.Fatal(err)
+ }
+
+ before := counts.total.Load()
+ if r := b.Renewal("bilibili"); r.Available || r.Reason != "由本地续期" {
+ t.Fatalf("Renewal = %+v", r)
+ }
+ if _, err := b.RefreshCookie(ctx); !errors.Is(err, ErrRemoteUnsupported) {
+ t.Fatalf("RefreshCookie = %v, want ErrRemoteUnsupported", err)
+ }
+ if ids := b.startDueFullCacheSweeps(ctx, b.StartedAt().AddDate(1, 0, 0)); len(ids) != 0 {
+ t.Fatalf("full-cache sweep started %v on the remote", ids)
+ }
+ if q := b.ListCacheQueue(); len(q) != 0 {
+ t.Fatalf("cache queue on the remote = %+v", q)
+ }
+ if _, err := b.EnqueueCacheQueue(ctx, CacheQueueRequest{Site: "bilibili", List: "videos", User: "1001"}); !errors.Is(err, ErrRemoteUnsupported) {
+ t.Fatalf("EnqueueCacheQueue = %v, want ErrRemoteUnsupported", err)
+ }
+ if _, err := b.EnqueueVideoCache(ctx, download.VideoEnqueueRequest{BVID: "BV1xx411c7mD"}); !errors.Is(err, ErrRemoteUnsupported) {
+ t.Fatalf("EnqueueVideoCache = %v, want ErrRemoteUnsupported", err)
+ }
+ if n := counts.total.Load() - before; n != 0 {
+ t.Fatalf("%d site requests for renewal or 全部缓存 on the remote", n)
+ }
+ if counts.renewal.Load() != 0 {
+ t.Fatal("the remote sent a renewal request")
+ }
+ st := b.ServerStatus()
+ if len(st.Notes) == 0 || !strings.Contains(st.Notes[0], "全部缓存") {
+ t.Fatalf("status notes = %v", st.Notes)
+ }
+ if acc := b.AccountStatus(); acc.Source != CredentialSourceRemotePush || acc.HasRefreshToken {
+ t.Fatalf("pushed credential = %+v", acc)
+ }
+}
+
+// Items cached here carry cachedBy with this installation's node,
+// which stays the same after a restart; old items without it still load.
+func TestCachedByNodeIsStableAndOldItemsStillLoad(t *testing.T) {
+ loc := testLocations(t)
+ open := func() *Backend {
+ b, err := NewBackend(Options{Locations: loc, Desktop: NewMockDesktop(), DisableBgWorkers: true, NodeName: "台式机"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+ }
+ b := open()
+ node := b.LibraryStore().Node()
+ if len(node.Node) != 32 || node.Name != "台式机" {
+ t.Fatalf("node = %+v", node)
+ }
+ itemDir := filepath.Join(b.GetSettings().CacheDir, "bilibili", "1001", "videos", "BV1node")
+ _ = os.MkdirAll(itemDir, 0o700)
+ _ = os.WriteFile(filepath.Join(itemDir, "P01.mp4"), []byte("v"), 0o600)
+ meta, err := b.LibraryStore().SaveItem(itemDir, library.ItemMetadata{ID: "video:BV1node", Site: "bilibili", Kind: "video", Title: "t", Media: []library.MediaFile{{Role: "video", Path: "P01.mp4", Bytes: 1}}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if meta.CachedBy == nil || meta.CachedBy.Node != node.Node {
+ t.Fatalf("cachedBy = %+v, want %s", meta.CachedBy, node.Node)
+ }
+ // An old item.json without cachedBy.
+ oldDir := filepath.Join(b.GetSettings().CacheDir, "bilibili", "1001", "videos", "BV1old")
+ _ = os.MkdirAll(oldDir, 0o700)
+ _ = os.WriteFile(filepath.Join(oldDir, "P01.mp4"), []byte("v"), 0o600)
+ _ = os.WriteFile(filepath.Join(oldDir, "item.json"), []byte(`{"version":1,"id":"video:BV1old","site":"bilibili","kind":"video","title":"旧","status":"complete","media":[{"role":"video","path":"P01.mp4","bytes":1}]}`), 0o600)
+ _ = b.Close()
+
+ b = open()
+ defer b.Close()
+ if again := b.LibraryStore().Node(); again.Node != node.Node {
+ t.Fatalf("node after restart = %s, want %s", again.Node, node.Node)
+ }
+ if _, err := b.LibraryStore().RefreshIndex(); err != nil {
+ t.Fatal(err)
+ }
+ old, ok, err := b.LibraryStore().GetItem("BV1old")
+ if err != nil || !ok || old.Title != "旧" {
+ t.Fatalf("old item = %+v %v %v", old, ok, err)
+ }
+ raw, _ := os.ReadFile(filepath.Join(oldDir, "item.json"))
+ if strings.Contains(string(raw), "cachedBy") {
+ t.Fatal("reading an old item rewrote it with cachedBy")
+ }
+}
diff --git a/internal/service/remote_server_api.go b/internal/service/remote_server_api.go
new file mode 100644
index 0000000..c568db2
--- /dev/null
+++ b/internal/service/remote_server_api.go
@@ -0,0 +1,265 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/chialecode/trace/internal/appdirs"
+ "github.com/chialecode/trace/internal/credential"
+ "github.com/chialecode/trace/internal/remote"
+ "github.com/chialecode/trace/internal/site"
+ "github.com/chialecode/trace/internal/subscription"
+)
+
+// This file is what trace-server's API calls (docs/design/remote.md §3–§5,
+// §7). Status is assembled from what the backend already knows; it never
+// sends a site request of its own.
+
+// ServerStatus returns the remote's status without the upload part (the
+// server adds it) and without the disk part when free is 0.
+func (b *Backend) ServerStatus() remote.Status {
+ build := appdirs.BuildInfo()
+ node := b.lib.Node()
+ now := time.Now().UTC()
+ st := remote.Status{
+ Version: build.Version,
+ Protocol: remote.ProtocolVersion,
+ Node: remote.Node{ID: node.Node, Name: node.Name},
+ StartedAt: b.startedAt.UTC().Format(time.RFC3339),
+ Now: now.Format(time.RFC3339),
+ }
+ sync := b.loadSyncState()
+ st.Subscriptions = b.ServerSubscriptions()
+
+ backoff := map[string]string{}
+ if b.subs != nil {
+ for siteName, s := range b.subs.ListSiteSchedulerStates() {
+ if until, err := time.Parse(time.RFC3339, s.BackoffUntil); err == nil && until.After(now) {
+ backoff[siteName] = until.UTC().Format(time.RFC3339)
+ }
+ }
+ }
+ for _, sid := range []site.ID{site.Bilibili, site.Douyin} {
+ cs := b.credMgr.Status(string(sid))
+ row := remote.SiteStatus{Site: string(sid), Uname: cs.Uname, CookieSyncedAt: sync.CookieSyncedAt[string(sid)]}
+ switch {
+ case cs.State == "logged_out" || cs.State == "decrypt_failed" || cs.State == "":
+ row.State = remote.SiteNone
+ case cs.State == "expired":
+ row.State = remote.SiteResync
+ row.Message = "登录已失效,请在本地重新同步 Cookie"
+ case backoff[string(sid)] != "":
+ row.State = remote.SiteBackoff
+ row.BackoffUntil = backoff[string(sid)]
+ case cs.State == "unknown":
+ row.State = remote.SiteUnknown
+ row.Message = "暂时无法确认登录状态"
+ default:
+ row.State = remote.SiteValid
+ }
+ st.Sites = append(st.Sites, row)
+ }
+
+ for _, p := range b.checkPlanLocal() {
+ st.Checks = append(st.Checks, remote.CheckRow{
+ Site: p.Site, UID: p.UID, Name: p.Name, Subscription: p.SubName,
+ LastCheckedAt: p.LastCheckedAt, LastResult: firstNonEmpty(p.Note, p.LastKind), NextAt: p.NextAt,
+ Baseline: p.LastKind == "baseline", Scheduled: p.Plan == subscription.PlanScheduled,
+ })
+ }
+
+ if b.dl != nil {
+ if tasks, err := b.dl.ListTasks(); err == nil {
+ var done []remote.TaskRow
+ for _, t := range tasks {
+ switch t.Status {
+ case "running":
+ st.Cache.Running++
+ case "queued":
+ st.Cache.Queued++
+ case "completed", "partial", "failed":
+ msg := ""
+ if t.Status == "failed" {
+ msg = firstNonEmpty(t.ErrorMessage, t.LastError)
+ }
+ done = append(done, remote.TaskRow{Site: t.Site, Title: t.Title, Status: t.Status, At: t.UpdatedAt, Error: b.sanitizeLogLine(msg)})
+ }
+ }
+ sort.SliceStable(done, func(i, j int) bool { return done[i].At > done[j].At })
+ if len(done) > 20 {
+ done = done[:20]
+ }
+ st.Cache.Recent = done
+ }
+ }
+
+ if b.live != nil {
+ for _, r := range b.live.ListRooms() {
+ if !r.Recording {
+ continue
+ }
+ row := remote.RecordingRow{Site: firstNonEmpty(r.Site, string(site.Bilibili)), Name: r.Uname, Title: r.Title, DurationSec: int64(r.RecordDurationSec), Bytes: r.RecordBytes, Segments: r.RecordSegments, Incidents: len(r.Incidents)}
+ if r.RecordDurationSec > 0 {
+ row.StartedAt = now.Add(-time.Duration(r.RecordDurationSec * float64(time.Second))).Format(time.RFC3339)
+ }
+ st.Recordings = append(st.Recordings, row)
+ }
+ }
+
+ for _, e := range b.RecentErrors() {
+ st.Errors = append(st.Errors, remote.ErrorRow{At: e.At, Category: errorCategory(e.Message), Message: e.Message})
+ }
+ for _, s := range b.mustListSubscriptions() {
+ if s.Rules.FullCache {
+ st.Notes = append(st.Notes, "规则里的“全部缓存”在远程不执行,远程只缓存建立起点之后的新内容")
+ break
+ }
+ }
+ return st
+}
+
+func (b *Backend) mustListSubscriptions() []subscription.Subscription {
+ subs, _ := b.subs.List()
+ return subs
+}
+
+func errorCategory(msg string) string {
+ m := strings.ToLower(msg)
+ switch {
+ case strings.Contains(m, "upload"):
+ return "上传"
+ case strings.Contains(m, "live") || strings.Contains(m, "record"):
+ return "录制"
+ case strings.Contains(m, "subscription") || strings.Contains(m, "check"):
+ return "检查"
+ case strings.Contains(m, "download") || strings.Contains(m, "task"):
+ return "缓存"
+ case strings.Contains(m, "cookie") || strings.Contains(m, "login") || strings.Contains(m, "auth"):
+ return "登录"
+ default:
+ return "其他"
+ }
+}
+
+// ServerSubscriptions is the remote's subscription summary and the hash of
+// the snapshot it last applied.
+func (b *Backend) ServerSubscriptions() remote.SubscriptionsInfo {
+ sync := b.loadSyncState()
+ info := remote.SubscriptionsInfo{SyncedAt: sync.SyncedAt, Hash: sync.Hash}
+ for _, s := range b.mustListSubscriptions() {
+ info.Subscriptions++
+ info.Accounts += len(s.Accounts)
+ }
+ return info
+}
+
+// ApplyRemoteSnapshot replaces the remote's subscriptions, rules and synced
+// settings with the snapshot's (remote.md §4) and records its hash.
+func (b *Backend) ApplyRemoteSnapshot(raw []byte) (remote.SubscriptionsInfo, error) {
+ if b.profile != ProfileRemote {
+ return remote.SubscriptionsInfo{}, errors.New("only the remote applies a sync snapshot")
+ }
+ snap, err := subscription.ParseSnapshot(raw)
+ if err != nil {
+ return remote.SubscriptionsInfo{}, err
+ }
+ if err := b.subs.ReplaceFromSnapshot(snap); err != nil {
+ return remote.SubscriptionsInfo{}, err
+ }
+ if snap.Settings != nil {
+ if _, err := b.UpdateSettings(applySnapshotSettings(b.settings.Get(), *snap.Settings)); err != nil {
+ b.logError("ApplyRemoteSnapshot.settings", err)
+ return remote.SubscriptionsInfo{}, err
+ }
+ }
+ subsCount, accsCount := snap.Counts()
+ st, err := b.mutateSyncState(func(s *syncState) {
+ s.Hash = snap.Hash()
+ s.SyncedAt = time.Now().UTC().Format(time.RFC3339)
+ s.Subscriptions, s.Accounts = subsCount, accsCount
+ })
+ if err != nil {
+ return remote.SubscriptionsInfo{}, err
+ }
+ b.logInfo(fmt.Sprintf("subscriptions synced: subscriptions=%d accounts=%d", st.Subscriptions, st.Accounts))
+ b.subs.WakeScheduler()
+ return b.ServerSubscriptions(), nil
+}
+
+// AcceptPushedCredential checks a Cookie the desktop pushed (nav for
+// 哔哩哔哩, the profile for 抖音) and keeps it only when the check passes;
+// otherwise the stored credential is unchanged and the reason is returned
+// (remote.md §5). The kept credential is marked remote_push: no refresh
+// token, never renewed.
+func (b *Backend) AcceptPushedCredential(ctx context.Context, siteID, cookie string) (remote.SiteStatus, error) {
+ id, err := normalizeSiteID(siteID)
+ if err != nil {
+ return remote.SiteStatus{}, err
+ }
+ if strings.TrimSpace(cookie) == "" {
+ return remote.SiteStatus{}, &site.Error{Site: id, Kind: site.ErrKindInvalidInput, Message: "没有收到 Cookie"}
+ }
+ var st credential.Status
+ if id == site.Bilibili {
+ st, err = b.ImportCookie(ctx, cookie, "")
+ } else {
+ st, err = b.LoginWithCookie(ctx, string(id), cookie, "")
+ }
+ if err != nil {
+ return remote.SiteStatus{}, err
+ }
+ if !st.LoggedIn {
+ return remote.SiteStatus{}, &site.Error{Site: id, Kind: site.ErrKindAuthRequired, Message: "站点确认这个 Cookie 未登录"}
+ }
+ if _, err := b.credMgr.Store(string(id)).MarkPushed(CredentialSourceRemotePush); err != nil {
+ return remote.SiteStatus{}, err
+ }
+ if _, err := b.mutateSyncState(func(sync *syncState) {
+ if sync.CookieSyncedAt == nil {
+ sync.CookieSyncedAt = map[string]string{}
+ }
+ sync.CookieSyncedAt[string(id)] = time.Now().UTC().Format(time.RFC3339)
+ }); err != nil {
+ b.logError("AcceptPushedCredential.syncState", err)
+ }
+ b.logInfo("credential pushed by the desktop: site=" + string(id))
+ b.subs.WakeScheduler()
+ for _, row := range b.ServerStatus().Sites {
+ if row.Site == string(id) {
+ return row, nil
+ }
+ }
+ return remote.SiteStatus{Site: string(id), State: remote.SiteValid}, nil
+}
+
+// ClearPushedCredential clears the remote's login of one site.
+func (b *Backend) ClearPushedCredential(siteID string) error {
+ _, err := b.LogoutSite(siteID)
+ if err == nil {
+ key := strings.ToLower(strings.TrimSpace(siteID))
+ _, _ = b.mutateSyncState(func(sync *syncState) {
+ delete(sync.CookieSyncedAt, key)
+ })
+ }
+ return err
+}
+
+// ExitGracefully is SIGTERM on the remote: the same path as 退出 in the
+// tray (tasks paused, recordings finalized), bounded by timeout.
+func (b *Backend) ExitGracefully(timeout time.Duration) bool {
+ done := make(chan struct{})
+ go func() {
+ b.PauseForExit()
+ close(done)
+ }()
+ select {
+ case <-done:
+ return true
+ case <-time.After(timeout):
+ return false
+ }
+}
diff --git a/internal/service/remote_sync.go b/internal/service/remote_sync.go
new file mode 100644
index 0000000..0c87830
--- /dev/null
+++ b/internal/service/remote_sync.go
@@ -0,0 +1,251 @@
+package service
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/chialecode/trace/internal/remote"
+ "github.com/chialecode/trace/internal/settings"
+ "github.com/chialecode/trace/internal/storage"
+ "github.com/chialecode/trace/internal/subscription"
+)
+
+var errFileTooLarge = errors.New("file too large")
+
+func readFileLimited(path string, maxBytes int64) ([]byte, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer func() { _ = f.Close() }()
+ if info, err := f.Stat(); err == nil && info.Size() > maxBytes {
+ return nil, errFileTooLarge
+ }
+ raw, err := io.ReadAll(io.LimitReader(f, maxBytes+1))
+ if err != nil {
+ return nil, err
+ }
+ if int64(len(raw)) > maxBytes {
+ return nil, errFileTooLarge
+ }
+ return raw, nil
+}
+
+// SubscriptionTransferService exports and imports subscription lists
+// (docs/design/remote.md §6.4); the same snapshot is what the desktop syncs
+// to the remote (§4).
+type SubscriptionTransferService interface {
+ ExportSubscriptions(path string) (string, error)
+ PreviewSubscriptionImport(path string) (subscription.ImportPreview, error)
+ ApplySubscriptionImport(path string, choices subscription.ImportChoices) (subscription.ImportPreview, error)
+}
+
+var _ SubscriptionTransferService = (*Backend)(nil)
+
+// SubscriptionSnapshot is the current subscriptions, rules and the synced
+// part of the settings, stamped with this installation.
+func (b *Backend) SubscriptionSnapshot() (subscription.Snapshot, error) {
+ snap, err := b.subs.Snapshot()
+ if err != nil {
+ return subscription.Snapshot{}, err
+ }
+ set := snapshotSettings(b.settings.Get())
+ snap.Settings = &set
+ node := b.lib.Node()
+ if node.Node != "" {
+ snap.Node = &subscription.SnapshotNode{ID: node.Node, Name: node.Name}
+ }
+ snap.ExportedAt = time.Now().UTC().Format(time.RFC3339)
+ return snap, nil
+}
+
+func snapshotSettings(s settings.Settings) subscription.SnapshotSettings {
+ return subscription.SnapshotSettings{
+ VideoQuality: s.VideoQuality,
+ CodecOrder: append([]string(nil), s.CodecOrder...),
+ AudioQuality: s.AudioQuality,
+ MultiPart: s.MultiPart,
+ Concurrency: s.Concurrency,
+ Danmaku: s.Danmaku,
+ Subtitles: s.Subtitles,
+ AISubtitles: s.AISubtitles,
+ CheckIntervalMin: s.CheckIntervalMin,
+ LiveCheckIntervalMin: s.LiveCheckIntervalMin,
+ }
+}
+
+// applySnapshotSettings sets the synced settings, top-level and nested
+// alike, so Normalize keeps them.
+func applySnapshotSettings(s settings.Settings, in subscription.SnapshotSettings) settings.Settings {
+ if in.VideoQuality != "" {
+ s.VideoQuality, s.Download.VideoQuality = in.VideoQuality, in.VideoQuality
+ }
+ if len(in.CodecOrder) > 0 {
+ s.CodecOrder = append([]string(nil), in.CodecOrder...)
+ s.Download.CodecOrder = append([]string(nil), in.CodecOrder...)
+ s.Download.PreferredVideoCodec = in.CodecOrder[0]
+ }
+ if in.AudioQuality != "" {
+ s.AudioQuality = in.AudioQuality
+ }
+ if in.MultiPart != "" {
+ s.MultiPart, s.Download.MultiPart = in.MultiPart, in.MultiPart
+ }
+ if in.Concurrency > 0 {
+ s.Concurrency, s.Download.MaxConcurrentTasks = in.Concurrency, in.Concurrency
+ }
+ s.Danmaku, s.Download.SaveDanmaku = in.Danmaku, in.Danmaku
+ s.Subtitles, s.Download.SaveSubtitles = in.Subtitles, in.Subtitles
+ s.AISubtitles, s.Download.IncludeAI = in.AISubtitles, in.AISubtitles
+ if in.CheckIntervalMin > 0 {
+ s.CheckIntervalMin, s.Subscription.IntervalMinutes = in.CheckIntervalMin, in.CheckIntervalMin
+ }
+ if in.LiveCheckIntervalMin > 0 {
+ s.LiveCheckIntervalMin = in.LiveCheckIntervalMin
+ s.Live.PollIntervalSeconds = in.LiveCheckIntervalMin * 60
+ }
+ return s
+}
+
+// LocalSnapshotHash is the hash of the current subscriptions as they would
+// be synced; Settings › 远程 compares it with the remote's.
+func (b *Backend) LocalSnapshotHash() string {
+ snap, err := b.SubscriptionSnapshot()
+ if err != nil {
+ return ""
+ }
+ return snap.Hash()
+}
+
+// ExportSubscriptions writes trace-subscriptions.json (no Cookie) to path,
+// or into path when it is a folder, and returns the file written.
+func (b *Backend) ExportSubscriptions(path string) (string, error) {
+ path = snapshotPath(path)
+ if path == "" {
+ return "", fmt.Errorf("请填写保存位置")
+ }
+ snap, err := b.SubscriptionSnapshot()
+ if err != nil {
+ return "", err
+ }
+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
+ return "", err
+ }
+ if err := storage.WriteJSONAtomic(path, snap, 0o600); err != nil {
+ return "", err
+ }
+ subs, accs := snap.Counts()
+ b.logInfo(fmt.Sprintf("subscriptions exported: subscriptions=%d accounts=%d", subs, accs))
+ return path, nil
+}
+
+// snapshotPath is path, or trace-subscriptions.json inside it when path is
+// a folder.
+func snapshotPath(path string) string {
+ path = strings.Trim(strings.TrimSpace(path), `"`)
+ if path == "" {
+ return ""
+ }
+ if st, err := os.Stat(path); (err == nil && st.IsDir()) || strings.HasSuffix(path, "/") || strings.HasSuffix(path, `\`) {
+ return filepath.Join(path, subscription.SnapshotFileName)
+ }
+ return path
+}
+
+func readSnapshotFile(path string) (subscription.Snapshot, error) {
+ path = snapshotPath(path)
+ raw, err := readFileLimited(path, int64(remote.MaxBodyBytes*8))
+ if err != nil {
+ if errors.Is(err, errFileTooLarge) {
+ return subscription.Snapshot{}, subscription.ErrBadSnapshot
+ }
+ return subscription.Snapshot{}, fmt.Errorf("读取订阅文件失败:%s", filepath.Base(path))
+ }
+ return subscription.ParseSnapshot(raw)
+}
+
+// PreviewSubscriptionImport reads a trace-subscriptions.json and reports
+// what importing it would change; nothing is written.
+func (b *Backend) PreviewSubscriptionImport(path string) (subscription.ImportPreview, error) {
+ snap, err := readSnapshotFile(path)
+ if err != nil {
+ return subscription.ImportPreview{}, err
+ }
+ return b.subs.PreviewImport(snap)
+}
+
+// ApplySubscriptionImport imports the file with the user's choices in one
+// write; the synced settings in the file are not applied on the desktop.
+func (b *Backend) ApplySubscriptionImport(path string, choices subscription.ImportChoices) (subscription.ImportPreview, error) {
+ snap, err := readSnapshotFile(path)
+ if err != nil {
+ return subscription.ImportPreview{}, err
+ }
+ res, err := b.subs.ApplyImport(snap, choices)
+ if err != nil {
+ return res, err
+ }
+ b.logInfo(fmt.Sprintf("subscriptions imported: new=%d existing=%d merge=%v rules=%d", len(res.New), len(res.Existing), choices.MergeExisting, len(choices.UseImportedRules)))
+ if subs, err := b.subs.List(); err == nil {
+ for _, s := range subs {
+ b.rememberAccountAvatars(s.Accounts)
+ }
+ }
+ b.events.Publish(EventSubscriptionChecked, "imported")
+ return res, nil
+}
+
+func marshalSnapshot(snap subscription.Snapshot) ([]byte, error) {
+ raw, err := json.Marshal(snap)
+ if err != nil {
+ return nil, err
+ }
+ if len(raw) > remote.MaxBodyBytes {
+ return nil, fmt.Errorf("订阅太多,同步内容超过 1 MiB")
+ }
+ return raw, nil
+}
+
+// syncState is what the remote remembers of the last subscription sync and
+// Cookie pushes (/remote-sync.json).
+type syncState struct {
+ Hash string `json:"hash,omitempty"`
+ SyncedAt string `json:"syncedAt,omitempty"`
+ Subscriptions int `json:"subscriptions"`
+ Accounts int `json:"accounts"`
+ CookieSyncedAt map[string]string `json:"cookieSyncedAt,omitempty"`
+}
+
+const syncStateFile = "remote-sync.json"
+
+func (b *Backend) loadSyncStateLocked() syncState {
+ var st syncState
+ raw, err := os.ReadFile(filepath.Join(b.loc.DataDir, syncStateFile))
+ if err == nil {
+ _ = json.Unmarshal(raw, &st)
+ }
+ return st
+}
+
+func (b *Backend) loadSyncState() syncState {
+ b.syncStateMu.Lock()
+ defer b.syncStateMu.Unlock()
+ return b.loadSyncStateLocked()
+}
+
+func (b *Backend) mutateSyncState(fn func(*syncState)) (syncState, error) {
+ b.syncStateMu.Lock()
+ defer b.syncStateMu.Unlock()
+ st := b.loadSyncStateLocked()
+ fn(&st)
+ if err := storage.WriteJSONAtomic(filepath.Join(b.loc.DataDir, syncStateFile), st, 0o600); err != nil {
+ return syncState{}, err
+ }
+ return st, nil
+}
diff --git a/internal/service/service_test.go b/internal/service/service_test.go
index 021f9f6..2463871 100644
--- a/internal/service/service_test.go
+++ b/internal/service/service_test.go
@@ -39,7 +39,7 @@ func newTestBiliServer(t *testing.T) *httptest.Server {
mux.HandleFunc("/bfs/", func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Cookie") != "" || r.Header.Get("Referer") != "" {
- t.Errorf("R11 violation: thumbnail request leaked Cookie or Referer: %v", r.Header)
+ t.Errorf("thumbnail request leaked Cookie or Referer: %v", r.Header)
}
w.Header().Set("Content-Type", "image/png")
_, _ = w.Write(samplePNG(color.RGBA{R: 214, G: 51, B: 108, A: 255}))
@@ -363,7 +363,7 @@ func TestServiceAuthIsolationOpenLinkAndRedaction(t *testing.T) {
t.Fatalf("OpenLink live failed: res=%+v err=%v", liveRes, err)
}
- // Verify MockDesktop records external URL and folder open actions without spawning OS processes (§6.4).
+ // Verify MockDesktop records external URL and folder open actions without spawning OS processes.
if err := b.OpenLiveRoomInBrowser(223344); err != nil {
t.Fatalf("OpenLiveRoomInBrowser: %v", err)
}
@@ -419,19 +419,19 @@ func TestServiceAuthIsolationOpenLinkAndRedaction(t *testing.T) {
scanned++
for _, sec := range []string{secretSess, secretJct, secretRefresh, "spm_id_from"} {
if strings.Contains(string(raw), sec) {
- t.Fatalf("C37 violation: file %s leaked secret/tracking string %q", fp, sec)
+ t.Fatalf("secret leak: file %s leaked secret/tracking string %q", fp, sec)
}
}
return nil
})
}
- t.Logf("C37 scanned %d files", scanned)
+ t.Logf("secret scan covered %d files", scanned)
if scanned < len(filesToCheck) {
- t.Fatalf("C37 scan covered only %d files", scanned)
+ t.Fatalf("secret scan covered only %d files", scanned)
}
for _, sec := range []string{secretSess, secretJct, secretRefresh} {
if strings.Contains(string(diagBytes), sec) {
- t.Fatalf("C37 violation: DiagnosticsSnapshot leaked secret %q", sec)
+ t.Fatalf("secret leak: DiagnosticsSnapshot leaked secret %q", sec)
}
}
diff --git a/internal/service/subscription_service.go b/internal/service/subscription_service.go
new file mode 100644
index 0000000..f982b5f
--- /dev/null
+++ b/internal/service/subscription_service.go
@@ -0,0 +1,474 @@
+package service
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/chialecode/trace/internal/site"
+ "github.com/chialecode/trace/internal/site/bilibili"
+ "github.com/chialecode/trace/internal/subscription"
+)
+
+// AccountCheckRow is a row of Tasks › 检查计划: an account's update checks
+// and, when its subscription records broadcasts, its live checks.
+type AccountCheckRow struct {
+ subscription.AccountCheckPlan
+ // LiveCheckedAt is the last live status check (RFC 3339), "" if none
+ // in this run; LiveEverySec how often one comes, about.
+ LiveCheckedAt string `json:"liveCheckedAt,omitempty"`
+ LiveEverySec int `json:"liveEverySec,omitempty"`
+}
+
+// ListSubscriptions returns all creator subscriptions.
+func (b *Backend) ListSubscriptions() ([]subscription.Subscription, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return nil, err
+ }
+ return b.subs.List()
+}
+
+// UpsertSubscription creates or updates a creator subscription.
+func (b *Backend) UpsertSubscription(sub subscription.Subscription) (subscription.Subscription, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return subscription.Subscription{}, err
+ }
+ res, err := b.subs.Upsert(sub)
+ if err == nil {
+ // A user page subscribes with only Mid and Face; the stored accounts
+ // then carry that face. Raw input accounts win when given.
+ if len(sub.Accounts) > 0 {
+ b.rememberAccountAvatars(sub.Accounts)
+ } else {
+ b.rememberAccountAvatars(res.Accounts)
+ }
+ b.events.Publish(EventSubscriptionChecked, "upserted")
+ }
+ return res, err
+}
+
+// CreateSubscription creates a new multi-account subscription.
+func (b *Backend) CreateSubscription(name, note string, accounts []subscription.AccountRef, rules subscription.SubRules) (subscription.Subscription, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return subscription.Subscription{}, err
+ }
+ res, err := b.subs.Create(name, note, accounts, rules)
+ if err == nil {
+ // The input still has the raw avatar URL; a stored Douyin one is dropped.
+ b.rememberAccountAvatars(accounts)
+ b.events.Publish(EventSubscriptionChecked, "created")
+ }
+ return res, err
+}
+
+// LinkSubscriptionAccount links an account to an existing subscription.
+func (b *Backend) LinkSubscriptionAccount(subID, siteID, uid, name, face string) (subscription.Subscription, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return subscription.Subscription{}, err
+ }
+ res, err := b.subs.Link(subID, siteID, uid, name, face)
+ if err == nil {
+ b.rememberAccountAvatar(siteID, uid, face)
+ b.events.Publish(EventSubscriptionChecked, "linked")
+ }
+ return res, err
+}
+
+// LinkSubscriptionAccountRef links an AccountRef (preserving Douyin UniqueID and WebRID) to a subscription.
+func (b *Backend) LinkSubscriptionAccountRef(subID string, acct subscription.AccountRef) (subscription.Subscription, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return subscription.Subscription{}, err
+ }
+ res, err := b.subs.LinkAccount(subID, acct)
+ if err == nil {
+ b.rememberAccountAvatar(acct.Site, acct.UID, acct.Face)
+ b.events.Publish(EventSubscriptionChecked, "linked")
+ }
+ return res, err
+}
+
+// UnlinkSubscriptionAccount removes an account from a subscription.
+func (b *Backend) UnlinkSubscriptionAccount(subID, siteID, uid string) (subscription.Subscription, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return subscription.Subscription{}, err
+ }
+ res, err := b.subs.Unlink(subID, siteID, uid)
+ if err == nil {
+ b.pruneAccountAvatars()
+ b.events.Publish(EventSubscriptionChecked, "unlinked")
+ }
+ return res, err
+}
+
+// MoveSubscriptionAccount atomically moves an account from its current subscription to toSubID.
+func (b *Backend) MoveSubscriptionAccount(siteID, uid, toSubID string) (subscription.Subscription, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return subscription.Subscription{}, err
+ }
+ res, err := b.subs.Move(siteID, uid, toSubID)
+ if err == nil {
+ b.events.Publish(EventSubscriptionChecked, "moved")
+ }
+ return res, err
+}
+
+// SetSubscriptionRules updates per-subscription rules and manages AutoCache.Since.
+func (b *Backend) SetSubscriptionRules(subID string, rules subscription.SubRules) (subscription.Subscription, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return subscription.Subscription{}, err
+ }
+ res, err := b.subs.SetRules(subID, rules)
+ if err == nil {
+ b.events.Publish(EventSubscriptionChecked, "rules_updated")
+ }
+ return res, err
+}
+
+// ListCacheRules returns the shared cache rules, the built-in one first.
+func (b *Backend) ListCacheRules() []subscription.CacheRule {
+ return b.subs.ListRules()
+}
+
+// SaveCacheRule creates or edits a shared rule and applies it to every subscription that uses it.
+func (b *Backend) SaveCacheRule(rule subscription.CacheRule) (subscription.CacheRule, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return subscription.CacheRule{}, err
+ }
+ res, err := b.subs.SaveRule(rule)
+ if err == nil {
+ b.events.Publish(EventSubscriptionChecked, "rules_updated")
+ }
+ return res, err
+}
+
+// DeleteCacheRule removes a shared rule; its subscriptions use the default.
+func (b *Backend) DeleteCacheRule(id string) error {
+ if err := b.requireAnyLogin(); err != nil {
+ return err
+ }
+ err := b.subs.DeleteRule(id)
+ if err == nil {
+ b.events.Publish(EventSubscriptionChecked, "rules_updated")
+ }
+ return err
+}
+
+// SetSubscriptionRule makes a subscription use a shared rule.
+func (b *Backend) SetSubscriptionRule(subID, ruleID string) (subscription.Subscription, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return subscription.Subscription{}, err
+ }
+ res, err := b.subs.SetSubscriptionRule(subID, ruleID)
+ if err == nil {
+ b.events.Publish(EventSubscriptionChecked, "rules_updated")
+ }
+ return res, err
+}
+
+// SetSubscriptionsRule assigns a shared rule to the selected subscriptions in one batch;
+// unselected subscriptions that previously used a non-default rule fall back to DefaultRuleID.
+func (b *Backend) SetSubscriptionsRule(ruleID string, subIDs []string) error {
+ if err := b.requireAnyLogin(); err != nil {
+ return err
+ }
+ err := b.subs.SetSubscriptionsRule(ruleID, subIDs)
+ if err == nil {
+ b.events.Publish(EventSubscriptionChecked, "rules_updated")
+ }
+ return err
+}
+
+// PreviewAccount resolves a Bilibili or Douyin account input and checks whether it is already owned by a subscription.
+func (b *Backend) PreviewAccount(ctx context.Context, input string) (subscription.AccountRef, *subscription.Subscription, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return subscription.AccountRef{}, nil, err
+ }
+ siteID, normalized, err := b.registry.DetectSite(input)
+ if err != nil {
+ return subscription.AccountRef{}, nil, err
+ }
+ if err := b.requireSiteLogin(siteID); err != nil {
+ return subscription.AccountRef{}, nil, err
+ }
+
+ if siteID == site.Douyin {
+ target, rErr := b.douyin.ResolveLink(ctx, normalized)
+ if rErr != nil {
+ return subscription.AccountRef{}, nil, rErr
+ }
+ var secUID string
+ switch target.Kind {
+ case "user":
+ secUID = firstNonEmpty(target.SecUID, target.ID)
+ case "live":
+ lv, lErr := b.DouyinLive(ctx, firstNonEmpty(target.WebRID, target.ID))
+ if lErr != nil {
+ return subscription.AccountRef{}, nil, lErr
+ }
+ secUID = lv.OwnerSecUID
+ default:
+ return subscription.AccountRef{}, nil, &site.Error{
+ Site: site.Douyin,
+ Kind: site.ErrKindBadRequest,
+ Message: "请粘贴抖音用户主页链接、分享文本或 sec_uid",
+ }
+ }
+ uv, uErr := b.DouyinUser(ctx, secUID)
+ if uErr != nil {
+ return subscription.AccountRef{}, nil, uErr
+ }
+ acc := subscription.AccountRef{
+ Site: string(site.Douyin),
+ UID: uv.SecUID,
+ UniqueID: uv.UniqueID,
+ WebRID: uv.WebRID,
+ Name: uv.Nickname,
+ Face: uv.AvatarURL,
+ AddedAt: time.Now().UTC().Format(time.RFC3339),
+ }
+ return b.subs.PreviewResolvedAccount(acc)
+ }
+
+ target, err := b.bili.ResolveLink(ctx, normalized)
+ if err != nil {
+ return subscription.AccountRef{}, nil, err
+ }
+ if target.Kind != "user" {
+ return subscription.AccountRef{}, nil, fmt.Errorf("请粘贴用户主页链接或 UID")
+ }
+ card, err := b.bili.UserCard(ctx, target.Mid)
+ if err != nil {
+ return subscription.AccountRef{}, nil, err
+ }
+ uidStr := fmt.Sprintf("%d", card.Mid)
+ acc := subscription.AccountRef{
+ Site: "bilibili",
+ UID: uidStr,
+ Name: card.Name,
+ Face: card.Face,
+ AddedAt: time.Now().UTC().Format(time.RFC3339),
+ }
+ if owner, owned := b.subs.OwnerOf("bilibili", uidStr); owned {
+ return acc, &owner, nil
+ }
+ return acc, nil, nil
+}
+
+// OwnerOfAccount returns the subscription owning (site, uid), if any.
+func (b *Backend) OwnerOfAccount(siteID, uid string) (subscription.Subscription, bool) {
+ if b.requireAnyLogin() != nil {
+ return subscription.Subscription{}, false
+ }
+ return b.subs.OwnerOf(siteID, uid)
+}
+
+// ListSubscriptionUpdates returns discovered update items for a subscription.
+func (b *Backend) ListSubscriptionUpdates(subID string) ([]subscription.UpdateItem, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return nil, err
+ }
+ return b.subs.ListUpdates(subID)
+}
+
+// ListSubscriptionUpdatesPage returns a paginated slice of discovered update items for a subscription.
+func (b *Backend) ListSubscriptionUpdatesPage(subID string, limit, offset int) ([]subscription.UpdateItem, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return nil, err
+ }
+ return b.subs.ListUpdatesPage(subID, limit, offset)
+}
+
+// DeleteSubscription removes a creator subscription.
+func (b *Backend) DeleteSubscription(subIDOrMid string) error {
+ if err := b.requireAnyLogin(); err != nil {
+ return err
+ }
+ err := b.subs.Delete(subIDOrMid)
+ if err == nil {
+ b.pruneAccountAvatars()
+ b.events.Publish(EventSubscriptionChecked, "deleted")
+ }
+ return err
+}
+
+// CheckSubscriptionsNow triggers an immediate incremental check for targetMid (or 0 for all enabled).
+func (b *Backend) CheckSubscriptionsNow(ctx context.Context, targetMid int64) (subscription.CheckSummary, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return subscription.CheckSummary{}, err
+ }
+ if targetMid > 0 {
+ if err := b.requireSiteLogin(site.Bilibili); err != nil {
+ return subscription.CheckSummary{}, err
+ }
+ }
+ return b.subs.CheckNow(ctx, targetMid)
+}
+
+// CheckSubscription triggers an immediate check for all accounts of subID.
+func (b *Backend) CheckSubscription(ctx context.Context, subID string) (subscription.CheckSummary, error) {
+ if err := b.requireAnyLogin(); err != nil {
+ return subscription.CheckSummary{}, err
+ }
+ return b.subs.CheckSubscription(ctx, subID)
+}
+
+// CheckAccount checks one account of a subscription for updates at once.
+func (b *Backend) CheckAccount(ctx context.Context, subID, siteName, uid string) (subscription.CheckSummary, error) {
+ id, err := normalizeSiteID(siteName)
+ if err != nil {
+ return subscription.CheckSummary{}, err
+ }
+ if err := b.requireSiteLogin(id); err != nil {
+ return subscription.CheckSummary{}, err
+ }
+ return b.subs.CheckAccount(ctx, subID, string(id), uid)
+}
+
+// CancelSubscriptionCheck cancels an in-progress subscription update check.
+func (b *Backend) CancelSubscriptionCheck() { b.subs.CancelCheck() }
+
+func formatBackoffLevelText(level int) string {
+ switch {
+ case level <= 1:
+ return "15 分钟"
+ case level == 2:
+ return "30 分钟"
+ case level == 3:
+ return "1 小时"
+ case level == 4:
+ return "2 小时"
+ default:
+ return "6 小时"
+ }
+}
+
+// SchedulerStatuses returns per-site scheduled check timing and backoff state for Settings -> 订阅与直播.
+func (b *Backend) SchedulerStatuses() map[string]SiteSchedulerStatus {
+ out := make(map[string]SiteSchedulerStatus, 2)
+ var states map[string]subscription.SchedulerState
+ if b.subs != nil {
+ states = b.subs.ListSiteSchedulerStates()
+ }
+ for _, id := range site.All() {
+ key := string(id)
+ label := "哔哩哔哩"
+ if id == site.Douyin {
+ label = "抖音"
+ }
+ st := SiteSchedulerStatus{
+ Site: key,
+ DisplayName: label,
+ }
+ if b.subs != nil {
+ raw := states[key]
+ st.LastError = raw.LastStopReason
+ if inBackoff, until := b.subs.IsSiteInBackoff(key); inBackoff {
+ lvlText := formatBackoffLevelText(raw.BackoffLevel)
+ st.BackingOff = true
+ st.CurrentInterval = lvlText
+ st.BackoffUntil = until.UTC().Format("2006-01-02T15:04:05Z07:00")
+ st.BackoffSummary = fmt.Sprintf("%s:因风控放慢到 %s,%s 恢复", label, lvlText, until.Local().Format("1 月 2 日 15:04"))
+ }
+ }
+ out[key] = st
+ }
+ return out
+}
+
+// CheckPlan lists every subscribed account with its last update check and
+// the scheduled round expected to check it next, plus the live checks of
+// accounts whose subscriptions record broadcasts.
+func (b *Backend) CheckPlan() []AccountCheckRow {
+ if b.requireAnyLogin() != nil {
+ return nil
+ }
+ return b.checkPlanLocal()
+}
+
+// checkPlanLocal builds the check plan strictly from local subscription and
+// live state without requiring an active site login (used by remote status).
+func (b *Backend) checkPlanLocal() []AccountCheckRow {
+ if b.subs == nil {
+ return nil
+ }
+ plans := b.subs.CheckPlan()
+ var liveAt map[string]time.Time
+ if b.live != nil {
+ liveAt = b.live.LiveCheckTimes()
+ }
+ autoRecord := map[string]int{}
+ for _, p := range plans {
+ if p.AutoRecord {
+ autoRecord[p.Site]++
+ }
+ }
+ out := make([]AccountCheckRow, 0, len(plans))
+ for _, p := range plans {
+ row := AccountCheckRow{AccountCheckPlan: p}
+ if p.AutoRecord && b.live != nil {
+ if at, ok := liveAt[p.Site+":"+p.UID]; ok {
+ row.LiveCheckedAt = at.UTC().Format(time.RFC3339)
+ }
+ row.LiveEverySec = int(b.live.LiveCheckEvery(site.ID(p.Site), autoRecord[p.Site]).Seconds())
+ }
+ out = append(out, row)
+ }
+ return out
+}
+
+// RelationTags returns the logged-in user's Bilibili following groups.
+func (b *Backend) RelationTags(ctx context.Context) ([]bilibili.RelationTag, error) {
+ if err := b.requireSiteLogin(site.Bilibili); err != nil {
+ return nil, err
+ }
+ return b.bili.RelationTags(ctx)
+}
+
+// RelationFollowings returns a page of Bilibili followings (either for a specific tagID > 0 or all followings when tagID == 0).
+func (b *Backend) RelationFollowings(ctx context.Context, tagID int64, pn, ps int) ([]bilibili.FollowingUser, error) {
+ if err := b.requireSiteLogin(site.Bilibili); err != nil {
+ return nil, err
+ }
+ if tagID != 0 {
+ mid := b.cred.Status().Mid
+ return b.bili.RelationTagUsers(ctx, mid, tagID, pn, ps)
+ }
+ page, err := b.bili.RelationFollowings(ctx, 0, pn, ps)
+ if err != nil {
+ return nil, err
+ }
+ return page.Items, nil
+}
+
+// ImportCreators imports selected Bilibili creators into subscriptions idempotently.
+func (b *Backend) ImportCreators(users []bilibili.FollowingUser, scope, autoCache string, liveNotify, liveAutoRecord bool) (int, error) {
+ if err := b.requireSiteLogin(site.Bilibili); err != nil {
+ return 0, err
+ }
+ n, err := b.subs.ImportCreators(users, scope, autoCache, liveNotify, liveAutoRecord)
+ if err == nil {
+ b.events.Publish(EventSubscriptionChecked, "imported")
+ }
+ return n, err
+}
+
+// subscribedAccountName is the name an account has in the subscriptions
+// (empty when it is not subscribed or has none).
+func (b *Backend) subscribedAccountName(siteID site.ID, uid string) string {
+ if b.subs == nil {
+ return ""
+ }
+ subs, err := b.subs.List()
+ if err != nil {
+ return ""
+ }
+ for _, sub := range subs {
+ for _, acc := range sub.Accounts {
+ if strings.EqualFold(acc.Site, string(siteID)) && acc.UID == uid && strings.TrimSpace(acc.Name) != "" {
+ return strings.TrimSpace(acc.Name)
+ }
+ }
+ }
+ return ""
+}
diff --git a/internal/service/transfer_jobs.go b/internal/service/transfer_jobs.go
new file mode 100644
index 0000000..3be52a5
--- /dev/null
+++ b/internal/service/transfer_jobs.go
@@ -0,0 +1,369 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/transfer"
+)
+
+// TransferService is 媒体库 › 导入… / 导出… (docs/design/remote.md §6.3,
+// §6.4): background jobs listed on the Tasks page under 导入.
+type TransferService interface {
+ // StartImportScan scans a folder (read-only) in the background; the
+ // job becomes "ready" with a plan to confirm.
+ StartImportScan(path string) (TransferJob, error)
+ // ImportPlan returns the plan of a scanned job.
+ ImportPlan(jobID string) (transfer.Plan, bool)
+ // StartImport imports a scanned plan with the user's answers.
+ StartImport(jobID string, choices transfer.Choices) (TransferJob, error)
+ // StartExport copies the items of a media library filter (everything
+ // when empty; Limit and Offset are ignored) into a folder.
+ StartExport(target string, filter library.FeedFilter) (TransferJob, error)
+ TransferJobs() []TransferJob
+ // CancelTransfer stops a scan, import or export; a ready plan is
+ // dropped.
+ CancelTransfer(jobID string) error
+}
+
+var _ TransferService = (*Backend)(nil)
+
+// Transfer job states.
+const (
+ TransferScanning = "scanning"
+ TransferReady = "ready"
+ TransferRunning = "running"
+ TransferDone = "done"
+ TransferFailed = "failed"
+ TransferCanceled = "canceled"
+)
+
+// TransferJob is one import or export.
+type TransferJob struct {
+ ID string `json:"id"`
+ Kind string `json:"kind"` // "import" or "export"
+ Status string `json:"status"`
+ Source string `json:"source,omitempty"`
+ Target string `json:"target,omitempty"`
+ Progress transfer.Progress `json:"progress"`
+ SpeedBps int64 `json:"speedBps"`
+ Counts map[transfer.Category]int `json:"counts,omitempty"`
+ Summary *transfer.Summary `json:"summary,omitempty"`
+ Export *transfer.ExportSummary `json:"export,omitempty"`
+ Error string `json:"error,omitempty"`
+ StartedAt string `json:"startedAt"`
+ FinishedAt string `json:"finishedAt,omitempty"`
+}
+
+// Active reports whether the job is still working.
+func (j TransferJob) Active() bool {
+ return j.Status == TransferScanning || j.Status == TransferRunning
+}
+
+type transferJobs struct {
+ mu sync.Mutex
+ seq int
+ jobs map[string]*transferJobState
+}
+
+type transferJobState struct {
+ job TransferJob
+ plan *transfer.Plan
+ cancel context.CancelFunc
+ lastAt time.Time
+ lastByte int64
+ lastPub time.Time
+}
+
+func (b *Backend) transfers() *transferJobs {
+ b.transferOnce.Do(func() { b.transferState = &transferJobs{jobs: map[string]*transferJobState{}} })
+ return b.transferState
+}
+
+func cloneTransferJob(j TransferJob) TransferJob {
+ if len(j.Counts) > 0 {
+ counts := make(map[transfer.Category]int, len(j.Counts))
+ for k, v := range j.Counts {
+ counts[k] = v
+ }
+ j.Counts = counts
+ }
+ if j.Summary != nil {
+ s := *j.Summary
+ if len(s.Errors) > 0 {
+ s.Errors = append([]string(nil), s.Errors...)
+ }
+ j.Summary = &s
+ }
+ if j.Export != nil {
+ e := *j.Export
+ if len(e.Errors) > 0 {
+ e.Errors = append([]string(nil), e.Errors...)
+ }
+ j.Export = &e
+ }
+ return j
+}
+
+func (b *Backend) newTransferJob(kind, source, target, status string) (*transferJobState, TransferJob, context.Context, context.CancelFunc) {
+ t := b.transfers()
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ t.seq++
+ ctx, cancel := context.WithCancel(b.bgCtx)
+ st := &transferJobState{job: TransferJob{ID: fmt.Sprintf("%s-%d-%d", kind, time.Now().Unix(), t.seq), Kind: kind, Status: status, Source: source, Target: target,
+ StartedAt: time.Now().UTC().Format(time.RFC3339)}, cancel: cancel, lastAt: time.Now()}
+ t.jobs[st.job.ID] = st
+ return st, cloneTransferJob(st.job), ctx, cancel
+}
+
+func (b *Backend) hasActiveTransferJobs() bool {
+ t := b.transfers()
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ for _, st := range t.jobs {
+ if st.job.Active() {
+ return true
+ }
+ }
+ return false
+}
+
+func (b *Backend) updateTransfer(st *transferJobState, fn func(j *TransferJob)) {
+ t := b.transfers()
+ t.mu.Lock()
+ fn(&st.job)
+ id := st.job.ID
+ now := time.Now()
+ publish := !st.job.Active() || now.Sub(st.lastPub) > 250*time.Millisecond
+ if publish {
+ st.lastPub = now
+ }
+ t.mu.Unlock()
+ if publish {
+ b.events.Publish(EventTransferUpdated, id)
+ }
+}
+
+func (b *Backend) transferProgress(st *transferJobState) func(transfer.Progress) {
+ return func(p transfer.Progress) {
+ b.updateTransfer(st, func(j *TransferJob) {
+ j.Progress = p
+ now := time.Now()
+ if dt := now.Sub(st.lastAt); dt >= time.Second {
+ j.SpeedBps = int64(float64(p.Bytes-st.lastByte) / dt.Seconds())
+ st.lastAt, st.lastByte = now, p.Bytes
+ }
+ })
+ }
+}
+
+func (b *Backend) finishTransfer(st *transferJobState, err error, fn func(j *TransferJob)) {
+ b.updateTransfer(st, func(j *TransferJob) {
+ if fn != nil {
+ fn(j)
+ }
+ j.SpeedBps = 0
+ j.FinishedAt = time.Now().UTC().Format(time.RFC3339)
+ switch {
+ case errors.Is(err, context.Canceled):
+ j.Status = TransferCanceled
+ case err != nil:
+ j.Status, j.Error = TransferFailed, b.sanitizeLogLine(err.Error())
+ case j.Status == TransferScanning:
+ j.Status = TransferReady
+ default:
+ j.Status = TransferDone
+ }
+ if j.Status != TransferReady {
+ st.plan = nil
+ }
+ })
+}
+
+// StartImportScan scans path in the background.
+func (b *Backend) StartImportScan(path string) (TransferJob, error) {
+ if err := b.requireDesktop(); err != nil {
+ return TransferJob{}, err
+ }
+ path = strings.TrimSpace(path)
+ if path == "" {
+ return TransferJob{}, errors.New("请填写要导入的文件夹")
+ }
+ st, job, ctx, cancel := b.newTransferJob("import", path, b.lib.CacheDir(), TransferScanning)
+ started := b.goBg(func(context.Context) {
+ defer cancel()
+ plan, err := transfer.Scan(ctx, path, b.lib, b.transferProgress(st))
+ b.finishTransfer(st, err, func(j *TransferJob) {
+ if err == nil {
+ st.plan = &plan
+ j.Counts = plan.Counts
+ }
+ })
+ if err == nil {
+ b.logInfo(fmt.Sprintf("import scanned: items=%d", len(plan.Entries)))
+ }
+ })
+ if !started {
+ cancel()
+ b.finishTransfer(st, context.Canceled, nil)
+ return TransferJob{}, errors.New("后端正在关闭")
+ }
+ return job, nil
+}
+
+// ImportPlan returns a scanned job's plan.
+func (b *Backend) ImportPlan(jobID string) (transfer.Plan, bool) {
+ t := b.transfers()
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ st, ok := t.jobs[jobID]
+ if !ok || st.plan == nil {
+ return transfer.Plan{}, false
+ }
+ return *st.plan, true
+}
+
+// StartImport imports a ready plan.
+func (b *Backend) StartImport(jobID string, choices transfer.Choices) (TransferJob, error) {
+ if err := b.requireDesktop(); err != nil {
+ return TransferJob{}, err
+ }
+ t := b.transfers()
+ t.mu.Lock()
+ st, ok := t.jobs[jobID]
+ if !ok || st.plan == nil || st.job.Status != TransferReady {
+ t.mu.Unlock()
+ return TransferJob{}, errors.New("这次扫描已失效,请重新扫描")
+ }
+ plan := *st.plan
+ prevCancel := st.cancel
+ ctx, cancel := context.WithCancel(b.bgCtx)
+ st.cancel = cancel
+ st.job.Status = TransferRunning
+ st.job.FinishedAt = ""
+ st.job.Progress = transfer.Progress{}
+ st.job.SpeedBps = 0
+ st.job.Error = ""
+ st.lastAt, st.lastByte = time.Now(), 0
+ job := cloneTransferJob(st.job)
+ t.mu.Unlock()
+ if prevCancel != nil {
+ prevCancel()
+ }
+ b.events.Publish(EventTransferUpdated, jobID)
+ started := b.goBg(func(context.Context) {
+ defer cancel()
+ sum, err := transfer.Apply(ctx, plan, choices, b.lib, b.transferProgress(st))
+ b.finishTransfer(st, err, func(j *TransferJob) { s := sum; j.Summary = &s })
+ b.logInfo(fmt.Sprintf("import finished: new=%d supplemented=%d conflicts=%d incomplete=%d files=%d errors=%d", sum.Imported, sum.Supplemented, sum.Conflicts, sum.Incomplete, sum.Files, len(sum.Errors)))
+ b.events.Publish(EventLibraryChanged, "import")
+ })
+ if !started {
+ cancel()
+ b.finishTransfer(st, context.Canceled, nil)
+ return TransferJob{}, errors.New("后端正在关闭")
+ }
+ return job, nil
+}
+
+// StartExport exports the items of filter into target.
+func (b *Backend) StartExport(target string, filter library.FeedFilter) (TransferJob, error) {
+ if err := b.requireDesktop(); err != nil {
+ return TransferJob{}, err
+ }
+ target = strings.TrimSpace(target)
+ if target == "" {
+ return TransferJob{}, errors.New("请填写导出到的文件夹")
+ }
+ items, err := exportItems(b.lib, filter)
+ if err != nil {
+ return TransferJob{}, err
+ }
+ if len(items) == 0 {
+ return TransferJob{}, errors.New("当前范围内没有可导出的内容")
+ }
+ st, job, ctx, cancel := b.newTransferJob("export", b.lib.CacheDir(), target, TransferRunning)
+ started := b.goBg(func(context.Context) {
+ defer cancel()
+ sum, err := transfer.Export(ctx, items, b.lib, target, b.transferProgress(st))
+ b.finishTransfer(st, err, func(j *TransferJob) { s := sum; j.Export = &s })
+ b.logInfo(fmt.Sprintf("export finished: items=%d files=%d errors=%d", sum.Items, sum.Files, len(sum.Errors)))
+ })
+ if !started {
+ cancel()
+ b.finishTransfer(st, context.Canceled, nil)
+ return TransferJob{}, errors.New("后端正在关闭")
+ }
+ return job, nil
+}
+
+// exportPageSize is how many items exportItems reads at a time.
+var exportPageSize = 500
+
+// exportItems lists every item of filter, page by page (ListItems returns
+// at most one page).
+func exportItems(lib interface {
+ ListItems(library.FeedFilter) ([]library.ItemMetadata, error)
+}, filter library.FeedFilter) ([]library.ItemMetadata, error) {
+ page := exportPageSize
+ filter.Limit, filter.Sort = page, "oldest"
+ var out []library.ItemMetadata
+ for offset := 0; ; offset += page {
+ filter.Offset = offset
+ items, err := lib.ListItems(filter)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, items...)
+ if len(items) < page {
+ return out, nil
+ }
+ }
+}
+
+// TransferJobs lists the jobs of this run, newest first.
+func (b *Backend) TransferJobs() []TransferJob {
+ t := b.transfers()
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ out := make([]TransferJob, 0, len(t.jobs))
+ for _, st := range t.jobs {
+ out = append(out, cloneTransferJob(st.job))
+ }
+ sort.Slice(out, func(i, j int) bool {
+ if out[i].StartedAt != out[j].StartedAt {
+ return out[i].StartedAt > out[j].StartedAt
+ }
+ return out[i].ID > out[j].ID
+ })
+ return out
+}
+
+// CancelTransfer stops a job, or drops a ready plan.
+func (b *Backend) CancelTransfer(jobID string) error {
+ t := b.transfers()
+ t.mu.Lock()
+ st, ok := t.jobs[jobID]
+ if !ok {
+ t.mu.Unlock()
+ return nil
+ }
+ if st.job.Status == TransferReady {
+ st.job.Status, st.plan = TransferCanceled, nil
+ st.job.FinishedAt = time.Now().UTC().Format(time.RFC3339)
+ }
+ cancel := st.cancel
+ t.mu.Unlock()
+ if cancel != nil {
+ cancel()
+ }
+ b.events.Publish(EventTransferUpdated, jobID)
+ return nil
+}
diff --git a/internal/service/transfer_jobs_test.go b/internal/service/transfer_jobs_test.go
new file mode 100644
index 0000000..93f1b31
--- /dev/null
+++ b/internal/service/transfer_jobs_test.go
@@ -0,0 +1,126 @@
+package service
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/chialecode/trace/internal/library"
+ "github.com/chialecode/trace/internal/transfer"
+)
+
+func transferTestBackend(t *testing.T) *Backend {
+ t.Helper()
+ b, err := NewBackend(Options{Locations: testLocations(t), Desktop: NewMockDesktop(), DisableBgWorkers: true})
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = b.Close() })
+ return b
+}
+
+func waitTransfer(t *testing.T, b *Backend, id string, want string) TransferJob {
+ t.Helper()
+ deadline := time.Now().Add(10 * time.Second)
+ for time.Now().Before(deadline) {
+ for _, j := range b.TransferJobs() {
+ if j.ID == id && !j.Active() {
+ if j.Status != want {
+ t.Fatalf("job %s: status %s (want %s), error %q", id, j.Status, want, j.Error)
+ }
+ return j
+ }
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ t.Fatalf("job %s did not finish", id)
+ return TransferJob{}
+}
+
+// TestTransferJobsExportEverythingAndImportElsewhere exports more items than
+// one page of the library list, then scans and imports the folder into
+// another installation through the job API.
+func TestTransferJobsExportEverythingAndImportElsewhere(t *testing.T) {
+ old := exportPageSize
+ exportPageSize = 2
+ t.Cleanup(func() { exportPageSize = old })
+
+ src := transferTestBackend(t)
+ for i := 1; i <= 5; i++ {
+ id := fmt.Sprintf("BV1tr%05d", i)
+ dir := filepath.Join(src.lib.CacheDir(), "bilibili", "1001", "video", id)
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ data := []byte("合成视频 " + id)
+ if err := os.WriteFile(filepath.Join(dir, "P01.mp4"), data, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ sum := sha256.Sum256(data)
+ meta := library.ItemMetadata{Version: 1, ID: "video:" + id, Site: "bilibili", Kind: "video", Title: "合成 " + id, Status: "complete",
+ Author: library.ItemAuthor{Mid: 1001, Name: "合成作者"},
+ Media: []library.MediaFile{{Role: "video", Path: "P01.mp4", Bytes: int64(len(data)), SHA256: hex.EncodeToString(sum[:])}}}
+ if _, err := src.lib.SaveItem(dir, meta); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, err := src.StartExport(t.TempDir(), library.FeedFilter{Site: "douyin"}); err == nil {
+ t.Fatal("export of an empty range should fail")
+ }
+ out := filepath.Join(t.TempDir(), "export")
+ job, err := src.StartExport(out, library.FeedFilter{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ done := waitTransfer(t, src, job.ID, TransferDone)
+ if done.Export == nil || done.Export.Items != 5 || done.Export.Files != 5 {
+ t.Fatalf("export summary = %+v", done.Export)
+ }
+
+ dst := transferTestBackend(t)
+ scan, err := dst.StartImportScan(out)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ready := waitTransfer(t, dst, scan.ID, TransferReady)
+ if ready.Counts[transfer.CategoryNew] != 5 {
+ t.Fatalf("scan counts = %v", ready.Counts)
+ }
+ if _, ok := dst.ImportPlan(scan.ID); !ok {
+ t.Fatal("ready job has no plan")
+ }
+ if _, err := dst.StartImport(scan.ID, transfer.Choices{}); err != nil {
+ t.Fatal(err)
+ }
+ imported := waitTransfer(t, dst, scan.ID, TransferDone)
+ if imported.Summary == nil || imported.Summary.Imported != 5 {
+ t.Fatalf("import summary = %+v", imported.Summary)
+ }
+ if _, err := dst.StartImport(scan.ID, transfer.Choices{}); err == nil {
+ t.Fatal("a finished plan should not import twice")
+ }
+ items, err := dst.lib.ListItems(library.FeedFilter{Limit: 50})
+ if err != nil || len(items) != 5 {
+ t.Fatalf("imported items = %d, %v", len(items), err)
+ }
+
+ // A ready plan that is dropped cannot be imported.
+ again, err := dst.StartImportScan(out)
+ if err != nil {
+ t.Fatal(err)
+ }
+ waitTransfer(t, dst, again.ID, TransferReady)
+ if err := dst.CancelTransfer(again.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := dst.ImportPlan(again.ID); ok {
+ t.Fatal("dropped plan still available")
+ }
+ if _, err := dst.StartImport(again.ID, transfer.Choices{}); err == nil {
+ t.Fatal("dropped plan imported")
+ }
+}
diff --git a/internal/settings/settings.go b/internal/settings/settings.go
index 85a3e9b..34d302d 100644
--- a/internal/settings/settings.go
+++ b/internal/settings/settings.go
@@ -48,10 +48,36 @@ type Settings struct {
Diagnostics DiagnosticsSettings `json:"diagnostics"`
Updates UpdateSettings `json:"updates"`
Network NetworkSettings `json:"network"`
+ // Remote is the connection to trace-server (docs/design/remote.md §3,
+ // §7). Optional; the access token is kept in the credential store,
+ // never here.
+ Remote RemoteSettings `json:"remote"`
+}
+
+// RemoteSettings holds the remote connections (one for now; a list so a
+// later cluster mode can add more) and the sites whose Cookie still has to
+// be pushed to the remote.
+type RemoteSettings struct {
+ Connections []RemoteConnection `json:"connections,omitempty"`
+ PendingCookies []PendingCookie `json:"pendingCookies,omitempty"`
+}
+
+// RemoteConnection is one remote: its address, name and pinned
+// certificate fingerprint.
+type RemoteConnection struct {
+ ID string `json:"id"`
+ Name string `json:"name,omitempty"`
+ URL string `json:"url"`
+ Fingerprint string `json:"fingerprint"`
+ AddedAt string `json:"addedAt,omitempty"`
+}
+
+// PendingCookie marks a site whose new Cookie the remote has not received.
+type PendingCookie struct {
+ Site string `json:"site"`
+ Since string `json:"since"`
}
-// UpdateSettings are the update preferences of the release channel
-// (FR-UPD-002): both on by default, a file without them keeps the defaults.
// NetworkSettings chooses the proxy of every site request (DEC-046 ⑤):
// "system" (default: the system's settings and HTTP(S)_PROXY), "none" or
// "custom" with ProxyURL (http://, https:// or socks5://).
@@ -60,6 +86,8 @@ type NetworkSettings struct {
ProxyURL string `json:"proxyUrl,omitempty"`
}
+// UpdateSettings are the update preferences of the release channel
+// (FR-UPD-002): both on by default, a file without them keeps the defaults.
type UpdateSettings struct {
AutoCheck bool `json:"autoCheck"`
AutoDownload bool `json:"autoDownload"`
@@ -357,6 +385,8 @@ func Normalize(s Settings, defaultCacheDir string) (Settings, error) {
if s.LiveCheckIntervalMin == 0 {
if s.Live.PollIntervalSeconds >= 60 {
s.LiveCheckIntervalMin = s.Live.PollIntervalSeconds / 60
+ } else if s.Live.PollIntervalSeconds >= 30 {
+ s.LiveCheckIntervalMin = 1
} else {
s.LiveCheckIntervalMin = 3
}
@@ -522,9 +552,18 @@ func Open(path, defaultCacheDir string) (*Store, bool, string, error) {
if bErr != nil {
return nil, false, "", bErr
}
- _ = storage.WriteJSONAtomic(path, def, 0o600)
+ if wErr := storage.WriteJSONAtomic(path, def, 0o600); wErr != nil {
+ return nil, true, backup, wErr
+ }
return s, true, backup, nil
}
+ if loaded.Version > 1 {
+ return nil, false, "", &storage.NewerDataError{
+ File: filepath.Base(path),
+ Found: loaded.Version,
+ Supported: 1,
+ }
+ }
norm, err := Normalize(loaded, defaultCacheDir)
if err != nil {
@@ -532,7 +571,9 @@ func Open(path, defaultCacheDir string) (*Store, bool, string, error) {
if bErr != nil {
return nil, false, "", bErr
}
- _ = storage.WriteJSONAtomic(path, def, 0o600)
+ if wErr := storage.WriteJSONAtomic(path, def, 0o600); wErr != nil {
+ return nil, true, backup, wErr
+ }
return s, true, backup, nil
}
@@ -591,7 +632,14 @@ func normalizeUpdate(next, before Settings, defaultCacheDir string) (Settings, e
syncChangedAlias(&next.MaxRecordings, &next.Live.MaxConcurrentRecordings, before.MaxRecordings, before.Live.MaxConcurrentRecordings)
syncChangedAlias(&next.CloseAction, &next.Window.CloseAction, before.CloseAction, before.Window.CloseAction)
if next.LiveCheckIntervalMin == before.LiveCheckIntervalMin && next.Live.PollIntervalSeconds != before.Live.PollIntervalSeconds {
- next.LiveCheckIntervalMin = next.Live.PollIntervalSeconds / 60
+ if next.Live.PollIntervalSeconds < 30 {
+ return Settings{}, fmt.Errorf("settings: live pollIntervalSeconds must be >= 30, got %d", next.Live.PollIntervalSeconds)
+ }
+ mins := next.Live.PollIntervalSeconds / 60
+ if mins < 1 {
+ mins = 1
+ }
+ next.LiveCheckIntervalMin = mins
}
if slices.Equal(next.CodecOrder, before.CodecOrder) && next.Download.PreferredVideoCodec != before.Download.PreferredVideoCodec {
next.CodecOrder = uniqueCodecs([]string{next.Download.PreferredVideoCodec, "avc", "av1", "hevc"})
@@ -614,5 +662,11 @@ func cloneSettings(in Settings) Settings {
if in.Live.CodecOrder != nil {
out.Live.CodecOrder = append([]string(nil), in.Live.CodecOrder...)
}
+ if in.Remote.Connections != nil {
+ out.Remote.Connections = append([]RemoteConnection(nil), in.Remote.Connections...)
+ }
+ if in.Remote.PendingCookies != nil {
+ out.Remote.PendingCookies = append([]PendingCookie(nil), in.Remote.PendingCookies...)
+ }
return out
}
diff --git a/internal/settings/settings_test.go b/internal/settings/settings_test.go
index 20826cf..b896cb0 100644
--- a/internal/settings/settings_test.go
+++ b/internal/settings/settings_test.go
@@ -80,10 +80,6 @@ func TestSettingsCorruptRecoveryAndUnknownFields(t *testing.T) {
}
}
-func TestSettingsSanitizeAndCorruptRecovery(t *testing.T) {
- TestSettingsCorruptRecoveryAndUnknownFields(t)
-}
-
func TestSettingsCanToggleRulesAndRestoreDefaults(t *testing.T) {
dir := t.TempDir()
store, _, _, err := Open(filepath.Join(dir, "settings.json"), filepath.Join(dir, "cache"))
@@ -113,3 +109,40 @@ func TestSettingsCanToggleRulesAndRestoreDefaults(t *testing.T) {
t.Fatalf("saved settings did not round trip: %+v %v", loaded, err)
}
}
+
+func TestSettingsCloneIsolatesRemoteSlicesAndPollInterval(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "settings.json")
+ store, _, _, err := Open(path, filepath.Join(dir, "cache"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ next := store.Get()
+ next.Live.PollIntervalSeconds = 45
+ next.Remote.Connections = []RemoteConnection{{ID: "r1", Name: "srv", URL: "https://example.com"}}
+ next.Remote.PendingCookies = []PendingCookie{{Site: "bilibili", Since: "2026-01-01T00:00:00Z"}}
+ updated, err := store.Update(next)
+ if err != nil {
+ t.Fatalf("Update: %v", err)
+ }
+ if updated.LiveCheckIntervalMin != 1 || updated.Live.PollIntervalSeconds != 60 {
+ t.Fatalf("45s poll interval = (%d min, %d sec), want (1, 60)", updated.LiveCheckIntervalMin, updated.Live.PollIntervalSeconds)
+ }
+ // Mutating caller or returned slices must not mutate committed state.
+ next.Remote.Connections[0].Name = "mutated-input"
+ updated.Remote.Connections[0].Name = "mutated-return"
+ next.Remote.PendingCookies[0].Site = "douyin"
+ updated.Remote.PendingCookies[0].Site = "douyin"
+ got := store.Get()
+ if got.Remote.Connections[0].Name != "srv" || got.Remote.PendingCookies[0].Site != "bilibili" {
+ t.Fatalf("committed Remote slices were aliased: %+v", got.Remote)
+ }
+
+ newerPath := filepath.Join(dir, "newer-settings.json")
+ if err := os.WriteFile(newerPath, []byte(`{"version":5}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, _, err := Open(newerPath, filepath.Join(dir, "cache")); err == nil {
+ t.Fatal("Open(version=5) succeeded, want NewerDataError")
+ }
+}
diff --git a/internal/shell/crashlog.go b/internal/shell/crashlog.go
index 51e6193..e395c35 100644
--- a/internal/shell/crashlog.go
+++ b/internal/shell/crashlog.go
@@ -1,6 +1,7 @@
package shell
import (
+ "fmt"
"os"
"path/filepath"
"runtime/debug"
@@ -16,8 +17,7 @@ const (
)
// setupCrashOutput makes the Go runtime write the traceback of a fatal crash
-// to /crash.log (2026-11-15 log review: three restarts on 11-14 left
-// nothing in trace.log). A non-empty crash.log left by the previous run is
+// to /crash.log. A non-empty crash.log left by the previous run is
// kept as crash-