feat(tmdb): 缓存库重构为 entities + lookups(schema 2)
- 新增 core/tmdb_store.py:{type}_{tmdb_id} 实体 + 标题/年份索引,fcntl.flock
串行化 + 临时文件原子替换,容器内 pipeline 与宿主机 media-archive 共用
- 命中优先级:目录名里的 [tmdbid-xxx] → 缓存 lookup → 在线搜索
- 搜索先去掉年份条件;精确标题匹配后仍有多条才交互选择(非 TTY 取第一条
并告警),解决「苍兰诀」真人版/动漫版同名同年歧义
- 未给年份的搜索在解析出实体后,同时补写空年份桶与带年份桶
- tmdb_original_title 保留原文;新增 media_title(白名单清洗 + 120 字符截断)
专供拼文件名,清洗规则改为只保留字母/数字/下划线/连字符
- 年份三级兜底:目录名 → TMDB 实体 → 省略年份段;取消阻塞式年份追问
- Season 00 年份统一取 Season 01
- media-archive 改用同一 store,删除自带的 details_ 缓存
- 迁移 415 条旧记录 → 411 实体 / 409 标题索引(4 个 TMDB id 已失效跳过)
- 移除不再使用的 core/cache.py
This commit is contained in:
+214
-86
@@ -1,112 +1,240 @@
|
||||
# src/services/tmdb.py
|
||||
"""TMDB 查询:优先用目录名里的 tmdbid,其次查本地缓存库,最后才发请求。"""
|
||||
|
||||
import sys
|
||||
|
||||
import requests
|
||||
from requests.adapters import HTTPAdapter
|
||||
from urllib3.util.retry import Retry
|
||||
|
||||
from core import config
|
||||
from core import tmdb_store as store
|
||||
from core.logger import log
|
||||
from core.utils import StringUtil
|
||||
from core.cache import JsonCacheManager # 💡 接入统一缓存层
|
||||
|
||||
|
||||
class TMDBService:
|
||||
_notified_cache_hits = set()
|
||||
_notified_cache_hits = set()
|
||||
|
||||
# ------------------------------------------------------------ HTTP
|
||||
|
||||
@staticmethod
|
||||
def _get_session():
|
||||
s = requests.Session()
|
||||
retries = Retry(total=config.TMDB_MAX_RETRIES, backoff_factor=1, status_forcelist=[429, 502, 503, 504])
|
||||
retries = Retry(total=config.TMDB_MAX_RETRIES, backoff_factor=1,
|
||||
status_forcelist=[429, 502, 503, 504])
|
||||
s.mount('https://', HTTPAdapter(max_retries=retries))
|
||||
return s
|
||||
|
||||
@classmethod
|
||||
def _fetch_season_years(cls, session, tmdb_id):
|
||||
details_url = f"https://api.themoviedb.org/3/tv/{tmdb_id}"
|
||||
season_years = {}
|
||||
try:
|
||||
resp = session.get(details_url, params={"api_key": config.TMDB_API_KEY.strip()}, timeout=config.TMDB_TIMEOUT)
|
||||
if resp.status_code == 200:
|
||||
for season in resp.json().get('seasons', []):
|
||||
s_num = str(season.get('season_number', 0)).zfill(2)
|
||||
air_date = season.get('air_date')
|
||||
if air_date and len(air_date) >= 4:
|
||||
season_years[s_num] = air_date[:4]
|
||||
except Exception as e:
|
||||
log.warning(f"获取剧集详情年份失败 [ID:{tmdb_id}]: {e}")
|
||||
return season_years
|
||||
|
||||
@staticmethod
|
||||
def search_media(title, year=None, m_type="movie", season_num=None):
|
||||
def _params(extra: dict | None = None) -> dict:
|
||||
params = {"api_key": config.TMDB_API_KEY.strip(), "language": config.TMDB_LANGUAGE}
|
||||
if extra:
|
||||
params.update(extra)
|
||||
return params
|
||||
|
||||
@classmethod
|
||||
def _fetch_details(cls, session, mtype: str, tmdb_id) -> dict | None:
|
||||
endpoint = "tv" if mtype == "tv" else "movie"
|
||||
try:
|
||||
resp = session.get(f"https://api.themoviedb.org/3/{endpoint}/{tmdb_id}",
|
||||
params=cls._params(), timeout=config.TMDB_TIMEOUT)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.warning(f"⚠️ TMDB 详情请求异常 [{mtype}/{tmdb_id}]: {exc}")
|
||||
return None
|
||||
if resp.status_code != 200:
|
||||
log.warning(f"⚠️ TMDB 详情获取失败 [{mtype}/{tmdb_id}]: HTTP {resp.status_code}")
|
||||
return None
|
||||
return resp.json()
|
||||
|
||||
@classmethod
|
||||
def _search(cls, session, title: str, year_s: str, mtype: str) -> list[dict]:
|
||||
endpoint = "tv" if mtype == "tv" else "movie"
|
||||
extra = {"query": title}
|
||||
if year_s:
|
||||
extra["first_air_date_year" if mtype == "tv" else "year"] = year_s
|
||||
try:
|
||||
resp = session.get(f"https://api.themoviedb.org/3/search/{endpoint}",
|
||||
params=cls._params(extra), timeout=config.TMDB_TIMEOUT)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.warning(f"⚠️ TMDB 搜索异常 [{title}]: {exc}")
|
||||
return []
|
||||
if resp.status_code != 200:
|
||||
log.warning(f"⚠️ TMDB 搜索失败 [{title}]: HTTP {resp.status_code}")
|
||||
return []
|
||||
return resp.json().get("results") or []
|
||||
|
||||
# ------------------------------------------------------------ 对外入口
|
||||
|
||||
@classmethod
|
||||
def search_media(cls, title, year=None, m_type="movie", season_num=None, known_tmdb_id=None):
|
||||
"""取 TMDB 实体,失败返回 None。
|
||||
|
||||
优先级:目录名里的 tmdbid → 缓存 lookup → 在线搜索。
|
||||
返回的实体字段见 core.tmdb_store.build_entity。
|
||||
"""
|
||||
if not config.TMDB_API_KEY:
|
||||
return None
|
||||
|
||||
cache_path = config.TMDB_CACHE_PATH
|
||||
cache_key = f"{m_type}_{title}_{year}"
|
||||
|
||||
# 💡 利用解耦的缓存管理器
|
||||
cached_data = JsonCacheManager.get(cache_path, cache_key)
|
||||
|
||||
if cached_data:
|
||||
if m_type == "tv" and season_num:
|
||||
if season_num not in cached_data.get("season_years", {}):
|
||||
log.info(f"🔄 {title} 缓存缺失新季数 (S{season_num}) 的年份,触发按需增量更新...")
|
||||
tmdb_id = cached_data.get("tmdb_id")
|
||||
if tmdb_id:
|
||||
session = TMDBService._get_session()
|
||||
new_sy = TMDBService._fetch_season_years(session, tmdb_id)
|
||||
|
||||
if "season_years" not in cached_data:
|
||||
cached_data["season_years"] = {}
|
||||
|
||||
if new_sy:
|
||||
cached_data["season_years"].update(new_sy)
|
||||
|
||||
if season_num not in cached_data["season_years"]:
|
||||
cached_data["season_years"][season_num] = year
|
||||
log.debug(f"⚠️ TMDB 暂无 S{season_num} 年份记录,已使用首播年份 ({year}) 兜底并锁定缓存。")
|
||||
|
||||
JsonCacheManager.set(cache_path, cache_key, cached_data)
|
||||
JsonCacheManager.save(cache_path)
|
||||
year_s = str(year).strip() if year else ""
|
||||
path = config.TMDB_CACHE_PATH
|
||||
|
||||
if cache_key not in TMDBService._notified_cache_hits:
|
||||
log.debug(f"⚡ TMDB 缓存命中: {title} ({year})")
|
||||
TMDBService._notified_cache_hits.add(cache_key)
|
||||
return cached_data
|
||||
entity = None
|
||||
if known_tmdb_id:
|
||||
entity = cls._from_id(path, m_type, known_tmdb_id, title, year_s)
|
||||
if entity is None:
|
||||
entity = cls._from_lookup(path, m_type, title, year_s)
|
||||
if entity is None:
|
||||
entity = cls._from_search(path, m_type, title, year_s)
|
||||
if entity is None:
|
||||
return None
|
||||
return cls._ensure_season(entity, season_num, year_s)
|
||||
|
||||
endpoint = "tv" if m_type == "tv" else "movie"
|
||||
url = f"https://api.themoviedb.org/3/search/{endpoint}"
|
||||
params = {"api_key": config.TMDB_API_KEY.strip(), "query": title, "language": config.TMDB_LANGUAGE}
|
||||
|
||||
if year:
|
||||
if m_type == "tv": params["first_air_date_year"] = year
|
||||
else: params["year"] = year
|
||||
# ------------------------------------------------------------ 三条来源
|
||||
|
||||
@classmethod
|
||||
def _from_id(cls, path, mtype, tmdb_id, title, year_s):
|
||||
key = store.entity_key(mtype, tmdb_id)
|
||||
db = store.snapshot(path)
|
||||
entity = db["entities"].get(key)
|
||||
if entity is not None:
|
||||
log.debug(f"⚡ TMDB 命中(目录名 tmdbid): {key}")
|
||||
return entity
|
||||
|
||||
session = cls._get_session()
|
||||
payload = cls._fetch_details(session, mtype, tmdb_id)
|
||||
if not payload:
|
||||
return None
|
||||
entity = store.build_entity(mtype, tmdb_id, payload)
|
||||
cls._save(path, [entity], title, year_s, chosen=entity)
|
||||
return entity
|
||||
|
||||
@classmethod
|
||||
def _from_lookup(cls, path, mtype, title, year_s):
|
||||
db = store.snapshot(path)
|
||||
keys = store.lookup(db, mtype, title, year_s)
|
||||
entities = [db["entities"][k] for k in keys if k in db["entities"]]
|
||||
if not entities:
|
||||
return None
|
||||
|
||||
if len(entities) == 1:
|
||||
mark = (mtype, store.normalize_title(title), year_s)
|
||||
if mark not in cls._notified_cache_hits:
|
||||
log.debug(f"⚡ TMDB 缓存命中: {title} ({year_s or '无年份'})")
|
||||
cls._notified_cache_hits.add(mark)
|
||||
return entities[0]
|
||||
|
||||
log.info(f"🔀 缓存里「{title}」({year_s or '无年份'}) 有 {len(entities)} 个候选")
|
||||
return cls._choose(entities, title, year_s)
|
||||
|
||||
@classmethod
|
||||
def _from_search(cls, path, mtype, title, year_s):
|
||||
session = cls._get_session()
|
||||
log.debug(f"🌐 请求 TMDB 搜索: {title} ({year_s or '无年份'})")
|
||||
results = cls._search(session, title, year_s, mtype)
|
||||
if not results:
|
||||
log.warning(f"⚠️ TMDB 未搜到: {title}")
|
||||
return None
|
||||
|
||||
target = store.normalize_title(title)
|
||||
exact = [
|
||||
r for r in results
|
||||
if store.normalize_title(r.get("title") or r.get("name") or "") == target
|
||||
or store.normalize_title(r.get("original_title") or r.get("original_name") or "") == target
|
||||
]
|
||||
pool = (exact or results)[:5]
|
||||
|
||||
entities = []
|
||||
for result in pool:
|
||||
payload = cls._fetch_details(session, mtype, result.get("id"))
|
||||
if not payload:
|
||||
continue
|
||||
entities.append(store.build_entity(mtype, result["id"], payload))
|
||||
if not entities:
|
||||
return None
|
||||
|
||||
if len(entities) == 1:
|
||||
chosen = entities[0]
|
||||
elif exact:
|
||||
# 精确标题匹配后仍有多条(如「苍兰诀」真人版 + 动漫版)→ 才问
|
||||
log.info(f"🔀 「{title}」精确匹配到 {len(entities)} 个候选,需要确认")
|
||||
chosen = cls._choose(entities, title, year_s)
|
||||
else:
|
||||
log.warning(f"⚠️ 「{title}」没有精确匹配,{len(entities)} 个候选取热度最高者"
|
||||
f"(tmdbid-{entities[0]['tmdb_id']}),如有误请核对")
|
||||
chosen = entities[0]
|
||||
|
||||
cls._save(path, entities, title, year_s, chosen)
|
||||
return chosen
|
||||
|
||||
# ------------------------------------------------------------ 选择与落库
|
||||
|
||||
@classmethod
|
||||
def _choose(cls, entities, title, year_s):
|
||||
"""候选并列时才走到这里:交互模式让用户选,否则取第一个(搜索热度顺序)。"""
|
||||
for idx, ent in enumerate(entities, 1):
|
||||
genres = "/".join(g["name"] for g in ent["details"].get("genres", [])[:3]) or "-"
|
||||
seasons = len(ent.get("season_years") or {})
|
||||
tail = f" {seasons} 季" if ent["type"] == "tv" and seasons else ""
|
||||
print(f" {idx}. {ent['type']}/{ent['tmdb_id']} {ent['title']} "
|
||||
f"({ent.get('year') or '?'}) {genres}{tail}")
|
||||
|
||||
if sys.stdin.isatty():
|
||||
try:
|
||||
raw = input(f" ➤ 选择编号(1-{len(entities)},回车默认 1): ").strip()
|
||||
if raw.isdigit() and 1 <= int(raw) <= len(entities):
|
||||
return entities[int(raw) - 1]
|
||||
except (EOFError, KeyboardInterrupt):
|
||||
pass
|
||||
log.warning(f"⚠️ 未选择,取热度最高者({title} {year_s or '无年份'} → "
|
||||
f"tmdbid-{entities[0]['tmdb_id']})")
|
||||
return entities[0]
|
||||
|
||||
@classmethod
|
||||
def _save(cls, path, entities, title, year_s, chosen):
|
||||
keys = [store.entity_key(e["type"], e["tmdb_id"]) for e in entities]
|
||||
years = set()
|
||||
if year_s:
|
||||
years.add(year_s)
|
||||
chosen_year = str(chosen.get("year") or "")
|
||||
if chosen_year:
|
||||
years.add(chosen_year)
|
||||
if not year_s:
|
||||
years.add("") # 未给年份的搜索:同时维护空年份桶
|
||||
|
||||
try:
|
||||
session = TMDBService._get_session()
|
||||
log.debug(f"🌐 请求 TMDB [{endpoint.upper()}]: {title}")
|
||||
resp = session.get(url, params=params, timeout=config.TMDB_TIMEOUT)
|
||||
data = resp.json()
|
||||
|
||||
if resp.status_code == 200 and data.get('results'):
|
||||
res = data['results'][0]
|
||||
orig = res.get('original_name') if m_type == "tv" else res.get('original_title')
|
||||
|
||||
clean_orig = StringUtil.sanitize_title(orig)
|
||||
tmdb_id = res.get('id')
|
||||
|
||||
result = {
|
||||
"original_title": clean_orig,
|
||||
"tmdb_id": tmdb_id
|
||||
}
|
||||
|
||||
if m_type == "tv" and tmdb_id:
|
||||
result["season_years"] = TMDBService._fetch_season_years(session, tmdb_id)
|
||||
if season_num and season_num not in result["season_years"]:
|
||||
result["season_years"][season_num] = year
|
||||
with store.transaction(path) as db:
|
||||
for entity in entities:
|
||||
store.put_entity(db, entity)
|
||||
store.merge_candidates(db, chosen["type"], title, years, keys)
|
||||
except OSError as exc:
|
||||
log.warning(f"⚠️ TMDB 缓存写入失败(不影响本次处理): {exc}")
|
||||
|
||||
JsonCacheManager.set(cache_path, cache_key, result)
|
||||
JsonCacheManager.save(cache_path)
|
||||
return result
|
||||
except Exception as e:
|
||||
log.error(f"TMDB 异常 [{title}]: {e}")
|
||||
return None
|
||||
# ------------------------------------------------------------ 季年份
|
||||
|
||||
@classmethod
|
||||
def _ensure_season(cls, entity, season_num, year_s):
|
||||
"""剧集缺某一季的年份时按需补拉(旧行为保留),并写入缓存。"""
|
||||
if entity.get("type") != "tv" or not season_num:
|
||||
return entity
|
||||
|
||||
season_years = entity.setdefault("season_years", {})
|
||||
if season_num in season_years:
|
||||
return entity
|
||||
|
||||
log.info(f"🔄 缓存缺少 S{season_num} 的年份,按需补拉剧集详情...")
|
||||
session = cls._get_session()
|
||||
payload = cls._fetch_details(session, "tv", entity["tmdb_id"])
|
||||
if payload:
|
||||
merged = store.season_years_from(payload)
|
||||
merged.update({k: v for k, v in season_years.items() if v})
|
||||
entity["season_years"] = merged
|
||||
season_years = merged
|
||||
if season_num not in season_years and year_s:
|
||||
season_years[season_num] = year_s
|
||||
|
||||
try:
|
||||
with store.transaction(config.TMDB_CACHE_PATH) as db:
|
||||
store.put_entity(db, entity)
|
||||
except OSError as exc:
|
||||
log.warning(f"⚠️ 补季写入失败: {exc}")
|
||||
return entity
|
||||
|
||||
Reference in New Issue
Block a user