Files
unshackle/unshackle/core/providers/imdb.py
T

180 lines
7.0 KiB
Python

from __future__ import annotations
import hashlib
import json
import requests
from unshackle.core.providers._base import (
ExternalIds,
MetadataProvider,
MetadataResult,
best_ratio,
result_matches,
strip_year,
)
GRAPHQL_URL = "https://caching.graphql.imdb.com/"
GRAPHQL_HEADERS = {
"Accept": "application/graphql+json, application/json",
"Content-Type": "application/json",
"Origin": "https://www.imdb.com",
"X-Imdb-Client-Name": "imdb-web-next-localized",
"X-Imdb-User-Country": "US",
}
KIND_TO_TYPES: dict[str, list[str]] = {
"movie": ["movie", "tvMovie"],
"tv": ["tvSeries", "tvMiniSeries"],
}
TITLE_FIELDS = (
"id titleText { text } originalTitleText { text } releaseYear { year } "
"spokenLanguages { spokenLanguages { id text } }"
)
def escape_graphql(value: str) -> str:
return value.replace("\\", "\\\\").replace('"', '\\"')
def primary_language(data: dict) -> str | None:
"""IMDb orders spokenLanguages most prominent first. Either level can come back null."""
spoken = data.get("spokenLanguages") or {}
langs = spoken.get("spokenLanguages") or []
return langs[0].get("id") if langs else None
def node_names(node: dict) -> tuple[str, ...]:
"""The display title, then the original title, of an IMDb title node."""
names = ((node.get("titleText") or {}).get("text"), (node.get("originalTitleText") or {}).get("text"))
return tuple(n for n in names if n)
def title_to_result(node: dict, kind: str) -> MetadataResult | None:
names = node_names(node)
if not names:
return None
return MetadataResult(
title=names[0],
year=(node.get("releaseYear") or {}).get("year"),
kind=kind,
external_ids=ExternalIds(imdb_id=node.get("id")),
original_language=primary_language(node),
source="imdb",
raw=node,
names=names,
)
class IMDBProvider(MetadataProvider):
"""IMDb metadata provider using IMDb's own GraphQL edge cache (no API key)."""
NAME = "imdb"
REQUIRES_KEY = False
ID_KIND = "imdb"
def is_available(self) -> bool:
return True
def graphql(self, operation: str, query: str) -> dict | None:
"""Send a persisted query, and add it to the gateway with one POST if the gateway does not know its hash."""
extensions = {"persistedQuery": {"version": 1, "sha256Hash": hashlib.sha256(query.encode()).hexdigest()}}
# IMDb's GraphQL gateway decodes "+" literally, so these JSON params must carry no spaces
params = {
"operationName": operation,
"variables": "{}",
"extensions": json.dumps(extensions, separators=(",", ":")),
}
try:
r = self.session.get(GRAPHQL_URL, params=params, headers=GRAPHQL_HEADERS, timeout=30)
body = r.json()
if persisted_query_missing(body):
self.log.debug("Registering persisted query %s", operation)
payload = {"operationName": operation, "variables": {}, "query": query, "extensions": extensions}
r = self.session.post(GRAPHQL_URL, json=payload, headers=GRAPHQL_HEADERS, timeout=30)
body = r.json()
except (requests.RequestException, ValueError) as exc:
self.log.debug("IMDb GraphQL %s failed: %s", operation, exc)
return None
if body.get("errors"):
self.log.debug("IMDb GraphQL %s errors: %s", operation, [e.get("message") for e in body["errors"]][:3])
return None
return body.get("data")
def search(self, title: str, year: int | None, kind: str) -> MetadataResult | None:
"""Find a title released in `year`, then on a miss the one title of that name released in or before it.
A service can give the year of a later season, which is after the year that IMDb lists for the series.
"""
search_title = strip_year(title, year) if year else title
self.log.debug("Searching IMDb for %r (%s, %s)", search_title, kind, year)
result = self.search_range(title, search_title, kind, year)
if not result and year:
result = self.search_range(title, search_title, kind, year, wide=True)
return result
def search_range(
self, title: str, search_title: str, kind: str, year: int | None, wide: bool = False
) -> MetadataResult | None:
constraints = [f'titleTextConstraint: {{searchTerm: "{escape_graphql(search_title)}"}}']
if year:
start = "" if wide else f'start: "{year}-01-01", '
constraints.append(f'releaseDateConstraint: {{releaseDateRange: {{{start}end: "{year}-12-31"}}}}')
types = KIND_TO_TYPES.get(kind)
if types:
constraints.append(f"titleTypeConstraint: {{anyTitleTypeIds: {json.dumps(types)}}}")
first = 10 if wide else 5
query = (
f"query UnshackleTitleSearch {{ advancedTitleSearch(first: {first}, constraints: {{{', '.join(constraints)}}}) "
f"{{ edges {{ node {{ title {{ {TITLE_FIELDS} }} }} }} }} }}"
)
data = self.graphql("UnshackleTitleSearch", query)
edges = ((data or {}).get("advancedTitleSearch") or {}).get("edges") or []
nodes = [edge["node"]["title"] for edge in edges if (edge.get("node") or {}).get("title")]
if not nodes:
self.log.debug("IMDb returned no results for %r (%s, wide %s)", search_title, year, wide)
return None
scores = [best_ratio(search_title, node_names(n)) for n in nodes]
top = max(scores)
if wide and scores.count(top) > 1:
self.log.debug("IMDb has %d titles named like %r up to %s", scores.count(top), search_title, year)
return None
result = title_to_result(nodes[scores.index(top)], kind)
if not result or not result_matches(result, title):
self.log.debug("IMDb title mismatch: searched %r, got %r", title, result.title if result else None)
return None
self.log.debug("IMDb -> %s (ID %s)", result.title, result.external_ids.imdb_id)
return result
def get_by_id(self, provider_id: int | str, kind: str) -> MetadataResult | None:
"""Fetch metadata by IMDB ID (e.g. 'tt1375666')."""
imdb_id = str(provider_id)
self.log.debug("Fetching IMDb title %s", imdb_id)
query = f'query UnshackleTitle {{ title(id: "{escape_graphql(imdb_id)}") {{ {TITLE_FIELDS} }} }}'
data = self.graphql("UnshackleTitle", query)
node = (data or {}).get("title")
if not node:
return None
return title_to_result(node, kind)
def get_external_ids(self, provider_id: int | str, kind: str) -> ExternalIds:
"""Return external IDs. For IMDB, the provider_id IS the IMDB ID."""
return ExternalIds(imdb_id=str(provider_id))
def persisted_query_missing(body: dict) -> bool:
for error in body.get("errors") or []:
code = (error.get("extensions") or {}).get("code")
if code == "PERSISTED_QUERY_NOT_FOUND" or error.get("message") == "PersistedQueryNotFound":
return True
return False