72 lines
2.3 KiB
Python
72 lines
2.3 KiB
Python
import hashlib
|
|
import re
|
|
import threading
|
|
from pathlib import Path
|
|
|
|
from server.services.http import http
|
|
from server.services.huangdou.crypto import USER_AGENT, decrypt_resource
|
|
|
|
CACHE_DIR = Path(__file__).resolve().parents[3] / "cache" / "huangdou" / "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/huangdou/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/huangdou/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 = http.get_bytes(remote, headers={"User-Agent": USER_AGENT, "Referer": "https://pmihlvee.cc/"})
|
|
data = decrypt_resource(data)
|
|
media = _sniff_media(data) or media
|
|
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 _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()
|