"""Externe Cover-/Metadaten-Quellen (Open Library).""" # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations import logging import os from typing import Optional import httpx log = logging.getLogger(__name__) OL_SEARCH = "https://openlibrary.org/search.json" OL_COVER = "https://covers.openlibrary.org/b/isbn/{isbn}-L.jpg" DEFAULT_TIMEOUT = float(os.environ.get("WATCHSTACK_HTTP_TIMEOUT", "8")) def lookup_book_by_isbn(isbn: str, *, timeout: float = DEFAULT_TIMEOUT) -> Optional[dict]: """Sucht Buchdaten anhand ISBN via Open Library.""" if not isbn: return None isbn = isbn.strip().replace("-", "").replace(" ", "") try: with httpx.Client(timeout=timeout) as client: r = client.get(OL_SEARCH, params={"isbn": isbn, "limit": 1}) r.raise_for_status() data = r.json() except Exception as exc: # pragma: no cover log.warning("Open-Library-Suche fehlgeschlagen: %s", exc) return None docs = data.get("docs") or [] if not docs: return None d = docs[0] return { "title": d.get("title"), "original_title": d.get("title"), "author": ", ".join(d.get("author_name") or []) or None, "release_year": d.get("first_publish_year"), "cover_url": OL_COVER.format(isbn=isbn) if isbn else None, "total_pages": d.get("number_of_pages_median"), "description": None, # OL liefert hier keine handliche Kurzbeschreibung } def lookup_book_by_title(title: str, *, timeout: float = DEFAULT_TIMEOUT) -> Optional[dict]: """Sucht Buchdaten anhand Titel (Fallback).""" if not title: return None try: with httpx.Client(timeout=timeout) as client: r = client.get(OL_SEARCH, params={"title": title, "limit": 1}) r.raise_for_status() data = r.json() except Exception as exc: # pragma: no cover log.warning("Open-Library-Suche fehlgeschlagen: %s", exc) return None docs = data.get("docs") or [] if not docs: return None d = docs[0] isbn = None isbns = d.get("isbn") or [] if isbns: isbn = isbns[0] return { "title": d.get("title"), "author": ", ".join(d.get("author_name") or []) or None, "release_year": d.get("first_publish_year"), "cover_url": OL_COVER.format(isbn=isbn) if isbn else None, "total_pages": d.get("number_of_pages_median"), }