refactor(api): build list, search and session services through one launch_served

This commit is contained in:
imSp4rky
2026-11-29 14:28:47 -07:00
parent e41760c2b3
commit de2ffcb9bd
22 changed files with 444 additions and 280 deletions
+1 -1
View File
@@ -203,7 +203,7 @@ Get the list of titles behind a title ID, for example episodes or a movie, witho
| `profile` | string | no | Credential/cookie profile. |
| `proxy` | string | no | Full proxy URI on a public host, a Control D resolver as `controld://<resolver>@dns.controld.com`, or a country code when the API key has `server_proxy`. |
| `no_proxy` | boolean | no | Force-disable proxy. |
| `cdm_type` | string | no | Preferred CDM type. |
| `cdm_type` | string | no | Preferred CDM type. A request that sets one of the service's `SERVER_DEVICE_OPTIONS` ignores it: the server loads the first-listed device of its `cdm` entry. |
| `credentials`, `cookies`, `cache` | - | no | Your own login material, on a `--remote-only` server only. See [Client cache on a remote-only server](#client-cache-on-a-remote-only-server). |
You can also pass a service's own CLI options, in a nested `service_params` object or as
+5 -3
View File
@@ -2,9 +2,11 @@
import base64
import zlib
from types import SimpleNamespace
import pytest
from tests.remote.sessions import launch_session
from unshackle.core.api import handlers, key_policy
from unshackle.core.api.errors import APIError
from unshackle.core.api.handlers import load_client_cookies
@@ -52,12 +54,12 @@ def test_load_client_cookies_rejects_a_malformed_blob(blob):
@pytest.fixture
def built_ctx(monkeypatch):
"""Stub the service machinery so create_service_instance runs without a real service; return the captured ctx."""
"""Stub the service machinery so a session launch runs without a real service; return the captured ctx."""
seen = {}
def fake_instantiate(parent_ctx, *args):
seen["ctx"] = parent_ctx
return object()
return SimpleNamespace()
monkeypatch.setattr(key_policy, "load_service_config", lambda service: {})
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
@@ -65,7 +67,7 @@ def built_ctx(monkeypatch):
monkeypatch.setattr(handlers, "instantiate_service", fake_instantiate)
def build(data):
_, cookies, _ = handlers.create_service_instance("EXAMPLE", "title", data, None, [], None)
cookies = launch_session("EXAMPLE", "title", data).cookies
return seen["ctx"], cookies
return build
+3 -2
View File
@@ -19,6 +19,7 @@ import pytest
import unshackle.commands.dl as dl_module
from tests.admission import refusal
from tests.remote.sessions import launch_session
from tests.remote.unit.test_remote_service_helpers import _sent_create_data
from unshackle.core import mux_step
from unshackle.core.api import download_manager, handlers, key_policy
@@ -835,7 +836,7 @@ def test_a_remote_session_puts_the_flag_in_the_service_ctx(monkeypatch: pytest.M
def fake_instantiate(parent_ctx: Any, *args: Any) -> object:
seen["ctx"] = parent_ctx
return object()
return SimpleNamespace()
monkeypatch.setattr(key_policy, "load_service_config", lambda service: {})
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
@@ -843,7 +844,7 @@ def test_a_remote_session_puts_the_flag_in_the_service_ctx(monkeypatch: pytest.M
monkeypatch.setattr(handlers, "instantiate_service", fake_instantiate)
data = {"generate_dv": True} if to_dv else {}
handlers.create_service_instance("EXAMPLE", "title", data, None, [], None)
launch_session("EXAMPLE", "title", data)
assert seen["ctx"].params["generate_dv"] is to_dv
+5 -6
View File
@@ -10,6 +10,7 @@ from typing import Any
import click
import pytest
from tests.remote.sessions import launch_session
from unshackle.core.launch import LaunchKeys
pytestmark = pytest.mark.unit
@@ -81,7 +82,7 @@ def rest_relay(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> click.Context
def rest_list(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> click.Context:
handlers, seen = rest_handlers(monkeypatch)
handlers.setup_list_service({}, "EXAMPLE", None, "t")
handlers.launch_served(handlers.LIST, {}, "EXAMPLE", "t", None)
return seen["ctx"]
@@ -101,7 +102,7 @@ def rest_search(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> click.Contex
def rest_session(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> click.Context:
handlers, seen = rest_handlers(monkeypatch)
handlers.create_service_instance("EXAMPLE", "t", {}, None, [], None)
launch_session("EXAMPLE", "t", {})
return seen["ctx"]
@@ -167,11 +168,9 @@ def served_paths(monkeypatch: pytest.MonkeyPatch) -> dict[str, Callable[[dict],
return {
"relay": lambda data: handlers.relay_service(data, "server", None, "t").parent,
"list": lambda data: captured(lambda: handlers.setup_list_service(data, "EXAMPLE", None, "t")),
"list": lambda data: captured(lambda: handlers.launch_served(handlers.LIST, data, "EXAMPLE", "t", None)),
"search": lambda data: captured(lambda: handlers.run_service_search(data, "EXAMPLE", "query")),
"session": lambda data: captured(
lambda: handlers.create_service_instance("EXAMPLE", "t", data, None, [], None)
),
"session": lambda data: captured(lambda: launch_session("EXAMPLE", "t", data)),
}
+41
View File
@@ -1,8 +1,15 @@
"""A real remote session entry for the tests that call the session and licence handlers directly."""
from collections.abc import Callable
from types import SimpleNamespace
from typing import Any
import pytest
from unshackle.core.api import handlers, key_policy
from unshackle.core.api.handlers import Launched, SessionLaunch
from unshackle.core.api.input_bridge import InputBridge
from unshackle.core.api.key_policy import KeyPolicy
from unshackle.core.api.session_store import SessionEntry
from unshackle.core.remote_protocol import LicensingMode, Licensor
@@ -18,3 +25,37 @@ def session_entry(**fields: Any) -> SessionEntry:
**fields,
}
)
def session_launch(licensor: Licensor = Licensor.NO_DEVICE, **fields: Any) -> SessionLaunch:
"""The session purpose of ``launch_served``: no device and no server account, unless *fields* set another value."""
return SessionLaunch(
**{
"proxy": (None, []),
"policy": KeyPolicy.of(None),
"server_account": False,
"licensing": LicensingMode(licensor),
"input_bridge": InputBridge(),
"cache_dir": "_sessions/test/EXAMPLE",
**fields,
}
)
def launch_session(
service: str,
title: str,
data: dict,
profile: str | None = None,
licensor: Licensor = Licensor.NO_DEVICE,
**fields: Any,
) -> Launched:
"""``launch_served`` for a remote session of *service* with the :func:`session_launch` purpose."""
return handlers.launch_served(session_launch(licensor, **fields), data, service, title, profile)
def stub_service_build(monkeypatch: pytest.MonkeyPatch, build: Callable[[], Any]) -> None:
"""Make every served launch build its service with *build*, with no service config or CDM behind it."""
monkeypatch.setattr(key_policy, "load_service_config", lambda tag: {})
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: build())
+1 -1
View File
@@ -62,7 +62,7 @@ class _FakeService:
def run_list_tracks(monkeypatch: pytest.MonkeyPatch, titles: list[Episode], **data: Any) -> dict[str, Any]:
"""Drive list_tracks_handler end to end with the service layer stubbed out."""
monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: "FAKE")
monkeypatch.setattr(handlers, "setup_list_service", lambda *a, **kw: _FakeService(titles))
monkeypatch.setattr(handlers, "launch_served", lambda *a, **kw: handlers.Launched(_FakeService(titles), None, None))
payload = {"service": "FAKE", "title_id": "t1", **data}
try:
response = asyncio.run(handlers.list_tracks_handler(payload))
+4 -2
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import click
@@ -10,6 +11,7 @@ import pytest
import unshackle.commands.dl as dl_module
from tests.admission import refusal
from tests.remote.sessions import launch_session
from unshackle.core.api import download_manager, handlers, key_policy
from unshackle.core.services import Services
@@ -55,13 +57,13 @@ def session_params(monkeypatch: pytest.MonkeyPatch, data: dict) -> dict:
def fake_instantiate(parent_ctx: click.Context, *args: object) -> object:
seen["params"] = parent_ctx.params
return object()
return SimpleNamespace()
monkeypatch.setattr(key_policy, "load_service_config", lambda service: {})
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
monkeypatch.setattr(handlers.Services, "load", lambda service: None)
monkeypatch.setattr(handlers, "instantiate_service", fake_instantiate)
handlers.create_service_instance("EXAMPLE", "title", data, None, [], None)
launch_session("EXAMPLE", "title", data)
return seen["params"]
+4 -2
View File
@@ -168,7 +168,9 @@ class _FakeService:
@pytest.mark.parametrize("wanted", [None, "S01"], ids=["one-title", "episodes"])
def test_list_tracks_stamps_the_service_flags(monkeypatch: pytest.MonkeyPatch, wanted: str | None) -> None:
monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: "FAKE")
monkeypatch.setattr(handlers, "setup_list_service", lambda *a, **kw: _FakeService([ep(), ep(number=2)]))
monkeypatch.setattr(
handlers, "launch_served", lambda *a, **kw: handlers.Launched(_FakeService([ep(), ep(number=2)]), None, None)
)
response = asyncio.run(handlers.list_tracks_handler({"service": "FAKE", "title_id": "t1", "wanted": wanted}))
body = json.loads(response.body)
titles = [e["title"] for e in body["episodes"]] if wanted else [body["title"]]
@@ -178,7 +180,7 @@ def test_list_tracks_stamps_the_service_flags(monkeypatch: pytest.MonkeyPatch, w
def test_list_titles_stamps_the_service_flags(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: "FAKE")
monkeypatch.setattr(handlers, "setup_list_service", lambda *a, **kw: _FakeService([ep()]))
monkeypatch.setattr(handlers, "launch_served", lambda *a, **kw: handlers.Launched(_FakeService([ep()]), None, None))
response = asyncio.run(handlers.list_titles_handler({"service": "FAKE", "title_id": "t1"}))
title = json.loads(response.body)["titles"][0]
assert (title["anime"], title["daily"]) == (True, True)
+8 -20
View File
@@ -14,7 +14,7 @@ import pytest
from pywidevine import DeviceTypes
from pywidevine.pssh import PSSH
from tests.remote.sessions import session_entry
from tests.remote.sessions import launch_session, session_entry
from unshackle.core.api import handlers, key_policy, server_keys
from unshackle.core.api.errors import APIError
from unshackle.core.api.input_bridge import InputBridge
@@ -178,7 +178,7 @@ def test_a_relaying_client_gets_a_stand_in_with_its_device_facts(monkeypatch: py
lambda obj, plan, keys: built.update(cdm=obj.cdm, config=obj.config, params={**plan.params, **keys}),
)
monkeypatch.setattr(handlers.Services, "load", lambda tag: Declares)
monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: "service")
monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: SimpleNamespace())
data = {
"cdm_type": "widevine",
@@ -189,7 +189,7 @@ def test_a_relaying_client_gets_a_stand_in_with_its_device_facts(monkeypatch: py
"service_config": {"esn": "CLIENT"},
}
bridge = InputBridge()
handlers.create_service_instance("EXAMPLE1", "t", data, None, [], None, client_device=True, input_bridge=bridge)
launch_session("EXAMPLE1", "t", data, licensor=Licensor.CLIENT_DEVICE, input_bridge=bridge)
cdm = built["cdm"]
assert isinstance(cdm, ClientDeviceCdm)
@@ -339,12 +339,10 @@ def test_a_lent_device_gives_the_service_the_server_config_back(monkeypatch: pyt
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: server_device)
monkeypatch.setattr(handlers, "served_context", lambda obj, *a: built.update(cdm=obj.cdm, config=obj.config))
monkeypatch.setattr(handlers.Services, "load", lambda tag: Declares)
monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: "service")
monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: SimpleNamespace())
data = {"cdm_type": "widevine", "cdm_relay": True, "service_config": {"esn": "CLIENT", "esn_map": {"1": "c"}}}
handlers.create_service_instance(
"EXAMPLE1", "t", data, None, [], None, client_device=True, input_bridge=InputBridge()
)
launch_session("EXAMPLE1", "t", data, licensor=Licensor.CLIENT_DEVICE)
service_config = built["config"]
assert service_config["esn"] == "CLIENT"
@@ -382,20 +380,10 @@ def test_a_server_device_option_takes_the_first_listed_device_of_a_dual_entry(
monkeypatch.setattr("unshackle.core.cdm.load_cdm", lambda name, **k: devices.append(name))
monkeypatch.setattr(handlers, "served_context", lambda obj, *a: built.update(cdm=obj.cdm))
monkeypatch.setattr(handlers.Services, "load", lambda tag: ServerSideService)
monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: "service")
monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: SimpleNamespace())
data = {"cdm_type": client_type, "cdm_relay": True, "service_params": {"server_side": server_side}}
handlers.create_service_instance(
"EXAMPLE1",
"t",
data,
None,
[],
None,
server_cdm=not client_device,
client_device=client_device,
input_bridge=InputBridge(),
)
launch_session("EXAMPLE1", "t", data, licensor=Licensor.CLIENT_DEVICE if client_device else Licensor.SERVER_CDM)
if client_device:
built["cdm"].lend_server_device()
assert devices == [loaded]
@@ -424,7 +412,7 @@ def test_a_track_listing_with_a_server_device_option_ignores_the_client_system(
monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: service)
data = {"cdm_type": "widevine", "service_params": {"server_side": server_side}}
handlers.setup_list_service(data, "EXAMPLE1", None, "t")
handlers.launch_served(handlers.LIST, data, "EXAMPLE1", "t", None)
assert loaded == [cdm_type]
+1 -1
View File
@@ -93,7 +93,7 @@ async def test_list_tracks_leaves_the_loop_free(monkeypatch: pytest.MonkeyPatch)
handshake = Handshake()
service = BlockingTracks(handshake)
monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: "EXAMPLE")
monkeypatch.setattr(handlers, "setup_list_service", lambda *args, **kwargs: service)
monkeypatch.setattr(handlers, "launch_served", lambda *args, **kwargs: handlers.Launched(service, None, None))
data = {"service": "EXAMPLE", "title_id": "movie-0001"}
response = await handshake.drive(lambda: handlers.list_tracks_handler(data))
@@ -6,6 +6,7 @@ from types import SimpleNamespace
import pytest
from tests.remote.sessions import stub_service_build
from unshackle.core.api import handlers, job_admission, key_policy
from unshackle.core.api.errors import APIError
from unshackle.core.remote_protocol import APIErrorCode
@@ -166,7 +167,7 @@ def test_non_string_client_region_rejected(monkeypatch, key):
assert exc_info.value.error_code == APIErrorCode.INVALID_INPUT
def test_setup_list_service_threads_request(monkeypatch):
def test_a_list_launch_threads_the_request(monkeypatch):
"""A regression that stops passing the request through would re-open the proxy gate."""
seen = {}
@@ -187,7 +188,7 @@ def test_setup_list_service_threads_request(monkeypatch):
monkeypatch.setattr("unshackle.core.login.get_credentials", lambda service, profile: None)
req = request("plainkey")
handlers.setup_list_service({}, "EXAMPLE", None, "some-title", req)
handlers.launch_served(handlers.LIST, {}, "EXAMPLE", "some-title", None, req)
assert seen["request"] is req
assert seen["authenticated"]
@@ -359,7 +360,7 @@ def test_session_create_builds_service_off_the_event_loop(monkeypatch):
monkeypatch.setattr(handlers, "server_account_for", lambda *args: False)
monkeypatch.setattr(handlers.Services, "load", lambda service: type("SlowProxySvc", (), {}))
monkeypatch.setattr(handlers, "SessionLogBuffer", RecordingBuffer)
monkeypatch.setattr(handlers, "create_service_instance", failed_check)
stub_service_build(monkeypatch, failed_check)
response = asyncio.run(handlers.session_create_handler({"service": "EXAMPLE", "title_id": "t"}))
+5 -2
View File
@@ -8,6 +8,7 @@ from types import SimpleNamespace
import pytest
from tests.remote.sessions import stub_service_build
from unshackle.core.api import handlers, job_admission, key_policy, server_keys
from unshackle.core.api.errors import APIError
from unshackle.core.api.key_policy import KeyPolicy
@@ -142,7 +143,8 @@ def test_a_session_keeps_identity_keys_from_the_client_unless_the_identity_is_th
monkeypatch.setattr(handlers, "request_policy", lambda request: user)
monkeypatch.setattr(handlers, "choose_session_cdm", lambda *args: (server_cdm, None))
monkeypatch.setattr(handlers.Services, "load", lambda service: Service)
monkeypatch.setattr(handlers, "create_service_instance", lambda *args, **kwargs: (Service(), None, None))
stub_service_build(monkeypatch, Service)
monkeypatch.setattr(handlers, "load_client_cookies", lambda text: text)
async def run():
data = {"service": "EXAMPLE", "title_id": "t", "cookies": "x", "cache": {"keys/planted": text}, **sent}
@@ -177,7 +179,8 @@ def test_a_service_on_the_lent_device_makes_a_lent_device_session(server, monkey
monkeypatch.setattr(handlers, "request_policy", lambda request: KeyPolicy({"server_vault": True}))
monkeypatch.setattr(handlers, "choose_session_cdm", lambda *args: (False, None))
monkeypatch.setattr(handlers.Services, "load", lambda service: Service)
monkeypatch.setattr(handlers, "create_service_instance", lambda *args, **kwargs: (Service(), "x", None))
stub_service_build(monkeypatch, Service)
monkeypatch.setattr(handlers, "load_client_cookies", lambda text: text)
async def run():
data = {"service": "EXAMPLE", "title_id": "t", "cookies": "x", "cdm_type": "widevine", "cdm_relay": True}
+177
View File
@@ -0,0 +1,177 @@
"""``launch_served``: the one build of a served service, with the rules its purpose picks."""
from __future__ import annotations
from types import SimpleNamespace
from typing import Any
import click
import pytest
from tests.remote.sessions import session_launch
from unshackle.core.api import handlers, key_policy
from unshackle.core.api.errors import APIError
from unshackle.core.api.input_bridge import NoUserBridge
from unshackle.core.api.stats import stats
from unshackle.core.remote_protocol import APIErrorCode, Licensor
pytestmark = pytest.mark.unit
@click.command()
@click.option("--server-side", is_flag=True, default=False)
def server_side_cli(server_side: bool) -> None: ...
class ServerSideModule:
SERVER_DEVICE_OPTIONS = ("server_side",)
cli = server_side_cli
class Built:
def __init__(self) -> None:
self.logins: list[tuple[Any, Any]] = []
def authenticate(self, cookies: Any, credential: Any) -> None:
self.logins.append((cookies, credential))
@pytest.fixture
def seen(monkeypatch: pytest.MonkeyPatch, tmp_path: Any) -> dict[str, Any]:
"""Stub everything around the launch and record what it asked for."""
record: dict[str, Any] = {"cdm_types": []}
monkeypatch.setattr(handlers.config.directories, "cache", tmp_path)
monkeypatch.setattr(stats, "mode", "full")
monkeypatch.setattr(key_policy, "load_service_config", lambda tag: {})
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *a: (None, []))
monkeypatch.setattr(handlers, "resolve_server_account", lambda *a: None)
monkeypatch.setattr(
handlers, "load_full_cdm", lambda service, profile, cdm_type, cfg: record["cdm_types"].append(cdm_type)
)
monkeypatch.setattr(handlers.Services, "load", lambda tag: ServerSideModule)
monkeypatch.setattr(handlers, "server_account_cookies", lambda *a: "account-jar")
monkeypatch.setattr("unshackle.core.login.get_cookie_jar", lambda *a: "server-jar")
monkeypatch.setattr("unshackle.core.login.get_credentials", lambda *a: "server-credential")
def instantiate(parent_ctx: click.Context, module: Any, title: str, *rest: Any) -> Built:
record["keys"] = rest[1] if rest else None
return Built()
monkeypatch.setattr(handlers, "instantiate_service", instantiate)
return record
PURPOSES = {
"list": lambda: handlers.LIST,
"search": lambda: handlers.SEARCH,
"session": lambda: session_launch(),
"server-cdm session": lambda: session_launch(Licensor.SERVER_CDM),
}
@pytest.mark.parametrize(
("purpose", "server_side", "asked"),
[
("list", False, "widevine"),
("list", True, None),
("search", False, "widevine"),
("search", True, None),
("session", True, "widevine"),
("server-cdm session", False, None),
],
)
def test_the_purpose_picks_the_cdm_rule(seen: dict, purpose: str, server_side: bool, asked: str | None) -> None:
data = {"cdm_type": "widevine", "service_params": {"server_side": server_side}}
handlers.launch_served(PURPOSES[purpose](), data, "EXAMPLE", "t", None)
assert seen["cdm_types"] == [asked]
def test_a_server_cdm_session_follows_the_client_only_on_a_dual_entry(seen: dict, monkeypatch) -> None:
monkeypatch.setattr(handlers.config, "cdm", {"EXAMPLE": {"widevine": "wv", "playready": "pr"}}, raising=False)
for server_side in (False, True):
data = {"cdm_type": "widevine", "service_params": {"server_side": server_side}}
handlers.launch_served(session_launch(Licensor.SERVER_CDM), data, "EXAMPLE", "t", None)
assert seen["cdm_types"] == ["widevine", None]
@pytest.mark.parametrize(
("purpose", "mode", "login"),
[
("list", "full", ("server-jar", "server-credential")),
("list", "remote_only", (None, None)),
("search", "full", ("server-jar", "server-credential")),
("session", "full", (None, None)),
],
)
def test_the_purpose_picks_the_login_material(
seen: dict, monkeypatch: pytest.MonkeyPatch, purpose: str, mode: str, login: tuple
) -> None:
monkeypatch.setattr(stats, "mode", mode)
launched = handlers.launch_served(PURPOSES[purpose](), {}, "EXAMPLE", "t", None)
assert (launched.cookies, launched.credential) == login
@pytest.mark.parametrize("purpose", ["list", "search"])
def test_a_server_account_takes_its_own_files_and_cache(seen: dict, monkeypatch, purpose: str) -> None:
monkeypatch.setattr(handlers, "resolve_server_account", lambda *a: "acct")
launched = handlers.launch_served(PURPOSES[purpose](), {}, "EXAMPLE", "t", None)
assert (launched.cookies, launched.service.cache.service_tag) == ("account-jar", "_accounts/EXAMPLE/acct")
def test_a_session_on_a_server_account_takes_its_own_files_and_cache(seen: dict) -> None:
purpose = session_launch(server_account=True)
launched = handlers.launch_served(purpose, {"cookies": "client"}, "EXAMPLE", "t", "work")
assert (launched.cookies, launched.service.cache.service_tag) == ("account-jar", "_accounts/EXAMPLE/work")
def test_a_session_runs_on_its_own_cache_and_bridge_and_logs_in_later(seen: dict) -> None:
purpose = session_launch()
launched = handlers.launch_served(purpose, {}, "EXAMPLE", "t", None)
assert launched.service.cache.service_tag == purpose.cache_dir
assert launched.service._input_bridge is purpose.input_bridge
assert launched.service.logins == []
assert launched.licensing == purpose.licensing
assert seen["keys"] == handlers.SESSION_TRANSPORT_KEYS
@pytest.mark.parametrize(("purpose", "keys"), [("list", handlers.LIST_HANDLER_TRANSPORT_KEYS), ("search", None)])
def test_a_list_or_search_logs_in_with_no_user(seen: dict, purpose: str, keys: set | None) -> None:
launched = handlers.launch_served(PURPOSES[purpose](), {}, "EXAMPLE", "t", None)
assert isinstance(launched.service._input_bridge, NoUserBridge)
assert launched.service.logins == [("server-jar", "server-credential")]
assert seen["keys"] == keys
def test_an_anonymous_search_skips_the_login(seen: dict, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(ServerSideModule, "ANONYMOUS_SEARCH", True, raising=False)
launched = handlers.launch_served(handlers.SEARCH, {}, "EXAMPLE", "q", None)
assert (launched.cookies, launched.service.logins) == (None, [])
def test_only_a_search_maps_a_failed_build_to_a_service_error(seen: dict, monkeypatch: pytest.MonkeyPatch) -> None:
def broken(*a: Any) -> Any:
raise RuntimeError("boom")
monkeypatch.setattr(handlers, "instantiate_service", broken)
with pytest.raises(APIError) as exc:
handlers.launch_served(handlers.SEARCH, {}, "EXAMPLE", "q", None)
assert exc.value.error_code is APIErrorCode.SERVICE_ERROR
with pytest.raises(RuntimeError):
handlers.launch_served(handlers.LIST, {}, "EXAMPLE", "t", None)
def test_a_lent_device_turns_the_session_licensing_lent(seen: dict, monkeypatch: pytest.MonkeyPatch) -> None:
lent = Built()
lent.ctx = SimpleNamespace(obj=SimpleNamespace(cdm=SimpleNamespace(lent=True))) # type: ignore[attr-defined]
monkeypatch.setattr(handlers, "instantiate_service", lambda *a: lent)
launched = handlers.launch_served(session_launch(Licensor.CLIENT_DEVICE), {}, "EXAMPLE", "t", None)
assert launched.licensing is not None and launched.licensing.licensor is Licensor.LENT_DEVICE
@pytest.mark.parametrize(("licensor", "routed"), [(Licensor.NO_DEVICE, True), (Licensor.CLIENT_DEVICE, False)])
def test_a_session_keeps_identity_keys_apart_unless_the_identity_is_the_clients(
seen: dict, monkeypatch: pytest.MonkeyPatch, licensor: Licensor, routed: bool
) -> None:
monkeypatch.setattr(Built, "IDENTITY_CACHE", ("keys/",), raising=False)
launched = handlers.launch_served(session_launch(licensor), {}, "EXAMPLE", "t", None)
assert (launched.service.cache.route is not None) is routed
+2 -1
View File
@@ -21,6 +21,7 @@ import requests
from aiohttp import web
from langcodes import Language
from tests.remote.sessions import stub_service_build
from tests.remote.unit.test_tunnel import wait_until
from unshackle.core import remote_channel, remote_service
from unshackle.core.api import handlers, routes, session_store
@@ -153,7 +154,7 @@ def server(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch, tmp_
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, []))
monkeypatch.setattr(handlers, "server_account_for", lambda *args: False)
monkeypatch.setattr(handlers.Services, "load", lambda service: StubService)
monkeypatch.setattr(handlers, "create_service_instance", lambda *a, **k: (StubService(beats), None, None))
stub_service_build(monkeypatch, lambda: StubService(beats))
app = web.Application(middlewares=[record, cors_middleware, no_5xx_middleware, api_key_authentication])
app["config"] = {"users": [KEY]}
@@ -8,7 +8,7 @@ from enum import Enum
import pytest
from tests.remote.sessions import session_entry
from tests.remote.sessions import session_entry, stub_service_build
from unshackle.core.manifests.snapshot import match_track
from unshackle.core.remote_service import RemoteService
from unshackle.core.titles.episode import Episode
@@ -682,11 +682,7 @@ def test_a_session_create_that_fails_after_the_cache_write_leaves_no_cache_dir(t
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, []))
monkeypatch.setattr(handlers, "server_account_for", lambda *args: False)
monkeypatch.setattr(handlers.Services, "load", lambda service: type("Svc", (), {}))
monkeypatch.setattr(
handlers,
"create_service_instance",
lambda *args, **kwargs: (SimpleNamespace(log=logging.getLogger("Svc")), None, None),
)
stub_service_build(monkeypatch, lambda: SimpleNamespace(log=logging.getLogger("Svc")))
monkeypatch.setattr("unshackle.core.api.session_store.refuse_while_draining", lambda: None)
class RefusingStore:
@@ -247,7 +247,7 @@ def fault_cases() -> dict[str, Case]:
"POST",
SESSION_CREATE_ROUTE,
BODIES[SESSION_CREATE_ROUTE],
patch={"resolve_handler_proxy": lambda *args: (None, None), "create_service_instance": Faulty(kind).fail},
patch={"resolve_handler_proxy": lambda *args: (None, None), "launch_served": Faulty(kind).fail},
)
cases["license unhashable track"] = Case(
"POST", fill(LICENSE_ROUTE), {"track_id": ["v1"], "challenge": "AAAA"}, session=Faulty()
+14 -11
View File
@@ -1,5 +1,8 @@
from types import SimpleNamespace
import pytest
from tests.remote.sessions import launch_session
from unshackle.core.api import handlers, key_policy
from unshackle.core.api.errors import APIError
@@ -74,9 +77,10 @@ def test_client_managed_gets_nothing(monkeypatch, accounts):
monkeypatch.setattr(key_policy, "load_service_config", lambda s: {})
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: object()))
monkeypatch.setattr(handlers, "instantiate_service", lambda *a: "svc")
svc, cookies, cred = handlers.create_service_instance("OTHER", "t", {}, None, [], None)
assert (svc, cookies, cred) == ("svc", None, None)
built = SimpleNamespace()
monkeypatch.setattr(handlers, "instantiate_service", lambda *a: built)
svc, cookies, cred, _ = launch_session("OTHER", "t", {})
assert (svc, cookies, cred) == (built, None, None)
def test_per_key_gate(accounts, monkeypatch):
@@ -100,10 +104,10 @@ def test_server_account_ignores_client_credentials(monkeypatch, accounts):
monkeypatch.setattr(key_policy, "load_service_config", lambda s: {})
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: object()))
monkeypatch.setattr(handlers, "instantiate_service", lambda *a: "svc")
monkeypatch.setattr(handlers, "instantiate_service", lambda *a: SimpleNamespace())
monkeypatch.setattr(handlers, "server_account_cookies", lambda s, p: "server-jar")
data = {"credentials": {"username": "old", "password": "client"}, "cookies": "AAAA", "cache": {"x": "y"}}
svc, cookies, cred = handlers.create_service_instance("EX", "t", data, None, [], "ca_main", server_account=True)
_, cookies, cred, _ = launch_session("EX", "t", data, "ca_main", server_account=True)
assert cookies == "server-jar"
assert cred.username == "a" and cred.password == "b"
@@ -124,10 +128,10 @@ def test_server_cdm_ignores_client_cdm_type(monkeypatch):
monkeypatch.setattr(key_policy, "load_service_config", lambda s: {})
monkeypatch.setattr(handlers, "load_full_cdm", lambda s, p, t=None, app_config=None: seen.append(t))
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: object()))
monkeypatch.setattr(handlers, "instantiate_service", lambda *a: "svc")
monkeypatch.setattr(handlers, "instantiate_service", lambda *a: SimpleNamespace())
data = {"cdm_type": "playready"}
handlers.create_service_instance("OTHER", "t", data, None, [], None, server_cdm=True)
handlers.create_service_instance("OTHER", "t", data, None, [], None)
launch_session("OTHER", "t", data, licensor=handlers.Licensor.SERVER_CDM)
launch_session("OTHER", "t", data)
assert seen == [None, "playready"]
@@ -154,8 +158,7 @@ def _create_with_real_ctx(monkeypatch, data):
monkeypatch.setattr(key_policy, "load_service_config", lambda s: {})
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: _lang_option_module()))
svc, _, _ = handlers.create_service_instance("OTHER", "t", data, None, [], None)
return svc
return launch_session("OTHER", "t", data).service
DL_DEFAULTS = {
@@ -230,5 +233,5 @@ def test_profile_reaches_the_parent_ctx_params(monkeypatch):
monkeypatch.setattr(key_policy, "load_service_config", lambda s: {})
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: _lang_option_module()))
svc, _, _ = handlers.create_service_instance("OTHER", "t", {}, None, [], "work")
svc = launch_session("OTHER", "t", {}, "work").service
assert svc.parent_params["profile"] == "work"
@@ -13,7 +13,7 @@ import pywidevine.pssh as wv_pssh_mod
import unshackle.core.drm as drm_mod
from tests.core.key_resolver import key_table, resolver
from tests.remote.key_source import CAPPED, PR_DEVICE, MemoryKeySource, one_title, remote_session
from tests.remote.sessions import session_entry
from tests.remote.sessions import launch_session, session_entry
from unshackle.commands.dl import dl
from unshackle.core import remote_channel
from unshackle.core.api import handlers, job_admission, key_policy, server_keys
@@ -345,10 +345,10 @@ def test_a_client_device_session_builds_the_service_on_a_stub_of_that_device(mon
monkeypatch.setattr(handlers, "load_full_cdm", no_server_device)
monkeypatch.setattr(handlers, "served_context", lambda obj, *a: built.update(cdm=obj.cdm))
monkeypatch.setattr(handlers.Services, "load", lambda tag: object)
monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: "service")
monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: SimpleNamespace())
data = {"cdm_type": "playready", "cdm_security_level": 3000}
handlers.create_service_instance("EXAMPLE1", "t", data, None, [], None, client_device=True)
launch_session("EXAMPLE1", "t", data, licensor=Licensor.CLIENT_DEVICE)
assert built["cdm"].is_playready is True
assert built["cdm"].security_level == 3000
@@ -19,7 +19,7 @@ import pywidevine.pssh as wv_pssh_mod
import unshackle.core.cdm as cdm_mod
import unshackle.core.cdm.detect as detect_mod
import unshackle.core.drm as drm_mod
from tests.remote.sessions import session_entry
from tests.remote.sessions import launch_session, session_entry
from unshackle.core.api import handlers, key_policy, server_keys
from unshackle.core.api.errors import APIError
from unshackle.core.api.key_policy import KeyPolicy
@@ -245,9 +245,10 @@ def test_the_server_device_follows_the_client_only_when_both_systems_are_mapped(
handlers, "load_full_cdm", lambda service, profile, cdm_type, app_config=None: asked.append(cdm_type)
)
monkeypatch.setattr(handlers.Services, "load", lambda tag: object)
monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: "service")
monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: SimpleNamespace())
handlers.create_service_instance("EXAMPLE1", "t", {"cdm_type": "playready"}, None, [], None, server_cdm=server_cdm)
licensor = Licensor.SERVER_CDM if server_cdm else Licensor.NO_DEVICE
launch_session("EXAMPLE1", "t", {"cdm_type": "playready"}, licensor=licensor)
assert asked == [wanted]
+2 -1
View File
@@ -7,6 +7,7 @@ from typing import Any
import pytest
from tests.remote.sessions import stub_service_build
from unshackle.core.api import session_store as store_mod
from unshackle.core.api.handlers import session_tracks_handler
from unshackle.core.api.server_keys import find_title_for_track
@@ -168,7 +169,7 @@ def test_the_create_event_carries_the_session_as_created(monkeypatch: pytest.Mon
monkeypatch.setattr(handlers, "server_account_for", lambda *args: False)
monkeypatch.setattr(handlers, "choose_session_cdm", lambda *args: (True, 1080))
monkeypatch.setattr(handlers.Services, "load", lambda service: Service)
monkeypatch.setattr(handlers, "create_service_instance", lambda *a, **k: (Service(), None, None))
stub_service_build(monkeypatch, Service)
async def run() -> list:
mark = bus.seq
+3 -3
View File
@@ -3,7 +3,7 @@ from types import SimpleNamespace
import pytest
import requests
from tests.remote.sessions import session_entry
from tests.remote.sessions import session_entry, stub_service_build
from unshackle.core.api import server_keys
from unshackle.core.api.errors import APIError
from unshackle.core.api.handlers import client_session_auth, resolve_handler_proxy, scrub_track_data
@@ -354,7 +354,7 @@ def _run_session(monkeypatch, tmp_path, data, answer, server_account=False, fail
monkeypatch.setattr(handlers, "server_account_for", lambda *args: server_account)
monkeypatch.setattr(handlers, "next_server_profile", lambda *args: None)
monkeypatch.setattr(handlers.Services, "load", lambda service: PromptingService)
monkeypatch.setattr(handlers, "create_service_instance", lambda *a, **k: (PromptingService(), None, None))
stub_service_build(monkeypatch, PromptingService)
if data.get("cache") == "tokens":
data["cache"] = {"tokens_default": base64.b64encode(zlib.compress(b"{}")).decode("ascii")}
@@ -440,7 +440,7 @@ def test_login_that_outlives_its_session_leaves_no_cache(monkeypatch, tmp_path):
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, []))
monkeypatch.setattr(handlers, "server_account_for", lambda *args: False)
monkeypatch.setattr(handlers.Services, "load", lambda service: SlowPairingService)
monkeypatch.setattr(handlers, "create_service_instance", lambda *a, **k: (SlowPairingService(), None, None))
stub_service_build(monkeypatch, SlowPairingService)
async def run():
resp = await handlers.session_create_handler({"service": "EXAMPLE", "title_id": "t"})
+149 -203
View File
@@ -17,7 +17,7 @@ from dataclasses import dataclass, field
from functools import partial
from http.cookiejar import CookieJar
from pathlib import Path
from typing import Any, Optional
from typing import Any, Final, Literal, NamedTuple, Optional
from urllib.parse import urlsplit
import click
@@ -241,19 +241,19 @@ def instantiate_service(
def server_login_material(
data: dict[str, Any], normalized_service: str, account: str | None, profile: str | None
data: dict[str, Any], normalized_service: str, account: str | None, profile: str | None, client_only: bool = False
) -> tuple:
"""(cookies, credential) for a list or search call.
"""(cookies, credential) for a served service.
A lent account takes the server's files for that account. Otherwise the full-mode server,
which the operator's own UI drives, uses its own profiles; a ``--remote-only`` server uses only
what the client sent, the same rule as a remote session.
A lent account takes the server's files for that account. Otherwise only what the client sent counts
for a remote session (``client_only``) and on a ``--remote-only`` server; a full-mode list or search,
which the operator's own UI drives, uses the server's own profiles.
"""
from unshackle.core.api.stats import stats
if account:
return server_account_cookies(normalized_service, profile), login.get_credentials(normalized_service, profile)
if stats.mode != "remote_only":
if not client_only and stats.mode != "remote_only":
return login.get_cookie_jar(normalized_service, profile), login.get_credentials(normalized_service, profile)
return load_client_cookies(data.get("cookies")), client_credential(data)
@@ -768,52 +768,151 @@ def remote_search(data: dict[str, Any], server: str, query: str, request: web.Re
return {"results": results, "count": len(results)}
def setup_list_service(
LIST: Final = "list"
SEARCH: Final = "search"
@dataclass(frozen=True)
class SessionLaunch:
"""What a remote session chose before its service is built: the session purpose of :func:`launch_served`."""
proxy: tuple[str | None, list]
policy: KeyPolicy
server_account: bool
licensing: LicensingMode
input_bridge: InputBridge
cache_dir: str
class Launched(NamedTuple):
"""A served service, the login material it authenticates with, and the licensing of a remote session after the build."""
service: Any
cookies: Any
credential: Any
licensing: LicensingMode | None = None
def launch_served(
purpose: Literal["list", "search"] | SessionLaunch,
data: dict[str, Any],
normalized_service: str,
service: str,
title: str,
profile: str | None,
title_id: str,
request: web.Request | None = None,
request_cache: RequestCache | None = None,
) -> Any:
"""Assemble and authenticate a service instance for list_titles / list_tracks.
) -> Launched:
"""Build the service that ``data`` asks for, for a list, a search or a remote session.
Runs the shared preamble: load yaml → get proxy → load CDM → assemble ctx →
instantiate → authenticate. Raises APIError on proxy failure.
The purpose picks the CDM rule, the login material, the cache and the transport keys. A list or search
service comes back authenticated; a remote session authenticates later, when the client can answer its prompts.
"""
session = purpose if isinstance(purpose, SessionLaunch) else None
api_key = caller_key(request)
policy = request_policy(request)
service_config = policy.service_yaml(normalized_service)
policy = session.policy if session else request_policy(request)
server_config = service_config = policy.service_yaml(service)
proxy_param, proxy_providers = session.proxy if session else resolve_handler_proxy(data, service, request)
proxy_param, proxy_providers = resolve_handler_proxy(data, normalized_service, request)
account = resolve_server_account(policy, normalized_service, data.get("client_region"))
if session:
account = (profile or "default") if session.server_account else None
else:
account = resolve_server_account(policy, service, data.get("client_region"))
if account:
profile = None if account == "default" else account
service_module = Services.load(normalized_service)
cdm_type = None if server_device_requested(service_module, data) else data.get("cdm_type")
cdm = load_full_cdm(normalized_service, profile, cdm_type, policy.cdm_config())
cookies, credential = server_login_material(data, normalized_service, account, profile)
service_module = Services.load(service)
key_config = policy.cdm_config()
licensing = session.licensing if session else None
client_identity = False
cdm: Any
if session and session.licensing.client_device:
client_config = getattr(service_module, "CLIENT_CONFIG", ())
if client_config:
service_config, client_identity = client_config_overlay(
server_config, client_config, data.get("service_config")
)
def lend_server_device() -> Any:
"""The server's device, with the server's own config back in the dict the service holds as ``self.config``."""
if service_config is not server_config:
service_config.clear()
service_config.update(server_config)
return load_full_cdm(service, profile, None, key_config)
cdm = client_device_cdm(data, session.input_bridge, lend_server_device)
else:
if session is None:
follows_client = not server_device_requested(service_module, data)
elif session.licensing.server_cdm:
follows_client = choose_cdm(key_config.cdm, service).both and not server_device_requested(
service_module, data
)
else:
follows_client = True
cdm = load_full_cdm(service, profile, data.get("cdm_type") if follows_client else None, key_config)
anonymous = purpose == SEARCH and getattr(service_module, "ANONYMOUS_SEARCH", False)
cookies, credential = (
(None, None) if anonymous else server_login_material(data, service, account, profile, session is not None)
)
keys: LaunchKeys = {"cookies_supplied": cookies is not None}
if session:
# A service with CLIENT_CONFIG reads client_device and client_identity: with client_identity it uses
# only what the client sent, and without it the server's identity, whose keys then come only from a vault.
keys["client_device"] = session.licensing.client_device
keys["client_identity"] = client_identity
parent_ctx = served_parent(
ContextData(config=service_config, cdm=cdm, proxy_providers=proxy_providers, profile=profile),
data,
{"cookies_supplied": cookies is not None},
keys,
proxy_param,
# Services key their token caches on this. A list or search leaves it out: it shares the server's
# cache, where a session runs on a cache directory of its own.
profile if session else None,
SESSION_TRANSPORT_KEYS if session else frozenset(),
)
service_instance = instantiate_service(parent_ctx, service_module, title_id, data, LIST_HANDLER_TRANSPORT_KEYS)
if purpose == SEARCH:
try:
service_instance = instantiate_service(parent_ctx, service_module, title)
except (ConnectionError, click.ClickException) as exc:
raise categorize_exception(exc, {"service": service}) from exc
except Exception as exc:
raise APIError(
APIErrorCode.SERVICE_ERROR, f"Failed to initialize service: {exc}", details={"service": service}
) from exc
else:
transport_keys = SESSION_TRANSPORT_KEYS if session else LIST_HANDLER_TRANSPORT_KEYS
service_instance = instantiate_service(parent_ctx, service_module, title, data, transport_keys)
if session:
# the service asked for the server's device in __init__, so the session never licenses live
stand_in = getattr(getattr(getattr(service_instance, "ctx", None), "obj", None), "cdm", None)
if getattr(stand_in, "lent", False) is True:
licensing = session.licensing.lent()
if account:
account_tag = f"_accounts/{normalized_service}/{account}"
service_instance.cache = keyed_cache(account_tag, service_instance, normalized_service, api_key, policy)
account_tag = f"_accounts/{service}/{account}"
service_instance.cache = keyed_cache(account_tag, service_instance, service, api_key, policy)
elif session and licensing:
service_instance.cache = keyed_cache(
session.cache_dir,
service_instance,
service,
api_key,
policy,
temporary=True,
client_identity=licensing.client_identity,
)
elif request_cache is not None:
client_login = cookies is not None or credential is not None
request_cache.attach(service_instance, data, normalized_service, request, client_login, policy)
service_instance._input_bridge = NoUserBridge()
request_cache.attach(service_instance, data, service, request, client_login, policy)
service_instance._input_bridge = session.input_bridge if session else NoUserBridge()
if not session and not anonymous:
service_instance.authenticate(cookies, credential)
return service_instance
return Launched(service_instance, cookies, credential, licensing)
def run_service_search(
@@ -823,63 +922,13 @@ def run_service_search(
request: web.Request | None = None,
request_cache: RequestCache | None = None,
) -> list[dict[str, Any]]:
"""Assemble and authenticate a service instance, then run its search.
The same preamble as :func:`setup_list_service`, without the service option extras,
plus the search itself. Every step blocks on disk or network, so the caller runs the
whole function in one worker thread and keeps the event loop free for other clients.
"""Launch the service for a search and run it, in one worker thread, so the event loop stays free.
The server account check and its cache directory apply to an ``ANONYMOUS_SEARCH`` service too.
"""
profile = client_profile(data)
api_key = caller_key(request)
policy = request_policy(request)
service_config = policy.service_yaml(normalized_service)
proxy_param, proxy_providers = resolve_handler_proxy(data, normalized_service, request)
account = resolve_server_account(policy, normalized_service, data.get("client_region"))
if account:
profile = None if account == "default" else account
cdm = load_full_cdm(normalized_service, profile, data.get("cdm_type"), policy.cdm_config())
service_module = Services.load(normalized_service)
anonymous = getattr(service_module, "ANONYMOUS_SEARCH", False)
cookies, credential = (
(None, None) if anonymous else server_login_material(data, normalized_service, account, profile)
)
parent_ctx = served_parent(
ContextData(config=service_config, cdm=cdm, proxy_providers=proxy_providers, profile=profile),
data,
{"cookies_supplied": cookies is not None},
proxy_param,
)
from click import ClickException
try:
service_instance = instantiate_service(parent_ctx, service_module, query)
except (ConnectionError, ClickException) as exc:
raise categorize_exception(exc, {"service": normalized_service}) from exc
except Exception as exc:
raise APIError(
APIErrorCode.SERVICE_ERROR,
f"Failed to initialize service: {exc}",
details={"service": normalized_service},
) from exc
if account:
account_tag = f"_accounts/{normalized_service}/{account}"
service_instance.cache = keyed_cache(account_tag, service_instance, normalized_service, api_key, policy)
elif request_cache is not None:
client_login = cookies is not None or credential is not None
request_cache.attach(service_instance, data, normalized_service, request, client_login, policy)
service_instance._input_bridge = NoUserBridge()
if not anonymous:
service_instance.authenticate(cookies, credential)
service_instance = launch_served(
SEARCH, data, normalized_service, query, client_profile(data), request, request_cache
).service
results: list[dict[str, Any]] = []
try:
for result in service_instance.search():
@@ -1376,9 +1425,10 @@ async def list_titles_handler(data: dict[str, Any], request: web.Request | None
lease, titles = await leased_titles(data, server, info, profile, title_id, request, True)
service_instance = lease.service
else:
service_instance = await asyncio.to_thread(
setup_list_service, data, normalized_service, profile, title_id, request, request_cache
launched = await asyncio.to_thread(
launch_served, LIST, data, normalized_service, title_id, profile, request, request_cache
)
service_instance = launched.service
titles = await asyncio.to_thread(service_instance.get_titles)
title_list = [serialize_title(t, service_instance) for t in listed_titles(titles)]
@@ -1425,9 +1475,10 @@ async def list_tracks_handler(data: dict[str, Any], request: web.Request | None
service_instance = lease.service
call: Callable[..., Any] = partial(remote_call, lease)
else:
service_instance = await asyncio.to_thread(
setup_list_service, data, normalized_service, profile, title_id, request, request_cache
launched = await asyncio.to_thread(
launch_served, LIST, data, normalized_service, title_id, profile, request, request_cache
)
service_instance = launched.service
call = asyncio.to_thread
titles = await call(service_instance.get_titles)
@@ -2722,86 +2773,6 @@ def client_device_cdm(
)
def create_service_instance(
normalized_service: str,
title_id: str,
data: dict[str, Any],
proxy_param: str | None,
proxy_providers: list,
profile: str | None,
server_account: bool = False,
server_cdm: bool = False,
client_device: bool = False,
input_bridge: InputBridge | None = None,
policy: KeyPolicy | None = None,
) -> Any:
"""Make a service instance and resolve its credentials and cookies.
``policy`` is the calling API key's: its own ``cdm`` and ``service_config`` apply.
With ``client_device`` the service sees a stand-in for the client's device, which relays CDM calls
through ``input_bridge`` when the client can answer them, and a config holding the client's own identity.
A service option in ``SERVER_DEVICE_OPTIONS`` gets the server's device whatever device the client has: from an
entry with a device for both systems, the one the entry lists first.
With ``server_account`` the service takes the server's own credential and cookie file for
``profile`` and drops anything the client sent. Otherwise only client-sent data counts: a
client that sends nothing authenticates with nothing, because the server never lends its
own accounts.
"""
policy = policy or KeyPolicy.of(None)
server_config = service_config = policy.service_yaml(normalized_service)
service_module = Services.load(normalized_service)
key_config = policy.cdm_config()
cdm: Any
client_identity = False
if client_device:
client_config = getattr(service_module, "CLIENT_CONFIG", ())
if client_config:
service_config, client_identity = client_config_overlay(
server_config, client_config, data.get("service_config")
)
def lend_server_device() -> Any:
"""The server's device, with the server's own config back in the dict the service holds as ``self.config``."""
if service_config is not server_config:
service_config.clear()
service_config.update(server_config)
return load_full_cdm(normalized_service, profile, None, key_config)
cdm = client_device_cdm(data, input_bridge, lend_server_device)
else:
follows_client = not server_cdm or (
choose_cdm(key_config.cdm, normalized_service).both and not server_device_requested(service_module, data)
)
cdm = load_full_cdm(normalized_service, profile, data.get("cdm_type") if follows_client else None, key_config)
if server_account:
cookies = server_account_cookies(normalized_service, profile)
credential = login.get_credentials(normalized_service, profile)
else:
credential = client_credential(data)
cookies = load_client_cookies(data.get("cookies"))
parent_ctx = served_parent(
ContextData(config=service_config, cdm=cdm, proxy_providers=proxy_providers, profile=profile),
data,
# A service with CLIENT_CONFIG reads client_device and client_identity: with client_identity it uses
# only what the client sent, and without it the server's identity, whose keys then come only from a vault.
{"cookies_supplied": cookies is not None, "client_device": client_device, "client_identity": client_identity},
proxy_param,
# Services key their token caches on this. The list and search handlers leave it out: they
# share the server's cache, where a session runs on a cache directory of its own.
profile,
SESSION_TRANSPORT_KEYS,
)
service_instance = instantiate_service(parent_ctx, service_module, title_id, data, SESSION_TRANSPORT_KEYS)
return service_instance, cookies, credential
async def session_create_handler(data: dict[str, Any], request: web.Request | None = None) -> web.Response:
"""Answer the remote session creation: authenticate + get titles + get tracks + get chapters.
@@ -2838,7 +2809,6 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
api_key = caller_key(request)
policy = request_policy(request)
session_cache_dir = f"_sessions/{api_key_namespace(request)}/{session_id}/{normalized_service}"
session_cache_tag: str | None = session_cache_dir
server_account = server_account_for(policy, normalized_service)
if server_account:
@@ -2855,45 +2825,21 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
log_buffer = None if server_account else SessionLogBuffer()
service_class_name = getattr(Services.load(normalized_service), "__name__", normalized_service)
def build_service() -> Any:
with capture_service_logs(service_class_name, log_buffer):
return create_service_instance(
normalized_service,
title_id,
data,
proxy_param,
proxy_providers,
profile,
server_account=server_account,
server_cdm=licensing.server_cdm,
client_device=licensing.client_device,
input_bridge=bridge,
policy=policy,
purpose = SessionLaunch(
(proxy_param, proxy_providers), policy, server_account, licensing, bridge, session_cache_dir
)
service_instance, cookies, credential = await asyncio.to_thread(build_service)
def build_service() -> Launched:
with capture_service_logs(service_class_name, log_buffer):
return launch_served(purpose, data, normalized_service, title_id, profile, request)
service_instance, cookies, credential, launched_licensing = await asyncio.to_thread(build_service)
licensing = launched_licensing or licensing
if log_buffer:
service_instance.log = SessionLogMirror(service_instance.log, log_buffer)
# the service asked for the server's device in __init__, so the session never licenses live
stand_in = getattr(getattr(getattr(service_instance, "ctx", None), "obj", None), "cdm", None)
if getattr(stand_in, "lent", False) is True:
licensing = licensing.lent()
cache_tag = f"_accounts/{normalized_service}/{profile or 'default'}" if server_account else session_cache_dir
if server_account:
session_cache_tag = None
service_instance.cache = keyed_cache(
cache_tag,
service_instance,
normalized_service,
api_key,
policy,
temporary=not server_account,
client_identity=licensing.client_identity,
)
session_cache_tag = None if server_account else session_cache_dir
cache_data = data.get("cache", {})
service_instance._input_bridge = bridge
client = data.get("client")
store = get_session_store()
try: