import hashlib import re import threading from pathlib import Path from server.services.dramabox.client import USER_AGENT from server.services.http import http CACHE_DIR = Path(__file__).resolve().parents[3] / "cache" / "dramabox" / "covers" _lock = threading.Lock() _IMAGE_TYPES = { b"\xff\xd8\xff": "image/jpeg", b"\x89PNG": "image/png", b"GIF8": "image/gif", b"RIFF": "image/webp", } class CoverCache: def local_url(self, remote: str) -> str: remote = (remote or "").strip() if not remote: return "" if remote.startswith("/api/dramabox/covers/"): return remote if not remote.startswith(("http://", "https://")): return remote digest = hashlib.sha256(remote.encode("utf-8")).hexdigest() CACHE_DIR.mkdir(parents=True, exist_ok=True) meta = CACHE_DIR / f"{digest}.url" if not meta.is_file(): meta.write_text(remote, encoding="utf-8") return f"/api/dramabox/covers/{digest}" def read(self, digest: str) -> tuple[bytes, str]: if not re.fullmatch(r"[0-9a-f]{64}", digest): raise RuntimeError("封面不存在") meta = CACHE_DIR / f"{digest}.url" body = CACHE_DIR / digest if not meta.is_file(): raise RuntimeError("封面不存在") if body.is_file() and body.stat().st_size > 0: return body.read_bytes(), _media_type(body) remote = meta.read_text(encoding="utf-8").strip() data, media = _download(remote) with _lock: CACHE_DIR.mkdir(parents=True, exist_ok=True) body.write_bytes(data) (CACHE_DIR / f"{digest}.type").write_text(media, encoding="utf-8") return data, media def _download(remote: str) -> tuple[bytes, str]: headers = {"User-Agent": USER_AGENT, "Referer": "https://www.dramaboxapp.com/"} last_error = "封面读取失败" for url in _candidates(remote): try: response = http.send("GET", url, headers=headers, timeout=30.0) response.raise_for_status() except Exception as exc: last_error = str(exc) or last_error continue media = _sniff_media(response.content) or (response.headers.get("content-type") or "").split(";", 1)[0].strip() if response.content and media.startswith("image/"): return response.content, media last_error = "不是图片" raise RuntimeError(last_error) def _candidates(remote: str) -> list[str]: urls = [remote] stripped = re.sub(r"@w=\d+&h=\d+$", "", remote) if stripped != remote: urls.append(stripped) return urls def _sniff_media(data: bytes) -> str: for magic, media in _IMAGE_TYPES.items(): if data.startswith(magic): return media return "" def _media_type(path: Path) -> str: sidecar = Path(f"{path}.type") if sidecar.is_file(): media = sidecar.read_text(encoding="utf-8").strip() if media.startswith("image/"): return media return "image/jpeg" covers = CoverCache()