mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-27 03:15:08 +00:00
refactor(core): lift title metadata enrichment out of dl into TitleMetadata
This commit is contained in:
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.title_metadata import TitleMetadata
|
||||
from unshackle.core.titles.episode import Episode, Series
|
||||
from unshackle.core.wire import apply_title_fields
|
||||
|
||||
@@ -25,8 +25,7 @@ def episode(season: int, number: int, part: int | None = None) -> Episode:
|
||||
|
||||
|
||||
def renumber(series: Series) -> Series:
|
||||
stub = SimpleNamespace(log=SimpleNamespace(info=lambda *a, **k: None))
|
||||
return dl.apply_continuous_episodes(stub, series)
|
||||
return TitleMetadata(log=SimpleNamespace(info=lambda *a, **k: None)).apply_continuous_episodes(series)
|
||||
|
||||
|
||||
def numbers(slots: list[tuple[int, int]]) -> list[tuple[int, int]]:
|
||||
|
||||
@@ -4,10 +4,10 @@ from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.commands.dl import parse_language
|
||||
from unshackle.core.providers.imdb import primary_language as imdb_language
|
||||
from unshackle.core.providers.omdb import primary_language as omdb_language
|
||||
from unshackle.core.providers.tvdb import primary_language as tvdb_language
|
||||
from unshackle.core.title_metadata import parse_language
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
|
||||
@@ -133,7 +133,7 @@ class _FakeProvider:
|
||||
def fill(
|
||||
monkeypatch: pytest.MonkeyPatch, episodes: list, mapping: dict, tvdb_id=73871, provider=True, order="official"
|
||||
):
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.title_metadata import TitleMetadata
|
||||
|
||||
fake = _FakeProvider(mapping, order) if provider else None
|
||||
monkeypatch.setattr(providers, "get_provider", lambda _name: fake)
|
||||
@@ -143,9 +143,8 @@ def fill(
|
||||
info=lambda *a, **k: logged.append(("info", a)),
|
||||
warning=lambda *a, **k: logged.append(("warning", a)),
|
||||
)
|
||||
stub = SimpleNamespace(tvdb_id=tvdb_id, log=logger)
|
||||
titles = Series(episodes)
|
||||
dl.fill_absolute_numbers(stub, titles, tvdb_id)
|
||||
TitleMetadata(tvdb_id=tvdb_id, log=logger).fill_absolute_numbers(titles, tvdb_id)
|
||||
return titles, fake, logged
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""The --daily air-date fill: dl.fill_air_dates and the daily_hint gate."""
|
||||
"""The --daily air-date fill: TitleMetadata.fill_air_dates and the daily_hint gate."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -48,7 +48,7 @@ def fill(
|
||||
daily=True,
|
||||
service_daily=False,
|
||||
):
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.title_metadata import TitleMetadata
|
||||
|
||||
fake = _FakeProvider(episodes) if provider else None
|
||||
monkeypatch.setattr(providers, "get_provider", lambda _name: fake)
|
||||
@@ -58,10 +58,8 @@ def fill(
|
||||
info=lambda *a, **k: logged.append(("info", a)),
|
||||
warning=lambda *a, **k: logged.append(("warning", a)),
|
||||
)
|
||||
stub = SimpleNamespace(tvdb_id=tvdb_id, log=logger, daily=daily, service_daily=service_daily)
|
||||
stub.daily_hint = lambda title=None: dl.daily_hint(stub, title)
|
||||
series = Series(titles)
|
||||
dl.fill_air_dates(stub, series, tvdb_id)
|
||||
TitleMetadata(tvdb_id=tvdb_id, log=logger, daily=service_daily, force_daily=daily).fill_air_dates(series, tvdb_id)
|
||||
return series, logged
|
||||
|
||||
|
||||
|
||||
@@ -2,7 +2,8 @@ from types import SimpleNamespace
|
||||
|
||||
from langcodes import Language
|
||||
|
||||
from unshackle.commands.dl import apply_enrich, load_tracks
|
||||
from unshackle.commands.dl import load_tracks
|
||||
from unshackle.core.title_metadata import Enrichment, apply_enrich
|
||||
from unshackle.core.titles import Episode, Movie, Song
|
||||
from unshackle.core.tracks import Chapters, Tracks
|
||||
from unshackle.core.wire import apply_title_fields
|
||||
@@ -21,14 +22,14 @@ def refreshing_service(info):
|
||||
def test_enrich_wins_over_a_movie_title_set_in_get_tracks():
|
||||
movie = Movie(id_="movie-0001", service=SERVICE, name="The Gold Seekers", year=2017)
|
||||
service = refreshing_service({"name": "Los Buscadores", "year": 2016, "language": "pt"})
|
||||
load_tracks(service, movie, name="The Gold Seekers", year=2017, language=Language.get("es"))
|
||||
load_tracks(service, movie, enrichment=Enrichment("The Gold Seekers", 2017, Language.get("es")))
|
||||
assert (movie.name, movie.year, str(movie.language)) == ("The Gold Seekers", 2017, "es")
|
||||
|
||||
|
||||
def test_enrich_wins_over_a_series_title_set_in_get_tracks():
|
||||
episode = Episode(id_="episode-0001", service=SERVICE, title="English", season=1, number=1, name="Pilot")
|
||||
service = refreshing_service({"series_title": "Local", "name": "Pilot", "year": 2016})
|
||||
load_tracks(service, episode, name="English", year=2017)
|
||||
load_tracks(service, episode, enrichment=Enrichment("English", 2017))
|
||||
assert (episode.title, episode.name, episode.year) == ("English", "Pilot", 2017)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
"""TitleMetadata: the external-ID lookups and the episode numbering a run applies to its titles."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import date
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from langcodes import Language
|
||||
|
||||
from unshackle.core import providers
|
||||
from unshackle.core.console import console
|
||||
from unshackle.core.providers import ExternalIds, MetadataResult
|
||||
from unshackle.core.title_metadata import TitleMetadata
|
||||
from unshackle.core.title_source import CacheIdentity
|
||||
from unshackle.core.titles import Episode, Movie, Movies, Series
|
||||
|
||||
CACHE = CacheIdentity("cacher", "show-1", "gb", "hash")
|
||||
CACHE_KWARGS = {
|
||||
"title_cacher": "cacher",
|
||||
"cache_title_id": "show-1",
|
||||
"cache_region": "gb",
|
||||
"cache_account_hash": "hash",
|
||||
}
|
||||
|
||||
|
||||
def ids(tmdb_id: int | None = None, imdb_id: str | None = None) -> dict[str, Any]:
|
||||
return {"tmdb_id": tmdb_id, "imdb_id": imdb_id, "tvdb_id": None, "anilist_id": None}
|
||||
|
||||
|
||||
class DummyService:
|
||||
pass
|
||||
|
||||
|
||||
def episode(season: int, number: int, **kwargs: Any) -> Episode:
|
||||
return Episode(
|
||||
id_=f"ep-{season}x{number}", service=DummyService, title="The Show", season=season, number=number, **kwargs
|
||||
)
|
||||
|
||||
|
||||
def movie() -> Movie:
|
||||
return Movie(id_="movie-1", service=DummyService, name="The Film", year=2001)
|
||||
|
||||
|
||||
class Providers:
|
||||
"""Records each provider call and answers resolve_by_ids with one result."""
|
||||
|
||||
def __init__(self, monkeypatch: pytest.MonkeyPatch, result: MetadataResult | None, tvdb: Any = None) -> None:
|
||||
self.result = result
|
||||
self.resolved: list[tuple[tuple, dict]] = []
|
||||
self.fetched: list[tuple] = []
|
||||
monkeypatch.setattr(providers, "resolve_by_ids", self.resolve)
|
||||
monkeypatch.setattr(providers, "fetch_external_ids", lambda *a, **k: self.fetched.append((*a, *k.values())))
|
||||
monkeypatch.setattr(providers, "get_provider", lambda _name: tvdb)
|
||||
|
||||
def resolve(self, *args: Any, **kwargs: Any) -> MetadataResult | None:
|
||||
self.resolved.append((args, kwargs))
|
||||
return self.result
|
||||
|
||||
|
||||
class FakeTvdb:
|
||||
def __init__(self, mapping: dict, episodes: list | None = None) -> None:
|
||||
self.mapping = mapping
|
||||
self.episodes = episodes or []
|
||||
self.ids: list = []
|
||||
|
||||
def detect_order(self, tvdb_id: int, _keys: list) -> str:
|
||||
self.ids.append(tvdb_id)
|
||||
return "official"
|
||||
|
||||
def get_order_map(self, tvdb_id: int, order: str, source_order: str | None = None) -> dict:
|
||||
return self.mapping
|
||||
|
||||
def get_episodes(self, tvdb_id: int, order: str) -> list:
|
||||
return self.episodes
|
||||
|
||||
|
||||
def found(tmdb_id: int | None = 1396, tvdb_id: int | None = None, **kwargs: Any) -> MetadataResult:
|
||||
return MetadataResult(external_ids=ExternalIds(tmdb_id=tmdb_id, tvdb_id=tvdb_id), source="tmdb", **kwargs)
|
||||
|
||||
|
||||
def test_enrich_resolves_the_given_ids_and_sets_the_metadata_on_each_title(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
calls = Providers(monkeypatch, found(title="Real Name", year=1999, original_language="ko"))
|
||||
metadata = TitleMetadata(tmdb_id=5, imdb_id="tt1", cache=CACHE, anime=True)
|
||||
titles = metadata.prepare(Series([episode(1, 1), episode(1, 2)]), enrich=True, tvdb_order="", continuous=False)
|
||||
|
||||
assert calls.resolved == [((), {**ids(5, "tt1"), **CACHE_KWARGS, "kind": "tv", "anime": True})]
|
||||
assert [(t.title, t.year, str(t.language)) for t in titles] == [
|
||||
("Real Name", 1999, "ko"),
|
||||
("Real Name", 1999, "ko"),
|
||||
]
|
||||
assert metadata.enrichment == ("Real Name", 1999, Language.get("ko"))
|
||||
|
||||
|
||||
def test_enrich_fills_absolute_numbers_from_the_resolved_tvdb_id(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
tvdb = FakeTvdb({(1, 1): (1, 1, None)})
|
||||
Providers(monkeypatch, found(tvdb_id=73871, title="Show"), tvdb)
|
||||
titles = TitleMetadata(tmdb_id=5).prepare(Series([episode(1, 1)]), enrich=True, tvdb_order="", continuous=False)
|
||||
assert tvdb.ids == [73871]
|
||||
assert [t.absolute for t in titles] == [1]
|
||||
|
||||
|
||||
def test_enrich_with_no_answer_keeps_the_service_values(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
Providers(monkeypatch, None)
|
||||
metadata = TitleMetadata(tmdb_id=5)
|
||||
titles = metadata.prepare(Movies([movie()]), enrich=True, tvdb_order="", continuous=False)
|
||||
assert [(t.name, t.year) for t in titles] == [("The Film", 2001)]
|
||||
assert metadata.enrichment == (None, None, None)
|
||||
|
||||
|
||||
def test_no_option_makes_no_provider_call(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
calls = Providers(monkeypatch, found())
|
||||
series = Series([episode(1, 1)])
|
||||
assert TitleMetadata(tmdb_id=5).prepare(series, enrich=False, tvdb_order="", continuous=False) is series
|
||||
assert calls.resolved == []
|
||||
|
||||
|
||||
def test_the_tvdb_order_resolves_a_tvdb_id_and_keeps_it_for_the_tags(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
calls = Providers(monkeypatch, found(tvdb_id=73871), FakeTvdb({(1, 1): (2, 1, None), (1, 2): (2, 2, None)}))
|
||||
metadata = TitleMetadata(tmdb_id=5, cache=CACHE)
|
||||
titles = metadata.prepare(Series([episode(1, 1), episode(1, 2)]), enrich=False, tvdb_order="dvd", continuous=True)
|
||||
|
||||
assert calls.resolved == [((), {**ids(5), **CACHE_KWARGS, "title": "The Show", "year": None, "kind": "tv"})]
|
||||
assert metadata.tvdb_id == 73871
|
||||
assert [(t.season, t.number) for t in titles] == [(2, 1), (2, 2)]
|
||||
|
||||
|
||||
def test_a_series_is_searched_once_and_each_title_fetches_its_external_ids(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
calls = Providers(monkeypatch, found(title="The Show"))
|
||||
monkeypatch.setattr(providers, "fuzzy_match", lambda a, b: a == b)
|
||||
metadata = TitleMetadata(cache=CACHE)
|
||||
metadata.search(episode(1, 1))
|
||||
metadata.search(episode(1, 2))
|
||||
|
||||
assert len(calls.resolved) == 1
|
||||
assert calls.resolved[0][1]["title"] == "The Show"
|
||||
assert (metadata.tmdb_id, metadata.search_source) == (1396, "tmdb")
|
||||
assert calls.fetched == [(1396, "tv", *CACHE)] * 2
|
||||
|
||||
|
||||
def test_a_search_that_matches_another_show_sets_no_id(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
calls = Providers(monkeypatch, found(title="Another Show"))
|
||||
monkeypatch.setattr(providers, "fuzzy_match", lambda a, b: a == b)
|
||||
metadata = TitleMetadata()
|
||||
metadata.search(episode(1, 1))
|
||||
assert (metadata.tmdb_id, metadata.searched, calls.fetched) == (None, True, [])
|
||||
|
||||
|
||||
def test_a_given_tmdb_id_is_kept(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
Providers(monkeypatch, found(tmdb_id=1, title="Other"))
|
||||
metadata = TitleMetadata(tmdb_id=5)
|
||||
metadata.search(episode(1, 1))
|
||||
assert metadata.tmdb_id == 5
|
||||
|
||||
|
||||
@pytest.mark.parametrize("source", ["simkl", "imdb"])
|
||||
def test_a_match_from_a_non_tmdb_source_fetches_no_tmdb_ids(monkeypatch: pytest.MonkeyPatch, source: str) -> None:
|
||||
calls = Providers(monkeypatch, None)
|
||||
metadata = TitleMetadata(tmdb_id=5)
|
||||
metadata.searched, metadata.search_source = True, source
|
||||
metadata.search(episode(1, 1))
|
||||
assert calls.fetched == []
|
||||
|
||||
|
||||
def test_a_movie_is_looked_up_only_for_a_listing(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
calls = Providers(monkeypatch, found())
|
||||
metadata = TitleMetadata(imdb_id="tt1")
|
||||
metadata.search(movie())
|
||||
assert calls.resolved == []
|
||||
metadata.search(movie(), listing=True)
|
||||
assert [kwargs["tmdb_id"] for _, kwargs in calls.resolved] == [None]
|
||||
assert metadata.tmdb_id is None
|
||||
|
||||
|
||||
def test_the_hints_take_the_title_before_the_source() -> None:
|
||||
anime_title = episode(1, 1)
|
||||
anime_title.anime = False
|
||||
daily_title = episode(1, 1)
|
||||
daily_title.daily = False
|
||||
metadata = TitleMetadata(anime=True, daily=True)
|
||||
assert (metadata.anime_hint(episode(1, 1)), metadata.anime_hint(anime_title)) == (True, False)
|
||||
assert (metadata.daily_hint(episode(1, 1)), metadata.daily_hint(daily_title)) == (True, False)
|
||||
assert TitleMetadata(force_daily=True).daily_hint(daily_title) is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("result", "level", "message"),
|
||||
[
|
||||
(None, logging.WARNING, "--enrich found no metadata"),
|
||||
(
|
||||
found(title="Real Name"),
|
||||
logging.WARNING,
|
||||
"--enrich source gave no year, language, kept the service's values",
|
||||
),
|
||||
(
|
||||
found(title="Real", year=1999, original_language="ko"),
|
||||
logging.INFO,
|
||||
"Original language from metadata: ko",
|
||||
),
|
||||
],
|
||||
ids=["nothing", "missing", "language"],
|
||||
)
|
||||
def test_enrich_reports_what_the_source_gave(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
result: MetadataResult | None,
|
||||
level: int,
|
||||
message: str,
|
||||
) -> None:
|
||||
Providers(monkeypatch, result)
|
||||
caplog.set_level(logging.INFO, logger="download")
|
||||
TitleMetadata(tmdb_id=5).prepare(Movies([movie()]), enrich=True, tvdb_order="", continuous=False)
|
||||
assert (level, message) in [(r.levelno, r.getMessage()) for r in caplog.records]
|
||||
|
||||
|
||||
def test_enrich_fills_the_air_dates_of_a_daily_series(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
tvdb = FakeTvdb({}, [{"seasonNumber": 1, "number": 1, "aired": "2026-08-10"}])
|
||||
Providers(monkeypatch, found(tvdb_id=73871), tvdb)
|
||||
metadata = TitleMetadata(tmdb_id=5, daily=True)
|
||||
titles = metadata.prepare(Series([episode(1, 1)]), enrich=True, tvdb_order="", continuous=False)
|
||||
assert [t.air_date for t in titles] == [date(2026, 8, 10)]
|
||||
|
||||
|
||||
def test_a_listing_prints_the_search_match(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
Providers(monkeypatch, found(title="The Show"))
|
||||
monkeypatch.setattr(providers, "fuzzy_match", lambda a, b: a == b)
|
||||
with console.capture() as captured:
|
||||
TitleMetadata().search(episode(1, 1), listing=True)
|
||||
assert "Search -> The Show (ID 1396)" in captured.get()
|
||||
|
||||
|
||||
def test_a_listing_with_no_movie_match_says_so(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
Providers(monkeypatch, None)
|
||||
with console.capture() as captured:
|
||||
TitleMetadata().search(movie(), listing=True)
|
||||
assert "Search -> No match found" in captured.get()
|
||||
|
||||
|
||||
def test_a_movie_fetches_the_movie_external_ids(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
calls = Providers(monkeypatch, None)
|
||||
TitleMetadata(tmdb_id=5, cache=CACHE).search(movie())
|
||||
assert calls.fetched == [(5, "movie", *CACHE)]
|
||||
@@ -212,18 +212,14 @@ class _FakeProvider:
|
||||
def renumber(monkeypatch: pytest.MonkeyPatch, episodes: list, mapping: dict):
|
||||
from types import SimpleNamespace
|
||||
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.title_metadata import TitleMetadata
|
||||
from unshackle.core.titles.episode import Series
|
||||
|
||||
monkeypatch.setattr(providers, "get_provider", lambda _name: _FakeProvider(mapping))
|
||||
errors: list = []
|
||||
stub = SimpleNamespace(
|
||||
tvdb_id=73871,
|
||||
tvdb_order="dvd",
|
||||
service="STUB",
|
||||
log=SimpleNamespace(warning=lambda *a, **k: None, info=lambda *a, **k: None, error=lambda *a: errors.append(a)),
|
||||
)
|
||||
return dl.apply_tvdb_order(stub, Series(episodes)), errors
|
||||
log = SimpleNamespace(warning=lambda *a, **k: None, info=lambda *a, **k: None, error=lambda *a: errors.append(a))
|
||||
metadata = TitleMetadata(tvdb_id=73871, service="EXAMPLE", log=log)
|
||||
return metadata.apply_tvdb_order(Series(episodes), "dvd"), errors
|
||||
|
||||
|
||||
def ep(season: int, number: int, part=None):
|
||||
|
||||
@@ -110,7 +110,6 @@ def run(
|
||||
cmd = Harness.__new__(Harness)
|
||||
cmd.log = logging.getLogger("test_kind_only")
|
||||
cmd.service = "FAKE"
|
||||
cmd.tmdb_searched = True
|
||||
cmd.completed_files = []
|
||||
cmd.skipped_titles = []
|
||||
cmd.skipped_subtitles = []
|
||||
|
||||
@@ -186,11 +186,12 @@ def test_tagging_ids_are_read_at_dispatch_not_snapshotted():
|
||||
import textwrap
|
||||
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.title_metadata import TitleMetadata
|
||||
|
||||
holder = SimpleNamespace(tmdb_id=None, imdb_id="tt0000001", tvdb_id=None)
|
||||
assert build_context(SimpleNamespace(), ids=dl.post_script_ids(holder))["tmdb"] == ""
|
||||
holder.tmdb_id = 1396
|
||||
assert build_context(SimpleNamespace(), ids=dl.post_script_ids(holder))["tmdb"] == "1396"
|
||||
metadata = TitleMetadata(imdb_id="tt0000001")
|
||||
assert build_context(SimpleNamespace(), ids=metadata.post_script_ids())["tmdb"] == ""
|
||||
metadata.tmdb_id = 1396
|
||||
assert build_context(SimpleNamespace(), ids=metadata.post_script_ids())["tmdb"] == "1396"
|
||||
|
||||
body = ast.parse(textwrap.dedent(inspect.getsource(dl.result)))
|
||||
for node in ast.walk(body):
|
||||
|
||||
+26
-384
@@ -8,15 +8,11 @@ import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from collections import Counter
|
||||
from collections.abc import Callable, Collection, Iterable, Sequence
|
||||
from concurrent import futures
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from copy import deepcopy
|
||||
from datetime import date, timedelta
|
||||
from functools import partial
|
||||
from itertools import groupby
|
||||
from operator import attrgetter
|
||||
from pathlib import Path
|
||||
from threading import Lock
|
||||
from typing import TYPE_CHECKING, Any, TypedDict
|
||||
@@ -24,7 +20,7 @@ from typing import TYPE_CHECKING, Any, TypedDict
|
||||
import click
|
||||
import mediaexport
|
||||
from click.core import ParameterSource
|
||||
from langcodes import Language, tag_is_valid
|
||||
from langcodes import Language
|
||||
from pymediainfo import MediaInfo
|
||||
from rich.console import Group
|
||||
from rich.padding import Padding
|
||||
@@ -32,7 +28,7 @@ from rich.rule import Rule
|
||||
from rich.spinner import Spinner
|
||||
from rich.table import Table
|
||||
|
||||
from unshackle.core import __version__, binaries, login, providers
|
||||
from unshackle.core import __version__, binaries, login
|
||||
from unshackle.core.cdm.choice import choose_cdm
|
||||
from unshackle.core.cdm.detect import cdm_system, cdm_type_stub, is_playready_cdm, is_remote_cdm
|
||||
from unshackle.core.config import cdm_entry_names_device, config, resolve_cdm_name, resolve_decryption
|
||||
@@ -66,7 +62,7 @@ from unshackle.core.launch import LaunchKeys, launch, load_service_config
|
||||
from unshackle.core.manifests.snapshot import capture
|
||||
from unshackle.core.mux_step import mux_title
|
||||
from unshackle.core.placement import SAMPLE_DIR, Placement, sample_name
|
||||
from unshackle.core.providers.tvdb import SEASON_TYPES, parse_int
|
||||
from unshackle.core.providers.tvdb import SEASON_TYPES
|
||||
from unshackle.core.proxies.resolve import (
|
||||
REGION,
|
||||
describe_explicit_proxy,
|
||||
@@ -82,6 +78,7 @@ from unshackle.core.run_plan import PlanError, RunOutcome, RunStopped, bitrate_r
|
||||
from unshackle.core.service import grow_session_pool
|
||||
from unshackle.core.services import ROUTING_PARAMS, Services
|
||||
from unshackle.core.temp import with_task_temp
|
||||
from unshackle.core.title_metadata import Enrichment, TitleMetadata, apply_enrich
|
||||
from unshackle.core.title_source import KeyArrival, TitleSource
|
||||
from unshackle.core.titles import Movie, Movies, Series, Song, Title_T
|
||||
from unshackle.core.titles.episode import Episode
|
||||
@@ -96,7 +93,6 @@ from unshackle.core.tracks.track import (
|
||||
has_encrypted_sample_entry,
|
||||
)
|
||||
from unshackle.core.utilities import (
|
||||
apply_original_language,
|
||||
find_font_with_fallbacks,
|
||||
get_debug_logger,
|
||||
get_system_fonts,
|
||||
@@ -153,14 +149,6 @@ class SkippedSubtitle(TypedDict):
|
||||
title: str
|
||||
|
||||
|
||||
def parse_language(tag: str | None) -> Language | None:
|
||||
"""A provider's original-language tag as a Language, or None if it is absent or not a real tag."""
|
||||
tag = (tag or "").strip()
|
||||
if not tag or not tag_is_valid(tag) or tag.startswith("und"):
|
||||
return None
|
||||
return Language.get(tag)
|
||||
|
||||
|
||||
def normalize_dl_config(dl_config: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Map aliased config keys (e.g. ``range``) to their Click parameter names (``range_``)."""
|
||||
return {DL_OPTION_ALIASES.get(key, key): value for key, value in dl_config.items()}
|
||||
@@ -236,35 +224,19 @@ def latest_episode_keys(titles: Any, latest_episode: bool, latest_episodes: int
|
||||
return list(dict.fromkeys((ep.season, ep.number) for ep in titles))[-count:]
|
||||
|
||||
|
||||
def apply_enrich(title: Title_T, name: str | None, year: int | None, language: Language | None) -> None:
|
||||
"""Set the --enrich name, year and original language on a title. A song takes only the language.
|
||||
|
||||
A service can set the title again in get_tracks, so dl applies them after that call too.
|
||||
"""
|
||||
if isinstance(title, Episode):
|
||||
title.title = name or title.title
|
||||
elif isinstance(title, Movie):
|
||||
title.name = name or title.name
|
||||
if isinstance(title, (Episode, Movie)):
|
||||
title.year = year or title.year
|
||||
if language:
|
||||
apply_original_language(title, language)
|
||||
|
||||
|
||||
def load_tracks(
|
||||
service: TitleSource,
|
||||
title: Title_T,
|
||||
*,
|
||||
name: str | None = None,
|
||||
year: int | None = None,
|
||||
language: Language | None = None,
|
||||
enrichment: Enrichment | None = None,
|
||||
workers: int | None = None,
|
||||
on_probe: Callable[[], None] | None = None,
|
||||
) -> None:
|
||||
"""Load the tracks and chapters of a title, then apply the --enrich name, year and language again."""
|
||||
title.tracks.add(probed_tracks(service, title, workers=workers, on_probe=on_probe), warn_only=True)
|
||||
title.tracks.chapters = service.get_chapters(title)
|
||||
apply_enrich(title, name, year, language)
|
||||
if enrichment:
|
||||
apply_enrich(title, *enrichment)
|
||||
|
||||
|
||||
def server_url(server_name: str | None) -> str:
|
||||
@@ -581,14 +553,6 @@ class dl:
|
||||
|
||||
return created_paths
|
||||
|
||||
def post_script_ids(self) -> dict[str, Any]:
|
||||
"""Tagging IDs as they stand right now.
|
||||
|
||||
Read at each post-script call, never snapshotted: the search inside the title loop
|
||||
finds an Episode's TMDB ID, so a snapshot taken before it is always empty.
|
||||
"""
|
||||
return {"tmdb": self.tmdb_id, "imdb": self.imdb_id, "tvdb": self.tvdb_id}
|
||||
|
||||
@click.command(
|
||||
short_help="Download, Decrypt, and Mux tracks for titles from a Service.",
|
||||
cls=Services,
|
||||
@@ -1202,8 +1166,6 @@ class dl:
|
||||
self.enrich = enrich
|
||||
self.daily = daily
|
||||
self.output_dir = output_dir
|
||||
self.service_anime = False
|
||||
self.service_daily = False
|
||||
|
||||
if self.daily and not self.enrich:
|
||||
self.log.warning("--daily takes TVDB air dates only with --enrich")
|
||||
@@ -1536,10 +1498,6 @@ class dl:
|
||||
if continue_downloads:
|
||||
config.continue_downloads = True
|
||||
config.sample = sample
|
||||
self.tmdb_searched = False
|
||||
self.search_source = None
|
||||
self.service_anime = service.ANIME
|
||||
self.service_daily = service.DAILY
|
||||
# a remote session sends --cdm to the server, which can hand it the tracks above its cap
|
||||
if self.cdm_override and service.key_arrival is KeyArrival.EXPORT:
|
||||
self.log.warning("--cdm is ignored: an import uses the keys in the export")
|
||||
@@ -1727,58 +1685,21 @@ class dl:
|
||||
level="INFO", operation="get_titles", service=self.service, context={"titles": titles_info}
|
||||
)
|
||||
|
||||
title_cacher, cache_title_id, cache_region, cache_account_hash = service.cache_identity()
|
||||
|
||||
enrich_lang: Language | None = None
|
||||
enrich_title: str | None = None
|
||||
enrich_year: int | None = None
|
||||
if self.enrich:
|
||||
sample_title = titles[0] if hasattr(titles, "__getitem__") else titles
|
||||
kind = "tv" if isinstance(sample_title, Episode) else "movie"
|
||||
|
||||
enrich_result = providers.resolve_by_ids(
|
||||
metadata = TitleMetadata(
|
||||
self.tmdb_id,
|
||||
self.imdb_id,
|
||||
self.tvdb_id,
|
||||
self.anilist_id,
|
||||
kind=kind,
|
||||
title_cacher=title_cacher,
|
||||
cache_title_id=cache_title_id,
|
||||
cache_region=cache_region,
|
||||
cache_account_hash=cache_account_hash,
|
||||
anime=self.anime_hint(sample_title),
|
||||
cache=service.cache_identity(),
|
||||
service=self.service,
|
||||
anime=service.ANIME,
|
||||
daily=service.DAILY,
|
||||
force_daily=self.daily,
|
||||
log=self.log,
|
||||
)
|
||||
titles = metadata.prepare(
|
||||
titles, enrich=self.enrich, tvdb_order=self.tvdb_order, continuous=self.continuous_episodes
|
||||
)
|
||||
if enrich_result:
|
||||
enrich_title = enrich_result.title
|
||||
enrich_year = enrich_result.year
|
||||
enrich_lang = parse_language(enrich_result.original_language)
|
||||
|
||||
if enrich_lang:
|
||||
self.log.info(f"Original language from metadata: {enrich_lang}")
|
||||
if not (enrich_title or enrich_year or enrich_lang):
|
||||
self.log.warning("--enrich found no metadata")
|
||||
elif missing := [
|
||||
name
|
||||
for name, value in (("title", enrich_title), ("year", enrich_year), ("language", enrich_lang))
|
||||
if not value
|
||||
]:
|
||||
self.log.warning(f"--enrich source gave no {', '.join(missing)}, kept the service's values")
|
||||
|
||||
if isinstance(titles, (Series, Movies)):
|
||||
for t in titles:
|
||||
apply_enrich(t, enrich_title, enrich_year, enrich_lang)
|
||||
|
||||
if isinstance(titles, Series):
|
||||
enrich_tvdb_id = self.tvdb_id or (enrich_result.external_ids.tvdb_id if enrich_result else None)
|
||||
self.fill_absolute_numbers(titles, enrich_tvdb_id)
|
||||
if any(self.daily_hint(t) for t in titles):
|
||||
self.fill_air_dates(titles, enrich_tvdb_id)
|
||||
|
||||
if self.tvdb_order and isinstance(titles, Series):
|
||||
titles = self.apply_tvdb_order(titles, title_cacher, cache_title_id, cache_region, cache_account_hash)
|
||||
|
||||
if self.continuous_episodes and isinstance(titles, Series):
|
||||
titles = self.apply_continuous_episodes(titles)
|
||||
|
||||
console.print(Padding(Rule(f"[rule.text]{titles.__class__.__name__}: {titles}"), (1, 2)))
|
||||
print_listing(titles.tree(verbose=list_titles))
|
||||
@@ -1991,76 +1912,7 @@ class dl:
|
||||
title_rule = f"Track {title.track:02}: {title.name}" if isinstance(title, Song) else str(title)
|
||||
console.print(Padding(Rule(f"[rule.text]{title_rule}"), (1, 2)))
|
||||
|
||||
if isinstance(title, Episode) and not self.tmdb_searched:
|
||||
kind = "tv"
|
||||
tmdb_title: str | None = None
|
||||
has_ids = bool(self.tmdb_id or self.imdb_id or self.tvdb_id or self.anilist_id)
|
||||
result = providers.resolve_by_ids(
|
||||
self.tmdb_id,
|
||||
self.imdb_id,
|
||||
self.tvdb_id,
|
||||
self.anilist_id,
|
||||
title=title.title,
|
||||
year=title.year,
|
||||
kind=kind,
|
||||
title_cacher=title_cacher,
|
||||
cache_title_id=cache_title_id,
|
||||
cache_region=cache_region,
|
||||
cache_account_hash=cache_account_hash,
|
||||
anime=self.anime_hint(title),
|
||||
)
|
||||
if result:
|
||||
if has_ids:
|
||||
tmdb_title = result.title
|
||||
if not self.tmdb_id:
|
||||
self.tmdb_id = result.external_ids.tmdb_id
|
||||
elif result.title and providers.fuzzy_match(result.title, title.title):
|
||||
self.tmdb_id = result.external_ids.tmdb_id
|
||||
tmdb_title = result.title
|
||||
self.search_source = result.source
|
||||
if list_ or list_titles:
|
||||
if self.tmdb_id:
|
||||
console.print(
|
||||
Padding(
|
||||
f"Search -> {tmdb_title or '?'} [bright_black](ID {self.tmdb_id})",
|
||||
(0, 5),
|
||||
)
|
||||
)
|
||||
else:
|
||||
console.print(Padding("Search -> [bright_black]No match found[/]", (0, 5)))
|
||||
self.tmdb_searched = True
|
||||
|
||||
if isinstance(title, Movie) and (list_ or list_titles) and not self.tmdb_id:
|
||||
movie_result = providers.resolve_by_ids(
|
||||
None,
|
||||
self.imdb_id,
|
||||
self.tvdb_id,
|
||||
self.anilist_id,
|
||||
title=title.name,
|
||||
year=title.year,
|
||||
kind="movie",
|
||||
title_cacher=title_cacher,
|
||||
cache_title_id=cache_title_id,
|
||||
cache_region=cache_region,
|
||||
cache_account_hash=cache_account_hash,
|
||||
anime=self.anime_hint(title),
|
||||
)
|
||||
if movie_result and movie_result.external_ids.tmdb_id:
|
||||
console.print(
|
||||
Padding(
|
||||
f"Search -> {movie_result.title or '?'} "
|
||||
f"[bright_black](ID {movie_result.external_ids.tmdb_id})",
|
||||
(0, 5),
|
||||
)
|
||||
)
|
||||
else:
|
||||
console.print(Padding("Search -> [bright_black]No match found[/]", (0, 5)))
|
||||
|
||||
if self.tmdb_id and getattr(self, "search_source", None) not in ("simkl", "imdb"):
|
||||
kind = "tv" if isinstance(title, Episode) else "movie"
|
||||
providers.fetch_external_ids(
|
||||
self.tmdb_id, kind, title_cacher, cache_title_id, cache_region, cache_account_hash
|
||||
)
|
||||
metadata.search(title, listing=list_ or list_titles)
|
||||
|
||||
if slow and i != 0:
|
||||
delay = random.randint(slow[0], slow[1])
|
||||
@@ -2085,9 +1937,7 @@ class dl:
|
||||
load_tracks(
|
||||
service,
|
||||
title,
|
||||
name=enrich_title,
|
||||
year=enrich_year,
|
||||
language=enrich_lang,
|
||||
enrichment=metadata.enrichment,
|
||||
workers=workers,
|
||||
on_probe=partial(tracks_spinner.update, text="Probing HDR10 tracks for HDR10+..."),
|
||||
)
|
||||
@@ -2437,7 +2287,7 @@ class dl:
|
||||
build_context(
|
||||
title,
|
||||
service=self.service,
|
||||
ids=self.post_script_ids(),
|
||||
ids=metadata.post_script_ids(),
|
||||
error=f"{type(e).__name__}: {e}",
|
||||
),
|
||||
postscript,
|
||||
@@ -2705,11 +2555,11 @@ class dl:
|
||||
tags.tag_file(
|
||||
final_path,
|
||||
title,
|
||||
self.tmdb_id,
|
||||
self.imdb_id,
|
||||
self.tvdb_id,
|
||||
self.anilist_id,
|
||||
self.anime_hint(title),
|
||||
metadata.tmdb_id,
|
||||
metadata.imdb_id,
|
||||
metadata.tvdb_id,
|
||||
metadata.anilist_id,
|
||||
metadata.anime_hint(title),
|
||||
session=service.session,
|
||||
)
|
||||
if include_sample:
|
||||
@@ -2726,7 +2576,7 @@ class dl:
|
||||
filepath=final_path,
|
||||
sidecars=sidecar_files.get(muxed_path, []),
|
||||
service=self.service,
|
||||
ids=self.post_script_ids(),
|
||||
ids=metadata.post_script_ids(),
|
||||
)
|
||||
dispatch("success", "file", post_script_context, postscript)
|
||||
post_script_last.setdefault(post_script_group(title), {})[final_path.parent] = (
|
||||
@@ -2808,214 +2658,6 @@ class dl:
|
||||
if returncode > 1 or not output.exists():
|
||||
self.log.warning(f"mkvmerge wrote no sample for {source.name}")
|
||||
|
||||
def anime_hint(self, title: Title_T | None = None) -> bool:
|
||||
"""Whether metadata lookups for this title should prefer AniList."""
|
||||
per_title = getattr(title, "anime", None)
|
||||
return self.service_anime if per_title is None else bool(per_title)
|
||||
|
||||
def daily_hint(self, title: Title_T | None = None) -> bool:
|
||||
"""Whether this title is daily content named by air date."""
|
||||
per_title = getattr(title, "daily", None)
|
||||
return self.daily or (self.service_daily if per_title is None else bool(per_title))
|
||||
|
||||
def fill_air_dates(self, titles: Series, tvdb_id: int | None = None) -> None:
|
||||
"""Fill in missing episode air dates from TVDB.
|
||||
|
||||
Additive only: an air date the service already set is kept.
|
||||
"""
|
||||
tvdb = providers.get_provider("tvdb")
|
||||
if not tvdb:
|
||||
self.log.debug("Air dates need a tvdb_api_key in your config, skipping.")
|
||||
return
|
||||
|
||||
if not tvdb_id:
|
||||
self.log.debug("Could not resolve a TVDB ID, skipping air dates.")
|
||||
return
|
||||
|
||||
wanted = [t for t in titles if self.daily_hint(t)]
|
||||
if not wanted:
|
||||
return
|
||||
|
||||
keys = list(dict.fromkeys((t.season, t.number) for t in titles))
|
||||
source_order = tvdb.detect_order(tvdb_id, keys) # type: ignore[attr-defined]
|
||||
episodes = tvdb.get_episodes(tvdb_id, source_order) # type: ignore[attr-defined]
|
||||
if not episodes:
|
||||
self.log.debug("TVDB listed no episodes for series %s, skipping air dates.", tvdb_id)
|
||||
return
|
||||
|
||||
aired_by_key: dict[tuple[int, int], str] = {}
|
||||
for episode in episodes:
|
||||
season, number = parse_int(episode.get("seasonNumber")), parse_int(episode.get("number"))
|
||||
aired = episode.get("aired")
|
||||
if season is None or number is None or not aired:
|
||||
continue
|
||||
aired_by_key[(season, number)] = str(aired)
|
||||
|
||||
# TVDB carries placeholder schedule dates for unaired episodes. Stamping one would
|
||||
# name the file with a date the episode never aired on.
|
||||
limit = date.today() + timedelta(days=1)
|
||||
|
||||
filled = 0
|
||||
for title in wanted:
|
||||
if title.air_date is not None:
|
||||
continue
|
||||
aired = aired_by_key.get((title.season, title.number))
|
||||
if not aired:
|
||||
continue
|
||||
try:
|
||||
air_date = date.fromisoformat(aired[:10])
|
||||
except ValueError:
|
||||
continue
|
||||
if air_date.year < 1970 or air_date > limit:
|
||||
continue
|
||||
title.air_date = air_date
|
||||
filled += 1
|
||||
|
||||
if filled:
|
||||
self.log.info("Filled air dates for %d episode(s) from TVDB (ID %s).", filled, tvdb_id)
|
||||
|
||||
def fill_absolute_numbers(self, titles: Series, tvdb_id: int | None = None) -> None:
|
||||
"""Fill in missing absolute episode numbers from TVDB's absolute order.
|
||||
|
||||
Additive only: season and number are never written, and an absolute number the
|
||||
service already set is kept.
|
||||
"""
|
||||
tvdb = providers.get_provider("tvdb")
|
||||
if not tvdb:
|
||||
self.log.debug("Absolute episode numbers need a tvdb_api_key in your config, skipping.")
|
||||
return
|
||||
|
||||
if not tvdb_id:
|
||||
self.log.debug("Could not resolve a TVDB ID, skipping absolute episode numbers.")
|
||||
return
|
||||
|
||||
keys = list(dict.fromkeys((t.season, t.number) for t in titles))
|
||||
source_order = tvdb.detect_order(tvdb_id, keys) # type: ignore[attr-defined]
|
||||
if source_order == "absolute":
|
||||
# the service already numbers in absolute order; get_order_map would return the
|
||||
# empty same-order map, but here the episode numbers are their own fill
|
||||
mapping = {key: (*key, None) for key in keys}
|
||||
else:
|
||||
mapping = tvdb.get_order_map(tvdb_id, "absolute", source_order) # type: ignore[attr-defined]
|
||||
if not mapping:
|
||||
self.log.debug("TVDB has no absolute order for series %s, skipping absolute episode numbers.", tvdb_id)
|
||||
return
|
||||
|
||||
filled = 0
|
||||
for title in titles:
|
||||
if title.absolute is not None:
|
||||
continue
|
||||
entry = mapping.get((title.season, title.number))
|
||||
if not entry:
|
||||
continue
|
||||
title.absolute = entry[1]
|
||||
filled += 1
|
||||
|
||||
if filled:
|
||||
self.log.info("Filled absolute numbers for %d episode(s) from TVDB (ID %s).", filled, tvdb_id)
|
||||
|
||||
def apply_continuous_episodes(self, titles: Series) -> Series:
|
||||
"""Number each season on from the last episode of the season before it.
|
||||
|
||||
Season 0 and episode 0 keep their numbers, and a season that already starts past the season before it is kept.
|
||||
The Series is rebuilt, as it does not re-sort an episode whose number changed.
|
||||
"""
|
||||
last = 0
|
||||
renumbered = 0
|
||||
for season, group in groupby(titles, key=attrgetter("season")):
|
||||
episodes = [t for t in group if t.number]
|
||||
if not season or not episodes:
|
||||
continue
|
||||
if min(t.number for t in episodes) <= last:
|
||||
for t in episodes:
|
||||
t.number += last
|
||||
renumbered += len(episodes)
|
||||
last = max(t.number for t in episodes)
|
||||
self.log.info("Numbered %d episode(s) on from the season before.", renumbered)
|
||||
return type(titles)(list(titles))
|
||||
|
||||
def apply_tvdb_order(
|
||||
self,
|
||||
titles: Series,
|
||||
title_cacher: Any = None,
|
||||
cache_title_id: str | None = None,
|
||||
cache_region: str | None = None,
|
||||
cache_account_hash: str | None = None,
|
||||
) -> Series:
|
||||
"""Renumber episodes from the service's own numbering into a TVDB season order."""
|
||||
tvdb = providers.get_provider("tvdb")
|
||||
if not tvdb:
|
||||
self.log.warning("--tvdb-order needs a tvdb_api_key in your config, skipping renumber.")
|
||||
return titles
|
||||
|
||||
tvdb_id = self.tvdb_id
|
||||
if not tvdb_id:
|
||||
show = titles[0]
|
||||
result = providers.resolve_by_ids(
|
||||
self.tmdb_id,
|
||||
self.imdb_id,
|
||||
None,
|
||||
title=show.title,
|
||||
year=show.year,
|
||||
kind="tv",
|
||||
title_cacher=title_cacher,
|
||||
cache_title_id=cache_title_id,
|
||||
cache_region=cache_region,
|
||||
cache_account_hash=cache_account_hash,
|
||||
)
|
||||
tvdb_id = result.external_ids.tvdb_id if result else None
|
||||
if not tvdb_id:
|
||||
self.log.warning("Could not resolve a TVDB ID for %r, skipping %s renumber.", str(titles), self.tvdb_order)
|
||||
return titles
|
||||
self.tvdb_id = tvdb_id # keep the mux tag on the series the renumbering used
|
||||
|
||||
# parts of one episode share a (season, number) slot; without the dedupe the
|
||||
# collision check below reads them as several episodes clashing on one slot
|
||||
keys = list(dict.fromkeys((t.season, t.number) for t in titles))
|
||||
source_order = tvdb.detect_order(tvdb_id, keys) # type: ignore[attr-defined]
|
||||
if source_order == self.tvdb_order:
|
||||
self.log.info("%s already lists this series in TVDB %s order.", self.service, self.tvdb_order)
|
||||
return titles
|
||||
|
||||
mapping = tvdb.get_order_map(tvdb_id, self.tvdb_order, source_order) # type: ignore[attr-defined]
|
||||
if not mapping:
|
||||
return titles
|
||||
|
||||
# an unmapped episode keeps its own numbering and can land on a remapped episode's slot
|
||||
renumbered = [mapping.get(key, (*key, None))[:2] for key in keys]
|
||||
unmapped = sum(1 for key in keys if key not in mapping)
|
||||
collisions = [slot for slot, count in Counter(renumbered).items() if count > 1]
|
||||
if collisions:
|
||||
self.log.error(
|
||||
"TVDB's %s order misses %d episode(s) and puts two in %d slot(s), keeping the %s numbering of %s",
|
||||
self.tvdb_order,
|
||||
unmapped,
|
||||
len(collisions),
|
||||
source_order,
|
||||
self.service,
|
||||
)
|
||||
return titles
|
||||
|
||||
for title in titles:
|
||||
entry = mapping.get((title.season, title.number))
|
||||
if not entry:
|
||||
continue
|
||||
title.season, title.number, tvdb_name = entry
|
||||
if tvdb_name and not title.name:
|
||||
title.name = tvdb_name
|
||||
|
||||
if unmapped:
|
||||
self.log.warning(
|
||||
"%d episode(s) are not in TVDB's %s order and keep their %s numbering.",
|
||||
unmapped,
|
||||
self.tvdb_order,
|
||||
source_order,
|
||||
)
|
||||
self.log.info("Renumbered episodes from TVDB %s to %s order (ID %s).", source_order, self.tvdb_order, tvdb_id)
|
||||
|
||||
# Series is a SortedKeyList; renumbering in place does not re-sort it
|
||||
return type(titles)(list(titles))
|
||||
|
||||
@staticmethod
|
||||
def title_to_meta(title: Title_T) -> dict[str, Any]:
|
||||
"""Capture the title fields needed to rebuild a Title for output naming on import."""
|
||||
|
||||
@@ -0,0 +1,383 @@
|
||||
"""The external IDs of a download's titles and the episode numbering the metadata providers give them."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections import Counter
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, timedelta
|
||||
from itertools import groupby
|
||||
from operator import attrgetter
|
||||
from typing import Any, NamedTuple
|
||||
|
||||
from langcodes import Language, tag_is_valid
|
||||
from rich.padding import Padding
|
||||
|
||||
from unshackle.core import providers
|
||||
from unshackle.core.console import console
|
||||
from unshackle.core.providers import MetadataResult
|
||||
from unshackle.core.providers.tvdb import parse_int
|
||||
from unshackle.core.title_source import CacheIdentity
|
||||
from unshackle.core.titles import Episode, Movie, Movies, Series, Title_T, Titles_T
|
||||
from unshackle.core.utilities import apply_original_language
|
||||
|
||||
|
||||
def parse_language(tag: str | None) -> Language | None:
|
||||
"""A provider's original-language tag as a Language, or None if it is absent or not a real tag."""
|
||||
tag = (tag or "").strip()
|
||||
if not tag or not tag_is_valid(tag) or tag.startswith("und"):
|
||||
return None
|
||||
return Language.get(tag)
|
||||
|
||||
|
||||
def apply_enrich(title: Title_T, name: str | None, year: int | None, language: Language | None) -> None:
|
||||
"""Set the --enrich name, year and original language on a title. A song takes only the language.
|
||||
|
||||
A service can set the title again in get_tracks, so dl applies them after that call too.
|
||||
"""
|
||||
if isinstance(title, Episode):
|
||||
title.title = name or title.title
|
||||
elif isinstance(title, Movie):
|
||||
title.name = name or title.name
|
||||
if isinstance(title, (Episode, Movie)):
|
||||
title.year = year or title.year
|
||||
if language:
|
||||
apply_original_language(title, language)
|
||||
|
||||
|
||||
class Enrichment(NamedTuple):
|
||||
"""The --enrich name, year and original language; None where the metadata source gave none."""
|
||||
|
||||
name: str | None = None
|
||||
year: int | None = None
|
||||
language: Language | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class TitleMetadata:
|
||||
"""The external IDs of one run, and the metadata lookups that resolve them and renumber its episodes.
|
||||
|
||||
The IDs start as the ones the user gave. ``prepare`` and ``search`` add the IDs that the lookups resolve,
|
||||
and tagging and post-scripts read them as they stand.
|
||||
"""
|
||||
|
||||
tmdb_id: int | None = None
|
||||
imdb_id: str | None = None
|
||||
tvdb_id: int | None = None
|
||||
anilist_id: int | str | None = None
|
||||
cache: CacheIdentity = CacheIdentity(None, None, None, None)
|
||||
service: str | None = None
|
||||
anime: bool = False
|
||||
daily: bool = False
|
||||
force_daily: bool = False
|
||||
log: logging.Logger = field(default_factory=lambda: logging.getLogger("download"))
|
||||
enrichment: Enrichment = field(default=Enrichment(), init=False)
|
||||
searched: bool = field(default=False, init=False)
|
||||
search_source: str | None = field(default=None, init=False)
|
||||
|
||||
def post_script_ids(self) -> dict[str, Any]:
|
||||
"""Tagging IDs as they stand right now.
|
||||
|
||||
Read at each post-script call, never snapshotted: the search inside the title loop
|
||||
finds an Episode's TMDB ID, so a snapshot taken before it is always empty.
|
||||
"""
|
||||
return {"tmdb": self.tmdb_id, "imdb": self.imdb_id, "tvdb": self.tvdb_id}
|
||||
|
||||
def anime_hint(self, title: Title_T | None = None) -> bool:
|
||||
"""Whether metadata lookups for this title should prefer AniList."""
|
||||
per_title = getattr(title, "anime", None)
|
||||
return self.anime if per_title is None else bool(per_title)
|
||||
|
||||
def daily_hint(self, title: Title_T | None = None) -> bool:
|
||||
"""Whether this title is daily content named by air date."""
|
||||
per_title = getattr(title, "daily", None)
|
||||
return self.force_daily or (self.daily if per_title is None else bool(per_title))
|
||||
|
||||
def cache_kwargs(self) -> dict[str, Any]:
|
||||
"""The cache identity of this run as the cache keywords of the metadata lookups."""
|
||||
return {
|
||||
"title_cacher": self.cache.cacher,
|
||||
"cache_title_id": self.cache.title_id,
|
||||
"cache_region": self.cache.region,
|
||||
"cache_account_hash": self.cache.account_hash,
|
||||
}
|
||||
|
||||
def resolve(self, **kwargs: Any) -> MetadataResult | None:
|
||||
"""``providers.resolve_by_ids`` with the IDs and the cache of this run; a keyword overrides either."""
|
||||
ids = {"tmdb_id": self.tmdb_id, "imdb_id": self.imdb_id, "tvdb_id": self.tvdb_id, "anilist_id": self.anilist_id}
|
||||
return providers.resolve_by_ids(**{**ids, **self.cache_kwargs(), **kwargs})
|
||||
|
||||
def prepare(self, titles: Titles_T, *, enrich: bool, tvdb_order: str, continuous: bool) -> Titles_T:
|
||||
"""Apply --enrich, then --tvdb-order, then --continuous-episodes, and return the titles."""
|
||||
if enrich:
|
||||
self.enrich(titles)
|
||||
if tvdb_order and isinstance(titles, Series):
|
||||
titles = self.apply_tvdb_order(titles, tvdb_order)
|
||||
if continuous and isinstance(titles, Series):
|
||||
titles = self.apply_continuous_episodes(titles)
|
||||
return titles
|
||||
|
||||
def enrich(self, titles: Titles_T) -> None:
|
||||
"""Set the provider's name, year and original language on each title, then fill a series from TVDB."""
|
||||
sample_title = titles[0] if hasattr(titles, "__getitem__") else titles
|
||||
kind = "tv" if isinstance(sample_title, Episode) else "movie"
|
||||
|
||||
result = self.resolve(kind=kind, anime=self.anime_hint(sample_title))
|
||||
self.enrichment = (
|
||||
Enrichment(result.title, result.year, parse_language(result.original_language)) if result else Enrichment()
|
||||
)
|
||||
name, year, language = self.enrichment
|
||||
|
||||
if language:
|
||||
self.log.info(f"Original language from metadata: {language}")
|
||||
if not (name or year or language):
|
||||
self.log.warning("--enrich found no metadata")
|
||||
elif missing := [
|
||||
label for label, value in (("title", name), ("year", year), ("language", language)) if not value
|
||||
]:
|
||||
self.log.warning(f"--enrich source gave no {', '.join(missing)}, kept the service's values")
|
||||
|
||||
if isinstance(titles, (Series, Movies)):
|
||||
for t in titles:
|
||||
apply_enrich(t, name, year, language)
|
||||
|
||||
if isinstance(titles, Series):
|
||||
tvdb_id = self.tvdb_id or (result.external_ids.tvdb_id if result else None)
|
||||
self.fill_absolute_numbers(titles, tvdb_id)
|
||||
if any(self.daily_hint(t) for t in titles):
|
||||
self.fill_air_dates(titles, tvdb_id)
|
||||
|
||||
def search(self, title: Title_T, listing: bool = False) -> None:
|
||||
"""Find the TMDB ID of a series once, and fetch the external IDs of each title.
|
||||
|
||||
``listing`` prints the match, and looks a movie up as well.
|
||||
"""
|
||||
if isinstance(title, Episode) and not self.searched:
|
||||
tmdb_title: str | None = None
|
||||
has_ids = bool(self.tmdb_id or self.imdb_id or self.tvdb_id or self.anilist_id)
|
||||
result = self.resolve(
|
||||
title=title.title,
|
||||
year=title.year,
|
||||
kind="tv",
|
||||
anime=self.anime_hint(title),
|
||||
)
|
||||
if result:
|
||||
if has_ids:
|
||||
tmdb_title = result.title
|
||||
if not self.tmdb_id:
|
||||
self.tmdb_id = result.external_ids.tmdb_id
|
||||
elif result.title and providers.fuzzy_match(result.title, title.title):
|
||||
self.tmdb_id = result.external_ids.tmdb_id
|
||||
tmdb_title = result.title
|
||||
self.search_source = result.source
|
||||
if listing:
|
||||
if self.tmdb_id:
|
||||
console.print(Padding(f"Search -> {tmdb_title or '?'} [bright_black](ID {self.tmdb_id})", (0, 5)))
|
||||
else:
|
||||
console.print(Padding("Search -> [bright_black]No match found[/]", (0, 5)))
|
||||
self.searched = True
|
||||
|
||||
if isinstance(title, Movie) and listing and not self.tmdb_id:
|
||||
movie_result = self.resolve(
|
||||
tmdb_id=None,
|
||||
title=title.name,
|
||||
year=title.year,
|
||||
kind="movie",
|
||||
anime=self.anime_hint(title),
|
||||
)
|
||||
if movie_result and movie_result.external_ids.tmdb_id:
|
||||
console.print(
|
||||
Padding(
|
||||
f"Search -> {movie_result.title or '?'} [bright_black](ID {movie_result.external_ids.tmdb_id})",
|
||||
(0, 5),
|
||||
)
|
||||
)
|
||||
else:
|
||||
console.print(Padding("Search -> [bright_black]No match found[/]", (0, 5)))
|
||||
|
||||
if self.tmdb_id and self.search_source not in ("simkl", "imdb"):
|
||||
providers.fetch_external_ids(
|
||||
self.tmdb_id,
|
||||
"tv" if isinstance(title, Episode) else "movie",
|
||||
**self.cache_kwargs(),
|
||||
)
|
||||
|
||||
def fill_air_dates(self, titles: Series, tvdb_id: int | None = None) -> None:
|
||||
"""Fill in missing episode air dates from TVDB.
|
||||
|
||||
Additive only: an air date the service already set is kept.
|
||||
"""
|
||||
tvdb = providers.get_provider("tvdb")
|
||||
if not tvdb:
|
||||
self.log.debug("Air dates need a tvdb_api_key in your config, skipping.")
|
||||
return
|
||||
|
||||
if not tvdb_id:
|
||||
self.log.debug("Could not resolve a TVDB ID, skipping air dates.")
|
||||
return
|
||||
|
||||
wanted = [t for t in titles if self.daily_hint(t)]
|
||||
if not wanted:
|
||||
return
|
||||
|
||||
keys = list(dict.fromkeys((t.season, t.number) for t in titles))
|
||||
source_order = tvdb.detect_order(tvdb_id, keys) # type: ignore[attr-defined]
|
||||
episodes = tvdb.get_episodes(tvdb_id, source_order) # type: ignore[attr-defined]
|
||||
if not episodes:
|
||||
self.log.debug("TVDB listed no episodes for series %s, skipping air dates.", tvdb_id)
|
||||
return
|
||||
|
||||
aired_by_key: dict[tuple[int, int], str] = {}
|
||||
for episode in episodes:
|
||||
season, number = parse_int(episode.get("seasonNumber")), parse_int(episode.get("number"))
|
||||
aired = episode.get("aired")
|
||||
if season is None or number is None or not aired:
|
||||
continue
|
||||
aired_by_key[(season, number)] = str(aired)
|
||||
|
||||
# TVDB carries placeholder schedule dates for unaired episodes. Stamping one would
|
||||
# name the file with a date the episode never aired on.
|
||||
limit = date.today() + timedelta(days=1)
|
||||
|
||||
filled = 0
|
||||
for title in wanted:
|
||||
if title.air_date is not None:
|
||||
continue
|
||||
aired = aired_by_key.get((title.season, title.number))
|
||||
if not aired:
|
||||
continue
|
||||
try:
|
||||
air_date = date.fromisoformat(aired[:10])
|
||||
except ValueError:
|
||||
continue
|
||||
if air_date.year < 1970 or air_date > limit:
|
||||
continue
|
||||
title.air_date = air_date
|
||||
filled += 1
|
||||
|
||||
if filled:
|
||||
self.log.info("Filled air dates for %d episode(s) from TVDB (ID %s).", filled, tvdb_id)
|
||||
|
||||
def fill_absolute_numbers(self, titles: Series, tvdb_id: int | None = None) -> None:
|
||||
"""Fill in missing absolute episode numbers from TVDB's absolute order.
|
||||
|
||||
Additive only: season and number are never written, and an absolute number the
|
||||
service already set is kept.
|
||||
"""
|
||||
tvdb = providers.get_provider("tvdb")
|
||||
if not tvdb:
|
||||
self.log.debug("Absolute episode numbers need a tvdb_api_key in your config, skipping.")
|
||||
return
|
||||
|
||||
if not tvdb_id:
|
||||
self.log.debug("Could not resolve a TVDB ID, skipping absolute episode numbers.")
|
||||
return
|
||||
|
||||
keys = list(dict.fromkeys((t.season, t.number) for t in titles))
|
||||
source_order = tvdb.detect_order(tvdb_id, keys) # type: ignore[attr-defined]
|
||||
if source_order == "absolute":
|
||||
# the service already numbers in absolute order; get_order_map would return the
|
||||
# empty same-order map, but here the episode numbers are their own fill
|
||||
mapping = {key: (*key, None) for key in keys}
|
||||
else:
|
||||
mapping = tvdb.get_order_map(tvdb_id, "absolute", source_order) # type: ignore[attr-defined]
|
||||
if not mapping:
|
||||
self.log.debug("TVDB has no absolute order for series %s, skipping absolute episode numbers.", tvdb_id)
|
||||
return
|
||||
|
||||
filled = 0
|
||||
for title in titles:
|
||||
if title.absolute is not None:
|
||||
continue
|
||||
entry = mapping.get((title.season, title.number))
|
||||
if not entry:
|
||||
continue
|
||||
title.absolute = entry[1]
|
||||
filled += 1
|
||||
|
||||
if filled:
|
||||
self.log.info("Filled absolute numbers for %d episode(s) from TVDB (ID %s).", filled, tvdb_id)
|
||||
|
||||
def apply_continuous_episodes(self, titles: Series) -> Series:
|
||||
"""Number each season on from the last episode of the season before it.
|
||||
|
||||
Season 0 and episode 0 keep their numbers, and a season that already starts past the season before it is kept.
|
||||
The Series is rebuilt, as it does not re-sort an episode whose number changed.
|
||||
"""
|
||||
last = 0
|
||||
renumbered = 0
|
||||
for season, group in groupby(titles, key=attrgetter("season")):
|
||||
episodes = [t for t in group if t.number]
|
||||
if not season or not episodes:
|
||||
continue
|
||||
if min(t.number for t in episodes) <= last:
|
||||
for t in episodes:
|
||||
t.number += last
|
||||
renumbered += len(episodes)
|
||||
last = max(t.number for t in episodes)
|
||||
self.log.info("Numbered %d episode(s) on from the season before.", renumbered)
|
||||
return type(titles)(list(titles))
|
||||
|
||||
def apply_tvdb_order(self, titles: Series, order: str) -> Series:
|
||||
"""Renumber episodes from the service's own numbering into a TVDB season order."""
|
||||
tvdb = providers.get_provider("tvdb")
|
||||
if not tvdb:
|
||||
self.log.warning("--tvdb-order needs a tvdb_api_key in your config, skipping renumber.")
|
||||
return titles
|
||||
|
||||
tvdb_id = self.tvdb_id
|
||||
if not tvdb_id:
|
||||
show = titles[0]
|
||||
result = self.resolve(tvdb_id=None, anilist_id=None, title=show.title, year=show.year, kind="tv")
|
||||
tvdb_id = result.external_ids.tvdb_id if result else None
|
||||
if not tvdb_id:
|
||||
self.log.warning("Could not resolve a TVDB ID for %r, skipping %s renumber.", str(titles), order)
|
||||
return titles
|
||||
self.tvdb_id = tvdb_id # keep the mux tag on the series the renumbering used
|
||||
|
||||
# parts of one episode share a (season, number) slot; without the dedupe the
|
||||
# collision check below reads them as several episodes clashing on one slot
|
||||
keys = list(dict.fromkeys((t.season, t.number) for t in titles))
|
||||
source_order = tvdb.detect_order(tvdb_id, keys) # type: ignore[attr-defined]
|
||||
if source_order == order:
|
||||
self.log.info("%s already lists this series in TVDB %s order.", self.service, order)
|
||||
return titles
|
||||
|
||||
mapping = tvdb.get_order_map(tvdb_id, order, source_order) # type: ignore[attr-defined]
|
||||
if not mapping:
|
||||
return titles
|
||||
|
||||
# an unmapped episode keeps its own numbering and can land on a remapped episode's slot
|
||||
renumbered = [mapping.get(key, (*key, None))[:2] for key in keys]
|
||||
unmapped = sum(1 for key in keys if key not in mapping)
|
||||
collisions = [slot for slot, count in Counter(renumbered).items() if count > 1]
|
||||
if collisions:
|
||||
self.log.error(
|
||||
"TVDB's %s order misses %d episode(s) and puts two in %d slot(s), keeping the %s numbering of %s",
|
||||
order,
|
||||
unmapped,
|
||||
len(collisions),
|
||||
source_order,
|
||||
self.service,
|
||||
)
|
||||
return titles
|
||||
|
||||
for title in titles:
|
||||
entry = mapping.get((title.season, title.number))
|
||||
if not entry:
|
||||
continue
|
||||
title.season, title.number, tvdb_name = entry
|
||||
if tvdb_name and not title.name:
|
||||
title.name = tvdb_name
|
||||
|
||||
if unmapped:
|
||||
self.log.warning(
|
||||
"%d episode(s) are not in TVDB's %s order and keep their %s numbering.",
|
||||
unmapped,
|
||||
order,
|
||||
source_order,
|
||||
)
|
||||
self.log.info("Renumbered episodes from TVDB %s to %s order (ID %s).", source_order, order, tvdb_id)
|
||||
|
||||
# Series is a SortedKeyList; renumbering in place does not re-sort it
|
||||
return type(titles)(list(titles))
|
||||
Reference in New Issue
Block a user