update 202605101839
This commit is contained in:
+75
-40
@@ -2,6 +2,7 @@
|
||||
|
||||
import json
|
||||
import requests
|
||||
import re
|
||||
from pathlib import Path
|
||||
from requests.adapters import HTTPAdapter
|
||||
from urllib3.util.retry import Retry
|
||||
@@ -9,25 +10,20 @@ from core import config
|
||||
from core.logger import log
|
||||
|
||||
class TMDBService:
|
||||
# 💡 缓存文件路径放在根目录
|
||||
_cache_file = Path(__file__).parent.parent.parent / 'tmdb_cache.json'
|
||||
_cache_file = config.TMDB_CACHE_PATH
|
||||
_cache = None
|
||||
_notified_cache_hits = set() # 💡 新增:用于记录已经打印过“缓存命中”的键值,防止刷屏
|
||||
|
||||
@classmethod
|
||||
def _load_cache(cls):
|
||||
"""加载本地缓存"""
|
||||
if cls._cache is None:
|
||||
if cls._cache_file.exists():
|
||||
try:
|
||||
cls._cache = json.loads(cls._cache_file.read_text('utf-8'))
|
||||
except:
|
||||
cls._cache = {}
|
||||
else:
|
||||
cls._cache = {}
|
||||
try: cls._cache = json.loads(cls._cache_file.read_text('utf-8'))
|
||||
except: cls._cache = {}
|
||||
else: cls._cache = {}
|
||||
|
||||
@classmethod
|
||||
def _save_cache(cls):
|
||||
"""保存到本地缓存"""
|
||||
if cls._cache is not None:
|
||||
cls._cache_file.write_text(json.dumps(cls._cache, ensure_ascii=False, indent=2), 'utf-8')
|
||||
|
||||
@@ -38,64 +34,103 @@ class TMDBService:
|
||||
s.mount('https://', HTTPAdapter(max_retries=retries))
|
||||
return s
|
||||
|
||||
@classmethod
|
||||
def _fetch_season_years(cls, session, tmdb_id):
|
||||
"""🛠️ 专属辅助方法:根据 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"):
|
||||
"""
|
||||
智能搜索接口:自动区分电影/电视剧,并接入本地缓存
|
||||
"""
|
||||
def search_media(title, year=None, m_type="movie", season_num=None): # 💡 1. 接收 season_num 传入
|
||||
if not config.TMDB_API_KEY:
|
||||
log.debug("TMDB API Key 未配置,跳过在线刮削")
|
||||
return None
|
||||
|
||||
# 💡 1. 拦截层:检查本地缓存
|
||||
TMDBService._load_cache()
|
||||
cache_key = f"{m_type}_{title}_{year}"
|
||||
|
||||
if cache_key in TMDBService._cache:
|
||||
log.debug(f"⚡ 命中 TMDB 本地缓存: {title} ({year})")
|
||||
return TMDBService._cache[cache_key]
|
||||
cached_data = TMDBService._cache[cache_key]
|
||||
|
||||
# 💡 2. 局部缓存穿透检测与按需更新
|
||||
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"] = {}
|
||||
|
||||
# 合并 TMDB 返回的最新数据
|
||||
if new_sy:
|
||||
cached_data["season_years"].update(new_sy)
|
||||
|
||||
# 🛡️ 3. 终极防御:负向缓存 (Negative Cache)
|
||||
# 如果 TMDB 上目前确实连这部剧的第四季条目都没有创建,
|
||||
# 为了防止后续 E02、E03 疯狂请求接口引发雪崩限流,我们用首播年份给它强行占个坑
|
||||
if season_num not in cached_data["season_years"]:
|
||||
cached_data["season_years"][season_num] = year
|
||||
log.debug(f"⚠️ TMDB 暂无 S{season_num} 年份记录,已使用首播年份 ({year}) 兜底并锁定缓存。")
|
||||
|
||||
# 💡 2. 路由层:分流 Movie 和 TV 接口
|
||||
TMDBService._save_cache()
|
||||
|
||||
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}
|
||||
|
||||
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
|
||||
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} ({year})")
|
||||
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')
|
||||
|
||||
# 💡 电视剧取 original_name,电影取 original_title
|
||||
original_title = res.get('original_name') if m_type == "tv" else res.get('original_title')
|
||||
clean_orig = re.sub(r'[\\/*?:"<>|,!&:,!?、\s]+|\.+', '.', orig.replace("'", "").replace("’", "")).strip('.') if orig else ""
|
||||
tmdb_id = res.get('id')
|
||||
|
||||
result = {
|
||||
"english_title": original_title.replace(' ', '.') if original_title else "",
|
||||
"tmdb_id": res.get('id')
|
||||
"original_title": clean_orig,
|
||||
"tmdb_id": tmdb_id
|
||||
}
|
||||
|
||||
# 💡 3. 存储层:写回缓存并持久化
|
||||
# 首次全量拉取
|
||||
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
|
||||
|
||||
TMDBService._cache[cache_key] = result
|
||||
TMDBService._save_cache()
|
||||
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
log.error(f"TMDB 请求异常 [{title}]: {str(e)[:100]}...")
|
||||
|
||||
log.error(f"TMDB 异常 [{title}]: {e}")
|
||||
return None
|
||||
Reference in New Issue
Block a user