refactor(layout): 源码迁入 src/,项目根迁到 SceneMarshal

This commit is contained in:
ali
2026-11-20 14:31:34 +08:00
parent b804897029
commit e6a4113ca0
41 changed files with 129 additions and 128 deletions
+158
View File
@@ -0,0 +1,158 @@
# src/services/renamer.py
import re
from pathlib import Path
from core import config
from core.logger import log
from core.constants import RegexPatterns
from core.utils import MediaUtil
from services.fileops import FileOpsService
class RenamerService:
"""媒体文件规范重命名编排器"""
@staticmethod
def scan_existing_subtitles(f_path: Path, target_stem: str, m_type: str, dest_dir: Path, task_mgr) -> bool:
# 只导出 ASS 模式下不做 SRT 转换,外挂字幕保持原样
if 'srt' not in config.SUBTITLE_EXPORT:
return False
has_external_sub = False
for sub in f_path.parent.glob("*"):
if sub.is_file() and sub.suffix.lower() in {'.srt', '.ass', '.ssa'}:
# 🛡️ 幂等保护:本工具已按目标名生成过的字幕(含 *.internal.<lang>.srt 与去重用的 .2/.3 后缀)
# 不再参与"外挂字幕规范化",否则复跑时会被改名成 <目标名>.zh-CN.2.srt,丢掉 internal 标识且不断产生新后缀。
if sub.name.startswith(f"{target_stem}."):
continue
is_match = False
if f_path.stem in sub.name: is_match = True
elif m_type == "tv":
match = RegexPatterns.SUB_EP_MATCH.search(sub.name)
if match:
ep = next((g for g in match.groups() if g), None)
target_ep_match = RegexPatterns.SUB_TARGET_EP.search(target_stem)
if target_ep_match and ep and ep.zfill(2) == target_ep_match.group(1):
is_match = True
if is_match:
has_external_sub = True
lang_tag = MediaUtil.detect_subtitle_language(sub)
if sub.suffix.lower() != '.srt':
desired_path = dest_dir / f"{target_stem}.{lang_tag}.srt"
# ==========================================
# 🛡️ 恢复丢失的外挂转换前置拦截器
# ==========================================
if desired_path.exists() and desired_path.stat().st_size > 0:
log.debug(f"✨ [跳过转换] 孪生 SRT 已存在,忽略外挂源文件: {sub.name}")
continue
reserved_path = task_mgr.reserve_path(desired_path, source_path=sub)
from services.subtitle import SubtitleService
task_mgr.add_extract(
f"[外挂字幕转换] {sub.name} --> {reserved_path.name}",
SubtitleService.convert_to_srt,
(sub, reserved_path)
)
else:
desired_path = dest_dir / f"{target_stem}.{lang_tag}.srt"
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} --> {reserved_path.name}",
FileOpsService.move_file,
(sub, reserved_path)
)
return has_external_sub
# 单视频目录下可以「兜底认领」的附属文件类型。
# 只收字幕:movie.nfo / tvshow.nfo / season.nfo 是 Jellyfin 的目录级元数据,
# poster/fanart/logo 等是目录图片,都不能跟着视频改名。
# 值见 config.ini [Media] sidecar_per_video_exts / reserved_sidecar_stems,
# 语言后缀正则见 [Naming] lang_tail_pattern。
SIDECAR_PER_VIDEO_EXTS = config.SIDECAR_PER_VIDEO_EXTS
# 目录级文件名(不含扩展名),任何情况下都不当作单个视频的附属文件
RESERVED_SIDECAR_STEMS = config.RESERVED_SIDECAR_STEMS
LANG_TAIL = config.LANG_TAIL_PATTERN
@staticmethod
def _sidecar_lang(asset: Path) -> str:
match = RenamerService.LANG_TAIL.search(asset.stem)
return match.group(0).lstrip(".-_") if match else ""
@staticmethod
def _sidecar_rest(asset: Path, video: Path, single_video: bool) -> str | None:
"""判断 asset 是否属于 video;是则返回拼到目标名后的后缀(含前导点)。"""
name = asset.name
if name.startswith(video.stem):
rest = name[len(video.stem):]
return rest if rest and not rest[0].isalnum() else None
# 前缀对不上时(例如视频按日文原名、字幕用中文名),
# 若该目录只有这一个视频,就把字幕直接认领给它。
if not single_video or asset.suffix.lower() not in RenamerService.SIDECAR_PER_VIDEO_EXTS:
return None
if asset.stem.strip().lower() in RenamerService.RESERVED_SIDECAR_STEMS:
return None
lang = RenamerService._sidecar_lang(asset)
return f".{lang}{asset.suffix.lower()}" if lang else asset.suffix.lower()
@staticmethod
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):
# 综艺命名约定:<规范名>-<YYYYMMDD>.<期名>。技术标签变化时这段说明要保留,
# 否则整库整理会把期名抹掉(WEB-DL 里也有连字符,不能简单按 "-" 切)。
tail_match = re.search(r"(-\d{8}\..+)$", f_path.stem)
tail = tail_match.group(1) if tail_match else ""
# 视频的最终主名:附属文件必须跟着它走,否则会把 <目标名>-日期.期名.nfo
# 改成 <目标名>.nfo,NFO/字幕就和视频失联了。
final_stem = f"{target_stem}{tail}"
# 「<目标名>-说明」视为已规范:综艺整理会加这段说明,
# 整库扫描不应把它当作错名再改回去。
if f_path.stem in (target_stem, final_stem):
reserved_new_path = f_path
else:
new_path = dest_dir / f"{final_stem}{f_path.suffix.lower()}"
reserved_new_path = task_mgr.reserve_path(new_path, source_path=f_path)
if f_path.resolve() != reserved_new_path.resolve():
task_mgr.add_file_rename(
f"[主视频] {f_path.name} --> {reserved_new_path.name}",
FileOpsService.move_file,
(f_path, reserved_new_path)
)
# 附属文件单独处理:即使视频本身已经命名正确,
# 也要把对不上的外挂字幕/元数据纠正过来。
siblings = [p for p in f_path.parent.iterdir()
if p.is_file() and p.suffix.lower() in config.SUPPORTED_EXTS]
single_video = len(siblings) == 1
for asset in sorted(f_path.parent.iterdir()):
if not asset.is_file() or asset.suffix.lower() not in config.SIDECAR_EXTS:
continue
rest = RenamerService._sidecar_rest(asset, f_path, single_video)
if rest is None:
continue
new_asset_name = f"{final_stem}{rest}"
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}",
FileOpsService.move_file,
(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))