feat(providers): let a service name the metadata provider its catalogue resolves through

This commit is contained in:
imSp4rky
2026-11-29 09:42:39 -07:00
parent 8e67081e11
commit 36fd0033ce
18 changed files with 260 additions and 30 deletions
+1
View File
@@ -103,6 +103,7 @@ Declared at class level to configure framework behaviour:
| `ANONYMOUS_SEARCH` | `bool` | Set `True` when `search()` needs no login and no state from `authenticate()`. A search then skips the cookie load, `authenticate()` and the cookie save. Default `False`. | | `ANONYMOUS_SEARCH` | `bool` | Set `True` when `search()` needs no login and no state from `authenticate()`. A search then skips the cookie load, `authenticate()` and the cookie save. Default `False`. |
| `NO_SUBTITLES` | `bool` | Set `True` on a service with no subtitle tracks to skip subtitle handling entirely. Default `False`. | | `NO_SUBTITLES` | `bool` | Set `True` on a service with no subtitle tracks to skip subtitle handling entirely. Default `False`. |
| `ANIME` | `bool` | Set `True` when the catalogue is anime, so metadata lookups prefer AniList. A title's own `anime` flag overrides it. | | `ANIME` | `bool` | Set `True` when the catalogue is anime, so metadata lookups prefer AniList. A title's own `anime` flag overrides it. |
| `METADATA_PROVIDER` | `Optional[str]` | Set it, such as to `"tmdb"`, when an index keeps your catalogue's titles only in a form your service does not use (romanized, for one), and another provider finds them by the name your service gives. Lookups try that provider first. It only reorders `metadata_providers` and never adds a provider the user left out. A title's own `metadata_provider` overrides it. |
| `DAILY` | `bool` | Set `True` when the catalogue is daily/date-based (talk shows, news, sports), so unshackle names episodes by air date. A title's own `daily` flag overrides it. | | `DAILY` | `bool` | Set `True` when the catalogue is daily/date-based (talk shows, news, sports), so unshackle names episodes by air date. A title's own `daily` flag overrides it. |
`GEOFENCE` drives an automatic proxy: on startup, if you did not pass an `GEOFENCE` drives an automatic proxy: on startup, if you did not pass an
+1
View File
@@ -291,6 +291,7 @@ These keys are sent only when the title carries them, so a title without them se
| `daily` | boolean | episode | The episode is daily/date-based. Set from the title, or from the service's `DAILY` class attribute. | | `daily` | boolean | episode | The episode is daily/date-based. Set from the title, or from the service's `DAILY` class attribute. |
| `sport` | boolean | episode | The episode is a sports event, so it uses the `sports` output template when one is set. Sent only when true. | | `sport` | boolean | episode | The episode is a sports event, so it uses the `sports` output template when one is set. Sent only when true. |
| `anime` | boolean | episode, movie | The title is anime, so metadata lookups prefer AniList. Set from the title, or from the service's `ANIME` class attribute. | | `anime` | boolean | episode, movie | The title is anime, so metadata lookups prefer AniList. Set from the title, or from the service's `ANIME` class attribute. |
| `metadata_provider` | string | episode, movie | The metadata provider that lookups for this title try first. Set from the title, or from the service's `METADATA_PROVIDER` class attribute. Sent only when set. |
!!! info "`part` on a split episode" !!! info "`part` on a split episode"
A service that splits one episode into several separately playable videos reports each A service that splits one episode into several separately playable videos reports each
+1
View File
@@ -68,6 +68,7 @@ Declared at the top of your service class, these are static descriptors:
| `AUTH_METHODS` | `Optional[tuple[str, ...]]` | Accepted auth methods (`"cookies"` / `"credentials"`). When `None`, the REST `/services` endpoint infers them from `authenticate()`. | | `AUTH_METHODS` | `Optional[tuple[str, ...]]` | Accepted auth methods (`"cookies"` / `"credentials"`). When `None`, the REST `/services` endpoint infers them from `authenticate()`. |
| `ANONYMOUS_SEARCH` | `bool` | `search()` needs no login and no state from `authenticate()`. A search then skips the cookie load, `authenticate()` and the cookie save. Default `False`. | | `ANONYMOUS_SEARCH` | `bool` | `search()` needs no login and no state from `authenticate()`. A search then skips the cookie load, `authenticate()` and the cookie save. Default `False`. |
| `ANIME` | `bool` | The catalogue is anime, so metadata lookups prefer AniList. A title's own `anime` flag overrides it. | | `ANIME` | `bool` | The catalogue is anime, so metadata lookups prefer AniList. A title's own `anime` flag overrides it. |
| `METADATA_PROVIDER` | `Optional[str]` | The metadata provider the catalogue resolves through, such as `"tmdb"`. Lookups try it first. It only reorders `metadata_providers` and never adds a provider the user left out. A title's own `metadata_provider` overrides it. |
| `DAILY` | `bool` | The catalogue is daily/date-based, so unshackle names episodes by air date. A title's own `daily` flag overrides it. | | `DAILY` | `bool` | The catalogue is daily/date-based, so unshackle names episodes by air date. A title's own `daily` flag overrides it. |
### Required methods ### Required methods
+4
View File
@@ -1116,6 +1116,10 @@ all end up as the same language.
A service can also mark its titles as anime. For those titles unshackle tries AniList A service can also mark its titles as anime. For those titles unshackle tries AniList
first. When AniList has no match, it falls through to the normal order. first. When AniList has no match, it falls through to the normal order.
A service can also name the metadata provider its catalogue resolves through. unshackle
tries that provider first, also before AniList for an anime title, but never adds one that
`metadata_providers` leaves out.
Each ID goes to the providers that read that kind of ID, in Each ID goes to the providers that read that kind of ID, in
[`metadata_providers`](../reference/configuration/misc.md#external-api-keys) order: [`metadata_providers`](../reference/configuration/misc.md#external-api-keys) order:
+5
View File
@@ -45,6 +45,11 @@ each metadata provider can answer with, see
`anilist` is last in the default order. It only answers for anime and returns nothing for `anilist` is last in the default order. It only answers for anime and returns nothing for
anything else, so it is harmless there. Move it earlier if you mostly download anime. anything else, so it is harmless there. Move it earlier if you mostly download anime.
A service can name the metadata provider its catalogue resolves through. unshackle then tries
that provider first, also ahead of an order that you set. This only changes the order: a
metadata provider that `metadata_providers` leaves out stays out. For an anime title the
service's metadata provider comes first and `anilist` second.
The order applies to a title search and to a direct lookup of an ID you give with The order applies to a title search and to a direct lookup of an ID you give with
`--tmdb`, `--imdb`, `--tvdb`, or `--anilist`. A supplied ID always goes to the providers `--tmdb`, `--imdb`, `--tvdb`, or `--anilist`. A supplied ID always goes to the providers
that read that kind of ID, and it never falls back to a title search. that read that kind of ID, and it never falls back to a title search.
+18
View File
@@ -489,3 +489,21 @@ def test_a_3d_video_stays_3d_through_export_and_import(tmp_path: Path) -> None:
svc = ImportService(import_ctx(), "EXAMPLE", "movie-1", str(export)) svc = ImportService(import_ctx(), "EXAMPLE", "movie-1", str(export))
movie = next(iter(svc.get_titles())) movie = next(iter(svc.get_titles()))
assert svc.get_tracks(movie).videos[0].stereo assert svc.get_tracks(movie).videos[0].stereo
class ProviderService:
ANIME = True
METADATA_PROVIDER = "tmdb"
session = SimpleNamespace(headers={})
def test_the_service_metadata_provider_survives_export_and_import(tmp_path: Path) -> None:
export = tmp_path / "export.json"
title = make_title()
runner = make_dl()
runner.export_service = cast(Any, ProviderService())
runner.write_export(export, title, title.tracks.videos[0])
movie = list(ImportService(import_ctx(), "EXAMPLE", "movie-1", str(export)).get_titles())[0]
assert (movie.metadata_provider, movie.anime) == ("tmdb", True)
+81
View File
@@ -2,12 +2,16 @@
from __future__ import annotations from __future__ import annotations
from typing import Any
import pytest import pytest
from unshackle.core import providers from unshackle.core import providers
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult
search_metadata = providers.search_metadata
class FakeProvider(MetadataProvider): class FakeProvider(MetadataProvider):
"""Stands in for a real provider; records the ID it was asked for.""" """Stands in for a real provider; records the ID it was asked for."""
@@ -228,6 +232,83 @@ def test_the_anime_hint_reaches_search(monkeypatch: pytest.MonkeyPatch) -> None:
assert calls and calls[0]["args"][-1] is True assert calls and calls[0]["args"][-1] is True
def test_the_service_provider_goes_first_with_the_rest_behind_it() -> None:
ordered = [cls.NAME for cls in providers.provider_order("movie", prefer="tmdb")]
assert ordered == ["tmdb", *(name for name in providers.DEFAULT_ORDER if name != "tmdb")]
def test_the_service_provider_cannot_add_one_the_config_left_out(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "metadata_providers", ["imdb"])
assert [cls.NAME for cls in providers.provider_order("movie", prefer="tmdb")] == ["imdb"]
def test_the_service_provider_goes_before_anilist_on_an_anime_title() -> None:
ordered = [cls.NAME for cls in providers.provider_order("tv", anime=True, prefer="tmdb")]
assert ordered[:2] == ["tmdb", "anilist"]
assert ordered[2:] == [name for name in providers.DEFAULT_ORDER if name not in ("anilist", "tmdb")]
def test_the_user_order_stays_behind_both_hints(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "metadata_providers", ["imdb", "tvdb", "anilist", "tmdb"])
ordered = [cls.NAME for cls in providers.provider_order("tv", anime=True, prefer="tmdb")]
assert ordered == ["tmdb", "anilist", "imdb", "tvdb"]
def test_an_anilist_service_provider_on_an_anime_title_keeps_anilist_first() -> None:
ordered = [cls.NAME for cls in providers.provider_order("tv", anime=True, prefer="anilist")]
assert ordered == ["anilist", *(name for name in providers.DEFAULT_ORDER if name != "anilist")]
@pytest.mark.parametrize(
("prefer", "expected"),
[
("IMDB", ["imdb", "tmdb"]),
("imdbapi", ["imdb", "tmdb"]),
("nope", ["tmdb", "imdb"]),
(5, ["tmdb", "imdb"]),
(None, ["tmdb", "imdb"]),
],
)
def test_the_service_provider_is_read_like_a_config_entry(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, prefer: Any, expected: list[str]
) -> None:
monkeypatch.setattr(config, "metadata_providers", ["tmdb", "imdb"])
with caplog.at_level("WARNING"):
assert [cls.NAME for cls in providers.provider_order("movie", prefer=prefer)] == expected
assert "Ignoring unknown" not in caplog.text
def test_the_service_provider_reaches_search(monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[dict] = []
monkeypatch.setattr(providers, "search_metadata", lambda *a, **kw: calls.append({"args": a, "kw": kw}) or None)
patch_providers(monkeypatch, {})
providers.resolve_by_ids(title="Some Show", year=1999, kind="tv", prefer="tmdb")
assert calls and calls[0]["kw"]["prefer"] == "tmdb"
def test_the_service_provider_orders_a_supplied_id(monkeypatch: pytest.MonkeyPatch) -> None:
imdb = FakeProvider("imdb", MetadataResult(title="Wrong Film", year=2020, kind="movie"))
tmdb = FakeProvider("tmdb", MetadataResult(title="Right Film", year=2010, kind="movie"))
patch_providers(monkeypatch, {"imdb": imdb, "tmdb": tmdb})
result = providers.resolve_by_ids(27205, "tt1375666", kind="movie", prefer="tmdb")
assert result is not None and result.title == "Right Film"
assert imdb.asked == []
def test_search_metadata_orders_by_the_service_provider(monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[tuple] = []
monkeypatch.setattr(config, "disable_metadata", False)
monkeypatch.setattr(providers, "provider_order", lambda *a: calls.append(a) or [])
search_metadata("X", None, "movie", prefer="tmdb")
assert calls == [("movie", False, "tmdb")]
def test_all_supplied_ids_survive_together(monkeypatch: pytest.MonkeyPatch) -> None: def test_all_supplied_ids_survive_together(monkeypatch: pytest.MonkeyPatch) -> None:
"""anilist_id combined with a western trio member: every supplied ID reaches external_ids.""" """anilist_id combined with a western trio member: every supplied ID reaches external_ids."""
tvdb = FakeProvider( tvdb = FakeProvider(
+13
View File
@@ -139,3 +139,16 @@ def test_a_matroska_tagger_fault_warns_and_never_raises(
with caplog.at_level("WARNING", logger="TAGS"): with caplog.at_level("WARNING", logger="TAGS"):
tags_module.tag_file(Path("04. Example Track.mka"), make_song(), session=SESSION) tags_module.tag_file(Path("04. Example Track.mka"), make_song(), session=SESSION)
assert "mkvpropedit not found" in caplog.text assert "mkvpropedit not found" in caplog.text
def test_the_tag_lookup_passes_the_service_provider(calls: Calls, monkeypatch: pytest.MonkeyPatch) -> None:
seen: list[dict[str, Any]] = []
monkeypatch.setattr(config, "tag_imdb_tmdb", True)
monkeypatch.setattr(tags_module, "get_available_providers", lambda: [object()])
monkeypatch.setattr(tags_module, "resolve_by_ids", lambda *a, **kw: seen.append(kw) or None)
tags_module.tag_file(
Path("Some Movie.mkv"), Movie(id_="movie-0001", service=DummyService, name="Some Movie"), prefer="tmdb"
)
assert seen and seen[0]["prefer"] == "tmdb"
+40 -2
View File
@@ -85,7 +85,7 @@ def test_enrich_resolves_the_given_ids_and_sets_the_metadata_on_each_title(monke
metadata = TitleMetadata(tmdb_id=5, imdb_id="tt1", cache=CACHE, anime=True) 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) 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 calls.resolved == [((), {**ids(5, "tt1"), **CACHE_KWARGS, "kind": "tv", "anime": True, "prefer": None})]
assert [(t.title, t.year, str(t.language)) for t in titles] == [ assert [(t.title, t.year, str(t.language)) for t in titles] == [
("Real Name", 1999, "ko"), ("Real Name", 1999, "ko"),
("Real Name", 1999, "ko"), ("Real Name", 1999, "ko"),
@@ -121,7 +121,9 @@ def test_the_tvdb_order_resolves_a_tvdb_id_and_keeps_it_for_the_tags(monkeypatch
metadata = TitleMetadata(tmdb_id=5, cache=CACHE) metadata = TitleMetadata(tmdb_id=5, cache=CACHE)
titles = metadata.prepare(Series([episode(1, 1), episode(1, 2)]), enrich=False, tvdb_order="dvd", continuous=True) 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 calls.resolved == [
((), {**ids(5), **CACHE_KWARGS, "title": "The Show", "year": None, "kind": "tv", "prefer": None})
]
assert metadata.tvdb_id == 73871 assert metadata.tvdb_id == 73871
assert [(t.season, t.number) for t in titles] == [(2, 1), (2, 2)] assert [(t.season, t.number) for t in titles] == [(2, 1), (2, 2)]
@@ -248,3 +250,39 @@ def test_a_movie_fetches_the_movie_external_ids(monkeypatch: pytest.MonkeyPatch)
calls = Providers(monkeypatch, None) calls = Providers(monkeypatch, None)
TitleMetadata(tmdb_id=5, cache=CACHE).search(movie()) TitleMetadata(tmdb_id=5, cache=CACHE).search(movie())
assert calls.fetched == [(5, "movie", *CACHE)] assert calls.fetched == [(5, "movie", *CACHE)]
def test_the_service_provider_reaches_every_lookup(monkeypatch: pytest.MonkeyPatch) -> None:
calls = Providers(monkeypatch, found(tvdb_id=73871), FakeTvdb({(1, 1): (1, 1, None)}))
TitleMetadata(metadata_provider="tmdb").prepare(
Series([episode(1, 1)]), enrich=True, tvdb_order="dvd", continuous=False
)
TitleMetadata(metadata_provider="tmdb").search(episode(1, 1), listing=True)
TitleMetadata(metadata_provider="tmdb").search(movie(), listing=True)
assert len(calls.resolved) == 4
assert [kwargs["prefer"] for _, kwargs in calls.resolved] == ["tmdb"] * 4
def test_a_title_overrides_the_service_provider(monkeypatch: pytest.MonkeyPatch) -> None:
calls = Providers(monkeypatch, None)
ep = episode(1, 1)
ep.metadata_provider = "tvdb"
TitleMetadata(metadata_provider="tmdb").search(ep, listing=True)
assert calls.resolved[0][1]["prefer"] == "tvdb"
def test_an_empty_title_provider_keeps_the_configured_order() -> None:
ep = episode(1, 1)
ep.metadata_provider = ""
assert TitleMetadata(metadata_provider="tmdb").provider_hint(ep) == ""
def test_a_per_title_anime_flag_keeps_the_service_provider(monkeypatch: pytest.MonkeyPatch) -> None:
calls = Providers(monkeypatch, None)
ep = episode(1, 1)
ep.anime = True
TitleMetadata(metadata_provider="tmdb").search(ep, listing=True)
assert (calls.resolved[0][1]["anime"], calls.resolved[0][1]["prefer"]) == (True, "tmdb")
+28 -3
View File
@@ -16,11 +16,10 @@ from langcodes import Language
from unshackle.commands.dl import dl from unshackle.commands.dl import dl
from unshackle.core.api import handlers from unshackle.core.api import handlers
from unshackle.core.api.handlers import stamp_service_flags
from unshackle.core.titles.episode import Episode from unshackle.core.titles.episode import Episode
from unshackle.core.titles.movie import Movie from unshackle.core.titles.movie import Movie
from unshackle.core.titles.music import Song from unshackle.core.titles.music import Song
from unshackle.core.wire import build_title, serialize_title from unshackle.core.wire import build_title, serialize_title, stamp_service_flags
pytestmark = pytest.mark.unit pytestmark = pytest.mark.unit
@@ -50,7 +49,7 @@ def _movie(**overrides: Any) -> Movie:
return Movie(**base) return Movie(**base)
NEW_KEYS = ("air_date", "absolute", "daily", "anime") NEW_KEYS = ("air_date", "absolute", "daily", "anime", "metadata_provider")
def test_a_plain_episode_gains_no_new_keys() -> None: def test_a_plain_episode_gains_no_new_keys() -> None:
@@ -119,6 +118,32 @@ def test_a_plain_service_stamps_nothing() -> None:
assert not [k for k in NEW_KEYS if k in d] assert not [k for k in NEW_KEYS if k in d]
class _ProviderSvc:
METADATA_PROVIDER = "tmdb"
@pytest.mark.parametrize("make", [ep, _movie], ids=["episode", "movie"])
def test_the_stamp_fills_the_metadata_provider_from_the_service_class(make: Any) -> None:
assert stamp_service_flags(serialize_title(make()), _ProviderSvc())["metadata_provider"] == "tmdb"
def test_the_stamp_keeps_a_per_title_metadata_provider() -> None:
episode = ep()
episode.metadata_provider = "tvdb"
assert stamp_service_flags(serialize_title(episode), _ProviderSvc())["metadata_provider"] == "tvdb"
def test_the_metadata_provider_survives_the_round_trip() -> None:
assert round_trip(ep(), stamp=_ProviderSvc()).metadata_provider == "tmdb"
assert round_trip(ep()).metadata_provider is None
def test_title_to_meta_round_trip_keeps_the_metadata_provider() -> None:
movie = _movie()
movie.metadata_provider = "tmdb"
assert build_title(dl.title_to_meta(movie), "FAKE", "fallback-id").metadata_provider == "tmdb"
def test_a_movie_is_never_stamped_daily() -> None: def test_a_movie_is_never_stamped_daily() -> None:
d = stamp_service_flags(serialize_title(_movie()), _AnimeDailySvc()) d = stamp_service_flags(serialize_title(_movie()), _AnimeDailySvc())
assert d["anime"] is True assert d["anime"] is True
+5 -1
View File
@@ -1765,6 +1765,7 @@ class dl:
cache=service.cache_identity(), cache=service.cache_identity(),
service=self.service, service=self.service,
anime=service.ANIME, anime=service.ANIME,
metadata_provider=service.METADATA_PROVIDER,
daily=service.DAILY, daily=service.DAILY,
force_daily=self.daily, force_daily=self.daily,
log=self.log, log=self.log,
@@ -2647,6 +2648,7 @@ class dl:
metadata.tvdb_id, metadata.tvdb_id,
metadata.anilist_id, metadata.anilist_id,
metadata.anime_hint(title), metadata.anime_hint(title),
prefer=metadata.provider_hint(title),
session=service.session, session=service.session,
) )
if include_sample: if include_sample:
@@ -2899,7 +2901,9 @@ class dl:
def export_entry(self, title: Title_T) -> mediaexport.Entry: def export_entry(self, title: Title_T) -> mediaexport.Entry:
"""A mediaexport entry for ``title``: manifests, chapters, a small track list, no keys yet.""" """A mediaexport entry for ``title``: manifests, chapters, a small track list, no keys yet."""
meta = self.title_to_meta(title) from unshackle.core import wire
meta = wire.stamp_service_flags(self.title_to_meta(title), self.export_service)
all_tracks = [*title.tracks.videos, *title.tracks.audio, *title.tracks.subtitles] all_tracks = [*title.tracks.videos, *title.tracks.audio, *title.tracks.subtitles]
primary_url = title.tracks.manifest_url or next( primary_url = title.tracks.manifest_url or next(
(str(t.url) for t in all_tracks if t.descriptor != Video.Descriptor.URL), "" (str(t.url) for t in all_tracks if t.descriptor != Video.Descriptor.URL), ""
+1 -14
View File
@@ -99,6 +99,7 @@ from unshackle.core.wire import (
serialize_title, serialize_title,
serialize_tracks, serialize_tracks,
served_url, served_url,
stamp_service_flags,
) )
if TYPE_CHECKING: if TYPE_CHECKING:
@@ -1316,20 +1317,6 @@ def listed_titles(titles: Any) -> list[Any]:
return list(titles) if hasattr(titles, "__iter__") and not isinstance(titles, str) else [titles] return list(titles) if hasattr(titles, "__iter__") and not isinstance(titles, str) else [titles]
def stamp_service_flags(serialized: dict[str, Any], service_instance: Any) -> dict[str, Any]:
"""Fill anime/daily from the service class for titles that set neither.
The client rebuilds titles from this JSON against a synthetic service class, so a
class-level ANIME/DAILY would otherwise be lost on the way across.
"""
for key, attr in (("anime", "ANIME"), ("daily", "DAILY")):
if key == "daily" and serialized.get("type") != "episode":
continue
if serialized.get(key) is None and getattr(type(service_instance), attr, False):
serialized[key] = True
return serialized
def drm_preference_name(track: Any) -> str | None: def drm_preference_name(track: Any) -> str | None:
"""The track's drm_preference as a full DRM system name, "widevine" or "playready"; None when unset.""" """The track's drm_preference as a full DRM system name, "widevine" or "playready"; None when unset."""
preference = getattr(track, "drm_preference", None) preference = getattr(track, "drm_preference", None)
+21 -6
View File
@@ -34,22 +34,33 @@ ALIASES: dict[str, str] = {"imdbapi": "imdb"}
DEFAULT_ORDER: tuple[str, ...] = ("imdb", "omdb", "simkl", "tmdb", "tvdb", "anilist") DEFAULT_ORDER: tuple[str, ...] = ("imdb", "omdb", "simkl", "tmdb", "tvdb", "anilist")
def provider_order(kind: str | None = None, anime: bool = False) -> list[type[MetadataProvider]]: def provider_name(name: object) -> str:
"""A `metadata_providers` entry as its registry name."""
return ALIASES.get(str(name).lower(), str(name).lower())
def provider_order(
kind: str | None = None, anime: bool = False, prefer: str | None = None
) -> list[type[MetadataProvider]]:
"""Metadata provider classes in the order configured by `metadata_providers`. """Metadata provider classes in the order configured by `metadata_providers`.
`metadata_providers` is either a flat list applying to both kinds, or a mapping of `metadata_providers` is either a flat list applying to both kinds, or a mapping of
kind ("tv"/"movie") to its own list. A kind the mapping omits uses `DEFAULT_ORDER`. kind ("tv"/"movie") to its own list. A kind the mapping omits uses `DEFAULT_ORDER`.
An `anime` title puts AniList first. The rest of the order stays behind it to An `anime` title puts AniList first. The rest of the order stays behind it to
fall back on. fall back on. `prefer` (a service's `METADATA_PROVIDER`) moves that metadata provider
in front of both, so an anime title asks it first and AniList second. Neither hint adds a
metadata provider the config left out.
""" """
from unshackle.core.config import config from unshackle.core.config import config
configured = config.metadata_providers configured = config.metadata_providers
selected = (configured.get(kind) if kind else None) if isinstance(configured, dict) else configured selected = (configured.get(kind) if kind else None) if isinstance(configured, dict) else configured
names = [ALIASES.get(str(n).lower(), str(n).lower()) for n in (selected or DEFAULT_ORDER)] names = [provider_name(n) for n in (selected or DEFAULT_ORDER)]
if anime and AniListProvider.NAME in names: if anime and AniListProvider.NAME in names:
names = [AniListProvider.NAME, *names] names = [AniListProvider.NAME, *names]
if prefer and (wanted := provider_name(prefer)) in names:
names = [wanted, *names]
unknown = [n for n in names if n not in REGISTRY] unknown = [n for n in names if n not in REGISTRY]
if unknown: if unknown:
log.warning("Ignoring unknown metadata_providers entries: %s", ", ".join(unknown)) log.warning("Ignoring unknown metadata_providers entries: %s", ", ".join(unknown))
@@ -79,6 +90,7 @@ def search_metadata(
cache_region: str | None = None, cache_region: str | None = None,
cache_account_hash: str | None = None, cache_account_hash: str | None = None,
anime: bool = False, anime: bool = False,
prefer: str | None = None,
) -> MetadataResult | None: ) -> MetadataResult | None:
"""Find metadata in every available metadata provider. Returns the best result.""" """Find metadata in every available metadata provider. Returns the best result."""
from unshackle.core.config import config from unshackle.core.config import config
@@ -89,7 +101,7 @@ def search_metadata(
log.debug("Metadata lookups are disabled by config; not searching for %r", title) log.debug("Metadata lookups are disabled by config; not searching for %r", title)
return None return None
ordered = provider_order(kind, anime) ordered = provider_order(kind, anime, prefer)
if title_cacher and cache_title_id: if title_cacher and cache_title_id:
for cls in ordered: for cls in ordered:
@@ -278,6 +290,7 @@ def resolve_by_ids(
cache_region: str | None = None, cache_region: str | None = None,
cache_account_hash: str | None = None, cache_account_hash: str | None = None,
anime: bool = False, anime: bool = False,
prefer: str | None = None,
) -> MetadataResult | None: ) -> MetadataResult | None:
"""Get metadata from user-supplied external IDs, and find the title by name only without them. """Get metadata from user-supplied external IDs, and find the title by name only without them.
@@ -299,10 +312,12 @@ def resolve_by_ids(
if not supplied: if not supplied:
if not title: if not title:
return None return None
return search_metadata(title, year, kind, title_cacher, cache_title_id, cache_region, cache_account_hash, anime) return search_metadata(
title, year, kind, title_cacher, cache_title_id, cache_region, cache_account_hash, anime, prefer=prefer
)
result: MetadataResult | None = None result: MetadataResult | None = None
for cls in provider_order(kind, anime): for cls in provider_order(kind, anime, prefer):
provider_id = supplied.get(cls.ID_KIND or "") provider_id = supplied.get(cls.ID_KIND or "")
if provider_id is None: if provider_id is None:
continue continue
+17 -2
View File
@@ -68,6 +68,7 @@ class TitleMetadata:
cache: CacheIdentity = CacheIdentity(None, None, None, None) cache: CacheIdentity = CacheIdentity(None, None, None, None)
service: str | None = None service: str | None = None
anime: bool = False anime: bool = False
metadata_provider: str | None = None
daily: bool = False daily: bool = False
force_daily: bool = False force_daily: bool = False
log: logging.Logger = field(default_factory=lambda: logging.getLogger("download")) log: logging.Logger = field(default_factory=lambda: logging.getLogger("download"))
@@ -88,6 +89,11 @@ class TitleMetadata:
per_title = getattr(title, "anime", None) per_title = getattr(title, "anime", None)
return self.anime if per_title is None else bool(per_title) return self.anime if per_title is None else bool(per_title)
def provider_hint(self, title: Title_T | None = None) -> str | None:
"""The metadata provider that lookups for this title try first; None keeps the configured order."""
per_title = getattr(title, "metadata_provider", None)
return self.metadata_provider if per_title is None else per_title
def daily_hint(self, title: Title_T | None = None) -> bool: def daily_hint(self, title: Title_T | None = None) -> bool:
"""Whether this title is daily content named by air date.""" """Whether this title is daily content named by air date."""
per_title = getattr(title, "daily", None) per_title = getattr(title, "daily", None)
@@ -122,7 +128,7 @@ class TitleMetadata:
sample_title = titles[0] if hasattr(titles, "__getitem__") else titles sample_title = titles[0] if hasattr(titles, "__getitem__") else titles
kind = "tv" if isinstance(sample_title, Episode) else "movie" kind = "tv" if isinstance(sample_title, Episode) else "movie"
result = self.resolve(kind=kind, anime=self.anime_hint(sample_title)) result = self.resolve(kind=kind, anime=self.anime_hint(sample_title), prefer=self.provider_hint(sample_title))
self.enrichment = ( self.enrichment = (
Enrichment(result.title, result.year, parse_language(result.original_language)) if result else Enrichment() Enrichment(result.title, result.year, parse_language(result.original_language)) if result else Enrichment()
) )
@@ -160,6 +166,7 @@ class TitleMetadata:
year=title.year, year=title.year,
kind="tv", kind="tv",
anime=self.anime_hint(title), anime=self.anime_hint(title),
prefer=self.provider_hint(title),
) )
if result: if result:
if has_ids: if has_ids:
@@ -184,6 +191,7 @@ class TitleMetadata:
year=title.year, year=title.year,
kind="movie", kind="movie",
anime=self.anime_hint(title), anime=self.anime_hint(title),
prefer=self.provider_hint(title),
) )
if movie_result and movie_result.external_ids.tmdb_id: if movie_result and movie_result.external_ids.tmdb_id:
console.print( console.print(
@@ -328,7 +336,14 @@ class TitleMetadata:
tvdb_id = self.tvdb_id tvdb_id = self.tvdb_id
if not tvdb_id: if not tvdb_id:
show = titles[0] show = titles[0]
result = self.resolve(tvdb_id=None, anilist_id=None, title=show.title, year=show.year, kind="tv") result = self.resolve(
tvdb_id=None,
anilist_id=None,
title=show.title,
year=show.year,
kind="tv",
prefer=self.provider_hint(show),
)
tvdb_id = result.external_ids.tvdb_id if result else None tvdb_id = result.external_ids.tvdb_id if result else None
if not tvdb_id: if not tvdb_id:
self.log.warning("Could not resolve a TVDB ID for %r, skipping %s renumber.", str(titles), order) self.log.warning("Could not resolve a TVDB ID for %r, skipping %s renumber.", str(titles), order)
+1
View File
@@ -102,6 +102,7 @@ class TitleSource(metaclass=ABCMeta):
NO_SUBTITLES: bool = False # the source has no subtitles; dl skips the subtitle and caption extraction. NO_SUBTITLES: bool = False # the source has no subtitles; dl skips the subtitle and caption extraction.
ANIME: bool = False # service catalogue is anime; metadata lookups prefer AniList. Title.anime overrides per title. ANIME: bool = False # service catalogue is anime; metadata lookups prefer AniList. Title.anime overrides per title.
METADATA_PROVIDER: str | None = None # metadata lookups try this provider first. Title.metadata_provider overrides.
DAILY: bool = False # catalog is daily/date-based. episodes are named by air date. Title.daily overrides per title. DAILY: bool = False # catalog is daily/date-based. episodes are named by air date. Title.daily overrides per title.
ctx: click.Context ctx: click.Context
+1
View File
@@ -61,6 +61,7 @@ class Title:
self.data: Any = data self.data: Any = data
self.anime: bool | None = None self.anime: bool | None = None
self.daily: bool | None = None self.daily: bool | None = None
self.metadata_provider: str | None = None
self.tracks = Tracks() self.tracks = Tracks()
+2 -1
View File
@@ -92,6 +92,7 @@ def tag_file(
tvdb_id: int | None = None, tvdb_id: int | None = None,
anilist_id: int | str | None = None, anilist_id: int | str | None = None,
anime: bool = False, anime: bool = False,
prefer: str | None = None,
session: AnySession | None = None, session: AnySession | None = None,
) -> None: ) -> None:
log.debug("Tagging file %s with title %r", path, title) log.debug("Tagging file %s with title %r", path, title)
@@ -146,7 +147,7 @@ def tag_file(
return return
result = resolve_by_ids( result = resolve_by_ids(
tmdb_id, imdb_id, tvdb_id, anilist_id, title=name, year=year, kind=kind, anime=anime tmdb_id, imdb_id, tvdb_id, anilist_id, title=name, year=year, kind=kind, anime=anime, prefer=prefer
) )
if result and result.external_ids: if result and result.external_ids:
+20 -1
View File
@@ -132,6 +132,8 @@ def serialize_title(title: Title_T) -> dict[str, Any]:
result["music_data"] = {key: metadata[key] for key in MUSIC_DATA_KEYS if metadata.get(key) not in (None, "")} result["music_data"] = {key: metadata[key] for key in MUSIC_DATA_KEYS if metadata.get(key) not in (None, "")}
if isinstance(title, (Episode, Movie)) and getattr(title, "anime", None) is not None: if isinstance(title, (Episode, Movie)) and getattr(title, "anime", None) is not None:
result["anime"] = title.anime result["anime"] = title.anime
if isinstance(title, (Episode, Movie)) and getattr(title, "metadata_provider", None) is not None:
result["metadata_provider"] = title.metadata_provider
if availability is not None: if availability is not None:
result["availability"] = availability result["availability"] = availability
@@ -166,9 +168,26 @@ def title_to_meta(title: Title_T) -> dict[str, Any]:
meta.update(type="movie", name=str(title)) meta.update(type="movie", name=str(title))
if getattr(title, "anime", None) is not None: if getattr(title, "anime", None) is not None:
meta["anime"] = title.anime meta["anime"] = title.anime
if getattr(title, "metadata_provider", None) is not None:
meta["metadata_provider"] = title.metadata_provider
return meta return meta
def stamp_service_flags(serialized: dict[str, Any], service_instance: Any) -> dict[str, Any]:
"""Fill anime/daily/metadata_provider from the service class for titles that set none.
A remote client and an import rebuild titles from this JSON against a synthetic service
class, so a class-level flag would otherwise be lost on the way across.
"""
for key, attr in (("anime", "ANIME"), ("daily", "DAILY"), ("metadata_provider", "METADATA_PROVIDER")):
if key == "daily" and serialized.get("type") != "episode":
continue
value = getattr(type(service_instance), attr, None)
if serialized.get(key) is None and value:
serialized[key] = value
return serialized
def episode_name(name: str | None, series_title: str | None) -> str | None: def episode_name(name: str | None, series_title: str | None) -> str | None:
"""Drop a placeholder episode name the way ``Episode.__init__`` does. """Drop a placeholder episode name the way ``Episode.__init__`` does.
@@ -222,7 +241,7 @@ def apply_title_fields(title: Title_T, info: dict[str, Any]) -> None:
elif info.get("name"): elif info.get("name"):
title.name = info["name"] title.name = info["name"]
for key in ("anime", "daily", "sport", *(SONG_FIELDS if isinstance(title, Song) else ())): for key in ("anime", "daily", "sport", "metadata_provider", *(SONG_FIELDS if isinstance(title, Song) else ())):
if info.get(key) is not None: if info.get(key) is not None:
setattr(title, key, info[key]) setattr(title, key, info[key])