Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat(media): 支持 STRM 按需播放与统一视频预览设置

longmeidao7887699b3ee4
diff --git a/README.md b/README.md
index e5612e0e9..5c9e0f5e9 100644
--- a/README.md
+++ b/README.md
@@ -31,7 +31,7 @@ https://github.com/user-attachments/assets/a5610874-e611-41bb-be22-7d99f0d64b62
- **整理过的片子直接用**:扫描时读取片子旁边已有的 NFO 和海报,不用重新刮削。
- **不动你的文件**:扫描只读,文件留在原处;改名、移动由你手动发起,先看预览,做完可以撤回。
-- **网盘和本地一起看**:115、PikPak 用 CloudDrive2 挂载成本地磁盘后,和硬盘里的片子进同一个馆藏。
+- **网盘和本地一起看**:115、PikPak、光鸭、OneDrive 用 CloudDrive2 或其他工具挂载成本地磁盘后,和硬盘里的片子进同一个馆藏;其他网盘可选「其他已挂载网盘」登记路径。
- **挂载状态**:定期检查媒体目录;读取失败会复查,确认后在托盘和作品页说明来源及原因。扫描跳过 NAS 回收站与系统目录。
- **播放墙挑片**:拖动全屏封面墙浏览,点开作品就在墙内播放;同一番号的版本和分卷可以直接切换。
- **跨站关注与追新作**:把同一创作者在多个站点的更新汇到一起;按女优名订阅新作,尚未入库也能追。
@@ -81,7 +81,9 @@ https://github.com/user-attachments/assets/a5610874-e611-41bb-be22-7d99f0d64b62
- **西方图片来源**:出演者与网黄博主可选 Babepedia 主图库人像;Tushy 等 Vixen 网络作品以出演者和发行日匹配官方封面,卡片、详情和头像框选共用原图,无法唯一匹配时留待核验。
- **女优页**:别名、生日身材、社媒和 JavDB、MISSAV 链接汇在一页,下面是她在你馆藏里的全部作品和照片;换头像时图库人像、作品封面、本机图片和图片地址都能先框一块,也能整张使用。
- **补资料**:按番号从片商官网、DMM、JavBus、JavDB 等站点补标题、女优和厂牌;封面优先选择尺寸更大的官方原图,JavDB 图片只用于核验。只填空着的资料,不覆盖你改过的。
-- **补全预览**:影片缺图时,列表和详情提供「补全资料与预览」按钮,自动补封面并为本机影片生成抽帧预览。下拉可选「只生成本地预览」或「只采集在线资料」;全库处理在数据管理的「扫描与采集」。
+- **同步媒体库**:数据管理的「同步媒体库」扫描文件、探测媒体信息并补全资料与图片;列表和详情可同步指定影片。下拉菜单可单独扫描文件、同步已入库影片、生成视频预览或补全资料。重复同步按缺项与来源缓存补全。
+- **视频预览**:设置中的「生成视频预览」控制九宫格与时间轴抽帧;关闭后仍保留普通媒体按来源规则执行的时长、分辨率探测。时间轴默认关闭,可选择每 10 秒或 30 秒一张;重新开启总开关后需自行选择时间轴间隔。
+- **STRM 与原盘**:支持单个 HTTP(S) 地址的 `.strm` 文件,扫描时登记指针,播放时才读取目标;可沿用本地 NFO 与海报。STRM 和 ISO 跳过后台探测与抽帧,ISO 在外部播放器中打开。
- **播放**:在浏览器里直接播放,记下看到哪;可以点喜欢、打分、稍后看、加进播放列表,也能「记一次高潮」。馆藏和关注详情的「接着看」可横向浏览推荐内容,点卡片直接切换。
- **播放墙**:右上角常驻入口打开独立的全屏封面墙,拖动上下左右浏览有封面的作品,探索时自动接续未展示作品,图片可切换为缩略图。点击作品原位展开并高亮,其余磁贴变暗,同块磁贴同步让位;可在墙内播放、切换分卷与版本或打开共用详情,收起时可继续在小窗播放。封面按磁贴比例选择全封或正封,跟随人脸取景;播放时背景模糊、标题移到上方。继承馆藏搜索、筛选及资料页作品范围,顶部提示可清除作品筛选并继续浏览当前 JAV 与来源范围。左上角返回键旁可换一批,等待时墙面变灰、变糊,右下角可搜索和调整图片与缩放。
- **追新作**:在女优页打开订阅,或在关注管理里按名字订阅,馆藏中尚未收录的女优也可订阅。Peach 会定期检查新作;新作卡显示人物头像,点击卡片打开站内作品详情,查看资料、预览图、评论和资源;点击已建档人物的头像可进入资料页。创作者可跨 FANBOX、Patreon、Kemono 等站点关注,不同站点的同一作品合成一张卡。
@@ -154,7 +156,7 @@ Linux 无桌面镜像与 CloudDrive2 分别部署,媒体目录与运行数据
- `<片名>-poster.jpg` 这样的海报。
- 已有的标题、女优、厂牌和海报会直接显示。
- **支持哪些网盘?**
- - 支持通过 CloudDrive2 挂载的 115 和 PikPak。
+ - 支持已挂载的 115、PikPak、光鸭、OneDrive;其他网盘用「其他已挂载网盘」登记。新增来源按只读方式管理;每个挂载目录可开启「代理流量保护」,不提供原生账号登录或上传。
- CloudDrive2 也可运行在群晖等 NAS 上。Windows 先把共享目录映射为盘符,再在 Peach 中选择对应文件夹;这种方式无需在 Windows 安装 CloudDrive2 或 WinFsp。
- 看片时 Peach 只把它当普通文件夹读,不保存网盘账号。
- 用云下载时,CloudDrive2 的 API 令牌和 PikPak 的登录令牌存在这台电脑的凭据文件里。
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index 46c681d2d..3badc2242 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -72,6 +72,8 @@
## 参考产品证据登记
+- STRM 与挂载来源(2026-10-17):[固定源码、差异与验收](reference-snapshots/strm-source-evidence.md)。
+
- 目录树与面包屑:2026-10-17 取得 BoardUI registry 源码,版本、SHA-256 与适配见 [BoardUI 适配](BOARD_UI.md#目录浏览)。保留首页结构,目录用途由用户确认。官方实时示例未取得。
- Open Claude UI:[设计准则](DESIGN_GUIDELINES.md)与[取舍证据](reference-snapshots/open-claude-ui.md)。
diff --git a/docs/PRODUCT_BACKLOG.md b/docs/PRODUCT_BACKLOG.md
index a5c139729..e76c35aea 100644
--- a/docs/PRODUCT_BACKLOG.md
+++ b/docs/PRODUCT_BACKLOG.md
@@ -2,8 +2,13 @@
最后核验:2026-10-07。这里只记还没做完的需求和待执行的操作;做完就删,历史去 Git 查。运行数字以 `peach-data/state/job-status.md` 的自动区块为准。
+当前开发与版本范围见 [Peach 开发进度](https://github.com/orgs/peach-mitao/projects/6);本文件保留资料复核、运维等待条件与长期待办。
+
## 待复核的元数据
+- #61 的 OneDrive、光鸭与通用挂载来源待真实账号验收;#62 的真实 STRM 上游兼容性待补,合成 HTTP Range 与 HLS 回归在隔离环境验证。
+- [#63 Emby/Jellyfin 兼容](https://github.com/peach-mitao/peach/issues/63)待明确目标客户端、认证、媒体库查询、播放与进度接口范围。
+
- amane 0.21.0 桥升级待在独立工作树验证 MGStage 数字前缀搜索、站点字段与失败契约;Peach 独立 DMM 链路的目录与 CID 规则另测,采用范围见 [上游复核](reference-snapshots/upstream-review.md)。
- JAV 发现的历史目录候选、年代与时长偏好、质量参考、近期偏好衰减及可撤回的负向探索反馈待取得并验证,范围与有界采集方案见 [JAV 发现](JAV_DISCOVERY.md)。
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 9c78f403b..74bcc3794 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -1,5 +1,11 @@
# 复用清单
+## STRM 与挂载来源
+
+STRM 采用文本指针、播放时解析的通用行为,参考 SmartStrm 文档、OpenList 的 `drivers/strm` 与 Jellyfin 的 STRM 探测入口;固定 revision、许可证与实际读取位置见 [取证记录](reference-snapshots/strm-source-evidence.md)。SmartStrm 核心闭源,源码未取得。Peach 独立实现受限 HTTP(S) 指针,复用 HTTPX、现有 Range 传输、`m3u8` 解析与播放器计划;无新增运行依赖,也不复制上游应用代码。
+
+光鸭、OneDrive 与其他网盘复用声明挂载根、路径翻译、扫描和只读保护;网盘登录与平台 API 由 CloudDrive2 或 OpenList 等挂载工具提供。挂载目录可单独设置代理流量保护,成本投影与批处理使用同一规则。STRM、ISO 跳过后台媒体读取,普通媒体保留按来源策略执行的探测;九宫格和时间轴共用本机视频预览开关。
+
Actions 工作流静态检查复用 actionlint 1.7.12(MIT,`rhysd/actionlint:1.7.12` 官方 Docker 镜像),由本地 Docker action 使用,独立 Docker 目录纳入 Dependabot 与接管入口。GitHub Actions 生态不更新 `docker://` 镜像引用。Windows 官方二进制按发布校验和完成本地 POC;CI 在 Linux 容器检查语法、表达式、任务依赖与脚本。Python 与浏览器回归继续使用现有统一入口及 Playwright;六片浏览器权重来自 [已通过的 CI](https://github.com/peach-mitao/peach/actions/runs/38981261189) 的 69 份 TAP,记录在 `scripts/ci-browser-timings.json`,没有新增应用运行依赖。
目录浏览的 `media_folders` 复用 `PureWindowsPath`、媒体库声明根和账本路径,不访问媒体挂载。`folder_rules` 复用 profile 偏好、规范实体、字段归属、身份断言、逐件归属否定和扫描登记入口;规则以 `user:directory-<目录标识>` 保存独立来源,预览摘要绑定资产版本与关系,撤回只处理本来源。已有明确归属保持独立。
diff --git a/docs/reference-snapshots/strm-source-evidence.md b/docs/reference-snapshots/strm-source-evidence.md
new file mode 100644
index 000000000..ff190ce57
--- /dev/null
+++ b/docs/reference-snapshots/strm-source-evidence.md
@@ -0,0 +1,37 @@
+# STRM 与挂载来源参考
+
+核对日期:2026-10-17。本文件是人工取证笔记,不登记为可由上游字节覆盖的 snapshot。
+源码链接固定 revision;产品文档仅作行为说明,没有逐字复制或引入运行依赖。
+
+## 实测证据
+
+| 来源 | 版本与实际读取位置 | 结论 |
+| --- | --- | --- |
+| [SmartStrm](https://github.com/Cp0204/SmartStrm/tree/01e9318d932187c65d485ecac5bcb46cbd2196bf) | `01e9318d932187c65d485ecac5bcb46cbd2196bf` 的仓库树、README、NOTICE;[FAQ](https://smartstrm.github.io/help/faq)、[代理说明](https://smartstrm.github.io/settings/proxy) | 核心闭源,实现源码未取得。文档说明稳定解析地址、OpenList 签名与播放时 302;不能据此声称复现其内部实现。 |
+| [OpenList](https://github.com/OpenListTeam/OpenList/tree/3b28270a4066ea52943a69ecddd850d83f7e8bdc) | `drivers/strm/driver.go`、`drivers/strm/util.go`;AGPL-3.0 | 列表生成指针和附属文件,播放按需解析目标。复用稳定指针与解析时机的语义,不复制驱动代码。 |
+| [Jellyfin](https://github.com/jellyfin/jellyfin/tree/dbb1f5dd5d0c73825a511a91aef051b254c637cb) | `MediaBrowser.Providers/MediaInfo/ProbeProvider.cs`、`Emby.Server.Implementations/Library/MediaSourceManager.cs`;GPL-2.0 | STRM 是文本入口,读取首个非空、非注释行;播放与媒体探测是独立阶段。Peach 主动拒绝多个目标,避免歧义。 |
+| [Kodi STRM 文档](https://kodi.wiki/view/Internet_video_and_audio_streams) | Internet video and audio streams | 文本 URL、NFO 与海报可分别存在,指针不等于媒体本身。 |
+| [CloudDrive2 支持列表](https://www.clouddrive2.com/en/features.html) | Storage supported today;光鸭支持的版本记录 `v1.0.11 / f58306f` | OneDrive 与光鸭可由外部工具挂载;光鸭版本记录注明只读。Peach 不引入网盘登录或上传 SDK。 |
+| [OpenList OneDrive](https://doc.oplist.org/guide/drivers/onedrive) | OneDrive 驱动说明;光鸭驱动参考 `v4.2.5 / cc87e88` | 平台登录、分享链接与目录访问交给驱动;Peach 使用已经挂载的文件系统路径。 |
+
+## Peach 的采用范围
+
+STRM 仅接受一个 HTTP(S) 地址,支持 UTF-8 BOM、空行和注释。扫描只登记本地指针,播放才发起上游请求;签名参数保留原始编码。HTTP Range 与 HLS 使用既有 HTTPX 传输、播放器计划和 HLS 解析库,浏览器只取得 Peach 的鉴权地址。映射有容量与有效期,不持久缓存正片。
+
+本地 OpenList、CloudDrive 地址可以作为指针初始来源;重定向和播放列表只能继续访问同一来源,或经公网 HTTPS 检查的目标。浏览器 Cookie 和共享 HTTP 客户端的认证信息不转发给上游。错误回执不包含签名地址。
+
+STRM 与 ISO 不参与后台探测、九宫格或时间轴抽帧。ISO 只登记与管理,并提供外部播放器入口;未声称浏览器支持 ISO、BDMV 导航或多片段原盘。
+
+「生成视频预览」控制九宫格与时间轴抽帧,保留普通媒体按来源策略执行的 ffprobe 探测。关闭后停止时间轴任务,重新开启总开关不自动开启时间轴采集。时间轴间隔仍由用户选择。
+
+挂载目录通过「代理流量保护」选择读取成本,文件写入能力独立判断。光鸭默认正常读取;OneDrive 与通用挂载入口默认保护,可按实际路径关闭。通用「其他已挂载网盘」只承诺文件系统读取,不承诺每家平台的原生 API、上传、分享或回收站功能。
+
+## 代理与成本证据
+
+[光鸭官网](https://www.guangyapan.com/)面向大陆提供第三方应用直连能力,支持默认正常读取的产品判断,真实账号下载路径未取得。[微软网络说明](https://learn.microsoft.com/en-us/microsoft-365/enterprise/microsoft-365-networking-china?view=o365-worldwide)区分国际租户跨境拥塞与世纪互联环境;[OpenList 驱动](https://doc.oplist.org/guide/drivers/onedrive)按账号类型选择应用端点,并提供独立的下载反代设置。登录可达不等于文件下载直连;不能仅凭网盘名称推断代理费用。
+
+本机匿名 HEAD 核验中,显式绕过客户端代理的光鸭官网返回 200,`login.live.com` 返回 404,`graph.microsoft.com` 返回 405,OneDrive 个人网页版连接超时。404、405 只证明公共端点可达,不代表认证或业务成功。FlowLens 快照未观测到这些短连接,不能用它证明系统隧道路径、零代理流量或全大陆可用性。无网盘登录、真实媒体读取或路由配置改动。
+
+## 验证边界
+
+自动回归使用临时账本、合成文件、本机 HTTP 服务与模拟上游,验证登记不预读、真实 Range 206、签名重定向、HLS 子资源鉴权及预览开关。真实 OneDrive、光鸭账号及挂载未取得;真实云端端到端兼容性未验证。SmartStrm 核心源码未取得。
diff --git a/frontend/e2e/design-controls.test.ts b/frontend/e2e/design-controls.test.ts
index 2b740a136..1b185f449 100644
--- a/frontend/e2e/design-controls.test.ts
+++ b/frontend/e2e/design-controls.test.ts
@@ -290,7 +290,7 @@ describe('设计决定:控件、状态与首页顶部', () => {
assert.equal(await fill(1),
await tokenColor(opened.page, '.peach-react', '--color-border-focus-ring'));
// 忙态不改 `disabled`:控件仍可聚焦,重复触发由页面自己挡。
- const scan = card.getByRole('button', { name: '扫描并补全资料', exact: true });
+ const scan = card.getByRole('button', { name: '同步媒体库', exact: true });
assert.equal(await scan.getAttribute('aria-busy'), 'true');
assert.equal(await scan.evaluate((element) => (element as HTMLButtonElement).disabled), false,
'用原生 disabled 挡的话按钮连焦点都拿不到');
diff --git a/frontend/e2e/design-manage.test.ts b/frontend/e2e/design-manage.test.ts
index c16a9ed9d..db67e1ef7 100644
--- a/frontend/e2e/design-manage.test.ts
+++ b/frontend/e2e/design-manage.test.ts
@@ -27,13 +27,13 @@ describe('设计决定:数据管理、索引页与资料页头', () => {
const expected = await disabledTokens(page);
const waiting = await waitingActionFaces(page, '[data-skeleton="cleanup"] [data-skeleton-action]');
assert.deepEqual(waiting.map((face) => face.name),
- ['扫描并补全资料', '更多扫描与采集方式', '开始修复', '预览', '检查死链', '检查文件']);
+ ['同步媒体库', '更多同步方式', '开始修复', '预览', '检查死链', '检查文件']);
for (const face of waiting) assertDisabledFace(face, expected);
const ring = await page.locator('[data-skeleton="cleanup"] [data-split-button]')
.evaluate((element) => getComputedStyle(element).boxShadow);
assert.ok(ring.includes(expected.ring), `骨架里的分体键外圈不是禁用那一档描边:${ring}`);
const sizes = await controlFaces(page, {
- 扫描并补全资料: '.cleanupscraping [data-split-button] > button:first-child',
+ 同步媒体库: '.cleanupscraping [data-split-button] > button:first-child',
更多方式: '.cleanupscraping [data-split-button] > button:last-child',
开始修复: '.cleanupmediarepair footer > button',
});
@@ -46,7 +46,7 @@ describe('设计决定:数据管理、索引页与资料页头', () => {
.waitFor({ timeout: 15_000 });
await settle(page);
const final = await controlFaces(page, {
- 扫描并补全资料: 'section[aria-label="扫描与采集"] [data-split-button] > button:first-child',
+ 同步媒体库: 'section[aria-label="扫描与采集"] [data-split-button] > button:first-child',
更多方式: 'section[aria-label="扫描与采集"] [data-split-button] > button:last-child',
开始修复: 'section[aria-label="媒体修复"] footer > button',
});
diff --git a/frontend/e2e/library-completion.test.ts b/frontend/e2e/library-completion.test.ts
index 67f5db941..61d859325 100644
--- a/frontend/e2e/library-completion.test.ts
+++ b/frontend/e2e/library-completion.test.ts
@@ -61,18 +61,18 @@ describe('缺预览时的统一补全入口', () => {
const text = await prompt.locator('p').boundingBox();
assert.ok(text && text.width >= viewport.width - 80, '手机提示正文应独占一行宽度');
}
- const more = prompt.getByRole('button', { name: '更多资料与预览补全方式' });
+ const more = prompt.getByRole('button', { name: '更多同步方式' });
await more.focus();
await page.keyboard.press('Enter');
- const menu = page.getByRole('dialog', { name: '资料与预览补全方式' });
+ const menu = page.getByRole('dialog', { name: '同步方式' });
await menu.waitFor();
- assert.deepEqual(await menu.getByRole('button').allTextContents(), ['补全资料与预览', '只生成本地预览', '只采集在线资料']);
+ assert.deepEqual(await menu.getByRole('button').allTextContents(), ['同步这些影片', '仅生成视频预览', '仅补全资料']);
const box = await menu.boundingBox();
assert.ok(box && box.x >= 0 && box.x + box.width <= viewport.width);
await page.keyboard.press('Escape');
await menu.waitFor({ state: 'hidden' });
await page.waitForFunction(() => document.activeElement?.getAttribute('aria-label')
- === '更多资料与预览补全方式', null, { timeout: 5_000 });
+ === '更多同步方式', null, { timeout: 5_000 });
for (const dark of [false, true]) {
await page.evaluate(value => {
document.documentElement.dataset.theme = value ? 'dark' : 'light';
@@ -90,7 +90,7 @@ describe('缺预览时的统一补全入口', () => {
await menu.waitFor({ state: 'hidden' });
}
await more.click();
- await menu.getByRole('button', { name: '只生成本地预览' }).click();
+ await menu.getByRole('button', { name: '仅生成视频预览' }).click();
await prompt.waitFor({ state: 'hidden' });
await page.locator('[data-media-card] img.poster').waitFor();
assert.deepEqual(posts, [{ stage: 'previews', asset_ids: [11] }]);
diff --git a/frontend/e2e/media-processing-settings.test.ts b/frontend/e2e/media-processing-settings.test.ts
new file mode 100644
index 000000000..4f40119b3
--- /dev/null
+++ b/frontend/e2e/media-processing-settings.test.ts
@@ -0,0 +1,63 @@
+import assert from 'node:assert/strict';
+import { mkdir } from 'node:fs/promises';
+import path from 'node:path';
+import { after, before, describe, it } from 'node:test';
+import type { Browser } from 'playwright-core';
+import { launch, layout, settle, visit, VIEWPORTS } from './harness.ts';
+
+describe('视频预览设置', () => {
+ let browser: Browser;
+ before(async () => { browser = await launch() });
+ after(async () => { await browser?.close() });
+ for (const viewport of VIEWPORTS) {
+ it(`${viewport.name}:总开关持久化并控制时间轴设置,重新开启后时间轴由用户选择`, async () => {
+ let disabled = false;
+ let timeline = 'coarse';
+ const writes: unknown[] = [];
+ const opened = await visit(browser, '/settings/library', viewport, async page => {
+ await page.route('**/api/media-processing', async route => {
+ if (route.request().method() === 'POST') {
+ const body = route.request().postDataJSON();
+ writes.push(body);
+ disabled = body.metadata_only;
+ if (disabled) timeline = 'off';
+ }
+ await route.fulfill({ json: { metadata_only: disabled } });
+ });
+ await page.route('**/api/thumbnail-jobs', route => route.fulfill({ json: { mode: timeline, status: 'idle' } }));
+ });
+ const { page } = opened;
+ try {
+ const toggle = page.getByRole('switch', { name: '生成视频预览', exact: true });
+ const interval = page.locator('#videoThumbnailSetting button');
+ await toggle.waitFor();
+ await settle(page);
+ assert.equal(await toggle.isChecked(), true);
+ assert.equal(await interval.isDisabled(), false);
+ await page.locator('label').filter({ has: toggle }).click();
+ await page.getByText('已关闭视频预览生成', { exact: true }).waitFor();
+ assert.equal(await toggle.isChecked(), false);
+ assert.equal(await interval.isDisabled(), true);
+ await page.reload();
+ await toggle.waitFor();
+ await settle(page);
+ assert.equal(await toggle.isChecked(), false);
+ assert.equal(await interval.isDisabled(), true);
+ assert.match(await interval.innerText(), /关闭/);
+ await toggle.focus();
+ await page.keyboard.press('Space');
+ await page.getByText('已开启视频预览生成', { exact: true }).waitFor();
+ assert.equal(await interval.isDisabled(), false);
+ assert.match(await interval.innerText(), /关闭/);
+ assert.deepEqual(writes, [{ metadata_only: true }, { metadata_only: false }]);
+ const measured = await layout(page);
+ assert.ok(measured.scrollWidth <= measured.viewportWidth, JSON.stringify(measured));
+ assert.deepEqual(measured.offenders, []);
+ const artifacts = path.resolve('..', 'build', 'agent-verification', 'media-processing');
+ await mkdir(artifacts, { recursive: true });
+ await page.screenshot({ path: path.join(artifacts, `${viewport.name}.png`), fullPage: true });
+ assert.deepEqual(opened.problems, []);
+ } finally { await opened.close() }
+ });
+ }
+});
diff --git a/frontend/src/management.ts b/frontend/src/management.ts
index a5977680d..4fa9d5f40 100644
--- a/frontend/src/management.ts
+++ b/frontend/src/management.ts
@@ -4,7 +4,7 @@ import { islandButton, islandGlyph, islandSelect } from './island-skeleton';
/* 「扫描与采集」「媒体修复」两张卡的正文。卡片本体由 React 画,骨架与遗留层的取数占位
画的是同一段话:写两份的话,骨架上的那句会比真卡短一截,接管时整张卡跳一次。 */
-export const SCAN_CARD_TEXT = '扫描媒体文件夹,补全资料、封面与视频预览。下拉菜单可选择只扫描、只生成本地预览或只采集在线资料。';
+export const SCAN_CARD_TEXT = '同步文件与影片资料,按设置生成本地视频预览。下拉菜单可选择只扫描文件、同步已入库影片、生成预览或补全资料。';
export const REPAIR_CARD_TEXT = '修缺时间戳表(播放卡顿)和缺索引(打不开)的 MP4。常看的片子先修。';
const bar = '<span class="skeleton skeleton-text" aria-hidden="true"></span>';
@@ -27,7 +27,7 @@ const cardText = (title: string, text: string) => `<div data-geist-fieldset-cont
export function scanCardSkeletonHtml(): string {
return island(`<section aria-label="扫描与采集" data-geist-fieldset data-cleanup-task data-cleanup-processing data-fieldset-stack>
${cardText('扫描与采集', SCAN_CARD_TEXT)}
- <footer data-geist-fieldset-footer><a href="/sources" class="inline-flex items-center justify-center gap-1 whitespace-nowrap font-sans rounded-sm text-body-medium text-accent-600"><span>来源和凭证</span>${islandGlyph('arrow-up', 'size-[18px] shrink-0 rotate-90')}</a><span data-button-group data-split-button data-variant="primary">${islandButton({ glyph: 'database', label: '扫描并补全资料', attrs: waitingAction })}${islandButton({ glyph: 'chevron-down', attrs: `${waitingAction} aria-label="更多扫描与采集方式"` })}</span></footer>
+ <footer data-geist-fieldset-footer><a href="/sources" class="inline-flex items-center justify-center gap-1 whitespace-nowrap font-sans rounded-sm text-body-medium text-accent-600"><span>来源和凭证</span>${islandGlyph('arrow-up', 'size-[18px] shrink-0 rotate-90')}</a><span data-button-group data-split-button data-variant="primary">${islandButton({ glyph: 'database', label: '同步媒体库', attrs: waitingAction })}${islandButton({ glyph: 'chevron-down', attrs: `${waitingAction} aria-label="更多同步方式"` })}</span></footer>
</section>`);
}
diff --git a/frontend/src/player/stream.ts b/frontend/src/player/stream.ts
index f785c421a..eff8221ab 100644
--- a/frontend/src/player/stream.ts
+++ b/frontend/src/player/stream.ts
@@ -32,7 +32,7 @@ export async function playableStreamSource(item: PlayerItem, session: string): P
try {
const plan = await api(`/api/stream-plan?id=${item.id}&session=${encodeURIComponent(session)}`) as
{ protocol?: string; src?: string; mime_type?: string } | null;
- if (plan?.protocol === 'hls' && plan.src) return { src: plan.src, type: plan.mime_type || 'application/vnd.apple.mpegurl' };
+ if (plan?.src) return { src: plan.src, type: plan.mime_type || (plan.protocol === 'hls' ? 'application/vnd.apple.mpegurl' : 'video/mp4') };
} catch { /* 取不到计划就直读 */ }
return directStreamSource(item, session);
}
diff --git a/frontend/src/react/item-detail/item-detail-page.tsx b/frontend/src/react/item-detail/item-detail-page.tsx
index f8a394ead..f4ac78446 100644
--- a/frontend/src/react/item-detail/item-detail-page.tsx
+++ b/frontend/src/react/item-detail/item-detail-page.tsx
@@ -185,7 +185,13 @@ function MediaFrame({ item, gate, helpers, actions, autoplay, onEnded }: {
: <Button variant="secondary" {...busyProps(source.isFetching)} title={source.data?.message || requestErrorMessage(source.error)}
onClick={() => { refreshSamples.current = true; void source.refetch() }}>重试样图</Button>}</div> : null}
{gate === 'offline' ? <OfflineGate item={item} badge={badge} helpers={helpers} actions={actions} />
- : gate === 'online' ? (
+ : gate === 'disc' ? (
+ <div role="status" data-item-gate="disc">
+ <b>ISO 原盘</b>
+ <span>请使用支持原盘的外部播放器打开。</span>
+ <ExternalPlayback id={item.id} />
+ </div>
+ ) : gate === 'online' ? (
<div id="onlineGate" role="status" data-item-gate="online">
<Html html={badge} />
<b>在线资产</b>
diff --git a/frontend/src/react/item-detail/item-detail.ts b/frontend/src/react/item-detail/item-detail.ts
index fb5d94e19..349719bd2 100644
--- a/frontend/src/react/item-detail/item-detail.ts
+++ b/frontend/src/react/item-detail/item-detail.ts
@@ -470,12 +470,13 @@ export const sameOrder = (a: readonly number[], b: readonly number[]) =>
/* ── 播放区 ── */
-export type MediaGate = 'offline' | 'online' | 'metered' | '';
+export type MediaGate = 'offline' | 'online' | 'metered' | 'disc' | '';
/** 播放区此刻挡在视频前面的是哪一种说明:来源没挂载、在线资产反查不到关注条目、计费来源要
* 点一下才拉流。保存过的在线资产照常播(壳在取数时已经把它转去关注详情)。 */
export function mediaGate(item: DetailItem, offline: boolean): MediaGate {
if (offline) return 'offline';
+ if (String(item.name || '').toLowerCase().endsWith('.iso')) return 'disc';
if (item.location === 'online' && !item.follow_item_id) return 'online';
if (item.cost === 'metered' && item.location !== 'online') return 'metered';
return '';
diff --git a/frontend/src/react/library-processing/library-completion.tsx b/frontend/src/react/library-processing/library-completion.tsx
index 1f8218e6c..fa04ba67f 100644
--- a/frontend/src/react/library-processing/library-completion.tsx
+++ b/frontend/src/react/library-processing/library-completion.tsx
@@ -16,11 +16,12 @@ import {
import { ProcessingActions } from './processing-actions';
/** 缺图判据与卡面一致;本机影片可抽帧,有番号的挂载影片可补发行封面。 */
-type PreviewItem = Pick<MediaItem, 'id' | 'medium' | 'disposal' | 'location' | 'code' | 'is_jav'
+type PreviewItem = Pick<MediaItem, 'id' | 'name' | 'medium' | 'disposal' | 'location' | 'code' | 'is_jav'
| 'has_cover' | 'cover_key' | 'has_thumb' | 'has_local_poster' | 'follow_thumb_url'>;
export function missingPreviewIds(items: PreviewItem[], javImage: string): number[] {
return [...new Set(items.filter(item => (!item.medium || item.medium === 'video')
+ && (!/\.(strm|iso)$/i.test(item.name || '') || !!item.code)
&& !item.disposal && item.location !== 'online' && (item.location === 'local' || !!item.code)
&& !cardArtwork(item, 'small', false, javImage).html).map(item => item.id))];
}
@@ -60,9 +61,9 @@ function Completion({ assetIds, onComplete }: { assetIds: number[]; onComplete?(
const problem = start.error ? errorMessage(start.error) : job.error ? DISCONNECTED_TEXT
: started && state?.job_id === started && state.status === 'failed' ? state.error || '补全未完成' : '';
const message = problem || (busy ? start.isPending ? '正在启动补全…' : currentLine(state!)
- : outcome || `这批影片中有 ${assetIds.length.toLocaleString()} 部暂无预览,可补全封面与视频画面。`);
+ : outcome || `这批影片中有 ${assetIds.length.toLocaleString()} 部暂无预览,可补全资料与图片。`);
return <section aria-label="补全预览" aria-live="polite" data-library-completion="" className="@container mb-4">
- <Note tone={problem ? 'warning' : 'neutral'} actionLayout="below" action={<ProcessingActions busy={busy} onRun={command => {
+ <Note tone={problem ? 'warning' : 'neutral'} actionLayout="below" action={<ProcessingActions busy={busy} metadataOnly={state?.metadata_only} onRun={command => {
if (busy) return;
setOutcome('');
start.mutate(command);
diff --git a/frontend/src/react/library-processing/library-processing-card.tsx b/frontend/src/react/library-processing/library-processing-card.tsx
index dccac69b4..8431be9c3 100644
--- a/frontend/src/react/library-processing/library-processing-card.tsx
+++ b/frontend/src/react/library-processing/library-processing-card.tsx
@@ -180,7 +180,7 @@ export function LibraryProcessingCard(props: LibraryProcessingProps) {
{/* 两个入口并存,各自答的不是一个问题:这里是「重新跑一整批」,下面那条错误提示里
的「重试未完成项」只补上一趟没做完的那些。采集里网络超时几乎每趟都留下几项可
重试的,页脚要是让位给重试键,新入库的片子就再也没有入口被扫到。 */}
- <ProcessingActions scan busy={busy} onRun={run} />
+ <ProcessingActions scan busy={busy} metadataOnly={state?.metadata_only} onRun={run} />
</>
}>
<div className="flex flex-col gap-2">
diff --git a/frontend/src/react/library-processing/library-processing.ts b/frontend/src/react/library-processing/library-processing.ts
index 9ae8a5273..907e285c0 100644
--- a/frontend/src/react/library-processing/library-processing.ts
+++ b/frontend/src/react/library-processing/library-processing.ts
@@ -24,6 +24,7 @@ export interface LibraryProcessingIssue {
/** 一趟扫描与采集的快照。字段以 `q_library_processing`(`src/peach/web_library_processing.py`)为准。 */
export interface LibraryProcessingData {
+ metadata_only?: boolean;
/** `idle` | `running` | `complete` | `failed`。 */
status: string;
job_id?: string;
diff --git a/frontend/src/react/library-processing/processing-actions.tsx b/frontend/src/react/library-processing/processing-actions.tsx
index 5513b0382..2bce6b9d0 100644
--- a/frontend/src/react/library-processing/processing-actions.tsx
+++ b/frontend/src/react/library-processing/processing-actions.tsx
@@ -1,32 +1,27 @@
import { useRef, useState } from 'react';
import { RiArrowDownSLine, RiDatabase2Line, RiGlobalLine, RiHardDrive2Line } from '@remixicon/react';
import { Popover } from 'react-aria-components';
-
import { Button } from '@/components/base/buttons/button';
import { MENU_ITEM, MENU_ITEM_INTERACTIVE, MENU_POPOVER_SURFACE } from '@/components/base/dropdown/menu-styles';
import { cx } from '@/utils/cx';
-
import { MenuDialog } from '../components/menu-dialog';
import { busyProps } from '../settings/use-action';
import type { LibraryProcessingCommand } from './library-processing';
-const COMPLETE = { label: '补全资料与预览', icon: RiDatabase2Line, command: { stage: 'collect' } } as const;
-const PREVIEWS = { label: '只生成本地预览', icon: RiHardDrive2Line, command: { stage: 'previews' } } as const;
-const METADATA = { label: '只采集在线资料', icon: RiGlobalLine, command: { stage: 'metadata' } } as const;
-const SCAN_OPTIONS = [
- { label: '扫描并补全资料', icon: RiDatabase2Line, command: {} }, COMPLETE,
- { label: '只扫描', icon: RiHardDrive2Line, command: { stage: 'scan' } }, PREVIEWS, METADATA,
-] as const;
-const COMPLETE_OPTIONS = [COMPLETE, PREVIEWS, METADATA] as const;
-
-/** 馆藏补全与扫描共用同一组操作,菜单第一项始终是主动作。 */
-export function ProcessingActions({ busy, scan = false, onRun }: {
- busy: boolean; scan?: boolean; onRun(command: LibraryProcessingCommand): void;
+/** 扫描和已有作品补全共用资料流水线,视频预览由媒体库设置决定。 */
+export function ProcessingActions({ busy, scan = false, metadataOnly = false, onRun }: {
+ busy: boolean; scan?: boolean; metadataOnly?: boolean; onRun(command: LibraryProcessingCommand): void;
}) {
const trigger = useRef<HTMLButtonElement>(null);
const [open, setOpen] = useState(false);
- const options = scan ? SCAN_OPTIONS : COMPLETE_OPTIONS;
- const primary = options[0];
+ const primary: { label: string; icon: typeof RiDatabase2Line; command: LibraryProcessingCommand } = { label: scan ? '同步媒体库' : '同步这些影片', icon: RiDatabase2Line,
+ command: scan ? {} : { stage: 'collect' as const } };
+ const options: typeof primary[] = [primary,
+ ...(scan ? [{ label: '仅扫描文件', icon: RiHardDrive2Line, command: { stage: 'scan' as const } }] : []),
+ ...(scan ? [{ label: '仅同步已入库影片', icon: RiDatabase2Line, command: { stage: 'collect' as const } }] : []),
+ { label: '仅生成视频预览', icon: RiHardDrive2Line, command: { stage: 'previews' as const } },
+ { label: '仅补全资料', icon: RiGlobalLine, command: { stage: 'metadata' as const } },
+ ];
const run = (command: LibraryProcessingCommand) => {
if (busy) return;
setOpen(false);
@@ -34,21 +29,20 @@ export function ProcessingActions({ busy, scan = false, onRun }: {
};
return <>
<span data-button-group data-split-button data-variant="primary">
- <Button leadingIcon={primary.icon} onClick={() => run(primary.command)} {...busyProps(busy)}>
- {primary.label}
- </Button>
- <Button ref={trigger} iconOnly leadingIcon={RiArrowDownSLine}
- aria-label={scan ? '更多扫描与采集方式' : '更多资料与预览补全方式'}
+ <Button leadingIcon={primary.icon} {...busyProps(busy)} onClick={() => run(primary.command)}>{primary.label}</Button>
+ <Button ref={trigger} iconOnly leadingIcon={RiArrowDownSLine} aria-label="更多同步方式"
aria-haspopup="dialog" aria-expanded={open} {...busyProps(busy)} onClick={() => { if (!busy) setOpen(!open) }} />
</span>
<Popover triggerRef={trigger} isOpen={open} onOpenChange={setOpen} placement="bottom end" offset={4}
className={MENU_POPOVER_SURFACE}>
- <MenuDialog aria-label={scan ? '扫描与采集方式' : '资料与预览补全方式'}
- className="flex w-56 flex-col gap-1 outline-none">
- {options.map(({ label, icon: Icon, command }) => <button key={label} type="button"
- className={cx(MENU_ITEM, MENU_ITEM_INTERACTIVE, 'text-body-2-medium')} onClick={() => run(command)}>
- <Icon aria-hidden className="size-4 shrink-0" />{label}
- </button>)}
+ <MenuDialog aria-label="同步方式" className="flex w-56 flex-col gap-1 outline-none">
+ {options.map(({ label, icon: Icon, command }) => {
+ const blocked = metadataOnly && 'stage' in command && command.stage === 'previews';
+ return <button key={label} type="button" disabled={blocked}
+ title={blocked ? '请先在媒体库设置中开启视频预览生成' : undefined}
+ className={cx(MENU_ITEM, MENU_ITEM_INTERACTIVE, 'text-body-2-medium')}
+ onClick={() => run(command)}><Icon aria-hidden className="size-4 shrink-0" />{label}</button>;
+ })}
</MenuDialog>
</Popover>
</>;
diff --git a/frontend/src/react/settings/configuration-page.tsx b/frontend/src/react/settings/configuration-page.tsx
index 4e7c7b963..92f815a00 100644
--- a/frontend/src/react/settings/configuration-page.tsx
+++ b/frontend/src/react/settings/configuration-page.tsx
@@ -17,6 +17,7 @@ import { DownloadGroup } from './download-settings';
import { GeneralSettings } from './general-settings';
import { MaintenanceSettings } from './maintenance-settings';
import { MediaSettings } from './media-settings';
+import { MediaProcessingSettings } from './media-processing-settings';
import { NetworkSettings } from './network-settings';
import { SourceSettings } from './source-settings';
import { groupRoot } from './configuration-panel';
@@ -67,7 +68,9 @@ function ConfigurationGroups(
const network = Boolean(data.peach_proxy || data.access || data.tunnel || (data.editable && data.port_editable !== false));
const downloads = data.downloads;
const groups: Group[] = [
- { title: '媒体库与入库', body: (panel) => <MediaSettings {...group} panel={panel} /> },
+ { title: '媒体库与入库', body: (panel) => <div {...groupRoot(panel)}>
+ <MediaSettings {...group} /><MediaProcessingSettings receipt={receipt} />
+ </div> },
{ title: '来源与订阅', body: (panel) => <SourceSettings {...group} panel={panel} /> },
...(downloads ? [{
title: '下载渠道',
diff --git a/frontend/src/react/settings/media-processing-settings.tsx b/frontend/src/react/settings/media-processing-settings.tsx
new file mode 100644
index 000000000..336de428c
--- /dev/null
+++ b/frontend/src/react/settings/media-processing-settings.tsx
@@ -0,0 +1,38 @@
+import { useQuery } from '@tanstack/react-query';
+import { SettingsRow } from '@/components/application/settings/settings-rows';
+import { Switch } from '@/components/base/switch/switch';
+
+import { apiGet, apiSend, errorMessage } from '../../api';
+import { queryClient } from '../query';
+import { THUMBNAIL_JOBS_KEY } from '../settings-panel/settings-data';
+import { LIBRARY_PROCESSING_KEY } from '../library-processing/library-processing';
+import { ErrorText, Help, Rows, Section, Stack } from './section';
+import { useAction } from './use-action';
+import { VideoThumbnailControls } from './service-preferences';
+
+const KEY = ['media-processing'] as const;
+interface Policy { metadata_only: boolean }
+
+export function MediaProcessingSettings({ receipt }: { receipt(message: string): void }) {
+ const policy = useQuery({ queryKey: KEY, queryFn: ({ signal }) => apiGet<Policy>('/api/media-processing', signal) });
+ const action = useAction();
+ const error = action.error || (policy.error ? errorMessage(policy.error) : '');
+ return <Section title="视频预览">
+ <Rows>
+ <SettingsRow label="生成视频预览" description="为本地视频生成九宫格与时间轴预览;关闭后仍按入库规则探测时长与分辨率。">
+ <Switch aria-label="生成视频预览" isSelected={!!policy.data && !policy.data.metadata_only}
+ isDisabled={!policy.data || policy.isFetching || !!action.busy}
+ onChange={(value) => void action.run('save', (signal) =>
+ apiSend<Policy>('/api/media-processing', { metadata_only: !value }, 'POST', signal), (saved) => {
+ queryClient.setQueryData(KEY, saved);
+ void queryClient.invalidateQueries({ queryKey: THUMBNAIL_JOBS_KEY });
+ void queryClient.invalidateQueries({ queryKey: LIBRARY_PROCESSING_KEY });
+ receipt(saved.metadata_only ? '已关闭视频预览生成' : '已开启视频预览生成');
+ })} />
+ </SettingsRow>
+ </Rows>
+ <VideoThumbnailControls disabled={!policy.data || policy.data.metadata_only || !!action.busy} />
+ {action.busy ? <Stack divided><Help role="status">正在保存…</Help></Stack> : null}
+ {error ? <Stack divided><ErrorText>{error}</ErrorText></Stack> : null}
+ </Section>;
+}
diff --git a/frontend/src/react/settings/media-settings.tsx b/frontend/src/react/settings/media-settings.tsx
index 97be65412..b7634d8b0 100644
--- a/frontend/src/react/settings/media-settings.tsx
+++ b/frontend/src/react/settings/media-settings.tsx
@@ -25,7 +25,6 @@ import { groupRoot } from './configuration-panel';
import { FolderRow, isCloudSource, MEDIA_SOURCES, SourceSelect, sourceMark, useFolderRows, WindowsRootInput } from './folder-rows';
import { LibraryIconPicker } from './library-icon-picker';
import { PushDiscoveryForm } from './push-discovery-settings';
-import { VideoThumbnailRow } from './service-preferences';
import {
ErrorText, ExternalLink, Fact, FactList, FieldLabel, Footer, Help, Section, SourceMark, Stack,
} from './section';
@@ -65,7 +64,6 @@ export function MediaSettings({ data, receipt, panel }: ConfigurationGroupProps)
{data.push_discovery
? <PushDiscoveryForm initial={data.push_discovery} receipt={receipt} />
: null}
- <VideoThumbnailRow />
</div>
);
}
diff --git a/frontend/src/react/settings/service-preferences.tsx b/frontend/src/react/settings/service-preferences.tsx
index 508bfd538..84a88f0e8 100644
--- a/frontend/src/react/settings/service-preferences.tsx
+++ b/frontend/src/react/settings/service-preferences.tsx
@@ -20,6 +20,10 @@ import { ErrorText, Help, Rows, Section, Stack } from './section';
const THUMBNAIL_OPTIONS = [['off', '关闭'], ['precise', '每 10 秒一张'], ['coarse', '每 30 秒一张']] as const;
export function VideoThumbnailRow({ epoch = 0 }: { epoch?: number }) {
+ return <Section title="时间轴缩略图"><VideoThumbnailControls epoch={epoch} /></Section>;
+}
+
+export function VideoThumbnailControls({ epoch = 0, disabled = false }: { epoch?: number; disabled?: boolean }) {
const status = useQuery({ queryKey: THUMBNAIL_JOBS_KEY, queryFn: ({ signal }) => fetchThumbnailJobs(signal), refetchOnMount: 'always' });
const save = useSaveThumbnailMode();
const reset = save.reset;
@@ -27,12 +31,12 @@ export function VideoThumbnailRow({ epoch = 0 }: { epoch?: number }) {
const data = status.data;
const error = save.error || status.error;
return (
- <Section title="时间轴缩略图">
+ <>
<Rows>
- <SettingsRow label="采集间隔" description="仅采集本机磁盘上的视频。">
+ <SettingsRow label="时间轴预览" description="按所选间隔抽帧,仅处理本机磁盘上的视频。">
<div id="videoThumbnailSetting">
<Select aria-label="缩略图采集间隔" selectedKey={data?.mode || 'off'}
- isDisabled={!data || status.isFetching || save.isPending}
+ isDisabled={disabled || !data || status.isFetching || save.isPending}
onSelectionChange={(key) => { if (key !== null) save.mutate(String(key)) }}>
{THUMBNAIL_OPTIONS.map(([key, label]) => <SelectItem key={key} id={key}>{label}</SelectItem>)}
</Select>
@@ -43,7 +47,7 @@ export function VideoThumbnailRow({ epoch = 0 }: { epoch?: number }) {
? <Stack divided><Help role="status">{save.isPending ? '正在保存…' : '正在采集,进度在活动页查看。'}</Help></Stack>
: null}
{error ? <Stack divided><ErrorText>{errorMessage(error)}</ErrorText></Stack> : null}
- </Section>
+ </>
);
}
diff --git a/frontend/test/management.test.ts b/frontend/test/management.test.ts
index 12d434c75..2a9cdcbb2 100644
--- a/frontend/test/management.test.ts
+++ b/frontend/test/management.test.ts
@@ -47,7 +47,7 @@ describe('数据管理首屏', () => {
for (const button of legacy) expect(button.classList.contains('primary')).toBe(true);
const actions = root.querySelectorAll('button:not(.board-plain-stat, [aria-haspopup="listbox"])');
expect([...actions].map(button => button.textContent || button.getAttribute('aria-label')))
- .toEqual(['扫描并补全资料', '更多扫描与采集方式', '开始修复', '预览', '检查死链', '检查文件']);
+ .toEqual(['同步媒体库', '更多同步方式', '开始修复', '预览', '检查死链', '检查文件']);
for (const button of actions) {
expect(button.hasAttribute('disabled')).toBe(true);
expect(button.hasAttribute('data-skeleton-action')).toBe(true);
diff --git a/frontend/test/player.test.ts b/frontend/test/player.test.ts
index b8a197149..afcec4c94 100644
--- a/frontend/test/player.test.ts
+++ b/frontend/test/player.test.ts
@@ -68,6 +68,12 @@ describe('片源判据', () => {
await flush(); await flush();
expect(JSON.parse(document.documentElement.dataset.peachStreamCancel || 'null')).toEqual({ cancelled: 1 });
});
+
+ it('STRM 的文件类型使用服务端播放计划', async () => {
+ stubFetch(() => ({ protocol: 'range', src: '/stream?id=6', mime_type: 'video/webm' }));
+ expect(await playableStreamSource({ id: 6, name: 'ABC-123.strm' }, 'strm'))
+ .toEqual({ src: '/stream?id=6', type: 'video/webm' });
+ });
});
describe('观看上报', () => {
diff --git a/frontend/test/react/item-detail.test.tsx b/frontend/test/react/item-detail.test.tsx
index dc5436eb9..f63ed677d 100644
--- a/frontend/test/react/item-detail.test.tsx
+++ b/frontend/test/react/item-detail.test.tsx
@@ -249,6 +249,7 @@ describe('身份与标签', () => {
expect(mediaGate(item(1, { location: 'online', follow_item_id: 5 } as Partial<DetailItem>), false)).toBe('');
expect(mediaGate(item(1, { cost: 'metered' }), false)).toBe('metered');
expect(mediaGate(item(1), false)).toBe('');
+ expect(mediaGate(item(1, { name: 'ABC-123.ISO' }), false)).toBe('disc');
});
});
diff --git a/frontend/test/react/library-completion.test.tsx b/frontend/test/react/library-completion.test.tsx
index dc6d712f5..9555c6e61 100644
--- a/frontend/test/react/library-completion.test.tsx
+++ b/frontend/test/react/library-completion.test.tsx
@@ -22,9 +22,18 @@ it('缺图提示只选择没有可用卡面且可以补全的影片,保留来
item(7, { location: '115' }), item(8, { code: 'ABW-001', location: '115' }),
item(9, { follow_thumb_url: 'https://example.test/image.jpg' }),
item(10, { has_cover: true, cover_key: 'sample' }),
+ item(11, { name: 'unknown.strm' }), item(12, { name: 'unknown.iso' }),
], 'cover')).toEqual([1, 8]);
});
+it('关闭视频预览生成时保留资料同步,并禁用单独抽帧', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({ status: 'idle', metadata_only: true }) })));
+ const host = await mount(prompt());
+ await click(host.querySelector('[aria-haspopup="dialog"]'));
+ expect(buttonNamed('仅生成视频预览', document)?.disabled).toBe(true);
+ expect(buttonNamed('仅补全资料', document)?.disabled).toBe(false);
+});
+
it('没有缺图影片时不显示入口也不查询任务', async () => {
const fetcher = vi.fn();
vi.stubGlobal('fetch', fetcher);
@@ -41,11 +50,11 @@ it('默认补全与下拉分项都只提交当前缺图影片,菜单包含主
}));
const host = await mount(prompt());
expect(host.textContent).toContain('2 部暂无预览');
- await click(buttonNamed('补全资料与预览', host));
- for (const label of ['只生成本地预览', '只采集在线资料']) {
+ await click(buttonNamed('同步这些影片', host));
+ for (const label of ['仅生成视频预览', '仅补全资料']) {
await click(host.querySelector('[aria-haspopup="dialog"]'));
const menu = document.querySelector('[role="dialog"]')!;
- expect(buttonNamed('补全资料与预览', menu)).not.toBeNull();
+ expect(buttonNamed('同步这些影片', menu)).not.toBeNull();
await click(buttonNamed(label, menu));
}
expect(posts).toEqual([
@@ -69,7 +78,7 @@ it('启动等待期间不重复提交,结束后刷新馆藏并给出封面与
queryClient.setQueryData(['catalog-grid', 'catalog', 'sample', 1], { pages: [] });
const onComplete = vi.fn();
const host = await mount(prompt([7], onComplete));
- const primary = buttonNamed('补全资料与预览', host)!;
+ const primary = buttonNamed('同步这些影片', host)!;
await click(primary);
expect(primary.getAttribute('aria-busy')).toBe('true');
const more = host.querySelector<HTMLButtonElement>('[aria-haspopup="dialog"]')!;
@@ -95,9 +104,9 @@ it('启动失败保留入口与处理详情,不显示完成回执', async () =
? { ok: false, status: 400, json: async () => ({ error: '请先添加媒体文件夹' }) }
: { ok: true, json: async () => ({ status: 'idle' }) }));
const host = await mount(prompt());
- await click(buttonNamed('补全资料与预览', host));
+ await click(buttonNamed('同步这些影片', host));
expect(host.textContent).toContain('请先添加媒体文件夹');
expect(host.textContent).not.toContain('补全完成');
expect(host.querySelector('a[href="/data-cleanup#libraryProcessing"]')?.textContent).toBe('查看并处理');
- expect(buttonNamed('补全资料与预览', host)?.disabled).toBe(false);
+ expect(buttonNamed('同步这些影片', host)?.disabled).toBe(false);
});
diff --git a/frontend/test/react/library-processing.test.tsx b/frontend/test/react/library-processing.test.tsx
index ad67847c8..9aab24416 100644
--- a/frontend/test/react/library-processing.test.tsx
+++ b/frontend/test/react/library-processing.test.tsx
@@ -93,16 +93,16 @@ it('扫描与补全方式共用一颗主键加一个下拉,各自交自己的
const served = await open({ status: 'idle' }, () => ({ status: 'complete' }));
const host = await mount(card({ toast: vi.fn() }));
- await click(buttonNamed('扫描并补全资料', host));
+ await click(buttonNamed('同步媒体库', host));
await click(host.querySelector('[aria-haspopup="dialog"]'));
- expect(menuItem('扫描并补全资料')).not.toBeNull();
- await click(menuItem('只扫描'));
+ expect(menuItem('同步媒体库')).not.toBeNull();
+ await click(menuItem('仅扫描文件'));
await click(host.querySelector('[aria-haspopup="dialog"]'));
- await click(menuItem('补全资料与预览'));
+ await click(menuItem('仅同步已入库影片'));
await click(host.querySelector('[aria-haspopup="dialog"]'));
- await click(menuItem('只生成本地预览'));
+ await click(menuItem('仅生成视频预览'));
await click(host.querySelector('[aria-haspopup="dialog"]'));
- await click(menuItem('只采集在线资料'));
+ await click(menuItem('仅补全资料'));
expect(served.posts()).toEqual([{}, { stage: 'scan' }, { stage: 'collect' }, { stage: 'previews' }, { stage: 'metadata' }]);
expect(host.querySelector('a[href="/sources"]')?.textContent).toContain('来源和凭证');
@@ -117,7 +117,7 @@ it('启动只提交一次,进度用 GET 读回来,完成后给出回执与
: { status: 'complete', job_id: 'one', scanned: 9, identified: 4, candidates: 2 },
);
const host = await mount(card({ toast }));
- await click(buttonNamed('扫描并补全资料', host));
+ await click(buttonNamed('同步媒体库', host));
expect(served.calls.map((call) => call.method)).toEqual(['POST', 'GET']);
expect(host.querySelector('a[href="/review"]')).not.toBeNull();
@@ -142,7 +142,7 @@ it('补齐女优资料的读数进回执,冲突和未取得各自点名', asyn
},
);
const host = await mount(card({ toast: vi.fn() }));
- await click(buttonNamed('扫描并补全资料', host));
+ await click(buttonNamed('同步媒体库', host));
expect(served.posts()).toEqual([{}]);
expect(host.querySelector('[role="status"]')?.textContent).toContain(
@@ -173,7 +173,7 @@ it('运行态说清当前项目、动作与等待时长,处理慢只提示不
expect(host.querySelectorAll('[role="progressbar"]')).toHaveLength(1);
expect(host.querySelector('[role="progressbar"]')?.getAttribute('aria-valuenow')).toBe('2');
- await click(buttonNamed('扫描并补全资料', host));
+ await click(buttonNamed('同步媒体库', host));
expect(served.posts()).toEqual([]);
});
@@ -209,7 +209,7 @@ it('失败时把问题清单折叠进错误提示,重试只交失败的那些
expect(log.closest('.border-t')!.className).toContain('border-current/20');
expect(details.querySelector('button[aria-label="在资源管理器中显示"]')).not.toBeNull();
// 补上没做完的那些是这一趟的事,重新跑一整批是下一趟的事:页脚那颗留着,各答各的问题。
- expect(buttonNamed('扫描并补全资料', host)?.textContent).toBe('扫描并补全资料');
+ expect(buttonNamed('同步媒体库', host)?.textContent).toBe('同步媒体库');
// 重试键属于错误提示,问题清单收起时仍可操作。
const retry = buttonNamed('重试未完成项')!;
@@ -230,7 +230,7 @@ it('有可重试项时页脚那颗发的仍是整批,不夹带上一趟的失
}, () => ({ status: 'running', job_id: 'two' }));
const host = await mount(card({ toast: vi.fn() }));
- await click(buttonNamed('扫描并补全资料', host));
+ await click(buttonNamed('同步媒体库', host));
expect(served.posts()).toEqual([{}]);
});
@@ -241,7 +241,7 @@ it('失败项都不可重试时仍能重新发起整批任务', async () => {
});
const host = await mount(card({ toast: vi.fn() }));
expect(buttonNamed('重试未完成项')).toBeNull();
- expect(buttonNamed('扫描并补全资料', host)?.textContent).toBe('扫描并补全资料');
+ expect(buttonNamed('同步媒体库', host)?.textContent).toBe('同步媒体库');
});
it('读不回来时留住已有进度,只在旁边说一句连接中断', async () => {
diff --git a/frontend/test/react/media-processing-settings.test.tsx b/frontend/test/react/media-processing-settings.test.tsx
new file mode 100644
index 000000000..b676197f6
--- /dev/null
+++ b/frontend/test/react/media-processing-settings.test.tsx
@@ -0,0 +1,51 @@
+import { QueryClientProvider, notifyManager } from '@tanstack/react-query';
+import { afterEach, expect, it, vi } from 'vitest';
+
+import { queryClient } from '../../src/react/query';
+import { MediaProcessingSettings } from '../../src/react/settings/media-processing-settings';
+import { click, mount, pending, settle } from './render';
+
+notifyManager.setScheduler((notify) => notify());
+afterEach(() => queryClient.clear());
+
+it('读取已保存模式,等待服务端保存完成才更新开关和回执', async () => {
+ const saved = pending<{ metadata_only: boolean }>();
+ const receipt = vi.fn();
+ const requests: unknown[] = [];
+ vi.stubGlobal('fetch', vi.fn(async (_url: string, init?: RequestInit) => {
+ if (init?.method === 'POST') {
+ requests.push(JSON.parse(String(init.body)));
+ return { ok: true, json: () => saved.answer };
+ }
+ return { ok: true, json: async () => ({ metadata_only: false }) };
+ }));
+ const host = await mount(<QueryClientProvider client={queryClient}><MediaProcessingSettings receipt={receipt} /></QueryClientProvider>);
+ await settle();
+ const control = host.querySelector<HTMLInputElement>('input[role="switch"]') || host.querySelector<HTMLInputElement>('input[type="checkbox"]');
+ expect(control).not.toBeNull();
+ await click(control);
+ await settle();
+ expect(requests).toEqual([{ metadata_only: true }]);
+ expect(receipt).not.toHaveBeenCalled();
+ expect(host.textContent).toContain('正在保存');
+ await saved.release({ metadata_only: true });
+ await settle();
+ expect(receipt).toHaveBeenCalledWith('已关闭视频预览生成');
+ expect(control?.checked).toBe(false);
+});
+
+it('保存失败保留当前模式并显示可恢复的错误', async () => {
+ vi.stubGlobal('fetch', vi.fn(async (_url: string, init?: RequestInit) => ({
+ ok: init?.method !== 'POST', status: init?.method === 'POST' ? 400 : 200,
+ json: async () => init?.method === 'POST' ? { error: '设置未能保存' } : { metadata_only: true },
+ })));
+ const receipt = vi.fn();
+ const host = await mount(<QueryClientProvider client={queryClient}><MediaProcessingSettings receipt={receipt} /></QueryClientProvider>);
+ await settle();
+ const control = host.querySelector<HTMLInputElement>('input[type="checkbox"]');
+ await click(control);
+ await settle();
+ expect(control?.checked).toBe(false);
+ expect(host.textContent).toContain('设置未能保存');
+ expect(receipt).not.toHaveBeenCalled();
+});
diff --git a/frontend/test/react/surface-routes.test.tsx b/frontend/test/react/surface-routes.test.tsx
index 76705207f..be25b15ab 100644
--- a/frontend/test/react/surface-routes.test.tsx
+++ b/frontend/test/react/surface-routes.test.tsx
@@ -131,7 +131,7 @@ it('处理横幅取齐首屏才换掉骨架;首屏在途时容器已归路由
await act(async () => { await opening });
expect(el.querySelector('[data-skeleton]')).toBeNull();
// token、Preflight 与焦点规则都作用在 `.peach-react` 上,页面不画在它里面就没有样式。
- expect(el.querySelector('.peach-react')?.textContent).toContain('扫描并补全资料');
+ expect(el.querySelector('.peach-react')?.textContent).toContain('同步媒体库');
});
it('取数期间壳已换页就不画,骨架留给下一页', async () => {
diff --git a/src/peach/api.py b/src/peach/api.py
index 2c28754e5..c9d8c6a67 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -424,6 +424,8 @@ def create_app(
app.state.downloads = downloads
app.state.mount_reachability = mount_reachability
app.state.stream_sessions = StreamSessionRegistry()
+ from .strm_stream import StrmResources
+ app.state.strm_resources = StrmResources()
import secrets
app.state.external_playback_key = secrets.token_bytes(32)
app.state.sync = sync
diff --git a/src/peach/follow_stream.py b/src/peach/follow_stream.py
index d9b36bd6b..dba34f071 100644
--- a/src/peach/follow_stream.py
+++ b/src/peach/follow_stream.py
@@ -406,7 +406,8 @@ def proxy_request_headers(target: ResolvedFollowMedia,
def open_upstream(client: httpx.Client, method: str, target: ResolvedFollowMedia, *,
- incoming: Mapping[str, str]) -> httpx.Response:
+ incoming: Mapping[str, str], allowed=None, accepted_statuses=(),
+ strip_credentials=False) -> httpx.Response:
"""打开上游媒体流;只在拿到可转发的 2xx 时返回。
这里自己跟重定向而不是交给 client 的 `follow_redirects`:`target.headers` 可能
@@ -417,16 +418,19 @@ def open_upstream(client: httpx.Client, method: str, target: ResolvedFollowMedia
非 2xx 同样在这里终止:上游的 403 页面、限流提示或错误 JSON 转发给播放器毫无
用处,只会把上游的状态与正文(可能含主机名、提示语)原样交给浏览器。
"""
- if not target.allowed_hosts and not target.public_hosts:
+ if allowed is None and not target.allowed_hosts and not target.public_hosts:
raise FollowProxyError("这条媒体没有可代理的主机白名单")
url = target.url
headers = proxy_request_headers(target, incoming)
response: httpx.Response | None = None
for _ in range(MAX_PROXY_REDIRECTS + 1):
- if not _hop_allowed(target, url):
+ if not (allowed(url) if allowed is not None else _hop_allowed(target, url)):
raise FollowProxyError("媒体地址不在可代理的主机范围内" if url == target.url
else "上游把媒体重定向到了不受信任的地址")
request = client.build_request(method, url, headers=headers)
+ if strip_credentials:
+ for name in ('cookie', 'authorization', 'proxy-authorization'):
+ request.headers.pop(name, None)
response = client.send(request, stream=True, follow_redirects=False)
if response.status_code not in _REDIRECT_STATUSES:
break
@@ -436,7 +440,7 @@ def open_upstream(client: httpx.Client, method: str, target: ResolvedFollowMedia
url = urllib.parse.urljoin(url, location)
if response is None:
raise FollowProxyError("上游重定向次数过多")
- if not 200 <= response.status_code < 300:
+ if not 200 <= response.status_code < 300 and response.status_code not in accepted_statuses:
status = response.status_code
response.close()
raise FollowProxyError(f"上游返回 HTTP {status}")
diff --git a/src/peach/library_processing.py b/src/peach/library_processing.py
index 7bd4b70cf..e9cfadd86 100644
--- a/src/peach/library_processing.py
+++ b/src/peach/library_processing.py
@@ -37,6 +37,8 @@ from .scan import scan_location
from .ffmpeg import FFmpegResolver
from .jobs import DiskGuard
from .media_probe import probe_unmeasured
+from .media_processing_policy import metadata_only
+from .strm import skip_background_read
from .record_rehome import reattach_in
FIELDS = ('item_key', 'code', 'query', 'asset_id', 'asset_path', 'field', 'field_label', 'current_value',
@@ -1657,7 +1659,7 @@ def _scan_sources(config, db_path, *, locations, asset_ids, stage, guard, update
chosen_paths = _chosen_asset_paths(db_path, asset_ids)
scan = asset_ids is None and stage in (ALL_STAGES, SCAN_STAGE)
mounts = {key: tuple(str(value) for value in values) for key, values in config.mounts.items()}
- ffprobe = _ffprobe_path(config) if scan else None
+ ffprobe = _ffprobe_path(config) if scan or stage == COLLECT_STAGE else None
for source, roots in locations.items():
if stage == PREVIEWS_STAGE and source != 'local':
continue
@@ -1677,6 +1679,10 @@ def _scan_sources(config, db_path, *, locations, asset_ids, stage, guard, update
report=lambda done, total: update(stage='读取时长与分辨率', checked=done, total=total))
reattach_in(db_path, registered.new_ids)
update(scanned=result.scanned, probed=result.probed)
+ elif stage == COLLECT_STAGE:
+ result.probed += probe_unmeasured(
+ db_path, ffprobe, source, root, asset_ids=asset_ids,
+ report=lambda done, total: update(stage='读取时长与分辨率', checked=done, total=total))
return result
@@ -1788,6 +1794,8 @@ def _generate_preview(config, row, database, resolver, *, progress):
with tempfile.TemporaryDirectory(prefix='peach-preview-') as temporary:
frames = Path(temporary)
for index in range(9):
+ if metadata_only(config.directory('state')):
+ return False
progress()
timestamp = duration * (0.03 + 0.94 * (index + 0.5) / 9)
if not frame_capture.capture_with_retry(
@@ -1812,10 +1820,12 @@ def _generate_previews(config, rows, database, *, update, issue, guard,
"""只读本机视频;来源失败与抽帧失败各自保留可重试项目。"""
if database is None:
return 0
- rows = [row for row in rows if row['location'] == 'local']
+ rows = [row for row in rows if row['location'] == 'local' and not skip_background_read(row['path'])]
resolver = FFmpegResolver(config.directory('tools') / 'ffmpeg')
made = 0
for index, row in enumerate(rows):
+ if metadata_only(config.directory('state')):
+ break
if _checkpoint_key(row) in completed:
continue
def progress(row=row, index=index, made=made):
@@ -1904,6 +1914,8 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='co
_require_writer(config, db_path)
if stage not in STAGES:
raise ValueError('处理阶段无效')
+ if stage == PREVIEWS_STAGE and metadata_only(config.directory('state')):
+ raise ValueError('视频预览生成已关闭,请先在媒体库设置中开启')
if asset_ids is not None and retry_ids is not None:
raise ValueError('选择项目与失败重试不能同时使用')
selected_ids = _asset_selection(db_path, asset_ids)
@@ -1996,7 +2008,8 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='co
return state
rows, genre_decisions = _collection_rows(
db_path, locations=locations, online_roots=sources.online_roots, asset_ids=scope_ids)
- if stage in (ALL_STAGES, COLLECT_STAGE, PREVIEWS_STAGE):
+ if (stage in (ALL_STAGES, COLLECT_STAGE, PREVIEWS_STAGE)
+ and not metadata_only(config.directory('state'))):
_generate_previews(config, rows, database, update=update, issue=issue, guard=guard,
completed=checkpoints.completed['completed_previews'],
checkpoint=lambda row: checkpoints.mark('completed_previews', row, flush_state))
diff --git a/src/peach/media_probe.py b/src/peach/media_probe.py
index dac4ddb80..55e500bb7 100644
--- a/src/peach/media_probe.py
+++ b/src/peach/media_probe.py
@@ -23,6 +23,7 @@ from pathlib import PureWindowsPath
from .jobs import ACTIVE_ASSET_SQL, SourceAccessPolicy
from .media import resolve_case_insensitive
+from .strm import skip_background_read
#: 一次探测最多等多久。ffprobe 只读文件头,网盘上实测一两秒。
TIMEOUT_SECONDS = 20.0
@@ -52,6 +53,8 @@ def context_fields(width: int, height: int, duration: float) -> tuple[str | None
def probe_file(ffprobe: str, path: str, timeout: float = TIMEOUT_SECONDS) -> tuple:
+ if skip_background_read(path):
+ raise ValueError('STRM 和 ISO 不执行视频探测')
result = subprocess.run(
[
ffprobe, "-v", "error", "-rw_timeout", "8000000",
@@ -98,21 +101,30 @@ def measure(ffprobe: str, asset_id: int, path: str, timeout: float = TIMEOUT_SEC
def probe_unmeasured(
db_path, ffprobe: str | None, location: str, root: str, *,
report: Callable[[int, int], None] = lambda done, total: None,
+ asset_ids: Sequence[int] | None = None,
) -> int:
"""`root`(账本口径)下还没探过的视频逐个探一遍,返回探了几个。"""
if not ffprobe or location in SourceAccessPolicy().metered_locations:
return 0
prefix = str(PureWindowsPath(root)).rstrip("\\") + "\\"
+ selected = ''
+ parameters = (location, len(prefix), prefix)
+ if asset_ids is not None:
+ if not asset_ids:
+ return 0
+ selected = ' AND id IN (' + ','.join('?' * len(asset_ids)) + ')'
+ parameters += tuple(asset_ids)
with closing(sqlite3.connect(db_path, timeout=30)) as connection:
rows = connection.execute(
- f"SELECT id,path FROM asset WHERE {_UNMEASURED} AND substr(path,1,?)=? ORDER BY id",
- (location, len(prefix), prefix)).fetchall()
+ f"SELECT id,path FROM asset WHERE {_UNMEASURED} AND substr(path,1,?)=?{selected} ORDER BY id",
+ parameters).fetchall()
return _record(db_path, ffprobe, rows, report)
def probe_path(db_path, ffprobe: str | None, location: str, path: str) -> int:
"""推送发现刚登记的这一个文件;不是视频、已经探过或来源计费都回 0。"""
- if not ffprobe or location in SourceAccessPolicy().metered_locations:
+ if (not ffprobe or location in SourceAccessPolicy().metered_locations
+ or skip_background_read(path)):
return 0
with closing(sqlite3.connect(db_path, timeout=30)) as connection:
rows = connection.execute(
@@ -123,6 +135,7 @@ def probe_path(db_path, ffprobe: str | None, location: str, path: str) -> int:
def _record(db_path, ffprobe: str, rows: Sequence, report: Callable[[int, int], None]) -> int:
"""探完一条写一条。`report` 抛出来(任务被停)时,还没开始的那些不再探。"""
+ rows = [row for row in rows if not skip_background_read(row[1])]
if not rows:
return 0
done = 0
diff --git a/src/peach/media_processing_policy.py b/src/peach/media_processing_policy.py
new file mode 100644
index 000000000..44a45e987
--- /dev/null
+++ b/src/peach/media_processing_policy.py
@@ -0,0 +1,43 @@
+"""本机视频预览偏好;资料管理模式保留媒体探测、关闭视频抽帧。"""
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from .fsutil import atomic_write_text
+
+FILENAME = 'media-processing.json'
+
+
+def metadata_only(state_root: Path | None = None) -> bool:
+ if state_root is None:
+ from .settings_file import active
+ state_root = active().directory('state')
+ try:
+ payload = json.loads((Path(state_root) / FILENAME).read_text(encoding='utf-8'))
+ except FileNotFoundError:
+ return False
+ except (OSError, ValueError):
+ return True
+ return not isinstance(payload, dict) or payload.get('metadata_only') is not False
+
+
+def save(state_root: Path, value: bool) -> None:
+ if not isinstance(value, bool):
+ raise ValueError('请选择视频预览生成状态')
+ atomic_write_text(Path(state_root) / FILENAME,
+ json.dumps({'metadata_only': value}) + '\n')
+
+
+def q_media_processing(contract, _args):
+ return {'metadata_only': metadata_only(contract.follow_state_root)}
+
+
+def w_media_processing(contract, body):
+ value = (body or {}).get('metadata_only')
+ save(contract.follow_state_root, value)
+ if value:
+ from .web_timeline_thumbnails import write_mode
+ write_mode('off', Path(contract.follow_state_root) / 'timeline-thumbnails.json')
+ contract.thumbnail_job.stop(resume=False)
+ return q_media_processing(contract, {})
diff --git a/src/peach/preview_cache.py b/src/peach/preview_cache.py
index ed8fdbd49..455c18f16 100644
--- a/src/peach/preview_cache.py
+++ b/src/peach/preview_cache.py
@@ -12,6 +12,29 @@ from .http import public_https_url
PLAYLIST_REFRESH_SECONDS = 300
+
+def rewrite_hls(body: bytes, url: str, register) -> bytes:
+ """用已声明的 m3u8 模型投影全部媒体引用,地址登记策略由消费者提供。"""
+ text = body.decode('utf-8-sig')
+ if not text.lstrip().startswith('#EXTM3U'):
+ raise ValueError('播放列表未取得')
+ playlist = m3u8.loads(text, uri=url)
+ if playlist.content_steering:
+ raise ValueError('暂不支持 Content Steering 播放列表')
+ nested = [*playlist.playlists, *playlist.iframe_playlists, *playlist.image_playlists, *playlist.media]
+ objects = [*playlist.segments, *nested, *playlist.keys, *playlist.session_keys,
+ *playlist.session_data, *playlist.segment_map, *playlist.rendition_reports,
+ playlist.preload_hint]
+ objects += [segment.init_section for segment in playlist.segments if segment.init_section]
+ objects += [part for segment in playlist.segments for part in segment.parts]
+ seen = set()
+ for obj in objects:
+ if obj is not None and id(obj) not in seen and getattr(obj, 'uri', None):
+ seen.add(id(obj))
+ obj.uri = register(urljoin(url, obj.uri), any(obj is row for row in nested))
+ return playlist.dumps().encode('utf-8')
+
+
class PreviewCache:
def __init__(self, cache):
self.cache = cache
@@ -50,18 +73,7 @@ class PreviewCache:
generation = hashlib.sha256(url.encode()).hexdigest()
body = self.cache.bytes(f"preview:{code}:{ref}:playlist:{generation}", download,
ttl=PLAYLIST_REFRESH_SECONDS)
- playlist = m3u8.loads(body.decode("utf-8").removeprefix(chr(0xFEFF)), uri=url)
- nested = [*playlist.playlists, *playlist.iframe_playlists, *playlist.media]
- objects = [*playlist.segments, *nested, *playlist.keys, *playlist.session_keys, *playlist.segment_map]
- for obj in objects:
- if obj is None or not getattr(obj, "uri", None):
- continue
- source = urljoin(url, obj.uri)
- item = self.register(code, source, playlist=any(obj is row for row in nested))
- obj.uri = f"/jav-preview/{code}/{item}{'.m3u8' if any(obj is row for row in nested) else ''}"
- # 每个段的 init_section 是同一格式的独立对象,必须一同投影。
- for segment in playlist.segments:
- obj = segment.init_section
- if obj and obj.uri and not obj.uri.startswith("/jav-preview/"):
- obj.uri = f"/jav-preview/{code}/{self.register(code, urljoin(url, obj.uri))}"
- return playlist.dumps().encode("utf-8")
+ def register(source, nested):
+ item = self.register(code, source, playlist=nested)
+ return f"/jav-preview/{code}/{item}{'.m3u8' if nested else ''}"
+ return rewrite_hls(body, url, register)
diff --git a/src/peach/routes_media.py b/src/peach/routes_media.py
index bf9075bc5..2f2da7e8c 100644
--- a/src/peach/routes_media.py
+++ b/src/peach/routes_media.py
@@ -221,6 +221,9 @@ def _external_asset(request: Request, asset_id: int, ticket: str, origin: str):
@router.api_route("/external-stream/{id}", methods=["GET", "HEAD"])
def external_stream(request: Request, id: int, ticket: str, origin: str = ''):
path = _external_asset(request, id, ticket, origin)
+ from . import strm, strm_stream
+ if strm.is_pointer(path):
+ return strm_stream.proxy(request, id, path)
return BufferedFileResponse(path, headers={"Cache-Control": "no-store", "Referrer-Policy": "no-referrer"})
@@ -238,6 +241,11 @@ def stream(request: Request, id: int, session: str = "", args: dict[str, str] =
state = request.app.state
asset = state.media_engine.asset(id)
path = state.media_engine.filesystem.file_for(asset, thumbnail=False)
+ from . import strm, strm_stream
+ if strm.is_pointer(path):
+ return strm_stream.proxy(request, id, path, session)
+ if path.suffix.lower() in strm.DISC_SUFFIXES:
+ return JSONResponse({'error': 'ISO 原盘请使用作品详情中的外部播放器打开'}, status_code=415)
header = _repaired_header(state, id, path)
if header is not None:
return SplicedMp4Response(
@@ -276,6 +284,18 @@ def stream_plan(request: Request, id: int, session: str = "", mode: str = "", ar
plan = state.media_engine.stream_plan(id, mode=mode or "auto")
# 只有真的能读出关键帧才宣告 HLS,否则客户端会拿到一个必然 404 的播放列表。
source_path = state.media_engine.filesystem.file_for(asset, thumbnail=False)
+ from . import strm, strm_stream
+ if strm.is_pointer(source_path):
+ try:
+ target = strm.read_target(source_path)
+ except ValueError as error:
+ return JSONResponse({'error': str(error)}, status_code=400)
+ mime = strm_stream.mime_type(target)
+ return {'id': id, 'protocol': 'hls' if mime in strm_stream.PLAYLIST_TYPES else 'range',
+ 'mime_type': mime, 'duration': asset.duration,
+ 'src': f'/stream?id={id}&session={quote(session, safe="")}', 'reason': 'strm-pointer'}
+ if source_path.suffix.lower() in strm.DISC_SUFFIXES:
+ return JSONResponse({'error': 'ISO 原盘请使用作品详情中的外部播放器打开'}, status_code=415)
conversion = _needs_conversion(state, id, source_path, session)
resolved = (_hls_plan(state, id, session, conversion)
if conversion or plan.protocol == "hls" else None)
@@ -303,6 +323,20 @@ def stream_plan(request: Request, id: int, session: str = "", mode: str = "", ar
}
[email protected]_route('/strm-resource/{id}/{key}', methods=['GET', 'HEAD'])
+def strm_resource(request: Request, id: int, key: str, session: str = '',
+ ticket: str = '', origin: str = ''):
+ from . import strm, strm_stream
+ if ticket:
+ path = _external_asset(request, id, ticket, origin)
+ else:
+ require_auth(request)
+ path = request.app.state.media_engine.file_for(id)
+ if not strm.is_pointer(path):
+ return Response(status_code=404)
+ return strm_stream.proxy(request, id, path, session, key)
+
+
@router.get("/stream/hls/{id}/index.m3u8")
def hls_playlist(request: Request, id: int, session: str = "", args: dict[str, str] = Depends(require_auth)):
state = request.app.state
diff --git a/src/peach/scan.py b/src/peach/scan.py
index 28152fb0a..a69e8486a 100644
--- a/src/peach/scan.py
+++ b/src/peach/scan.py
@@ -42,7 +42,7 @@ from . import folder_rules, record_rehome, subtitles, wants
from .platform import is_windows_path, resolve_location, resolve_root
VIDEO = {".mp4", ".m4v", ".mkv", ".avi", ".wmv", ".mov", ".ts", ".flv", ".rmvb", ".mpg",
- ".m2ts"}
+ ".m2ts", ".strm", ".iso"}
IMAGE = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"}
AUDIO = {".mp3", ".flac", ".wav", ".m4a", ".ogg", ".opus"}
ARCHIVE = {".zip", ".rar", ".7z", ".tar", ".gz"}
@@ -70,7 +70,7 @@ _DERIVED_THUMB = re.compile(
_UPSERT = """INSERT INTO asset(location,path,name,medium,size,mtime,first_seen,last_seen)
VALUES(?,?,?,?,?,?,?,?)
ON CONFLICT(location,path) DO UPDATE SET
- size=excluded.size, mtime=excluded.mtime, last_seen=excluded.last_seen,
+ medium=excluded.medium, size=excluded.size, mtime=excluded.mtime, last_seen=excluded.last_seen,
disposal=CASE WHEN asset.disposal='vanished' THEN NULL ELSE asset.disposal END"""
diff --git a/src/peach/settings_file.py b/src/peach/settings_file.py
index 1ba5b7925..3832f76b7 100644
--- a/src/peach/settings_file.py
+++ b/src/peach/settings_file.py
@@ -362,7 +362,7 @@ def _merge(
raise _fail(path, (
"`[media]` 下不再接受盘符键:" + "、".join(stray)
+ "。改写成 `[media.mounts] <location-id> = <本机路径>`,"
- "ID 取 `[media.locations]` 里的键(local / 115 / pikpak),"
+ "ID 取 `[media.locations]` 中已配置的来源键,"
"路径填该来源的声明根在本机的落点,例如 "
"`local = '/mnt/media'`"
))
diff --git a/src/peach/strm.py b/src/peach/strm.py
new file mode 100644
index 000000000..d22c30210
--- /dev/null
+++ b/src/peach/strm.py
@@ -0,0 +1,44 @@
+"""STRM 文本指针:只读取授权目录中的小文件,播放时才解析目标。"""
+from __future__ import annotations
+
+from pathlib import Path
+from urllib.parse import urlsplit
+
+MAX_BYTES = 64 * 1024
+POINTER_SUFFIX = '.strm'
+DISC_SUFFIXES = frozenset({'.iso'})
+
+
+def is_pointer(path: str | Path) -> bool:
+ return Path(path).suffix.lower() == POINTER_SUFFIX
+
+
+def skip_background_read(path: str | Path) -> bool:
+ return Path(path).suffix.lower() in DISC_SUFFIXES | {POINTER_SUFFIX}
+
+
+def validate_url(url: str) -> str:
+ try:
+ parts = urlsplit(url)
+ valid = (parts.scheme.lower() in {'http', 'https'} and parts.hostname
+ and not parts.username and not parts.password and parts.port != 0)
+ except ValueError:
+ valid = False
+ if not valid or any(ord(char) < 33 or ord(char) == 127 for char in url) or '\\' in url:
+ raise ValueError('STRM 需要不含账号密码的 HTTP 或 HTTPS 播放地址')
+ return url
+
+
+def read_target(path: Path) -> str:
+ try:
+ with path.open('rb') as handle:
+ content = handle.read(MAX_BYTES + 1)
+ if len(content) > MAX_BYTES:
+ raise ValueError('STRM 文件超过 64 KiB')
+ lines = [line.strip() for line in content.decode('utf-8-sig').splitlines()
+ if line.strip() and not line.lstrip().startswith('#')]
+ except (OSError, UnicodeError) as error:
+ raise ValueError('STRM 文件未取得或不是 UTF-8 文本') from error
+ if len(lines) != 1:
+ raise ValueError('STRM 文件需要且只能包含一个播放地址')
+ return validate_url(lines[0])
diff --git a/src/peach/strm_stream.py b/src/peach/strm_stream.py
new file mode 100644
index 000000000..1f24949fb
--- /dev/null
+++ b/src/peach/strm_stream.py
@@ -0,0 +1,150 @@
+"""STRM 的按需播放代理;Range 与 HLS 均保留 Peach 鉴权和上游地址隔离。"""
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import threading
+import time
+from collections import OrderedDict
+from urllib.parse import quote, urlsplit
+
+import httpx
+from starlette.background import BackgroundTask
+from starlette.responses import JSONResponse, Response, StreamingResponse
+
+from .follow_stream import FollowProxyError, ResolvedFollowMedia, open_upstream
+from .http import public_https_url, resolves_publicly
+from .remote_media_cache import MEDIA_HEADERS
+from .preview_cache import rewrite_hls
+from .strm import read_target, validate_url
+
+PLAYLIST_TYPES = frozenset({'application/vnd.apple.mpegurl', 'application/x-mpegurl', 'audio/mpegurl'})
+PLAYLIST_LIMIT = 2 * 1024 * 1024
+
+
+def mime_type(url: str) -> str:
+ suffix = urlsplit(url).path.lower()
+ return ('application/vnd.apple.mpegurl' if suffix.endswith('.m3u8')
+ else 'video/webm' if suffix.endswith('.webm') else 'video/mp4')
+
+
+def allowed_hop(root: str, url: str) -> bool:
+ try:
+ validate_url(url)
+ parsed, original = urlsplit(url), urlsplit(root)
+ except ValueError:
+ return False
+ if (parsed.scheme, parsed.hostname, parsed.port) == (original.scheme, original.hostname, original.port):
+ return True
+ return public_https_url(url) and resolves_publicly(parsed.hostname or '')
+
+
+class StrmResources:
+ """HLS 子资源只发不含上游地址的短键,映射保存在本机有界内存。"""
+
+ def __init__(self, capacity: int = 65536):
+ self.entries = OrderedDict()
+ self.lock = threading.Lock()
+ self.capacity = capacity
+
+ def add(self, asset_id: int, root: str, url: str) -> str:
+ key = hashlib.sha256(f'{asset_id}\n{root}\n{url}'.encode()).hexdigest()
+ with self.lock:
+ self.entries.pop(key, None)
+ self.entries[key] = (time.monotonic() + 6 * 3600, asset_id, root, url)
+ while len(self.entries) > self.capacity:
+ self.entries.popitem(last=False)
+ return key
+
+ def get(self, key: str, asset_id: int, root: str) -> str:
+ with self.lock:
+ row = self.entries.get(key)
+ if row is None or row[0] <= time.monotonic() or row[1:3] != (asset_id, root):
+ raise ValueError('STRM 播放资源已失效,请重新打开作品')
+ return row[3]
+
+
+def resources(state):
+ return state.strm_resources
+
+
+def rewrite_playlist(state, body: bytes, base: str, asset_id: int, root: str, session: str,
+ external_query: str = '') -> str:
+ def link(target, _nested):
+ if not allowed_hop(root, target):
+ raise ValueError('STRM 播放列表包含不可访问的媒体地址')
+ key = resources(state).add(asset_id, root, target)
+ return f'/strm-resource/{asset_id}/{key}?session={quote(session, safe="")}{external_query}'
+
+ return rewrite_hls(body, base, link).decode('utf-8')
+
+
+def proxy(request, asset_id: int, path, session: str = '', resource: str = ''):
+ state = request.app.state
+ if len(session) > 128:
+ return JSONResponse({'error': 'invalid session'}, status_code=400)
+ if session and state.stream_sessions.is_cancelled(session):
+ return Response(status_code=410)
+ upstream = None
+ try:
+ root = read_target(path)
+ target = resources(state).get(resource, asset_id, root) if resource else root
+ upstream = open_upstream(
+ state.http_transport.client, request.method, ResolvedFollowMedia(target, ''),
+ incoming=request.headers, allowed=lambda url: allowed_hop(root, url),
+ accepted_statuses=(416,), strip_credentials=True)
+ headers = {name: upstream.headers[name] for name in MEDIA_HEADERS if name in upstream.headers}
+ headers.update({'cache-control': 'no-store', 'referrer-policy': 'no-referrer'})
+ if upstream.status_code == 416:
+ upstream.close()
+ return Response(status_code=416, headers={name: value for name, value in headers.items()
+ if name not in {'content-type', 'content-length', 'content-encoding'}})
+ content_type = upstream.headers.get('content-type', '').split(';')[0].lower()
+ playlist = content_type in PLAYLIST_TYPES or urlsplit(str(upstream.url)).path.lower().endswith('.m3u8')
+ if request.method == 'HEAD':
+ upstream.close()
+ return Response(status_code=upstream.status_code, headers=headers)
+ if playlist:
+ try:
+ content = bytearray()
+ for chunk in upstream.iter_bytes():
+ content.extend(chunk)
+ if len(content) > PLAYLIST_LIMIT:
+ raise ValueError('STRM 播放列表超过 2 MiB')
+ finally:
+ upstream.close()
+ external_query = ''
+ if request.query_params.get('ticket'):
+ external_query = ('&ticket=' + quote(request.query_params['ticket'], safe='')
+ + '&origin=' + quote(request.query_params.get('origin', ''), safe=''))
+ text = rewrite_playlist(state, bytes(content), str(upstream.url), asset_id, root, session,
+ external_query)
+ return Response(text, media_type='application/vnd.apple.mpegurl',
+ headers={'cache-control': 'no-store', 'referrer-policy': 'no-referrer'})
+
+ async def body():
+ task = asyncio.current_task()
+ registered = not session or state.stream_sessions.register(session, task)
+ try:
+ if not registered:
+ return
+ iterator = iter((upstream.content,)) if upstream.is_stream_consumed else upstream.iter_raw()
+ while True:
+ chunk = await asyncio.to_thread(next, iterator, None)
+ if chunk is None:
+ break
+ yield chunk
+ finally:
+ upstream.close()
+ if session and registered:
+ state.stream_sessions.unregister(session, task)
+ return StreamingResponse(body(), status_code=upstream.status_code,
+ headers=headers, background=BackgroundTask(upstream.close))
+ except ValueError:
+ if upstream is not None:
+ upstream.close()
+ return JSONResponse({'error': 'STRM 内容无法解析,请检查播放地址和列表格式'}, status_code=400)
+ except (FollowProxyError, OSError, httpx.HTTPError):
+ if upstream is not None:
+ upstream.close()
+ return JSONResponse({'error': 'STRM 媒体未取得,请检查播放地址或在生成工具中更新 STRM'}, status_code=502)
diff --git a/src/peach/timeline_sheets.py b/src/peach/timeline_sheets.py
index efd91192c..8ec25a9f6 100644
--- a/src/peach/timeline_sheets.py
+++ b/src/peach/timeline_sheets.py
@@ -221,6 +221,12 @@ def generate_library(db_path: Path | str, root: Path, interval: int, *, ffmpeg:
"failed": 0, "stopped": ""}
report(**state)
for asset_id, path, duration in tasks:
+ from .strm import skip_background_read
+ if skip_background_read(path):
+ state['done'] += 1
+ state['skipped'] += 1
+ report(**state)
+ continue
if not active():
state["stopped"] = STOPPED_BY_USER
break
diff --git a/src/peach/web_catalog.py b/src/peach/web_catalog.py
index b643fd745..b77731f70 100644
--- a/src/peach/web_catalog.py
+++ b/src/peach/web_catalog.py
@@ -49,6 +49,10 @@ CARD_PERFORMERS = 6
def attach_artwork_fields(contract: WebContract, item: dict) -> None:
"""列表、详情与推荐共用本地官方封面和版本投影。"""
+ from .strm import is_pointer
+ if is_pointer(item.get('path') or item.get('name') or ''):
+ item['size'] = None
+ item['is_strm'] = True
key = artwork_key(item['id'], item.get('code'))
item['has_cover'] = contract.has_cover(key)
item['cover_key'] = key if item['has_cover'] else ''
diff --git a/src/peach/web_library_processing.py b/src/peach/web_library_processing.py
index 33ea0aa64..30ffebdb2 100644
--- a/src/peach/web_library_processing.py
+++ b/src/peach/web_library_processing.py
@@ -14,6 +14,8 @@ def _current(contract):
def q_library_processing(contract, _args):
state = decorate(_current(contract))
+ from .media_processing_policy import metadata_only
+ state['metadata_only'] = metadata_only(settings_file.active().directory('state'))
from .job_recovery import read
recovery = read(contract.db_path, 'library-processing')
if state.get('status') != 'running' and recovery.get('status') == 'blocked':
@@ -90,6 +92,9 @@ def w_library_processing(contract, body, *, resume=False):
(previous.get('requested_stage') if retry_ids is not None else None) or ALL_STAGES)
if stage not in STAGES:
raise ValueError('处理阶段无效')
+ from .media_processing_policy import metadata_only
+ if stage == PREVIEWS_STAGE and metadata_only(config.directory('state')):
+ raise ValueError('视频预览生成已关闭,请先在媒体库设置中开启')
if retry_ids is not None and not retry_ids:
return previous
def work(job_id):
diff --git a/src/peach/web_router.py b/src/peach/web_router.py
index 7ced59db6..c0c531b4f 100644
--- a/src/peach/web_router.py
+++ b/src/peach/web_router.py
@@ -94,6 +94,7 @@ from .web_custom_metadata import q_custom_metadata, w_custom_metadata
from .web_resource_sync import w_purge_missing, w_resource_sync_apply, w_resource_sync_scan
from .web_review import q_review, w_review_decision, w_review_genre
from .web_settings import q_settings, w_settings
+from .media_processing_policy import q_media_processing, w_media_processing
from .web_library_shortcuts import q_library_shortcuts, w_library_shortcuts
from .web_folders import q_folders, w_folder_preview, w_folder_rule
from .web_scraping import (
@@ -315,6 +316,7 @@ def _post_empty_trash(contract, _body):
GET_HANDLERS = {
+ "/api/media-processing": q_media_processing,
"/api/folders": q_folders,
"/api/tasks": q_tasks,
"/api/downloads": q_downloads,
@@ -381,6 +383,7 @@ GET_HANDLERS = {
}
POST_HANDLERS = {
+ "/api/media-processing": w_media_processing,
"/api/folders/preview": w_folder_preview,
"/api/folders/rule": w_folder_rule,
"/api/downloads": w_download_submit,
@@ -447,6 +450,7 @@ POST_HANDLERS = {
#: 不该拦它们——「查找」只联网、「存凭据」只写本机 secrets 文件,都不碰账本。
#: 追更的「查找」在只读端被拦成 409 是实测踩到的。
READ_ONLY_POST_ROUTES = frozenset({
+ "/api/media-processing",
"/api/folders/preview",
"/api/custom-metadata",
"/api/scraping/settings", "/api/scraping/check",
diff --git a/src/peach/web_timeline_thumbnails.py b/src/peach/web_timeline_thumbnails.py
index c1718d116..aba68a4f6 100644
--- a/src/peach/web_timeline_thumbnails.py
+++ b/src/peach/web_timeline_thumbnails.py
@@ -12,6 +12,7 @@ from .config import FFMPEG_DIR, STATE_DIR
from .ffmpeg import FFmpegResolver
from .fsutil import atomic_path
from .jobs import DiskGuard
+from .media_processing_policy import metadata_only
from .platform import system_volume
#: 采集期间系统盘至少留这么多 GiB。数字和抽帧脚本的默认值同一个:真正会把系统盘写满的
@@ -78,6 +79,8 @@ def w_thumbnail_jobs(contract, body):
mode = str((body or {}).get('mode') or timeline_sheets.OFF)
if mode not in timeline_sheets.MODES:
raise ValueError('采集密度无效')
+ if mode != timeline_sheets.OFF and metadata_only(contract.follow_state_root):
+ raise ValueError('视频预览生成已关闭,请先在媒体库设置中开启')
write_mode(mode)
if mode == timeline_sheets.OFF:
contract.thumbnail_job.stop(resume=False)
@@ -92,7 +95,8 @@ def w_thumbnail_jobs(contract, body):
guard = DiskGuard(system_volume(), MIN_FREE_GB)
result = timeline_sheets.generate_library(
contract.db_path, root, interval, ffmpeg=str(choice.path),
- active=lambda: (contract.thumbnail_job.snapshot() or {}).get('job_id') == job_id,
+ active=lambda: ((contract.thumbnail_job.snapshot() or {}).get('job_id') == job_id
+ and not metadata_only(contract.follow_state_root)),
report=lambda **fields: contract.thumbnail_job.update(job_id, **_with_progress(fields)),
guard=guard)
# 磁盘触线停下来的那一轮不能记成完成:队列后面还剩几千部,而页面上「完成」
diff --git a/tests/test_metadata_library.py b/tests/test_metadata_library.py
index 61dc46a1f..c02a85579 100644
--- a/tests/test_metadata_library.py
+++ b/tests/test_metadata_library.py
@@ -2385,6 +2385,18 @@ class LibraryPreviewCompletionTests(unittest.TestCase):
self.assertEqual(result['previews'], 0)
self.assertEqual(result['status'], 'complete')
+ def test_management_mode_keeps_collection_and_suppresses_automatic_previews(self):
+ from peach.media_processing_policy import save
+ save(self.config.directory('state'), True)
+ with patch('peach.library_processing._generate_previews', side_effect=AssertionError('不应抽帧')), \
+ patch('peach.library_processing._finish_collection', return_value={}) as finish:
+ result = self.run_processing(stage='collect', asset_ids=[1])
+ self.assertEqual(result['status'], 'complete')
+ self.assertEqual(result['previews'], 0)
+ finish.assert_called_once()
+ with self.assertRaisesRegex(ValueError, '视频预览生成已关闭'):
+ self.run_processing(stage='previews', asset_ids=[1])
+
def test_local_preview_is_available_when_online_collection_starts(self):
with self.database.write_transaction() as connection:
connection.execute("UPDATE asset SET code='ABW-358' WHERE id=1")
diff --git a/tests/test_strm.py b/tests/test_strm.py
new file mode 100644
index 000000000..f71d3cfdb
--- /dev/null
+++ b/tests/test_strm.py
@@ -0,0 +1,269 @@
+"""STRM 入库、按需播放与媒体读取模式的行为回归。"""
+import json
+import sqlite3
+import tempfile
+import threading
+import unittest
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from dataclasses import replace
+from pathlib import Path
+from contextlib import closing
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import httpx
+
+from peach import media_processing_policy as policy, strm
+from peach.api import create_app
+from peach.config import PeachSettings
+from peach.media_probe import probe_unmeasured
+from peach.scan import medium_of, scan_location
+from peach.strm_stream import StrmResources, rewrite_playlist
+from support.ledger import fresh_ledger
+from support.web import route_client
+
+
+class StrmTextTests(unittest.TestCase):
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name).resolve()
+ self.path = self.root / 'ABC-123.strm'
+
+ def test_signed_address_preserves_encoding_comments_and_bom(self):
+ url = 'http://127.0.0.1:5244/d/%E5%AA%92%E4%BD%93/a.mp4?sign=a%2Bb&x=2'
+ self.path.write_text('\ufeff# a comment\r\n\r\n' + url + '\r\n', encoding='utf-8')
+ self.assertEqual(strm.read_target(self.path), url)
+
+ def test_invalid_or_ambiguous_pointers_are_refused_without_the_target_in_the_error(self):
+ for text in ('', 'file:///private.mp4', 'C:\\private.mp4', 'plugin://addon/play',
+ 'https://user:[email protected]/a.mp4', 'https://example.com/a b.mp4',
+ 'https://one.test/a\nhttps://two.test/b', 'http://host:99999/a', 'x' * (strm.MAX_BYTES + 1)):
+ with self.subTest(text=text[:20]):
+ self.path.write_text(text, encoding='utf-8')
+ with self.assertRaises(ValueError) as caught:
+ strm.read_target(self.path)
+ self.assertNotIn('secret', str(caught.exception))
+
+ def test_strm_and_iso_are_catalogued_without_background_probe(self):
+ db = fresh_ledger(self.root)
+ with closing(sqlite3.connect(db)) as connection, connection:
+ for index, name in enumerate(('one.STRM', 'two.ISO', 'three.mp4'), 1):
+ self.assertEqual(medium_of(name), 'video')
+ connection.execute('INSERT INTO asset(id,location,path,name,medium) VALUES(?,?,?,?,?)',
+ (index, 'local', 'R:\\media\\' + name, name, 'video'))
+ measured = (10, 1280, 720, 'h264', 24, None, '速食', '横屏', '720P', 3)
+ with patch('peach.media_probe.measure', return_value=measured) as measure:
+ policy.save(self.root, True)
+ self.assertEqual(probe_unmeasured(db, 'ffprobe', 'local', 'R:\\media'), 1)
+ self.assertEqual(measure.call_args.args[1:3], (3, 'R:\\media\\three.mp4'))
+ with closing(sqlite3.connect(db)) as connection:
+ self.assertEqual(connection.execute('SELECT duration FROM asset WHERE id<3').fetchall(), [(None,), (None,)])
+
+ def test_preview_mode_survives_restart_and_can_be_disabled(self):
+ self.assertFalse(policy.metadata_only(self.root))
+ policy.save(self.root, True)
+ self.assertTrue(policy.metadata_only(self.root))
+ policy.save(self.root, False)
+ self.assertFalse(policy.metadata_only(self.root))
+ (self.root / policy.FILENAME).write_text('{', encoding='utf-8')
+ self.assertTrue(policy.metadata_only(self.root))
+
+ def test_scan_recognizes_pointers_and_disc_images_and_preserves_sidecars(self):
+ media = self.root / 'media'
+ media.mkdir()
+ (media / 'ABC-123.strm').write_text('https://example.com/movie.mp4', encoding='utf-8')
+ (media / 'ABC-124.iso').write_bytes(b'iso')
+ (media / 'ABC-123.nfo').write_text('<movie/>', encoding='utf-8')
+ (media / 'ABC-123-poster.jpg').write_bytes(b'poster')
+ db = fresh_ledger(self.root)
+ def scan():
+ return scan_location(db, 'local', 'R:\\media', declared_roots={'local': ('R:\\media',)},
+ mounts={'local': (str(media),)}, windows=False)
+ scan()
+ with closing(sqlite3.connect(db)) as connection, connection:
+ self.assertEqual(connection.execute('SELECT name,medium FROM asset ORDER BY name').fetchall(),
+ [('ABC-123.strm', 'video'), ('ABC-124.iso', 'video')])
+ connection.execute("UPDATE asset SET medium='other' WHERE name='ABC-123.strm'")
+ scan()
+ with closing(sqlite3.connect(db)) as connection:
+ self.assertEqual(connection.execute('SELECT COUNT(*) FROM asset').fetchone()[0], 2)
+ self.assertEqual(connection.execute("SELECT medium FROM asset WHERE name='ABC-123.strm'").fetchone()[0], 'video')
+
+ def test_hls_resource_map_is_bounded_and_bound_to_the_pointer(self):
+ resources = StrmResources(capacity=2)
+ root = 'https://example.com/master.m3u8'
+ first = resources.add(1, root, 'https://example.com/first.ts')
+ second = resources.add(1, root, 'https://example.com/second.ts')
+ resources.add(1, root, 'https://example.com/third.ts')
+ with self.assertRaises(ValueError):
+ resources.get(first, 1, root)
+ self.assertEqual(resources.get(second, 1, root), 'https://example.com/second.ts')
+ for asset_id, pointer in ((2, root), (1, 'https://example.com/other.m3u8')):
+ with self.assertRaises(ValueError):
+ resources.get(second, asset_id, pointer)
+
+
+class StrmPlaybackTests(unittest.TestCase):
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name).resolve()
+ self.path = self.root / 'ABC-123.strm'
+ self.path.write_text('http://127.0.0.1:5244/d/movie.mp4?sign=private', encoding='utf-8')
+ self.db = fresh_ledger(self.root)
+ with closing(sqlite3.connect(self.db)) as connection, connection:
+ connection.execute('INSERT INTO asset(id,location,path,name,medium,size) VALUES(1,?,?,?,?,?)',
+ ('local', str(self.path), self.path.name, 'video', self.path.stat().st_size))
+ self.app = create_app(PeachSettings(configured=True, db_path=self.db,
+ follow_state_root=self.root / 'state', allowed_media_roots=(self.root,)))
+ self.addCleanup(self.app.state.http_transport.close)
+ self.requests = []
+ self.upstream = httpx.Client(transport=httpx.MockTransport(self.serve))
+ self.addCleanup(self.upstream.close)
+ self.app.state.http_transport.client.close()
+ self.app.state.http_transport.client = self.upstream
+
+ def serve(self, request):
+ self.requests.append(request)
+ return httpx.Response(206, content=b'video', headers={
+ 'Content-Type': 'video/mp4', 'Content-Range': 'bytes 0-4/100', 'Accept-Ranges': 'bytes'})
+
+ def test_browsing_and_stream_plan_do_not_access_remote_video(self):
+ with route_client(self.app) as client:
+ result = client.get('/api/stream-plan?id=1').json()
+ item = client.get('/api/item?id=1').json()
+ self.assertEqual(result['reason'], 'strm-pointer')
+ self.assertNotIn('private', json.dumps(result))
+ self.assertIsNone(item['size'])
+ self.assertTrue(item['is_strm'])
+ self.assertEqual(self.requests, [])
+
+ def test_range_is_forwarded_without_browser_credentials_or_upstream_address(self):
+ self.upstream.cookies.set('service-secret', 'private', domain='127.0.0.1')
+ with route_client(self.app) as client:
+ response = client.get('/stream?id=1&session=test', headers={'Range': 'bytes=0-4', 'Cookie': 'private=cookie'})
+ self.assertEqual(response.status_code, 206)
+ self.assertEqual(response.content, b'video')
+ self.assertEqual(response.headers['content-range'], 'bytes 0-4/100')
+ self.assertEqual(self.requests[0].headers['range'], 'bytes=0-4')
+ self.assertNotIn('cookie', self.requests[0].headers)
+ self.assertNotIn('location', response.headers)
+
+ def test_real_http_range_flow_reads_only_the_requested_bytes(self):
+ seen = []
+ class Source(BaseHTTPRequestHandler):
+ def do_GET(self):
+ seen.append(self.headers.get('Range'))
+ self.send_response(206)
+ self.send_header('Content-Type', 'video/mp4')
+ self.send_header('Content-Length', '4')
+ self.send_header('Content-Range', 'bytes 4-7/100')
+ self.end_headers()
+ self.wfile.write(b'part')
+
+ def log_message(self, _format, *args):
+ pass
+ server = ThreadingHTTPServer(('127.0.0.1', 0), Source)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ self.path.write_text(f'http://127.0.0.1:{server.server_port}/movie.mp4', encoding='utf-8')
+ with httpx.Client(trust_env=False) as remote, route_client(self.app) as client:
+ self.app.state.http_transport.client = remote
+ result = client.get('/stream?id=1&session=real', headers={'Range': 'bytes=4-7'})
+ self.assertEqual((result.status_code, result.content), (206, b'part'))
+ self.assertEqual(seen, ['bytes=4-7'])
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+
+ def test_hls_external_ticket_authorizes_nested_resources_without_browser_cookie(self):
+ from peach.external_playback import issue
+ self.app.state.settings = replace(self.app.state.settings, token='password')
+ self.path.write_text('http://127.0.0.1:5244/movie.m3u8', encoding='utf-8')
+ def serve(request):
+ if request.url.path.endswith('.m3u8'):
+ return httpx.Response(200, text='#EXTM3U\n#EXTINF:6,\npart.ts\n#EXT-X-ENDLIST\n',
+ headers={'content-type': 'application/vnd.apple.mpegurl'})
+ return httpx.Response(200, content=b'part')
+ self.upstream._transport = httpx.MockTransport(serve)
+ origin = 'http://testserver'
+ ticket = issue(self.app.state.external_playback_key, 1, origin=origin)
+ with route_client(self.app) as client:
+ response = client.get('/external-stream/1', params={'ticket': ticket, 'origin': origin})
+ self.assertEqual(response.status_code, 200)
+ line = next(line for line in response.text.splitlines() if line.startswith('/strm-resource/'))
+ self.assertEqual(client.get(line).content, b'part')
+ self.assertEqual(client.get(line.split('?')[0]).status_code, 401)
+
+ def test_iso_catalogue_entry_streams_through_external_player_only(self):
+ iso = self.root / 'ABC-123.iso'
+ iso.write_bytes(b'iso')
+ with closing(sqlite3.connect(self.db)) as connection, connection:
+ connection.execute('UPDATE asset SET path=?,name=? WHERE id=1', (str(iso), iso.name))
+ with route_client(self.app) as client:
+ self.assertEqual(client.get('/api/stream-plan?id=1').status_code, 415)
+ self.assertEqual(client.get('/stream?id=1').status_code, 415)
+ self.assertEqual(self.requests, [])
+
+ def test_redirect_is_resolved_at_playback_and_signed_query_is_preserved(self):
+ def serve(request):
+ self.requests.append(request)
+ if request.url.path == '/d/movie.mp4':
+ return httpx.Response(302, headers={'Location': '/actual.mp4?sign=a%2Bb'})
+ return httpx.Response(200, content=b'ok')
+ self.upstream._transport = httpx.MockTransport(serve)
+ with route_client(self.app) as client:
+ self.assertEqual(client.get('/stream?id=1').content, b'ok')
+ self.assertEqual(str(self.requests[-1].url), 'http://127.0.0.1:5244/actual.mp4?sign=a%2Bb')
+
+ def test_hls_keeps_keys_maps_and_segments_behind_authenticated_local_urls(self):
+ self.path.write_text('http://127.0.0.1:5244/movie.m3u8', encoding='utf-8')
+ playlist = '#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXT-X-KEY:METHOD=AES-128,URI="key?sign=s"\n#EXT-X-MAP:URI="init.mp4"\n#EXTINF:6,\nsegment.ts?sign=s\n#EXT-X-ENDLIST\n'
+ def serve(request):
+ self.requests.append(request)
+ if request.url.path.endswith('.m3u8'):
+ return httpx.Response(200, text=playlist, headers={'content-type': 'application/vnd.apple.mpegurl'})
+ return httpx.Response(200, content=b'segment')
+ self.upstream._transport = httpx.MockTransport(serve)
+ with route_client(self.app) as client:
+ plan = client.get('/api/stream-plan?id=1').json()
+ self.assertEqual(plan['protocol'], 'hls')
+ result = client.get(plan['src'])
+ self.assertNotIn('sign=s', result.text)
+ self.assertNotIn('127.0.0.1', result.text)
+ line = next(line for line in result.text.splitlines() if line.startswith('/strm-resource/'))
+ self.assertEqual(client.get(line).content, b'segment')
+ self.assertEqual(client.get('/strm-resource/1/unknown').status_code, 400)
+
+ def test_cancelled_session_and_invalid_pointer_do_not_fetch(self):
+ self.app.state.stream_sessions.cancel('cancelled')
+ with route_client(self.app) as client:
+ self.assertEqual(client.get('/stream?id=1&session=cancelled').status_code, 410)
+ self.path.write_text('file:///secret', encoding='utf-8')
+ self.assertEqual(client.get('/stream?id=1').status_code, 400)
+ self.assertEqual(self.requests, [])
+
+ def test_policy_endpoint_stops_timeline_without_touching_ledger(self):
+ with route_client(self.app) as client:
+ response = client.post('/api/media-processing', json={'metadata_only': True})
+ self.assertEqual(response.status_code, 200)
+ self.assertTrue(client.get('/api/media-processing').json()['metadata_only'])
+ self.assertEqual(client.post('/api/thumbnail-jobs', json={'mode': 'precise'}).status_code, 400)
+ self.assertEqual(client.post('/api/media-processing', json={'metadata_only': 'yes'}).status_code, 400)
+ self.assertFalse(client.post('/api/media-processing', json={'metadata_only': False}).json()['metadata_only'])
+ self.assertEqual(json.loads((self.root / 'state' / 'timeline-thumbnails.json').read_text())['mode'], 'off')
+
+
+class StrmPlaylistTests(unittest.TestCase):
+ def test_master_playlist_rewrites_renditions_and_refuses_private_cross_origin(self):
+ state = SimpleNamespace(strm_resources=StrmResources())
+ root = 'http://127.0.0.1:5244/master.m3u8'
+ master = b'#EXTM3U\n#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="a",NAME="audio",URI="audio.m3u8"\n#EXT-X-STREAM-INF:BANDWIDTH=1000,AUDIO="a"\nvideo.m3u8\n'
+ result = rewrite_playlist(state, master, root, 1, root, '')
+ self.assertEqual(result.count('/strm-resource/'), 2)
+ with self.assertRaises(ValueError):
+ rewrite_playlist(state, b'#EXTM3U\n#EXTINF:1,\nhttp://127.0.0.1:9999/admin\n', root, 1, root, '')
+ self.assertLessEqual(len(state.strm_resources.entries), 4096)