Peach: Local-first video metadata scraper and media manager.
refactor(media): 分离完整传输安装并核对缓存门槛
longmeidaobb4c1c32b59d
diff --git a/src/peach/preview_cache.py b/src/peach/preview_cache.pyindex 73bad8420..384183fe4 100644--- a/src/peach/preview_cache.py+++ b/src/peach/preview_cache.py@@ -36,11 +36,11 @@ class PreviewCache:url = self.source(code, ref)["url"]def download():body = fetch(url)- if not body.lstrip().startswith(b"#EXTM3U"):+ if not body.decode("utf-8").removeprefix(chr(0xFEFF)).lstrip().startswith("#EXTM3U"):raise ValueError("预览清单未取得")return bodybody = self.cache.bytes(f"preview:{code}:{ref}:playlist", download)- playlist = m3u8.loads(body.decode("utf-8-sig"), uri=url)+ 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:diff --git a/src/peach/remote_media_cache.py b/src/peach/remote_media_cache.pyindex 415b8d5f5..021a0e06b 100644--- a/src/peach/remote_media_cache.py+++ b/src/peach/remote_media_cache.py@@ -15,7 +15,7 @@ from .fsutil import atomic_path, atomic_write_textAVATAR_REFRESH_SECONDS = 90 * 86400FAVICON_REFRESH_SECONDS = 365 * 86400-MEDIA_HEADERS = ("content-type", "content-length", "content-range", "accept-ranges")+MEDIA_HEADERS = ("content-type", "content-length", "content-range", "accept-ranges", "content-encoding")class RemoteMediaUnavailable(ValueError):@@ -110,25 +110,8 @@ class RemoteMediaCache:slot = self._slot(key, byte_range)def body():try:- if not accepted:- yield from upstream.iter_raw()- return- with atomic_path(slot.with_suffix(".bin")) as temporary:- size = 0- with temporary.open("wb") as handle:- for chunk in upstream.iter_raw():- handle.write(chunk)- size += len(chunk)- yield chunk- expected = int(forwarded.get("content-length", size))- if not size or size != expected or (content_range and- size != int(content_range[2]) - int(content_range[1]) + 1):- raise OSError("媒体响应长度不完整")- atomic_write_text(slot.with_suffix(".json"), json.dumps({- "status": 200 if complete_range else upstream.status_code, "size": size, "headers": {- name: value for name, value in forwarded.items() if name in MEDIA_HEADERS- and not (complete_range and name == "content-range")},- }), mode=0o600)+ yield from self._capture_response(slot, upstream, forwarded, accepted=accepted,+ content_range=content_range, complete_range=complete_range)finally:close()return StreamingResponse(body(), status_code=upstream.status_code, headers=forwarded,@@ -137,6 +120,28 @@ class RemoteMediaCache:close()raise+ def _capture_response(self, slot, upstream, headers, *, accepted, content_range, complete_range):+ """安装一次完整传输的字节与范围信息,未完成的临时文件由原子写入清除。"""+ if not accepted:+ yield from upstream.iter_raw()+ return+ with atomic_path(slot.with_suffix(".bin")) as temporary:+ size = 0+ with temporary.open("wb") as handle:+ for chunk in upstream.iter_raw():+ handle.write(chunk)+ size += len(chunk)+ yield chunk+ expected = int(headers.get("content-length", size))+ if not size or size != expected or (content_range and+ size != int(content_range[2]) - int(content_range[1]) + 1):+ raise OSError("媒体响应长度不完整")+ atomic_write_text(slot.with_suffix(".json"), json.dumps({+ "status": 200 if complete_range else upstream.status_code, "size": size, "headers": {+ name: value for name, value in headers.items() if name in MEDIA_HEADERS+ and not (complete_range and name == "content-range")},+ }), mode=0o600)+def bytes(self, key: str, fetch, *, ttl: int | None = None) -> bytes:"""图片与清单复用原子文件及跨进程锁;刷新失败保留可用副本。"""path = self._slot(key).with_suffix(".data")diff --git a/src/peach/routes_media.py b/src/peach/routes_media.pyindex 3effc6cd8..2a05d13e0 100644--- a/src/peach/routes_media.py+++ b/src/peach/routes_media.py@@ -962,7 +962,7 @@ def jav_preview(request: Request, code: str, ref: str, args: dict[str, str] = Deresponse = open_upstream(client, "GET", ResolvedFollowMedia(url, public_hosts=True), incoming={})try:chunks, size = [], 0- for chunk in response.iter_raw():+ for chunk in response.iter_bytes():size += len(chunk)if size > 1024 * 1024:raise ValueError("预览清单过大")diff --git a/tests/test_follow_media_cache.py b/tests/test_follow_media_cache.pyindex 265a4ebb6..7cebd4270 100644--- a/tests/test_follow_media_cache.py+++ b/tests/test_follow_media_cache.py@@ -1,5 +1,6 @@import asyncioimport json+import gzipimport osimport tempfileimport unittest@@ -60,6 +61,14 @@ class RemoteMediaCacheTests(unittest.IsolatedAsyncioTestCase):self.assertIsNone(self.cache.stored("follow:1:media:0", "bytes=6-9"))self.assertIsNone(self.cache.stored("follow:1:media:0"))+ async def test_content_encoding_is_preserved_for_disk_replay(self):+ self.payload = gzip.compress(b"0123456789")+ self.headers.update({"content-encoding": "gzip", "content-length": str(len(self.payload))})+ for _ in range(2):+ response = await self.client.get("/media")+ self.assertEqual(response.content, b"0123456789")+ self.assertEqual(self.calls, 1)+async def test_concurrent_cold_requests_download_once(self):responses = await asyncio.gather(self.client.get("/media"), self.client.get("/media"))self.assertEqual([response.content for response in responses], [self.payload] * 2)@@ -120,7 +129,7 @@ class PreviewCacheTests(unittest.TestCase):cache = RemoteMediaCache(Path(directory).resolve())previews = PreviewCache(cache)root = previews.register("ABP-123", "https://cdn.example/root.m3u8", identity="root", playlist=True)- fetch = mock.Mock(return_value=b'#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=10\nvideo/list\n')+ fetch = mock.Mock(return_value=b'\xef\xbb\xbf#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=10\nvideo/list\n')body = previews.playlist("ABP-123", root, fetch).decode()self.assertNotIn("https://", body)child = body.splitlines()[-1].rsplit("/", 1)[-1]diff --git a/tests/test_source_assertion_ratchet.py b/tests/test_source_assertion_ratchet.pyindex b45c6775b..d277f16a4 100644--- a/tests/test_source_assertion_ratchet.py+++ b/tests/test_source_assertion_ratchet.py@@ -52,7 +52,6 @@ BASELINE: dict[str, int] = {"test_subprocess_encoding.py": 2,"test_tray.py": 3,"test_web_js.py": 1,- "test_web_settings.py": 1,"test_web_ui.py": 14,"test_windows_update.py": 3,}