- 详情 404 的 tmdb id 记入 _dead_ids,后续文件直接跳过(DEBUG 日志), 不再逐集重复请求 - 搜索无结果的 (类型, 标题, 年份) 记入 _failed_searches,同一标题只搜一次 - 起因:知否知否 (DVD版) 的 [tmdbid-309718] 在 TMDB 已不存在(迁移时那 4 个 失效 id 之一),62 集每集都重走「详情404 + 中文搜 + 英文名搜」流程, 窗口被刷屏;修复后同一目录只产生 1 次 404 + 2 次搜索 - 控制台是 INFO 级,跳过日志为 DEBUG,只在日志文件留痕
265 lines
11 KiB
Python
265 lines
11 KiB
Python
# 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
|
||
|
||
|
||
class TMDBService:
|
||
_notified_cache_hits = set()
|
||
# 本进程内的「负缓存」:同一个目录的每一集都会重复调用 search_media,
|
||
# 失败结果不记住的话,一个 60 集的剧会白跑 180 次请求。
|
||
_dead_ids = set() # 详情 404 的 tmdb id
|
||
_failed_searches = 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])
|
||
s.mount('https://', HTTPAdapter(max_retries=retries))
|
||
return s
|
||
|
||
@staticmethod
|
||
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:
|
||
try:
|
||
cache_key = (mtype, int(tmdb_id))
|
||
except (TypeError, ValueError):
|
||
return None
|
||
if cache_key in cls._dead_ids:
|
||
log.debug(f"⏭ 跳过已确认失效的 TMDB id: {mtype}/{tmdb_id}")
|
||
return 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 == 404:
|
||
# 目录名里的 tmdbid 已失效(TMDB 侧删除/合并),本次运行不再重试
|
||
cls._dead_ids.add(cache_key)
|
||
log.warning(f"⚠️ TMDB id 已失效(404),本次运行不再重试: {mtype}/{tmdb_id}")
|
||
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
|
||
|
||
year_s = str(year).strip() if year else ""
|
||
path = config.TMDB_CACHE_PATH
|
||
|
||
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)
|
||
|
||
# ------------------------------------------------------------ 三条来源
|
||
|
||
@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):
|
||
search_key = (mtype, store.normalize_title(title), year_s)
|
||
if search_key in cls._failed_searches:
|
||
log.debug(f"⏭ 跳过本进程内已失败过的搜索: {title} ({year_s or '无年份'})")
|
||
return None
|
||
|
||
session = cls._get_session()
|
||
log.debug(f"🌐 请求 TMDB 搜索: {title} ({year_s or '无年份'})")
|
||
results = cls._search(session, title, year_s, mtype)
|
||
if not results:
|
||
cls._failed_searches.add(search_key)
|
||
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:
|
||
cls._failed_searches.add(search_key)
|
||
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:
|
||
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}")
|
||
|
||
# ------------------------------------------------------------ 季年份
|
||
|
||
@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
|