- 规则:特辑日期 < 该季首集 → 插到第 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 刷新不生效),待进一步确认存储位置
156 lines
6.2 KiB
Python
156 lines
6.2 KiB
Python
# 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)
|