"""Look up anime on AniList by ID. This module wraps AniList's public GraphQL API (https://graphql.anilist.co) and exposes one public function, :func:`get_anime_name`, which resolves an AniList media ID to the best available display title. All failures are raised as subclasses of :class:`anilist_errors.AniListError` so callers (and the proxy) can handle them in one place. Each error carries a ``status_code``, a stable ``code`` and a safe ``client_message``; internal detail is logged here rather than exposed to clients. """ import requests from anilist_errors import AniListApiError, AnimeNotFound, InvalidAnimeId, MissingAnimeName, RateLimitedError from simple_logger_handler import setup_logger logger = setup_logger(__name__) ANILIST_API_URL = "https://graphql.anilist.co" DEFAULT_TIMEOUT = 10 _ID_QUERY = """ query ($id: Int) { Media(id: $id, type: ANIME) { id title { romaji english native } } } """ # Preference order when picking a display name. _TITLE_PREFERENCE = ("english", "romaji", "native") def _post( query: str, variables: dict, session: requests.Session | None, timeout: float, ) -> dict: """POST a GraphQL query to AniList and return the ``data`` part of the reply. This is the only function that talks to the network. It translates every way a request can go wrong into a :class:`AniListError` subclass, in this order: 1. Transport failure (DNS, connection, timeout, ...) -> ``AniListApiError`` 2. HTTP 404 -> ``AnimeNotFound`` 3. HTTP 429 -> ``RateLimitedError`` 4. Other HTTP error status or body that isn't JSON -> ``AniListApiError`` 5. JSON body that isn't an object -> ``AniListApiError`` 6. GraphQL ``errors`` array present -> ``AniListApiError`` 7. ``data`` present but not an object -> ``AniListApiError`` A missing or ``null`` ``data`` field is not an error here; it is returned as an empty dict and the caller decides what that means. Args: query: The GraphQL query string. variables: Variables for the query. The ``"id"`` key, if present, is used to identify the anime in a 404 error. session: Optional ``requests.Session``. When ``None``, a one-off ``requests.post`` is used. timeout: Request timeout in seconds. Returns: The ``data`` dict from the GraphQL response, or ``{}`` if AniList returned no ``data``. Raises: AnimeNotFound: AniList answered HTTP 404 (unknown ID). RateLimitedError: AniList answered HTTP 429. ``retry_after`` is set when the ``Retry-After`` header was a valid integer. AniListApiError: Network failure, non-2xx status, invalid or unexpected JSON, or a GraphQL-level error. """ anime_id = variables.get("id") http = session or requests try: response = http.post( ANILIST_API_URL, json={"query": query, "variables": variables}, timeout=timeout, ) except requests.RequestException as e: raise AniListApiError(f"Request to AniList failed: {type(e).__name__}") from e if response.status_code == 404: logger.warning("AniList returned 404 for id=%s", anime_id) raise AnimeNotFound(variables.get("id")) if response.status_code == 429: retry_after = response.headers.get("Retry-After", "unknown") logger.warning("Rate limited by AniList on id=%s (Retry-After=%s)", anime_id, retry_after,) raise RateLimitedError(int(retry_after) if retry_after.isdigit() else None) try: response.raise_for_status() payload = response.json() except (requests.HTTPError, ValueError) as e: logger.warning("Bad response from AniList: %s", e) raise AniListApiError(f"Bad response from AniList: {e}") from e if not isinstance(payload, dict): logger.warning("Unexpected AniList payload type: %s", type(payload).__name__) raise AniListApiError(f"Unexpected response shape: {type(payload).__name__}") if errors := payload.get("errors"): messages = "; ".join(str(err.get("message", err)) for err in errors) raise AniListApiError(f"AniList returned errors: {messages}") data = payload.get("data") if data is None: logger.debug("AniList response for id=%s had no 'data'; returning empty dict", anime_id) return {} if not isinstance(data, dict): logger.warning("Unexpected 'data' shape for id=%s: %s", anime_id, type(data).__name__,) raise AniListApiError(f"Unexpected 'data' shape: {type(data).__name__}") logger.debug("Parsed AniList data for id=%s: keys=%s", anime_id, list(data)) return data def _pick_name(title: dict | None) -> str | None: """Choose the best display name from an AniList ``title`` object. Tries each key in ``_TITLE_PREFERENCE`` (English, then romaji, then native) and returns the first one that is non-empty after stripping whitespace. Missing keys, ``None`` values and blank strings are skipped. Args: title: The ``title`` object from AniList, e.g. ``{"romaji": "...", "english": None, "native": "..."}``. ``None`` is treated the same as an empty dict. Returns: The chosen title, or ``None`` if no usable title exists. """ title = title or {} for key in _TITLE_PREFERENCE: name = (title.get(key) or "").strip() if name: logger.debug("Picked '%s' title: %r", key, name) return name logger.debug("No usable title among keys %s in %s", _TITLE_PREFERENCE, title) return None def get_anime_name( anilist_id: int, *, session: requests.Session | None = None, timeout: float = DEFAULT_TIMEOUT, ) -> str: """Return the best available title for an AniList anime ID. Validates the ID, queries AniList, and picks a title in the order English, romaji, native. Only media of type ``ANIME`` match; a manga or other media ID is treated as not found. Every failure is raised as an :class:`AniListError` subclass, so a single ``except AniListError`` is enough to catch them all. Errors with ``client_visible = True`` are safe to show to end users; the rest carry internal detail and should only be logged. Args: anilist_id: AniList media ID. Must be a positive ``int`` (``bool`` is rejected even though it is an ``int`` subclass). session: Optional ``requests.Session`` to reuse connections when looking up many IDs. timeout: Request timeout in seconds. Defaults to ``DEFAULT_TIMEOUT``. Returns: The anime's display title, stripped of surrounding whitespace. Raises: InvalidAnimeId: ``anilist_id`` is not a positive integer. No request is made. Client-visible (422). AnimeNotFound: No anime exists for this ID, either via HTTP 404 or an empty ``Media`` result. Client-visible (422). MissingAnimeName: The anime exists but none of its titles are usable. Client-visible (422). RateLimitedError: AniList rate limited the request (503). Callers running in a loop should stop rather than keep going; see ``retry_after`` on the exception. AniListApiError: Network failure, timeout, 5xx, malformed response or GraphQL error. Not client-visible (502); safe to retry later. Example: >>> get_anime_name(1) 'Cowboy Bebop' """ if not isinstance(anilist_id, int) or isinstance(anilist_id, bool) or anilist_id <= 0: logger.warning("Rejected invalid anilist_id: %r", anilist_id) raise InvalidAnimeId(anilist_id) data = _post(_ID_QUERY, {"id": anilist_id}, session, timeout) media = data.get("Media") if not media: logger.warning("AniList returned no Media for anilist_id=%s", anilist_id) raise AnimeNotFound(anilist_id) name = _pick_name(media.get("title")) if name is None: logger.warning("Anime anilist_id=%s exists but has no usable title", anilist_id) raise MissingAnimeName(anilist_id) logger.info("Resolved anilist_id=%s to %r", anilist_id, name) return name if __name__ == "__main__": from anilist_errors import AniListError try: print(get_anime_name(200927)) print(get_anime_name(999999)) except AniListError as e: print(f"{e.code} ({e.status_code}): {e.client_message}")