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
+24
View File
@@ -0,0 +1,24 @@
# src/services/fileops.py
import shutil
from pathlib import Path
from core.logger import log
class FileOpsService:
"""纯粹的物理层文件与目录操作服务"""
@staticmethod
def move_file(old_path: Path, new_path: Path):
"""执行物理重命名/移动任务,并记录审计日志。接入 shutil.move 保障跨盘跨 Docker 卷的安全"""
if old_path.exists() and old_path != new_path:
# 物理层变更审计:检测并创建缺失的目录
if not new_path.parent.exists():
log.info(f"🆕 发现目标目录不存在,正在执行物理创建: {new_path.parent.absolute()}")
new_path.parent.mkdir(parents=True, exist_ok=True)
try:
# 💡 替换掉了脆弱的 old_path.rename()
shutil.move(str(old_path), str(new_path))
except Exception as e:
log.error(f"❌ 跨盘或物理移动失败 [源: {old_path.name}] -> [异常: {e}]")
raise e
+7 -13
View File
@@ -1,9 +1,8 @@
# src/services/mediainfo.py
import json
import subprocess
from pathlib import Path
from core import config
from core.utils import FFprobeUtil
class MediaInfoService:
@staticmethod
@@ -15,43 +14,38 @@ class MediaInfoService:
"""
利用 ffprobe 获取专业 Scene 技术标签及判定是否为 REMUX
"""
cmd = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", str(f_path)]
# 兜底默认值
tags = {
"res": "1080p", "v_codec": "H264", "bits": "8bit",
"a_info": "AAC.2.0", "is_remux": False
}
try:
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
data = json.loads(res.stdout)
# 💡 重构:直接调用 FFprobeUtil
data = FFprobeUtil.get_json(f_path, "-show_format", "-show_streams")
if not data:
return tags
try:
duration = float(data.get('format', {}).get('duration', 0))
if duration > 0:
size_bytes = f_path.stat().st_size
mbps = (size_bytes * 8) / duration / 1_000_000
# 💡 就是漏了下面这一行!找回丢失的视频流数据!
v_stream = next((s for s in data.get('streams', []) if s['codec_type'] == 'video'), {})
h = int(v_stream.get('height', 1080)) if v_stream.get('height') else 1080
# 接入动态码率阈值
if (h > 2000 and mbps > config.REMUX_BITRATE_4K) or (h <= 2000 and mbps > config.REMUX_BITRATE_1080P):
tags['is_remux'] = True
# 技术标签提取
tags['res'] = "2160p" if h > 2000 else ("1080p" if h > 700 else "720p")
codec_name = v_stream.get('codec_name', '')
if '265' in codec_name or 'hevc' in codec_name:
tags['v_codec'] = "HEVC"
# 位深判定
if '10' in v_stream.get('pix_fmt', '') or '12' in v_stream.get('pix_fmt', ''):
tags['bits'] = "10bit"
# 音轨提取
a_stream = next((s for s in data.get('streams', []) if s['codec_type'] == 'audio'), {})
a_codec_raw = a_stream.get('codec_name', 'AAC').upper()
if 'DTS' in a_codec_raw: a_cod = 'DTS'
@@ -65,4 +59,4 @@ class MediaInfoService:
except Exception:
pass
return tags
return tags
+7 -7
View File
@@ -1,16 +1,15 @@
# src/services/metadata.py
import json
import subprocess
from pathlib import Path
from core import config
from core.utils import FFprobeUtil
class MetadataService:
@staticmethod
def scan_ads(file_path: Path, task_mgr):
if file_path.suffix.lower() != ".mkv": return
cmd = ["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream_tags=title", "-of", "csv=p=0:nk=1", str(file_path)]
# 💡 补上 stderr=subprocess.DEVNULL 堵住 FFmpeg 的底层报错
video_title = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True).stdout.strip()
if any(ad in video_title for ad in config.AD_KEYWORDS):
@@ -29,11 +28,12 @@ class MetadataService:
if f_path.suffix.lower() != '.mkv':
return
cmd = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_streams", "-select_streams", "a", str(f_path)]
# 💡 补上 stderr=subprocess.DEVNULL
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
# 💡 重构:直接调用 FFprobeUtil
data = FFprobeUtil.get_json(f_path, "-show_streams", "-select_streams", "a")
if not data:
return
try:
data = json.loads(res.stdout)
streams = data.get('streams', [])
if len(streams) != 2:
@@ -75,4 +75,4 @@ class MetadataService:
"--edit", f"track:a{c_idx}", "--set", "flag-default=1",
"--edit", f"track:a{m_idx}", "--set", "flag-default=0"
]
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+17 -11
View File
@@ -1,22 +1,21 @@
# src/services/subtitle.py
import re
import json
import subprocess
from pathlib import Path
import pysubs2
from core import config
from core.logger import log
from core.utils import FFprobeUtil
class SubtitleService:
# 💡 NEW: 新增专属的格式转换方法
@staticmethod
def convert_to_srt(in_sub: Path, out_srt: Path):
"""将非 srt 的外挂字幕洗白并转换为 srt,成功后抹除源文件"""
"""将非 srt 的外挂字幕洗白并转换为 srt,安全保留源文件"""
try:
subs = pysubs2.load(str(in_sub), encoding="utf-8")
for line in subs:
# 洗白特效标签
line.text = re.sub(r'\{.*?\}', '', line.text)
subs.save(str(out_srt), format="srt", encoding="utf-8")
@@ -25,11 +24,11 @@ class SubtitleService:
@staticmethod
def scan_subtitles(file_path: Path, task_mgr, target_stem: str, dest_dir: Path):
cmd = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_streams", "-select_streams", "s", str(file_path)]
data = FFprobeUtil.get_json(file_path, "-show_streams", "-select_streams", "s")
if not data:
return
try:
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
data = json.loads(res.stdout)
data = json.loads(res.stdout)
streams = data.get('streams', [])
lang_counts = {}
@@ -57,15 +56,21 @@ class SubtitleService:
if lang_code == "und" and lang != "und":
lang_code = lang[:3]
# 💡 核心新增:语言白名单拦截系统
if config.EXTRACT_SUBTITLE_LANGUAGES and lang_code not in config.EXTRACT_SUBTITLE_LANGUAGES:
continue
lang_counts[lang_code] = lang_counts.get(lang_code, 0) + 1
lang_suffix = "" if lang_counts[lang_code] == 1 else f".{lang_counts[lang_code]}"
# 💡 核心修改 1.1:加上 .internal 标签,明确表示是由内置流提取的
desired_out_srt = dest_dir / f"{target_stem}.internal.{lang_code}{lang_suffix}.srt"
# ==========================================
# 🛡️ 恢复丢失的内置提取前置拦截器
# ==========================================
if desired_out_srt.exists() and desired_out_srt.stat().st_size > 0:
log.debug(f"✨ [跳过提取] 目标内置字幕已存在,触发幂等保护: {desired_out_srt.name}")
continue
out_srt = task_mgr.reserve_path(desired_out_srt)
temp_ass = dest_dir / f"{target_stem}.temp.{out_srt.name}.ass"
@@ -94,4 +99,5 @@ class SubtitleService:
finally:
temp_ass.unlink(missing_ok=True)
else:
temp_ass.unlink(missing_ok=True)
temp_ass.unlink(missing_ok=True)
+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