fix(specials): 特典 NFO 幂等并在整理阶段写入 airs/display 标签
This commit is contained in:
+88
-11
@@ -27,9 +27,30 @@ _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")
|
||||
# Jellyfin API 返回的对应字段;用于判断「已经放对了」,避免每次综艺整理重复 POST
|
||||
_AIR_API_FIELDS = ("AirsBeforeSeasonNumber", "AirsBeforeEpisodeNumber", "AirsAfterSeasonNumber")
|
||||
|
||||
|
||||
class SpecialsService:
|
||||
@staticmethod
|
||||
def _as_number(value) -> int | None:
|
||||
"""把 API/NFO 里的 0/None/'' 统一成 None,其余转正整数。"""
|
||||
try:
|
||||
number = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return number if number > 0 else None
|
||||
|
||||
@classmethod
|
||||
def _placement_matches(cls, item: dict, plan: dict) -> bool:
|
||||
current = tuple(cls._as_number(item.get(field)) for field in _AIR_API_FIELDS)
|
||||
wanted = (
|
||||
cls._as_number(plan.get("airsbefore_season")),
|
||||
cls._as_number(plan.get("airsbefore_episode")),
|
||||
cls._as_number(plan.get("airsafter_season")),
|
||||
)
|
||||
return current == wanted
|
||||
|
||||
@staticmethod
|
||||
def _target_season(name: str, date: str, regular: dict) -> str | None:
|
||||
"""特辑属于哪一季:先看名字里的「第N季」,否则按日期找最近开播的一季。"""
|
||||
@@ -83,6 +104,41 @@ class SpecialsService:
|
||||
|
||||
# ------------------------------------------------------------ 写 NFO
|
||||
|
||||
@classmethod
|
||||
def _nfo_matches(cls, video: Path, plan: dict) -> bool:
|
||||
"""NFO 里的 airs/display 已经与计划一致时返回 True。"""
|
||||
nfo = video.with_suffix(".nfo")
|
||||
if not nfo.exists():
|
||||
return False
|
||||
try:
|
||||
root = ET.parse(nfo).getroot()
|
||||
except (ET.ParseError, OSError):
|
||||
return False
|
||||
|
||||
def text(tag: str) -> str:
|
||||
element = root.find(tag)
|
||||
return (element.text or "").strip() if element is not None else ""
|
||||
|
||||
current = tuple(cls._as_number(text(tag)) for tag in _AIR_TAGS)
|
||||
wanted = (
|
||||
cls._as_number(plan.get("airsbefore_season")),
|
||||
cls._as_number(plan.get("airsbefore_episode")),
|
||||
cls._as_number(plan.get("airsafter_season")),
|
||||
)
|
||||
if current != wanted:
|
||||
return False
|
||||
|
||||
# Jellyfin 12.4 的 NFO 还会写 displayseason/displayepisode;
|
||||
# 归档后它按这两个标签把特典显示进正季,所以也必须一致。
|
||||
display_season = cls._as_number(text("displayseason"))
|
||||
display_episode = cls._as_number(text("displayepisode"))
|
||||
if "airsbefore_season" in plan:
|
||||
return (display_season == cls._as_number(plan["airsbefore_season"])
|
||||
and display_episode == cls._as_number(plan["airsbefore_episode"]))
|
||||
if "airsafter_season" in plan:
|
||||
return display_season == cls._as_number(plan["airsafter_season"]) and display_episode is None
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def _write_nfo(cls, video: Path, plan: dict) -> bool:
|
||||
nfo = video.with_suffix(".nfo")
|
||||
@@ -98,7 +154,7 @@ class SpecialsService:
|
||||
tree = ET.ElementTree(root)
|
||||
|
||||
cand = plan["special"]
|
||||
for tag in _AIR_TAGS:
|
||||
for tag in _AIR_TAGS + ("displayseason", "displayepisode"):
|
||||
for element in root.findall(tag):
|
||||
root.remove(element)
|
||||
for tag, value in (("season", "0"), ("episode", str(cand["ep"]))):
|
||||
@@ -107,9 +163,14 @@ class SpecialsService:
|
||||
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])
|
||||
if "airsbefore_season" in plan:
|
||||
ET.SubElement(root, "airsbefore_season").text = str(cls._as_number(plan["airsbefore_season"]))
|
||||
ET.SubElement(root, "airsbefore_episode").text = str(cls._as_number(plan["airsbefore_episode"]))
|
||||
ET.SubElement(root, "displayseason").text = str(cls._as_number(plan["airsbefore_season"]))
|
||||
ET.SubElement(root, "displayepisode").text = str(cls._as_number(plan["airsbefore_episode"]))
|
||||
elif "airsafter_season" in plan:
|
||||
ET.SubElement(root, "airsafter_season").text = str(cls._as_number(plan["airsafter_season"]))
|
||||
ET.SubElement(root, "displayseason").text = str(cls._as_number(plan["airsafter_season"]))
|
||||
|
||||
try:
|
||||
tree.write(nfo, encoding="utf-8", xml_declaration=True)
|
||||
@@ -119,7 +180,7 @@ class SpecialsService:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def apply(cls, folder: Path, plans: list[dict]) -> dict:
|
||||
def apply(cls, folder: Path, plans: list[dict], dry_run: bool = False) -> dict:
|
||||
index: dict[tuple[str, int], Path] = {}
|
||||
for path in folder.rglob("*"):
|
||||
if path.is_file() and path.suffix.lower() in config.VIDEO_EXTS:
|
||||
@@ -127,25 +188,34 @@ class SpecialsService:
|
||||
if match:
|
||||
index.setdefault((match.group(1), int(match.group(2))), path)
|
||||
|
||||
written = missing = denied = 0
|
||||
written = missing = denied = unchanged = 0
|
||||
for plan in plans:
|
||||
cand = plan["special"]
|
||||
video = index.get(("00", cand["ep"]))
|
||||
if video is None:
|
||||
missing += 1
|
||||
continue
|
||||
if cls._nfo_matches(video, plan):
|
||||
unchanged += 1
|
||||
continue
|
||||
if dry_run:
|
||||
written += 1
|
||||
continue
|
||||
if cls._write_nfo(video, plan):
|
||||
written += 1
|
||||
else:
|
||||
denied += 1
|
||||
return {"written": written, "missing": missing, "denied": denied}
|
||||
return {"written": written, "missing": missing, "denied": denied,
|
||||
"unchanged": unchanged, "dry_run": dry_run}
|
||||
|
||||
@classmethod
|
||||
def apply_via_api(cls, show_name: str, plans: list[dict]) -> dict:
|
||||
def apply_via_api(cls, show_name: str, plans: list[dict], dry_run: bool = False) -> dict:
|
||||
"""通过 Jellyfin API 写入放置信息(等价于在 App 里手填,立即生效)。
|
||||
|
||||
Jellyfin 不会重读我们手写的 NFO,但 POST /Items/{id} 能直接改条目,
|
||||
改完它自己会回写 NFO(SaveLocalMetadata=true)。
|
||||
|
||||
dry_run=True 时只比对、不 POST,用来判断是否还有需要写入的条目。
|
||||
"""
|
||||
import json
|
||||
import urllib.parse
|
||||
@@ -197,13 +267,19 @@ class SpecialsService:
|
||||
episodes = get(f"/Shows/{series_id}/Episodes", season="0", limit="500").get("Items") or []
|
||||
by_number = {item.get("IndexNumber"): item for item in episodes}
|
||||
|
||||
written = missing = failed = 0
|
||||
written = missing = failed = unchanged = 0
|
||||
for plan in plans:
|
||||
cand = plan["special"]
|
||||
item = by_number.get(cand["ep"])
|
||||
if item is None:
|
||||
missing += 1
|
||||
continue
|
||||
if cls._placement_matches(item, plan):
|
||||
unchanged += 1
|
||||
continue
|
||||
if dry_run:
|
||||
written += 1
|
||||
continue
|
||||
payload = dict(item)
|
||||
payload["AirsBeforeSeasonNumber"] = plan.get("airsbefore_season")
|
||||
payload["AirsBeforeEpisodeNumber"] = plan.get("airsbefore_episode")
|
||||
@@ -218,12 +294,13 @@ class SpecialsService:
|
||||
except OSError as exc:
|
||||
log.warning(f"⚠️ API 写入失败 S00E{cand['ep']}: {exc}")
|
||||
failed += 1
|
||||
return {"written": written, "missing": missing, "failed": failed, "skipped": None}
|
||||
return {"written": written, "missing": missing, "failed": failed,
|
||||
"unchanged": unchanged, "skipped": None, "dry_run": dry_run}
|
||||
|
||||
@classmethod
|
||||
def preview(cls, plans: list[dict], limit: int = 10) -> None:
|
||||
log.info("=" * 60)
|
||||
log.info(f"🗂 特典放置:共 {len(plans)} 个 Season 00 条目需要定位")
|
||||
log.info(f"🗂 特典放置:共 {len(plans)} 个 Season 00 条目参与定位(已正确的会自动跳过)")
|
||||
for plan in plans[:limit]:
|
||||
cand = plan["special"]
|
||||
if "airsafter_season" in plan:
|
||||
|
||||
Reference in New Issue
Block a user