update
This commit is contained in:
@@ -0,0 +1,101 @@
|
||||
# src/services/tmdb.py
|
||||
|
||||
import json
|
||||
import requests
|
||||
from pathlib import Path
|
||||
from requests.adapters import HTTPAdapter
|
||||
from urllib3.util.retry import Retry
|
||||
from core import config
|
||||
from core.logger import log
|
||||
|
||||
class TMDBService:
|
||||
# 💡 缓存文件路径放在根目录
|
||||
_cache_file = Path(__file__).parent.parent.parent / 'tmdb_cache.json'
|
||||
_cache = None
|
||||
|
||||
@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 = {}
|
||||
|
||||
@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')
|
||||
|
||||
@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 search_media(title, year=None, m_type="movie"):
|
||||
"""
|
||||
智能搜索接口:自动区分电影/电视剧,并接入本地缓存
|
||||
"""
|
||||
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]
|
||||
|
||||
# 💡 2. 路由层:分流 Movie 和 TV 接口
|
||||
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} ({year})")
|
||||
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]
|
||||
|
||||
# 💡 电视剧取 original_name,电影取 original_title
|
||||
original_title = res.get('original_name') if m_type == "tv" else res.get('original_title')
|
||||
|
||||
result = {
|
||||
"english_title": original_title.replace(' ', '.') if original_title else "",
|
||||
"tmdb_id": res.get('id')
|
||||
}
|
||||
|
||||
# 💡 3. 存储层:写回缓存并持久化
|
||||
TMDBService._cache[cache_key] = result
|
||||
TMDBService._save_cache()
|
||||
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
log.error(f"TMDB 请求异常 [{title}]: {str(e)[:100]}...")
|
||||
|
||||
return None
|
||||
Reference in New Issue
Block a user