mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-26 10:55:08 +00:00
feat(metadata)!: replace animeapi with a first-class anilist provider
--anilist supersedes --animeapi (REST: anilist_id); the keyless AniList GraphQL provider joins the registry with title search, mal: ID lookup, an ANILIST mkv tag, and the anilist_title_language config option. Services mark anime via Service.ANIME / Title.anime for anilist-first metadata resolution with fall-through.
This commit is contained in:
@@ -420,7 +420,7 @@ def _perform_download(
|
||||
"imdb_id": params.get("imdb_id"),
|
||||
"tvdb_id": params.get("tvdb_id"),
|
||||
"tvdb_order": params.get("tvdb_order"),
|
||||
"animeapi_id": params.get("animeapi_id"),
|
||||
"anilist_id": params.get("anilist_id"),
|
||||
"enrich": params.get("enrich", False),
|
||||
"output_dir": Path(params["output_dir"]) if params.get("output_dir") else None,
|
||||
"no_cache": params.get("no_cache", False),
|
||||
@@ -452,7 +452,7 @@ def _perform_download(
|
||||
imdb_id=params.get("imdb_id"),
|
||||
tvdb_id=params.get("tvdb_id"),
|
||||
tvdb_order=params.get("tvdb_order"),
|
||||
animeapi_id=params.get("animeapi_id"),
|
||||
anilist_id=params.get("anilist_id"),
|
||||
enrich=params.get("enrich", False),
|
||||
output_dir=Path(params["output_dir"]) if params.get("output_dir") else None,
|
||||
)
|
||||
|
||||
@@ -14,6 +14,7 @@ from unshackle.core.api.input_bridge import AuthStatus, InputBridge
|
||||
from unshackle.core.api.sanitize import safe_cache_key, sanitize_log
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import AUDIO_CODEC_MAP, DYNAMIC_RANGE_MAP, VIDEO_CODEC_MAP
|
||||
from unshackle.core.providers.anilist import parse_anilist_ref
|
||||
from unshackle.core.proxies.resolve import initialize_proxy_providers, resolve_proxy
|
||||
from unshackle.core.services import Services
|
||||
from unshackle.core.titles import Episode, Movie, Title_T
|
||||
@@ -77,7 +78,7 @@ DEFAULT_DOWNLOAD_PARAMS = {
|
||||
"imdb_id": None,
|
||||
"tvdb_id": None,
|
||||
"tvdb_order": None,
|
||||
"animeapi_id": None,
|
||||
"anilist_id": None,
|
||||
"enrich": False,
|
||||
"output_dir": None,
|
||||
"no_cache": False,
|
||||
@@ -936,6 +937,13 @@ def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]:
|
||||
if not isinstance(data["imdb_id"], str) or not re.fullmatch(r"tt\d+", data["imdb_id"]):
|
||||
return "imdb_id must be an IMDB ID like 'tt1375666'"
|
||||
|
||||
if data.get("anilist_id") is not None:
|
||||
value = data["anilist_id"]
|
||||
# same parser as --anilist so both surfaces accept and reject the same inputs
|
||||
valid = not isinstance(value, bool) and isinstance(value, (int, str)) and parse_anilist_ref(value)
|
||||
if not valid:
|
||||
return "anilist_id must be a positive integer, or a MyAnimeList ID like 'mal:21'"
|
||||
|
||||
supplied_ids = [name for name in ("tmdb_id", "imdb_id", "tvdb_id") if data.get(name)]
|
||||
if len(supplied_ids) > 1:
|
||||
return (
|
||||
|
||||
@@ -759,12 +759,14 @@ async def download(request: web.Request) -> web.Response:
|
||||
tmdb_id:
|
||||
type: integer
|
||||
description: Use this TMDB ID for tagging instead of a title search. Set enrich to also take its title, year and original language. Mutually exclusive with imdb_id and tvdb_id. Needs tmdb_api_key (default - None)
|
||||
animeapi_id:
|
||||
type: string
|
||||
description: Anime database ID via AnimeAPI, e.g. mal:12345 (default - None)
|
||||
anilist_id:
|
||||
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)
|
||||
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 animeapi_id (default - false)
|
||||
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)
|
||||
no_folder:
|
||||
type: boolean
|
||||
description: Disable folder creation for TV shows (default - false)
|
||||
|
||||
@@ -120,6 +120,7 @@ class Config:
|
||||
self.tvdb_pin: str = kwargs.get("tvdb_pin") or ""
|
||||
self.tvdb_order: str = (kwargs.get("tvdb_order") or "").lower()
|
||||
self.metadata_providers: Union[list, dict] = kwargs.get("metadata_providers") or []
|
||||
self.anilist_title_language: str = (kwargs.get("anilist_title_language") or "english").lower()
|
||||
self.disable_metadata: bool = kwargs.get("disable_metadata", False)
|
||||
self.simkl_client_id: str = kwargs.get("simkl_client_id") or ""
|
||||
self.decrypt_labs_api_key: str = kwargs.get("decrypt_labs_api_key") or ""
|
||||
|
||||
@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Optional, Union
|
||||
import requests
|
||||
|
||||
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, fuzzy_match, log
|
||||
from unshackle.core.providers.anilist import AniListProvider, parse_anilist_ref
|
||||
from unshackle.core.providers.imdb import IMDBProvider
|
||||
from unshackle.core.providers.omdb import OMDBProvider
|
||||
from unshackle.core.providers.simkl import SimklProvider
|
||||
@@ -15,21 +16,24 @@ if TYPE_CHECKING:
|
||||
from unshackle.core.title_cacher import TitleCacher
|
||||
|
||||
REGISTRY: dict[str, type[MetadataProvider]] = {
|
||||
cls.NAME: cls for cls in (IMDBProvider, OMDBProvider, SimklProvider, TMDBProvider, TVDBProvider)
|
||||
cls.NAME: cls for cls in (AniListProvider, IMDBProvider, OMDBProvider, SimklProvider, TMDBProvider, TVDBProvider)
|
||||
}
|
||||
|
||||
# legacy `metadata_providers` names, still accepted
|
||||
ALIASES: dict[str, str] = {"imdbapi": "imdb"}
|
||||
|
||||
# used when `metadata_providers` is unset
|
||||
DEFAULT_ORDER: tuple[str, ...] = ("imdb", "omdb", "simkl", "tmdb", "tvdb")
|
||||
# used when `metadata_providers` is unset; anilist answers for anime only, so it costs
|
||||
# nothing at the end of the order
|
||||
DEFAULT_ORDER: tuple[str, ...] = ("imdb", "omdb", "simkl", "tmdb", "tvdb", "anilist")
|
||||
|
||||
|
||||
def provider_order(kind: Optional[str] = None) -> list[type[MetadataProvider]]:
|
||||
def provider_order(kind: Optional[str] = None, anime: bool = False) -> list[type[MetadataProvider]]:
|
||||
"""Provider classes in the order configured by `metadata_providers`.
|
||||
|
||||
`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`.
|
||||
An `anime` title puts anilist first; the rest of the order stays behind it to
|
||||
fall back on.
|
||||
"""
|
||||
from unshackle.core.config import config
|
||||
|
||||
@@ -37,6 +41,8 @@ def provider_order(kind: Optional[str] = None) -> list[type[MetadataProvider]]:
|
||||
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)]
|
||||
if anime and AniListProvider.NAME in names:
|
||||
names = [AniListProvider.NAME, *names]
|
||||
unknown = [n for n in names if n not in REGISTRY]
|
||||
if unknown:
|
||||
log.warning("Ignoring unknown metadata_providers entries: %s", ", ".join(unknown))
|
||||
@@ -68,6 +74,7 @@ def search_metadata(
|
||||
cache_title_id: Optional[str] = None,
|
||||
cache_region: Optional[str] = None,
|
||||
cache_account_hash: Optional[str] = None,
|
||||
anime: bool = False,
|
||||
) -> Optional[MetadataResult]:
|
||||
"""Search all available providers for metadata. Returns best match."""
|
||||
from unshackle.core.config import config
|
||||
@@ -78,7 +85,7 @@ def search_metadata(
|
||||
log.debug("Metadata lookups are disabled by config; not searching for %r", title)
|
||||
return None
|
||||
|
||||
ordered = provider_order(kind)
|
||||
ordered = provider_order(kind, anime)
|
||||
|
||||
# Check cache first
|
||||
if title_cacher and cache_title_id:
|
||||
@@ -290,6 +297,7 @@ def resolve_by_ids(
|
||||
tmdb_id: Optional[int] = None,
|
||||
imdb_id: Optional[str] = None,
|
||||
tvdb_id: Optional[int] = None,
|
||||
anilist_id: Optional[Union[int, str]] = None,
|
||||
*,
|
||||
title: Optional[str] = None,
|
||||
year: Optional[int] = None,
|
||||
@@ -298,6 +306,7 @@ def resolve_by_ids(
|
||||
cache_title_id: Optional[str] = None,
|
||||
cache_region: Optional[str] = None,
|
||||
cache_account_hash: Optional[str] = None,
|
||||
anime: bool = False,
|
||||
) -> Optional[MetadataResult]:
|
||||
"""Resolve metadata from user-supplied external IDs, falling back to search only without them.
|
||||
|
||||
@@ -313,14 +322,16 @@ def resolve_by_ids(
|
||||
supplied["imdb"] = imdb_id
|
||||
if tvdb_id is not None:
|
||||
supplied["tvdb"] = tvdb_id
|
||||
if anilist_id is not None:
|
||||
supplied["anilist"] = anilist_id
|
||||
|
||||
if not supplied:
|
||||
if not title:
|
||||
return None
|
||||
return search_metadata(title, year, kind, title_cacher, cache_title_id, cache_region, cache_account_hash)
|
||||
return search_metadata(title, year, kind, title_cacher, cache_title_id, cache_region, cache_account_hash, anime)
|
||||
|
||||
result: Optional[MetadataResult] = None
|
||||
for cls in provider_order(kind):
|
||||
for cls in provider_order(kind, anime):
|
||||
provider_id = supplied.get(cls.ID_KIND or "")
|
||||
if provider_id is None:
|
||||
continue
|
||||
@@ -346,6 +357,10 @@ def resolve_by_ids(
|
||||
ids.imdb_id = imdb_id
|
||||
if tvdb_id is not None:
|
||||
ids.tvdb_id = tvdb_id
|
||||
if anilist_id is not None and ids.anilist_id is None:
|
||||
ref = parse_anilist_ref(anilist_id)
|
||||
if ref and ref[0] == "id":
|
||||
ids.anilist_id = ref[1]
|
||||
|
||||
if ids.tmdb_id and not (ids.imdb_id and ids.tvdb_id):
|
||||
ext = fetch_external_ids(ids.tmdb_id, kind, title_cacher, cache_title_id, cache_region, cache_account_hash)
|
||||
@@ -480,6 +495,8 @@ def _external_ids_to_dict(ext: ExternalIds) -> dict:
|
||||
result["tmdb_kind"] = ext.tmdb_kind
|
||||
if ext.tvdb_id:
|
||||
result["tvdb_id"] = ext.tvdb_id
|
||||
if ext.anilist_id:
|
||||
result["anilist_id"] = ext.anilist_id
|
||||
return result
|
||||
|
||||
|
||||
@@ -567,6 +584,8 @@ def _cached_to_result(cached: dict, provider_name: str, kind: str) -> Optional[M
|
||||
source="tvdb",
|
||||
raw=cached,
|
||||
)
|
||||
elif provider_name == "anilist":
|
||||
return AniListProvider()._to_result(cached)
|
||||
elif provider_name == "imdb":
|
||||
from unshackle.core.providers.imdb import primary_language
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ class ExternalIds:
|
||||
tmdb_id: Optional[int] = None
|
||||
tmdb_kind: Optional[str] = None # "movie" or "tv"
|
||||
tvdb_id: Optional[int] = None
|
||||
anilist_id: Optional[int] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from difflib import SequenceMatcher
|
||||
from typing import Optional, Union
|
||||
|
||||
import requests
|
||||
|
||||
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, _clean
|
||||
|
||||
GRAPHQL_URL = "https://graphql.anilist.co"
|
||||
|
||||
MEDIA_FIELDS = "id idMal title { romaji english native } format startDate { year } countryOfOrigin"
|
||||
|
||||
SEARCH_QUERY = (
|
||||
"query UnshackleAniListSearch($search: String) { Page(perPage: 10) "
|
||||
"{ media(search: $search, type: ANIME, sort: SEARCH_MATCH) { %s } } }" % MEDIA_FIELDS
|
||||
)
|
||||
MEDIA_QUERY = "query UnshackleAniListMedia($id: Int) { Media(id: $id, type: ANIME) { %s } }" % MEDIA_FIELDS
|
||||
MAL_QUERY = "query UnshackleAniListMal($idMal: Int) { Media(idMal: $idMal, type: ANIME) { %s } }" % MEDIA_FIELDS
|
||||
|
||||
TITLE_LANGUAGES: tuple[str, ...] = ("english", "romaji", "native")
|
||||
|
||||
# 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"}
|
||||
|
||||
|
||||
def parse_anilist_ref(value: Union[int, str]) -> Optional[tuple[str, int]]:
|
||||
"""Split an AniList reference into its namespace and number.
|
||||
|
||||
A bare number is an AniList ID; ``mal:12345`` is a MyAnimeList ID, which AniList
|
||||
resolves natively. Returns None for anything else.
|
||||
"""
|
||||
text = str(value).strip().lower()
|
||||
namespace = "id"
|
||||
if ":" in text:
|
||||
prefix, _, text = text.partition(":")
|
||||
if prefix != "mal":
|
||||
return None
|
||||
namespace = "mal"
|
||||
# isdecimal, not isdigit: superscripts pass isdigit but crash int()
|
||||
if not text.isdecimal():
|
||||
return None
|
||||
number = int(text)
|
||||
return (namespace, number) if number > 0 else None
|
||||
|
||||
|
||||
class AniListProvider(MetadataProvider):
|
||||
"""Anime metadata provider using AniList's public GraphQL API (no API key)."""
|
||||
|
||||
NAME = "anilist"
|
||||
REQUIRES_KEY = False
|
||||
ID_KIND = "anilist"
|
||||
|
||||
def is_available(self) -> bool:
|
||||
return True
|
||||
|
||||
def _graphql(self, query: str, variables: dict) -> Optional[dict]:
|
||||
try:
|
||||
r = self.session.post(GRAPHQL_URL, json={"query": query, "variables": variables}, timeout=30)
|
||||
body = r.json()
|
||||
except (requests.RequestException, ValueError) as exc:
|
||||
self.log.debug("AniList GraphQL request failed: %s", exc)
|
||||
return None
|
||||
|
||||
if body.get("errors"):
|
||||
# a miss is a 404 with an error body, not an empty result
|
||||
self.log.debug("AniList GraphQL errors: %s", [e.get("message") for e in body["errors"]][:3])
|
||||
return None
|
||||
return body.get("data")
|
||||
|
||||
def _title_variant(self, titles: dict) -> Optional[str]:
|
||||
from unshackle.core.config import config
|
||||
|
||||
configured = (config.anilist_title_language or "english").lower()
|
||||
for variant in [configured, *(v for v in TITLE_LANGUAGES if v != configured)]:
|
||||
value = titles.get(variant)
|
||||
if value:
|
||||
return str(value)
|
||||
return None
|
||||
|
||||
def _to_result(self, node: dict) -> Optional[MetadataResult]:
|
||||
title = self._title_variant(node.get("title") or {})
|
||||
if not title:
|
||||
return None
|
||||
return MetadataResult(
|
||||
title=title,
|
||||
year=(node.get("startDate") or {}).get("year"),
|
||||
kind="movie" if node.get("format") == "MOVIE" else "tv",
|
||||
external_ids=ExternalIds(anilist_id=node.get("id")),
|
||||
original_language=COUNTRY_TO_LANGUAGE.get(node.get("countryOfOrigin") or ""),
|
||||
source="anilist",
|
||||
raw=node,
|
||||
)
|
||||
|
||||
def search(self, title: str, year: Optional[int], kind: str) -> Optional[MetadataResult]:
|
||||
self.log.debug("Searching AniList for %r (%s, %s)", title, kind, year)
|
||||
|
||||
data = self._graphql(SEARCH_QUERY, {"search": title})
|
||||
nodes = ((data or {}).get("Page") or {}).get("media") or []
|
||||
if not nodes:
|
||||
self.log.debug("AniList returned no results for %r", title)
|
||||
return None
|
||||
|
||||
# soft filters with fallback: other providers search kind-scoped endpoints, here
|
||||
# one ANIME search covers both kinds, so a TV hit must not shadow a movie search
|
||||
matching = [n for n in nodes if (n.get("format") == "MOVIE") == (kind == "movie")]
|
||||
nodes = matching or nodes
|
||||
if year:
|
||||
dated = [n for n in nodes if (n.get("startDate") or {}).get("year") == year]
|
||||
nodes = dated or nodes
|
||||
|
||||
best = max(nodes, key=lambda n: _match_ratio(n, title))
|
||||
result = self._to_result(best)
|
||||
if result:
|
||||
self.log.debug("AniList -> %s (ID %s)", result.title, result.external_ids.anilist_id)
|
||||
return result
|
||||
|
||||
def get_by_id(self, provider_id: Union[int, str], kind: str) -> Optional[MetadataResult]:
|
||||
"""Fetch metadata by AniList ID, or by MyAnimeList ID when given as 'mal:12345'."""
|
||||
ref = parse_anilist_ref(provider_id)
|
||||
if not ref:
|
||||
self.log.debug("Not an AniList reference: %r", provider_id)
|
||||
return None
|
||||
|
||||
namespace, number = ref
|
||||
self.log.debug("Fetching AniList media %s:%d", namespace, number)
|
||||
if namespace == "mal":
|
||||
data = self._graphql(MAL_QUERY, {"idMal": number})
|
||||
else:
|
||||
data = self._graphql(MEDIA_QUERY, {"id": number})
|
||||
|
||||
node = (data or {}).get("Media")
|
||||
if not node:
|
||||
return None
|
||||
return self._to_result(node)
|
||||
|
||||
def get_external_ids(self, provider_id: Union[int, str], kind: str) -> ExternalIds:
|
||||
"""Return external IDs. AniList knows no western IDs, so only its own."""
|
||||
ref = parse_anilist_ref(provider_id)
|
||||
if not ref:
|
||||
return ExternalIds()
|
||||
namespace, number = ref
|
||||
if namespace == "id":
|
||||
return ExternalIds(anilist_id=number)
|
||||
result = self.get_by_id(provider_id, kind)
|
||||
return result.external_ids if result else ExternalIds()
|
||||
|
||||
|
||||
def _match_ratio(node: dict, title: str) -> float:
|
||||
names = (node.get("title") or {}).values()
|
||||
return max((SequenceMatcher(None, _clean(title), _clean(n)).ratio() for n in names if n), default=0.0)
|
||||
@@ -93,6 +93,7 @@ class Service(metaclass=ABCMeta):
|
||||
# Abstract class variables
|
||||
ALIASES: tuple[str, ...] = () # list of aliases for the service; alternatives to the service tag.
|
||||
GEOFENCE: tuple[str, ...] = () # list of ip regions required to use the service. empty list == no specific region.
|
||||
ANIME: bool = False # service catalogue is anime; metadata lookups prefer AniList. Title.anime overrides per title.
|
||||
# vault namespace override; when set, key vault read/write uses this tag instead of the service's own.
|
||||
VAULT_TAG: Optional[str] = None
|
||||
# Auth methods the service accepts ("cookies"/"credentials"); when None the REST /services
|
||||
|
||||
@@ -47,6 +47,7 @@ class Title:
|
||||
self.service = service
|
||||
self.language = language
|
||||
self.data = data
|
||||
self.anime: Optional[bool] = None
|
||||
|
||||
self.tracks = Tracks()
|
||||
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from unshackle.core.providers._base import ExternalIds
|
||||
|
||||
log = logging.getLogger("ANIMEAPI")
|
||||
|
||||
PLATFORM_MAP: dict[str, str] = {
|
||||
"mal": "myanimelist",
|
||||
"anilist": "anilist",
|
||||
"kitsu": "kitsu",
|
||||
"tmdb": "themoviedb",
|
||||
"trakt": "trakt",
|
||||
"tvdb": "thetvdb",
|
||||
}
|
||||
|
||||
|
||||
def resolve_animeapi(value: str) -> tuple[Optional[str], ExternalIds]:
|
||||
"""Resolve an anime database ID via AnimeAPI to a title and external IDs.
|
||||
|
||||
Accepts formats like 'mal:12345', 'anilist:98765', or just '12345' (defaults to MAL).
|
||||
Returns (anime_title, ExternalIds) with any TMDB/IMDB/TVDB IDs found.
|
||||
"""
|
||||
import animeapi
|
||||
|
||||
platform_str, id_str = _parse_animeapi_value(value)
|
||||
|
||||
platform_enum = _get_platform(platform_str)
|
||||
if platform_enum is None:
|
||||
log.warning("Unknown AnimeAPI platform: %s (supported: %s)", platform_str, ", ".join(PLATFORM_MAP))
|
||||
return None, ExternalIds()
|
||||
|
||||
log.info("Resolving AnimeAPI %s:%s", platform_str, id_str)
|
||||
|
||||
try:
|
||||
with animeapi.AnimeAPI() as api:
|
||||
relation = api.get_anime_relations(id_str, platform_enum)
|
||||
except Exception as exc:
|
||||
log.warning("AnimeAPI lookup failed for %s:%s: %s", platform_str, id_str, exc)
|
||||
return None, ExternalIds()
|
||||
|
||||
title = getattr(relation, "title", None)
|
||||
|
||||
tmdb_id = getattr(relation, "themoviedb", None)
|
||||
tmdb_type = getattr(relation, "themoviedb_type", None)
|
||||
imdb_id = getattr(relation, "imdb", None)
|
||||
tvdb_id = getattr(relation, "thetvdb", None)
|
||||
|
||||
tmdb_kind: Optional[str] = None
|
||||
if tmdb_type is not None:
|
||||
tmdb_kind = tmdb_type.value if hasattr(tmdb_type, "value") else str(tmdb_type).lower()
|
||||
if tmdb_kind not in ("movie", "tv"):
|
||||
tmdb_kind = "tv"
|
||||
|
||||
external_ids = ExternalIds(
|
||||
tmdb_id=int(tmdb_id) if tmdb_id is not None else None,
|
||||
tmdb_kind=tmdb_kind,
|
||||
imdb_id=str(imdb_id) if imdb_id is not None else None,
|
||||
tvdb_id=int(tvdb_id) if tvdb_id is not None else None,
|
||||
)
|
||||
|
||||
log.info(
|
||||
"AnimeAPI resolved: title=%r, tmdb=%s, imdb=%s, tvdb=%s",
|
||||
title,
|
||||
external_ids.tmdb_id,
|
||||
external_ids.imdb_id,
|
||||
external_ids.tvdb_id,
|
||||
)
|
||||
|
||||
return title, external_ids
|
||||
|
||||
|
||||
def _parse_animeapi_value(value: str) -> tuple[str, str]:
|
||||
"""Parse 'platform:id' format. Defaults to 'mal' if no prefix."""
|
||||
if ":" in value:
|
||||
platform, _, id_str = value.partition(":")
|
||||
return platform.lower().strip(), id_str.strip()
|
||||
return "mal", value.strip()
|
||||
|
||||
|
||||
def _get_platform(platform_str: str) -> object | None:
|
||||
"""Map a platform string to an animeapi.Platform enum value."""
|
||||
import animeapi
|
||||
|
||||
canonical = PLATFORM_MAP.get(platform_str)
|
||||
if canonical is None:
|
||||
return None
|
||||
|
||||
platform_name = canonical.upper()
|
||||
return getattr(animeapi.Platform, platform_name, None)
|
||||
@@ -5,7 +5,7 @@ import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
from typing import Optional, Union
|
||||
from xml.sax.saxutils import escape
|
||||
|
||||
from unshackle.core import binaries
|
||||
@@ -74,6 +74,8 @@ def _build_tags_from_ids(ids: ExternalIds, kind: str) -> dict[str, str]:
|
||||
if ids.tvdb_id:
|
||||
prefix = "movies" if kind == "movie" else "series"
|
||||
tags["TVDB2"] = f"{prefix}/{ids.tvdb_id}"
|
||||
if ids.anilist_id:
|
||||
tags["ANILIST"] = str(ids.anilist_id)
|
||||
return tags
|
||||
|
||||
|
||||
@@ -83,6 +85,8 @@ def tag_file(
|
||||
tmdb_id: Optional[int] = None,
|
||||
imdb_id: Optional[str] = None,
|
||||
tvdb_id: Optional[int] = None,
|
||||
anilist_id: Optional[Union[int, str]] = None,
|
||||
anime: bool = False,
|
||||
) -> None:
|
||||
log.debug("Tagging file %s with title %r", path, title)
|
||||
custom_tags: dict[str, str] = {}
|
||||
@@ -114,13 +118,15 @@ def tag_file(
|
||||
|
||||
if config.tag_imdb_tmdb:
|
||||
try:
|
||||
has_ids = tmdb_id is not None or imdb_id is not None or tvdb_id is not None
|
||||
has_ids = any(value is not None for value in (tmdb_id, imdb_id, tvdb_id, anilist_id))
|
||||
if not get_available_providers() and not has_ids:
|
||||
log.debug("No metadata providers available; skipping tag lookup")
|
||||
apply_tags(path, custom_tags)
|
||||
return
|
||||
|
||||
result = resolve_by_ids(tmdb_id, imdb_id, tvdb_id, title=name, year=year, kind=kind)
|
||||
result = resolve_by_ids(
|
||||
tmdb_id, imdb_id, tvdb_id, anilist_id, title=name, year=year, kind=kind, anime=anime
|
||||
)
|
||||
|
||||
if result and result.external_ids:
|
||||
standard_tags = _build_tags_from_ids(result.external_ids, kind)
|
||||
|
||||
Reference in New Issue
Block a user