feat(providers): fill the western IDs of an AniList match from the anime-lists ID map

This commit is contained in:
imSp4rky
2026-11-29 10:47:22 -07:00
parent efd8ca65c7
commit 6758d9e4fa
13 changed files with 370 additions and 19 deletions
+1 -1
View File
@@ -179,7 +179,7 @@ Keep only certain track types, or skip certain track types.
!!! note "One ID at a time"
You cannot combine `--tmdb`, `--imdb` and `--tvdb`. Give one and unshackle finds the
others from it, and writes all three to the tags. `--anilist` is outside that rule and pairs
with one of them, which is how you attach a western ID to an anime title.
with one of them, which is how you set the western ID of an anime title yourself.
An ID with no metadata provider that can find it, such as `--tmdb` with no `tmdb_api_key`,
fails before the download starts. `--anilist` needs no API key, so it never fails this check.
+15 -4
View File
@@ -1101,7 +1101,7 @@ operates when you set its config key:
| OMDb | `omdb_api_key` | yes | yes, as an English name such as `Korean` | IMDb |
| IMDb | *(no config key needed)* | yes | yes, alpha-2 such as `ko` | IMDb |
| SIMKL | `simkl_client_id` | yes | no, it publishes a country and no language | IMDb, TMDB, TVDB |
| AniList | *(no config key needed)* | yes | yes, worked out from the country of origin, such as `ja` | AniList |
| AniList | *(no config key needed)* | yes | yes, worked out from the country of origin, such as `ja` | AniList, and TMDB, IMDb and TVDB from an ID map |
Whatever the tag looks like, unshackle normalises it before use, so `ko`, `kor` and `Korean`
all end up as the same language.
@@ -1128,14 +1128,25 @@ Each ID goes to the providers that read that kind of ID, in
out of the box, and an OMDb API key only matters when IMDb has no answer.
- `--tvdb` reads TVDB. It needs `tvdb_api_key`.
- `--anilist` reads AniList, which needs no API key. It supplies the title, the year and the
original language, and writes an AniList tag. It knows no TMDB, IMDB or TVDB ID, so pair it
with `--tmdb`, `--imdb` or `--tvdb` when you want those tags as well.
original language, and writes an AniList tag. AniList knows no TMDB, IMDB or TVDB ID, so
unshackle takes them from the [anime-lists](https://github.com/Fribb/anime-lists) ID map.
Pair it with `--tmdb`, `--imdb` or `--tvdb` when the map has no entry for the title, or
a wrong one. An ID that you give always wins over the map.
Give **one** of `--tmdb`, `--imdb` and `--tvdb`. You cannot combine them, because one ID
does the job on its own: unshackle finds the other two from it and writes all three to the
tags.
Passing two is an error rather than a silent choice between them. `--anilist` is the exception
and still pairs with one of the three, which is how you tag an anime title with a western ID.
and still pairs with one of the three, which is how you set the western ID of an anime title
yourself.
!!! note "The AniList ID map"
An AniList match, from a search or from `--anilist`, has no TMDB, IMDb or TVDB ID. unshackle
then looks the AniList ID up in the anime-lists ID map. It downloads the map (about 7 MB) the
first time that it needs it, and keeps it in the cache for a week. When the match already has a
western ID that differs from the map, unshackle does not use the map. A movie takes only a TMDB movie ID, and a series takes the
IDs of the whole series, also for a later season. When the map cannot download, the match
keeps only its AniList ID.
The ID you give must have a metadata provider that can find it, so unshackle makes sure of
that before it downloads anything. `--tmdb` without `tmdb_api_key`, or an ID whose metadata
+7
View File
@@ -14,6 +14,7 @@ import pytest
from unshackle.core import binaries
from unshackle.core import session as http_session
from unshackle.core.config import config
from unshackle.core.providers import anilist
from unshackle.core.proxies.proxy import CATALOGUES
from unshackle.core.update_checker import UpdateChecker
@@ -46,6 +47,12 @@ def no_update_check(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(UpdateChecker, "check_for_updates_sync", lambda *args, **kwargs: None)
@pytest.fixture(autouse=True)
def no_anime_id_map(monkeypatch: pytest.MonkeyPatch) -> None:
"""Keep the AniList ID map download and its cache file out of every test."""
monkeypatch.setattr(anilist, "western_id_map", dict)
@pytest.fixture(autouse=True)
def client_process(monkeypatch: pytest.MonkeyPatch) -> None:
"""Start as a client process, so a test that ran serve or a job worker cannot turn response bodies off."""
+108 -2
View File
@@ -2,13 +2,21 @@
from __future__ import annotations
from collections.abc import Iterator
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any
import pytest
import requests
from unshackle.core.cacher import Cacher
from unshackle.core.config import config
from unshackle.core.providers import anilist
from unshackle.core.providers.anilist import AniListProvider, parse_anilist_ref
real_id_map = anilist.western_id_map
ONE_PIECE = {
"id": 21,
"idMal": 21,
@@ -29,10 +37,13 @@ ONE_PIECE_MOVIE = {
class FakeResponse:
def __init__(self, body: dict) -> None:
def __init__(self, body: Any) -> None:
self._body = body
def json(self) -> dict:
def raise_for_status(self) -> None:
pass
def json(self) -> Any:
return self._body
@@ -258,3 +269,98 @@ def test_a_cached_node_rebuilds_with_the_read_time_title_language(monkeypatch: p
assert result.kind == "tv"
assert result.external_ids.anilist_id == 21
assert result.original_language == "ja"
def test_a_cached_node_keeps_the_ids_enrichment_filled() -> None:
from unshackle.core.providers import cached_to_result
enriched = {"imdb_id": "tt0388629", "tmdb_id": 37854, "tmdb_kind": "tv", "tvdb_id": 81797, "anilist_id": 21}
result = cached_to_result({**ONE_PIECE, "_enriched_ids": enriched}, "anilist", "tv")
assert result is not None
assert result.external_ids == anilist.ExternalIds("tt0388629", 37854, "tv", 81797, 21)
MAP_ENTRIES: list[Any] = [
{"anilist_id": 21, "imdb_id": ["tt0388629"], "themoviedb_id": {"tv": 37854}, "tvdb_id": 81797},
{"anilist_id": 199, "imdb_id": ["tt0245429"], "themoviedb_id": {"movie": [129]}},
{"anilist_id": 3269, "imdb_id": ["tt1164545"], "themoviedb_id": {"tv": 8864}, "tvdb_id": 79099},
{"anilist_id": 500, "imdb_id": ["tt1", "tt2"], "themoviedb_id": {"movie": [1, 2]}},
{"anilist_id": 600, "tvdb_id": "81797", "themoviedb_id": [37854], "imdb_id": ["tt12x"]},
{"mal_id": 7, "tvdb_id": 1},
]
@pytest.fixture
def id_map(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Iterator[list[str]]:
"""The real ID map loader with its cache in tmp_path and its download stubbed; returns the fetched URLs."""
fetched: list[str] = []
monkeypatch.setattr(config.directories, "cache", tmp_path)
monkeypatch.setattr(
requests.Session, "get", lambda self, url, **kwargs: fetched.append(url) or FakeResponse(MAP_ENTRIES)
)
monkeypatch.setattr(anilist, "western_id_map", real_id_map)
real_id_map.cache_clear()
yield fetched
real_id_map.cache_clear()
def test_the_id_map_keeps_only_unambiguous_western_ids(id_map: list[str]) -> None:
assert anilist.western_id_map() == {
"21": {"imdb": "tt0388629", "tmdb_tv": 37854, "tvdb": 81797},
"199": {"imdb": "tt0245429", "tmdb_movie": 129},
"3269": {"imdb": "tt1164545", "tmdb_tv": 8864, "tvdb": 79099},
}
def test_the_id_map_downloads_once_and_then_reads_the_cache(id_map: list[str]) -> None:
first = anilist.western_id_map()
real_id_map.cache_clear()
assert anilist.western_id_map() == first
assert id_map == [anilist.ID_MAP_URL]
def test_a_failed_download_gives_an_empty_map(monkeypatch: pytest.MonkeyPatch, id_map: list[str]) -> None:
def down(self: requests.Session, url: str, **kwargs: Any) -> FakeResponse:
raise requests.ConnectionError("down")
monkeypatch.setattr(requests.Session, "get", down)
assert anilist.western_id_map() == {}
def test_an_expired_map_still_answers_when_the_download_fails(
monkeypatch: pytest.MonkeyPatch, id_map: list[str]
) -> None:
stale = {"21": {"imdb": "tt0388629", "tmdb_tv": 37854, "tvdb": 81797}}
Cacher("global", anilist.ID_MAP_CACHE_KEY).set(stale, expiration=datetime.now() - timedelta(days=1))
monkeypatch.setattr(requests.Session, "get", lambda self, url, **kwargs: FakeResponse("not a list"))
assert anilist.western_id_map() == stale
def test_a_damaged_map_cache_is_downloaded_again(id_map: list[str]) -> None:
path = Cacher("global", anilist.ID_MAP_CACHE_KEY).path
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("{}")
assert "21" in anilist.western_id_map()
assert id_map == [anilist.ID_MAP_URL]
@pytest.mark.parametrize(
("anilist_id", "kind", "expected"),
[
(21, "tv", anilist.ExternalIds("tt0388629", 37854, "tv", 81797)),
(199, "movie", anilist.ExternalIds("tt0245429", 129, "movie")),
(199, "tv", anilist.ExternalIds("tt0245429")),
(3269, "movie", anilist.ExternalIds("tt1164545")),
(500, "movie", anilist.ExternalIds()),
(999, "tv", anilist.ExternalIds()),
],
)
def test_western_ids_never_cross_the_kind(
id_map: list[str], anilist_id: int, kind: str, expected: anilist.ExternalIds
) -> None:
assert anilist.western_ids(anilist_id, kind) == expected
+14
View File
@@ -6,6 +6,7 @@ import pytest
from unshackle.core import providers
from unshackle.core.config import config
from unshackle.core.providers import anilist
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult
@@ -63,3 +64,16 @@ def test_no_ids_returns_none(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(providers, "get_provider", lambda name: FakeProvider(name))
assert providers.resolve_by_ids(title="Futurama", year=1999, kind="tv") is None
def test_a_supplied_anilist_id_still_takes_the_mapped_western_ids(monkeypatch: pytest.MonkeyPatch) -> None:
anilist_provider = FakeProvider("anilist", MetadataResult(kind="tv", external_ids=ExternalIds(anilist_id=21)))
monkeypatch.setattr(providers, "get_provider", lambda name: {"anilist": anilist_provider}.get(name))
monkeypatch.setattr(
anilist, "western_id_map", lambda: {"21": {"imdb": "tt0388629", "tmdb_tv": 37854, "tvdb": 81797}}
)
result = providers.resolve_by_ids(anilist_id=21, kind="tv")
assert result is not None
assert result.external_ids == ExternalIds("tt0388629", 37854, "tv", 81797, 21)
+100
View File
@@ -8,10 +8,16 @@ import pytest
from unshackle.core import providers
from unshackle.core.config import config
from unshackle.core.providers import anilist
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult
search_metadata = providers.search_metadata
ANIME_MAP = {
"21": {"imdb": "tt0388629", "tmdb_tv": 37854, "tvdb": 81797},
"199": {"imdb": "tt0245429", "tmdb_movie": 129},
}
class FakeProvider(MetadataProvider):
"""Stands in for a real provider; records the ID it was asked for."""
@@ -330,3 +336,97 @@ def test_all_supplied_ids_survive_together(monkeypatch: pytest.MonkeyPatch) -> N
assert result is not None
assert result.external_ids.tvdb_id == 81797
assert result.external_ids.anilist_id == 21
@pytest.fixture
def anime_map(monkeypatch: pytest.MonkeyPatch) -> list[bool]:
"""A stubbed AniList ID map; returns one entry per map read."""
reads: list[bool] = []
monkeypatch.setattr(anilist, "western_id_map", lambda: reads.append(True) or ANIME_MAP)
monkeypatch.setattr(providers, "get_provider", lambda name: None)
return reads
def anilist_hit(anilist_id: int = 21, kind: str = "tv", **ids: Any) -> MetadataResult:
return MetadataResult(title="One Piece", kind=kind, external_ids=ExternalIds(anilist_id=anilist_id, **ids))
@pytest.mark.parametrize(
("hit", "kind", "expected"),
[
(anilist_hit(), "tv", ExternalIds("tt0388629", 37854, "tv", 81797, 21)),
(anilist_hit(199, "movie"), "movie", ExternalIds("tt0245429", 129, "movie", None, 199)),
(anilist_hit(tmdb_id=37854, tmdb_kind="tv"), "tv", ExternalIds("tt0388629", 37854, "tv", 81797, 21)),
(anilist_hit(tvdb_id=1), "tv", ExternalIds(tvdb_id=1, anilist_id=21)),
(anilist_hit(), "movie", ExternalIds(anilist_id=21)),
(anilist_hit(199, "movie"), "tv", ExternalIds(anilist_id=199)),
],
ids=["series", "movie", "agreeing-id-fills-the-rest", "other-id-wins", "tv-node-for-a-movie", "movie-node-for-tv"],
)
def test_an_anilist_match_takes_the_mapped_western_ids(
anime_map: list[bool], hit: MetadataResult, kind: str, expected: ExternalIds
) -> None:
providers.fill_anime_ids(hit, kind)
assert hit.external_ids == expected
@pytest.mark.parametrize(
"ids",
[ExternalIds("tt1", 5, "tv", 7, 21), ExternalIds(imdb_id="tt1"), ExternalIds()],
ids=["all-western-ids", "not-anilist", "no-ids"],
)
def test_the_map_is_not_read_without_need(anime_map: list[bool], ids: ExternalIds) -> None:
before = ExternalIds(**vars(ids))
providers.fill_anime_ids(MetadataResult(kind="tv", external_ids=ids), "tv")
assert (anime_map, ids) == ([], before)
def test_a_supplied_anilist_id_takes_the_mapped_western_ids(
monkeypatch: pytest.MonkeyPatch, anime_map: list[bool]
) -> None:
patch_providers(monkeypatch, {"anilist": FakeProvider("anilist", anilist_hit())})
result = providers.resolve_by_ids(anilist_id=21, kind="tv")
assert result is not None
assert result.external_ids == ExternalIds("tt0388629", 37854, "tv", 81797, 21)
def test_the_tagging_lookup_fills_the_rest_without_a_tmdb_key(
monkeypatch: pytest.MonkeyPatch, anime_map: list[bool]
) -> None:
patch_providers(monkeypatch, {"anilist": FakeProvider("anilist", anilist_hit())})
result = providers.resolve_by_ids(37854, anilist_id=21, kind="tv")
assert result is not None
assert result.external_ids == ExternalIds("tt0388629", 37854, "tv", 81797, 21)
def test_a_supplied_western_id_wins_over_the_map(monkeypatch: pytest.MonkeyPatch, anime_map: list[bool]) -> None:
patch_providers(monkeypatch, {"anilist": FakeProvider("anilist", anilist_hit())})
result = providers.resolve_by_ids(tvdb_id=1, anilist_id=21, kind="tv")
assert result is not None
assert result.external_ids == ExternalIds(tvdb_id=1, anilist_id=21)
class AniListHit(FakeProvider):
def search(self, title: str, year: int | None, kind: str) -> MetadataResult | None:
return anilist_hit()
def test_a_search_hit_on_anilist_takes_the_mapped_western_ids(
monkeypatch: pytest.MonkeyPatch, anime_map: list[bool]
) -> None:
monkeypatch.setattr(config, "disable_metadata", False)
monkeypatch.setattr(providers, "provider_order", lambda *a: [lambda: AniListHit("anilist")])
result = search_metadata("One Piece", None, "tv")
assert result is not None
assert result.external_ids == ExternalIds("tt0388629", 37854, "tv", 81797, 21)
+13
View File
@@ -239,6 +239,19 @@ def test_a_listing_prints_the_search_match(monkeypatch: pytest.MonkeyPatch) -> N
assert "Search -> The Show (ID 1396)" in captured.get()
def test_an_anilist_search_hit_keeps_its_anilist_id_for_the_tags(monkeypatch: pytest.MonkeyPatch) -> None:
hit = MetadataResult(
title="The Show", external_ids=ExternalIds(tmdb_id=37854, tmdb_kind="tv", anilist_id=21), source="anilist"
)
Providers(monkeypatch, hit)
monkeypatch.setattr(providers, "result_matches", lambda result, title: result.title == title)
metadata = TitleMetadata()
with console.capture() as captured:
metadata.search(episode(1, 1), listing=True)
assert (metadata.tmdb_id, metadata.anilist_id) == (37854, 21)
assert "Search -> The Show (ID 37854)" 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:
+1 -1
View File
@@ -910,7 +910,7 @@ class dl:
default=None,
help="Use this AniList ID for tagging instead of an automatic search, or a MyAnimeList ID as mal:12345. "
"Add --enrich to also take its title, year and original language. Combines with one of "
"--tmdb, --imdb or --tvdb, which AniList does not know.",
"--tmdb, --imdb or --tvdb, which wins over the IDs mapped from AniList.",
)
@click.option(
"--enrich",
+1 -1
View File
@@ -1178,7 +1178,7 @@ async def download(request: web.Request) -> web.Response:
oneOf:
- type: integer
- type: string
description: AniList ID for tagging instead of a title search, or a MyAnimeList ID as the string mal:21. Combines with one of tmdb_id, imdb_id and tvdb_id, which AniList does not know (default - None)
description: AniList ID for tagging instead of a title search, or a MyAnimeList ID as the string mal:21. Combines with one of tmdb_id, imdb_id and tvdb_id, which wins over the IDs mapped from AniList (default - None)
enrich:
type: boolean
description: Overwrite show title, year and original language with the external source's. Requires one of tmdb_id, imdb_id, tvdb_id or anilist_id (default - false)
+27 -6
View File
@@ -12,7 +12,7 @@ from unshackle.core.providers._base import (
log,
result_matches,
)
from unshackle.core.providers.anilist import AniListProvider, parse_anilist_ref
from unshackle.core.providers.anilist import AniListProvider, parse_anilist_ref, western_ids
from unshackle.core.providers.imdb import IMDBProvider, title_to_result
from unshackle.core.providers.omdb import OMDBProvider
from unshackle.core.providers.simkl import SimklProvider
@@ -125,11 +125,12 @@ def search_metadata(
log.debug("%s search failed: %s", p.NAME, exc)
continue
if result and result_matches(result, title):
fill_anime_ids(result, kind)
enrich_ids(result)
if title_cacher and cache_title_id and result.raw:
try:
cache_data = result.raw
if result.external_ids.tmdb_id or result.external_ids.tvdb_id:
if result.external_ids.tmdb_id or result.external_ids.imdb_id or result.external_ids.tvdb_id:
cache_data = {
**result.raw,
"_enriched_ids": external_ids_to_dict(result.external_ids),
@@ -354,6 +355,7 @@ def resolve_by_ids(
ids.imdb_id = ext.imdb_id
if ext.tvdb_id and not ids.tvdb_id:
ids.tvdb_id = ext.tvdb_id
fill_anime_ids(result, kind)
enrich_ids(result)
return result
@@ -370,6 +372,26 @@ def enrichment_providers(kind: str | None = None) -> list[str]:
return [name for name in ENRICHMENT_AUTHORITY if name in configured]
def fill_anime_ids(result: MetadataResult, kind: str) -> None:
"""Fill the western IDs that an AniList match of ``kind`` lacks from the AniList ID map.
The map is used only when every western ID the match already has agrees with it, and never
when AniList gives the match another kind, so a mapped ID never replaces or mixes with another one.
"""
ids = result.external_ids
complete = ids.tmdb_id and ids.imdb_id and (ids.tvdb_id or kind == "movie")
if not ids.anilist_id or complete or (result.kind or kind) != kind:
return
mapped = western_ids(ids.anilist_id, kind)
pairs = ((ids.imdb_id, mapped.imdb_id), (ids.tmdb_id, mapped.tmdb_id), (ids.tvdb_id, mapped.tvdb_id))
if any(have and have != got for have, got in pairs):
return
ids.imdb_id = ids.imdb_id or mapped.imdb_id
ids.tmdb_id = ids.tmdb_id or mapped.tmdb_id
ids.tmdb_kind = ids.tmdb_kind or mapped.tmdb_kind
ids.tvdb_id = ids.tvdb_id or mapped.tvdb_id
def enrich_ids(result: MetadataResult) -> None:
"""Enrich a MetadataResult by cross-referencing IMDB ID with the available metadata providers.
@@ -561,12 +583,11 @@ def cached_to_result(cached: dict, provider_name: str, kind: str) -> MetadataRes
source="tvdb",
raw=cached,
)
elif provider_name == "anilist":
return AniListProvider().to_result(cached)
elif provider_name == "imdb":
result = title_to_result(cached, kind)
elif provider_name in ("anilist", "imdb"):
result = AniListProvider().to_result(cached) if provider_name == "anilist" else title_to_result(cached, kind)
if result:
enriched = cached.get("_enriched_ids", {})
result.external_ids.imdb_id = result.external_ids.imdb_id or enriched.get("imdb_id")
result.external_ids.tmdb_id = enriched.get("tmdb_id")
result.external_ids.tmdb_kind = enriched.get("tmdb_kind")
result.external_ids.tvdb_id = enriched.get("tvdb_id")
+80 -2
View File
@@ -1,8 +1,11 @@
from __future__ import annotations
import functools
import re
import requests
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, best_ratio
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, best_ratio, log
GRAPHQL_URL = "https://graphql.anilist.co"
@@ -17,6 +20,10 @@ MAL_QUERY = f"query UnshackleAniListMal($idMal: Int) {{ Media(idMal: $idMal, typ
TITLE_LANGUAGES: tuple[str, ...] = ("english", "romaji", "native")
ID_MAP_URL = "https://raw.githubusercontent.com/Fribb/anime-lists/master/anime-list-mini.json"
ID_MAP_CACHE_KEY = "anilist_id_map"
ID_MAP_LIFETIME = 7 * 24 * 3600
# AniList records where a title was produced, not what it is spoken in; these are the
# production countries whose anime output is reliably in the country's own language
COUNTRY_TO_LANGUAGE: dict[str, str] = {"JP": "ja", "KR": "ko", "CN": "zh", "TW": "zh", "HK": "zh"}
@@ -134,7 +141,7 @@ class AniListProvider(MetadataProvider):
return self.to_result(node)
def get_external_ids(self, provider_id: int | str, kind: str) -> ExternalIds:
"""Return external IDs. AniList knows no western IDs, so only its own."""
"""Return the AniList ID only; ``fill_anime_ids`` adds the western IDs from the AniList ID map."""
ref = parse_anilist_ref(provider_id)
if not ref:
return ExternalIds()
@@ -145,6 +152,77 @@ class AniListProvider(MetadataProvider):
return result.external_ids if result else ExternalIds()
def as_id(value: object) -> int | None:
"""A positive integer ID, or None for anything else."""
return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else None
def single(values: object) -> object:
"""The one item of a list, or None for an empty or ambiguous list."""
return values[0] if isinstance(values, list) and len(values) == 1 else None
def reduce_map_entry(entry: dict) -> dict[str, int | str]:
"""The western IDs that one anime-lists entry sets; a list that holds several IDs gives none."""
tmdb = entry.get("themoviedb_id")
tmdb = tmdb if isinstance(tmdb, dict) else {}
imdb = single(entry.get("imdb_id"))
ids = {
"imdb": imdb if isinstance(imdb, str) and re.fullmatch(r"tt\d+", imdb) else None,
"tmdb_tv": as_id(tmdb.get("tv")),
"tmdb_movie": as_id(single(tmdb.get("movie"))),
"tvdb": as_id(entry.get("tvdb_id")),
}
return {key: value for key, value in ids.items() if value}
@functools.cache
def western_id_map() -> dict[str, dict]:
"""The anime-lists map from AniList ID to western IDs, downloaded once a week; empty when it cannot load."""
from unshackle.core.cacher import Cacher
cache = Cacher("global", ID_MAP_CACHE_KEY)
try:
cache = cache.get(ID_MAP_CACHE_KEY)
except (ValueError, KeyError, TypeError, AttributeError, OSError) as exc:
log.debug("Ignoring the unreadable AniList ID map cache: %s", exc)
if cache.data and not cache.expired:
return cache.data
try:
r = AniListProvider().session.get(ID_MAP_URL, timeout=30)
r.raise_for_status()
id_map: dict[str, dict] = {}
for entry in r.json():
anilist_id = as_id(entry.get("anilist_id"))
ids = reduce_map_entry(entry)
if anilist_id and ids:
id_map[str(anilist_id)] = ids
except (requests.RequestException, ValueError, TypeError, AttributeError) as exc:
log.debug("AniList ID map download failed: %s", exc)
return cache.data or {}
try:
cache.set(id_map, expiration=ID_MAP_LIFETIME)
except OSError as exc:
log.debug("AniList ID map not cached: %s", exc)
return id_map
def western_ids(anilist_id: int, kind: str) -> ExternalIds:
"""The TMDB, IMDb and TVDB IDs that the ID map gives an AniList ID of ``kind`` ("movie" or "tv").
A movie takes only a TMDB movie ID, and a series only a TMDB TV ID and the TVDB series ID.
"""
entry = western_id_map().get(str(anilist_id)) or {}
tmdb_id = entry.get("tmdb_movie") if kind == "movie" else entry.get("tmdb_tv")
return ExternalIds(
imdb_id=entry.get("imdb"),
tmdb_id=tmdb_id,
tmdb_kind=kind if tmdb_id else None,
tvdb_id=None if kind == "movie" else entry.get("tvdb"),
)
def media_names(node: dict) -> tuple[str, ...]:
"""Every title variant of an AniList media node that is set."""
return tuple(str(n) for n in (node.get("title") or {}).values() if n)
+2 -2
View File
@@ -69,8 +69,8 @@ def validate_metadata_ids(
) -> None:
"""Reject ID flags that conflict, or that no configured metadata provider could ever find.
--anilist stays outside the mutual exclusion: AniList knows no western IDs, so pairing
it with one of the other three is how an anime title gets both.
--anilist stays outside the mutual exclusion: a western ID given with it wins over the
IDs mapped from AniList.
"""
if anilist_id and not parse_anilist_ref(anilist_id):
raise PlanError("--anilist takes an AniList ID like 21, or a MyAnimeList ID like mal:21.")
+1
View File
@@ -175,6 +175,7 @@ class TitleMetadata:
self.tmdb_id = result.external_ids.tmdb_id
elif providers.result_matches(result, title.title):
self.tmdb_id = result.external_ids.tmdb_id
self.anilist_id = result.external_ids.anilist_id
tmdb_title = result.title
self.search_source = result.source
if listing: