refactor(core): one TitleSource base for Service, remote and import

This commit is contained in:
imSp4rky
2026-11-25 21:46:55 -07:00
parent 9febbb20c5
commit 92e8abbdbc
21 changed files with 619 additions and 470 deletions
@@ -1,19 +0,0 @@
"""ImportService and RemoteService stand in for a Service in dl, so they have every method dl calls on one."""
from __future__ import annotations
import re
from pathlib import Path
import pytest
from unshackle.commands import dl as dl_module
from unshackle.core.import_service import ImportService
from unshackle.core.remote_service import RemoteService
@pytest.mark.parametrize("cls", [ImportService, RemoteService])
def test_stand_in_service_has_every_method_dl_calls(cls: type) -> None:
called = set(re.findall(r"\bservice\.(\w+)\(", Path(dl_module.__file__).read_text(encoding="utf-8")))
assert called
assert sorted(name for name in called if not hasattr(cls, name)) == []
+172
View File
@@ -0,0 +1,172 @@
"""Each title source states how its content keys reach dl, what its caches file it under, and whose login it saves."""
from __future__ import annotations
import logging
from pathlib import Path
from typing import Any
from uuid import UUID
import pytest
import requests
from tests.core.test_export import crit_export, import_ctx
from tests.lang_selection import test_kind_only_selection as harness
from tests.lang_selection.test_kind_only_selection import FakeService
from tests.remote.key_source import MemoryKeySource, remote_keys
from unshackle.commands import dl as dl_module
from unshackle.core.drm import PlayReady, Widevine
from unshackle.core.drm.cenc import drm_stub
from unshackle.core.import_service import ImportService
from unshackle.core.service import Service
from unshackle.core.title_cacher import get_account_hash
from unshackle.core.title_source import CacheIdentity, KeyArrival
KIDS = [UUID(int=1).hex, UUID(int=2).hex]
class ExampleService(Service):
def get_titles(self) -> Any: ...
def get_tracks(self, title: Any) -> Any: ...
def get_chapters(self, title: Any) -> Any: ...
def service(**attrs: Any) -> ExampleService:
"""An ExampleService with only ``attrs`` set, as ``Service.__init__`` needs a config and a network."""
svc = object.__new__(ExampleService)
svc.__dict__.update(attrs)
return svc
def an_import(tmp_path: Path) -> ImportService:
return ImportService(import_ctx(), "EXAMPLE", "movie-1", str(crit_export(tmp_path / "export.json")))
def test_a_service_licenses_through_its_callbacks_and_has_no_key_source() -> None:
svc = service()
assert (svc.key_arrival, svc.key_source) == (KeyArrival.CALLBACK, None)
@pytest.mark.parametrize(("server_cdm", "arrival"), [(True, KeyArrival.SERVER), (False, KeyArrival.CALLBACK)])
def test_a_remote_session_follows_the_server_cdm_and_is_its_own_key_source(
server_cdm: bool, arrival: KeyArrival
) -> None:
"""Without the server CDM the challenge relay licenses, but the server vault still answers through the session."""
remote = remote_keys(server_cdm=server_cdm)
assert (remote.key_arrival, remote.key_source) == (arrival, remote)
def test_an_import_takes_the_keys_from_the_export(tmp_path: Path) -> None:
imported = an_import(tmp_path)
assert (imported.key_arrival, imported.key_source) == (KeyArrival.EXPORT, imported)
@pytest.mark.parametrize("attr", ["title", "title_id"])
def test_a_service_is_cached_under_the_title_id_it_keeps(attr: str) -> None:
svc = service(**{attr: "show-1", "title_cache": "cacher", "current_region": "gb"})
assert svc.cache_identity() == CacheIdentity("cacher", "show-1", "gb", get_account_hash(None))
def test_a_service_with_no_title_id_has_none_to_cache_under() -> None:
assert service().cache_identity().title_id is None
def test_a_remote_session_and_an_import_have_no_title_cache(tmp_path: Path) -> None:
remote = remote_keys()
remote.title_id = "show-1"
assert remote.cache_identity() == CacheIdentity(None, "show-1", None, None)
assert an_import(tmp_path).cache_identity() == CacheIdentity(None, "movie-1", None, None)
def test_only_a_service_saves_its_login_cookies(tmp_path: Path) -> None:
session = requests.Session()
assert service(session=session).login_cookies is session.cookies
assert remote_keys().login_cookies is None
assert an_import(tmp_path).login_cookies is None
def test_the_source_defaults_leave_a_track_alone() -> None:
"""A source that defines no hooks, sample decrypter or licence callback gets the no-op base."""
svc = service(log=logging.getLogger("test"))
assert not svc.decrypts_samples(None) # type: ignore[arg-type]
assert svc.get_widevine_license(challenge=b"", title=None, track=None) is None # type: ignore[arg-type]
assert svc.get_playready_license(challenge=b"", title=None, track=None) is None # type: ignore[arg-type]
with pytest.raises(NotImplementedError):
svc.get_sample_decrypter(None, 1) # type: ignore[arg-type]
svc.close()
def test_a_playready_stub_names_every_kid() -> None:
stub = drm_stub("playready", KIDS)
assert isinstance(stub, PlayReady)
assert [kid.hex for kid in stub.kids] == KIDS
@pytest.mark.parametrize("drm_type", ["widevine", "other"])
def test_any_other_stub_is_widevine_and_names_every_kid(drm_type: str) -> None:
stub = drm_stub(drm_type, KIDS)
assert isinstance(stub, Widevine)
assert [kid.hex for kid in stub.pssh.key_ids] == KIDS
class KeyedSource(FakeService):
"""A harness source that states its key arrival and records what dl does with it at the end of a run."""
def __init__(self, arrival: KeyArrival, cookies: Any = None) -> None:
super().__init__({1: {}})
self.arrival = arrival
self.cookies = cookies
self.keys = MemoryKeySource()
self.keys.key_arrival = arrival
self.closed = 0
@property
def key_arrival(self) -> KeyArrival:
return self.arrival
@property
def key_source(self) -> Any:
return None if self.arrival is KeyArrival.CALLBACK else self.keys
@property
def login_cookies(self) -> Any:
return self.cookies
def close(self) -> None:
self.closed += 1
@pytest.mark.parametrize(
("arrival", "line"),
[
(KeyArrival.EXPORT, "Using keys from the export; no CDM required"),
(KeyArrival.SERVER, "Using server CDM (Widevine); no local CDM required"),
],
)
def test_dl_licenses_with_no_cdm_of_its_own_when_the_keys_arrive_from_the_source(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, arrival: KeyArrival, line: str
) -> None:
lines: list[str] = []
monkeypatch.setattr(logging.getLogger("test_kind_only"), "info", lambda msg, *a, **k: lines.append(msg))
saved: list[Any] = []
monkeypatch.setattr(dl_module.login, "save_cookies", lambda *a: saved.append(a))
source = KeyedSource(arrival)
assert harness.run(monkeypatch, caplog, {1: {}}, service=source, to_end=True, skip_dl=True) is None
assert line in lines
assert (source.closed, saved) == (1, [])
def test_dl_saves_the_login_cookies_of_a_service(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, tmp_path: Path
) -> None:
jar = requests.cookies.RequestsCookieJar()
saved: list[Any] = []
monkeypatch.setattr(dl_module.login, "get_cookie_path", lambda *a: tmp_path / "cookies.txt")
monkeypatch.setattr(dl_module.login, "get_cookie_jar", lambda *a: None)
monkeypatch.setattr(dl_module.login, "save_cookies", lambda path, cookies: saved.append(cookies))
source = KeyedSource(KeyArrival.CALLBACK, cookies=jar)
assert harness.run(monkeypatch, caplog, {1: {}}, service=source, to_end=True, skip_dl=True) is None
assert saved == [jar]
assert source.closed == 1
@@ -11,16 +11,15 @@ from __future__ import annotations
import inspect
import logging
from pathlib import Path
from typing import Any, cast
from typing import Any
import pytest
import requests
from unshackle.commands.dl import dl
from unshackle.core import binaries
from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY
from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS
from unshackle.core.service import Service
from unshackle.core.title_source import TitleSource
from unshackle.core.titles import Episode, Series
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
@@ -42,17 +41,18 @@ class Harness(dl):
return None
class FakeService:
class FakeService(TitleSource):
"""One episode per entry; ``ad`` adds a descriptive track, ``forced`` a forced subtitle, ``ko`` Korean audio."""
def __init__(self, episodes: dict[int, dict[str, bool]]) -> None:
self.episodes = episodes
self.session = None
self.ctx = None
def authenticate(self, cookies: Any = None, credential: Any = None) -> None:
pass
def get_titles_cached(self) -> Series:
def get_titles(self) -> Series:
return Series(
Episode(id_=f"show-s01-e{n:03}", service=FakeService, title="Show", season=1, number=n, language="en")
for n in self.episodes
@@ -124,10 +124,8 @@ def run(
kwargs.update(flags)
caplog.set_level(logging.WARNING, logger="test_kind_only")
service = service or FakeService(episodes)
if to_end:
service.session = requests.Session()
try:
cmd.result(cast(Service, service), **kwargs)
cmd.result(service, **kwargs)
except Selected as sel:
return sel.ids
except SystemExit as exc:
+2 -1
View File
@@ -5,6 +5,7 @@ from typing import Any
from uuid import UUID
from unshackle.core.remote_service import RemoteService, ServerVault
from unshackle.core.title_source import KeyArrival
def remote_keys(
@@ -31,7 +32,7 @@ class MemoryKeySource:
A ``licence`` of None hands the track to this machine, as a capped server does.
"""
server_cdm = True
key_arrival = KeyArrival.SERVER
server_cdm_type = "widevine"
server_vault: Any = None
@@ -1,10 +1,4 @@
"""Contract tests for the RemoteService adapter.
RemoteService copies the Service interface but does not inherit from it. When a
method is added to the base Service and wired into dl.py, nothing forces it onto
the adapter, so it can go missing here until a real download calls it. These
tests pin the methods dl.py depends on so a gap fails in CI, not on the devbox.
"""
"""RemoteService licence callbacks that must not touch the remote session."""
from __future__ import annotations
@@ -14,30 +8,6 @@ from unshackle.core.remote_service import RemoteService
pytestmark = pytest.mark.unit
SERVICE_CONTRACT = (
"authenticate",
"get_titles",
"get_titles_cached",
"get_tracks",
"get_chapters",
"get_widevine_license",
"get_playready_license",
"get_clearkey_license",
"get_widevine_service_certificate",
"resolve_server_keys",
"on_segment_downloaded",
"on_track_downloaded",
"on_track_decrypted",
"on_track_repacked",
"on_track_multiplex",
"close",
)
@pytest.mark.parametrize("name", SERVICE_CONTRACT)
def test_remote_service_implements_contract(name: str) -> None:
assert callable(getattr(RemoteService, name, None)), f"RemoteService is missing {name}()"
def test_get_clearkey_license_returns_none() -> None:
# Regression: clearkey uses no CDM, so the adapter returns None and the
@@ -647,7 +647,7 @@ def _remote_service(parent_params: dict, service_params: dict) -> RemoteService:
svc._server_accounts = {"global": True}
svc._server_cdm = True
svc._service_params = service_params
svc._session = requests.Session()
svc.session = requests.Session()
svc.log = logging.getLogger("test")
svc.client = SimpleNamespace(post=post, server_url="https://server.example")
return svc
@@ -671,8 +671,8 @@ def test_the_client_session_downloads_through_the_proxy_it_sends(
svc = _remote_service({"no_proxy": no_proxy, "proxy": "http://proxy.example:8080"}, {})
with pytest.raises(_SentCreate) as exc:
svc.authenticate()
assert dict(svc._session.proxies) == expected
assert svc._session.trust_env is no_proxy # a proxied session ignores HTTP(S)_PROXY
assert dict(svc.session.proxies) == expected
assert svc.session.trust_env is no_proxy # a proxied session ignores HTTP(S)_PROXY
assert exc.value.args[0].get("proxy") == (None if no_proxy else "http://proxy.example:8080")
@@ -17,6 +17,7 @@ from tests.remote.sessions import session_entry
from unshackle.core.api import handlers
from unshackle.core.api.errors import APIError
from unshackle.core.drm import BlowfishStripe
from unshackle.core.drm.cenc import drm_stub
from unshackle.core.remote_service import RemoteService
pytestmark = pytest.mark.unit
@@ -286,7 +287,7 @@ def test_resolve_server_keys_names_only_the_manifest_kids():
widevine = Widevine(pssh=PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=[KID]))
assert resolve([widevine]).kids == [KID]
playready = RemoteService.create_drm_stub("playready", [KID.hex])
playready = drm_stub("playready", [KID.hex])
assert resolve([playready], "playready").kids == [KID]
+3 -2
View File
@@ -25,6 +25,7 @@ from unshackle.core.cdm.detect import cdm_type_stub
from unshackle.core.config import config
from unshackle.core.drm import Widevine, key_resolution
from unshackle.core.remote_service import RemoteService
from unshackle.core.title_source import KeyArrival
from unshackle.core.vaults import Vaults
from unshackle.vaults.SQLite import SQLite
@@ -134,7 +135,7 @@ def decrypt(
assert vaults.get_key(VAULTED) == (OTHER_KEY, local)
pushed: list = []
source = SimpleNamespace(
server_cdm=False,
key_arrival=KeyArrival.CALLBACK,
server_vault=SimpleNamespace(add_keys=lambda service, keys, track: pushed.append((keys, track))),
)
keys = resolver(vaults, tag="EXAMPLE", source=source)
@@ -306,7 +307,7 @@ def test_cdm_only_declines_the_server_cdm_and_its_vault(monkeypatch, tmp_path) -
try:
svc.authenticate()
assert svc.posts[0]["server_cdm"] is False
assert (svc.server_cdm, svc._server_vault) == (False, False)
assert (svc.key_arrival, svc._server_vault) == (KeyArrival.CALLBACK, False)
svc.resolve_server_keys(SimpleNamespace(tracks=SimpleNamespace(videos=["v"], audio=[])))
assert len(svc.posts) == 1
finally:
+3 -3
View File
@@ -125,7 +125,7 @@ def test_remote_get_tracks_scopes_server_cookies():
_title_alias={},
_sample_decrypt_tracks=set(),
_server_cdm=None,
_session=requests.Session(),
session=requests.Session(),
_session_id="s",
service_tag="EXAMPLE",
log=logging.getLogger("test"),
@@ -133,9 +133,9 @@ def test_remote_get_tracks_scopes_server_cookies():
drain_server_logs=lambda: None,
)
service.get_tracks(SimpleNamespace(id="t1"))
cdn = service._session.prepare_request(requests.Request("GET", "https://cdn.other.net/seg.mp4"))
cdn = service.session.prepare_request(requests.Request("GET", "https://cdn.other.net/seg.mp4"))
assert "Cookie" not in cdn.headers
assert service._session.cookies.get("sid", domain=".example.com") == "secret"
assert service.session.cookies.get("sid", domain=".example.com") == "secret"
def test_server_login_strips_auth():