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:
+7
-16
@@ -1,7 +1,9 @@
|
||||
# src/core/task.py
|
||||
|
||||
from pathlib import Path
|
||||
from .logger import log
|
||||
from core.logger import log
|
||||
# 💡 解耦:引入专门的文件操作服务
|
||||
from services.fileops import FileOpsService
|
||||
|
||||
class TaskManager:
|
||||
def __init__(self):
|
||||
@@ -15,13 +17,10 @@ class TaskManager:
|
||||
def has_tasks(self) -> bool:
|
||||
return any(self.tasks.values())
|
||||
|
||||
# 💡 增加 source_path,如果存在的文件就是自己,就不需要加 .2 防撞
|
||||
def reserve_path(self, desired_path: Path, source_path: Path = None) -> Path:
|
||||
if not hasattr(self, 'claimants'):
|
||||
self.claimants = {}
|
||||
|
||||
# 💡 终极防卫:认主机制(幂等性校验)
|
||||
# 如果这个坑位已经被占了,并且占坑的人就是“当前申请人”自己,直接返回原路径,绝不自己撞自己!
|
||||
source_name = source_path.name if source_path else "未知"
|
||||
if desired_path in self.reserved_paths:
|
||||
if self.claimants.get(str(desired_path.resolve())) == source_name:
|
||||
@@ -59,22 +58,21 @@ class TaskManager:
|
||||
def add_extract(self, desc, func, args): self.tasks['extract'].append((desc, func, args))
|
||||
def add_clean(self, desc, func, args): self.tasks['clean'].append((desc, func, args))
|
||||
def add_file_rename(self, desc, func, args): self.tasks['rename_file'].append((desc, func, args))
|
||||
|
||||
def add_season_dir_rename(self, old_dir, new_dir):
|
||||
if old_dir not in self.dir_renames:
|
||||
# 💡 补上 [季目录] 前缀
|
||||
desc = f"[季目录] {old_dir.name} --> {new_dir.name}"
|
||||
self.tasks['rename_season_dir'].append((desc, old_dir.rename, new_dir))
|
||||
# 💡 强制使用 FileOpsService 统一接管物理移动
|
||||
self.tasks['rename_season_dir'].append((desc, FileOpsService.move_file, (old_dir, new_dir)))
|
||||
self.dir_renames.add(old_dir)
|
||||
|
||||
def add_root_dir_rename(self, old_dir, new_dir):
|
||||
if old_dir not in self.dir_renames:
|
||||
# 💡 补上 [根目录] 前缀
|
||||
desc = f"[根目录] {old_dir.name} --> {new_dir.name}"
|
||||
self.tasks['rename_root_dir'].append((desc, old_dir.rename, new_dir))
|
||||
self.tasks['rename_root_dir'].append((desc, FileOpsService.move_file, (old_dir, new_dir)))
|
||||
self.dir_renames.add(old_dir)
|
||||
|
||||
def preview_and_confirm(self, auto_execute=False) -> bool:
|
||||
# 💡 去掉了原来的 all_empty 相关的逻辑,因为现在会在外部提前拦截
|
||||
if not auto_execute:
|
||||
log.info("==================== 待执行任务预览 ====================")
|
||||
|
||||
@@ -106,7 +104,6 @@ class TaskManager:
|
||||
if ans in ['n', 'q']:
|
||||
log.debug("用户取消任务执行。")
|
||||
return False
|
||||
# elif ans in ['y', '']: # 包含直接敲回车的情况
|
||||
elif ans in ['y']:
|
||||
log.debug("用户确认执行任务。")
|
||||
return True
|
||||
@@ -119,24 +116,18 @@ class TaskManager:
|
||||
if not self.tasks[cat]: continue
|
||||
for desc, func, arg in self.tasks[cat]:
|
||||
try:
|
||||
# 💡 针对重命名操作,开启详细物理路径追踪
|
||||
if cat in ['rename_file', 'rename_season_dir', 'rename_root_dir']:
|
||||
# 智能提取原始路径和目标路径
|
||||
old_p = arg[0] if isinstance(arg, tuple) else getattr(func, '__self__', None)
|
||||
new_p = arg[1] if isinstance(arg, tuple) else arg
|
||||
|
||||
if old_p and hasattr(old_p, 'exists') and old_p.exists():
|
||||
if old_p.resolve() != new_p.resolve():
|
||||
# 执行物理变更
|
||||
if isinstance(arg, tuple): func(*arg)
|
||||
else: func(arg)
|
||||
|
||||
# 💡 记录全景绝对路径日志
|
||||
log.info(f"✅ 重命名成功: [源] {old_p.absolute()} --> [终] {new_p.absolute()}")
|
||||
else:
|
||||
log.warning(f"⚠️ 跳过重命名,源路径不存在: {old_p}")
|
||||
else:
|
||||
# 对于非重命名任务(清理、提取等),保持常规日志
|
||||
action_name = desc.split(' -->')[0]
|
||||
log.info(f"⚙️ 正在执行 -> {action_name}")
|
||||
if isinstance(arg, tuple): func(*arg)
|
||||
|
||||
@@ -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
|
||||
@@ -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'
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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"
|
||||
@@ -95,3 +100,4 @@ class SubtitleService:
|
||||
temp_ass.unlink(missing_ok=True)
|
||||
else:
|
||||
temp_ass.unlink(missing_ok=True)
|
||||
|
||||
|
||||
+14
-38
@@ -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]
|
||||
# 💡 利用解耦的缓存管理器
|
||||
cached_data = JsonCacheManager.get(cache_path, cache_key)
|
||||
|
||||
# 💡 2. 局部缓存穿透检测与按需更新
|
||||
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
|
||||
|
||||
|
||||
Reference in New Issue
Block a user