diff --git a/tests/core/test_all_drm.py b/tests/core/test_all_drm.py index e11f0e01..78523661 100644 --- a/tests/core/test_all_drm.py +++ b/tests/core/test_all_drm.py @@ -330,7 +330,7 @@ def test_the_server_cdm_stub_is_the_first_drm_system_of_the_config_entry( ) -> None: monkeypatch.setattr("unshackle.core.config.config.cdm", {"EXAMPLE": entry}) monkeypatch.setattr( - "unshackle.core.api.handlers.detect_cdm_type", + "unshackle.core.api.handlers.device_system", lambda name, _: "playready" if name == "pr_device" else "widevine", ) diff --git a/tests/core/test_cdm_choice.py b/tests/core/test_cdm_choice.py index 76eab8fe..c9673fc7 100644 --- a/tests/core/test_cdm_choice.py +++ b/tests/core/test_cdm_choice.py @@ -69,9 +69,7 @@ ROWS: dict[str, tuple[dict, Optional[str], Optional[dict]]] = { 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]) - ) + monkeypatch.setattr(handlers, "device_system", lambda name, _: {"wv": "widevine", "pr": "playready"}.get(name[:2])) def shown(value: Any) -> Any: diff --git a/tests/core/test_cdm_detect.py b/tests/core/test_cdm_detect.py index 159f43f2..3212cc87 100644 --- a/tests/core/test_cdm_detect.py +++ b/tests/core/test_cdm_detect.py @@ -1,208 +1,124 @@ -"""CDM detection and load-time DRM stamping for local and remote CDMs. +"""The CDM catalogue: a device name's DRM system read from config, and what each built CDM object says it is. -Covers the predicates in ``unshackle.core.cdm.detect`` (playready/widevine, local/remote, -and the remote combinations) and the loader stamping that sets a remote CDM's DRM type at -load time instead of guessing it on each call. Services such as EXAMPLE choose a device -profile from that type, so a wrong classification here is what produces a licence denial -for the requested resolution. +The config peek, the loader and the CDM classes read one rule, so a device is the same system before +and after it loads. """ from __future__ import annotations -from pathlib import Path from types import SimpleNamespace import pytest -from unshackle.core.cdm import loader as loader_mod -from unshackle.core.cdm.detect import ( - cdm_location, - is_local_cdm, - is_playready_cdm, - is_remote_cdm, - is_remote_playready_cdm, - is_remote_widevine_cdm, - is_widevine_cdm, -) -from unshackle.core.cdm.loader import stamp_remote +from unshackle.commands.dl import cdm_summary +from unshackle.core.api import handlers +from unshackle.core.cdm.client_relay import ClientDeviceCdm +from unshackle.core.cdm.detect import cdm_system, cdm_type_stub, is_playready_cdm, is_remote_cdm, is_widevine_cdm +from unshackle.core.cdm.loader import device_system, load_cdm +from unshackle.core.config import config pytestmark = pytest.mark.unit -REPO = Path(__file__).resolve().parents[2] -PRD_DIR = REPO / "unshackle" / "PRDs" +ENTRIES = [ + ({"type": "decrypt_labs", "secret": "s", "device_name": "SL2"}, "playready"), + ({"type": "decrypt_labs", "secret": "s", "device_name": "ChromeCDM", "device_type": "PLAYREADY"}, "playready"), + ({"type": "decrypt_labs", "secret": "s", "device_name": "L1"}, "widevine"), + ({"type": "custom_api", "host": "http://h.invalid", "device": {"type": "PLAYREADY", "name": "pr"}}, "playready"), + ({"type": "custom_api", "host": "http://h.invalid", "device": {"name": "SL3000"}}, "playready"), + ({"type": "custom_api", "host": "http://h.invalid", "device": {"name": "ChromeCDM"}}, "widevine"), + ({"Device Type": "PLAYREADY", "host": "http://h.invalid", "secret": "s", "device_name": "d"}, "playready"), + ( + { + "device_type": "ANDROID", + "system_id": 1, + "security_level": 3, + "host": "http://h.invalid", + "secret": "s", + "device_name": "SLOT", + }, + "widevine", + ), +] -def test_stamped_remote_playready(): - cdm = SimpleNamespace(drm="playready", is_remote_cdm=True) - assert is_playready_cdm(cdm) - assert not is_widevine_cdm(cdm) +def app_config(tmp_path, entries=(), cdm=None): + """A config view with ``entries`` as its remote_cdm and ``tmp_path`` as both device folders.""" + folders = SimpleNamespace(prds=tmp_path / "prd", wvds=tmp_path / "wvd") + folders.prds.mkdir(exist_ok=True) + folders.wvds.mkdir(exist_ok=True) + return SimpleNamespace(remote_cdm=list(entries), directories=folders, cdm=cdm or {}) + + +@pytest.mark.parametrize(("entry", "system"), ENTRIES) +def test_config_and_the_built_cdm_agree(entry, system, tmp_path, monkeypatch): + entry = {"name": "x", **entry} + assert device_system("x", app_config(tmp_path, [entry])) == system + + monkeypatch.setattr(config, "remote_cdm", [entry]) + cdm = load_cdm("x", service_name="EXAMPLE") + assert cdm_system(cdm) == system assert is_remote_cdm(cdm) - assert is_remote_playready_cdm(cdm) - assert not is_remote_widevine_cdm(cdm) - assert cdm_location(cdm) == "remote" -def test_stamped_remote_widevine(): - cdm = SimpleNamespace(drm="widevine", is_remote_cdm=True) - assert is_widevine_cdm(cdm) - assert not is_playready_cdm(cdm) - assert is_remote_widevine_cdm(cdm) - assert not is_remote_playready_cdm(cdm) - assert cdm_location(cdm) == "remote" - - -def test_drm_stamp_beats_conflicting_is_playready_attr(): - # The stamped drm takes priority over the wrapper's own is_playready guess. - cdm = SimpleNamespace(drm="playready", is_playready=False, is_remote_cdm=True) - assert is_playready_cdm(cdm) - assert not is_widevine_cdm(cdm) - - -def test_drm_stamp_case_insensitive(): - cdm = SimpleNamespace(drm="PlayReady", is_remote_cdm=True) - assert is_playready_cdm(cdm) - - -def test_none_classifies_as_nothing(): - for fn in ( - is_playready_cdm, - is_widevine_cdm, - is_remote_cdm, - is_local_cdm, - is_remote_playready_cdm, - is_remote_widevine_cdm, - ): - assert fn(None) is False - assert cdm_location(None) == "unknown" - - -@pytest.mark.parametrize("device_name", ["SL2", "SL3", "SL2000", "SL3000", "sl3000"]) -def test_decryptlabs_sl_names_are_playready(device_name): - from unshackle.core.cdm.decrypt_labs_remote_cdm import DecryptLabsRemoteCDM - - cdm = DecryptLabsRemoteCDM(secret="x", device_name=device_name) - assert cdm.is_playready - assert is_playready_cdm(cdm) - assert is_remote_cdm(cdm) - assert is_remote_playready_cdm(cdm) - assert not is_local_cdm(cdm) - - -@pytest.mark.parametrize("device_name", ["ChromeCDM", "L1", "L2"]) -def test_decryptlabs_widevine_names(device_name): - from unshackle.core.cdm.decrypt_labs_remote_cdm import DecryptLabsRemoteCDM - - cdm = DecryptLabsRemoteCDM(secret="x", device_name=device_name) - assert not cdm.is_playready - assert is_widevine_cdm(cdm) - assert is_remote_widevine_cdm(cdm) - - -def test_decryptlabs_device_type_forces_playready(): - from unshackle.core.cdm.decrypt_labs_remote_cdm import DecryptLabsRemoteCDM - - cdm = DecryptLabsRemoteCDM(secret="x", device_name="ChromeCDM", device_type="PLAYREADY") - assert cdm.is_playready +def test_the_server_settles_a_service_on_its_remote_device_system(tmp_path): + entry = {"name": "x", "type": "decrypt_labs", "secret": "s", "device_name": "SL3000"} + assert ( + handlers.detect_cdm_type_for_service("EXAMPLE", app_config(tmp_path, [entry], {"EXAMPLE": "x"})) == "playready" + ) @pytest.mark.parametrize( - ("device", "expect_pr"), - [ - ({"name": "SL3000"}, True), - ({"name": "SL2"}, True), - ({"name": "ChromeCDM"}, False), - ({"type": "PLAYREADY", "name": "ChromeCDM"}, True), - ], + ("folder", "suffix", "system"), + [("prd", "prd", "playready"), ("wvd", "prd", "playready"), ("wvd", "wvd", "widevine")], ) -def test_custom_remote_cdm_classification(device, expect_pr): +def test_a_local_file_names_its_system(folder, suffix, system, tmp_path): + view = app_config(tmp_path) + (tmp_path / folder / f"x.{suffix}").write_bytes(b"") + assert device_system("x", view) == system + + +def test_an_unknown_name_is_no_device(tmp_path, monkeypatch): + view = app_config(tmp_path) + assert device_system("x", view) is None + monkeypatch.setattr(config, "remote_cdm", []) + monkeypatch.setattr(config, "directories", view.directories) + with pytest.raises(ValueError, match="does not exist"): + load_cdm("x") + + +def test_stand_ins_carry_their_system(): + assert cdm_system(cdm_type_stub("playready")) == "playready" + assert cdm_system(cdm_type_stub("None")) == "widevine" + assert cdm_system(ClientDeviceCdm(SimpleNamespace(), is_playready=True)) == "playready" + assert not is_remote_cdm(cdm_type_stub("widevine")) + + +def test_library_cdms_are_known_by_class(): + from pyplayready.cdm import Cdm as PlayReadyCdm + from pyplayready.remote.remotecdm import RemoteCdm as PlayReadyRemoteCdm + from pywidevine.cdm import Cdm as WidevineCdm + from pywidevine.remotecdm import RemoteCdm as WidevineRemoteCdm + + local_pr, remote_wv = object.__new__(PlayReadyCdm), object.__new__(WidevineRemoteCdm) + assert is_playready_cdm(local_pr) and not is_remote_cdm(local_pr) + assert is_widevine_cdm(object.__new__(WidevineCdm)) + assert is_widevine_cdm(remote_wv) and is_remote_cdm(remote_wv) + assert is_remote_cdm(object.__new__(PlayReadyRemoteCdm)) + + +@pytest.mark.parametrize("cdm", [None, object()]) +def test_no_cdm_is_neither_system(cdm): + assert cdm_system(cdm) is None + assert not is_playready_cdm(cdm) and not is_widevine_cdm(cdm) and not is_remote_cdm(cdm) + + +@pytest.mark.parametrize( + ("device", "drm_type"), [({"type": "PLAYREADY", "name": "pr"}, "PlayReady"), ({"name": "wv"}, "Widevine")] +) +def test_the_load_log_names_a_custom_remote_cdm_by_its_system(device, drm_type): from unshackle.core.cdm.custom_remote_cdm import CustomRemoteCDM - cdm = CustomRemoteCDM(host="http://example.invalid", device=device) - assert cdm.is_playready is expect_pr - assert is_playready_cdm(cdm) is expect_pr - assert is_remote_cdm(cdm) - - -def test_stamp_remote_sets_attrs_and_returns_same_object(): - obj = SimpleNamespace() - out = stamp_remote(obj, "playready") - assert out is obj - assert obj.drm == "playready" - assert obj.is_remote_cdm is True - - -def test_stamp_remote_is_best_effort_on_unsettable_object(): - class Slotted: - __slots__ = () - - obj = Slotted() - out = stamp_remote(obj, "widevine") # must not raise - assert out is obj - assert not hasattr(obj, "drm") - - -def test_load_remote_decryptlabs_playready_is_stamped(): - cdm_api = {"name": "dl-pr", "type": "decrypt_labs", "secret": "x", "device_name": "SL3000"} - cdm = loader_mod.load_remote_cdm(dict(cdm_api), "dl-pr", "EXAMPLE", None) - assert cdm.drm == "playready" - assert cdm.is_remote_cdm is True - assert is_remote_playready_cdm(cdm) - - -def test_load_remote_decryptlabs_widevine_is_stamped(): - cdm_api = {"name": "dl-wv", "type": "decrypt_labs", "secret": "x", "device_name": "ChromeCDM"} - cdm = loader_mod.load_remote_cdm(dict(cdm_api), "dl-wv", "EXAMPLE", None) - assert cdm.drm == "widevine" - assert is_remote_widevine_cdm(cdm) - - -def test_load_remote_native_playready_is_stamped(monkeypatch): - import unshackle.core.cdm.unprobed_remote_cdm as unprobed_mod - - class FakePlayReadyRemote: - def __init__(self, **kwargs): - self.kwargs = kwargs - - monkeypatch.setattr(unprobed_mod, "UnprobedPlayReadyRemoteCdm", FakePlayReadyRemote) - cdm_api = {"name": "pr", "Device Type": "PLAYREADY", "host": "h", "secret": "s", "device_name": "d"} - cdm = loader_mod.load_remote_cdm(dict(cdm_api), "pr", "EXAMPLE", None) - assert isinstance(cdm, FakePlayReadyRemote) - assert cdm.drm == "playready" - assert cdm.is_remote_cdm is True - assert is_remote_playready_cdm(cdm) - - -def test_load_remote_native_widevine_is_stamped(monkeypatch): - import unshackle.core.cdm.unprobed_remote_cdm as unprobed_mod - - class FakeWidevineRemote: - def __init__(self, **kwargs): - self.kwargs = kwargs - - monkeypatch.setattr(unprobed_mod, "UnprobedWidevineRemoteCdm", FakeWidevineRemote) - cdm_api = {"name": "wv", "Device Type": "ANDROID", "host": "h", "secret": "s", "device_name": "d"} - cdm = loader_mod.load_remote_cdm(dict(cdm_api), "wv", "EXAMPLE", None) - assert isinstance(cdm, FakeWidevineRemote) - assert cdm.drm == "widevine" - assert is_remote_widevine_cdm(cdm) - - -@pytest.fixture -def local_playready_cdm(): - prds = sorted(PRD_DIR.glob("*.prd")) - if not prds: - pytest.skip(f"no local .prd present in {PRD_DIR}") - from pyplayready.cdm import Cdm - from pyplayready.device import Device - - return Cdm.from_device(Device.load(str(prds[0]))) - - -def test_local_playready_is_playready_and_local(local_playready_cdm): - cdm = local_playready_cdm - assert is_playready_cdm(cdm) - assert not is_widevine_cdm(cdm) - assert is_local_cdm(cdm) - assert not is_remote_cdm(cdm) - assert not is_remote_playready_cdm(cdm) - assert cdm_location(cdm) == "local" + summary = cdm_summary(CustomRemoteCDM(host="http://h.invalid", device=device)) + assert summary["drm_type"] == drm_type + assert summary["remote"] is True + assert summary["device"] == device["name"] diff --git a/tests/remote/unit/test_key_identity.py b/tests/remote/unit/test_key_identity.py index df6f5dcc..60499603 100644 --- a/tests/remote/unit/test_key_identity.py +++ b/tests/remote/unit/test_key_identity.py @@ -108,7 +108,7 @@ def test_bad_key_config_is_refused_at_load(server, monkeypatch, user_cfg, proble def test_a_known_device_passes_validation(server, monkeypatch): monkeypatch.setattr(handlers.Services, "get_tags", staticmethod(lambda: ["EXAMPLE"])) - monkeypatch.setattr(handlers, "detect_cdm_type", lambda name, cfg: "playready") + monkeypatch.setattr(handlers, "device_system", lambda name, cfg: "playready") assert handlers.key_config_error("u", {"cdm": {"EXAMPLE": {"playready": "dev"}}, "service_config": {}}) is None assert handlers.key_config_error("u", {"cdm": {"EXAMPLE": {"default": "dev"}}, "service_config": None}) is None assert handlers.key_config_error("u", {"cdm": {"EXAMPLE": {"widevine": "dev"}}}) is not None diff --git a/tests/remote/unit/test_load_full_cdm_type.py b/tests/remote/unit/test_load_full_cdm_type.py index 05523de4..28d231ae 100644 --- a/tests/remote/unit/test_load_full_cdm_type.py +++ b/tests/remote/unit/test_load_full_cdm_type.py @@ -21,7 +21,7 @@ def widevine_configured(monkeypatch): app_config, "cdm", {"SVC": {"<=1080": "wv_l3", ">1080": "wv_l1", "default": "wv_l3"}}, raising=False ) # every resolved device name is a Widevine device - monkeypatch.setattr(handlers, "detect_cdm_type", lambda name, cfg: "widevine") + monkeypatch.setattr(handlers, "device_system", lambda name, cfg: "widevine") def fail_load(*args, **kwargs): raise AssertionError("load_cdm must not run for a mismatched type") @@ -39,7 +39,7 @@ def test_widevine_client_loads_the_configured_device(monkeypatch): from unshackle.core.config import config as app_config monkeypatch.setattr(app_config, "cdm", {"SVC": {"default": "wv_l3"}}, raising=False) - monkeypatch.setattr(handlers, "detect_cdm_type", lambda name, cfg: "widevine") + monkeypatch.setattr(handlers, "device_system", lambda name, cfg: "widevine") loaded = {} monkeypatch.setattr("unshackle.core.cdm.load_cdm", lambda name, service_name=None: loaded.setdefault("n", name)) handlers.load_full_cdm("SVC", None, "widevine") diff --git a/tests/remote/unit/test_server_cdm_type_override.py b/tests/remote/unit/test_server_cdm_type_override.py index 053a3948..c80024ac 100644 --- a/tests/remote/unit/test_server_cdm_type_override.py +++ b/tests/remote/unit/test_server_cdm_type_override.py @@ -97,7 +97,7 @@ def env(monkeypatch): monkeypatch.setattr(handlers.config, "serve", {"users": {}}, raising=False) # the device name says what the device is, in place of the .wvd / .prd file on disk monkeypatch.setattr( - handlers, "detect_cdm_type", lambda name, cfg: {"wv": "widevine", "pr": "playready"}.get(name[:2]) + handlers, "device_system", lambda name, cfg: {"wv": "widevine", "pr": "playready"}.get(name[:2]) ) diff --git a/unshackle/commands/dl.py b/unshackle/commands/dl.py index fb7e3f06..d7acb745 100644 --- a/unshackle/commands/dl.py +++ b/unshackle/commands/dl.py @@ -39,7 +39,7 @@ from rich.table import Table from unshackle.core import __version__, binaries, providers 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_system, cdm_type_stub, is_playready_cdm, is_remote_cdm 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.constants import ( @@ -475,6 +475,21 @@ def no_mux_extension(track: Any, path: Path, media_info: MediaInfo) -> str: return ".m4a" if isinstance(track, Audio) and path.suffix == ".mp4" and container == "MPEG-4" else path.suffix +def cdm_summary(cdm: Any) -> dict[str, Any]: + """The loaded CDM's DRM system, whether it is remote, its device and its security level, for the load log.""" + drm_type = "PlayReady" if is_playready_cdm(cdm) else "Widevine" + remote = is_remote_cdm(cdm) + if isinstance(cdm, DecryptLabsRemoteCDM): + device = "DecryptLabs" + elif remote: + device = cdm.device_name + elif drm_type == "Widevine": + device = str(cdm.system_id) + else: + device = cdm.certificate_chain.get_name() if cdm.certificate_chain else "Unknown" + return {"drm_type": drm_type, "remote": remote, "device": device, "security_level": cdm.security_level} + + def apply_service_dl_overrides(ctx: click.Context, service_dl_config: dict[str, Any], log: logging.Logger) -> None: """Apply ``services..dl`` config onto ``ctx.params``. Explicit CLI/env values win. The config replaces defaults and global ``dl:`` default_map values. @@ -1554,36 +1569,12 @@ class dl: sys.exit(1) if self.cdm: - cdm_info = {} - if isinstance(self.cdm, DecryptLabsRemoteCDM): - drm_type = "PlayReady" if self.cdm.is_playready else "Widevine" - self.log.info(f"Loaded {drm_type} Remote CDM: DecryptLabs (L{self.cdm.security_level})") - cdm_info = {"type": "DecryptLabs", "drm_type": drm_type, "security_level": self.cdm.security_level} - elif hasattr(self.cdm, "device_type") and self.cdm.device_type.name in ["ANDROID", "CHROME"]: - self.log.info(f"Loaded Widevine CDM: {self.cdm.system_id} (L{self.cdm.security_level})") - cdm_info = { - "type": "Widevine", - "system_id": self.cdm.system_id, - "security_level": self.cdm.security_level, - "device_type": self.cdm.device_type.name, - } - else: - # Handle both local PlayReady CDM and RemoteCdm (which has certificate_chain=None) - is_remote = self.cdm.certificate_chain is None and hasattr(self.cdm, "device_name") - if is_remote: - cdm_name = self.cdm.device_name - self.log.info(f"Loaded PlayReady Remote CDM: {cdm_name} (L{self.cdm.security_level})") - else: - cdm_name = self.cdm.certificate_chain.get_name() if self.cdm.certificate_chain else "Unknown" - self.log.info(f"Loaded PlayReady CDM: {cdm_name} (L{self.cdm.security_level})") - cdm_info = { - "type": "PlayReady", - "certificate": cdm_name, - "security_level": self.cdm.security_level, - } - - if cdm_info: - log_event("load_cdm", level="INFO", service=self.service, context={"cdm": cdm_info}) + cdm_info = cdm_summary(self.cdm) + where = " Remote" if cdm_info["remote"] else "" + self.log.info( + f"Loaded {cdm_info['drm_type']}{where} CDM: {cdm_info['device']} (L{cdm_info['security_level']})" + ) + log_event("load_cdm", level="INFO", service=self.service, context={"cdm": cdm_info}) if ctx.params.get("local_proxy"): require_alone_local_proxy(ctx) @@ -2588,25 +2579,14 @@ class dl: video_tracks = title.tracks.videos if video_tracks and not server_cdm_type: highest_quality = max((track.height for track in video_tracks if track.height), default=0) - if highest_quality > 0: - if is_widevine_cdm(self.cdm): - quality_based_cdm = self.get_cdm( - self.service, self.profile, drm="widevine", quality=highest_quality + system = cdm_system(self.cdm) + if highest_quality > 0 and system: + quality_based_cdm = self.get_cdm(self.service, self.profile, drm=system, quality=highest_quality) + if quality_based_cdm and quality_based_cdm != self.cdm: + self.log.debug( + f"Pre-selecting the {system} CDM for the highest quality {highest_quality}p of all video tracks" ) - if quality_based_cdm and quality_based_cdm != self.cdm: - self.log.debug( - f"Pre-selecting Widevine CDM based on highest quality {highest_quality}p across all video tracks" - ) - self.cdm = quality_based_cdm - elif is_playready_cdm(self.cdm): - quality_based_cdm = self.get_cdm( - self.service, self.profile, drm="playready", quality=highest_quality - ) - if quality_based_cdm and quality_based_cdm != self.cdm: - self.log.debug( - f"Pre-selecting PlayReady CDM based on highest quality {highest_quality}p across all video tracks" - ) - self.cdm = quality_based_cdm + self.cdm = quality_based_cdm title_all_drm = all_drm and not server_cdm_type if all_drm and server_cdm_type and DOWNLOAD_ALL_DRM.is_set(): @@ -2614,18 +2594,18 @@ class dl: self.log.warning("--all-drm is ignored: the server CDM licenses this session with one DRM system") if title_all_drm: heights = {track.height for track in title.tracks.videos if track.height} or {None} - for system, matches in (("Widevine", is_widevine_cdm), ("PlayReady", is_playready_cdm)): - system_cdms = [self.cdm_for(system.lower(), height) for height in heights] - if not all(system_cdm and matches(system_cdm) for system_cdm in system_cdms): + for system, name in (("widevine", "Widevine"), ("playready", "PlayReady")): + system_cdms = [self.cdm_for(system, height) for height in heights] + if not all(cdm_system(system_cdm) == system for system_cdm in system_cdms): hint = ( "drop --cdm, which selects one device" if self.cdm_override - else f"set cdm.{self.service}.{system.lower()}" + else f"set cdm.{self.service}.{system}" ) - raise click.ClickException(f"--all-drm needs a {system} CDM for {self.service}: {hint}") - if is_remote_cdm(system_cdms[0]) and system not in self.keys.all_drm_warned: - self.keys.all_drm_warned.add(system) - self.log.warning(f"The {system} CDM is remote and can answer with cached content keys") + raise click.ClickException(f"--all-drm needs a {name} CDM for {self.service}: {hint}") + if is_remote_cdm(system_cdms[0]) and name not in self.keys.all_drm_warned: + self.keys.all_drm_warned.add(name) + self.log.warning(f"The {name} CDM is remote and can answer with cached content keys") self.keys.take_server_keys(title) @@ -3984,9 +3964,8 @@ class dl: A quality key that names one device applies to both DRM systems. When that device is for the other system, the ``widevine`` or ``playready`` config key selects the device. """ - matches = is_playready_cdm if system == "playready" else is_widevine_cdm cdm = self.get_cdm(self.service, self.profile, drm=system, quality=quality) - if quality and not (cdm and matches(cdm)): + if quality and cdm_system(cdm) != system: cdm = self.get_cdm(self.service, self.profile, drm=system) return cdm diff --git a/unshackle/core/api/handlers.py b/unshackle/core/api/handlers.py index 9d7f99c3..3f555f0c 100644 --- a/unshackle/core/api/handlers.py +++ b/unshackle/core/api/handlers.py @@ -34,7 +34,8 @@ from unshackle.core.api.session_store import SessionEntry, SessionStore from unshackle.core.binaries import binary_version 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_system, cdm_type_stub +from unshackle.core.cdm.loader import device_system from unshackle.core.config import config, load_yaml from unshackle.core.dl_options import ( DEFAULT_DOWNLOAD_PARAMS, @@ -141,7 +142,7 @@ def load_full_cdm( return resolve_server_cdm(service, profile, cdm_type, app_config) wanted = drm_system(cdm_type) - if wanted and detect_cdm_type(cdm_name, app_config) not in (None, wanted): + if wanted and device_system(cdm_name, app_config) not in (None, wanted): return cdm_type_stub(wanted) try: @@ -1087,7 +1088,7 @@ def key_config_error(where: str, user_cfg: Dict[str, Any], app_config: Any = Non ): return f"{where}.cdm.{tag} must be a device name or a widevine/playready/default mapping of device names" for system, device in named.items(): - found = detect_cdm_type(device, app_config) + found = device_system(device, app_config) if found is None or system != "default" and found != system: return f"{where}.cdm.{tag}: no {'CDM' if system == 'default' else system} device named '{device}'" for tag, entry in service_config.items(): @@ -3800,7 +3801,7 @@ async def session_tracks_handler( config_cdm_type = detect_cdm_type_for_service(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) - config_cdm_type = "playready" if is_playready_cdm(loaded) else "widevine" + config_cdm_type = cdm_system(loaded) or "widevine" track_has_wv = any( d.__class__.__name__ == "Widevine" for t in list(tracks.videos) + list(tracks.audio) if t.drm for d in t.drm @@ -3948,7 +3949,7 @@ def resolve_server_cdm( app_config = app_config or config cdm_name = choose_cdm(app_config.cdm, service, view="stub").name if cdm_name: - detected_type = detect_cdm_type(cdm_name, app_config) + detected_type = device_system(cdm_name, app_config) if detected_type: return cdm_type_stub(detected_type) @@ -3968,30 +3969,7 @@ def detect_cdm_type_for_service(service: str, app_config: Any) -> Optional[str]: if choice.systems: return choice.system if choice.name: - return detect_cdm_type(choice.name, app_config) - return None - - -def detect_cdm_type(cdm_name: str, app_config: Any) -> Optional[str]: - """Detect CDM type (PlayReady/widevine) from config without loading it. - - Checks remote_cdm entries and local file extensions to determine the type. - """ - for entry in getattr(app_config, "remote_cdm", []) or []: - if entry.get("name") == cdm_name: - device_type = str(entry.get("device_type", entry.get("Device Type", ""))).upper() - return "playready" if device_type == "PLAYREADY" else "widevine" - - prd_path = app_config.directories.prds / f"{cdm_name}.prd" - if not prd_path.is_file(): - prd_path = app_config.directories.wvds / f"{cdm_name}.prd" - if prd_path.is_file(): - return "playready" - - wvd_path = app_config.directories.wvds / f"{cdm_name}.wvd" - if wvd_path.is_file(): - return "widevine" - + return device_system(choice.name, app_config) return None @@ -4440,7 +4418,7 @@ def server_drm_candidates( device_name = resolve_device_name(user_config, drm_type, service_tag) except APIError: continue - if detect_cdm_type(device_name, app_config) in (None, drm_type): + if device_system(device_name, app_config) in (None, drm_type): candidates.append(drm_type) preferred = drm_preference_name(track) diff --git a/unshackle/core/cdm/__init__.py b/unshackle/core/cdm/__init__.py index e6c2d8c1..06444cd1 100644 --- a/unshackle/core/cdm/__init__.py +++ b/unshackle/core/cdm/__init__.py @@ -11,14 +11,14 @@ from __future__ import annotations from typing import Any +from .detect import is_playready_cdm, is_remote_cdm, is_widevine_cdm + __all__ = [ "DecryptLabsRemoteCDM", "CustomRemoteCDM", "MonaLisaCDM", "load_cdm", "is_remote_cdm", - "is_local_cdm", - "cdm_location", "is_playready_cdm", "is_widevine_cdm", ] @@ -42,21 +42,4 @@ def __getattr__(name: str) -> Any: return load_cdm - if name in { - "is_remote_cdm", - "is_local_cdm", - "cdm_location", - "is_playready_cdm", - "is_widevine_cdm", - }: - from .detect import cdm_location, is_local_cdm, is_playready_cdm, is_remote_cdm, is_widevine_cdm - - return { - "is_remote_cdm": is_remote_cdm, - "is_local_cdm": is_local_cdm, - "cdm_location": cdm_location, - "is_playready_cdm": is_playready_cdm, - "is_widevine_cdm": is_widevine_cdm, - }[name] - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/unshackle/core/cdm/custom_remote_cdm.py b/unshackle/core/cdm/custom_remote_cdm.py index 062ffa85..c2d91f28 100644 --- a/unshackle/core/cdm/custom_remote_cdm.py +++ b/unshackle/core/cdm/custom_remote_cdm.py @@ -11,6 +11,7 @@ from pywidevine.device import DeviceTypes from requests import Session from unshackle.core import __version__ +from unshackle.core.cdm.loader import system_of from unshackle.core.vault import is_null_key from unshackle.core.vaults import Vaults @@ -115,6 +116,8 @@ class CustomRemoteCDM: service_certificate_challenge = b"\x08\x04" + is_remote_cdm = True + def __init__( self, host: str, @@ -158,9 +161,7 @@ class CustomRemoteCDM: self.system_id = device.get("system_id", 26830) self.security_level = device.get("security_level", 3) - self._is_playready = self.device_type_str.upper() == "PLAYREADY" or ( - bool(self.device_name) and self.device_name.upper().startswith("SL") - ) + self._is_playready = system_of(self.device_type_str, self.device_name) == "playready" if self.device_type_str: self.device_type = self.get_device_type_enum(self.device_type_str) diff --git a/unshackle/core/cdm/decrypt_labs_remote_cdm.py b/unshackle/core/cdm/decrypt_labs_remote_cdm.py index 978f7b15..b237f496 100644 --- a/unshackle/core/cdm/decrypt_labs_remote_cdm.py +++ b/unshackle/core/cdm/decrypt_labs_remote_cdm.py @@ -11,6 +11,7 @@ from pywidevine.device import DeviceTypes from requests import Session from unshackle.core import __version__ +from unshackle.core.cdm.loader import system_of from unshackle.core.vault import is_null_key from unshackle.core.vaults import Vaults @@ -97,6 +98,8 @@ class DecryptLabsRemoteCDM: service_certificate_challenge = b"\x08\x04" + is_remote_cdm = True + def __init__( self, secret: str, @@ -135,9 +138,7 @@ class DecryptLabsRemoteCDM: if device_type: self.device_type = self.get_device_type_enum(device_type) - self._is_playready = (device_type and device_type.upper() == "PLAYREADY") or ( - bool(device_name) and device_name.upper().startswith("SL") - ) + self._is_playready = system_of(device_type, device_name) == "playready" if self._is_playready: self.system_id = system_id or 0 diff --git a/unshackle/core/cdm/detect.py b/unshackle/core/cdm/detect.py index 6365aa3c..3aba74e1 100644 --- a/unshackle/core/cdm/detect.py +++ b/unshackle/core/cdm/detect.py @@ -1,3 +1,9 @@ +"""What a built CDM object is: its DRM system and whether its device runs on another machine. + +unshackle's own CDM classes and stand-ins carry ``is_playready``; a pywidevine or pyplayready CDM +is known by its class. For a device name in config, see ``loader.find_device``. +""" + from __future__ import annotations from types import SimpleNamespace @@ -5,216 +11,55 @@ from typing import Any, Optional def cdm_type_stub(cdm_type: str, security_level: Optional[int] = None) -> SimpleNamespace: - """Type-only CDM stand-in so is_widevine_cdm()/is_playready_cdm() (and thus - get_drm_for_cdm) route correctly without loading a real device. Used for - server_cdm mode, where the server holds the device and returns the keys. + """A CDM stand-in that only carries its DRM system, for when another machine holds the device. - ``security_level`` lets a service pick a robustness tier; the attribute is absent when unknown.""" + ``security_level`` lets a service pick a robustness tier; the attribute is absent when unknown. + """ stub = SimpleNamespace(is_playready=cdm_type == "playready") if security_level is not None: stub.security_level = security_level return stub -def is_remote_cdm(cdm: Any) -> bool: - """ - Return True if a remote CDM or a service CDM backs the CDM instance. - - This is useful for service logic that needs to know whether the CDM runs - locally (in-process) vs over HTTP/RPC (remote). - """ - +def cdm_system(cdm: Any) -> Optional[str]: + """``playready`` or ``widevine`` for a CDM object; None for no CDM or one of neither system.""" if cdm is None: - return False + return None + playready = getattr(cdm, "is_playready", None) + if isinstance(playready, bool): + return "playready" if playready else "widevine" - if hasattr(cdm, "is_remote_cdm"): - try: - return bool(getattr(cdm, "is_remote_cdm")) - except Exception: - pass + from pyplayready.cdm import Cdm as PlayReadyCdm + from pywidevine.cdm import Cdm as WidevineCdm - try: - from pyplayready.remote.remotecdm import RemoteCdm as PlayReadyRemoteCdm - except Exception: - PlayReadyRemoteCdm = None - - if PlayReadyRemoteCdm is not None: - try: - if isinstance(cdm, PlayReadyRemoteCdm): - return True - except Exception: - pass - - try: - from pywidevine.remotecdm import RemoteCdm as WidevineRemoteCdm - except Exception: - WidevineRemoteCdm = None # type: ignore[misc,assignment] - - if WidevineRemoteCdm is not None: - try: - if isinstance(cdm, WidevineRemoteCdm): - return True - except Exception: - pass - - cls = getattr(cdm, "__class__", None) - mod = getattr(cls, "__module__", "") or "" - name = getattr(cls, "__name__", "") or "" - - if mod == "unshackle.core.cdm.decrypt_labs_remote_cdm" and name == "DecryptLabsRemoteCDM": - return True - if mod == "unshackle.core.cdm.custom_remote_cdm" and name == "CustomRemoteCDM": - return True - - if mod.startswith("pyplayready.remote") or mod.startswith("pywidevine.remote"): - return True - if "remote" in mod.lower() and name.lower().endswith("cdm"): - return True - if name.lower().endswith("remotecdm"): - return True - - return False - - -def is_local_cdm(cdm: Any) -> bool: - """ - Return True if the CDM instance is local/in-process. - - Unknown CDM types return False (use `cdm_location()` if you need 3-state). - """ - - if cdm is None: - return False - - if is_remote_cdm(cdm): - return False - - if is_playready_cdm(cdm) or is_widevine_cdm(cdm): - return True - - cls = getattr(cdm, "__class__", None) - mod = getattr(cls, "__module__", "") or "" - name = getattr(cls, "__name__", "") or "" - if mod == "unshackle.core.cdm.monalisa.monalisa_cdm" and name == "MonaLisaCDM": - return True - - return False - - -def cdm_location(cdm: Any) -> str: - """ - Return one of: "local", "remote", "unknown". - """ - - if is_remote_cdm(cdm): - return "remote" - if is_local_cdm(cdm): - return "local" - return "unknown" + if isinstance(cdm, PlayReadyCdm): + return "playready" + if isinstance(cdm, WidevineCdm): + return "widevine" + return None def is_playready_cdm(cdm: Any) -> bool: - """ - Return True if unshackle treats the given CDM as PlayReady. - - This intentionally supports both: - - Local PlayReady CDMs (pyplayready.cdm.Cdm) - - Remote/wrapper CDMs (for example DecryptLabsRemoteCDM) that have `is_playready` - """ - - if cdm is None: - return False - - drm = getattr(cdm, "drm", None) - if drm: - return str(drm).lower() == "playready" - - if hasattr(cdm, "is_playready"): - try: - return bool(getattr(cdm, "is_playready")) - except Exception: - pass - - try: - from pyplayready.cdm import Cdm as PlayReadyCdm - except Exception: - PlayReadyCdm = None - - if PlayReadyCdm is not None: - try: - return isinstance(cdm, PlayReadyCdm) - except Exception: - pass - - try: - from pyplayready.remote.remotecdm import RemoteCdm as PlayReadyRemoteCdm - except Exception: - PlayReadyRemoteCdm = None - - if PlayReadyRemoteCdm is not None: - try: - return isinstance(cdm, PlayReadyRemoteCdm) - except Exception: - pass - - mod = getattr(getattr(cdm, "__class__", None), "__module__", "") or "" - return "pyplayready" in mod - - -def is_remote_playready_cdm(cdm: Any) -> bool: - """Return True if the CDM is a remote PlayReady CDM (as opposed to a local .prd).""" - - return is_playready_cdm(cdm) and is_remote_cdm(cdm) - - -def is_remote_widevine_cdm(cdm: Any) -> bool: - """Return True if the CDM is a remote Widevine CDM (as opposed to a local .wvd).""" - - return is_widevine_cdm(cdm) and is_remote_cdm(cdm) + """True for a PlayReady CDM.""" + return cdm_system(cdm) == "playready" def is_widevine_cdm(cdm: Any) -> bool: - """ - Return True if unshackle treats the given CDM as Widevine. + """True for a Widevine CDM.""" + return cdm_system(cdm) == "widevine" - Note: for remote/wrapper CDMs that have `is_playready`, unshackle treats - Widevine as the logical opposite. - """ - if cdm is None: - return False +def is_remote_cdm(cdm: Any) -> bool: + """True for a CDM whose device runs on another machine.""" + if getattr(cdm, "is_remote_cdm", False): + return True - drm = getattr(cdm, "drm", None) - if drm: - return str(drm).lower() == "widevine" + from pyplayready.remote.remotecdm import RemoteCdm as PlayReadyRemoteCdm + from pywidevine.remotecdm import RemoteCdm as WidevineRemoteCdm - if hasattr(cdm, "is_playready"): - try: - return not bool(getattr(cdm, "is_playready")) - except Exception: - pass + return isinstance(cdm, (PlayReadyRemoteCdm, WidevineRemoteCdm)) - try: - from pywidevine.cdm import Cdm as WidevineCdm - except Exception: - WidevineCdm = None # type: ignore[misc,assignment] - if WidevineCdm is not None: - try: - return isinstance(cdm, WidevineCdm) - except Exception: - pass - - try: - from pywidevine.remotecdm import RemoteCdm as WidevineRemoteCdm - except Exception: - WidevineRemoteCdm = None # type: ignore[misc,assignment] - - if WidevineRemoteCdm is not None: - try: - return isinstance(cdm, WidevineRemoteCdm) - except Exception: - pass - - mod = getattr(getattr(cdm, "__class__", None), "__module__", "") or "" - return "pywidevine" in mod +def is_remote_playready_cdm(cdm: Any) -> bool: + """True for a PlayReady CDM whose device runs on another machine.""" + return is_playready_cdm(cdm) and is_remote_cdm(cdm) diff --git a/unshackle/core/cdm/loader.py b/unshackle/core/cdm/loader.py index 0bc054ae..413d2bac 100644 --- a/unshackle/core/cdm/loader.py +++ b/unshackle/core/cdm/loader.py @@ -1,32 +1,71 @@ -"""Shared CDM loading utility. +"""The CDM catalogue: what a device name in config is, and how to build it. -Instantiates a CDM object (local or remote) given a resolved device name. -Name resolution (quality-based, profile-based, DRM-type) is the caller's -responsibility. This module does the instantiation step only. +A device is a ``remote_cdm`` entry or a local .prd or .wvd file. :func:`find_device` reads its DRM +system from config without loading it, and :func:`load_cdm` builds it. Which name a service uses +is the caller's choice (see ``choice.py``). """ from __future__ import annotations import logging -from typing import Any, Optional +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Optional, Union log = logging.getLogger("cdm") -def stamp_remote(cdm: Any, drm: str) -> Any: - """Record a remote CDM's DRM type and mark it as remote. +def system_of(device_type: Any, device_name: Any = None) -> str: + """``playready`` for a PLAYREADY device type or a PlayReady level name (SL2, SL3000); else ``widevine``.""" + playready = str(device_type or "").upper() == "PLAYREADY" or str(device_name or "").upper().startswith("SL") + return "playready" if playready else "widevine" - The loader knows the DRM type from config, so it sets it here as the value - `detect.py` reads before it falls back to class or module checks. Setting the - attributes is best effort: a third-party CDM object that rejects them still - works, since detect.py keeps its existing checks. + +def entry_system(entry: dict) -> str: + """The DRM system of a ``remote_cdm`` entry, read from the keys its CDM class reads. + + A serve entry names no level, so only its device type counts. """ - try: - cdm.drm = drm - cdm.is_remote_cdm = True - except (AttributeError, TypeError): - pass - return cdm + if entry.get("type") == "custom_api": + device = entry.get("device") or {} + return system_of(device.get("type"), device.get("name")) + if entry.get("type") == "decrypt_labs": + return system_of(entry.get("device_type"), entry.get("device_name")) + return system_of(entry.get("Device Type", entry.get("device_type"))) + + +@dataclass(frozen=True, eq=False) +class Device: + """A device config names: its DRM system, and its ``remote_cdm`` entry or its local file.""" + + system: str + source: Union[dict[str, Any], Path] + + +def find_device(name: str, app_config: Any = None) -> Optional[Device]: + """The device ``name`` names in ``remote_cdm`` or the device folders; None when there is none. + + ``app_config`` is an API key's view of the config; None reads the config itself. + """ + if app_config is None: + from unshackle.core.config import config + + app_config = config + entry = next((e for e in getattr(app_config, "remote_cdm", None) or [] if e.get("name") == name), None) + if entry: + return Device(entry_system(entry), entry) + directories = app_config.directories + for path in (directories.prds / f"{name}.prd", directories.wvds / f"{name}.prd"): + if path.is_file(): + return Device("playready", path) + path = directories.wvds / f"{name}.wvd" + return Device("widevine", path) if path.is_file() else None + + +def device_system(name: str, app_config: Any = None) -> Optional[str]: + """``widevine`` or ``playready`` for the device ``name`` names, without loading it; None when there is none.""" + device = find_device(name, app_config) + return device.system if device else None def load_cdm( @@ -35,118 +74,80 @@ def load_cdm( service_name: str = "", vaults: Optional[Any] = None, ) -> Any: - """Instantiate a CDM by device name. - - Looks up the name in config.remote_cdm first (for remote/API CDMs), - then falls back to local .prd / .wvd files. - - Returns a CDM object (WidevineCdm, PlayReadyCdm, RemoteCdm, - DecryptLabsRemoteCDM, CustomRemoteCDM, or PlayReadyRemoteCdm). + """Build the CDM a device name names: a remote CDM for a ``remote_cdm`` entry, else the local device. Raises ValueError if the device cannot be found or loaded. """ + device = find_device(cdm_name) + if device is None: + raise ValueError(f"{cdm_name} does not exist or is not a file") + if isinstance(device.source, dict): + return load_remote_cdm(cdm_name, device.source, device.system, service_name, vaults) + return load_local_cdm(cdm_name, device.system, device.source) + + +def load_remote_cdm(name: str, entry: dict[str, Any], system: str, service_name: str, vaults: Optional[Any]) -> Any: + """Build a remote CDM from its ``remote_cdm`` entry.""" from unshackle.core.config import config - cdm_api = next(iter(x.copy() for x in config.remote_cdm if x["name"] == cdm_name), None) - if cdm_api: - return load_remote_cdm(cdm_api, cdm_name, service_name, vaults) - - return load_local_cdm(cdm_name) - - -def load_remote_cdm( - cdm_api: dict, - cdm_name: str, - service_name: str, - vaults: Optional[Any], -) -> Any: - """Instantiate a remote CDM from a config.remote_cdm entry.""" - from unshackle.core.config import config - - cdm_type = cdm_api.get("type") + cdm_api: Any = dict(entry) + cdm_type = cdm_api.pop("type", None) + cdm_api.pop("name", None) if cdm_type == "decrypt_labs": from unshackle.core.cdm.decrypt_labs_remote_cdm import DecryptLabsRemoteCDM - del cdm_api["name"] - del cdm_api["type"] - - if "secret" not in cdm_api or not cdm_api["secret"]: + if not cdm_api.get("secret"): if config.decrypt_labs_api_key: cdm_api["secret"] = config.decrypt_labs_api_key else: raise ValueError( - f"No secret provided for DecryptLabs CDM '{cdm_name}' and no global decrypt_labs_api_key configured" + f"No secret provided for DecryptLabs CDM '{name}' and no global decrypt_labs_api_key configured" ) - - cdm: Any = DecryptLabsRemoteCDM(service_name=service_name, vaults=vaults, **cdm_api) - return stamp_remote(cdm, "playready" if cdm.is_playready else "widevine") + return DecryptLabsRemoteCDM(service_name=service_name, vaults=vaults, **cdm_api) if cdm_type == "custom_api": from unshackle.core.cdm.custom_remote_cdm import CustomRemoteCDM - del cdm_api["name"] - del cdm_api["type"] - cdm = CustomRemoteCDM(service_name=service_name, vaults=vaults, **cdm_api) - return stamp_remote(cdm, "playready" if cdm.is_playready else "widevine") + return CustomRemoteCDM(service_name=service_name, vaults=vaults, **cdm_api) - device_type = cdm_api.get("Device Type", cdm_api.get("device_type", "")) - if str(device_type).upper() == "PLAYREADY": - from unshackle.core.cdm.unprobed_remote_cdm import UnprobedPlayReadyRemoteCdm + from unshackle.core.cdm.unprobed_remote_cdm import UnprobedPlayReadyRemoteCdm, UnprobedWidevineRemoteCdm - return stamp_remote( - UnprobedPlayReadyRemoteCdm( - security_level=cdm_api.get("Security Level", cdm_api.get("security_level", 3000)), - host=cdm_api.get("Host", cdm_api.get("host")), - secret=cdm_api.get("Secret", cdm_api.get("secret")), - device_name=cdm_api.get("Device Name", cdm_api.get("device_name")), - ), - "playready", - ) - - from unshackle.core.cdm.unprobed_remote_cdm import UnprobedWidevineRemoteCdm - - return stamp_remote( - UnprobedWidevineRemoteCdm( - device_type=cdm_api.get("Device Type", cdm_api.get("device_type", "")), - system_id=cdm_api.get("System ID", cdm_api.get("system_id", "")), - security_level=cdm_api.get("Security Level", cdm_api.get("security_level", 3000)), - host=cdm_api.get("Host", cdm_api.get("host")), - secret=cdm_api.get("Secret", cdm_api.get("secret")), - device_name=cdm_api.get("Device Name", cdm_api.get("device_name")), - ), - "widevine", + security_level = cdm_api.get("Security Level", cdm_api.get("security_level", 3000)) + host = cdm_api.get("Host", cdm_api.get("host")) + secret = cdm_api.get("Secret", cdm_api.get("secret")) + device_name = cdm_api.get("Device Name", cdm_api.get("device_name")) + if system == "playready": + return UnprobedPlayReadyRemoteCdm(security_level, host, secret, device_name) + return UnprobedWidevineRemoteCdm( + device_type=cdm_api.get("Device Type", cdm_api.get("device_type", "")), + system_id=cdm_api.get("System ID", cdm_api.get("system_id", "")), + security_level=security_level, + host=host, + secret=secret, + device_name=device_name, ) -def load_local_cdm(cdm_name: str) -> Any: - """Instantiate a local CDM from a .prd or .wvd file.""" - from unshackle.core.config import config - - prd_path = config.directories.prds / f"{cdm_name}.prd" - if not prd_path.is_file(): - prd_path = config.directories.wvds / f"{cdm_name}.prd" - if prd_path.is_file(): +def load_local_cdm(name: str, system: str, path: Path) -> Any: + """Build a local CDM from its .prd or .wvd file.""" + if system == "playready": from pyplayready.cdm import Cdm as PlayReadyCdm from pyplayready.device import Device as PlayReadyDevice - return PlayReadyCdm.from_device(PlayReadyDevice.load(prd_path)) - - cdm_path = config.directories.wvds / f"{cdm_name}.wvd" - if not cdm_path.is_file(): - raise ValueError(f"{cdm_name} does not exist or is not a file") + return PlayReadyCdm.from_device(PlayReadyDevice.load(path)) from construct import ConstError from pywidevine.cdm import Cdm as WidevineCdm - from pywidevine.device import Device + from pywidevine.device import Device as WidevineDevice try: - device = Device.load(cdm_path) + wvd = WidevineDevice.load(path) except ConstError as e: if "expected 2 but parsed 1" in str(e): raise ValueError( - f"{cdm_name}.wvd seems to be a v1 WVD file, use `pywidevine migrate --help` to migrate it to v2." + f"{name}.wvd seems to be a v1 WVD file, use `pywidevine migrate --help` to migrate it to v2." ) - raise ValueError(f"{cdm_name}.wvd is an invalid or corrupt Widevine Device file, {e}") + raise ValueError(f"{name}.wvd is an invalid or corrupt Widevine Device file, {e}") - return WidevineCdm.from_device(device) + return WidevineCdm.from_device(wvd) diff --git a/unshackle/core/drm/key_resolution.py b/unshackle/core/drm/key_resolution.py index 16591b20..e36ba295 100644 --- a/unshackle/core/drm/key_resolution.py +++ b/unshackle/core/drm/key_resolution.py @@ -20,7 +20,7 @@ from rich.text import Text from rich.tree import Tree from unshackle.core import binaries -from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm +from unshackle.core.cdm.detect import cdm_system, is_playready_cdm from unshackle.core.console import console from unshackle.core.constants import DOWNLOAD_CANCELLED, AnyTrack, DownloadCancelled from unshackle.core.drm import ( @@ -722,7 +722,7 @@ class ContentKeyResolver: a track downloading at the same time can swap self.cdms.cdm. """ if drm_system is None: - drm_system = "playready" if is_playready_cdm(self.cdms.cdm) else "widevine" + drm_system = cdm_system(self.cdms.cdm) or "widevine" fn = self.service.get_playready_license if drm_system == "playready" else self.service.get_widevine_license return fn(**declared_kwargs(fn, kwargs)) @@ -959,11 +959,10 @@ class ContentKeyResolver: licence = partial(licence, drm_system=drm_system) if not server_cdm and isinstance(drm, (Widevine, PlayReady)): - matches = is_playready_cdm if drm_system == "playready" else is_widevine_cdm - if not matches(self.cdms.cdm): + if cdm_system(self.cdms.cdm) != drm_system: name, other = ("PlayReady", "Widevine") if drm_system == "playready" else ("Widevine", "PlayReady") system_cdm = self.cdms.cdm_for(drm_system, track_quality) - if system_cdm and matches(system_cdm): + if cdm_system(system_cdm) == drm_system: self.log.info(f"Switching to the {name} CDM") self.cdms.cdm = system_cdm track_cdm = system_cdm diff --git a/unshackle/core/remote_service.py b/unshackle/core/remote_service.py index e26f8c28..bbc23f14 100644 --- a/unshackle/core/remote_service.py +++ b/unshackle/core/remote_service.py @@ -1175,13 +1175,13 @@ class RemoteService: "so the server decides who licenses it" ) if cdm is not None: - from unshackle.core.cdm.detect import is_playready_cdm + from unshackle.core.cdm.detect import cdm_system if cdm_entry or cdm_name or cdm_only: self._server_cdm = False if self._server_cdm is False: create_data["server_cdm"] = False - create_data["cdm_type"] = "playready" if is_playready_cdm(cdm) else "widevine" + create_data["cdm_type"] = cdm_system(cdm) or "widevine" level = getattr(cdm, "security_level", None) if isinstance(level, int): create_data["cdm_security_level"] = level @@ -1580,9 +1580,9 @@ class RemoteService: drm_type = self.server_cdm_type if getattr(self, "_server_vault", False): - from unshackle.core.cdm.detect import is_playready_cdm + from unshackle.core.cdm.detect import cdm_system - drm_type = "playready" if is_playready_cdm(self.local_cdm) else "widevine" + drm_type = cdm_system(self.local_cdm) or "widevine" self.log.debug(f"Requesting server CDM keys (server_cdm_type={drm_type})") capped: Dict[str, Any] = {} @@ -1657,7 +1657,7 @@ class RemoteService: dl then licenses it through the challenge relay. An HLS track with no DRM yet passes, as its media playlist names the DRM and the downloader honours ``drm_preference``. """ - from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm + from unshackle.core.cdm.detect import cdm_system, is_playready_cdm if refusal.get("reason") == "server_device": vaults = ( @@ -1683,8 +1683,11 @@ class RemoteService: systems = {d.__class__.__name__ for d in track.drm or ()} if systems and drm_class not in systems: other = "Widevine" if drm_class == "PlayReady" else "PlayReady" - matches = is_widevine_cdm if other == "Widevine" else is_playready_cdm - if not (other in systems and self.ctx.obj.cdm_for and matches(self.ctx.obj.cdm_for(other.lower(), height))): + if not ( + other in systems + and self.ctx.obj.cdm_for + and cdm_system(self.ctx.obj.cdm_for(other.lower(), height)) == other.lower() + ): label = f"the {height}p track" if height else str(track) hint = f"; pass -q {height} to start the session on your device" if cap and height else "" have = " and ".join(sorted(systems))