mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-26 10:55: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:
@@ -387,7 +387,8 @@ def _perform_download(
|
||||
if isinstance(wanted_raw, str):
|
||||
wanted_raw = [wanted_raw]
|
||||
# Only convert if not already in internal "SxE" format
|
||||
needs_conversion = any(not re.match(r"^\d+x\d+$", w) for w in wanted_raw)
|
||||
# the !? keeps a pre-parsed part exclusion from being re-fed through parse_tokens
|
||||
needs_conversion = any(not re.match(r"^!?\d+x\d+(\.\d+)?$", w) for w in wanted_raw)
|
||||
if needs_conversion:
|
||||
season_range = SeasonRange()
|
||||
params["wanted"] = season_range.parse_tokens(*wanted_raw)
|
||||
|
||||
@@ -93,6 +93,7 @@ LIST_HANDLER_TRANSPORT_KEYS = {
|
||||
"profile",
|
||||
"season",
|
||||
"episode",
|
||||
"part",
|
||||
"wanted",
|
||||
"proxy",
|
||||
"no_proxy",
|
||||
@@ -324,6 +325,11 @@ def require_fields(data: Dict[str, Any], *names: str) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _part_key_suffix(part: Optional[int]) -> str:
|
||||
"""`.2` selection-syntax suffix for a part-ful episode, empty otherwise."""
|
||||
return f".{part}" if part is not None else ""
|
||||
|
||||
|
||||
def serialize_title(title: Title_T) -> Dict[str, Any]:
|
||||
"""Convert a title object to JSON-serializable dict."""
|
||||
title_language = str(title.language) if hasattr(title, "language") and title.language else None
|
||||
@@ -336,7 +342,10 @@ def serialize_title(title: Title_T) -> Dict[str, Any]:
|
||||
cover_url = _data.get("cover_url") if isinstance(_data, dict) else None
|
||||
|
||||
is_episode = isinstance(title, Episode)
|
||||
episode_part = title.part if isinstance(title, Episode) else None
|
||||
if is_episode:
|
||||
# no part suffix here: remote_service._build_title rebuilds the Episode from this dict, so a
|
||||
# suffixed name plus the structural `part` below would render the part twice in the filename
|
||||
name = title.name if title.name else f"Episode {title.number:02d}"
|
||||
else:
|
||||
name = str(title.name) if hasattr(title, "name") else str(title)
|
||||
@@ -357,6 +366,8 @@ def serialize_title(title: Title_T) -> Dict[str, Any]:
|
||||
result["series_title"] = str(title.title)
|
||||
result["season"] = title.season
|
||||
result["number"] = title.number
|
||||
if episode_part is not None:
|
||||
result["part"] = episode_part # conditional, so part-less JSON is unchanged
|
||||
|
||||
return result
|
||||
|
||||
@@ -705,6 +716,7 @@ async def list_tracks_handler(data: Dict[str, Any], request: Optional[web.Reques
|
||||
wanted_param = data.get("wanted")
|
||||
season = data.get("season")
|
||||
episode = data.get("episode")
|
||||
part = data.get("part")
|
||||
|
||||
if hasattr(titles, "__iter__") and not isinstance(titles, str):
|
||||
titles_list = list(titles)
|
||||
@@ -729,7 +741,7 @@ async def list_tracks_handler(data: Dict[str, Any], request: Optional[web.Reques
|
||||
details={"wanted": wanted_param, "service": normalized_service},
|
||||
)
|
||||
elif season is not None and episode is not None:
|
||||
wanted = [f"{season}x{episode}"]
|
||||
wanted = [f"{season}x{episode}{_part_key_suffix(part)}"]
|
||||
|
||||
if wanted:
|
||||
# Filter titles based on wanted episodes, similar to how dl.py does it
|
||||
@@ -737,8 +749,8 @@ async def list_tracks_handler(data: Dict[str, Any], request: Optional[web.Reques
|
||||
log.debug(f"Filtering {len(titles_list)} titles with {len(wanted)} wanted episodes")
|
||||
for title in titles_list:
|
||||
if isinstance(title, Episode):
|
||||
episode_key = f"{title.season}x{title.number}"
|
||||
if episode_key in wanted:
|
||||
episode_key = f"{title.season}x{title.number}{_part_key_suffix(title.part)}"
|
||||
if title.matches_wanted(wanted):
|
||||
log.debug(f"Episode {episode_key} matches wanted list")
|
||||
matching_titles.append(title)
|
||||
else:
|
||||
@@ -755,7 +767,7 @@ async def list_tracks_handler(data: Dict[str, Any], request: Optional[web.Reques
|
||||
details={
|
||||
"service": normalized_service,
|
||||
"title_id": title_id,
|
||||
"wanted": wanted_param or f"{season}x{episode}",
|
||||
"wanted": wanted_param or wanted[0],
|
||||
},
|
||||
)
|
||||
|
||||
@@ -765,7 +777,7 @@ async def list_tracks_handler(data: Dict[str, Any], request: Optional[web.Reques
|
||||
failed_episodes = []
|
||||
|
||||
# Sort matching titles by season and episode number for consistent ordering
|
||||
sorted_titles = sorted(matching_titles, key=lambda t: (t.season, t.number))
|
||||
sorted_titles = sorted(matching_titles, key=lambda t: (t.season, t.number, t.part or 0))
|
||||
|
||||
for title in sorted_titles:
|
||||
try:
|
||||
@@ -786,12 +798,12 @@ async def list_tracks_handler(data: Dict[str, Any], request: Optional[web.Reques
|
||||
log.debug(f"Successfully got tracks for {title.season}x{title.number}")
|
||||
except SystemExit:
|
||||
# Service calls sys.exit() for unavailable episodes - catch and skip
|
||||
failed_episodes.append(f"S{title.season}E{title.number:02d}")
|
||||
failed_episodes.append(f"S{title.season}E{title.number:02d}{_part_key_suffix(title.part)}")
|
||||
log.debug(f"Episode {title.season}x{title.number} not available, skipping")
|
||||
continue
|
||||
except (Exception, SystemExit) as e:
|
||||
# Handle other errors gracefully
|
||||
failed_episodes.append(f"S{title.season}E{title.number:02d}")
|
||||
failed_episodes.append(f"S{title.season}E{title.number:02d}{_part_key_suffix(title.part)}")
|
||||
log.debug(f"Error getting tracks for {title.season}x{title.number}: {e}")
|
||||
continue
|
||||
|
||||
@@ -1586,6 +1598,7 @@ SESSION_TRANSPORT_KEYS = {
|
||||
"title_id",
|
||||
"season",
|
||||
"episode",
|
||||
"part",
|
||||
"wanted",
|
||||
"proxy",
|
||||
"no_proxy",
|
||||
|
||||
@@ -173,6 +173,7 @@ class Config:
|
||||
"episode",
|
||||
"season_episode",
|
||||
"episode_name",
|
||||
"part",
|
||||
"date",
|
||||
"quality",
|
||||
"resolution",
|
||||
|
||||
@@ -299,6 +299,7 @@ def _build_title(info: Dict[str, Any], service_tag: str, fallback_id: str) -> Un
|
||||
year=info.get("year"),
|
||||
language=lang,
|
||||
air_date=info.get("air_date"),
|
||||
part=info.get("part"),
|
||||
)
|
||||
return Movie(
|
||||
id_=info.get("id", fallback_id),
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -174,11 +174,18 @@ class SeasonRange(click.ParamType):
|
||||
|
||||
MIN_EPISODE = 0
|
||||
MAX_EPISODE = 999
|
||||
MIN_PART = 1
|
||||
MAX_PART = 99
|
||||
|
||||
def parse_tokens(self, *tokens: str) -> list[str]:
|
||||
"""
|
||||
Parse multiple tokens or ranged tokens as '{s}x{e}' strings.
|
||||
|
||||
An episode split into separately playable parts is addressed as '{s}x{e}.{p}'.
|
||||
A part range must stay inside one episode, since how many parts an episode has
|
||||
is not knowable here. A part-qualified exclusion cannot be removed from the
|
||||
computed keys (they are base keys), so it becomes a '!' key resolved at match time.
|
||||
|
||||
Supports exclusioning by putting a `-` before the token.
|
||||
|
||||
Example:
|
||||
@@ -189,6 +196,10 @@ class SeasonRange(click.ParamType):
|
||||
["2x1", "2x3", "2x4", "2x5"]
|
||||
>>> sr.parse_tokens("S01-S05", "-S03", "-S02E01")
|
||||
["1x0", "1x1", ..., "2x0", (...), "2x2", (...), "4x0", ..., "5x0", ...]
|
||||
>>> sr.parse_tokens("S01E01.1-S01E01.3")
|
||||
["1x1.1", "1x1.2", "1x1.3"]
|
||||
>>> sr.parse_tokens("S01E01", "-S01E01.2")
|
||||
["1x1", "!1x1.2"]
|
||||
"""
|
||||
if len(tokens) == 0:
|
||||
return []
|
||||
@@ -199,36 +210,56 @@ class SeasonRange(click.ParamType):
|
||||
if exclude:
|
||||
token = token[1:]
|
||||
parsed = [
|
||||
re.match(r"^S(?P<season>\d+)(E(?P<episode>\d+))?$", x, re.IGNORECASE) for x in re.split(r"[:-]", token)
|
||||
re.match(r"^S(?P<season>\d+)(E(?P<episode>\d+)(\.(?P<part>\d+))?)?$", x, re.IGNORECASE)
|
||||
for x in re.split(r"[:-]", token)
|
||||
]
|
||||
if len(parsed) > 2:
|
||||
self.fail(f"Invalid token, only a left and right range is acceptable: {token}")
|
||||
if len(parsed) == 1:
|
||||
# the same match object is read with different per-side defaults, so a bare
|
||||
# S01 spans from MIN_EPISODE to MAX_EPISODE
|
||||
parsed.append(parsed[0])
|
||||
if any(x is None for x in parsed):
|
||||
self.fail(f"Invalid token, syntax error occurred: {token}")
|
||||
from_season, from_episode = [
|
||||
int(v) if v is not None else self.MIN_EPISODE
|
||||
for k, v in parsed[0].groupdict().items()
|
||||
if parsed[0] # type: ignore[union-attr]
|
||||
]
|
||||
to_season, to_episode = [
|
||||
int(v) if v is not None else self.MAX_EPISODE
|
||||
for k, v in parsed[1].groupdict().items()
|
||||
if parsed[1] # type: ignore[union-attr]
|
||||
]
|
||||
left, right = parsed[0], parsed[1]
|
||||
from_season = int(left.group("season")) # type: ignore[union-attr]
|
||||
from_episode_raw = left.group("episode") # type: ignore[union-attr]
|
||||
from_episode = int(from_episode_raw) if from_episode_raw is not None else self.MIN_EPISODE
|
||||
from_part_raw = left.group("part") # type: ignore[union-attr]
|
||||
from_part = int(from_part_raw) if from_part_raw is not None else None
|
||||
to_season = int(right.group("season")) # type: ignore[union-attr]
|
||||
to_episode_raw = right.group("episode") # type: ignore[union-attr]
|
||||
to_episode = int(to_episode_raw) if to_episode_raw is not None else self.MAX_EPISODE
|
||||
to_part_raw = right.group("part") # type: ignore[union-attr]
|
||||
to_part = int(to_part_raw) if to_part_raw is not None else None
|
||||
if from_season > to_season:
|
||||
self.fail(f"Invalid range, left side season cannot be bigger than right side season: {token}")
|
||||
if from_season == to_season and from_episode > to_episode:
|
||||
self.fail(f"Invalid range, left side episode cannot be bigger than right side episode: {token}")
|
||||
if (from_part is None) != (to_part is None):
|
||||
self.fail(f"Invalid range, a part must be given on both sides or on neither: {token}")
|
||||
if from_part is not None and to_part is not None:
|
||||
if (from_season, from_episode) != (to_season, to_episode):
|
||||
self.fail(f"Invalid range, a part range must stay within one episode: {token}")
|
||||
if not all(self.MIN_PART <= p <= self.MAX_PART for p in (from_part, to_part)):
|
||||
self.fail(f"Invalid part, must be between {self.MIN_PART} and {self.MAX_PART}: {token}")
|
||||
if from_part > to_part:
|
||||
self.fail(f"Invalid range, left side part cannot be bigger than right side part: {token}")
|
||||
for p in range(from_part, to_part + 1):
|
||||
(computed if not exclude else exclusions).append(f"{from_season}x{from_episode}.{p}")
|
||||
continue
|
||||
for s in range(from_season, to_season + 1):
|
||||
for e in range(
|
||||
from_episode if s == from_season else 0, (self.MAX_EPISODE if s < to_season else to_episode) + 1
|
||||
):
|
||||
(computed if not exclude else exclusions).append(f"{s}x{e}")
|
||||
for exclusion in exclusions:
|
||||
if exclusion in computed:
|
||||
computed.remove(exclusion)
|
||||
if "." in exclusion:
|
||||
computed.append(f"!{exclusion}") # base key stays; resolved at match time
|
||||
else:
|
||||
# a base exclusion must drop that episode's part keys too, or they still match
|
||||
prefix = f"{exclusion}."
|
||||
computed = [k for k in computed if k != exclusion and not k.startswith(prefix)]
|
||||
return list(set(computed))
|
||||
|
||||
def convert(
|
||||
|
||||
Reference in New Issue
Block a user