refactor(cdm): read a cdm entry for device and DRM system in one module

This commit is contained in:
imSp4rky
2026-11-24 19:25:26 -07:00
parent 2dfed221d5
commit 1be56b15b3
6 changed files with 450 additions and 93 deletions
+350
View File
@@ -0,0 +1,350 @@
"""Characterisation table: the device and DRM system each CDM ladder gives for one ``cdm`` config entry.
Device names start with the system they are for: ``wv_`` is Widevine, ``pr_`` is PlayReady. A stub is ``stub:wv`` or
``stub:pr``. Each answer tuple runs over the named systems of its column.
"""
from types import SimpleNamespace
from typing import Any, Callable, Optional
import pytest
import unshackle.core.cdm as cdm_mod
from unshackle.commands.dl import dl
from unshackle.core.api import handlers
from unshackle.core.cdm.choice import choose_cdm, drm_system
from unshackle.core.cdm.detect import is_playready_cdm
pytestmark = pytest.mark.unit
LOCAL = (None, "widevine", "playready", "pr")
SERVER = ("widevine", "playready", "wv")
TIER = {"devices": ["wv_tier"], "playready_devices": ["pr_tier"]}
DUAL = {"widevine": "wv_dev", "playready": "pr_dev"}
ROWS: dict[str, tuple[dict, Optional[str], Optional[dict]]] = {
"string widevine": ({"EXAMPLE": "wv_dev"}, None, None),
"string playready": ({"EXAMPLE": "pr_dev"}, None, None),
"profile mapping, no profile": ({"EXAMPLE": {"alice": "pr_alice", "default": "wv_dev"}}, None, None),
# drift, not changed: the licence and stub answers ignore the profile that the load answer follows
"profile mapping, named profile": ({"EXAMPLE": {"alice": "pr_alice", "default": "wv_dev"}}, "alice", None),
# drift, not changed: the stub takes the first value of the entry, the load and licence answers cdm.default
"profile mapping, other profile, cdm.default": (
{"EXAMPLE": {"alice": "pr_alice"}, "default": "wv_def"},
"bob",
None,
),
# drift, not changed: a playready client gets a widevine stub here, but a playready stub for a widevine string
"widevine only": ({"EXAMPLE": {"widevine": "wv_dev"}}, None, None),
"playready only": ({"EXAMPLE": {"playready": "pr_dev"}}, None, None),
"dual, widevine first": ({"EXAMPLE": DUAL}, None, None),
"dual, playready first": ({"EXAMPLE": {"playready": "pr_dev", "widevine": "wv_dev"}}, None, None),
"dual, keys in mixed case": ({"example": {"PlayReady": "pr_dev", "Widevine": "wv_dev"}}, None, None),
# drift, not changed: two keys settle no system, but with one device the entry does not follow the client
"dual, playready empty": ({"EXAMPLE": {"widevine": "wv_dev", "playready": None}}, None, None),
"dual, playready first and empty": ({"EXAMPLE": {"playready": None, "widevine": "wv_dev"}}, None, None),
# drift, not changed: dl has no playready device here, the licence answer takes the entry's default
"widevine and a default device": ({"EXAMPLE": {"widevine": "wv_dev", "default": "pr_dev"}}, None, None),
"default entry string": ({"default": "pr_def"}, None, None),
"default entry dual": ({"default": {"widevine": "wv_def", "playready": "pr_def"}}, None, None),
# drift, not changed: the short form "pr" reaches the stub unread and gives a widevine stub
"default entry widevine only": ({"default": {"widevine": "wv_def"}}, None, None),
# drift, not changed: as above, the stub reads the first tier
"quality tiers, cdm.default": (
{"EXAMPLE": {"<=1080": "wv_tier1", ">1080": "wv_tier2"}, "default": "pr_def"},
None,
None,
),
"quality tiers, no default": ({"EXAMPLE": {"<=1080": "wv_tier1", ">1080": "pr_tier2"}}, None, None),
# drift, not changed: a config key that is not a string crashes every ladder
"quality key read as a number": ({"EXAMPLE": {1080: "wv_dev", "default": "pr_dev"}}, None, None),
"missing entry": ({"OTHER": "pr_other"}, None, None),
"per-key view replaces the entry": ({"EXAMPLE": DUAL, "OTHER": "wv_other"}, None, {"EXAMPLE": "pr_key"}),
"per-key view, other service": ({"EXAMPLE": "wv_dev", "OTHER": "wv_other"}, None, {"OTHER": "pr_key"}),
"per-key view, dual": ({"EXAMPLE": "wv_dev"}, None, {"EXAMPLE": DUAL}),
}
@pytest.fixture
def devices(monkeypatch: pytest.MonkeyPatch) -> None:
"""A device loads as its own name, and its name says its DRM system in place of a device file."""
monkeypatch.setitem(cdm_mod.__dict__, "load_cdm", lambda name, **_: name)
monkeypatch.setattr(
handlers, "detect_cdm_type", lambda name, _: {"wv": "widevine", "pr": "playready"}.get(name[:2])
)
def shown(value: Any) -> Any:
"""A loaded device as its name, a stub as its system, an error as its class name."""
if value is None or isinstance(value, (str, bool, list)):
return value
return "stub:pr" if is_playready_cdm(value) else "stub:wv"
def attempt(answer: Callable[[], Any]) -> Any:
"""What ``answer`` gives, with an error shown as its class name."""
try:
return shown(answer())
except Exception as error:
return type(error).__name__
def each(systems: tuple, answer: Callable[[Any], Any]) -> tuple:
"""``answer`` for each named system."""
return tuple(attempt(lambda: answer(system)) for system in systems)
def answers(monkeypatch: pytest.MonkeyPatch, cdm: dict, profile: Optional[str], key_cdm: Optional[dict]) -> dict:
"""What every ladder answers for one config row."""
monkeypatch.setattr(handlers.config, "cdm", cdm, raising=False)
user = {**TIER, **({"cdm": key_cdm} if key_cdm else {})}
view = handlers.key_cdm_config(user)
cmd = dl.__new__(dl)
cmd.vaults = None
track = SimpleNamespace(drm_preference=None)
return {
"dl": each(LOCAL, lambda s: cmd.get_cdm("EXAMPLE", profile, drm=s)),
"load": each(LOCAL, lambda s: handlers.load_full_cdm("EXAMPLE", profile, s, view)),
"stub": each(LOCAL, lambda s: handlers.resolve_server_cdm("EXAMPLE", profile, s, view)),
"device": each(SERVER, lambda s: handlers.resolve_device_name(user, s, "EXAMPLE")),
"settled": attempt(lambda: handlers.detect_cdm_type_for_service("EXAMPLE", view)),
"both": attempt(lambda: choose_cdm(view.cdm, "EXAMPLE").both),
"candidates": each(SERVER, lambda s: handlers.server_drm_candidates("EXAMPLE", user, s, track)),
}
EXPECTED: dict[str, dict[str, Any]] = {
"string widevine": {
"dl": ("wv_dev", "wv_dev", "wv_dev", "wv_dev"),
"load": ("wv_dev", "wv_dev", "stub:pr", "stub:pr"),
"stub": ("stub:wv", "stub:wv", "stub:wv", "stub:wv"),
"device": ("wv_dev", "wv_dev", "wv_dev"),
"settled": "widevine",
"both": False,
"candidates": (["widevine"], ["widevine"], ["widevine"]),
},
"string playready": {
"dl": ("pr_dev", "pr_dev", "pr_dev", "pr_dev"),
"load": ("pr_dev", "stub:wv", "pr_dev", "pr_dev"),
"stub": ("stub:pr", "stub:pr", "stub:pr", "stub:pr"),
"device": ("pr_dev", "pr_dev", "pr_dev"),
"settled": "playready",
"both": False,
"candidates": (["playready"], ["playready"], ["playready"]),
},
"profile mapping, no profile": {
"dl": ("wv_dev", "wv_dev", "wv_dev", "wv_dev"),
"load": ("wv_dev", "wv_dev", "stub:pr", "stub:pr"),
"stub": ("stub:wv", "stub:wv", "stub:wv", "stub:wv"),
"device": ("wv_dev", "wv_dev", "wv_dev"),
"settled": "widevine",
"both": False,
"candidates": (["widevine"], ["widevine"], ["widevine"]),
},
"profile mapping, named profile": {
"dl": ("pr_alice", "pr_alice", "pr_alice", "pr_alice"),
"load": ("pr_alice", "stub:wv", "pr_alice", "pr_alice"),
"stub": ("stub:wv", "stub:wv", "stub:wv", "stub:wv"),
"device": ("wv_dev", "wv_dev", "wv_dev"),
"settled": "widevine",
"both": False,
"candidates": (["widevine"], ["widevine"], ["widevine"]),
},
"profile mapping, other profile, cdm.default": {
"dl": ("wv_def", "wv_def", "wv_def", "wv_def"),
"load": ("wv_def", "wv_def", "stub:pr", "stub:pr"),
"stub": ("stub:pr", "stub:pr", "stub:pr", "stub:pr"),
"device": ("wv_def", "wv_def", "wv_def"),
"settled": "widevine",
"both": False,
"candidates": (["widevine"], ["widevine"], ["widevine"]),
},
"widevine only": {
"dl": ("wv_dev", "wv_dev", None, None),
"load": ("wv_dev", "wv_dev", "stub:wv", "stub:wv"),
"stub": ("stub:wv", "stub:wv", "stub:wv", "stub:wv"),
"device": ("wv_dev", "pr_tier", "wv_tier"),
"settled": "widevine",
"both": False,
"candidates": (["widevine", "playready"], ["widevine", "playready"], ["widevine", "playready"]),
},
"playready only": {
"dl": ("pr_dev", "pr_dev", "pr_dev", "pr_dev"),
"load": ("pr_dev", "stub:wv", "pr_dev", "pr_dev"),
"stub": ("stub:pr", "stub:pr", "stub:pr", "stub:pr"),
"device": ("wv_tier", "pr_dev", "wv_tier"),
"settled": "playready",
"both": False,
"candidates": (["playready", "widevine"], ["playready", "widevine"], ["playready", "widevine"]),
},
"dual, widevine first": {
"dl": ("wv_dev", "wv_dev", "pr_dev", "pr_dev"),
"load": ("wv_dev", "wv_dev", "pr_dev", "pr_dev"),
"stub": ("stub:wv", "stub:wv", "stub:wv", "stub:wv"),
"device": ("wv_dev", "pr_dev", "wv_tier"),
"settled": None,
"both": True,
"candidates": (["widevine", "playready"], ["playready", "widevine"], ["widevine", "playready"]),
},
"dual, playready first": {
"dl": ("pr_dev", "wv_dev", "pr_dev", "pr_dev"),
"load": ("pr_dev", "wv_dev", "pr_dev", "pr_dev"),
"stub": ("stub:pr", "stub:pr", "stub:pr", "stub:pr"),
"device": ("wv_dev", "pr_dev", "wv_tier"),
"settled": None,
"both": True,
"candidates": (["widevine", "playready"], ["playready", "widevine"], ["widevine", "playready"]),
},
"dual, keys in mixed case": {
"dl": ("pr_dev", "wv_dev", "pr_dev", "pr_dev"),
"load": ("pr_dev", "wv_dev", "pr_dev", "pr_dev"),
"stub": ("stub:pr", "stub:pr", "stub:pr", "stub:pr"),
"device": ("wv_dev", "pr_dev", "wv_tier"),
"settled": None,
"both": True,
"candidates": (["widevine", "playready"], ["playready", "widevine"], ["widevine", "playready"]),
},
"dual, playready empty": {
"dl": ("wv_dev", "wv_dev", None, None),
"load": ("wv_dev", "wv_dev", "stub:wv", "stub:wv"),
"stub": ("stub:wv", "stub:wv", "stub:wv", "stub:wv"),
"device": ("wv_dev", "pr_tier", "wv_tier"),
"settled": None,
"both": False,
"candidates": (["widevine", "playready"], ["playready", "widevine"], ["widevine", "playready"]),
},
"dual, playready first and empty": {
"dl": (None, "wv_dev", None, None),
"load": ("stub:wv", "wv_dev", "stub:wv", "stub:wv"),
"stub": ("stub:wv", "stub:wv", "stub:wv", "stub:wv"),
"device": ("wv_dev", "pr_tier", "wv_tier"),
"settled": None,
"both": False,
"candidates": (["widevine", "playready"], ["playready", "widevine"], ["widevine", "playready"]),
},
"widevine and a default device": {
"dl": ("wv_dev", "wv_dev", None, None),
"load": ("wv_dev", "wv_dev", "stub:wv", "stub:wv"),
"stub": ("stub:wv", "stub:wv", "stub:wv", "stub:wv"),
"device": ("wv_dev", "pr_dev", "pr_dev"),
"settled": "widevine",
"both": False,
"candidates": (["widevine", "playready"], ["widevine", "playready"], ["widevine", "playready"]),
},
"default entry string": {
"dl": ("pr_def", "pr_def", "pr_def", "pr_def"),
"load": ("pr_def", "stub:wv", "pr_def", "pr_def"),
"stub": (None, "stub:wv", "stub:pr", "stub:wv"),
"device": ("wv_tier", "pr_tier", "wv_tier"),
"settled": None,
"both": False,
"candidates": (["widevine", "playready"], ["playready", "widevine"], ["widevine", "playready"]),
},
"default entry dual": {
"dl": ("wv_def", "wv_def", "pr_def", "pr_def"),
"load": ("wv_def", "wv_def", "pr_def", "pr_def"),
"stub": (None, "stub:wv", "stub:pr", "stub:wv"),
"device": ("wv_tier", "pr_tier", "wv_tier"),
"settled": None,
"both": True,
"candidates": (["widevine", "playready"], ["playready", "widevine"], ["widevine", "playready"]),
},
"default entry widevine only": {
"dl": ("wv_def", "wv_def", None, None),
"load": ("wv_def", "wv_def", "stub:pr", "stub:wv"),
"stub": (None, "stub:wv", "stub:pr", "stub:wv"),
"device": ("wv_tier", "pr_tier", "wv_tier"),
"settled": None,
"both": False,
"candidates": (["widevine", "playready"], ["playready", "widevine"], ["widevine", "playready"]),
},
"quality tiers, cdm.default": {
"dl": ("pr_def", "pr_def", "pr_def", "pr_def"),
"load": ("pr_def", "stub:wv", "pr_def", "pr_def"),
"stub": ("stub:wv", "stub:wv", "stub:wv", "stub:wv"),
"device": ("pr_def", "pr_def", "pr_def"),
"settled": "playready",
"both": False,
"candidates": (["playready"], ["playready"], ["playready"]),
},
"quality tiers, no default": {
"dl": (None, None, None, None),
"load": ("stub:wv", "stub:wv", "stub:wv", "stub:wv"),
"stub": ("stub:wv", "stub:wv", "stub:wv", "stub:wv"),
"device": ("wv_tier", "pr_tier", "wv_tier"),
"settled": None,
"both": False,
"candidates": (["widevine", "playready"], ["playready", "widevine"], ["widevine", "playready"]),
},
"quality key read as a number": {
"dl": ("AttributeError", "AttributeError", "AttributeError", "AttributeError"),
"load": ("AttributeError", "AttributeError", "AttributeError", "AttributeError"),
"stub": ("AttributeError", "AttributeError", "AttributeError", "AttributeError"),
"device": ("AttributeError", "AttributeError", "AttributeError"),
"settled": "AttributeError",
"both": "AttributeError",
"candidates": ("AttributeError", "AttributeError", "AttributeError"),
},
"missing entry": {
"dl": (None, None, None, None),
"load": (None, "stub:wv", "stub:pr", "stub:wv"),
"stub": (None, "stub:wv", "stub:pr", "stub:wv"),
"device": ("wv_tier", "pr_tier", "wv_tier"),
"settled": None,
"both": False,
"candidates": (["widevine", "playready"], ["playready", "widevine"], ["widevine", "playready"]),
},
"per-key view replaces the entry": {
"dl": ("wv_dev", "wv_dev", "pr_dev", "pr_dev"),
"load": ("pr_key", "stub:wv", "pr_key", "pr_key"),
"stub": ("stub:pr", "stub:pr", "stub:pr", "stub:pr"),
"device": ("pr_key", "pr_key", "pr_key"),
"settled": "playready",
"both": False,
"candidates": (["playready"], ["playready"], ["playready"]),
},
"per-key view, other service": {
"dl": ("wv_dev", "wv_dev", "wv_dev", "wv_dev"),
"load": ("wv_dev", "wv_dev", "stub:pr", "stub:pr"),
"stub": ("stub:wv", "stub:wv", "stub:wv", "stub:wv"),
"device": ("wv_dev", "wv_dev", "wv_dev"),
"settled": "widevine",
"both": False,
"candidates": (["widevine"], ["widevine"], ["widevine"]),
},
"per-key view, dual": {
"dl": ("wv_dev", "wv_dev", "wv_dev", "wv_dev"),
"load": ("wv_dev", "wv_dev", "pr_dev", "pr_dev"),
"stub": ("stub:wv", "stub:wv", "stub:wv", "stub:wv"),
"device": ("wv_dev", "pr_dev", "wv_tier"),
"settled": None,
"both": True,
"candidates": (["widevine", "playready"], ["playready", "widevine"], ["widevine", "playready"]),
},
}
def test_every_row_has_a_pinned_answer() -> None:
assert ROWS.keys() == EXPECTED.keys()
@pytest.mark.parametrize("name", ROWS)
def test_each_ladder_gives_the_pinned_choice(monkeypatch: pytest.MonkeyPatch, devices: None, name: str) -> None:
cdm, profile, key_cdm = ROWS[name]
assert answers(monkeypatch, cdm, profile, key_cdm) == EXPECTED[name]
@pytest.mark.parametrize(
("name", "system"),
[("wv", "widevine"), ("PlayReady", "playready"), ("PR", "playready"), ("clearkey", None), (5, None), (None, None)],
)
def test_drm_system_reads_each_name_of_a_system(name: Any, system: Optional[str]) -> None:
assert drm_system(name) == system
@pytest.mark.parametrize(
("entry", "system"),
[({"widevine": "wv_dev"}, "widevine"), (DUAL, None), ({"default": "pr_dev"}, None), ("pr_dev", None)],
)
def test_the_entry_settles_a_system_only_when_it_names_one(entry: Any, system: Optional[str]) -> None:
assert choose_cdm({"EXAMPLE": entry}, "EXAMPLE").system == system
+1 -1
View File
@@ -26,7 +26,7 @@ def server(monkeypatch, tmp_path):
def test_a_key_entry_replaces_the_whole_server_entry(server): def test_a_key_entry_replaces_the_whole_server_entry(server):
user = {"cdm": {"example": "own_pr"}} user = {"cdm": {"example": "own_pr"}}
assert handlers.key_cdm_config(user).cdm == {"OTHER": "x", "example": "own_pr"} assert handlers.key_cdm_config(user).cdm == {"OTHER": "x", "example": "own_pr"}
assert handlers.configured_cdm_name("EXAMPLE", "widevine", handlers.key_cdm_config(user)) == "own_pr" assert handlers.resolve_device_name(user, "widevine", "EXAMPLE") == "own_pr"
assert handlers.key_cdm_config({}) is config assert handlers.key_cdm_config({}) is config
@@ -22,6 +22,7 @@ import unshackle.core.cdm.detect as detect_mod
import unshackle.core.drm as drm_mod import unshackle.core.drm as drm_mod
from unshackle.core.api import handlers from unshackle.core.api import handlers
from unshackle.core.api.errors import APIError from unshackle.core.api.errors import APIError
from unshackle.core.cdm.choice import choose_cdm
pytestmark = pytest.mark.unit pytestmark = pytest.mark.unit
@@ -118,8 +119,7 @@ async def _license(monkeypatch, track, body):
async def test_server_type_wins_over_client_request(env, monkeypatch): async def test_server_type_wins_over_client_request(env, monkeypatch):
monkeypatch.setattr(handlers, "detect_cdm_type_for_service", lambda tag, cfg: "widevine") monkeypatch.setattr(handlers.config, "cdm", {"EXAMPLE": "wv_dev"}, raising=False)
monkeypatch.setattr(handlers, "resolve_device_name", lambda *a, **k: "wv_dev")
monkeypatch.setattr(handlers, "require_track_pssh", lambda track, pssh, drm_type: None) monkeypatch.setattr(handlers, "require_track_pssh", lambda track, pssh, drm_type: None)
track = SimpleNamespace(id="vid", drm=[_pr_drm(), _wv_drm()]) track = SimpleNamespace(id="vid", drm=[_pr_drm(), _wv_drm()])
@@ -132,8 +132,7 @@ async def test_server_type_wins_over_client_request(env, monkeypatch):
async def test_playready_only_track_licenses_with_widevine_server(env, monkeypatch): async def test_playready_only_track_licenses_with_widevine_server(env, monkeypatch):
"""The batch route licenses a PlayReady-only header with the Widevine device; so must this one.""" """The batch route licenses a PlayReady-only header with the Widevine device; so must this one."""
monkeypatch.setattr(handlers, "detect_cdm_type_for_service", lambda tag, cfg: "widevine") monkeypatch.setattr(handlers.config, "cdm", {"EXAMPLE": "wv_dev"}, raising=False)
monkeypatch.setattr(handlers, "resolve_device_name", lambda *a, **k: "wv_dev")
track = SimpleNamespace(id="vid", drm=[_pr_drm()]) track = SimpleNamespace(id="vid", drm=[_pr_drm()])
body = await _license(monkeypatch, track, {"drm_type": "playready"}) body = await _license(monkeypatch, track, {"drm_type": "playready"})
@@ -302,9 +301,9 @@ def test_the_tracks_response_names_the_system_of_the_loaded_device(monkeypatch,
({"EXAMPLE1": "wv_device"}, False), ({"EXAMPLE1": "wv_device"}, False),
], ],
) )
def test_lists_both_systems_needs_a_device_for_each(monkeypatch, mapping, both): def test_both_systems_need_a_device_each(monkeypatch, mapping, both):
monkeypatch.setattr(handlers.config, "cdm", mapping, raising=False) monkeypatch.setattr(handlers.config, "cdm", mapping, raising=False)
assert handlers.lists_both_systems("EXAMPLE1", handlers.config) is both assert choose_cdm(handlers.config.cdm, "EXAMPLE1").both is both
@pytest.mark.parametrize("cdm_type", [5, ["playready"], {"a": 1}]) @pytest.mark.parametrize("cdm_type", [5, ["playready"], {"a": 1}])
+2 -14
View File
@@ -38,6 +38,7 @@ from rich.table import Table
from unshackle.core import __version__, binaries, providers from unshackle.core import __version__, binaries, providers
from unshackle.core.cdm import DecryptLabsRemoteCDM from unshackle.core.cdm import DecryptLabsRemoteCDM
from unshackle.core.cdm.choice import choose_cdm
from unshackle.core.cdm.detect import cdm_type_stub, is_playready_cdm, is_remote_cdm, is_widevine_cdm from unshackle.core.cdm.detect import cdm_type_stub, is_playready_cdm, is_remote_cdm, is_widevine_cdm
from unshackle.core.config import cdm_entry_names_device, config, load_yaml, resolve_cdm_name, resolve_decryption from unshackle.core.config import cdm_entry_names_device, config, load_yaml, resolve_cdm_name, resolve_decryption
from unshackle.core.console import GradientPulseBarColumn, SyncLive, console, listing_panel, print_listing from unshackle.core.console import GradientPulseBarColumn, SyncLive, console, listing_panel, print_listing
@@ -4173,20 +4174,7 @@ class dl:
cdm_name = quality_match cdm_name = quality_match
if isinstance(cdm_name, dict): if isinstance(cdm_name, dict):
lower_keys = {k.lower(): v for k, v in cdm_name.items()} cdm_name = choose_cdm(config.cdm, service, profile, drm, entry=cdm_name).device
if {"widevine", "playready"} & lower_keys.keys():
drm_key = None
if drm:
drm_key = {
"wv": "widevine",
"widevine": "widevine",
"pr": "playready",
"playready": "playready",
}.get(drm.lower())
first = next(key for key in lower_keys if key in ("widevine", "playready"))
cdm_name = lower_keys.get(drm_key or first) or lower_keys.get("playready")
else:
cdm_name = cdm_name.get(profile) or cdm_name.get("default") or ci_get(config.cdm, "default")
if not cdm_name: if not cdm_name:
return None return None
+20 -72
View File
@@ -33,6 +33,7 @@ from unshackle.core.api.session_log import SessionLogBuffer, SessionLogMirror, c
from unshackle.core.api.session_store import SessionStore from unshackle.core.api.session_store import SessionStore
from unshackle.core.binaries import binary_version from unshackle.core.binaries import binary_version
from unshackle.core.cacher import Cacher from unshackle.core.cacher import Cacher
from unshackle.core.cdm.choice import choose_cdm, drm_system
from unshackle.core.cdm.detect import cdm_type_stub, is_playready_cdm from unshackle.core.cdm.detect import cdm_type_stub, is_playready_cdm
from unshackle.core.config import config, load_yaml from unshackle.core.config import config, load_yaml
from unshackle.core.constants import AnyTrack from unshackle.core.constants import AnyTrack
@@ -123,8 +124,8 @@ def load_full_cdm(
Services often touch ``ctx.obj.cdm.security_level`` / ``.device_type`` / ``.system_id`` Services often touch ``ctx.obj.cdm.security_level`` / ``.device_type`` / ``.system_id``
inside ``__init__``, so the lightweight ``resolve_server_cdm`` stub is not enough inside ``__init__``, so the lightweight ``resolve_server_cdm`` stub is not enough
for list_titles / list_tracks / search. Mirrors ``dl.get_cdm`` selection logic but for list_titles / list_tracks / search. :func:`choose_cdm` picks the device as for
skips the quality-tier shortcuts (no track context yet) and falls back to the stub ``dl.get_cdm``, without the quality tiers (no track context yet). It falls back to the stub
if the configuration has no device, or if loading fails. ``app_config`` is an API key's if the configuration has no device, or if loading fails. ``app_config`` is an API key's
view from :func:`key_cdm_config`; None reads the server's own ``cdm``. view from :func:`key_cdm_config`; None reads the server's own ``cdm``.
""" """
@@ -133,29 +134,14 @@ def load_full_cdm(
app_config = app_config or config app_config = app_config or config
if not isinstance(cdm_type, str): if not isinstance(cdm_type, str):
cdm_type = None cdm_type = None
cdm_name = ci_get(app_config.cdm, service) or ci_get(app_config.cdm, "default") cdm_name = choose_cdm(app_config.cdm, service, profile, cdm_type).name
if isinstance(cdm_name, dict):
lower_keys = {k.lower(): v for k, v in cdm_name.items()}
if {"widevine", "playready"} & lower_keys.keys():
drm_key = None
if cdm_type:
drm_key = {"wv": "widevine", "widevine": "widevine", "pr": "playready", "playready": "playready"}.get(
cdm_type.lower()
)
first = next(key for key in lower_keys if key in ("widevine", "playready"))
cdm_name = lower_keys.get(drm_key or first) or lower_keys.get("playready")
else:
cdm_name = cdm_name.get(profile) or cdm_name.get("default") or ci_get(app_config.cdm, "default")
if not cdm_name or not isinstance(cdm_name, str): if not cdm_name:
return resolve_server_cdm(service, profile, cdm_type, app_config) return resolve_server_cdm(service, profile, cdm_type, app_config)
if cdm_type: wanted = drm_system(cdm_type)
wanted = {"wv": "widevine", "widevine": "widevine", "pr": "playready", "playready": "playready"}.get( if wanted and detect_cdm_type(cdm_name, app_config) not in (None, wanted):
cdm_type.lower() return cdm_type_stub(wanted)
)
if wanted and detect_cdm_type(cdm_name, app_config) not in (None, wanted):
return cdm_type_stub(wanted)
try: try:
return load_cdm(cdm_name, service_name=service) return load_cdm(cdm_name, service_name=service)
@@ -3476,7 +3462,7 @@ def create_service_instance(
cdm = client_device_cdm(data, input_bridge, lend_server_device) cdm = client_device_cdm(data, input_bridge, lend_server_device)
else: else:
follows_client = not server_cdm or lists_both_systems(normalized_service, key_config) follows_client = not server_cdm or choose_cdm(key_config.cdm, normalized_service).both
cdm = load_full_cdm(normalized_service, profile, data.get("cdm_type") if follows_client else None, key_config) cdm = load_full_cdm(normalized_service, profile, data.get("cdm_type") if follows_client else None, key_config)
# Reconstruct enum track-selection params from client data so service code that reads # Reconstruct enum track-selection params from client data so service code that reads
@@ -3888,7 +3874,7 @@ async def session_tracks_handler(
service_tag = session.service_tag service_tag = session.service_tag
config_cdm_type = detect_cdm_type_for_service(service_tag, app_config) config_cdm_type = detect_cdm_type_for_service(service_tag, app_config)
if not config_cdm_type and session.server_cdm and lists_both_systems(service_tag, app_config): if not config_cdm_type and session.server_cdm and choose_cdm(app_config.cdm, service_tag).both:
loaded = getattr(getattr(getattr(service_instance, "ctx", None), "obj", None), "cdm", None) loaded = getattr(getattr(getattr(service_instance, "ctx", None), "obj", None), "cdm", None)
config_cdm_type = "playready" if is_playready_cdm(loaded) else "widevine" config_cdm_type = "playready" if is_playready_cdm(loaded) else "widevine"
@@ -4036,52 +4022,17 @@ def resolve_server_cdm(
has no server CDM for the service. has no server CDM for the service.
""" """
app_config = app_config or config app_config = app_config or config
cdm_name = ci_get(app_config.cdm, service) cdm_name = choose_cdm(app_config.cdm, service, view="stub").name
if cdm_name: if cdm_name:
if isinstance(cdm_name, dict): detected_type = detect_cdm_type(cdm_name, app_config)
lower_keys = {k.lower(): v for k, v in cdm_name.items()} if detected_type:
if {"widevine", "playready"} & lower_keys.keys(): return cdm_type_stub(detected_type)
systems = [lower_keys[key] for key in lower_keys if key in ("widevine", "playready")]
cdm_name = next(filter(None, systems), None)
else:
cdm_name = cdm_name.get("default") or next(iter(cdm_name.values()), None)
if cdm_name and isinstance(cdm_name, str):
detected_type = detect_cdm_type(cdm_name, app_config)
if detected_type:
return cdm_type_stub(detected_type)
if cdm_type: if cdm_type:
return cdm_type_stub(cdm_type) return cdm_type_stub(cdm_type)
return None return None
def configured_cdm_name(service: str, drm_type: str, app_config: Any) -> Optional[str]:
"""The device name config.cdm maps a service to for one DRM system; None when the tier decides.
A dict names a device per system (``widevine`` / ``playready`` keys) or a ``default``.
Any other dict shape, such as the quality tiers ``dl`` reads, falls through to the
global ``cdm.default``: the server has no track context to pick a tier with.
"""
cdm_name = ci_get(app_config.cdm, service) if service else None
if isinstance(cdm_name, dict):
lower_keys = {k.lower(): v for k, v in cdm_name.items()}
drm_key = drm_type if drm_type in ("widevine", "playready") else None
cdm_name = lower_keys.get(drm_key) or lower_keys.get("default") or ci_get(app_config.cdm, "default")
if cdm_name and isinstance(cdm_name, str):
return cdm_name
return None
def lists_both_systems(service: str, app_config: Any) -> bool:
"""True when config.cdm names a device for both Widevine and PlayReady for ``service``.
The server CDM then loads the device of the client's DRM system, so the manifest suits the client's vaults.
"""
entry = ci_get(app_config.cdm, service) or ci_get(app_config.cdm, "default")
return isinstance(entry, dict) and {"widevine", "playready"} <= {key.lower() for key, name in entry.items() if name}
def detect_cdm_type_for_service(service: str, app_config: Any) -> Optional[str]: def detect_cdm_type_for_service(service: str, app_config: Any) -> Optional[str]:
"""The DRM system config.cdm settles for a service; None when the mapping leaves it open. """The DRM system config.cdm settles for a service; None when the mapping leaves it open.
@@ -4089,14 +4040,11 @@ def detect_cdm_type_for_service(service: str, app_config: Any) -> Optional[str]:
device ``resolve_device_name`` returns for it, so the routes plan with the device they device ``resolve_device_name`` returns for it, so the routes plan with the device they
load. A mapping that names a device for both systems settles nothing. load. A mapping that names a device for both systems settles nothing.
""" """
cdm_name = ci_get(app_config.cdm, service) choice = choose_cdm(app_config.cdm, service, view="licence")
if isinstance(cdm_name, dict): if choice.systems:
named = [system for system in ("widevine", "playready") if system in {k.lower() for k in cdm_name}] return choice.system
if named: if choice.name:
return named[0] if len(named) == 1 else None return detect_cdm_type(choice.name, app_config)
device_name = configured_cdm_name(service, "widevine", app_config)
if device_name:
return detect_cdm_type(device_name, app_config)
return None return None
@@ -4524,7 +4472,7 @@ def resolve_device_name(user_config: dict, drm_type: str, service_tag: str = "")
1. the key's own ``cdm`` entry for the service, else ``config.cdm[service_tag]`` 1. the key's own ``cdm`` entry for the service, else ``config.cdm[service_tag]``
2. serve.users.{key}.devices / playready_devices (user device list) 2. serve.users.{key}.devices / playready_devices (user device list)
""" """
cdm_name = configured_cdm_name(service_tag, drm_type, key_cdm_config(user_config)) cdm_name = choose_cdm(key_cdm_config(user_config).cdm, service_tag, drm=drm_type, view="licence").name
if cdm_name: if cdm_name:
return cdm_name return cdm_name
+72
View File
@@ -0,0 +1,72 @@
"""Which device and DRM system a ``cdm`` config entry gives a service. Config in, answer out: nothing loads here."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Literal, Optional
from unshackle.core.utils.collections import ci_get
SYSTEMS = ("widevine", "playready")
SYSTEM_NAMES = {"wv": "widevine", "widevine": "widevine", "pr": "playready", "playready": "playready"}
def drm_system(name: Any) -> Optional[str]:
"""``widevine`` or ``playready`` for either name or its short form in any case; None for anything else."""
return SYSTEM_NAMES.get(name.lower()) if isinstance(name, str) else None
@dataclass(frozen=True)
class CdmChoice:
"""The device an entry gives, its DRM system config keys in order, and whether it names a device for both."""
device: Any
systems: tuple[str, ...]
both: bool
@property
def system(self) -> Optional[str]:
"""The DRM system the entry settles by its keys alone: the only one it names."""
return self.systems[0] if len(self.systems) == 1 else None
@property
def name(self) -> Optional[str]:
"""The device as a device name; None when the entry gives none or an inline mapping."""
return self.device if isinstance(self.device, str) and self.device else None
def choose_cdm(
cdm: dict[str, Any],
service: str,
profile: Optional[str] = None,
drm: Optional[str] = None,
*,
entry: Any = None,
view: Literal["load", "licence", "stub"] = "load",
) -> CdmChoice:
"""The choice the ``cdm`` mapping makes for ``service`` and the named ``drm`` system, else the first one it lists.
``licence`` and ``stub`` read no ``cdm.default`` for a service with no entry. ``licence`` never gives the
other system's device, only the entry's ``default``. ``stub`` ignores ``drm`` and the profile.
"""
if entry is None:
entry = ci_get(cdm, service) if service else None
if not entry and view == "load":
entry = ci_get(cdm, "default")
if not isinstance(entry, dict):
return CdmChoice(entry, (), False)
lower = {key.lower(): value for key, value in entry.items()}
systems = tuple(key for key in lower if key in SYSTEMS)
both = set(SYSTEMS) <= {key.lower() for key, value in entry.items() if value}
if view == "licence":
device = (lower.get(drm) if drm in SYSTEMS else None) or lower.get("default") or ci_get(cdm, "default")
elif view == "stub" and systems:
device = next(filter(None, (lower[system] for system in systems)), None)
elif view == "stub":
device = entry.get("default") or next(iter(entry.values()), None)
elif systems:
device = lower.get(drm_system(drm) or systems[0]) or lower.get("playready")
else:
device = entry.get(profile) or entry.get("default") or ci_get(cdm, "default")
return CdmChoice(device, systems, both)