update 202605101839
This commit is contained in:
@@ -3,11 +3,11 @@
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from core import config
|
||||
|
||||
class MediaInfoService:
|
||||
@staticmethod
|
||||
def get_info(file_path: Path):
|
||||
# 兼容旧的方法,这里可以保留空或返回基础信息
|
||||
return {}
|
||||
|
||||
@staticmethod
|
||||
@@ -16,25 +16,27 @@ 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:
|
||||
# 💡 将 stderr 丢进 DEVNULL,强行让 ffprobe 的警告闭嘴
|
||||
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
|
||||
data = json.loads(res.stdout)
|
||||
|
||||
# REMUX 判定逻辑:计算真实物理码率
|
||||
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
|
||||
|
||||
@@ -45,11 +47,11 @@ class MediaInfoService:
|
||||
if '265' in codec_name or 'hevc' in codec_name:
|
||||
tags['v_codec'] = "HEVC"
|
||||
|
||||
# 修改 get_scene_tags 内部的位深判定
|
||||
# 位深判定
|
||||
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,4 +1,4 @@
|
||||
# python/services/metadata_srv.py
|
||||
# src/services/metadata.py
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
@@ -10,7 +10,8 @@ class MetadataService:
|
||||
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)]
|
||||
video_title = subprocess.run(cmd, stdout=subprocess.PIPE, text=True).stdout.strip()
|
||||
# 💡 补上 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):
|
||||
task_mgr.add_clean(
|
||||
@@ -21,21 +22,20 @@ class MetadataService:
|
||||
|
||||
@staticmethod
|
||||
def do_clear(file_path):
|
||||
subprocess.run(["mkvpropedit", str(file_path), "--edit", "track:v1", "--delete", "name"], stdout=subprocess.DEVNULL)
|
||||
subprocess.run(["mkvpropedit", str(file_path), "--edit", "track:v1", "--delete", "name"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
# 👇👇👇 新增:音轨智能钦定逻辑 👇👇👇
|
||||
@staticmethod
|
||||
def scan_audio_tracks(f_path: Path, task_mgr):
|
||||
if f_path.suffix.lower() != '.mkv':
|
||||
return
|
||||
|
||||
cmd = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_streams", "-select_streams", "a", str(f_path)]
|
||||
res = subprocess.run(cmd, stdout=subprocess.PIPE, text=True)
|
||||
# 💡 补上 stderr=subprocess.DEVNULL
|
||||
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
|
||||
try:
|
||||
data = json.loads(res.stdout)
|
||||
streams = data.get('streams', [])
|
||||
|
||||
# 💡 严格遵守需求:例外:如果有第三条或以上音轨,或只有一条,则不操作
|
||||
if len(streams) != 2:
|
||||
return
|
||||
|
||||
@@ -43,24 +43,20 @@ class MetadataService:
|
||||
mandarin_aid = None
|
||||
|
||||
for i, s in enumerate(streams):
|
||||
a_idx = i + 1 # 对应 mkvpropedit 的 track:a1, track:a2
|
||||
a_idx = i + 1
|
||||
lang = s.get('tags', {}).get('language', '').lower()
|
||||
title = s.get('tags', {}).get('title', '').lower()
|
||||
is_default = s.get('disposition', {}).get('default', 0)
|
||||
|
||||
# 识别粤语
|
||||
if '粤' in title or lang == 'yue':
|
||||
cantonese_aid = (a_idx, is_default)
|
||||
# 识别国语/普通话
|
||||
elif '国' in title or '普' in title or lang in ['cmn', 'chi', 'zho']:
|
||||
mandarin_aid = (a_idx, is_default)
|
||||
|
||||
# 如果确实是一国一粤的经典配置
|
||||
if cantonese_aid and mandarin_aid and cantonese_aid[0] != mandarin_aid[0]:
|
||||
c_idx, c_def = cantonese_aid
|
||||
m_idx, m_def = mandarin_aid
|
||||
|
||||
# 如果粤语已经是唯一的 default,且国语不是 default,直接跳过
|
||||
if c_def == 1 and m_def == 0:
|
||||
return
|
||||
|
||||
@@ -74,7 +70,6 @@ class MetadataService:
|
||||
|
||||
@staticmethod
|
||||
def do_set_default_audio(f_path, c_idx, m_idx):
|
||||
# 瞬间修改 MKV 头部元数据
|
||||
cmd = [
|
||||
"mkvpropedit", str(f_path),
|
||||
"--edit", f"track:a{c_idx}", "--set", "flag-default=1",
|
||||
|
||||
+114
-59
@@ -8,39 +8,52 @@ from core import config
|
||||
from core.logger import log
|
||||
|
||||
class RenamerService:
|
||||
|
||||
@staticmethod
|
||||
def infer_structure(file_path: Path, context_cache: dict):
|
||||
def infer_structure(file_path: Path, context_cache: dict, forced_type: str = None):
|
||||
parent_name = file_path.parent.name
|
||||
grandparent_name = file_path.parent.parent.name
|
||||
|
||||
# 1. 标准季目录识别
|
||||
season_match = re.match(r'^(?:S(?:eason)?[\s\-\_]*)?(\d{1,2})$', parent_name, re.IGNORECASE)
|
||||
|
||||
if season_match:
|
||||
m_type, season_num = "tv", season_match.group(1).zfill(2)
|
||||
target_season_folder = f"Season {season_num}"
|
||||
target_name, root_dir_path = grandparent_name, file_path.parent.parent
|
||||
else:
|
||||
# 💡 2. 扁平电视节目嗅探 (Flat TV Show)
|
||||
flat_tv_match = re.search(r'S(\d{1,2})E\d{1,3}|(?<!\d)(?:EP|E|第)(\d{1,3})(?:集)?(?!\d)', file_path.stem, re.IGNORECASE)
|
||||
pure_number_match = re.fullmatch(r'\d{1,3}', file_path.stem)
|
||||
flat_tv_match = re.search(r'S(\d{1,2})E\d{1,3}|(?<!\d)(?:EP|E|第)(\d{1,3})(?:集)?(?!\d)', file_path.stem, re.IGNORECASE)
|
||||
pure_number_match = re.fullmatch(r'\d{1,3}', file_path.stem)
|
||||
|
||||
if flat_tv_match or pure_number_match:
|
||||
m_type = "tv"
|
||||
season_num = (flat_tv_match.group(1) if flat_tv_match and flat_tv_match.lastindex >= 1 and flat_tv_match.group(1) else "01").zfill(2)
|
||||
target_season_folder = None # 🛡️ 核心保护:设为 None 表示禁止重命名父目录
|
||||
target_name, root_dir_path = parent_name, file_path.parent
|
||||
# 💡 核心改动:最高优先级判断 forced_type
|
||||
if forced_type == "tv" or (not forced_type and season_match):
|
||||
m_type = "tv"
|
||||
if season_match:
|
||||
season_num = season_match.group(1).zfill(2)
|
||||
target_season_folder = f"Season {season_num}"
|
||||
target_name, root_dir_path = grandparent_name, file_path.parent.parent
|
||||
else:
|
||||
m_type, season_num = "movie", "01"
|
||||
# 扁平 TV 兜底
|
||||
season_num = (flat_tv_match.group(1) if flat_tv_match and flat_tv_match.lastindex >= 1 and flat_tv_match.group(1) else "01").zfill(2)
|
||||
target_season_folder = None
|
||||
target_name, root_dir_path = parent_name, file_path.parent
|
||||
|
||||
elif forced_type == "movie" or (not forced_type and not season_match and not (flat_tv_match or pure_number_match)):
|
||||
m_type = "movie"
|
||||
season_num = "01"
|
||||
target_season_folder = None
|
||||
|
||||
# 容错:如果用户把电影放进了 "Season 1" 这种文件夹里,且被强制指定为 movie,需向上一级找根目录
|
||||
if season_match:
|
||||
target_name, root_dir_path = grandparent_name, file_path.parent.parent
|
||||
else:
|
||||
target_name, root_dir_path = parent_name, file_path.parent
|
||||
|
||||
elif not forced_type and (flat_tv_match or pure_number_match):
|
||||
# 原本的自动扁平 TV 判断
|
||||
m_type = "tv"
|
||||
season_num = (flat_tv_match.group(1) if flat_tv_match and flat_tv_match.lastindex >= 1 and flat_tv_match.group(1) else "01").zfill(2)
|
||||
target_season_folder = None
|
||||
target_name, root_dir_path = parent_name, file_path.parent
|
||||
else:
|
||||
return None # 异常流保护
|
||||
|
||||
root_key = str(root_dir_path)
|
||||
if root_key not in context_cache:
|
||||
# 💡 核心修复:先剔除已有的 [tmdbid] 干扰
|
||||
clean_name = re.sub(r'\s*[\[\(]tmdbid-\d+[\]\)]', '', target_name).strip()
|
||||
|
||||
# 重新匹配标题和年份
|
||||
tm = re.search(r'^(.*?)\s*[\[\(](\d{4})[\]\)]', clean_name)
|
||||
if tm:
|
||||
title, year = tm.group(1).strip().replace(' ', '.'), tm.group(2)
|
||||
@@ -48,7 +61,11 @@ class RenamerService:
|
||||
title, year = clean_name.strip().replace(' ', '.'), ""
|
||||
|
||||
if not year:
|
||||
# 💡 取路径的最后三级(爷爷/爸爸/儿子),给用户提供充足的上下文
|
||||
context_path = " / ".join(file_path.parts[-3:])
|
||||
log.warning(f"目录命名不规范: {root_dir_path.name}")
|
||||
log.warning(f"📁 案发现场: {context_path}") # 👈 增加这一行,清晰定位
|
||||
|
||||
user_title = input(f" ➤ 确认标题 (回车默认 '{title}'): ").strip()
|
||||
if user_title: title = user_title.replace(' ', '.')
|
||||
while not re.match(r'^\d{4}$', year):
|
||||
@@ -61,32 +78,40 @@ class RenamerService:
|
||||
|
||||
@staticmethod
|
||||
def get_target_info(f_path: Path, m_type: str, title: str, year: str, season_num: str, is_multi_version: bool = False):
|
||||
tags = MediaInfoService.get_scene_tags(f_path)
|
||||
# 💡 调用新的 search_media,并把 m_type 传给它
|
||||
tmdb = TMDBService.search_media(title, year, m_type)
|
||||
|
||||
# 💡 策略:文件名用英文/原名,文件夹用中文
|
||||
eng = tmdb['english_title'] if tmdb else ""
|
||||
tags = MediaInfoService.get_scene_tags(f_path)
|
||||
# 💡 这里多传一个 season_num,让 TMDB 服务自己决定要不要更新缓存
|
||||
tmdb = TMDBService.search_media(title, year, m_type, season_num)
|
||||
orig = tmdb['original_title'] if tmdb else ""
|
||||
if orig:
|
||||
display_name = orig
|
||||
else:
|
||||
display_name = re.sub(r'[\\/*?:"<>|,!&:,!?、\s]+|\.+', '.', title.replace("'", "").replace("’", "")).strip('.')
|
||||
|
||||
tid = f"[tmdbid-{tmdb['tmdb_id']}]" if (tmdb and config.INCLUDE_TMDB_ID) else ""
|
||||
|
||||
# 组装技术串 (Scene 规范)
|
||||
source = "BluRay.REMUX" if tags['is_remux'] else "WEB-DL"
|
||||
tech = f"{tags['res']}.{source}.{tags['v_codec']}.{tags['bits']}.{tags['a_info']}"
|
||||
|
||||
# 📁 文件夹:中文 (年份) [tmdbid]
|
||||
# ⚠️ 根目录文件夹使用主年份 (剧集首播年份)
|
||||
target_folder = f"{title.replace('.', ' ')} ({year}) {tid}".strip()
|
||||
|
||||
# 🎬 文件名:英文原名.年份.技术串
|
||||
display_name = eng if eng else title
|
||||
if m_type == "movie":
|
||||
if is_multi_version:
|
||||
return f"{title} ({year}) - {display_name}.{tech}", target_folder
|
||||
return f"{title} ({year}) - {tech}", target_folder
|
||||
return f"{display_name}.{year}.{tech}", target_folder
|
||||
else:
|
||||
# 💡 强化正则:提取 S01E01, EP01, E01, 或纯数字 01
|
||||
match = re.search(r'S\d{1,2}E(\d{1,3})|(?<!\d)(?:EP|E|第)?(\d{1,3})(?:集)?(?!\d)', f_path.name, re.IGNORECASE)
|
||||
ep = next((g for g in match.groups() if g), "01").zfill(2)
|
||||
return f"{display_name}.S{season_num}E{ep}.{year}.{tech}", target_folder
|
||||
else:
|
||||
regex = r'S\d{1,2}E(\d{1,4})|(?:EP|E|第|期)(\d{1,4})(?:集|话)?|(?<![a-zA-Z0-9])(\d{1,4})(?![a-zA-Z0-9])'
|
||||
match = re.search(regex, f_path.stem, re.IGNORECASE)
|
||||
ep = next((g for g in match.groups() if g), "01").zfill(2) if match else "01"
|
||||
|
||||
# 💡 核心新增:提取本季独立年份
|
||||
# 默认使用主年份兜底,如果缓存中有 season_years 且包含当前 season_num,则覆盖
|
||||
episode_year = year
|
||||
if tmdb and "season_years" in tmdb:
|
||||
episode_year = tmdb["season_years"].get(season_num, year)
|
||||
|
||||
# 文件名使用本季独立年份 episode_year
|
||||
return f"{display_name}.S{season_num}E{ep}.{episode_year}.{tech}", target_folder
|
||||
|
||||
@staticmethod
|
||||
def detect_subtitle_language(sub_path: Path) -> str:
|
||||
@@ -103,7 +128,7 @@ class RenamerService:
|
||||
except: return "und"
|
||||
|
||||
@staticmethod
|
||||
def scan_existing_subtitles(f_path: Path, target_stem: str, m_type: str, task_mgr):
|
||||
def scan_existing_subtitles(f_path: Path, target_stem: str, m_type: str, dest_dir: Path, task_mgr):
|
||||
for sub in f_path.parent.glob("*"):
|
||||
if sub.is_file() and sub.suffix.lower() in {'.srt', '.ass', '.ssa'}:
|
||||
is_match = False
|
||||
@@ -118,41 +143,71 @@ class RenamerService:
|
||||
|
||||
if is_match:
|
||||
lang_tag = RenamerService.detect_subtitle_language(sub)
|
||||
new_name = f"{target_stem}.{lang_tag}{sub.suffix.lower()}"
|
||||
if sub.name != new_name:
|
||||
desired_path = dest_dir / f"{target_stem}.{lang_tag}{sub.suffix.lower()}"
|
||||
# 💡 传入 source_path,如果计算出的名字存在且就是自己,就不会强制加 .2
|
||||
reserved_path = task_mgr.reserve_path(desired_path, source_path=sub)
|
||||
|
||||
|
||||
if sub.resolve() != reserved_path.resolve():
|
||||
task_mgr.add_file_rename(
|
||||
f"[外挂字幕] {sub.name} --> {new_name}",
|
||||
f"[外挂字幕] {sub.name} --> {reserved_path.name}",
|
||||
RenamerService.do_rename_single,
|
||||
(sub, task_mgr.reserve_path(sub.with_name(new_name)))
|
||||
(sub, reserved_path)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def scan_rename(f_path: Path, target_stem: str, m_type: str, target_season_folder: str, root_dir_path: Path, target_root_folder: str, task_mgr):
|
||||
new_path = f_path.with_name(f"{target_stem}{f_path.suffix.lower()}")
|
||||
def scan_rename(f_path: Path, target_stem: str, m_type: str, dest_dir: Path, target_season_folder: str, root_dir_path: Path, target_root_folder: str, task_mgr):
|
||||
new_path = dest_dir / f"{target_stem}{f_path.suffix.lower()}"
|
||||
reserved_new_path = task_mgr.reserve_path(new_path, source_path=f_path)
|
||||
|
||||
if f_path.name != new_path.name:
|
||||
if f_path.resolve() != reserved_new_path.resolve():
|
||||
task_mgr.add_file_rename(
|
||||
f"[主视频] {f_path.name} --> {new_path.name}",
|
||||
f"[主视频] {f_path.name} --> {reserved_new_path.name}",
|
||||
RenamerService.do_rename_single,
|
||||
(f_path, task_mgr.reserve_path(new_path))
|
||||
(f_path, reserved_new_path)
|
||||
)
|
||||
for asset in f_path.parent.glob(f"{f_path.stem}*"):
|
||||
if asset.is_file() and asset.suffix.lower() in config.SIDECAR_EXTS:
|
||||
new_asset_name = asset.name.replace(f_path.stem, target_stem, 1)
|
||||
task_mgr.add_file_rename(
|
||||
f"[附属元数据] {asset.name} --> {new_asset_name}",
|
||||
RenamerService.do_rename_single,
|
||||
(asset, task_mgr.reserve_path(asset.with_name(new_asset_name)))
|
||||
)
|
||||
|
||||
# 💡 只有在 target_season_folder 存在时才允许修改季目录(完美跳过扁平电视节目)
|
||||
if m_type == "tv" and target_season_folder and f_path.parent.name != target_season_folder:
|
||||
task_mgr.add_season_dir_rename(f_path.parent, f_path.parent.with_name(target_season_folder))
|
||||
|
||||
for asset in f_path.parent.glob(f"{f_path.stem}*"):
|
||||
if asset.is_file() and asset.suffix.lower() in config.SIDECAR_EXTS:
|
||||
|
||||
# 💡 核心修复:边界安全检查
|
||||
# 截取被匹配文件名多出来的“尾巴”部分
|
||||
rest_of_name = asset.name[len(f_path.stem):]
|
||||
|
||||
# 如果尾巴的第一个字符是字母或数字(比如 E10 匹配到了 E103,尾巴是 '3.nfo')
|
||||
# 说明这是一个“假匹配”,立刻跳过!
|
||||
if rest_of_name and rest_of_name[0].isalnum():
|
||||
continue
|
||||
|
||||
# 💡 安全组装:目标主文件名 + 剩余的合法尾巴 (如 '-thumb.jpg' 或 '.nfo')
|
||||
new_asset_name = f"{target_stem}{rest_of_name}"
|
||||
|
||||
reserved_asset = task_mgr.reserve_path(dest_dir / new_asset_name, source_path=asset)
|
||||
|
||||
if asset.resolve() != reserved_asset.resolve():
|
||||
task_mgr.add_file_rename(
|
||||
f"[附属元数据] {asset.name} --> {reserved_asset.name}",
|
||||
RenamerService.do_rename_single,
|
||||
(asset, reserved_asset)
|
||||
)
|
||||
|
||||
# 这里的目录重命名逻辑保持不变,但增加一个防爆锁
|
||||
if m_type == "tv" and target_season_folder and f_path.parent.name != target_season_folder:
|
||||
if f_path.parent != root_dir_path: # 🛡️ 防爆锁:绝不允许对根目录执行季目录改名
|
||||
task_mgr.add_season_dir_rename(f_path.parent, f_path.parent.with_name(target_season_folder))
|
||||
|
||||
if root_dir_path.name != target_root_folder:
|
||||
task_mgr.add_root_dir_rename(root_dir_path, root_dir_path.with_name(target_root_folder))
|
||||
|
||||
@staticmethod
|
||||
def do_rename_single(old_path: Path, new_path: Path):
|
||||
"""执行物理重命名/移动任务,并记录审计日志"""
|
||||
if old_path.exists() and old_path != new_path:
|
||||
old_path.rename(new_path)
|
||||
# 💡 物理层变更审计:检测并创建缺失的季目录/电影目录
|
||||
if not new_path.parent.exists():
|
||||
log.info(f"🆕 发现目标目录不存在,正在执行物理创建: {new_path.parent.absolute()}")
|
||||
new_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 执行移动
|
||||
old_path.rename(new_path)
|
||||
# 注意:成功移动后的日志由 task.py 的 execute() 统一接管输出,此处无需重复打印
|
||||
@@ -9,7 +9,7 @@ from core import config
|
||||
|
||||
class SubtitleService:
|
||||
@staticmethod
|
||||
def scan_subtitles(file_path: Path, task_mgr, target_stem: str):
|
||||
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)]
|
||||
try:
|
||||
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
|
||||
@@ -49,10 +49,11 @@ class SubtitleService:
|
||||
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]}"
|
||||
|
||||
desired_out_srt = file_path.with_name(f"{target_stem}.{lang_code}{lang_suffix}.srt")
|
||||
# 💡 核心新增:确保提取出的字幕直接落地在目标季目录
|
||||
desired_out_srt = dest_dir / f"{target_stem}.{lang_code}{lang_suffix}.srt"
|
||||
out_srt = task_mgr.reserve_path(desired_out_srt)
|
||||
|
||||
temp_ass = file_path.with_name(f"{target_stem}.temp.{out_srt.name}.ass")
|
||||
temp_ass = dest_dir / f"{target_stem}.temp.{out_srt.name}.ass"
|
||||
|
||||
task_mgr.add_extract(
|
||||
f"{file_path.name} (内置轨道 {stream_idx} | 格式: {codec.upper()}) --> {out_srt.name}",
|
||||
|
||||
+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