feat(specials): 新增 specials 模式,按播出日期计算并写入特典放置信息
- 规则:特辑日期 < 该季首集 → 插到第 1 集前;>= 末集 → 整季之后; 其它 → 插到「日期严格晚于它」的那一集之前(同日播出的特辑排在正片之后) - 季归属优先取特辑名里的「第N季」,否则按日期找最近开播的一季 - 写入 episode nfo 的 airsbefore_season / airsbefore_episode / airsafter_season - 写入失败(权限)不再中断整批,单独计数 - scripts/media-rename 支持 MEDIA_UID/MEDIA_GID,可切 root 写 Jellyfin 生成的 nfo - 实测:11 部剧写入成功(现在就出发 75、你好星期六 198、花儿与少年 70…) 已知:Jellyfin 12.4 目前未读入这些字段(NFO 已写、API 刷新不生效),待进一步确认存储位置
This commit is contained in:
@@ -55,6 +55,38 @@ class MediaPipeline:
|
||||
return 2
|
||||
return 0
|
||||
|
||||
def run_specials(self) -> int:
|
||||
"""特典放置:把 Season 00 按播出日期插进正季(写 NFO 的 airsbefore/airsafter)。"""
|
||||
from services.specials import SpecialsService
|
||||
|
||||
folder = self.target_dir
|
||||
show = self._resolve_variety_show(folder)
|
||||
if not show:
|
||||
log.error("❌ 无法识别剧集:请在目录名里加 [tmdbid-xxx],或用 --show <id> 指定")
|
||||
return 1
|
||||
show_id, show_name, _season_years = show[0], show[1], show[2]
|
||||
|
||||
plans = SpecialsService.compute(show_id)
|
||||
if not plans:
|
||||
log.info("✨ 该剧没有需要放置的特典(或 TMDB 未提供播出日期)。")
|
||||
return 0
|
||||
SpecialsService.preview(plans)
|
||||
|
||||
if not self.auto_execute:
|
||||
try:
|
||||
answer = input("⚠️ 是否写入以上放置信息?[y/n/q]: ").strip().lower()
|
||||
except EOFError:
|
||||
log.warning("⛔ 没有可用的终端输入,按取消处理。")
|
||||
return 2
|
||||
if answer not in {"y", "yes"}:
|
||||
log.info("💤 任务已由用户取消。")
|
||||
return 2
|
||||
|
||||
stats = SpecialsService.apply(folder, plans)
|
||||
log.info(f"🎉 {show_name}:写入 {stats['written']} 个 NFO,"
|
||||
f"{stats['missing']} 个无本地文件,{stats.get('denied', 0)} 个无写入权限")
|
||||
return 0
|
||||
|
||||
def run_variety(self) -> int:
|
||||
"""综艺整理:按日期匹配集号,产出 改名 / extras / 删除 三类动作。"""
|
||||
from services.variety import VarietyService
|
||||
|
||||
+7
-1
@@ -13,7 +13,7 @@ from services.preflight import PreflightService
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="🎬 流媒体高级自动化管理工具")
|
||||
parser.add_argument("mode", nargs='?', default=config.DEFAULT_MODE,
|
||||
choices=["manual", "auto", "variety", "clean-ads", "extract-subs", "watch", "check"],
|
||||
choices=["manual", "auto", "variety", "specials", "clean-ads", "extract-subs", "watch", "check"],
|
||||
help=f"运行模式(默认取 config.ini [Run] default_mode = {config.DEFAULT_MODE})")
|
||||
parser.add_argument("-p", "--path", default=config.DEFAULT_PATH,
|
||||
help="扫描目录(默认取 config.ini [Run] default_path,留空为当前目录)")
|
||||
@@ -44,6 +44,12 @@ def main():
|
||||
PreflightService.scan(target_dir)
|
||||
return
|
||||
|
||||
if args.mode == "specials":
|
||||
code = MediaPipeline(target_dir, args, auto_execute=bool(getattr(args, "yes", False))).run_specials()
|
||||
if code:
|
||||
sys.exit(code)
|
||||
return
|
||||
|
||||
if args.mode == "variety":
|
||||
# 综艺整理:日期 ↔ TMDB 播出日期匹配
|
||||
code = MediaPipeline(target_dir, args, auto_execute=bool(getattr(args, "yes", False))).run_variety()
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
# src/services/specials.py
|
||||
"""特典放置:把 Season 00 的条目按播出日期插到正季的合适位置。
|
||||
|
||||
Jellyfin 的三个字段(「特别剧集信息」):
|
||||
airsbefore_season = 季播出前
|
||||
airsbefore_episode = 集播出前
|
||||
airsafter_season = 季播出后
|
||||
|
||||
规则(全部由 TMDB 播出日期推导,不猜文件名):
|
||||
1. 日期 < 该季第一集 → airs before 该季第 1 集(先导片之类)
|
||||
2. 日期 >= 该季最后一集 → airs after 该季(收官特别篇)
|
||||
3. 其它:找第一集「日期严格晚于它」的正片 E → airs before E
|
||||
(用严格晚于,保证同一天播出的特辑排在正片之后)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import xml.etree.ElementTree as ET
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
from core.logger import log
|
||||
from services.variety import VarietyService
|
||||
|
||||
_CN_NUM = {"一": 1, "二": 2, "三": 3, "四": 4, "五": 5, "六": 6,
|
||||
"七": 7, "八": 8, "九": 9, "十": 10, "十一": 11, "十二": 12}
|
||||
_EP_RE = re.compile(r"S(\d{2})E(\d{1,4})", re.I)
|
||||
_AIR_TAGS = ("airsbefore_season", "airsbefore_episode", "airsafter_season")
|
||||
|
||||
|
||||
class SpecialsService:
|
||||
@staticmethod
|
||||
def _target_season(name: str, date: str, regular: dict) -> str | None:
|
||||
"""特辑属于哪一季:先看名字里的「第N季」,否则按日期找最近开播的一季。"""
|
||||
match = re.search(r"第\s*([0-9一二三四五六七八九十]+)\s*季", name or "")
|
||||
if match:
|
||||
raw = match.group(1)
|
||||
if raw.isdigit():
|
||||
return str(int(raw)).zfill(2)
|
||||
if raw in _CN_NUM:
|
||||
return str(_CN_NUM[raw]).zfill(2)
|
||||
best = None
|
||||
for season, episodes in regular.items():
|
||||
if not episodes:
|
||||
continue
|
||||
start = episodes[0][1]
|
||||
if start <= date and (best is None or start > regular[best][0][1]):
|
||||
best = season
|
||||
return best
|
||||
|
||||
@classmethod
|
||||
def compute(cls, show_id: int) -> list[dict]:
|
||||
index = VarietyService.build_index(show_id)
|
||||
regular: dict[str, list[tuple[int, str]]] = defaultdict(list)
|
||||
specials: list[tuple[str, dict]] = []
|
||||
for date, candidates in index.items():
|
||||
for cand in candidates:
|
||||
if cand["season"] == "00":
|
||||
specials.append((date, cand))
|
||||
else:
|
||||
regular[cand["season"]].append((cand["ep"], date))
|
||||
for episodes in regular.values():
|
||||
episodes.sort()
|
||||
|
||||
plans = []
|
||||
for date, cand in specials:
|
||||
season = cls._target_season(cand["name"], date, regular)
|
||||
if not season or not regular.get(season):
|
||||
continue
|
||||
episodes = regular[season]
|
||||
first_date, last_date = episodes[0][1], episodes[-1][1]
|
||||
if date < first_date:
|
||||
placement = {"airsbefore_season": season, "airsbefore_episode": 1}
|
||||
elif date >= last_date:
|
||||
placement = {"airsafter_season": season}
|
||||
else:
|
||||
nxt = next((ep for ep, d in episodes if d > date), None)
|
||||
placement = ({"airsbefore_season": season, "airsbefore_episode": nxt}
|
||||
if nxt is not None else {"airsafter_season": season})
|
||||
plans.append({**placement, "special": cand, "date": date, "season": season})
|
||||
return plans
|
||||
|
||||
# ------------------------------------------------------------ 写 NFO
|
||||
|
||||
@classmethod
|
||||
def _write_nfo(cls, video: Path, plan: dict) -> bool:
|
||||
nfo = video.with_suffix(".nfo")
|
||||
if nfo.exists():
|
||||
try:
|
||||
tree = ET.parse(nfo)
|
||||
root = tree.getroot()
|
||||
except ET.ParseError:
|
||||
log.warning(f"⚠️ NFO 解析失败,跳过: {nfo.name}")
|
||||
return False
|
||||
else:
|
||||
root = ET.Element("episodedetails")
|
||||
tree = ET.ElementTree(root)
|
||||
|
||||
cand = plan["special"]
|
||||
for tag in _AIR_TAGS:
|
||||
for element in root.findall(tag):
|
||||
root.remove(element)
|
||||
for tag, value in (("season", "0"), ("episode", str(cand["ep"]))):
|
||||
element = root.find(tag)
|
||||
if element is None:
|
||||
element = ET.SubElement(root, tag)
|
||||
element.text = value
|
||||
|
||||
for tag in ("airsbefore_season", "airsbefore_episode", "airsafter_season"):
|
||||
if tag in plan:
|
||||
ET.SubElement(root, tag).text = str(plan[tag])
|
||||
|
||||
try:
|
||||
tree.write(nfo, encoding="utf-8", xml_declaration=True)
|
||||
except OSError as exc:
|
||||
log.warning(f"⚠️ NFO 写入失败(权限?){nfo.name}: {exc}")
|
||||
return False
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def apply(cls, folder: Path, plans: list[dict]) -> dict:
|
||||
index: dict[tuple[str, int], Path] = {}
|
||||
for path in folder.rglob("*"):
|
||||
if path.is_file() and path.suffix.lower() in (".mp4", ".mkv"):
|
||||
match = _EP_RE.search(path.name)
|
||||
if match:
|
||||
index.setdefault((match.group(1), int(match.group(2))), path)
|
||||
|
||||
written = missing = denied = 0
|
||||
for plan in plans:
|
||||
cand = plan["special"]
|
||||
video = index.get(("00", cand["ep"]))
|
||||
if video is None:
|
||||
missing += 1
|
||||
continue
|
||||
if cls._write_nfo(video, plan):
|
||||
written += 1
|
||||
else:
|
||||
denied += 1
|
||||
return {"written": written, "missing": missing, "denied": denied}
|
||||
|
||||
@classmethod
|
||||
def preview(cls, plans: list[dict], limit: int = 10) -> None:
|
||||
log.info("=" * 60)
|
||||
log.info(f"🗂 特典放置:共 {len(plans)} 个 Season 00 条目需要定位")
|
||||
for plan in plans[:limit]:
|
||||
cand = plan["special"]
|
||||
if "airsafter_season" in plan:
|
||||
place = f"第{int(plan['airsafter_season'])}季之后"
|
||||
else:
|
||||
place = f"第{int(plan['airsbefore_season'])}季第{plan['airsbefore_episode']}集之前"
|
||||
log.info(f" S00E{cand['ep']:02d} {plan['date']} {cand['name'][:28]:<30} → {place}")
|
||||
if len(plans) > limit:
|
||||
log.info(f" …… 其余 {len(plans) - limit} 个略")
|
||||
log.info("=" * 60)
|
||||
Reference in New Issue
Block a user