refactor(drm): drop the hardcoded service branch in the license flow

One service needed session_id in its license call, which a near-duplicate of get_content_keys supplied behind a service-tag test. service_licence now passes each service only the arguments its own license function declares, so the duplicate and the branch are gone. The REST API license paths and the base PlayReady delegate get the same filtering, replacing their fixed argument set.

Two behaviour changes ride along: an empty license challenge now raises EmptyLicense for every service, not just the one, and a service that declares only challenge now receives a working call instead of a TypeError.
This commit is contained in:
imSp4rky
2026-09-05 22:14:47 -06:00
parent e845e9ba28
commit 0f9997be4c
8 changed files with 564 additions and 61 deletions
+7 -7
View File
@@ -67,6 +67,7 @@ from unshackle.core.tracks.hybrid import Hybrid
from unshackle.core.tracks.track import assert_fragments_decrypted, has_encrypted_sample_entry
from unshackle.core.utilities import (
as_requested,
declared_kwargs,
embedded_audio_langs,
excluded_language_tags,
find_font_with_fallbacks,
@@ -4007,14 +4008,16 @@ class dl:
def service_licence(self, service: Service, drm_system: Optional[str] = None, **kwargs: Any) -> Any:
"""Call the service's licence function for the track's DRM system.
Arguments go through declared_kwargs, so a service receives only the ones its own
licence function declares.
prepare_drm passes drm_system so the choice follows the track, not the loaded CDM:
a track downloading at the same time can swap self.cdm.
"""
if drm_system is None:
drm_system = "playready" if is_playready_cdm(self.cdm) else "widevine"
if drm_system == "playready":
return service.get_playready_license(**kwargs)
return service.get_widevine_license(**kwargs)
fn = service.get_playready_license if drm_system == "playready" else service.get_widevine_license
return fn(**declared_kwargs(fn, kwargs))
def prepare_drm(
self,
@@ -4281,10 +4284,7 @@ class dl:
)
try:
if self.service == "NF":
drm.get_NF_content_keys(cdm=track_cdm, licence=licence, certificate=certificate)
else:
drm.get_content_keys(cdm=track_cdm, licence=licence, certificate=certificate)
drm.get_content_keys(cdm=track_cdm, licence=licence, certificate=certificate)
except Exception as e:
if drm.content_keys:
self.log.debug(f"License call failed but keys already in content_keys: {e}")
+17 -4
View File
@@ -27,6 +27,7 @@ from unshackle.core.proxies.resolve import initialize_proxy_providers, resolve_p
from unshackle.core.services import Services
from unshackle.core.titles import Episode, Movie, Song, Title_T
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
from unshackle.core.utilities import declared_kwargs
from unshackle.core.utils.collections import ci_get
from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_text
@@ -3678,7 +3679,9 @@ def handle_single_server_cdm(
pr_drm.get_content_keys(
cdm=cdm,
certificate=lambda challenge, **_: None,
licence=lambda challenge, **_: service.get_playready_license(challenge=challenge, title=title, track=track),
licence=lambda **kw: service.get_playready_license(
**declared_kwargs(service.get_playready_license, {**kw, "title": title, "track": track})
),
)
keys = {kid.hex: key for kid, key in pr_drm.content_keys.items()}
elif drm_type == "widevine":
@@ -3705,7 +3708,9 @@ def handle_single_server_cdm(
certificate=lambda challenge, **_: service.get_widevine_service_certificate(
challenge=challenge, title=title, track=track
),
licence=lambda challenge, **_: service.get_widevine_license(challenge=challenge, title=title, track=track),
licence=lambda **kw: service.get_widevine_license(
**declared_kwargs(service.get_widevine_license, {**kw, "title": title, "track": track})
),
)
keys = {kid.hex: key for kid, key in wv_drm.content_keys.items()}
else:
@@ -3736,9 +3741,17 @@ def handle_proxy_license(
challenge_bytes = base64.b64decode(challenge_b64)
if drm_type == "widevine":
license_response = service.get_widevine_license(challenge=challenge_bytes, title=title, track=track)
license_response = service.get_widevine_license(
**declared_kwargs(
service.get_widevine_license, {"challenge": challenge_bytes, "title": title, "track": track}
)
)
elif drm_type == "playready":
license_response = service.get_playready_license(challenge=challenge_bytes, title=title, track=track)
license_response = service.get_playready_license(
**declared_kwargs(
service.get_playready_license, {"challenge": challenge_bytes, "title": title, "track": track}
)
)
else:
raise APIError(
APIErrorCode.INVALID_PARAMETERS,
+5 -47
View File
@@ -220,6 +220,10 @@ class Widevine:
if hasattr(cdm, "has_cached_keys") and cdm.has_cached_keys(session_id):
pass
elif not challenge:
raise Widevine.Exceptions.EmptyLicense(
"The CDM returned an empty licence challenge and has no cached keys"
)
else:
log_event(
"drm_license_request",
@@ -231,7 +235,7 @@ class Widevine:
kid_count=len(self.kids),
)
try:
license_res = licence(challenge=challenge, pssh=self.pssh)
license_res = licence(challenge=challenge, pssh=self.pssh, session_id=session_id)
except TypeError:
license_res = licence(challenge=challenge)
cdm.parse_license(session_id, license_res)
@@ -265,52 +269,6 @@ class Widevine:
finally:
cdm.close(session_id)
def get_NF_content_keys(self, cdm: WidevineCdm, certificate: Callable, licence: Callable) -> None:
"""
Make a CDM Session and get Content Keys for this DRM Instance.
The certificate and license params are functions. unshackle gives them
the challenge and the session ID.
"""
for kid in self.kids:
if kid in self.content_keys:
continue
session_id = cdm.open()
try:
cert = certificate(challenge=cdm.service_certificate_challenge)
if cert and hasattr(cdm, "set_service_certificate"):
cdm.set_service_certificate(session_id, cert)
if hasattr(cdm, "set_required_kids"):
try:
cdm.set_required_kids(self.kids, session_id=session_id)
except TypeError: # CDM predating the per-session signature
cdm.set_required_kids(self.kids)
challenge = cdm.get_license_challenge(session_id, self.pssh)
if hasattr(cdm, "has_cached_keys") and cdm.has_cached_keys(session_id):
pass
elif not challenge:
raise Widevine.Exceptions.EmptyLicense(
"The CDM returned an empty license challenge and has no cached keys"
)
else:
cdm.parse_license(
session_id,
licence(session_id=session_id, challenge=challenge),
)
self.content_keys = {key.kid: key.key.hex() for key in cdm.get_keys(session_id, "CONTENT")}
if not self.content_keys:
raise Widevine.Exceptions.EmptyLicense("No Content Keys were within the License")
if kid not in self.content_keys:
raise Widevine.Exceptions.CEKNotFound(f"No Content Key for KID {kid.hex} within the License")
finally:
cdm.close(session_id)
def decrypt(self, path: Path) -> None:
"""
Decrypt a Track with Widevine DRM.
+6 -2
View File
@@ -38,6 +38,7 @@ from unshackle.core.title_cacher import TitleCacher, get_account_hash, get_regio
from unshackle.core.titles import Title_T, Titles_T, remap_titles
from unshackle.core.tracks import Chapters, Tracks
from unshackle.core.tracks.video import Video
from unshackle.core.utilities import declared_kwargs
from unshackle.core.utils.ip_info import get_ip_info
from unshackle.core.utils.redact import mask_proxy
@@ -512,8 +513,11 @@ class Service(metaclass=ABCMeta):
:return: The License response as Bytes or a Base64 string. Do not Base64 Encode or
Decode the data, return as is to reduce unnecessary computations.
"""
# Delegates license handling to the Widevine license method by default if a service-specific PlayReady implementation is not provided.
return self.get_widevine_license(challenge=challenge, title=title, track=track)
# A service that implements Widevine licensing only still gets PlayReady, with the
# arguments its own signature declares.
return self.get_widevine_license(
**declared_kwargs(self.get_widevine_license, {"challenge": challenge, "title": title, "track": track})
)
def get_clearkey_license(
self, *, challenge: bytes, title: Title_T, track: AnyTrack
+19 -1
View File
@@ -2,6 +2,7 @@ import ast
import contextlib
import gzip
import importlib.util
import inspect
import json
import logging
import os
@@ -16,7 +17,7 @@ from collections import defaultdict
from datetime import datetime, timezone
from pathlib import Path
from types import ModuleType
from typing import Any, Optional, Sequence, Union
from typing import Any, Callable, Optional, Sequence, Union
from urllib.parse import ParseResult, urlparse
from uuid import uuid4
@@ -1254,6 +1255,23 @@ def close_debug_logger():
debug_logger = None
def declared_kwargs(fn: Callable[..., Any], kwargs: dict[str, Any]) -> dict[str, Any]:
"""Keep only the arguments ``fn`` declares, so an extra one never raises TypeError.
A service licence function that never asked for ``pssh`` or ``session_id`` must not fail
on them. Filter only against a signature this function can read and call by keyword.
Anything else, such as the licence function of a compiled service, gets every argument,
and the caller handles the TypeError.
"""
try:
params = inspect.signature(fn).parameters
except (TypeError, ValueError):
return kwargs
if "challenge" not in params or any(p.kind is p.VAR_KEYWORD for p in params.values()):
return kwargs
return {k: v for k, v in kwargs.items() if k in params}
__all__ = (
"DebugLogger",
"get_debug_logger",