# src/services/tmdb.py import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry from core import config from core.logger import log from core.utils import StringUtil from core.cache import JsonCacheManager # 💡 接入统一缓存层 class TMDBService: _notified_cache_hits = set() @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 @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): 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) 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 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 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 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