summaryrefslogtreecommitdiff
path: root/services/omdb.py
blob: 8e574a1769a75bed6f43ad2f8482fd3eb294362c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import os

import httpx

OMDB_URL = "http://www.omdbapi.com/"


def _api_key() -> str | None:
    return os.getenv("OMDB_API_KEY", "").strip() or None


async def fetch_ratings(
    *,
    title: str | None = None,
    year: int | None = None,
) -> dict | None:
    key = _api_key()
    if not key or not title:
        return None

    params: dict = {"apikey": key, "t": title}
    if year:
        params["y"] = str(year)

    try:
        async with httpx.AsyncClient(timeout=5.0) as client:
            response = await client.get(OMDB_URL, params=params)
            data = response.json()
    except Exception:
        return None

    if data.get("Response") == "False":
        return None

    result: dict = {}
    for rating in data.get("Ratings", []):
        source = rating.get("Source", "")
        value = rating.get("Value", "")
        if source == "Internet Movie Database":
            result["imdb"] = value
        elif source == "Rotten Tomatoes":
            result["rt"] = value
        elif source == "Metacritic":
            result["metacritic"] = value

    if not result.get("imdb"):
        raw = data.get("imdbRating", "")
        if raw and raw != "N/A":
            result["imdb"] = f"{raw}/10"

    return result or None