223 lines
7.1 KiB
Python
223 lines
7.1 KiB
Python
# src/core/tmdb_store.py
|
|
"""TMDB 缓存库(schema 2)。
|
|
|
|
结构::
|
|
|
|
{
|
|
"_meta": {"schema": 2, "updated_at": "..."},
|
|
"entities": {"movie_9007": {...}, "tv_231620": {...}},
|
|
"lookups": {"movie": {"标题": {"年份或空串": ["movie_9007"]}}, "tv": {...}}
|
|
}
|
|
|
|
- entities 以 ``{type}_{tmdb_id}`` 为主键,一条记录即一个 TMDB 实体
|
|
- lookups 是「标题(+年份) → 实体键列表」的索引,列表长度 >1 表示搜索结果并列
|
|
- 文件级访问用 fcntl.flock 串行化,写入走临时文件 + os.replace,供容器内 pipeline
|
|
与宿主机 media-archive 两个进程并发使用
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import fcntl
|
|
import json
|
|
import os
|
|
import unicodedata
|
|
from contextlib import contextmanager
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
|
|
from core.utils import StringUtil
|
|
|
|
SCHEMA = 2
|
|
TYPES = ("movie", "tv")
|
|
|
|
# 详情里我们关心的字段(写进 details 段)
|
|
DETAIL_KEYS = ("original_language", "origin_country")
|
|
|
|
|
|
# ------------------------------------------------------------------ 时间/字符串
|
|
|
|
def now_iso() -> str:
|
|
"""本地时区(东八区)ISO8601,精确到秒。"""
|
|
return datetime.now().astimezone().isoformat(timespec="seconds")
|
|
|
|
|
|
def normalize_title(title: str) -> str:
|
|
"""lookup 键归一化:NFKC + 去首尾空白 + 连续空白压成一个空格。"""
|
|
if not title:
|
|
return ""
|
|
return " ".join(unicodedata.normalize("NFKC", str(title)).strip().split())
|
|
|
|
|
|
def entity_key(mtype: str, tmdb_id) -> str:
|
|
return f"{mtype}_{int(tmdb_id)}"
|
|
|
|
|
|
# ------------------------------------------------------------------ 读写与锁
|
|
|
|
def empty_db() -> dict:
|
|
return {"_meta": {"schema": SCHEMA}, "entities": {}, "lookups": {t: {} for t in TYPES}}
|
|
|
|
|
|
@contextmanager
|
|
def _lock(path: Path):
|
|
lock_path = path.with_name(path.name + ".lock")
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
with open(lock_path, "a+") as fh:
|
|
fcntl.flock(fh, fcntl.LOCK_EX)
|
|
try:
|
|
yield
|
|
finally:
|
|
fcntl.flock(fh, fcntl.LOCK_UN)
|
|
|
|
|
|
def _read(path: Path) -> dict:
|
|
try:
|
|
data = json.loads(path.read_text(encoding="utf-8"))
|
|
except (OSError, ValueError):
|
|
return empty_db()
|
|
if not isinstance(data, dict) or "entities" not in data or "lookups" not in data:
|
|
# 旧扁平结构或损坏:运行期当空库用,转换交给迁移脚本
|
|
return empty_db()
|
|
for t in TYPES:
|
|
data["lookups"].setdefault(t, {})
|
|
data.setdefault("_meta", {}).setdefault("schema", SCHEMA)
|
|
return data
|
|
|
|
|
|
def _write(path: Path, db: dict) -> None:
|
|
db.setdefault("_meta", {})["schema"] = SCHEMA
|
|
db["_meta"]["updated_at"] = now_iso()
|
|
tmp = path.with_name(f"{path.name}.tmp{os.getpid()}")
|
|
tmp.write_text(json.dumps(db, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
os.replace(tmp, path)
|
|
|
|
|
|
@contextmanager
|
|
def transaction(path: Path):
|
|
"""持锁完成一次「读-改-写」;块内抛异常则不写回。"""
|
|
with _lock(path):
|
|
db = _read(path)
|
|
yield db
|
|
_write(path, db)
|
|
|
|
|
|
def snapshot(path: Path) -> dict:
|
|
"""只读快照(同样持锁,避免读到半个文件)。"""
|
|
with _lock(path):
|
|
return _read(path)
|
|
|
|
|
|
# ------------------------------------------------------------------ 实体
|
|
|
|
def get_entity(db: dict, mtype: str, tmdb_id) -> dict | None:
|
|
try:
|
|
return db["entities"].get(entity_key(mtype, tmdb_id))
|
|
except (TypeError, ValueError):
|
|
return None
|
|
|
|
|
|
def put_entity(db: dict, entity: dict) -> str:
|
|
key = entity_key(entity["type"], entity["tmdb_id"])
|
|
entity["updated_at"] = now_iso()
|
|
db["entities"][key] = entity
|
|
return key
|
|
|
|
|
|
def _first(payload: dict, *names):
|
|
for name in names:
|
|
value = payload.get(name)
|
|
if value:
|
|
return value
|
|
return None
|
|
|
|
|
|
def _year_of(payload: dict) -> int | None:
|
|
date = _first(payload, "release_date", "first_air_date", "air_date") or ""
|
|
return int(date[:4]) if len(date) >= 4 and date[:4].isdigit() else None
|
|
|
|
|
|
def season_years_from(payload: dict) -> dict[str, str]:
|
|
"""从 /tv/{id} 的 seasons 数组生成 {"01": "2023"}。
|
|
|
|
一律以 TMDB 各季的 air_date 为准,特别季 Season 00 也不例外
|
|
(例如《我的三体》特别篇 2019,第一季 2014)。
|
|
"""
|
|
out: dict[str, str] = {}
|
|
for season in payload.get("seasons") or []:
|
|
try:
|
|
num = str(int(season.get("season_number", 0))).zfill(2)
|
|
except (TypeError, ValueError):
|
|
continue
|
|
air = (season.get("air_date") or "").strip()
|
|
if len(air) >= 4 and air[:4].isdigit():
|
|
out[num] = air[:4]
|
|
return out
|
|
|
|
|
|
def special_years_from(payload: dict) -> dict[str, str]:
|
|
"""从 /tv/{id}/season/{n} 的响应生成按集号的年份 {"06": "2013"}。
|
|
|
|
Season 00 整体只有一个 air_date(往往是特别篇第一集的年份),
|
|
对逐个特别篇没有意义,所以按集取。
|
|
"""
|
|
out: dict[str, str] = {}
|
|
for episode in payload.get("episodes") or []:
|
|
try:
|
|
num = str(int(episode.get("episode_number", 0))).zfill(2)
|
|
except (TypeError, ValueError):
|
|
continue
|
|
air = (episode.get("air_date") or "").strip()
|
|
if len(air) >= 4 and air[:4].isdigit():
|
|
out[num] = air[:4]
|
|
return out
|
|
|
|
|
|
def build_entity(mtype: str, tmdb_id, payload: dict) -> dict:
|
|
"""把 TMDB 详情响应映射成本库的记录结构。"""
|
|
localized = _first(payload, "title", "name") or ""
|
|
original = _first(payload, "original_title", "original_name") or localized
|
|
genres = [
|
|
{"id": int(g.get("id")), "name": g.get("name") or ""}
|
|
for g in (payload.get("genres") or [])
|
|
if isinstance(g, dict) and g.get("id")
|
|
]
|
|
record = {
|
|
"type": mtype,
|
|
"tmdb_id": int(tmdb_id),
|
|
"title": localized,
|
|
"tmdb_original_title": original,
|
|
"media_title": StringUtil.media_title(original, fallback=localized),
|
|
"year": _year_of(payload),
|
|
"details": {
|
|
"genres": genres,
|
|
"original_language": (payload.get("original_language") or "").lower(),
|
|
"origin_country": [str(c).upper() for c in (payload.get("origin_country") or []) if c],
|
|
},
|
|
"updated_at": now_iso(),
|
|
}
|
|
if mtype == "tv":
|
|
record["season_years"] = season_years_from(payload)
|
|
return record
|
|
|
|
|
|
# ------------------------------------------------------------------ 索引
|
|
|
|
def lookup(db: dict, mtype: str, title: str, year) -> list[str]:
|
|
bucket = db["lookups"].get(mtype, {}).get(normalize_title(title))
|
|
if not bucket:
|
|
return []
|
|
return list(bucket.get(str(year or ""), []))
|
|
|
|
|
|
def merge_candidates(db: dict, mtype: str, title: str, years, keys) -> None:
|
|
"""把 keys 写进 title 的若干年份桶(年份为空串表示「未给年份的搜索」)。"""
|
|
key_title = normalize_title(title)
|
|
if not key_title or not keys:
|
|
return
|
|
bucket = db["lookups"].setdefault(mtype, {}).setdefault(key_title, {})
|
|
for year in years:
|
|
slot = bucket.setdefault(str(year), [])
|
|
for key in keys:
|
|
if key not in slot:
|
|
slot.append(key)
|