Peach: Local-first video metadata scraper and media manager.
fix: adapt unsupported media for browser playback
Peach local maintenance977679e720b1
diff --git a/README.md b/README.mdindex fcda797fc..71a96968d 100644--- a/README.md+++ b/README.md@@ -17,6 +17,8 @@ Peach(蜜桃)是一个单用户、本地优先的个人媒体系统:统一`R:\peach-data` 使用固定分层:`database` 保存真相库,`generated` 保存可再生成的视觉资产,`sources` 保存原始分析输入,`state` 保存人工维护状态,`secrets` 保存本机凭据材料,`logs` 保存运行记录,`archive` 保存历史备份,`inbox` 是临时下载落地区,`tools` 保存不进入 Git 的本机运行时工具。+浏览器原生支持的 MP4/WebM/Ogg 直接走 Range;AVI 等不兼容容器首次播放时由 Peach 管理的 FFmpeg 生成 `generated/transcodes` 下的 H.264/AAC MP4 缓存。缓存可删除重建,原媒体永不改写。+## 结构```textdiff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex 491164de4..59af23e50 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -204,6 +204,8 @@ all three.- Importing operational scripts must have no filesystem/network/database side effects. `scrape_codes.py` sends only catalog codes to declared metadata sources, writes a resumable review CSV, and dual-writes provenance only with `--apply`. `clean_names.py` previews first and creates a SQLite backup before every apply run.- Check ports 80, 8900 and 9999 before starting or switching services.- 115/PikPak playback depends on CloudDrive mounts `B:`/`A:`. Drive-letter visibility differs by Windows execution token; CloudDrive and Peach must see the same mount namespace. A running process or a drive check from another token proves nothing—test one known `/stream` through Peach. Restart CloudDrive only after proving no copy task and no active I/O.+- Browser-incompatible local/cloud containers are adapted by `TranscodeService`, not by Stash and not by front-end MIME guessing. Native MP4/WebM/Ogg stays direct; AVI and other unsupported suffixes are cached under `generated/transcodes` as H.264/AAC MP4 using a source size/mtime key, then served by the same Range endpoint. Never overwrite source media. A sandbox drive check is not authoritative because CloudDrive letters can be token-scoped.+- Never interpolate database metadata into inline JavaScript event attributes. Bind events after DOM insertion and keep metadata in text/data nodes; apostrophes in real studio names already caused a Firefox syntax failure.- Ledger snapshot paths written before the project/data split are rebased by an exact configured legacy prefix. Do not add basename searches or arbitrary path fallbacks.- Report verification separately: static/unit/API, desktop browser, 390×844 browser, and whether production was actually restarted.diff --git a/docs/STATUS.md b/docs/STATUS.mdindex 1636457c3..1016d96fd 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -4,7 +4,7 @@ Last verified: 2026-08-15## Runtime-- Production Peach: FastAPI `0.2.0` from `R:\peach-app` on HTTP `0.0.0.0:80` (PID 46372) and HTTPS `192.168.50.162:443` (PID 60632); health mode is `fastapi`.+- Production Peach: FastAPI `0.2.0` from `R:\peach-app` on HTTP `0.0.0.0:80` (listener PID 28676) and HTTPS `192.168.50.162:443` (listener PID 8268); health mode is `fastapi`.- `peach.local` is again the single official LAN entry. The publisher restores the verified pre-migration behavior: Python zeroconf listens on all eligible interfaces and publishes `peach.local -> 192.168.50.162`. Production health reports `mdns_backend=zeroconf-all-interfaces`; same-host DNS-SD discovery and `getaddrinfo('peach.local')` both resolved the correct address after restart. A second LAN device remains the final external check; no firewall or router rule was changed.- Stash: `127.0.0.1:9999`, PID observed as 35332.- Traffic monitor: running through `RM-TrafficWatch` from `R:\peach-app\.venv`; all probe/sheets tasks use the same project environment.@@ -37,12 +37,14 @@ Runtime PIDs are observations, not configuration; always re-check them.- Creator/studio top lists and related-item creator/tag/studio matching now read canonical entity relations. Real-ledger timings were 0.055 s for 28 top entries and 0.055 s for 24 related items.- Creator/studio filters, canonical-name search, creator index, facets and attribution stats now also read entity relations. Real-ledger timings were 0.040 s for a 1,545-item creator filter, 0.043 s for the first 60 creators, 0.132 s for facets and 0.394 s for stats.- Snapshot availability checks use the same strict legacy-prefix resolver as `/thumb`, so the front end requests migrated previews instead of displaying false “无预览” cards.-- 75 isolated tests pass under Python 3.14, including profile preference, batch operations, client routes, duration range, structural creator cleanup and mDNS tunnel-route fallback. The current inline JavaScript also passes syntax validation.+- 81 isolated tests pass under Python 3.14, including profile preference, batch operations, client routes, duration range, structural creator cleanup, cached browser transcodes, dynamic-handler safety and mDNS tunnel-route fallback. The current inline JavaScript also passes syntax validation.- Real migration preserved 81,873 assets and 59,697 tag links; both live database and backup passed `integrity_check` and `foreign_key_check` before later metadata writes.- The current slice passed isolated desktop 1280×720 and mobile 390×844 browser checks with zero horizontal overflow, all Lucide references resolved, no visible legacy length tags, and the mobile rail hidden.- Restarted production port 80 passed health, home, public OpenCode Go model discovery (26 models at verification time), canonical filtered-list/item reads, thumbnail `200` and 1 KiB `206 Partial Content` Range smoke checks.- After deleting the legacy server, restarted production also passed real `stats`, `tops` and `facets` aggregate contract checks.- HTTPS is running on `192.168.50.162:443` with a local CA for `peach.local` and the LAN IP. The first generated CA lacked `keyUsage`; the script now emits critical CA constraints/key-sign usage and verifies the chain before install. Python/OpenSSL verification with the corrected CA passed. macOS/iOS clients must install only `peach-local-ca.crt` and explicitly trust it.+- `/stream` now keeps browser-native MP4/WebM/Ogg files on the standard direct Range path and sends unsupported containers through Peach's own immutable MP4 cache. The source is never modified; cache keys include asset id, source size and mtime. Real AVI assets 5272 and 5313 were converted in 5.2 seconds total and verified as H.264/yuv420p plus AAC before deployment.+- Studio logo fallbacks no longer compile metadata inside inline JavaScript handlers. Names containing apostrophes such as `Deep's` use DOM event listeners, eliminating the Firefox unescaped-string failure without weakening escaping.- Immersive-mode actions use the shared local Lucide set; visible labels are replaced by accessible names and hover titles where the surrounding context is sufficient.- Long-card hover now enlarges the card and exposes ±10-second preview seeking; short cards expose a profile-backed “稍后看” action. Item details show linked performers/studio/creator/series, and top performer/studio entries navigate to entity pages instead of mutating filters.- The interaction pass now delays long-card enlargement and ±10-second controls until five seconds of continuous hover; quick pointer movement only previews. Creator names on cards and details navigate directly to entity pages. “换一批” is a filled action, not a pressed sort filter, and bottom “再来 60 个” pagination is replaced by an intersection-driven continuation sentinel.@@ -146,20 +148,20 @@ Runtime PIDs are observations, not configuration; always re-check them.Claude project hooks now refresh the managed batch block on Stop, StopFailure and SessionEnd. Codex has no equivalent task-end project hook; its coordinator must keep the same STATUS/HANDOFF write contract manually. Hook verification used a synthetic event and a temporary document/state file; no prompt, response or token was persisted.-The current UI/API candidate passed JavaScript parse, 75 isolated tests, desktop 1280×720 and mobile 390×844. Production HTTP, HTTPS and mDNS were restarted onto this code. HTTPS chain verification passed with the corrected local CA; browsing tests remained on the isolated candidate and did not write real playback, preference or feedback data.+The current UI/API candidate passed JavaScript parse, 81 isolated tests, desktop 1280×720 and mobile 390×844. Production HTTP, HTTPS and mDNS were restarted onto this code. HTTPS chain verification passed with the corrected local CA; browsing tests remained on the isolated candidate and did not write real playback, preference or feedback data.## 批处理进度(自动生成)<!-- job-status:start --><!-- 由 scripts/job_status.py 生成,勿手改;数字现算于账本与产物 -->-<!-- generated 2026-08-14T17:57Z -->+<!-- generated 2026-08-14T18:38Z -->-- 最近自动交接:`claude` / `SessionEnd` / `other`,2026-08-14T17:57:39+00:00。+- 最近自动交接:`claude` / `Stop` / `completed`,2026-08-14T18:38:37+00:00。- 资产 81873 条,其中视频 24980 条。- 待抽帧(可抽 / 缺时长待 probe / 合计):- `local`:4 / 1 / 5- - `115`:29 / 4034 / 4063+ - `115`:1368 / 2695 / 4063- `pikpak`:4751 / 5445 / 10196PikPak 计费,且单帧 seek 实测 25~40 秒,与 115 的 0.4~1.4 秒不是一个量级;全量抽帧按此速率是 14 天量级,按创作者采样是 2 小时量级。- 无内容标签视频 7538 条(占视频 30%)。diff --git a/src/peach/api.py b/src/peach/api.pyindex 9220f4b5c..d8ba0c7ad 100644--- a/src/peach/api.py+++ b/src/peach/api.py@@ -23,6 +23,7 @@ from .previews import PreviewService, PreviewUnavailablefrom .providers import OpenCodeGoClient, ProviderUnavailable, default_registryfrom .repository import LedgerRepositoryfrom .stash import StashClient+from .transcodes import TranscodeService, TranscodeUnavailabledef _first_query_values(request: Request) -> dict[str, str]:@@ -63,6 +64,7 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:repository, resolver, settings.snapshot_root, settings.poster_root,settings.avatar_root, settings.logo_root, settings.legacy_snapshot_roots,)+ transcode_service = TranscodeService(resolver, settings.transcode_root)mdns = create_mdns_publisher(settings.mdns_name, settings.mdns_port, secure=settings.tls_enabled,address=settings.mdns_address,@@ -98,6 +100,7 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:app.state.repository = repositoryapp.state.media_engine = media_engineapp.state.preview_service = preview_service+ app.state.transcode_service = transcode_serviceapp.state.mdns = mdnsapp.state.providers = providersapp.state.opencode_go = opencode_go@@ -159,7 +162,14 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:return JSONResponse({"error": "no such id"}, status_code=404)except MediaUnavailable:return JSONResponse({"error": "unavailable"}, status_code=404)- response = FileResponse(path)+ try:+ path, transcoded = transcode_service.browser_path(id, path)+ except TranscodeUnavailable:+ logging.getLogger(__name__).exception("browser transcode failed for asset %s", id)+ return JSONResponse({"error": "transcode unavailable"}, status_code=503)+ response = FileResponse(path, media_type="video/mp4" if transcoded else None)+ if transcoded:+ response.headers["X-Peach-Transcoded"] = "1"response.headers["Cache-Control"] = "no-store"return responsediff --git a/src/peach/config.py b/src/peach/config.pyindex 67d5a42b1..390de2e77 100644--- a/src/peach/config.py+++ b/src/peach/config.py@@ -16,6 +16,7 @@ ARCHIVE_DIR = DATA_ROOT / "archive"INBOX_DIR = DATA_ROOT / "inbox"TOOLS_DIR = DATA_ROOT / "tools"FFMPEG_DIR = TOOLS_DIR / "ffmpeg"+TRANSCODE_DIR = GENERATED_DIR / "transcodes"MIGRATIONS_DIR = PROJECT_ROOT / "migrations"@@ -38,3 +39,4 @@ class PeachSettings:avatar_root: Path = GENERATED_DIR / "avatars"logo_root: Path = GENERATED_DIR / "logos"ffmpeg_root: Path = FFMPEG_DIR+ transcode_root: Path = TRANSCODE_DIRdiff --git a/src/peach/transcodes.py b/src/peach/transcodes.pynew file mode 100644index 000000000..b7849d5cb--- /dev/null+++ b/src/peach/transcodes.py@@ -0,0 +1,85 @@+from __future__ import annotations++import os+import subprocess+import threading+import uuid+from pathlib import Path++from .ffmpeg import FFmpegResolver+++BROWSER_NATIVE_SUFFIXES = frozenset({".mp4", ".m4v", ".webm", ".ogv", ".ogg"})+++class TranscodeUnavailable(RuntimeError):+ pass+++class TranscodeService:+ """Create immutable browser-playable MP4 cache entries without touching sources."""++ def __init__(self, resolver: FFmpegResolver, cache_root: Path):+ self.resolver = resolver+ self.cache_root = cache_root+ self._locks: dict[int, threading.Lock] = {}+ self._locks_guard = threading.Lock()++ @staticmethod+ def needs_transcode(source: Path) -> bool:+ return source.suffix.lower() not in BROWSER_NATIVE_SUFFIXES++ def browser_path(self, asset_id: int, source: Path) -> tuple[Path, bool]:+ if not self.needs_transcode(source):+ return source, False++ choice = self.resolver.ffmpeg()+ if choice is None:+ raise TranscodeUnavailable("ffmpeg unavailable")++ try:+ stat = source.stat()+ except OSError as exc:+ raise TranscodeUnavailable("source unavailable") from exc++ target = self.cache_root / f"{asset_id}-{stat.st_size}-{stat.st_mtime_ns}.mp4"+ if target.is_file() and target.stat().st_size:+ return target, True++ with self._lock_for(asset_id):+ if target.is_file() and target.stat().st_size:+ return target, True+ self.cache_root.mkdir(parents=True, exist_ok=True)+ temporary = target.with_name(f"{target.stem}.{uuid.uuid4().hex}.tmp.mp4")+ command = [+ str(choice.path), "-hide_banner", "-loglevel", "error", "-nostdin",+ "-y", "-i", str(source),+ "-map", "0:v:0", "-map", "0:a:0?",+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "21",+ "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "160k",+ "-movflags", "+faststart", str(temporary),+ ]+ creationflags = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0+ try:+ result = subprocess.run(+ command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,+ stderr=subprocess.PIPE, timeout=3600, check=False,+ creationflags=creationflags,+ )+ if result.returncode or not temporary.is_file() or not temporary.stat().st_size:+ detail = result.stderr.decode("utf-8", "replace")[-1000:]+ raise TranscodeUnavailable(detail or "ffmpeg failed")+ temporary.replace(target)+ except (OSError, subprocess.TimeoutExpired) as exc:+ raise TranscodeUnavailable("ffmpeg failed") from exc+ finally:+ temporary.unlink(missing_ok=True)++ for stale in self.cache_root.glob(f"{asset_id}-*.mp4"):+ if stale != target:+ stale.unlink(missing_ok=True)+ return target, True++ def _lock_for(self, asset_id: int) -> threading.Lock:+ with self._locks_guard:+ return self._locks.setdefault(asset_id, threading.Lock())diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.pyindex 76f1ad955..c0bade08b 100644--- a/tests/test_fastapi_api.py+++ b/tests/test_fastapi_api.py@@ -55,6 +55,7 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):self.poster_root = self.root / "posters"self.avatar_root = self.root / "avatars"self.logo_root = self.root / "logos"+ self.transcode_root = self.root / "transcodes"for path in (self.media_root, self.snapshot_root, self.poster_root,self.avatar_root, self.logo_root):path.mkdir()@@ -90,15 +91,15 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):)con.commit()con.close()- app = create_app(PeachSettings(+ self.app = create_app(PeachSettings(db_path=self.db, token="secret", page_path=self.page,allowed_media_roots=(self.media_root,), snapshot_root=self.snapshot_root,legacy_snapshot_roots=(self.legacy_snapshot_root,),poster_root=self.poster_root, avatar_root=self.avatar_root, logo_root=self.logo_root,- ffmpeg_root=self.root / "ffmpeg",+ ffmpeg_root=self.root / "ffmpeg", transcode_root=self.transcode_root,))self.client = httpx.AsyncClient(- transport=httpx.ASGITransport(app=app), base_url="http://test"+ transport=httpx.ASGITransport(app=self.app), base_url="http://test")async def asyncTearDown(self):@@ -230,6 +231,33 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(head.content, b"")self.assertEqual(head.headers["content-length"], "10")+ async def test_transcoded_stream_has_browser_mime_and_marker(self):+ avi = self.media_root / "two.avi"+ avi.write_bytes(b"avi-source")+ cached = self.transcode_root / "two.mp4"+ cached.parent.mkdir(parents=True)+ cached.write_bytes(b"mp4-cache")+ con = sqlite3.connect(self.db)+ con.execute(+ "INSERT INTO asset(id,location,path,name,medium,size,first_seen) "+ "VALUES(2,'local',?,'two.avi','video',10,'2026-08-15')",+ (str(avi),),+ )+ con.commit()+ con.close()++ with patch.object(+ self.app.state.transcode_service, "browser_path",+ return_value=(cached, True),+ ):+ response = await self.client.get(+ "/stream?id=2", headers={"X-Token": "secret", "Range": "bytes=0-2"},+ )+ self.assertEqual(response.status_code, 206)+ self.assertEqual(response.content, b"mp4")+ self.assertEqual(response.headers["content-type"], "video/mp4")+ self.assertEqual(response.headers["x-peach-transcoded"], "1")+async def test_cached_visual_assets_and_thumbnail(self):headers = {"X-Token": "secret"}poster = await self.client.get("/poster?id=1&c=4", headers=headers)diff --git a/tests/test_transcodes.py b/tests/test_transcodes.pynew file mode 100644index 000000000..58590c191--- /dev/null+++ b/tests/test_transcodes.py@@ -0,0 +1,49 @@+import subprocess+import tempfile+import unittest+from pathlib import Path+from unittest.mock import patch++from peach.ffmpeg import BinaryChoice+from peach.transcodes import TranscodeService, TranscodeUnavailable+++class _Resolver:+ def __init__(self, binary: Path | None):+ self.binary = binary++ def ffmpeg(self):+ return BinaryChoice(self.binary, "test") if self.binary else None+++class TranscodeServiceTests(unittest.TestCase):+ def test_native_mp4_is_returned_without_ffmpeg(self):+ source = Path("movie.mp4")+ service = TranscodeService(_Resolver(None), Path("cache"))+ self.assertEqual(service.browser_path(1, source), (source, False))++ def test_unsupported_container_requires_ffmpeg(self):+ service = TranscodeService(_Resolver(None), Path("cache"))+ with self.assertRaises(TranscodeUnavailable):+ service.browser_path(1, Path("movie.avi"))++ def test_avi_is_transcoded_once_and_cached(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ source = root / "movie.avi"+ source.write_bytes(b"avi")+ service = TranscodeService(_Resolver(root / "ffmpeg.exe"), root / "cache")++ def run(command, **_kwargs):+ Path(command[-1]).write_bytes(b"mp4")+ return subprocess.CompletedProcess(command, 0, b"", b"")++ with patch("peach.transcodes.subprocess.run", side_effect=run) as execute:+ first, transcoded = service.browser_path(9, source)+ second, cached = service.browser_path(9, source)++ self.assertTrue(transcoded and cached)+ self.assertEqual(first, second)+ self.assertEqual(first.read_bytes(), b"mp4")+ self.assertEqual(execute.call_count, 1)+ self.assertIn("libx264", execute.call_args.args[0])diff --git a/tests/test_web_ui.py b/tests/test_web_ui.pynew file mode 100644index 000000000..b0c053e2a--- /dev/null+++ b/tests/test_web_ui.py@@ -0,0 +1,19 @@+import unittest+from pathlib import Path+++class WebUiSourceTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.page = (Path(__file__).resolve().parents[1] / "web" / "index.html").read_text(+ encoding="utf-8"+ )++ def test_studio_metadata_is_not_compiled_as_inline_javascript(self):+ self.assertNotIn('onerror="this.parentNode.innerHTML=', self.page)+ self.assertNotIn('onload="if(this.naturalWidth', self.page)+ self.assertIn("img.addEventListener('error',fallback", self.page)+++if __name__ == "__main__":+ unittest.main()diff --git a/web/index.html b/web/index.htmlindex b5d1bfd4f..500db7ffe 100644--- a/web/index.html+++ b/web/index.html@@ -630,7 +630,7 @@ const $=s=>document.querySelector(s);const icon=(name,cls='')=>`<svg${cls?` class="${cls}"`:''} viewBox="0 0 24 24" aria-hidden="true"><use href="#i-${name}"/></svg>`;const api=(p,o)=>fetch(p,Object.assign({headers:{'Content-Type':'application/json'}},o||{})).then(r=>r.json());const route=(path,replace=false)=>history[replace?'replaceState':'pushState']({},'',path);-const esc=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c]));+const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));const fmtDur=s=>{if(!s)return'—';s=Math.round(s);const h=s/3600|0,m=(s%3600)/60|0,x=s%60;return h?`${h}:${String(m).padStart(2,'0')}:${String(x).padStart(2,'0')}`:`${m}:${String(x).padStart(2,'0')}`};const fmtSize=b=>b>=1099511627776?(b/1099511627776).toFixed(2)+' TB':b>=1073741824?(b/1073741824).toFixed(1)+' GB':(b/1048576|0)+' MB';@@ -820,9 +820,7 @@ async function buildBars(){const bpHtml=x=>{const fallback=`${esc(x.k.slice(0,2))}`;return `<button class="brandpill" data-entity-kind="studio" data-entity-name="${esc(x.k)}">- <span class="mk"><img src="/logo?studio=${encodeURIComponent(x.k)}" alt=""- onerror="this.parentNode.innerHTML='${fallback}'"- onload="if(this.naturalWidth<32)this.parentNode.innerHTML='${fallback}'"+ <span class="mk" data-fallback="${fallback}"><img src="/logo?studio=${encodeURIComponent(x.k)}" alt=""style="width:100%;height:100%;object-fit:contain"></span>${esc(x.k)}</button>`;};$('#tiers').innerHTML=@@ -830,6 +828,11 @@ async function buildBars(){`<div class="tier">${tops.studios.map(bpHtml).join('')}</div>`;$('#tiers').querySelectorAll('[data-entity-kind]').forEach(b=>b.onclick=()=>openEntity(b.dataset.entityKind,b.dataset.entityName));+ $('#tiers').querySelectorAll('.mk img').forEach(img=>{+ const fallback=()=>{const box=img.parentNode;if(box)box.textContent=box.dataset.fallback||''};+ img.addEventListener('error',fallback,{once:true});+ img.addEventListener('load',()=>{if(img.naturalWidth<32)fallback()},{once:true});+ });const views=[{k:'',label:'全部'},{k:'fresh',label:'没看过'},{k:'played',label:'看过'},{k:'later',label:'稍后看'},{k:'flagged',label:'已标记'},{k:'ads',label:'疑似广告'}];