mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-27 11:25:08 +00:00
feat(titles): add optional Episode.part, selected with -w s1e1.2
Opt-in and additive: an episode without a part behaves exactly as before.
This commit is contained in:
@@ -2,7 +2,7 @@ import re
|
||||
from abc import ABC
|
||||
from collections import Counter
|
||||
from datetime import date, datetime
|
||||
from typing import Any, Iterable, Optional, Union
|
||||
from typing import Any, Collection, Iterable, Optional, Union
|
||||
|
||||
from langcodes import Language
|
||||
from pymediainfo import MediaInfo
|
||||
@@ -16,6 +16,9 @@ from unshackle.core.utils.template_formatter import TemplateFormatter, detect_sp
|
||||
|
||||
|
||||
class Episode(Title):
|
||||
# class-level default so Episodes restored from an older title cache read as part-less
|
||||
part: Optional[int] = None
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
id_: Any,
|
||||
@@ -29,6 +32,7 @@ class Episode(Title):
|
||||
data: Optional[Any] = None,
|
||||
description: Optional[str] = None,
|
||||
air_date: Optional[Union[date, str]] = None,
|
||||
part: Optional[Union[int, str]] = None,
|
||||
) -> None:
|
||||
super().__init__(id_, service, language, data)
|
||||
|
||||
@@ -51,6 +55,16 @@ class Episode(Title):
|
||||
elif not isinstance(number, int):
|
||||
raise TypeError(f"Expected number to be an int, not {number!r}")
|
||||
|
||||
if part is not None:
|
||||
if isinstance(part, str) and part.isdigit():
|
||||
part = int(part)
|
||||
# bool is an int subclass; True would render as ".True" in keys and filenames
|
||||
elif isinstance(part, bool) or not isinstance(part, int):
|
||||
raise TypeError(f"Expected part to be an int, not {part!r}")
|
||||
# parts are 1-based; a falsy 0 would read as "no part" downstream
|
||||
if part <= 0:
|
||||
raise ValueError(f"Episode part cannot be {part}")
|
||||
|
||||
if name is not None and not isinstance(name, str):
|
||||
raise TypeError(f"Expected name to be a str, not {name!r}")
|
||||
|
||||
@@ -89,8 +103,30 @@ class Episode(Title):
|
||||
self.year = year
|
||||
self.description = description
|
||||
self.air_date = air_date
|
||||
self.part = part
|
||||
|
||||
def _build_template_context(self, media_info: MediaInfo, show_service: bool = True) -> dict:
|
||||
def matches_wanted(self, wanted: Collection[str]) -> bool:
|
||||
"""Whether a parsed ``-w`` key set selects this episode.
|
||||
|
||||
A part-ful episode answers to both its base key and its part key, so ``-w s1e1``
|
||||
takes every part. ``!`` keys are part-qualified exclusions resolved here.
|
||||
"""
|
||||
base = f"{self.season}x{self.number}"
|
||||
keys = (base,) if self.part is None else (base, f"{base}.{self.part}")
|
||||
if any(f"!{k}" in wanted for k in keys):
|
||||
return False
|
||||
return any(k in wanted for k in keys)
|
||||
|
||||
def _part_suffix(self) -> str:
|
||||
"""``.Part.2`` / `` Part 2`` in the series template's own separator style."""
|
||||
if self.part is None:
|
||||
return ""
|
||||
sep = config.get_template_separator("series") if config.output_template.get("series") else "."
|
||||
return f"{sep}Part{sep}{self.part}"
|
||||
|
||||
def _build_template_context(
|
||||
self, media_info: MediaInfo, show_service: bool = True, include_part: bool = True
|
||||
) -> dict:
|
||||
"""Build template context dictionary from MediaInfo."""
|
||||
context = self._build_base_template_context(media_info, show_service)
|
||||
context["title"] = self.title.replace("$", "S")
|
||||
@@ -100,6 +136,7 @@ class Episode(Title):
|
||||
context["season_episode"] = f"S{self.season:02}E{self.number:02}"
|
||||
context["episode_name"] = self.name or ""
|
||||
context["date"] = ""
|
||||
context["part"] = self.part if include_part and self.part is not None else ""
|
||||
if self.air_date:
|
||||
# daily/sports: air date replaces SxxExx
|
||||
disp = self._air_date_display()
|
||||
@@ -108,6 +145,12 @@ class Episode(Title):
|
||||
context["season_episode"] = disp
|
||||
context["year"] = "" # air date is the sole date in the file; folders keep the year
|
||||
context["date"] = self.air_date.isoformat() if isinstance(self.air_date, date) else str(self.air_date)
|
||||
if include_part and self.part is not None:
|
||||
# folded into the identity tokens, not a token of its own: a standalone {part} is
|
||||
# absent from every shipped template, so two parts would render the same filename
|
||||
suffix = self._part_suffix()
|
||||
context["episode"] = f"{context['episode']}{suffix}"
|
||||
context["season_episode"] = f"{context['season_episode']}{suffix}"
|
||||
return context
|
||||
|
||||
def _air_date_display(self) -> str:
|
||||
@@ -123,19 +166,28 @@ class Episode(Title):
|
||||
return f"{self.air_date.year:04}"
|
||||
return f"S{self.season:02}"
|
||||
|
||||
def _part_label(self) -> str:
|
||||
"""``.2`` selection-syntax suffix for console output, empty when part-less."""
|
||||
return f".{self.part}" if self.part is not None else ""
|
||||
|
||||
def __str__(self) -> str:
|
||||
if self.air_date:
|
||||
return "{title}{year} {date} {name}".format(
|
||||
# dated content has no SxxExx to hang the part off, but the parts still have to
|
||||
# be told apart, so the same .N suffix follows the date
|
||||
return "{title}{year} {date}{part} {name}".format(
|
||||
title=self.title,
|
||||
year=f" {self.year}" if self.year else "",
|
||||
date=self._air_date_display(),
|
||||
part=self._part_label(),
|
||||
name=self.name or "",
|
||||
).strip()
|
||||
return "{title}{year} S{season:02}E{number:02} {name}".format(
|
||||
# the console shows the -w selection syntax (S01E01.2), not the filename form
|
||||
return "{title}{year} S{season:02}E{number:02}{part} {name}".format(
|
||||
title=self.title,
|
||||
year=f" {self.year}" if self.year else "",
|
||||
season=self.season,
|
||||
number=self.number,
|
||||
part=self._part_label(),
|
||||
name=self.name or "",
|
||||
).strip()
|
||||
|
||||
@@ -143,7 +195,8 @@ class Episode(Title):
|
||||
if folder:
|
||||
template = config.get_folder_template("series")
|
||||
if template:
|
||||
context = self._build_template_context(media_info, show_service)
|
||||
# all parts of an episode land in the same season folder
|
||||
context = self._build_template_context(media_info, show_service, include_part=False)
|
||||
context["season"] = self._folder_season()
|
||||
context["year"] = self.year or "" # folders keep the year
|
||||
spacer = detect_spacer(template) # one style for the whole path
|
||||
@@ -167,7 +220,7 @@ class Episode(Title):
|
||||
derived_template = re.sub(r"^[\.\s]+|[\.\s]+$", "", derived_template)
|
||||
|
||||
formatter = TemplateFormatter(derived_template)
|
||||
context = self._build_template_context(media_info, show_service)
|
||||
context = self._build_template_context(media_info, show_service, include_part=False)
|
||||
context["season"] = self._folder_season()
|
||||
context["year"] = self.year or "" # folders keep the year
|
||||
|
||||
@@ -190,7 +243,8 @@ class Episode(Title):
|
||||
|
||||
class Series(SortedKeyList, ABC):
|
||||
def __init__(self, iterable: Optional[Iterable] = None):
|
||||
super().__init__(iterable, key=lambda x: (x.season, x.number, x.year or 0))
|
||||
# part slots before year so existing ties still resolve by year
|
||||
super().__init__(iterable, key=lambda x: (x.season, x.number, x.part or 0, x.year or 0))
|
||||
|
||||
def __str__(self) -> str:
|
||||
if not self:
|
||||
@@ -218,7 +272,7 @@ class Series(SortedKeyList, ABC):
|
||||
episode._air_date_display()
|
||||
if episode.air_date
|
||||
else str(episode.number).zfill(len(str(episodes)))
|
||||
)
|
||||
) + episode._part_label()
|
||||
if episode.name:
|
||||
season_tree.add(f"[bold]{label}.[/] [bright_black]{episode.name}")
|
||||
elif episode.air_date:
|
||||
|
||||
Reference in New Issue
Block a user