57 lines
1.6 KiB
Python
57 lines
1.6 KiB
Python
import json
|
|
import os
|
|
import re
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
from jsonfile import PROJECT_ROOT
|
|
|
|
IMDB_ID_PATTERN = re.compile(r"tt\d{7,9}")
|
|
ENV_FILE = PROJECT_ROOT / ".env"
|
|
OMDB_URL = "https://www.omdbapi.com/"
|
|
OMDB_DEMO_URL = "http://www.omdbapi.com/demo.aspx/"
|
|
RATE_LIMITED_STATUS = 401
|
|
|
|
|
|
def imdb_id(text: str) -> str | None:
|
|
match = IMDB_ID_PATTERN.search(text)
|
|
return match.group(0) if match else None
|
|
|
|
|
|
def title_url(identifier: str) -> str:
|
|
return f"https://www.imdb.com/title/{identifier}/"
|
|
|
|
|
|
def omdb_api_key() -> str | None:
|
|
if os.environ.get("OMDB_API_KEY"):
|
|
return os.environ["OMDB_API_KEY"]
|
|
if not ENV_FILE.exists():
|
|
return None
|
|
for line in ENV_FILE.read_text(encoding="utf-8").splitlines():
|
|
key, _, value = line.partition("=")
|
|
if key.strip() == "OMDB_API_KEY" and value.strip():
|
|
return value.strip().strip("\"'")
|
|
return None
|
|
|
|
|
|
def request_json(url: str, parameters: dict) -> dict:
|
|
with urllib.request.urlopen(f"{url}?{urllib.parse.urlencode(parameters)}", timeout=10) as response:
|
|
return json.load(response)
|
|
|
|
|
|
def lookup(identifier: str) -> dict | None:
|
|
api_key = omdb_api_key()
|
|
if not api_key:
|
|
return None
|
|
try:
|
|
try:
|
|
result = request_json(OMDB_URL, {"apikey": api_key, "i": identifier})
|
|
except urllib.error.HTTPError as error:
|
|
if error.code != RATE_LIMITED_STATUS:
|
|
raise
|
|
result = request_json(OMDB_DEMO_URL, {"i": identifier, "token": "demo"})
|
|
except (OSError, ValueError):
|
|
return None
|
|
return result if result.get("Response") == "True" else None
|