feat(metadata)!: authoritative id resolver and keyless imdb provider

Supplied IDs resolve directly via a shared resolve_by_ids and never fall back to title search; metadata_providers gains per-kind ordering and a disable_metadata switch stops all automatic lookups while explicit IDs keep working.
BREAKING: --tmdb/--imdb/--tvdb are now mutually exclusive and require a usable provider; --enrich also overwrites original language; the imdbapi provider and imdb_api_enabled are replaced by a keyless imdb provider.
This commit is contained in:
imSp4rky
2026-08-11 15:07:24 -06:00
parent 0cec6c9686
commit ebb4e74318
22 changed files with 1035 additions and 293 deletions
+109 -15
View File
@@ -1,11 +1,11 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from typing import TYPE_CHECKING, Optional, Union
import requests
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, fuzzy_match, log
from unshackle.core.providers.imdbapi import IMDBApiProvider
from unshackle.core.providers.imdb import IMDBProvider
from unshackle.core.providers.omdb import OMDBProvider
from unshackle.core.providers.simkl import SimklProvider
from unshackle.core.providers.tmdb import TMDBProvider
@@ -15,18 +15,28 @@ if TYPE_CHECKING:
from unshackle.core.title_cacher import TitleCacher
REGISTRY: dict[str, type[MetadataProvider]] = {
cls.NAME: cls for cls in (IMDBApiProvider, OMDBProvider, SimklProvider, TMDBProvider, TVDBProvider)
cls.NAME: cls for cls in (IMDBProvider, OMDBProvider, SimklProvider, TMDBProvider, TVDBProvider)
}
# legacy `metadata_providers` names, still accepted
ALIASES: dict[str, str] = {"imdbapi": "imdb"}
# used when `metadata_providers` is unset
DEFAULT_ORDER: tuple[str, ...] = ("imdbapi", "omdb", "simkl", "tmdb", "tvdb")
DEFAULT_ORDER: tuple[str, ...] = ("imdb", "omdb", "simkl", "tmdb", "tvdb")
def provider_order() -> list[type[MetadataProvider]]:
"""Provider classes in the order configured by `metadata_providers`."""
def provider_order(kind: Optional[str] = None) -> list[type[MetadataProvider]]:
"""Provider classes in the order configured by `metadata_providers`.
`metadata_providers` is either a flat list applying to both kinds, or a mapping of
kind ("tv"/"movie") to its own list. A kind the mapping omits uses `DEFAULT_ORDER`.
"""
from unshackle.core.config import config
names = [str(n).lower() for n in (config.metadata_providers or DEFAULT_ORDER)]
configured = config.metadata_providers
selected = (configured.get(kind) if kind else None) if isinstance(configured, dict) else configured
names = [ALIASES.get(str(n).lower(), str(n).lower()) for n in (selected or DEFAULT_ORDER)]
unknown = [n for n in names if n not in REGISTRY]
if unknown:
log.warning("Ignoring unknown metadata_providers entries: %s", ", ".join(unknown))
@@ -60,7 +70,15 @@ def search_metadata(
cache_account_hash: Optional[str] = None,
) -> Optional[MetadataResult]:
"""Search all available providers for metadata. Returns best match."""
ordered = provider_order()
from unshackle.core.config import config
# the one gate for `disable_metadata`: every automatic lookup reaches a provider through
# here, while a user-supplied ID goes straight to `resolve_by_ids` and stays allowed
if config.disable_metadata:
log.debug("Metadata lookups are disabled by config; not searching for %r", title)
return None
ordered = provider_order(kind)
# Check cache first
if title_cacher and cache_title_id:
@@ -268,6 +286,78 @@ def fetch_external_ids(
return ext
def resolve_by_ids(
tmdb_id: Optional[int] = None,
imdb_id: Optional[str] = None,
tvdb_id: Optional[int] = None,
*,
title: Optional[str] = None,
year: Optional[int] = None,
kind: str = "movie",
title_cacher: Optional[TitleCacher] = None,
cache_title_id: Optional[str] = None,
cache_region: Optional[str] = None,
cache_account_hash: Optional[str] = None,
) -> Optional[MetadataResult]:
"""Resolve metadata from user-supplied external IDs, falling back to search only without them.
A supplied ID is authoritative. It is looked up directly through the providers that
consume its namespace, in `metadata_providers` order for `kind`, and it always survives
into `external_ids` whatever a provider answers. A fuzzy title search only runs when no
ID was supplied at all.
"""
supplied: dict[str, Union[int, str]] = {}
if tmdb_id is not None:
supplied["tmdb"] = tmdb_id
if imdb_id:
supplied["imdb"] = imdb_id
if tvdb_id is not None:
supplied["tvdb"] = tvdb_id
if not supplied:
if not title:
return None
return search_metadata(title, year, kind, title_cacher, cache_title_id, cache_region, cache_account_hash)
result: Optional[MetadataResult] = None
for cls in provider_order(kind):
provider_id = supplied.get(cls.ID_KIND or "")
if provider_id is None:
continue
p = get_provider(cls.NAME)
if not p:
continue
try:
result = p.get_by_id(provider_id, kind)
except Exception as exc:
log.debug("%s lookup of %s failed: %s", cls.NAME, provider_id, exc)
continue
if result:
break
if not result:
result = MetadataResult(title=title, year=year, kind=kind)
ids = result.external_ids
if tmdb_id is not None:
ids.tmdb_id = tmdb_id
ids.tmdb_kind = kind
if imdb_id:
ids.imdb_id = imdb_id
if tvdb_id is not None:
ids.tvdb_id = tvdb_id
if ids.tmdb_id and not (ids.imdb_id and ids.tvdb_id):
ext = fetch_external_ids(ids.tmdb_id, kind, title_cacher, cache_title_id, cache_region, cache_account_hash)
if ext.imdb_id and not ids.imdb_id:
ids.imdb_id = ext.imdb_id
if ext.tvdb_id and not ids.tvdb_id:
ids.tvdb_id = ext.tvdb_id
enrich_ids(result)
return result
# -- Internal helpers --
@@ -276,9 +366,9 @@ def fetch_external_ids(
_ENRICHMENT_AUTHORITY: tuple[str, ...] = ("tmdb", "simkl", "tvdb")
def _enrichment_providers() -> list[str]:
def _enrichment_providers(kind: Optional[str] = None) -> list[str]:
"""Names of configured providers that can resolve an IMDB ID, most trusted first."""
configured = {cls.NAME for cls in provider_order() if hasattr(cls, "find_by_imdb_id")}
configured = {cls.NAME for cls in provider_order(kind) if hasattr(cls, "find_by_imdb_id")}
return [name for name in _ENRICHMENT_AUTHORITY if name in configured]
@@ -298,7 +388,7 @@ def enrich_ids(result: MetadataResult) -> None:
kind = result.kind or "movie"
# Step 1: Collect enrichment results from all available providers
authority = {name: i for i, name in enumerate(_enrichment_providers())}
authority = {name: i for i, name in enumerate(_enrichment_providers(kind))}
enrichments: list[tuple[str, ExternalIds]] = []
for provider_name in authority:
p = get_provider(provider_name)
@@ -477,9 +567,11 @@ def _cached_to_result(cached: dict, provider_name: str, kind: str) -> Optional[M
source="tvdb",
raw=cached,
)
elif provider_name == "imdbapi":
title = cached.get("primaryTitle") or cached.get("originalTitle")
year = cached.get("startYear")
elif provider_name == "imdb":
from unshackle.core.providers.imdb import primary_language
title = (cached.get("titleText") or {}).get("text") or (cached.get("originalTitleText") or {}).get("text")
year = (cached.get("releaseYear") or {}).get("year")
imdb_id = cached.get("id")
# Restore enriched IDs that were saved alongside the raw data
enriched = cached.get("_enriched_ids", {})
@@ -493,7 +585,8 @@ def _cached_to_result(cached: dict, provider_name: str, kind: str) -> Optional[M
tmdb_kind=enriched.get("tmdb_kind"),
tvdb_id=enriched.get("tvdb_id"),
),
source="imdbapi",
original_language=primary_language(cached),
source="imdb",
raw=cached,
)
return None
@@ -513,5 +606,6 @@ __all__ = [
"get_title_by_id",
"get_year_by_id",
"provider_order",
"resolve_by_ids",
"search_metadata",
]
+2 -1
View File
@@ -37,7 +37,7 @@ class MetadataResult:
kind: Optional[str] = None # "movie" or "tv"
external_ids: ExternalIds = field(default_factory=ExternalIds)
original_language: Optional[str] = None # alpha-2 or alpha-3, whichever the provider speaks
source: str = "" # provider name, e.g. "tmdb", "simkl", "imdbapi"
source: str = "" # provider name, e.g. "tmdb", "simkl", "imdb"
raw: Optional[dict] = None # original API response for caching
@@ -46,6 +46,7 @@ class MetadataProvider(metaclass=ABCMeta):
NAME: str = ""
REQUIRES_KEY: bool = True
ID_KIND: Optional[str] = None
def __init__(self) -> None:
self.log = logging.getLogger(f"METADATA.{self.NAME.upper()}")
+156
View File
@@ -0,0 +1,156 @@
from __future__ import annotations
import hashlib
import json
from difflib import SequenceMatcher
from typing import Optional, Union
import requests
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, _clean, fuzzy_match
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) -> Optional[str]:
"""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 _title_to_result(node: dict, kind: str) -> Optional[MetadataResult]:
title = (node.get("titleText") or {}).get("text") or (node.get("originalTitleText") or {}).get("text")
if not title:
return None
return MetadataResult(
title=title,
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,
)
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) -> Optional[dict]:
"""Run a persisted query, registering it with one POST the first time it is seen."""
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: Optional[int], kind: str) -> Optional[MetadataResult]:
self.log.debug("Searching IMDb for %r (%s, %s)", title, kind, year)
constraints = [f'titleTextConstraint: {{searchTerm: "{escape_graphql(title)}"}}']
if year:
constraints.append(
f'releaseDateConstraint: {{releaseDateRange: {{start: "{year}-01-01", end: "{year}-12-31"}}}}'
)
types = KIND_TO_TYPES.get(kind)
if types:
constraints.append(f"titleTypeConstraint: {{anyTitleTypeIds: {json.dumps(types)}}}")
query = (
"query UnshackleTitleSearch { advancedTitleSearch(first: 5, constraints: {%s}) "
"{ edges { node { title { %s } } } } }" % (", ".join(constraints), 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", title)
return None
best = max(nodes, key=lambda n: _match_ratio(n, title))
result = _title_to_result(best, kind)
if not result or not result.title or not fuzzy_match(result.title, 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: Union[int, str], kind: str) -> Optional[MetadataResult]:
"""Fetch metadata by IMDB ID (e.g. 'tt1375666')."""
imdb_id = str(provider_id)
self.log.debug("Fetching IMDb title %s", imdb_id)
query = 'query UnshackleTitle { title(id: "%s") { %s } }' % (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: Union[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 _match_ratio(node: dict, title: str) -> float:
names = [(node.get("titleText") or {}).get("text"), (node.get("originalTitleText") or {}).get("text")]
return max((SequenceMatcher(None, _clean(title), _clean(n)).ratio() for n in names if n), default=0.0)
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
-132
View File
@@ -1,132 +0,0 @@
from __future__ import annotations
from difflib import SequenceMatcher
from typing import Optional, Union
import requests
from unshackle.core.config import config
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, _clean, fuzzy_match
# Mapping from our kind ("movie"/"tv") to IMDxAPI title types
KIND_TO_TYPES: dict[str, list[str]] = {
"movie": ["movie"],
"tv": ["tvSeries", "tvMiniSeries"],
}
def primary_language(data: dict) -> Optional[str]:
"""IMDb orders spokenLanguages most prominent first, and only detail responses carry it."""
langs = data.get("spokenLanguages") or []
return langs[0].get("code") if langs else None
class IMDBApiProvider(MetadataProvider):
"""IMDb metadata provider using IMDxAPI (api.tiffara.com, free, no API key)."""
NAME = "imdbapi"
REQUIRES_KEY = False
BASE_URL = "https://api.tiffara.com"
def is_available(self) -> bool:
return config.imdb_api_enabled
def search(self, title: str, year: Optional[int], kind: str) -> Optional[MetadataResult]:
self.log.debug("Searching IMDBApi for %r (%s, %s)", title, kind, year)
try:
params: dict[str, str | int] = {"query": title, "limit": 20}
r = self.session.get(
f"{self.BASE_URL}/search/titles",
params=params,
timeout=30,
)
r.raise_for_status()
data = r.json()
except (requests.RequestException, ValueError) as exc:
self.log.debug("IMDBApi search failed: %s", exc)
return None
results = data.get("titles") or data.get("results") or []
if not results:
self.log.debug("IMDBApi returned no results for %r", title)
return None
# Filter by type if possible
type_filter = KIND_TO_TYPES.get(kind, [])
filtered = [r for r in results if r.get("type") in type_filter] if type_filter else results
candidates = filtered if filtered else results
# Find best fuzzy match, optionally filtered by year
best_match: Optional[dict] = None
best_ratio = 0.0
for candidate in candidates:
primary = candidate.get("primaryTitle") or ""
original = candidate.get("originalTitle") or ""
for name in [primary, original]:
if not name:
continue
ratio = SequenceMatcher(None, _clean(title), _clean(name)).ratio()
if ratio > best_ratio:
# If year provided, prefer matches within 1 year
candidate_year = candidate.get("startYear")
if year and candidate_year and abs(year - candidate_year) > 1:
continue
best_ratio = ratio
best_match = candidate
if not best_match:
self.log.debug("No matching result found in IMDBApi for %r", title)
return None
result_title = best_match.get("primaryTitle") or best_match.get("originalTitle")
if not result_title or not fuzzy_match(result_title, title):
self.log.debug("IMDBApi title mismatch: searched %r, got %r", title, result_title)
return None
imdb_id = best_match.get("id")
result_year = best_match.get("startYear")
self.log.debug("IMDBApi -> %s (ID %s)", result_title, imdb_id)
return MetadataResult(
title=result_title,
year=result_year,
kind=kind,
external_ids=ExternalIds(imdb_id=imdb_id),
original_language=primary_language(best_match),
source="imdbapi",
raw=best_match,
)
def get_by_id(self, provider_id: Union[int, str], kind: str) -> Optional[MetadataResult]:
"""Fetch metadata by IMDB ID (e.g. 'tt1375666')."""
imdb_id = str(provider_id)
self.log.debug("Fetching IMDBApi title %s", imdb_id)
try:
r = self.session.get(f"{self.BASE_URL}/titles/{imdb_id}", timeout=30)
r.raise_for_status()
data = r.json()
except (requests.RequestException, ValueError) as exc:
self.log.debug("IMDBApi get_by_id failed: %s", exc)
return None
title = data.get("primaryTitle") or data.get("originalTitle")
result_year = data.get("startYear")
return MetadataResult(
title=title,
year=result_year,
kind=kind,
external_ids=ExternalIds(imdb_id=data.get("id")),
original_language=primary_language(data),
source="imdbapi",
raw=data,
)
def get_external_ids(self, provider_id: Union[int, str], kind: str) -> ExternalIds:
"""Return external IDs. For IMDB, the provider_id IS the IMDB ID."""
return ExternalIds(imdb_id=str(provider_id))
+1
View File
@@ -39,6 +39,7 @@ class OMDBProvider(MetadataProvider):
NAME = "omdb"
REQUIRES_KEY = True
ID_KIND = "imdb"
BASE_URL = "https://www.omdbapi.com/"
def is_available(self) -> bool:
+1
View File
@@ -14,6 +14,7 @@ class TMDBProvider(MetadataProvider):
NAME = "tmdb"
REQUIRES_KEY = True
ID_KIND = "tmdb"
BASE_URL = "https://api.themoviedb.org/3"
def is_available(self) -> bool:
+1
View File
@@ -71,6 +71,7 @@ class TVDBProvider(MetadataProvider):
NAME = "tvdb"
REQUIRES_KEY = True
ID_KIND = "tvdb"
BASE_URL = "https://api4.thetvdb.com/v4"
def __init__(self) -> None: