refactor(services): 引入 FileOpsService,统一 ffprobe 与缓存调用

- 新增 services/fileops.py:用 shutil.move 取代 Path.rename,解决跨盘/跨 Docker 卷移动报 Invalid cross-device link
- task.py:季目录与根目录改名统一交给 FileOpsService,任务结构统一为 (old, new) 元组
- mediainfo/metadata/subtitle:ffprobe 调用收敛到 FFprobeUtil,去掉重复的 json.loads 与 stderr 处理
- subtitle:内置字幕提取、外挂字幕转换增加"目标已存在且非空则跳过"的幂等保护
- tmdb:缓存读写迁移到 JsonCacheManager,移除类内静态缓存状态
This commit is contained in:
Hraulein
2026-11-17 11:32:40 +08:00
parent dfee0049fb
commit 53fdb1572c
6 changed files with 79 additions and 88 deletions
+16 -40
View File
@@ -1,31 +1,15 @@
# src/services/tmdb.py
import json
import requests
import re
from pathlib import Path
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:
_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 = {}
@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')
_notified_cache_hits = set()
@staticmethod
def _get_session():
@@ -36,7 +20,6 @@ class TMDBService:
@classmethod
def _fetch_season_years(cls, session, tmdb_id):
"""🛠️ 专属辅助方法:根据 ID 获取所有季的年份字典"""
details_url = f"https://api.themoviedb.org/3/tv/{tmdb_id}"
season_years = {}
try:
@@ -52,17 +35,17 @@ class TMDBService:
return season_years
@staticmethod
def search_media(title, year=None, m_type="movie", season_num=None): # 💡 1. 接收 season_num 传入
def search_media(title, year=None, m_type="movie", season_num=None):
if not config.TMDB_API_KEY:
return None
TMDBService._load_cache()
cache_path = config.TMDB_CACHE_PATH
cache_key = f"{m_type}_{title}_{year}"
if cache_key in TMDBService._cache:
cached_data = TMDBService._cache[cache_key]
# 💡 2. 局部缓存穿透检测与按需更新
# 💡 利用解耦的缓存管理器
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}) 的年份,触发按需增量更新...")
@@ -74,27 +57,21 @@ class TMDBService:
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}) 兜底并锁定缓存。")
TMDBService._save_cache()
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}
@@ -113,7 +90,7 @@ class TMDBService:
res = data['results'][0]
orig = 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 ""
clean_orig = StringUtil.sanitize_title(orig)
tmdb_id = res.get('id')
result = {
@@ -121,16 +98,15 @@ class TMDBService:
"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
TMDBService._cache[cache_key] = result
TMDBService._save_cache()
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
return None