diff --git a/media/src/services/variety.py b/media/src/services/variety.py index ed65777..42a5089 100644 --- a/media/src/services/variety.py +++ b/media/src/services/variety.py @@ -21,6 +21,7 @@ from collections import defaultdict from pathlib import Path from core.logger import log +from core import config from core import tmdb_store as store from core.utils import StringUtil from services.mediainfo import MediaInfoService @@ -31,8 +32,10 @@ _DATE_FULL = [ re.compile(r"(20\d{2})[-._年/](\d{1,2})[-._月/](\d{1,2})"), re.compile(r"(? int: + """让附属文件跟着视频走:<旧名>.xxx → <新名>.xxx。返回处理数量。""" + count = 0 + for side in list(src_video.parent.iterdir()): + if not side.is_file() or side.suffix.lower() not in config.SIDECAR_EXTS: + continue + if not side.name.startswith(src_video.stem): + continue + rest = side.name[len(src_video.stem):] + if rest and rest[0].isalnum(): + continue + target_side = dst_video.parent / f"{dst_video.stem}{rest}" + if target_side == side: + continue + try: + target_side.parent.mkdir(parents=True, exist_ok=True) + side.rename(target_side) + count += 1 + except OSError as exc: + log.warning(f"⚠️ 附属文件改名失败 {side.name}: {exc}") + return count + + @classmethod + def adopt_orphan_sidecars(cls, folder: Path, stats: dict) -> int: + """兜底认领:老名字的附属文件(视频早已改名)按「同一日期」认领到对应视频。 + + 典型场景:花儿与少年的 .nfo 还叫 花儿与少年.S01E20220610.nfo, + 而视频已经变成 …-20220610.第四季…,两者共享同一个 YYYYMMDD。 + """ + videos = [p for p in folder.rglob("*") + if p.is_file() and p.suffix.lower() in cls.VIDEO_EXTS] + by_date: dict[str, Path] = {} + for video in videos: + match = re.search(r"-(\d{8})\.", video.name) + if match: + by_date.setdefault(match.group(1), video) + video_stems = {p.stem for p in videos} + + adopted = 0 + for side in list(folder.rglob("*")): + if not side.is_file() or side.suffix.lower() not in config.SIDECAR_EXTS: + continue + if side.stem in video_stems or side.stem in {"season", "tvshow"}: + continue + match = re.search(r"(\d{8})", side.name) + if not match: + continue + video = by_date.get(match.group(1)) + if not video or video.parent != side.parent: + continue + rest = re.sub(r"^.*?\d{8}", "", side.stem) + target = video.with_name(f"{video.stem}{rest}{side.suffix.lower()}") + if target == side or target.exists(): + continue + try: + side.rename(target) + adopted += 1 + except OSError as exc: + log.warning(f"⚠️ 附属文件认领失败 {side.name}: {exc}") + if adopted: + stats["sidecars"] = stats.get("sidecars", 0) + adopted + return adopted + @classmethod def execute(cls, plan: dict, season_years: dict, media_title: str) -> dict: """执行改名 / 移入 extras / 删除。返回统计。""" folder: Path = plan["folder"] extras_dir = folder / "extras" - stats = {"renamed": 0, "extras": 0, "deleted": 0, "skipped": 0} + stats = {"renamed": 0, "extras": 0, "deleted": 0, "skipped": 0, "sidecars": 0} for file, candidate in plan["renames"]: target = file.with_name(cls._target_name(file, candidate, media_title, season_years)) - # 散在剧集根目录的正片按季归位:根目录 → Season XX - if file.parent == folder and candidate["season"]: + # 一律按 TMDB 季号归位:特典进 Season 00,正片进 Season XX。 + # 不这样做的话,「源文件本来就在 Season 04」的特典会一直留在 Season 04。 + if candidate["season"]: target = folder / f"Season {candidate['season']}" / target.name if target == file: + cls._follow_sidecars(file, target) continue if target.exists(): log.warning(f"⚠️ 目标已存在,跳过: {target.name}") @@ -309,6 +396,7 @@ class VarietyService: file.rename(target) log.info(f"✅ 改名: {file.name} → {target.relative_to(folder)}") stats["renamed"] += 1 + stats["sidecars"] = stats.get("sidecars", 0) + cls._follow_sidecars(file, target, moved=True) for file in plan["extras"]: extras_dir.mkdir(parents=True, exist_ok=True) @@ -330,6 +418,9 @@ class VarietyService: log.warning(f"⚠️ 删除失败 {file.name}: {exc}") stats["skipped"] += 1 + # 老名字的附属文件按日期兜底认领 + cls.adopt_orphan_sidecars(folder, stats) + # 留一个标识:综艺目录名往往不规范(「花儿与少年」会误匹配到衍生剧), # 常规扫描看到 .variety.json 就按这里记录的 id 识别,不会再用错剧名。 try: