Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat(metadata): 接入受限自定义来源与外部播放器

longmeidaof592d6fad090
diff --git a/docs/CUSTOM_SOURCES.md b/docs/CUSTOM_SOURCES.md
new file mode 100644
index 000000000..b61c1b310
--- /dev/null
+++ b/docs/CUSTOM_SOURCES.md
@@ -0,0 +1,56 @@
+# 自定义元数据来源
+
+采集页的「自定义元数据来源」用于接入公开 JSON 元数据接口。每个来源保存名称、固定 HTTPS
+接口地址、番号格式、字段路径、适用内容类型和连接方式。保存后可编辑、试查、启用、停用或删除。
+
+接口地址必须包含一个 `{code}`。字段路径用点连接对象键或数组下标,例如 `data.title`、
+`items.0.title`。番号字段必填;标题、厂牌、系列、发行日期是文本,演员和标签是文本数组。
+番号格式可选原样、小写、去掉连字符或转为下划线。试查番号输入后按回车,结果显示在当前表单。
+
+这套配置只适用于单次 GET 返回的 JSON,不解析 HTML、CSS selector、JSON-LD、YAML 规则,
+也不执行脚本。需要 Cookie、站点 API key、多次查询或浏览器验证的来源使用已有专用适配器。
+
+## 接口示例
+
+一本道公开接口的配置:
+
+| 字段 | 值 |
+| --- | --- |
+| 接口地址 | `https://www.1pondo.tv/dyn/phpauto/movie_details/movie_id/{code}.json` |
+| 番号格式 | 连字符转下划线 |
+| 番号字段 | `MovieID` |
+| 标题字段 | `Title` |
+| 演员字段 | `ActressesJa` |
+| 适用类型 | 无码 |
+
+Peach 已内置一本道适配器,此例用于说明接口配置,不需要重复添加。自定义来源的适用内容类型
+由用户选择;对于发行体系同形的番号,需要选择确实覆盖目标作品的接口。
+
+## 采集与复核
+
+启用的来源追加到适用类型的内建来源链末尾,前面的来源资料足够时按既有规则停止查询。
+响应中的番号字段必须与查询番号匹配,查询 URL 不能代替响应提供身份证据。
+
+结果进入现有来源快照、候选及复核流程,置信度为 `0.5`,归为未登记来源,不参与自动批准。
+来源端点、字段映射、番号格式或线路变化时,新的查询规则有独立证据键;启停或改名称保持证据键。
+删除配置不删除已保存的来源快照或复核产物。
+
+## 网络与存储
+
+接口使用 HTTPS 公网域名、默认 443 端口,拒绝用户信息、片段、私网解析结果和重定向。
+请求最多 15 秒、响应最多 1 MiB。直连或 Peach 代理都通过 cURL `CONNECT_TO` 固定已验证的
+公共 IP,TLS 的 SNI 和证书验证仍使用接口原域名。Peach 代理沿用已保存的连接设置,不另存凭据。
+
+配置位于本机 `secrets/custom-metadata.json`,通过文件锁和原子替换保存;不写 ledger。
+
+## 复用与取证
+
+- 参考 OpenAver `502278a3e09c7520838ffb00b2ff080323a4cdcb` 的声明式配置、公网目标检查和
+ 番号身份核对。上游支持 YAML、CSS/meta/JSON-LD 及一至两步页面抓取;Peach 主动收窄为单步 JSON。
+ 未复制上游实现。
+- 使用项目固定版本 `curl_cffi 0.16.3`、`filelock 4.0.12`,以及既有 `SiteRecord`、
+ `identifies_code`、来源链与复核流程,无新增依赖。cURL 的连接边界见
+ [CONNECT_TO 官方说明](https://curl.se/libcurl/c/CURLOPT_CONNECT_TO.html)。
+- 2026-10-13 无写入 POC:正式适配器经 Peach 代理、固定公共 IP、严格 TLS 查询
+ `112312_478`,返回番号匹配、标题非空、演员 1 人、置信度 `0.5`。直连 r18.dev 与一本道时
+ 返回 `curl (35) Recv failure: Connection was reset`;未降低 TLS 校验。
diff --git a/docs/EXTERNAL_PLAYERS.md b/docs/EXTERNAL_PLAYERS.md
new file mode 100644
index 000000000..64c5b68aa
--- /dev/null
+++ b/docs/EXTERNAL_PLAYERS.md
@@ -0,0 +1,27 @@
+# 外部播放器与 VR
+
+本地或已挂载视频的作品详情提供「外部播放器 / VR」。选择此设备的播放器后,点击「生成播放链接」,
+再打开播放器或下载 M3U 播放列表。VR 播放器可使用生成的网络播放地址。
+
+| 选项 | 使用方式 |
+| --- | --- |
+| M3U 播放列表 | 用支持网络地址的外部播放器打开下载的 `.m3u` |
+| VLC(iPhone / iPad) | 调用 VLC 的 `vlc-x-callback` 协议 |
+| IINA(Mac) | 调用 IINA 的 `iina://weblink` 协议 |
+
+播放器选择只保存在当前浏览器。另一台设备需要能访问当前 Peach 地址;电脑上用 `localhost`
+生成的地址不能供手机访问。HTTPS 使用项目证书时,外部设备也需要信任该证书。
+
+播放链接有效期为 6 小时,Peach 重启后失效。链接只允许读取选中的资产,不包含本机盘符路径或
+长期登录凭据。请求支持 HTTP Range,传输原始文件;解码能力、VR 投影方式由外部播放器决定。
+生成链接和打开播放器不计作观看记录,也不能证明播放器已经起播。
+
+## 协议与验证
+
+签发接口 `POST /api/external-playback?id=…` 使用现有登录及同源检查。流和 M3U 端点验证
+进程内密钥签发的单资产限时票据,每次读取仍经过现有媒体根目录检查。
+
+VLC 协议参考 [VideoLAN 官方实现说明](https://mailman.videolan.org/pipermail/vlc-devel/2014-October/099830.html),
+IINA 协议参考 [IINA 上游协议讨论](https://github.com/iina/iina/issues/3922)。播放器实现不进入 Peach,
+无新增依赖。协议打开后的实际播放取决于访问端是否安装对应播放器;自动化验证覆盖票据、Range、
+M3U 内容和页面交互,不替代真实设备的解码验收。
diff --git a/frontend/e2e/external-playback.test.ts b/frontend/e2e/external-playback.test.ts
new file mode 100644
index 000000000..cd5178758
--- /dev/null
+++ b/frontend/e2e/external-playback.test.ts
@@ -0,0 +1,32 @@
+import assert from 'node:assert/strict';
+import { after, before, describe, it } from 'node:test';
+import type { Browser } from 'playwright-core';
+import { launch, layout, VIEWPORTS } from './harness.ts';
+import { ITEM, openItemPage } from './item-fixture.ts';
+
+describe('外部播放器', () => {
+ let browser: Browser;
+ before(async () => { browser = await launch() });
+ after(async () => { await browser.close() });
+ for (const viewport of [VIEWPORTS.find((one) => !one.mobile)!, VIEWPORTS.find((one) => one.mobile)!]) {
+ it(`${viewport.mobile ? '手机' : '桌面'}按需生成可复制的网络地址`, { timeout: 60_000 }, async () => {
+ const opened = await openItemPage(browser, `/item/${ITEM.plain}`, viewport, { ready: '#stage[open] [data-item-side]' });
+ try {
+ const page = opened.page;
+ let requested = 0;
+ await page.route('**/api/external-playback?*', route => {
+ requested++;
+ return route.fulfill({ json: { url: `/external-stream/${ITEM.plain}?ticket=${'a'.repeat(90)}`,
+ playlist: `/external-playlist/${ITEM.plain}.m3u?ticket=${'a'.repeat(90)}` } });
+ });
+ await page.getByText('外部播放器 / VR', { exact: true }).click();
+ assert.equal(requested, 0);
+ await page.getByRole('button', { name: '生成播放链接', exact: true }).click();
+ await page.getByRole('link', { name: '下载 M3U 播放列表' }).waitFor();
+ assert.equal(requested, 1);
+ assert.match(await page.getByRole('textbox', { name: '网络播放地址' }).inputValue(), /\/external-stream\/11\?ticket=/);
+ assert.deepEqual((await layout(page)).offenders, []);
+ } finally { await opened.close() }
+ });
+ }
+});
diff --git a/frontend/src/react/item-detail/external-playback.tsx b/frontend/src/react/item-detail/external-playback.tsx
new file mode 100644
index 000000000..034e9dca0
--- /dev/null
+++ b/frontend/src/react/item-detail/external-playback.tsx
@@ -0,0 +1,48 @@
+import { useState } from 'react';
+import { Button } from '@/components/base/buttons/button';
+import { Input } from '@/components/base/input/input';
+import { apiSend } from '../../api';
+import { SelectField } from '../settings-panel/legacy-controls';
+import { ErrorText, Help, Stack } from '../settings/section';
+import { busyProps, useAction } from '../settings/use-action';
+
+const KEY = 'peach.external-player.v1';
+const PLAYERS = [['m3u', 'M3U 播放列表'], ['vlc-ios', 'VLC(iPhone / iPad)'], ['iina', 'IINA(Mac)']] as const;
+
+export function playerLink(player: string, url: string, playlist: string): string {
+ if (player === 'vlc-ios') return `vlc-x-callback://x-callback-url/stream?url=${encodeURIComponent(url)}`;
+ if (player === 'iina') return `iina://weblink?url=${encodeURIComponent(url)}`;
+ return playlist;
+}
+
+export function ExternalPlayback({ id }: { id: number }) {
+ const [player, setPlayer] = useState(() => {
+ try { return PLAYERS.find(([key]) => key === localStorage.getItem(KEY))?.[0] || 'm3u' } catch { return 'm3u' }
+ });
+ const [links, setLinks] = useState<{ url: string; playlist: string } | null>(null);
+ const action = useAction();
+ return <details key={id}>
+ <summary>外部播放器 / VR</summary>
+ <Stack>
+ <SelectField id={`external-player-${id}`} label="此设备的外部播放器" options={PLAYERS} value={player}
+ epoch={0} onPick={(value) => {
+ const selected = PLAYERS.find(([key]) => key === value)?.[0] || 'm3u';
+ setPlayer(selected);
+ try { localStorage.setItem(KEY, selected) } catch { /* 浏览器未允许保存偏好。 */ }
+ }} />
+ <Button variant="secondary" {...busyProps(action.busy === 'prepare')}
+ onClick={() => void action.run('prepare', (signal) => apiSend<{ url: string; playlist: string }>(
+ `/api/external-playback?id=${id}`, {}, 'POST', signal), (result) => setLinks({
+ url: new URL(result.url, location.origin).href, playlist: new URL(result.playlist, location.origin).href,
+ }))}>生成播放链接</Button>
+ {action.error ? <ErrorText>{action.error}</ErrorText> : null}
+ {links ? <>
+ <a href={playerLink(player, links.url, links.playlist)} rel="noreferrer">
+ {player === 'm3u' ? '下载 M3U 播放列表' : `打开 ${PLAYERS.find(([key]) => key === player)?.[1]}`}
+ </a>
+ <Input label="网络播放地址" value={links.url} isReadOnly />
+ <Help>链接有效期为 6 小时。VR 播放器可使用网络播放地址;另一台设备需要能访问当前 Peach 地址。</Help>
+ </> : null}
+ </Stack>
+ </details>;
+}
diff --git a/frontend/src/react/item-detail/item-detail-page.tsx b/frontend/src/react/item-detail/item-detail-page.tsx
index 88346c1ac..529f5022b 100644
--- a/frontend/src/react/item-detail/item-detail-page.tsx
+++ b/frontend/src/react/item-detail/item-detail-page.tsx
@@ -29,6 +29,7 @@ import { IdentityCell, IdentitySeries } from '../components/identity-cell';
import { useFoldedTitle } from '../components/folded-title';
import { MediaCarousel, useCarouselInset } from '../components/media-carousel';
import { CatalogPicture } from './catalog-picture';
+import { ExternalPlayback } from './external-playback';
import { CoverCrop } from '../cover-crop/cover-crop-page';
import { queryClient } from '../query';
import {
@@ -367,6 +368,7 @@ function Side({ item, queue, write, helpers, actions }: {
<Identity item={item} helpers={helpers} actions={actions} />
<Tags item={item} write={write} helpers={helpers} actions={actions} />
<Trace item={item} />
+ {item.medium === 'video' && item.location !== 'online' ? <ExternalPlayback key={item.id} id={item.id} /> : null}
<div data-stage-actions="" data-item-feedback="">
<button type="button" id="likeBtn" data-fb="like" aria-label={item.liked ? '取消喜欢' : '喜欢'} title="喜欢 · 记录口味偏好"
aria-pressed={!!item.liked} {...busy('like')} onClick={() => write.preference({ liked: !item.liked })}><Glyph name="thumbs-up" /></button>
diff --git a/frontend/src/react/scraping/custom-sources.tsx b/frontend/src/react/scraping/custom-sources.tsx
new file mode 100644
index 000000000..ece9f247e
--- /dev/null
+++ b/frontend/src/react/scraping/custom-sources.tsx
@@ -0,0 +1,94 @@
+import { useState } from 'react';
+import { useQuery } from '@tanstack/react-query';
+import { Button } from '@/components/base/buttons/button';
+import { Checkbox } from '@/components/base/checkbox/checkbox';
+import { Input } from '@/components/base/input/input';
+import { confirmModal, spinnerHtml } from '@peach/legacy/ui';
+import { esc } from '@peach/legacy/core';
+import { apiGet, apiSend, errorMessage } from '../../api';
+import { queryClient } from '../query';
+import { ErrorText, Footer, Help, Section, Stack } from '../settings/section';
+import { busyProps, useAction } from '../settings/use-action';
+import { SelectField } from '../settings-panel/legacy-controls';
+
+const URL = '/api/custom-metadata';
+const KEY = ['custom-metadata'] as const;
+const FIELDS = [['code', '番号'], ['title', '标题'], ['studio', '厂牌'], ['series', '系列'],
+ ['release_date', '发行日期'], ['performers', '演员(文本数组)'], ['tags', '标签(文本数组)']] as const;
+const TYPES = [['censored', '有码'], ['amateur', '素人'], ['uncensored', '无码'], ['fc2', 'FC2'],
+ ['kmib', '韩国 MIB'], ['other', '其他'], ['unsure', '待核番号'], ['unknown', '未知']] as const;
+interface Source { id?: string; name: string; endpoint: string; enabled: boolean; network?: string; code_format?: string; fields: Record<string, string>; content_types: string[] }
+const blank = (): Source => ({ name: '', endpoint: '', enabled: false, fields: { code: 'id', title: 'title' }, content_types: ['censored'] });
+
+export function CustomSources({ receipt }: { receipt(message: string): void }) {
+ const [editing, setEditing] = useState<Source | null>(null);
+ const query = useQuery({ queryKey: KEY, queryFn: ({ signal }) => apiGet<{ items: Source[] }>(URL, signal) });
+ const action = useAction();
+ const changed = (result: { items: Source[] }) => queryClient.setQueryData(KEY, result);
+ return <Section title="自定义元数据来源">
+ <Stack>
+ {query.isPending ? <div aria-busy="true" data-skeleton="" aria-label="读取自定义来源" /> : null}
+ {query.error ? <ErrorText>{errorMessage(query.error)}</ErrorText> : null}
+ {query.data?.items.map((source) => <div key={source.id} className="flex flex-wrap items-center gap-3">
+ <span className="min-w-0 flex-1">{source.name} · {source.enabled ? '已启用' : '已停用'}</span>
+ <Button variant="secondary" onClick={() => setEditing(source)}>编辑</Button>
+ <Button variant="secondary" {...busyProps(action.busy === source.id)} onClick={() => void action.run(source.id!,
+ (signal) => apiSend<{ items: Source[] }>(URL, { ...source, enabled: !source.enabled }, 'POST', signal),
+ (result) => { changed(result); receipt(source.enabled ? '已停用来源' : '已启用来源') })}>
+ {source.enabled ? '停用' : '启用'}</Button>
+ <Button variant="danger" onClick={() => confirmModal({ title: '删除自定义来源',
+ body: `删除「${esc(source.name)}」后,采集将不再查询这个来源。`, confirmLabel: '删除来源',
+ onConfirm: async () => { changed(await apiSend<{ items: Source[] }>(URL, { action: 'delete', id: source.id }));
+ setEditing(null); receipt('已删除来源') } })}>删除</Button>
+ </div>)}
+ {action.error ? <ErrorText>{action.error}</ErrorText> : null}
+ {!editing ? <Button variant="secondary" onClick={() => setEditing(blank())}>添加来源</Button> : null}
+ {editing ? <SourceForm key={editing.id || 'new'} initial={editing} cancel={() => setEditing(null)}
+ saved={(result) => { changed(result); setEditing(null); receipt('已保存来源') }} /> : null}
+ </Stack>
+ </Section>;
+}
+
+function SourceForm({ initial, cancel, saved }: {
+ initial: Source; cancel(): void; saved(result: { items: Source[] }): void;
+}) {
+ const [source, setSource] = useState(initial);
+ const [code, setCode] = useState('');
+ const [preview, setPreview] = useState<string>('');
+ const action = useAction();
+ const change = (patch: Partial<Source>) => { setSource((current) => ({ ...current, ...patch })); setPreview('') };
+ return <form aria-label="元数据来源配置" aria-busy={action.busy === 'preview'} onSubmit={(event) => {
+ event.preventDefault();
+ void action.run('save', (signal) => apiSend<{ items: Source[] }>(URL, source, 'POST', signal), saved);
+ }}>
+ <Stack>
+ <Input label="来源名称" value={source.name} maxLength={80} onChange={(name) => change({ name })} />
+ <Input label="JSON 接口地址" value={source.endpoint} maxLength={2048}
+ placeholder="https://example.com/api/movies/{code}" onChange={(endpoint) => change({ endpoint })} />
+ <SelectField id="custom-source-network" label="来源连接方式" epoch={0} value={source.network || 'direct'}
+ options={[["direct", "直连"], ["peach_proxy", "Peach 代理"]]} onPick={(network) => change({ network })} />
+ <SelectField id="custom-source-code-format" label="接口番号格式" epoch={0} value={source.code_format || 'original'}
+ options={[["original", "原样"], ["lowercase", "小写"], ["compact", "去掉连字符"], ["underscore", "连字符转下划线"]]}
+ onPick={(code_format) => change({ code_format })} />
+ <Help>填写公开 JSON 接口和响应字段路径,例如 data.title。番号字段用于核对作品身份。</Help>
+ {FIELDS.map(([field, label]) => <Input key={field} label={`${label}字段路径`} value={source.fields[field] || ''}
+ onChange={(path) => { const fields = { ...source.fields }; if (path) fields[field] = path; else delete fields[field]; change({ fields }) }} />)}
+ <div className="flex flex-wrap gap-3" role="group" aria-label="适用内容类型">
+ {TYPES.map(([type, label]) => <Checkbox key={type} isSelected={source.content_types.includes(type)}
+ onChange={(checked) => change({ content_types: checked ? [...source.content_types, type] : source.content_types.filter((kind) => kind !== type) })}>{label}</Checkbox>)}
+ </div>
+ <Checkbox isSelected={source.enabled} onChange={(enabled) => change({ enabled })}>启用来源</Checkbox>
+ <Input label="试查番号(回车查询)" value={code} onChange={setCode} onKeyDown={(event) => {
+ if (event.key !== 'Enter' || event.nativeEvent.isComposing) return;
+ event.preventDefault();
+ void action.run('preview', (signal) => apiSend<{ record: unknown }>(URL,
+ { ...source, code, action: 'preview' }, 'POST', signal), (result) => setPreview(JSON.stringify(result.record, null, 2)));
+ }} />
+ {action.busy === 'preview' ? <Help role="status"><span dangerouslySetInnerHTML={{ __html: spinnerHtml('正在试查来源') }} />正在试查来源…</Help> : null}
+ {preview ? <pre className="whitespace-pre-wrap break-all">{preview}</pre> : null}
+ {action.error ? <ErrorText>{action.error}</ErrorText> : null}
+ </Stack>
+ <Footer><Button variant="secondary" type="button" onClick={cancel}>取消</Button>
+ <Button type="submit" {...busyProps(action.busy === 'save')}>保存来源</Button></Footer>
+ </form>;
+}
diff --git a/frontend/test/react/custom-sources.test.tsx b/frontend/test/react/custom-sources.test.tsx
new file mode 100644
index 000000000..99ff258ea
--- /dev/null
+++ b/frontend/test/react/custom-sources.test.tsx
@@ -0,0 +1,26 @@
+import { notifyManager, QueryClientProvider } from '@tanstack/react-query';
+import { afterEach, expect, it, vi } from 'vitest';
+import { queryClient } from '../../src/react/query';
+import { CustomSources } from '../../src/react/scraping/custom-sources';
+import { click, mount, settle } from './render';
+
+notifyManager.setScheduler(notify => notify());
+afterEach(() => queryClient.clear());
+
+it('来源停用由服务端结果确认,保留配置以便再次启用', async () => {
+ const row = { id: 'custom-1234567890abcdef', name: '示例来源', endpoint: 'https://example.com/{code}',
+ fields: { code: 'id' }, content_types: ['censored'], enabled: true };
+ const fetcher = vi.fn(async (_url, options) => ({ ok: true, status: 200,
+ json: async () => ({ items: [{ ...row, enabled: options?.method === 'POST' ? false : true }] }) }));
+ vi.stubGlobal('fetch', fetcher);
+ const receipt = vi.fn();
+ const host = await mount(<QueryClientProvider client={queryClient}><CustomSources receipt={receipt} /></QueryClientProvider>);
+ await settle();
+ const disable = Array.from(host.querySelectorAll('button')).find(button => button.textContent === '停用');
+ await click(disable!);
+ await settle();
+ expect(receipt).toHaveBeenCalledWith('已停用来源');
+ expect(host.textContent).toContain('已停用');
+ const sent = JSON.parse(fetcher.mock.calls.find(([, options]) => options?.method === 'POST')?.[1].body);
+ expect(sent).toMatchObject({ id: row.id, enabled: false, fields: { code: 'id' } });
+});
diff --git a/frontend/test/react/external-playback.test.tsx b/frontend/test/react/external-playback.test.tsx
new file mode 100644
index 000000000..f4cdb0b56
--- /dev/null
+++ b/frontend/test/react/external-playback.test.tsx
@@ -0,0 +1,24 @@
+import { expect, it, vi } from 'vitest';
+import { ExternalPlayback, playerLink } from '../../src/react/item-detail/external-playback';
+import { click, mount, settle } from './render';
+
+it('外部播放器只在用户请求后签发链接,并保留网络地址供 VR 播放器使用', async () => {
+ const fetcher = vi.fn(async () => ({ ok: true, json: async () => ({
+ url: '/external-stream/1?ticket=short', playlist: '/external-playlist/1.m3u?ticket=short',
+ }) }));
+ vi.stubGlobal('fetch', fetcher);
+ const host = await mount(<ExternalPlayback id={1} />);
+ expect(fetcher).not.toHaveBeenCalled();
+ await click(Array.from(host.querySelectorAll('button')).find(button => button.textContent === '生成播放链接')!);
+ await settle();
+ expect(fetcher.mock.calls).toHaveLength(1);
+ expect(host.querySelector('a')?.getAttribute('href')).toContain('/external-playlist/1.m3u?ticket=short');
+ expect(host.querySelector('input')?.value).toContain('/external-stream/1?ticket=short');
+});
+
+it('专属协议只编码服务端播放地址', () => {
+ const url = 'https://peach.example/external-stream/1?ticket=a.b';
+ expect(playerLink('vlc-ios', url, '/list')).toBe(`vlc-x-callback://x-callback-url/stream?url=${encodeURIComponent(url)}`);
+ expect(playerLink('iina', url, '/list')).toBe(`iina://weblink?url=${encodeURIComponent(url)}`);
+ expect(playerLink('unknown', url, '/list')).toBe('/list');
+});
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 8e8888ee6..b0ba81dc6 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -59,7 +59,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_web_review.py", "test_web_settings.py"),
# 任务中心的两个文件跟着 `test_jobs.py` 走:`jobs.py` 与 `task_runs.py` 是同一条
# 接线的两端,改哪一端都要两边一起验。
- "media": ("test_runtime_consistency.py", "test_endcard.py", "test_fastapi_api.py", "test_jobs.py",
+ "media": ("test_external_playback.py", "test_runtime_consistency.py", "test_endcard.py", "test_fastapi_api.py", "test_jobs.py",
"test_task_runs.py", "test_followups.py", "test_task_center_integration.py",
"test_frame_capture.py", "test_timeline_sheets.py",
"test_web_timeline_thumbnails.py",
@@ -71,7 +71,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"sync": ("test_sync*.py", "test_platform.py", "test_mount.py", "test_tray*.py", "test_log_retention.py",
"test_mdns.py", "test_netwatch.py", "test_certs.py",
"test_review_mirror.py", "test_runtime_prepare.py"),
- "metadata": ("test_scraping_access.py", "test_browser_transport.py", "test_metadata*.py", "test_genre_taxonomy.py",
+ "metadata": ("test_custom_metadata.py", "test_scraping_access.py", "test_browser_transport.py", "test_metadata*.py", "test_genre_taxonomy.py",
"test_fc2*.py",
"test_community_catalog.py",
"test_babepedia_match.py",
diff --git a/src/peach/api.py b/src/peach/api.py
index cac4125d0..8f2177b56 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -391,6 +391,8 @@ def create_app(
app.state.downloads = downloads
app.state.mount_reachability = mount_reachability
app.state.stream_sessions = StreamSessionRegistry()
+ import secrets
+ app.state.external_playback_key = secrets.token_bytes(32)
app.state.sync = sync
app.state.tunnel = tunnel_manager
diff --git a/src/peach/custom_metadata.py b/src/peach/custom_metadata.py
new file mode 100644
index 000000000..46a3847ac
--- /dev/null
+++ b/src/peach/custom_metadata.py
@@ -0,0 +1,201 @@
+"""受限 JSON 来源:固定 HTTPS 端点、字段映射及候选身份核对。"""
+from __future__ import annotations
+
+import ipaddress
+import hashlib
+import json
+import re
+import secrets
+import time
+from pathlib import Path
+from urllib.parse import quote, urlsplit
+
+from curl_cffi import CurlOpt, ffi, lib, requests
+from filelock import FileLock
+
+from .fsutil import atomic_write_text
+from .http import host_addresses, public_https_url
+from .metadata import identifies_code, validate_provider_code
+from .metadata_routes import CONTENT_TYPES
+from .sources.base import SiteRecord
+
+FIELDS = ('code', 'title', 'studio', 'series', 'release_date', 'performers', 'tags')
+MAX_BYTES = 1024 * 1024
+MAX_SOURCES = 12
+_PATH = re.compile(r'[A-Za-z_][A-Za-z_0-9]*(?:\.[A-Za-z_][A-Za-z_0-9]*|\.\d+){0,7}')
+_ID = re.compile(r'custom-[a-f0-9]{16}')
+
+
+def validate(raw: dict) -> dict:
+ if not isinstance(raw, dict):
+ raise ValueError('来源配置必须是对象')
+ name = str(raw.get('name', '')).strip()
+ endpoint = str(raw.get('endpoint', '')).strip()
+ if not name or len(name) > 80:
+ raise ValueError('来源名称需要 1–80 个字符')
+ if endpoint.count('{code}') != 1 or '{' in endpoint.replace('{code}', '') or '}' in endpoint.replace('{code}', ''):
+ raise ValueError('接口地址需要包含一个 {code}')
+ parsed = urlsplit(endpoint.replace('{code}', 'ABW-001'))
+ if (not public_https_url(endpoint.replace('{code}', 'ABW-001')) or parsed.port not in (None, 443)
+ or not re.fullmatch(r'[a-z0-9-]+(?:\.[a-z0-9-]+)+', parsed.hostname or '')
+ or parsed.fragment or '{code}' in endpoint.split('://', 1)[-1].split('/', 1)[0]
+ or len(endpoint) > 2048 or any(ord(c) < 33 for c in endpoint)):
+ raise ValueError('接口需要使用固定公网域名的 HTTPS 地址,端口为 443')
+ mapping = raw.get('fields')
+ if not isinstance(mapping, dict) or not mapping.get('code'):
+ raise ValueError('请填写响应中番号字段的路径')
+ if set(mapping) - set(FIELDS) or any(not isinstance(v, str) or not _PATH.fullmatch(v) for v in mapping.values()):
+ raise ValueError('字段映射只接受对象键或数组下标组成的点路径')
+ kinds = raw.get('content_types', [])
+ if not isinstance(kinds, list) or not kinds or any(kind not in CONTENT_TYPES for kind in kinds):
+ raise ValueError('至少选择一种有效内容类型')
+ if not isinstance(raw.get('enabled', False), bool):
+ raise ValueError('启用状态必须为布尔值')
+ network = raw.get('network', 'direct')
+ if network not in ('direct', 'peach_proxy'):
+ raise ValueError('请选择直连或 Peach 代理')
+ code_format = raw.get('code_format', 'original')
+ if code_format not in ('original', 'lowercase', 'compact', 'underscore'):
+ raise ValueError('番号格式无效')
+ return dict(name=name, endpoint=endpoint, fields=dict(mapping),
+ content_types=list(dict.fromkeys(kinds)), enabled=raw.get('enabled', False), network=network,
+ code_format=code_format)
+
+
+def endpoint(config: dict, code: str) -> str:
+ shape = config.get('code_format', 'original')
+ value = code.lower() if shape == 'lowercase' else code.replace('-', '') if shape == 'compact' else (
+ code.replace('-', '_') if shape == 'underscore' else code)
+ return config['endpoint'].replace('{code}', quote(value, safe=''))
+
+
+def source_key(config: dict) -> str:
+ """查询规则的指纹隔离候选、成功缓存和缺失记忆。"""
+ fields = {key: config.get(key) for key in ('endpoint', 'fields', 'code_format', 'network')}
+ version = hashlib.sha256(json.dumps(fields, sort_keys=True).encode()).hexdigest()[:12]
+ return f"{config['id']}-{version}"
+
+
+def load(root: Path) -> list[dict]:
+ path = Path(root) / 'custom-metadata.json'
+ if not path.exists():
+ return []
+ rows = json.loads(path.read_text(encoding='utf-8'))
+ if not isinstance(rows, list) or len(rows) > MAX_SOURCES:
+ raise ValueError('自定义来源配置无效')
+ return [dict(validate(row), id=row['id']) for row in rows if _ID.fullmatch(str(row.get('id', '')))]
+
+
+def save(root: Path, body: dict) -> list[dict]:
+ root = Path(root)
+ root.mkdir(parents=True, exist_ok=True)
+ with FileLock(str(root / 'custom-metadata.lock')):
+ rows = load(root)
+ identity = str(body.get('id', ''))
+ if identity and not any(row['id'] == identity for row in rows):
+ raise ValueError('来源不存在,请刷新')
+ if body.get('action') == 'delete':
+ if not identity:
+ raise ValueError('请选择来源')
+ rows = [row for row in rows if row['id'] != identity]
+ else:
+ incoming = dict(validate(body), id=identity or 'custom-' + secrets.token_hex(8))
+ rows = [incoming if row['id'] == identity else row for row in rows]
+ if not identity:
+ rows.append(incoming)
+ if len(rows) > MAX_SOURCES:
+ raise ValueError(f'最多保存 {MAX_SOURCES} 个来源')
+ atomic_write_text(root / 'custom-metadata.json', json.dumps(rows, ensure_ascii=False))
+ return rows
+
+
+def _value(document, path):
+ for key in path.split('.'):
+ if isinstance(document, dict):
+ document = document.get(key)
+ elif isinstance(document, list) and key.isdecimal() and int(key) < len(document):
+ document = document[int(key)]
+ else:
+ return None
+ return document
+
+
+def parse(config: dict, code: str, document: object) -> SiteRecord:
+ config = dict(validate(config), id=config.get('id', 'custom-preview'))
+ values = {field: _value(document, path) for field, path in config['fields'].items()}
+ def text(field):
+ value = values.get(field)
+ if value is None:
+ return ''
+ if not isinstance(value, (str, int, float)) or isinstance(value, bool) or len(str(value)) > 4096:
+ raise ValueError(f'{field} 字段需要文本或数值')
+ return str(value).strip()
+ def strings(field):
+ value = values.get(field)
+ if value is None:
+ return ()
+ if not isinstance(value, list) or len(value) > 100 or any(not isinstance(v, str) or len(v) > 256 for v in value):
+ raise ValueError(f'{field} 字段需要文本数组')
+ return tuple(dict.fromkeys(v.strip() for v in value if v.strip()))
+ returned_code = text('code')
+ # 身份只核对响应字段,查询 URL 不能替来源证明自己答对了。
+ if not returned_code or not identifies_code(code, {'id': returned_code}):
+ raise ValueError('来源返回的番号与查询番号不一致')
+ return SiteRecord(source=config['id'], provenance='custom-json', code=returned_code,
+ source_url=endpoint(config, code),
+ title=text('title'), studio=text('studio'), series=text('series'),
+ release_date=text('release_date'),
+ performers=tuple({'japanese_name': name} for name in strings('performers')),
+ tags=strings('tags') if 'tags' in values else None, confidence=0.5)
+
+
+def fetch_json(url: str, timeout: float, *, client_options=None):
+ host = urlsplit(url).hostname or ''
+ addresses = host_addresses(host)
+ if not addresses or any(not ipaddress.ip_address(ip).is_global for ip in addresses):
+ raise ValueError('来源域名必须解析到公网地址')
+ address = addresses[0]
+ if ':' in address:
+ address = f'[{address}]'
+ # CONNECT_TO 固定已验证地址,HTTP 代理也只 CONNECT 到该公网 IP,TLS 仍校验原域名。
+ options = dict(client_options or {'trust_env': False})
+ # curl_cffi 0.16.3 的 CONNECT_TO 接收原生 slist;Session 关闭后才释放。
+ target = ffi.gc(lib.curl_slist_append(ffi.NULL, f'{host}:443:{address}:443'.encode()), lib.curl_slist_free_all)
+ curl_options = {CurlOpt.CONNECT_TO: target}
+ if not options.get('proxy') and not options.get('trust_env'):
+ curl_options[CurlOpt.NOPROXY] = '*'
+ with requests.Session(curl_options=curl_options, **options) as client:
+ try:
+ with client.stream('GET', url, timeout=timeout, allow_redirects=False,
+ headers={'Accept': 'application/json'}) as response:
+ if response.status_code != 200:
+ raise ValueError(f'来源响应 HTTP {response.status_code}')
+ chunks, total = [], 0
+ for chunk in response.iter_content():
+ total += len(chunk)
+ if total > MAX_BYTES:
+ raise ValueError('来源响应超过 1 MiB')
+ chunks.append(chunk)
+ return json.loads(b''.join(chunks))
+ except requests.exceptions.RequestException as error:
+ raise ValueError('来源连接失败') from error
+
+
+def query(config: dict, code: str, *, deadline=None, secrets_root=None) -> SiteRecord:
+ checked = validate(config)
+ code = validate_provider_code(code)
+ timeout = min(15.0, deadline - time.monotonic()) if deadline else 15.0
+ if timeout <= 0:
+ raise ValueError('来源查询已超时')
+ url = endpoint(checked, code)
+ options = None
+ if checked['network'] == 'peach_proxy':
+ if secrets_root is None:
+ raise ValueError('Peach 代理配置未取得')
+ from .peach_proxy import client_options
+ options = client_options(Path(secrets_root))
+ try:
+ document = fetch_json(url, timeout, client_options=options)
+ except (json.JSONDecodeError, UnicodeError) as error:
+ raise ValueError('来源响应不是有效 JSON') from error
+ return parse(config, code, document)
diff --git a/src/peach/external_playback.py b/src/peach/external_playback.py
new file mode 100644
index 000000000..c8d767073
--- /dev/null
+++ b/src/peach/external_playback.py
@@ -0,0 +1,27 @@
+"""单资产、限时的外部播放器访问票据。签名密钥只存在于服务进程内。"""
+from __future__ import annotations
+
+import hashlib
+import hmac
+import time
+
+TTL_SECONDS = 6 * 60 * 60
+
+
+def issue(key: bytes, asset_id: int, *, now: float | None = None) -> str:
+ expires = int(time.time() if now is None else now) + TTL_SECONDS
+ message = f"{asset_id}.{expires}"
+ signature = hmac.new(key, message.encode(), hashlib.sha256).hexdigest()
+ return f"{expires}.{signature}"
+
+
+def valid(key: bytes, asset_id: int, ticket: str, *, now: float | None = None) -> bool:
+ try:
+ expires, signature = ticket.split(".")
+ current = time.time() if now is None else now
+ if not current < int(expires) <= current + TTL_SECONDS:
+ return False
+ expected = hmac.new(key, f"{asset_id}.{expires}".encode(), hashlib.sha256).hexdigest()
+ return hmac.compare_digest(expected, signature)
+ except (ValueError, TypeError):
+ return False
diff --git a/src/peach/library_processing.py b/src/peach/library_processing.py
index cb2299fad..174ba52eb 100644
--- a/src/peach/library_processing.py
+++ b/src/peach/library_processing.py
@@ -893,7 +893,7 @@ def _merge_candidates(groups, row, code, source, document, evidence_path, genre_
candidate = dict(candidate_key=identity, source=source, provider=PROVIDER_NAMES.get(source, source),
value=value['value'], display_value=value.get('display_value', str(value['value'])),
warnings=value.get('warnings', []),
- confidence=0.9 if local else 0.75 if official else 0.6,
+ confidence=0.9 if local else 0.75 if official else 0.5 if source.startswith('custom-') else 0.6,
source_url=document.get('source_url', ''), raw_snapshot=str(evidence_path),
provider_id=str(document.get('id') or ''), content_id=str(document.get('content_id') or ''),
source_kind='local' if local else spec.kind if spec else 'community', official=official,
@@ -1175,7 +1175,7 @@ class _RemoteSession:
entries, covers = [], 0
if not _scrapes_as_jav(row, code):
return entries, covers
- chain = metadata_routes.route_for_code(code, *_studio_evidence(row), overrides=self._routes)
+ chain = self._chain(code, *_studio_evidence(row))
# 链上剩下的站都给过候选或说过没有、且至少有一家给过候选:这一行不是「没取到」,
# 只是没有新的可问,不进告知项。
if missing and chain and (self._askable(chain, code, answered)
@@ -1245,15 +1245,31 @@ class _RemoteSession:
if not missing or _uncandidated(groups, target_key, missing):
return missing
code = _provider_code(row['code'])
- chain = metadata_routes.route_for_code(code, *_studio_evidence(row), overrides=self._routes)
+ chain = self._chain(code, *_studio_evidence(row))
return missing if self._askable(chain, code, _answered_sources(groups, target_key, missing)) else []
+ def _custom_sources(self, code, *evidence):
+ from .custom_metadata import load
+ kind = metadata_routes.classify(code, *evidence)
+ return [entry for entry in load(self._config.directory('secrets'))
+ if entry['enabled'] and kind in entry['content_types']]
+
+ def _chain(self, code, *evidence):
+ from .custom_metadata import source_key
+ chain = metadata_routes.route_for_code(code, *evidence, overrides=self._routes)
+ return (*chain, *(source_key(entry) for entry in self._custom_sources(code, *evidence)))
+
def _ask(self, source, code, members, cached, *, required, deadline, evidence):
"""问链上的一档:按档名分派到 provider 对应的入口,返回这一档答上的 `[(来源, 资料)]`。
`members` 是这一档里这一行还该问的站(`_askable`),`cached` 是这一档缓存里已有的快照:
FC2 那一档把它们当作已答上的几处交下去,只补问缺演员时的镜像站。
"""
+ if source.startswith('custom-'):
+ from .custom_metadata import query, source_key
+ config = next((entry for entry in self._custom_sources(code, *evidence) if source_key(entry) == source), None)
+ return [(source, query(config, code, deadline=deadline,
+ secrets_root=self._config.directory('secrets')).payload())] if config else []
provider = self.provider()
if source in ('r18dev', 'dmm'):
return [(source, provider.query(code, source, deadline=deadline))]
@@ -1296,12 +1312,12 @@ class _RemoteSession:
deadline = time.monotonic() + budget
mark = _excused(self._provider)
evidence = _studio_evidence(row)
- chain = metadata_routes.route_for_code(code, *evidence, overrides=self._routes)
+ chain = self._chain(code, *evidence)
required = list(metadata_routes.required_scalars(missing))
wants_tags = 'tags' in missing
problems, held, entries = [], [], []
attempted = set(answered)
- stages = _sources_for(code, *evidence, route_overrides=self._routes)
+ stages = metadata_routes.stages_for_chain(chain)
for source, then in zip(stages, (*stages[1:], '')):
members = self._askable(metadata_routes.stage_members(source, chain), code, answered)
if not members:
diff --git a/src/peach/routes_media.py b/src/peach/routes_media.py
index 2a05d13e0..745b0a3ea 100644
--- a/src/peach/routes_media.py
+++ b/src/peach/routes_media.py
@@ -180,6 +180,44 @@ def _hls_plan(state, asset_id: int, session: str = "", conversion: bool | None =
return None if not plan else (asset, source, plan, False)
[email protected]("/api/external-playback")
+def external_playback(request: Request, id: int, args: dict[str, str] = Depends(require_auth)):
+ from .external_playback import TTL_SECONDS, issue
+ state = request.app.state
+ asset = state.media_engine.asset(id)
+ state.media_engine.filesystem.file_for(asset, thumbnail=False)
+ ticket = issue(state.external_playback_key, id)
+ path = f"/external-stream/{id}?ticket={ticket}"
+ playlist = f"/external-playlist/{id}.m3u?ticket={ticket}"
+ return JSONResponse({"url": path, "playlist": playlist, "expires_in": TTL_SECONDS},
+ headers={"Cache-Control": "no-store"})
+
+
+def _external_asset(request: Request, asset_id: int, ticket: str):
+ from .external_playback import valid
+ from fastapi import HTTPException
+ state = request.app.state
+ if not valid(state.external_playback_key, asset_id, ticket):
+ raise HTTPException(401, "播放链接已失效,请在作品详情重新打开")
+ asset = state.media_engine.asset(asset_id)
+ return state.media_engine.filesystem.file_for(asset, thumbnail=False)
+
+
[email protected]_route("/external-stream/{id}", methods=["GET", "HEAD"])
+def external_stream(request: Request, id: int, ticket: str):
+ path = _external_asset(request, id, ticket)
+ return BufferedFileResponse(path, headers={"Cache-Control": "no-store", "Referrer-Policy": "no-referrer"})
+
+
[email protected]("/external-playlist/{id}.m3u")
+def external_playlist(request: Request, id: int, ticket: str):
+ _external_asset(request, id, ticket)
+ url = str(request.base_url).rstrip('/') + f"/external-stream/{id}?ticket={ticket}"
+ return PlainTextResponse(f"#EXTM3U\n#EXTINF:-1,Peach {id}\n{url}\n", media_type="audio/x-mpegurl",
+ headers={"Content-Disposition": f'attachment; filename="peach-{id}.m3u"',
+ "Cache-Control": "no-store", "Referrer-Policy": "no-referrer"})
+
+
@router.api_route("/stream", methods=["GET", "HEAD"])
def stream(request: Request, id: int, session: str = "", args: dict[str, str] = Depends(require_auth)):
state = request.app.state
diff --git a/src/peach/web_custom_metadata.py b/src/peach/web_custom_metadata.py
new file mode 100644
index 000000000..78ccd5028
--- /dev/null
+++ b/src/peach/web_custom_metadata.py
@@ -0,0 +1,13 @@
+"""配置式元数据来源的管理与只读试查。"""
+from . import custom_metadata
+
+
+def q_custom_metadata(contract, args):
+ return {'items': custom_metadata.load(contract.follow_secrets_root)}
+
+
+def w_custom_metadata(contract, body):
+ if body.get('action') == 'preview':
+ record = custom_metadata.query(body, str(body.get('code', '')), secrets_root=contract.follow_secrets_root)
+ return {'record': record.payload(), 'source': record.source, 'confidence': record.confidence}
+ return {'items': custom_metadata.save(contract.follow_secrets_root, body)}
diff --git a/src/peach/web_router.py b/src/peach/web_router.py
index 6d374e421..c4e9a65bb 100644
--- a/src/peach/web_router.py
+++ b/src/peach/web_router.py
@@ -90,6 +90,7 @@ from .web_organize import (
)
from .web_orphan_records import q_orphan_records, w_orphan_attach
from .web_playlists import q_playlist, q_playlists, w_playlist
+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
@@ -365,6 +366,7 @@ GET_HANDLERS = {
"/api/tops": _get_tops,
"/api/ads": _get_ads,
"/api/related": _get_related,
+ "/api/custom-metadata": q_custom_metadata,
"/api/playlists": q_playlists,
"/api/playlist": q_playlist,
"/api/facets": _get_facets,
@@ -406,6 +408,7 @@ POST_HANDLERS = {
"/api/play": w_play,
"/api/feedback": w_feedback,
"/api/watch-later": w_watch_later,
+ "/api/custom-metadata": w_custom_metadata,
"/api/playlist": w_playlist,
"/api/preference": w_preference,
"/api/quality-goal": w_quality_goal,
@@ -439,6 +442,7 @@ POST_HANDLERS = {
#: 不该拦它们——「查找」只联网、「存凭据」只写本机 secrets 文件,都不碰账本。
#: 追更的「查找」在只读端被拦成 409 是实测踩到的。
READ_ONLY_POST_ROUTES = frozenset({
+ "/api/custom-metadata",
"/api/scraping/settings", "/api/scraping/check",
"/api/follow/resolve", "/api/follow/credential",
"/api/taste/refresh", "/api/taste/source", "/api/resource-sync/scan",
diff --git a/tests/test_custom_metadata.py b/tests/test_custom_metadata.py
new file mode 100644
index 000000000..36557209f
--- /dev/null
+++ b/tests/test_custom_metadata.py
@@ -0,0 +1,112 @@
+"""自定义来源的配置、网络边界与正式采集入口。"""
+import tempfile
+import time
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+from peach import custom_metadata as custom
+from peach.library_processing import _RemoteSession
+from peach.metadata_policy import CHAIN_UNKNOWN, source_tier
+from peach.metadata_auto_apply import _evidence_candidates
+
+
+def definition(**changes):
+ return dict(name='测试来源', endpoint='https://metadata.example.com/movies/{code}',
+ fields={'code': 'data.id', 'title': 'data.title', 'performers': 'data.cast'},
+ content_types=['censored'], enabled=True, **changes)
+
+
+class CustomMetadataTests(unittest.TestCase):
+ def test_save_toggle_delete_and_read(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp).resolve()
+ row = custom.save(root, definition())[0]
+ self.assertEqual(custom.load(root), [row])
+ custom.save(root, dict(row, enabled=False))
+ self.assertFalse(custom.load(root)[0]['enabled'])
+ self.assertEqual(custom.save(root, {'id': row['id'], 'action': 'delete'}), [])
+
+ def test_endpoints_and_paths_are_restricted(self):
+ for endpoint in ('http://public.example.com/{code}', 'https://127.0.0.1/{code}',
+ 'https://user:[email protected]/{code}', 'https://{code}.example.com/',
+ 'https://例子.com/{code}', 'https://example.com./{code}',
+ 'https://example.com:8443/{code}', 'https://example.com/{code}/{other}'):
+ with self.subTest(endpoint=endpoint), self.assertRaises(ValueError):
+ custom.validate(dict(definition(), endpoint=endpoint))
+ with self.assertRaises(ValueError):
+ custom.validate(dict(definition(), fields={'code': 'eval()'}))
+
+ def test_response_identity_must_come_from_response(self):
+ with self.assertRaisesRegex(ValueError, '番号'):
+ custom.parse(definition(), 'ABW-001', {'data': {'id': 'ABW-002', 'title': '错片'}})
+ record = custom.parse(definition(), 'ABW-001', {'data': {'id': 'ABW-001', 'title': '标题', 'cast': ['演员']}})
+ self.assertEqual(record.payload()['actresses'], [{'japanese_name': '演员'}])
+ self.assertEqual(record.confidence, 0.5)
+ self.assertEqual(source_tier(record.source), CHAIN_UNKNOWN)
+ self.assertEqual(_evidence_candidates({'candidates': [{'source': record.source, 'value': '标题'}]}, 'title'), [])
+
+ def test_private_dns_is_refused_before_connecting(self):
+ with patch.object(custom, 'host_addresses', return_value=('127.0.0.1',)), patch.object(custom.requests, 'Session') as session:
+ with self.assertRaisesRegex(ValueError, '公网'):
+ custom.fetch_json('https://metadata.example.com/ABW-001', 2)
+ session.assert_not_called()
+
+ def test_formal_pipeline_consumes_enabled_source_after_builtin_chain(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp).resolve()
+ source = custom.save(root / 'secrets', definition())[0]
+ key = custom.source_key(source)
+ config = SimpleNamespace(directory=lambda name: root / name)
+ remote = _RemoteSession(config, Mock, Mock(), retrying=True)
+ self.assertEqual(remote._chain('ABW-001')[-1], key)
+ with patch.object(custom, 'fetch_json', return_value={'data': {'id': 'ABW-001', 'title': '标题', 'cast': []}}):
+ answer = remote._ask(key, 'ABW-001', (key,), [], required=['title'],
+ deadline=time.monotonic() + 10, evidence=())
+ self.assertEqual(answer[0][0], key)
+ self.assertEqual(answer[0][1]['title'], '标题')
+ remote = _RemoteSession(config, Mock, Mock(), retrying=True, routes={'censored': ()})
+ with patch.object(custom, 'fetch_json', return_value={'data': {'id': 'ABW-001', 'title': '标题', 'cast': []}}):
+ entries, _covers = remote.collect({'id': 1, 'code': 'ABW-001', 'path': 'R:/ABW-001.mp4',
+ 'name': 'ABW-001.mp4'}, 'ABW-001', ['title'], root / 'covers', update=Mock(), issue=Mock())
+ self.assertEqual(entries[0][0], key)
+ self.assertEqual(entries[0][1]['title'], '标题')
+ self.assertTrue(entries[0][2].is_file())
+ custom.save(root / 'secrets', dict(source, enabled=False))
+ self.assertNotIn(key, remote._chain('ABW-001'))
+ changed = custom.save(root / 'secrets', dict(source, fields={'code': 'data.id', 'title': 'data.name'}))[0]
+ self.assertNotEqual(custom.source_key(changed), key)
+
+ def test_mapping_rejects_unbounded_or_wrong_shapes(self):
+ with self.assertRaises(ValueError):
+ custom.parse(definition(), 'ABW-001', {'data': {'id': 'ABW-001', 'cast': '演员'}})
+ with self.assertRaises(ValueError):
+ custom.parse(definition(), 'ABW-001', {'data': {'id': 'ABW-001', 'title': 'x' * 4097}})
+
+ def test_public_connection_is_pinned_with_proxy_and_redirects_refused(self):
+ response = Mock(status_code=200)
+ response.iter_content.return_value = [b'{"ok":true}']
+ with patch.object(custom, 'host_addresses', return_value=('1.1.1.1',)), patch.object(custom.requests, 'Session') as session:
+ session.return_value.__enter__.return_value.stream.return_value.__enter__.return_value = response
+ self.assertEqual(custom.fetch_json('https://metadata.example.com/ABW-001', 3,
+ client_options={'proxy': 'http://127.0.0.1:7890', 'trust_env': False}), {'ok': True})
+ options = session.call_args.kwargs
+ target = options['curl_options'][custom.CurlOpt.CONNECT_TO]
+ self.assertEqual(custom.ffi.string(target.data), b'metadata.example.com:443:1.1.1.1:443')
+ stream = session.return_value.__enter__.return_value.stream
+ self.assertFalse(stream.call_args.kwargs['allow_redirects'])
+ self.assertNotIn('verify', stream.call_args.kwargs)
+ response.status_code = 302
+ with self.assertRaisesRegex(ValueError, 'HTTP 302'):
+ custom.fetch_json('https://metadata.example.com/ABW-001', 3)
+
+ def test_response_limit_and_code_format(self):
+ response = Mock(status_code=200)
+ response.iter_content.return_value = [b'x' * (custom.MAX_BYTES + 1)]
+ with patch.object(custom, 'host_addresses', return_value=('1.1.1.1',)), patch.object(custom.requests, 'Session') as session:
+ session.return_value.__enter__.return_value.stream.return_value.__enter__.return_value = response
+ with self.assertRaisesRegex(ValueError, '1 MiB'):
+ custom.fetch_json('https://metadata.example.com/ABW-001', 3)
+ self.assertEqual(custom.endpoint(dict(definition(), code_format='underscore'), '112312-478'),
+ 'https://metadata.example.com/movies/112312_478')
diff --git a/tests/test_external_playback.py b/tests/test_external_playback.py
new file mode 100644
index 000000000..969dadc8b
--- /dev/null
+++ b/tests/test_external_playback.py
@@ -0,0 +1,16 @@
+"""外部播放器票据只授权单资产、限时读取。"""
+import unittest
+
+from peach.external_playback import TTL_SECONDS, issue, valid
+
+
+class ExternalPlaybackTests(unittest.TestCase):
+ def test_ticket_is_scoped_expiring_and_tamper_evident(self):
+ key = b'one-instance-key'
+ ticket = issue(key, 42, now=100)
+ self.assertTrue(valid(key, 42, ticket, now=101))
+ self.assertFalse(valid(key, 43, ticket, now=101))
+ self.assertFalse(valid(b'another-instance', 42, ticket, now=101))
+ self.assertFalse(valid(key, 42, ticket, now=100 + TTL_SECONDS))
+ self.assertFalse(valid(key, 42, ticket + '0', now=101))
+ self.assertFalse(valid(key, 42, '../../media.mp4', now=101))
diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.py
index 132417429..4c1cd896b 100644
--- a/tests/test_fastapi_api.py
+++ b/tests/test_fastapi_api.py
@@ -2223,6 +2223,47 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual((await self.client.get(f"/follow-cover?id={item.id}&t=secret")).status_code, 200)
self.assertEqual(len(requests), 2)
+ async def test_custom_metadata_api_keeps_preview_read_only_and_requires_auth(self):
+ root = self.root.resolve() / 'custom-secrets'
+ body = {'name': '测试来源', 'endpoint': 'https://metadata.example.com/{code}',
+ 'fields': {'code': 'id', 'title': 'title'}, 'content_types': ['censored'], 'enabled': False}
+ with patch.object(self.app.state.web_contract, 'follow_secrets_root', root):
+ self.assertEqual((await self.client.get('/api/custom-metadata')).status_code, 401)
+ with patch('peach.custom_metadata.fetch_json', return_value={'id': 'ABW-001', 'title': '标题'}):
+ preview = await self.client.post('/api/custom-metadata', json=dict(body, action='preview', code='ABW-001'),
+ headers={'X-Token': 'secret'})
+ self.assertEqual(preview.status_code, 200, preview.text)
+ self.assertEqual(preview.json()['record']['title'], '标题')
+ self.assertFalse((root / 'custom-metadata.json').exists())
+ saved = await self.client.post('/api/custom-metadata', json=body, headers={'X-Token': 'secret'})
+ self.assertEqual(saved.status_code, 200, saved.text)
+ read = await self.client.get('/api/custom-metadata', headers={'X-Token': 'secret'})
+ self.assertEqual(read.json(), saved.json())
+ removed = await self.client.post('/api/custom-metadata', json={'action': 'delete', 'id': saved.json()['items'][0]['id']},
+ headers={'X-Token': 'secret'})
+ self.assertEqual(removed.json(), {'items': []})
+
+ async def test_external_player_links_authorize_only_one_asset_and_support_ranges(self):
+ denied = await self.client.post('/api/external-playback?id=1', json={})
+ self.assertEqual(denied.status_code, 401)
+ issued = await self.client.post('/api/external-playback?id=1', json={}, headers={'X-Token': 'secret'})
+ self.assertEqual(issued.status_code, 200, issued.text)
+ links = issued.json()
+ self.assertNotIn('secret', json.dumps(links))
+ self.assertNotIn(str(self.media_root), json.dumps(links))
+ media = await self.client.get(links['url'], headers={'Range': 'bytes=2-5'})
+ self.assertEqual(media.status_code, 206)
+ self.assertEqual(media.content, b'2345')
+ playlist = await self.client.get(links['playlist'])
+ self.assertEqual(playlist.status_code, 200)
+ self.assertIn('#EXTM3U', playlist.text)
+ self.assertIn(links['url'], playlist.text)
+ self.assertNotIn(str(self.media_root), playlist.text)
+ self.assertEqual((await self.client.get(links['url'].replace('/1?', '/2?'))).status_code, 401)
+ cross_site = await self.client.post('/api/external-playback?id=1', json={},
+ headers={'X-Token': 'secret', 'Origin': 'https://attacker.example'})
+ self.assertEqual(cross_site.status_code, 403)
+
async def test_stream_session_cancel_is_authenticated_and_tombstoned(self):
denied = await self.client.post("/api/stream-cancel?session=detail-1")
self.assertEqual(denied.status_code, 401)