From 8d5234130a5251f7c41fb8e887c081b641da6cf1 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Tue, 24 Nov 2026 16:19:19 -0700 Subject: [PATCH] refactor(remote): keep the session protocol in core/remote_protocol.py --- docs/dev/rest-api/errors.md | 5 +- docs/dev/rest-api/remote-sessions.md | 4 +- tests/core/test_client_cookies_flag.py | 3 +- tests/core/test_service_wait_for_approval.py | 3 +- tests/remote/unit/test_api_dl_options.py | 3 +- .../unit/test_api_service_dl_overrides.py | 3 +- tests/remote/unit/test_client_device_cdm.py | 3 +- .../unit/test_download_gates_redaction.py | 3 +- tests/remote/unit/test_download_manager.py | 6 +- tests/remote/unit/test_errors.py | 9 +- .../remote/unit/test_handler_proxy_policy.py | 3 +- tests/remote/unit/test_handlers_serialize.py | 5 +- tests/remote/unit/test_input_bridge.py | 3 +- tests/remote/unit/test_key_identity.py | 2 +- tests/remote/unit/test_remote_protocol.py | 191 ++++++++++++ tests/remote/unit/test_remote_relay.py | 3 +- tests/remote/unit/test_routes.py | 3 +- tests/remote/unit/test_server_cdm_gate.py | 3 +- .../remote/unit/test_server_cdm_max_height.py | 3 +- tests/remote/unit/test_session_store.py | 3 +- tests/test_client_session_auth.py | 7 +- unshackle/commands/serve.py | 5 +- unshackle/core/api/download_manager.py | 3 +- unshackle/core/api/errors.py | 35 +-- unshackle/core/api/handlers.py | 167 +++++------ unshackle/core/api/input_bridge.py | 11 +- unshackle/core/api/routes.py | 59 ++-- unshackle/core/api/session_log.py | 21 +- unshackle/core/api/session_store.py | 6 +- unshackle/core/remote_protocol.py | 253 ++++++++++++++++ unshackle/core/remote_service.py | 274 +++++++++++------- 31 files changed, 797 insertions(+), 305 deletions(-) create mode 100644 tests/remote/unit/test_remote_protocol.py create mode 100644 unshackle/core/remote_protocol.py diff --git a/docs/dev/rest-api/errors.md b/docs/dev/rest-api/errors.md index 9d0a62ce..16a587b9 100644 --- a/docs/dev/rest-api/errors.md +++ b/docs/dev/rest-api/errors.md @@ -12,8 +12,9 @@ reference. Each endpoint lists the specific codes it raises, and this page gives meanings of those codes. !!! note "Where this comes from" - `unshackle/core/api/errors.py` defines the error format, and the wrapper - that turns raised errors into responses lives in `unshackle/core/api/routes.py`. + `unshackle/core/api/errors.py` defines the error format, `unshackle/core/remote_protocol.py` + defines the error codes, and the wrapper that turns raised errors into responses lives in + `unshackle/core/api/routes.py`. Nothing on this page is invented. It reflects the actual server behaviour. ## The standard error shape diff --git a/docs/dev/rest-api/remote-sessions.md b/docs/dev/rest-api/remote-sessions.md index dab33450..f7c6a8e9 100644 --- a/docs/dev/rest-api/remote-sessions.md +++ b/docs/dev/rest-api/remote-sessions.md @@ -656,7 +656,9 @@ it before each title, so it knows of the restart before it occurs. ### Reference client: `RemoteService` Source: `unshackle/core/remote_service.py`. This is the canonical consumer of the -remote session API and a good template for any client. +remote session API and a good template for any client. The routes, the `AuthStatus` values, +the error codes and the request and reply shapes that it shares with the server are in +`unshackle/core/remote_protocol.py`. - **`RemoteClient.request`** sets `X-Secret-Key` and `User-Agent: unshackle/`, uses the server's `timeout` from `remote_services` (default 120s) as the read timeout, diff --git a/tests/core/test_client_cookies_flag.py b/tests/core/test_client_cookies_flag.py index 92c380cd..82b2142d 100644 --- a/tests/core/test_client_cookies_flag.py +++ b/tests/core/test_client_cookies_flag.py @@ -6,8 +6,9 @@ import zlib import pytest from unshackle.core.api import handlers -from unshackle.core.api.errors import APIError, APIErrorCode +from unshackle.core.api.errors import APIError from unshackle.core.api.handlers import load_client_cookies +from unshackle.core.remote_protocol import APIErrorCode COOKIE_FILE = "\n".join( [ diff --git a/tests/core/test_service_wait_for_approval.py b/tests/core/test_service_wait_for_approval.py index 21a65a3c..ffb6ea1d 100644 --- a/tests/core/test_service_wait_for_approval.py +++ b/tests/core/test_service_wait_for_approval.py @@ -57,7 +57,8 @@ def test_a_request_with_no_user_fails_at_once(): def test_no_user_message_is_an_authentication_error(): - from unshackle.core.api.errors import APIErrorCode, categorize_exception + from unshackle.core.api.errors import categorize_exception + from unshackle.core.remote_protocol import APIErrorCode assert categorize_exception(RuntimeError(NO_USER_MESSAGE)).error_code == APIErrorCode.AUTH_FAILED diff --git a/tests/remote/unit/test_api_dl_options.py b/tests/remote/unit/test_api_dl_options.py index 751be1b0..1e281c0d 100644 --- a/tests/remote/unit/test_api_dl_options.py +++ b/tests/remote/unit/test_api_dl_options.py @@ -209,7 +209,8 @@ def test_the_worker_keeps_the_code_of_an_api_error(tmp_path, monkeypatch): import json from unshackle.core.api import download_worker - from unshackle.core.api.errors import APIError, APIErrorCode + from unshackle.core.api.errors import APIError + from unshackle.core.remote_protocol import APIErrorCode def refuse(*args, **kwargs): raise APIError(APIErrorCode.INVALID_PARAMETERS, "Invalid workers: expected a number, not a boolean") diff --git a/tests/remote/unit/test_api_service_dl_overrides.py b/tests/remote/unit/test_api_service_dl_overrides.py index 123169c6..ed628129 100644 --- a/tests/remote/unit/test_api_service_dl_overrides.py +++ b/tests/remote/unit/test_api_service_dl_overrides.py @@ -9,8 +9,9 @@ import pytest from unshackle.core.api import download_manager as dm from unshackle.core.api import handlers -from unshackle.core.api.errors import APIError, APIErrorCode +from unshackle.core.api.errors import APIError from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS +from unshackle.core.remote_protocol import APIErrorCode pytestmark = pytest.mark.unit diff --git a/tests/remote/unit/test_client_device_cdm.py b/tests/remote/unit/test_client_device_cdm.py index 95b868fe..4661fa52 100644 --- a/tests/remote/unit/test_client_device_cdm.py +++ b/tests/remote/unit/test_client_device_cdm.py @@ -16,8 +16,9 @@ from pywidevine.pssh import PSSH from unshackle.core.api import handlers from unshackle.core.api.errors import APIError -from unshackle.core.api.input_bridge import AuthStatus, InputBridge +from unshackle.core.api.input_bridge import InputBridge from unshackle.core.cdm.client_relay import ClientDeviceCdm, answer_cdm_call +from unshackle.core.remote_protocol import AuthStatus pytestmark = pytest.mark.unit diff --git a/tests/remote/unit/test_download_gates_redaction.py b/tests/remote/unit/test_download_gates_redaction.py index 06c6cd48..75f96bb8 100644 --- a/tests/remote/unit/test_download_gates_redaction.py +++ b/tests/remote/unit/test_download_gates_redaction.py @@ -16,7 +16,8 @@ from unshackle.core.api.download_manager import ( redact_parameters, secret_values, ) -from unshackle.core.api.errors import APIError, APIErrorCode +from unshackle.core.api.errors import APIError +from unshackle.core.remote_protocol import APIErrorCode pytestmark = pytest.mark.unit diff --git a/tests/remote/unit/test_download_manager.py b/tests/remote/unit/test_download_manager.py index 608d1f87..b33c607b 100644 --- a/tests/remote/unit/test_download_manager.py +++ b/tests/remote/unit/test_download_manager.py @@ -386,8 +386,9 @@ def test_a_prompt_discards_an_answer_sent_before_it(tmp_path: Path, monkeypatch: import threading from unshackle.core.api import download_worker - from unshackle.core.api.errors import APIErrorCode, categorize_exception + from unshackle.core.api.errors import categorize_exception from unshackle.core.console import prompt_user, set_prompt_handler + from unshackle.core.remote_protocol import APIErrorCode answers = tmp_path / "stdin" answers.write_text('"stale"\n', encoding="utf-8") @@ -558,8 +559,9 @@ async def test_input_handler_rejects_bad_requests( monkeypatch: pytest.MonkeyPatch, manager: DownloadQueueManager ) -> None: from unshackle.core.api import download_manager - from unshackle.core.api.errors import APIError, APIErrorCode + from unshackle.core.api.errors import APIError from unshackle.core.api.handlers import download_job_input_handler + from unshackle.core.remote_protocol import APIErrorCode monkeypatch.setattr(download_manager, "get_download_manager", lambda: manager) job = manager.create_job("EXAMPLE", "t") diff --git a/tests/remote/unit/test_errors.py b/tests/remote/unit/test_errors.py index 4f85c62a..9c85749c 100644 --- a/tests/remote/unit/test_errors.py +++ b/tests/remote/unit/test_errors.py @@ -6,13 +6,8 @@ import json import pytest -from unshackle.core.api.errors import ( - APIError, - APIErrorCode, - build_error_response, - categorize_exception, - handle_api_exception, -) +from unshackle.core.api.errors import APIError, build_error_response, categorize_exception, handle_api_exception +from unshackle.core.remote_protocol import APIErrorCode pytestmark = pytest.mark.unit diff --git a/tests/remote/unit/test_handler_proxy_policy.py b/tests/remote/unit/test_handler_proxy_policy.py index b12cf2fa..359e5ea6 100644 --- a/tests/remote/unit/test_handler_proxy_policy.py +++ b/tests/remote/unit/test_handler_proxy_policy.py @@ -5,7 +5,8 @@ from types import SimpleNamespace import pytest from unshackle.core.api import handlers -from unshackle.core.api.errors import APIError, APIErrorCode +from unshackle.core.api.errors import APIError +from unshackle.core.remote_protocol import APIErrorCode from unshackle.core.utils import ip_info pytestmark = pytest.mark.unit diff --git a/tests/remote/unit/test_handlers_serialize.py b/tests/remote/unit/test_handlers_serialize.py index 6541f78c..f264d342 100644 --- a/tests/remote/unit/test_handlers_serialize.py +++ b/tests/remote/unit/test_handlers_serialize.py @@ -8,7 +8,7 @@ import pytest import requests from langcodes import Language -from unshackle.core.api.errors import APIError, APIErrorCode +from unshackle.core.api.errors import APIError from unshackle.core.api.handlers import ( drm_preference_name, listed_titles, @@ -18,6 +18,7 @@ from unshackle.core.api.handlers import ( validate_service, ) from unshackle.core.config import config +from unshackle.core.remote_protocol import APIErrorCode from unshackle.core.titles.episode import Episode from unshackle.core.titles.movie import Movie from unshackle.core.tracks import Audio, Subtitle, Video @@ -367,8 +368,8 @@ async def test_search_unknown_service_raises_invalid_service() -> None: def test_resolve_vcodec_rejects_junk_as_invalid_input() -> None: """Session routes skip validate_download_parameters, so a bad codec must be a 400, not a 500.""" - from unshackle.core.api.errors import APIErrorCode from unshackle.core.api.handlers import resolve_vcodec + from unshackle.core.remote_protocol import APIErrorCode from unshackle.core.tracks import Video assert resolve_vcodec(["H265"]) == [Video.Codec.HEVC] diff --git a/tests/remote/unit/test_input_bridge.py b/tests/remote/unit/test_input_bridge.py index 198fcae9..cc417e99 100644 --- a/tests/remote/unit/test_input_bridge.py +++ b/tests/remote/unit/test_input_bridge.py @@ -7,7 +7,8 @@ import time import pytest -from unshackle.core.api.input_bridge import AuthStatus, InputBridge +from unshackle.core.api.input_bridge import InputBridge +from unshackle.core.remote_protocol import AuthStatus pytestmark = pytest.mark.unit diff --git a/tests/remote/unit/test_key_identity.py b/tests/remote/unit/test_key_identity.py index 6466ceaa..8de0a445 100644 --- a/tests/remote/unit/test_key_identity.py +++ b/tests/remote/unit/test_key_identity.py @@ -10,9 +10,9 @@ import pytest from unshackle.core.api import handlers from unshackle.core.api.errors import APIError -from unshackle.core.api.input_bridge import AuthStatus from unshackle.core.api.session_store import get_session_store from unshackle.core.config import config +from unshackle.core.remote_protocol import AuthStatus @pytest.fixture diff --git a/tests/remote/unit/test_remote_protocol.py b/tests/remote/unit/test_remote_protocol.py new file mode 100644 index 00000000..f8c93335 --- /dev/null +++ b/tests/remote/unit/test_remote_protocol.py @@ -0,0 +1,191 @@ +"""The remote session protocol: what a remote client sends must be what the server serves.""" + +from __future__ import annotations + +import ast +import functools +from pathlib import Path +from typing import Any, Optional + +import pytest +import yaml + +from unshackle.core import remote_protocol as protocol +from unshackle.core import remote_service +from unshackle.core.api import routes +from unshackle.core.api.handlers import SESSION_TRANSPORT_KEYS + +ROUTE_NAMES = {name for name in vars(protocol) if name.endswith("_ROUTE")} +CLIENT_METHODS = {"get": "GET", "get_optional": "GET", "post": "POST", "post_optional": "POST", "delete": "DELETE"} +SERVED = {(method, path): handler for method, path, handler, _ in routes.ROUTES} + + +@functools.cache +def client_tree() -> ast.Module: + return ast.parse(Path(remote_service.__file__).read_text(encoding="utf-8")) + + +def client_calls() -> tuple[set[tuple[str, str]], set[str]]: + """The (method, route) pairs the client sends, and every route name the client module reads. + + A URL a function keeps in a local variable counts at the call that sends it. + """ + tree = client_tree() + referenced = {n.id for n in ast.walk(tree) if isinstance(n, ast.Name) and n.id in ROUTE_NAMES} + calls: set[tuple[str, str]] = set() + for function in ast.walk(tree): + if not isinstance(function, ast.FunctionDef): + continue + local = { + target.id: node.value + for node in ast.walk(function) + if isinstance(node, ast.Assign) + for target in node.targets + if isinstance(target, ast.Name) + } + for call in ast.walk(function): + if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute) and call.args): + continue + if call.func.attr == "request" and isinstance(call.args[0], ast.Constant) and len(call.args) > 1: + method, target = str(call.args[0].value).upper(), call.args[1] + elif call.func.attr in CLIENT_METHODS: + method, target = CLIENT_METHODS[call.func.attr], call.args[0] + else: + continue + if isinstance(target, ast.Name): + target = local.get(target.id, target) + calls |= { + (method, getattr(protocol, n.id)) + for n in ast.walk(target) + if isinstance(n, ast.Name) and n.id in ROUTE_NAMES + } + return calls, referenced + + +def test_the_client_writes_no_api_path_of_its_own(): + """A path the client writes out by hand escapes the route check below.""" + tree = client_tree() + docstrings = {id(node.value) for node in ast.walk(tree) if isinstance(node, ast.Expr)} + assert not [ + node.lineno + for node in ast.walk(tree) + if isinstance(node, ast.Constant) + and isinstance(node.value, str) + and "/api/" in node.value + and id(node) not in docstrings + ] + + +def test_every_route_the_client_calls_is_served_with_that_method(): + calls, referenced = client_calls() + assert calls, "the scan found no client calls" + assert {path for _, path in calls} >= {getattr(protocol, name) for name in referenced} + assert calls <= SERVED.keys() + + +def test_the_server_takes_its_remote_session_routes_from_the_protocol(): + protocol_paths = {getattr(protocol, name) for name in ROUTE_NAMES} + served_paths = {path for _, path in SERVED} + assert protocol_paths <= served_paths + assert {path for path in served_paths if path.startswith("/api/session")} <= protocol_paths + + +def test_the_wire_values_stay_what_older_peers_send(): + """Both halves read one record, so only this list catches a renamed value that an older peer still sends.""" + assert {name: getattr(protocol, name) for name in ROUTE_NAMES} == { + "HEALTH_ROUTE": "/api/health", + "SERVICES_ROUTE": "/api/services", + "SEARCH_ROUTE": "/api/search", + "SESSION_CREATE_ROUTE": "/api/session/create", + "SESSION_ROUTE": "/api/session/{session_id}", + "TITLES_ROUTE": "/api/session/{session_id}/titles", + "TRACKS_ROUTE": "/api/session/{session_id}/tracks", + "SEGMENTS_ROUTE": "/api/session/{session_id}/segments", + "SEGMENT_FILTER_ROUTE": "/api/session/{session_id}/segment_filter", + "SAMPLES_ROUTE": "/api/session/{session_id}/samples", + "LICENSE_ROUTE": "/api/session/{session_id}/license", + "BAD_KEY_ROUTE": "/api/session/{session_id}/keys/bad", + "LOGS_ROUTE": "/api/session/{session_id}/logs", + "PROMPT_ROUTE": "/api/session/{session_id}/prompt", + } + assert [s.value for s in protocol.AuthStatus] == ["authenticating", "pending_input", "authenticated", "failed"] + assert {c.name for c in protocol.APIErrorCode} >= {"SESSION_NOT_FOUND", "SERVER_CDM_CAPPED", "SERVER_DRAINING"} + assert [k.value for k in protocol.ClientErrorKind] == [ + "CONNECT", + "TIMEOUT", + "AUTH", + "TUNNEL_CLOSED", + "GRANTS_CHANGED", + "UNKNOWN", + ] + + +def test_session_transport_keys_are_the_create_body(): + """The server keeps these out of the flat service options; it reads them from the session create body.""" + assert SESSION_TRANSPORT_KEYS == { + "service", + "title_id", + "profile", + "service_params", + "season", + "episode", + "part", + "wanted", + "proxy", + "no_proxy", + "credentials", + "cookies", + "cache", + "client_region", + "proxy_region", + "server_cdm", + "cdm_type", + "cdm_security_level", + "cdm_relay", + "cdm_system_id", + "cdm_device_type", + "service_config", + "range_", + "vcodec", + "quality", + "best_available", + "generate_dv", + "dl_params", + } + + +def test_a_client_error_kind_is_never_a_server_error_code(): + assert not {k.value for k in protocol.ClientErrorKind} & {c.value for c in protocol.APIErrorCode} + + +def keys(shape: Any) -> set[str]: + return set(shape.__required_keys__ | shape.__optional_keys__) + + +def properties(schema: Optional[dict]) -> set[str]: + return set( + ((schema or {}).get("content", {}).get("application/json", {}).get("schema", {}) or {}).get("properties", {}) + ) + + +@pytest.mark.parametrize( + "method,route,request_shape,reply_shape", + [ + ("POST", protocol.SESSION_CREATE_ROUTE, protocol.SessionCreate, protocol.SessionCreated), + ("POST", protocol.TRACKS_ROUTE, protocol.TracksRequest, None), + ("POST", protocol.SEGMENT_FILTER_ROUTE, protocol.SegmentFilterRequest, protocol.SegmentFilterReply), + ("POST", protocol.LICENSE_ROUTE, protocol.LicenseRequest, protocol.LicenseReply), + ("POST", protocol.BAD_KEY_ROUTE, protocol.BadKeyReport, None), + ("GET", protocol.LOGS_ROUTE, None, protocol.LogsReply), + ("GET", protocol.PROMPT_ROUTE, None, protocol.PromptReply), + ("POST", protocol.PROMPT_ROUTE, protocol.PromptAnswer, None), + ("GET", protocol.SESSION_ROUTE, None, protocol.SessionInfo), + ], +) +def test_the_openapi_yaml_names_only_protocol_keys(method, route, request_shape, reply_shape): + """The Swagger docs of a route list a subset of the keys its protocol shapes declare.""" + spec = yaml.safe_load((SERVED[(method, route)].__doc__ or "").split("---", 1)[1]) + if request_shape: + assert properties(spec.get("requestBody")) <= keys(request_shape) + if reply_shape: + assert properties(spec["responses"].get("200")) <= keys(reply_shape) diff --git a/tests/remote/unit/test_remote_relay.py b/tests/remote/unit/test_remote_relay.py index e6c2a699..45303d26 100644 --- a/tests/remote/unit/test_remote_relay.py +++ b/tests/remote/unit/test_remote_relay.py @@ -7,8 +7,9 @@ import pytest from unshackle.core import remote_service from unshackle.core.api import handlers -from unshackle.core.api.errors import APIError, APIErrorCode +from unshackle.core.api.errors import APIError from unshackle.core.config import config +from unshackle.core.remote_protocol import APIErrorCode SERVICES = [ { diff --git a/tests/remote/unit/test_routes.py b/tests/remote/unit/test_routes.py index a6b19404..c9df6199 100644 --- a/tests/remote/unit/test_routes.py +++ b/tests/remote/unit/test_routes.py @@ -16,8 +16,9 @@ from aiohttp import web from unshackle.core.api import routes from unshackle.core.api.compression import compression_middleware -from unshackle.core.api.errors import APIError, APIErrorCode +from unshackle.core.api.errors import APIError from unshackle.core.api.routes import api_handler, cors_middleware, heartbeat, setup_routes +from unshackle.core.remote_protocol import APIErrorCode pytestmark = pytest.mark.unit diff --git a/tests/remote/unit/test_server_cdm_gate.py b/tests/remote/unit/test_server_cdm_gate.py index 78e82df1..16b23768 100644 --- a/tests/remote/unit/test_server_cdm_gate.py +++ b/tests/remote/unit/test_server_cdm_gate.py @@ -6,7 +6,8 @@ from types import SimpleNamespace import pytest from unshackle.core.api import handlers -from unshackle.core.api.errors import APIError, APIErrorCode +from unshackle.core.api.errors import APIError +from unshackle.core.remote_protocol import APIErrorCode pytestmark = pytest.mark.unit diff --git a/tests/remote/unit/test_server_cdm_max_height.py b/tests/remote/unit/test_server_cdm_max_height.py index 8dd3be4d..f434fe8c 100644 --- a/tests/remote/unit/test_server_cdm_max_height.py +++ b/tests/remote/unit/test_server_cdm_max_height.py @@ -16,10 +16,11 @@ from tests.core.key_resolver import key_table, resolver from tests.remote.key_source import CAPPED, PR_DEVICE, one_title, remote_keys, remote_session from unshackle.commands.dl import dl from unshackle.core.api import handlers -from unshackle.core.api.errors import APIError, APIErrorCode +from unshackle.core.api.errors import APIError from unshackle.core.api.session_store import SessionEntry from unshackle.core.config import cdm_entry_names_device from unshackle.core.drm import Widevine +from unshackle.core.remote_protocol import APIErrorCode from unshackle.core.remote_service import RemoteClient, RemoteService from unshackle.core.tracks import Audio, Video diff --git a/tests/remote/unit/test_session_store.py b/tests/remote/unit/test_session_store.py index 8bdc0efe..ec3bed13 100644 --- a/tests/remote/unit/test_session_store.py +++ b/tests/remote/unit/test_session_store.py @@ -7,8 +7,9 @@ import time import pytest -from unshackle.core.api.input_bridge import AuthStatus, InputBridge +from unshackle.core.api.input_bridge import InputBridge from unshackle.core.api.session_store import SessionEntry, SessionStore, get_session_store +from unshackle.core.remote_protocol import AuthStatus pytestmark = pytest.mark.unit diff --git a/tests/test_client_session_auth.py b/tests/test_client_session_auth.py index 18c3354e..60fede74 100644 --- a/tests/test_client_session_auth.py +++ b/tests/test_client_session_auth.py @@ -276,7 +276,8 @@ def test_absent_key_keeps_server_devices(monkeypatch): def test_safe_inflate_rejects_non_str_via_isinstance(): # A non-string cache value must be caught before base64.b64decode raises a 500. # Mirror the guard used in session_create_handler. - from unshackle.core.api.errors import APIError, APIErrorCode + from unshackle.core.api.errors import APIError + from unshackle.core.remote_protocol import APIErrorCode def guard(content): if not isinstance(content, str): @@ -296,9 +297,9 @@ def _run_session(monkeypatch, tmp_path, data, answer, server_account=False, fail import zlib from unshackle.core.api import handlers - from unshackle.core.api.input_bridge import AuthStatus from unshackle.core.api.session_store import get_session_store from unshackle.core.config import config + from unshackle.core.remote_protocol import AuthStatus class PromptingService: _input_bridge = None @@ -356,7 +357,7 @@ def test_prompt_post_rejects_response_the_bridge_refused(monkeypatch): import asyncio from unshackle.core.api import handlers - from unshackle.core.api.input_bridge import AuthStatus + from unshackle.core.remote_protocol import AuthStatus bridge = SimpleNamespace(status=AuthStatus.PENDING_INPUT, submit_response=lambda text: False) diff --git a/unshackle/commands/serve.py b/unshackle/commands/serve.py index 2195ddaf..cee437a6 100644 --- a/unshackle/commands/serve.py +++ b/unshackle/commands/serve.py @@ -47,6 +47,7 @@ from unshackle.core.config import Config, config from unshackle.core.console import console from unshackle.core.constants import context_settings from unshackle.core.downloaders import format_speed, parse_speed_limit, set_speed_limit +from unshackle.core.remote_protocol import HEALTH_ROUTE class _MaskAccessKey(logging.Filter): @@ -549,7 +550,7 @@ def serve( known = bool(secret_key) and any( hmac.compare_digest(secret_key, k) for k in request.app["config"]["users"] ) - if request.path != "/api/health" and secret_key and known: + if request.path != HEALTH_ROUTE and secret_key and known: limited = rate_limit_response(secret_key) if limited is not None: return limited @@ -569,7 +570,7 @@ def serve( f"https://git.gay/ready-dl/pyplayready serve v{pyplayready_version}" ) - if request.path != "/api/health" and secret_key and known: + if request.path != HEALTH_ROUTE and secret_key and known: add_rate_limit_headers(response, secret_key) return response diff --git a/unshackle/core/api/download_manager.py b/unshackle/core/api/download_manager.py index 96b08ea4..c02e0d73 100644 --- a/unshackle/core/api/download_manager.py +++ b/unshackle/core/api/download_manager.py @@ -365,8 +365,9 @@ def perform_download( import click from unshackle.commands.dl import dl - from unshackle.core.api.errors import APIError, APIErrorCode + from unshackle.core.api.errors import APIError from unshackle.core.config import config, load_yaml + from unshackle.core.remote_protocol import APIErrorCode from unshackle.core.services import Services from unshackle.core.utils.click_types import ContextData from unshackle.core.utils.collections import merge_dict diff --git a/unshackle/core/api/errors.py b/unshackle/core/api/errors.py index 44a229b7..f902b5a5 100644 --- a/unshackle/core/api/errors.py +++ b/unshackle/core/api/errors.py @@ -10,47 +10,14 @@ from __future__ import annotations import secrets import traceback from datetime import datetime, timezone -from enum import Enum from typing import Any from aiohttp import web +from unshackle.core.remote_protocol import APIErrorCode from unshackle.core.utils.redact import redact_secrets -class APIErrorCode(str, Enum): - """Standard API error codes for programmatic error handling.""" - - INVALID_INPUT = "INVALID_INPUT" - INVALID_SERVICE = "INVALID_SERVICE" - INVALID_PROXY = "INVALID_PROXY" - INVALID_PARAMETERS = "INVALID_PARAMETERS" - - AUTH_FAILED = "AUTH_FAILED" - FORBIDDEN = "FORBIDDEN" - SERVER_CDM_CAPPED = "SERVER_CDM_CAPPED" - GEOFENCE = "GEOFENCE" - - NOT_FOUND = "NOT_FOUND" - NO_CONTENT = "NO_CONTENT" - JOB_NOT_FOUND = "JOB_NOT_FOUND" - SESSION_NOT_FOUND = "SESSION_NOT_FOUND" - TRACK_NOT_FOUND = "TRACK_NOT_FOUND" - - CONFLICT = "CONFLICT" - - RATE_LIMITED = "RATE_LIMITED" - - INTERNAL_ERROR = "INTERNAL_ERROR" - SERVICE_ERROR = "SERVICE_ERROR" - NETWORK_ERROR = "NETWORK_ERROR" - DRM_ERROR = "DRM_ERROR" - DOWNLOAD_ERROR = "DOWNLOAD_ERROR" - SERVICE_UNAVAILABLE = "SERVICE_UNAVAILABLE" - SERVER_DRAINING = "SERVER_DRAINING" - WORKER_ERROR = "WORKER_ERROR" - - class APIError(Exception): """ Structured API error with error code, message, and details. diff --git a/unshackle/core/api/handlers.py b/unshackle/core/api/handlers.py index a1037d17..d26462b7 100644 --- a/unshackle/core/api/handlers.py +++ b/unshackle/core/api/handlers.py @@ -24,8 +24,8 @@ import click from aiohttp import web from unshackle.core.api.compression import safe_inflate -from unshackle.core.api.errors import APIError, APIErrorCode, categorize_exception, handle_api_exception -from unshackle.core.api.input_bridge import AuthStatus, InputBridge, NoUserBridge +from unshackle.core.api.errors import APIError, categorize_exception, handle_api_exception +from unshackle.core.api.input_bridge import InputBridge, NoUserBridge from unshackle.core.api.progress import track_log_label from unshackle.core.api.sanitize import MAX_SESSION_CACHE_KEYS, safe_cache_key, safe_cache_payload, sanitize_log from unshackle.core.api.session_log import SessionLogBuffer, SessionLogMirror, capture_service_logs @@ -45,6 +45,26 @@ from unshackle.core.drm import BlowfishStripe, cbcs, is_null_key from unshackle.core.manifests.snapshot import capture from unshackle.core.providers.anilist import parse_anilist_ref from unshackle.core.proxies.resolve import initialize_proxy_providers, is_loopback, resolve_proxy +from unshackle.core.remote_protocol import ( + HEALTH_ROUTE, + APIErrorCode, + AuthStatus, + BadKeyReport, + LicenseReply, + LicenseRequest, + LogsReply, + PromptAnswer, + PromptReply, + SegmentFilterReply, + SegmentFilterRequest, + SessionClosed, + SessionCreate, + SessionCreated, + SessionInfo, + TitlesReply, + TracksReply, + TracksRequest, +) from unshackle.core.services import Services from unshackle.core.session import RnetSession, utf8_text from unshackle.core.titles import Episode, Song @@ -1502,7 +1522,7 @@ async def api_key_authentication(request: web.Request, handler: Any) -> web.Stre # recovered byte-by-byte from response timing. if not any(hmac.compare_digest(secret_key, k) for k in request.app["config"]["users"]): return web.json_response({"status": 401, "message": "Secret Key is Invalid."}, status=401) - if request.path == "/api/health": + if request.path == HEALTH_ROUTE: return await handler(request) return rate_limit_response(secret_key) or add_rate_limit_headers(await handler(request), secret_key) @@ -3296,36 +3316,8 @@ async def env_check_handler(request: Optional[web.Request] = None) -> web.Respon return handle_api_exception(e, context={"operation": "env_check"}, debug_mode=debug_mode) -SESSION_TRANSPORT_KEYS = { - "service", - "title_id", - "profile", - "service_params", - "season", - "episode", - "part", - "wanted", - "proxy", - "no_proxy", - "credentials", - "cookies", - "cache", - "client_region", - "proxy_region", - "server_cdm", - "cdm_type", - "cdm_security_level", - "cdm_relay", - "cdm_system_id", - "cdm_device_type", - "service_config", - "range_", - "vcodec", - "quality", - "best_available", - "generate_dv", - "dl_params", -} +# "client" stays out: a flat "client" value with no service_params is a service option. +SESSION_TRANSPORT_KEYS = (SessionCreate.__required_keys__ | SessionCreate.__optional_keys__) - {"client"} # A client's service config carries a device identity (an ESN, a few keys), never a bulk payload. @@ -3656,16 +3648,16 @@ async def session_create_handler(data: Dict[str, Any], request: Optional[web.Req auth_task.add_done_callback(_auth_tasks.discard) return web.json_response( - { - "session_id": session.session_id, - "service": normalized_service, - "status": "authenticating", - "server_account": server_account, - "server_cdm": use_server_cdm, - "server_cdm_max_height": max_height, - "server_vault": session.server_vault, - "server_device": session.server_device, - } + SessionCreated( + session_id=session.session_id, + service=normalized_service, + status=AuthStatus.AUTHENTICATING, + server_account=server_account, + server_cdm=use_server_cdm, + server_cdm_max_height=max_height, + server_vault=session.server_vault, + server_device=session.server_device, + ) ) except APIError: @@ -3708,12 +3700,7 @@ async def session_titles_handler(session_id: str, request: Optional[web.Request] serialized_titles.append(stamp_service_flags(serialize_title(t), service_instance)) SessionStore.publish_update(session) - return web.json_response( - { - "session_id": session_id, - "titles": serialized_titles, - } - ) + return web.json_response(TitlesReply(session_id=session_id, titles=serialized_titles)) except (Exception, SystemExit) as e: log.exception("Error getting titles") @@ -3798,7 +3785,7 @@ def scrub_track_data(data: Optional[Dict[str, Any]], session: Any) -> Optional[D async def session_tracks_handler( - data: Dict[str, Any], session_id: str, request: Optional[web.Request] = None + data: TracksRequest, session_id: str, request: Optional[web.Request] = None ) -> web.Response: """Get tracks and chapters for a specific title in the remote session. @@ -3896,6 +3883,17 @@ async def session_tracks_handler( d["data"] = scrub_track_data(d.get("data"), session) return {**lists, "attachments": [a for a in map(serialize_attachment, tracks.attachments) if a]} + session_fields = TracksReply( + session_headers=session_headers, + session_cookies=cookie_values(session_cookies), + session_cookie_jar=session_cookies, + server_cdm=session.server_cdm, + server_cdm_type=server_cdm_type, + sample_decrypt_tracks=[ + str(t.id) for t in [*tracks.videos, *tracks.audio] if service_instance.decrypts_samples(t) + ], + ) + return web.json_response( { "title": stamp_service_flags(serialize_title(title), service_instance), @@ -3905,14 +3903,7 @@ async def session_tracks_handler( for ch in session.chapters_by_title.get(str(title_id), []) ], **snapshot, - "session_headers": session_headers, - "session_cookies": cookie_values(session_cookies), - "session_cookie_jar": session_cookies, - "server_cdm": session.server_cdm, - "server_cdm_type": server_cdm_type, - "sample_decrypt_tracks": [ - str(t.id) for t in [*tracks.videos, *tracks.audio] if service_instance.decrypts_samples(t) - ], + **session_fields, } ) @@ -4121,25 +4112,25 @@ async def session_prompt_get_handler(session_id: str, request: Optional[web.Requ bridge = session.input_bridge if bridge and (cdm_call := bridge.get_pending_cdm_call()): return web.json_response( - {"status": "pending_input", "prompt": bridge.get_pending_prompt(), "cdm_call": cdm_call} + PromptReply(status=AuthStatus.PENDING_INPUT, prompt=bridge.get_pending_prompt(), cdm_call=cdm_call) ) if session.auth_status == AuthStatus.AUTHENTICATED: - return web.json_response({"status": "authenticated"}) + return web.json_response(PromptReply(status=AuthStatus.AUTHENTICATED)) if session.auth_status == AuthStatus.FAILED: - return web.json_response({"status": "failed", "error": session.auth_error or "unknown error"}) + return web.json_response(PromptReply(status=AuthStatus.FAILED, error=session.auth_error or "unknown error")) if bridge: prompt = bridge.get_pending_prompt() if prompt: - return web.json_response({"status": "pending_input", "prompt": prompt}) + return web.json_response(PromptReply(status=AuthStatus.PENDING_INPUT, prompt=prompt)) - return web.json_response({"status": "authenticating"}) + return web.json_response(PromptReply(status=AuthStatus.AUTHENTICATING)) async def session_prompt_post_handler( - data: Dict[str, Any], session_id: str, request: Optional[web.Request] = None + data: PromptAnswer, session_id: str, request: Optional[web.Request] = None ) -> web.Response: """Submit a response to a pending interactive prompt. @@ -4172,13 +4163,7 @@ async def session_logs_handler(session_id: str, since: int = 0, request: Optiona session = await get_validated_session(session_id, request) buffer = session.log_buffer logs = buffer.since(since) if buffer else [] - return web.json_response( - { - "session_id": session_id, - "logs": logs, - "last_seq": logs[-1]["seq"] if logs else since, - } - ) + return web.json_response(LogsReply(session_id=session_id, logs=logs, last_seq=logs[-1]["seq"] if logs else since)) async def get_validated_session(session_id: str, request: Optional[web.Request]) -> Any: @@ -4930,16 +4915,16 @@ def handle_proxy_license( raise APIError(APIErrorCode.SERVICE_ERROR, f"Licence request failed: {exc}") from None if license_blob is None: - return web.json_response({"license": None}) + return web.json_response(LicenseReply(license=None)) if isinstance(license_blob, str): # a Widevine service may answer in Base64 text, and the client hands its CDM the raw bytes license_blob = base64.b64decode(license_blob) if drm_type == "widevine" else license_blob.encode("utf-8") - return web.json_response({"license": base64.b64encode(license_blob).decode("ascii")}) + return web.json_response(LicenseReply(license=base64.b64encode(license_blob).decode("ascii"))) async def session_segment_filter_handler( - data: Dict[str, Any], session_id: str, request: Optional[web.Request] = None + data: SegmentFilterRequest, session_id: str, request: Optional[web.Request] = None ) -> web.Response: """Run the service's HLS ``OnSegmentFilter`` for one track and return the unwanted segment URIs. @@ -4963,7 +4948,7 @@ async def session_segment_filter_handler( segment_filter = getattr(track, "OnSegmentFilter", None) if not callable(segment_filter) or not getattr(track, "url", None): - return web.json_response({"unwanted": None}) + return web.json_response(SegmentFilterReply(unwanted=None)) def unwanted_segments() -> list[str]: import m3u8 @@ -4982,7 +4967,7 @@ async def session_segment_filter_handler( log.exception(f"Error running the segment filter for track {sanitize_log(str(track_id))}") raise APIError(APIErrorCode.SERVICE_ERROR, "Could not run the segment filter for this track") from None - return web.json_response({"unwanted": unwanted}) + return web.json_response(SegmentFilterReply(unwanted=unwanted)) async def session_samples_handler( @@ -5039,7 +5024,7 @@ async def session_samples_handler( async def session_license_handler( - data: Dict[str, Any], session_id: str, request: Optional[web.Request] = None + data: LicenseRequest, session_id: str, request: Optional[web.Request] = None ) -> web.Response: """Do the DRM licensing in proxy or server_cdm mode. @@ -5059,7 +5044,7 @@ async def session_license_handler( def license_response( - data: Dict[str, Any], session: Any, session_id: str, request: Optional[web.Request] + data: LicenseRequest, session: Any, session_id: str, request: Optional[web.Request] ) -> web.Response: """The licence response for :func:`session_license_handler`, made on a worker thread.""" track_id = data.get("track_id") @@ -5229,7 +5214,7 @@ def license_response( drm_types[tid] = track_drm_type actual_drm_type = track_drm_type - response: Dict[str, Any] = {"keys": all_keys} + response = LicenseReply(keys=all_keys) if clear_tracks: response["clear_tracks"] = clear_tracks if vault_keys: @@ -5304,7 +5289,7 @@ def license_response( ) log.info(f"Server CDM resolved {len(keys)} key(s) for track {track_log_label(track)}") note_served_keys(session, keys, key_sources) - return web.json_response({"keys": keys, "vault_keys": list(key_sources), "drm_type": server_drm_type}) + return web.json_response(LicenseReply(keys=keys, vault_keys=list(key_sources), drm_type=server_drm_type)) if pssh_b64: require_track_pssh(track, pssh_b64, drm_type) @@ -5348,7 +5333,7 @@ def note_served_keys(session: Any, keys: Dict[str, str], sources: Dict[str, str] async def session_bad_key_handler( - data: Dict[str, Any], session_id: str, request: Optional[web.Request] = None + data: BadKeyReport, session_id: str, request: Optional[web.Request] = None ) -> web.Response: """Flag a server-vault content key the client proved wrong, so the next licence reaches the CDM. @@ -5400,15 +5385,15 @@ async def session_info_handler(session_id: str, request: Optional[web.Request] = from unshackle.core.api.session_store import get_session_store return web.json_response( - { - "session_id": session.session_id, - "service": session.service_tag, - "valid": True, - "expires_in": get_session_store().ttl, - "draining": get_session_store().draining, - "track_count": len(session.tracks), - "title_count": len(session.title_map), - } + SessionInfo( + session_id=session.session_id, + service=session.service_tag, + valid=True, + expires_in=get_session_store().ttl, + draining=get_session_store().draining, + track_count=len(session.tracks), + title_count=len(session.title_map), + ) ) @@ -5427,7 +5412,7 @@ async def session_delete_handler(session_id: str, request: Optional[web.Request] await store.delete(session_id) - response: Dict[str, Any] = {"status": "ok"} + response = SessionClosed(status="ok") if cache_data: response["cache"] = cache_data return web.json_response(response) diff --git a/unshackle/core/api/input_bridge.py b/unshackle/core/api/input_bridge.py index 6577aebc..55de0dcf 100644 --- a/unshackle/core/api/input_bridge.py +++ b/unshackle/core/api/input_bridge.py @@ -12,18 +12,9 @@ from __future__ import annotations import json import threading from dataclasses import dataclass, field -from enum import Enum from typing import Any, Optional - -class AuthStatus(Enum): - """Authentication lifecycle states for a remote session.""" - - AUTHENTICATING = "authenticating" - PENDING_INPUT = "pending_input" - AUTHENTICATED = "authenticated" - FAILED = "failed" - +from unshackle.core.remote_protocol import AuthStatus # Seconds the server waits for a remote client to answer an input prompt before # giving up; also the TTL SessionStore grants AUTHENTICATING/PENDING_INPUT sessions. diff --git a/unshackle/core/api/routes.py b/unshackle/core/api/routes.py index 34471fb0..bb758ebf 100644 --- a/unshackle/core/api/routes.py +++ b/unshackle/core/api/routes.py @@ -13,13 +13,7 @@ from aiohttp_swagger3 import SwaggerDocs, SwaggerInfo, SwaggerUiSettings from unshackle.core import __code_hash__, __version__ from unshackle.core import services as services_module -from unshackle.core.api.errors import ( - APIError, - APIErrorCode, - build_error_response, - categorize_exception, - handle_api_exception, -) +from unshackle.core.api.errors import APIError, build_error_response, categorize_exception, handle_api_exception from unshackle.core.api.handlers import ( CORS_HEADERS, DASHBOARD_EVENTS_ROUTE, @@ -82,6 +76,23 @@ from unshackle.core.api.handlers import ( ) from unshackle.core.api.sanitize import sanitize_log from unshackle.core.drm import cbcs +from unshackle.core.remote_protocol import ( + BAD_KEY_ROUTE, + HEALTH_ROUTE, + LICENSE_ROUTE, + LOGS_ROUTE, + PROMPT_ROUTE, + SAMPLES_ROUTE, + SEARCH_ROUTE, + SEGMENT_FILTER_ROUTE, + SEGMENTS_ROUTE, + SERVICES_ROUTE, + SESSION_CREATE_ROUTE, + SESSION_ROUTE, + TITLES_ROUTE, + TRACKS_ROUTE, + APIErrorCode, +) from unshackle.core.services import Services from unshackle.core.tunnel import CHECK_ROUTE as TUNNEL_CHECK_ROUTE from unshackle.core.tunnel import ROUTE as TUNNEL_ROUTE @@ -3399,9 +3410,9 @@ async def remote_login_input(request: web.Request) -> web.Response: # --remote-only server mode; full mode registers every route. setup_routes registers the # routes and their docs from this table, so the live routes and the docs cannot drift. ROUTES: list[tuple[str, str, Handler, bool]] = [ - ("GET", "/api/health", health, True), - ("GET", "/api/services", services, True), - ("POST", "/api/search", search, True), + ("GET", HEALTH_ROUTE, health, True), + ("GET", SERVICES_ROUTE, services, True), + ("POST", SEARCH_ROUTE, search, True), ("POST", "/api/list-titles", list_titles, False), ("POST", "/api/list-tracks", list_tracks, False), ("POST", "/api/download", download, False), @@ -3423,21 +3434,21 @@ ROUTES: list[tuple[str, str, Handler, bool]] = [ ("GET", "/api/env/check", env_check, False), ("GET", "/api/remote/logins", remote_logins, False), ("POST", "/api/remote/logins/{login_id}/input", remote_login_input, False), - ("POST", "/api/session/create", session_create, True), + ("POST", SESSION_CREATE_ROUTE, session_create, True), ("GET", TUNNEL_ROUTE, tunnel, True), ("GET", TUNNEL_CHECK_ROUTE, tunnel_check, True), - ("GET", "/api/session/{session_id}/titles", session_titles, True), - ("POST", "/api/session/{session_id}/tracks", session_tracks, True), - ("POST", "/api/session/{session_id}/segments", session_segments, True), - ("POST", "/api/session/{session_id}/segment_filter", session_segment_filter, True), - ("POST", "/api/session/{session_id}/samples", session_samples, True), - ("POST", "/api/session/{session_id}/license", session_license, True), - ("POST", "/api/session/{session_id}/keys/bad", session_bad_key, True), - ("GET", "/api/session/{session_id}/logs", session_logs, True), - ("GET", "/api/session/{session_id}/prompt", session_prompt_get, True), - ("POST", "/api/session/{session_id}/prompt", session_prompt_submit, True), - ("GET", "/api/session/{session_id}", session_info, True), - ("DELETE", "/api/session/{session_id}", session_delete, True), + ("GET", TITLES_ROUTE, session_titles, True), + ("POST", TRACKS_ROUTE, session_tracks, True), + ("POST", SEGMENTS_ROUTE, session_segments, True), + ("POST", SEGMENT_FILTER_ROUTE, session_segment_filter, True), + ("POST", SAMPLES_ROUTE, session_samples, True), + ("POST", LICENSE_ROUTE, session_license, True), + ("POST", BAD_KEY_ROUTE, session_bad_key, True), + ("GET", LOGS_ROUTE, session_logs, True), + ("GET", PROMPT_ROUTE, session_prompt_get, True), + ("POST", PROMPT_ROUTE, session_prompt_submit, True), + ("GET", SESSION_ROUTE, session_info, True), + ("DELETE", SESSION_ROUTE, session_delete, True), ] DASHBOARD_ROUTES: list[tuple[str, str, Handler, bool]] = [ @@ -3473,7 +3484,7 @@ def setup_routes( "POST": router.add_post, "DELETE": router.add_delete, } - api_routes = [r for r in ROUTES if r[1] == "/api/health"] if cdm_only else ROUTES + api_routes = [r for r in ROUTES if r[1] == HEALTH_ROUTE] if cdm_only else ROUTES for method, path, handler, remote in api_routes + (DASHBOARD_ROUTES if dashboard else []): if remote_only and not remote: continue diff --git a/unshackle/core/api/session_log.py b/unshackle/core/api/session_log.py index ce7c27a0..0debde15 100644 --- a/unshackle/core/api/session_log.py +++ b/unshackle/core/api/session_log.py @@ -18,9 +18,10 @@ import threading import time import traceback from collections import deque -from typing import Any, Deque, Dict, List, MutableMapping, Optional, Tuple +from typing import Any, Deque, List, MutableMapping, Optional, Tuple from unshackle.core.api.sanitize import sanitize_log +from unshackle.core.remote_protocol import LogRecord MAX_RECORDS = 500 MAX_MESSAGE_LEN = 2000 @@ -30,7 +31,7 @@ class SessionLogBuffer: """Thread-safe bounded buffer of log records with a monotonic sequence.""" def __init__(self, maxlen: int = MAX_RECORDS) -> None: - self._records: Deque[Dict[str, Any]] = deque(maxlen=maxlen) + self._records: Deque[LogRecord] = deque(maxlen=maxlen) self._seq = 0 self._lock = threading.Lock() @@ -38,18 +39,18 @@ class SessionLogBuffer: with self._lock: self._seq += 1 self._records.append( - { - "seq": self._seq, - "level": logging.getLevelName(level), - "message": sanitize_log(message)[:MAX_MESSAGE_LEN], - "ts": time.time(), - } + LogRecord( + seq=self._seq, + level=logging.getLevelName(level), + message=sanitize_log(message)[:MAX_MESSAGE_LEN], + ts=time.time(), + ) ) - def since(self, seq: int) -> List[Dict[str, Any]]: + def since(self, seq: int) -> List[LogRecord]: """Records with a sequence number greater than *seq*, oldest first.""" with self._lock: - return [dict(r) for r in self._records if r["seq"] > seq] + return [r.copy() for r in self._records if r["seq"] > seq] @property def last_seq(self) -> int: diff --git a/unshackle/core/api/session_store.py b/unshackle/core/api/session_store.py index 926f2064..2753b1cb 100644 --- a/unshackle/core/api/session_store.py +++ b/unshackle/core/api/session_store.py @@ -17,9 +17,10 @@ from datetime import datetime, timezone from typing import Any, Deque, Dict, List, Optional from unshackle.core.api.events import bus -from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, AuthStatus, InputBridge +from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, InputBridge from unshackle.core.api.sanitize import sanitize_log from unshackle.core.config import config +from unshackle.core.remote_protocol import AuthStatus from unshackle.core.tracks import Track log = logging.getLogger("api.session") @@ -369,7 +370,8 @@ session_store: Optional[SessionStore] = None def refuse_while_draining() -> None: """Raise SERVER_DRAINING for a new session or job once the operator has started a drain.""" - from unshackle.core.api.errors import APIError, APIErrorCode + from unshackle.core.api.errors import APIError + from unshackle.core.remote_protocol import APIErrorCode if get_session_store().draining: raise APIError( diff --git a/unshackle/core/remote_protocol.py b/unshackle/core/remote_protocol.py new file mode 100644 index 00000000..34100284 --- /dev/null +++ b/unshackle/core/remote_protocol.py @@ -0,0 +1,253 @@ +"""The remote session protocol: the routes, login states, error codes and message shapes of client and server. + +``dl --remote`` (:mod:`unshackle.core.remote_service`) and the server (:mod:`unshackle.core.api`) both read this +record. Titles, tracks and DRM keep the form of :mod:`unshackle.core.wire`, and ``dl_params`` that of +:mod:`unshackle.core.dl_options`. Every name and value here is on the wire, so a change must stay readable by an +older peer. +""" + +from __future__ import annotations + +from enum import Enum, StrEnum +from typing import Any, Optional, TypedDict + +HEALTH_ROUTE = "/api/health" +SERVICES_ROUTE = "/api/services" +SEARCH_ROUTE = "/api/search" +SESSION_CREATE_ROUTE = "/api/session/create" +SESSION_ROUTE = "/api/session/{session_id}" +TITLES_ROUTE = SESSION_ROUTE + "/titles" +TRACKS_ROUTE = SESSION_ROUTE + "/tracks" +SEGMENTS_ROUTE = SESSION_ROUTE + "/segments" +SEGMENT_FILTER_ROUTE = SESSION_ROUTE + "/segment_filter" +SAMPLES_ROUTE = SESSION_ROUTE + "/samples" +LICENSE_ROUTE = SESSION_ROUTE + "/license" +BAD_KEY_ROUTE = SESSION_ROUTE + "/keys/bad" +LOGS_ROUTE = SESSION_ROUTE + "/logs" +PROMPT_ROUTE = SESSION_ROUTE + "/prompt" + + +class AuthStatus(StrEnum): + """Authentication lifecycle states for a remote session, as the ``status`` of a prompt reply.""" + + AUTHENTICATING = "authenticating" + PENDING_INPUT = "pending_input" + AUTHENTICATED = "authenticated" + FAILED = "failed" + + +class APIErrorCode(str, Enum): + """Standard API error codes for programmatic error handling.""" + + INVALID_INPUT = "INVALID_INPUT" + INVALID_SERVICE = "INVALID_SERVICE" + INVALID_PROXY = "INVALID_PROXY" + INVALID_PARAMETERS = "INVALID_PARAMETERS" + + AUTH_FAILED = "AUTH_FAILED" + FORBIDDEN = "FORBIDDEN" + SERVER_CDM_CAPPED = "SERVER_CDM_CAPPED" + GEOFENCE = "GEOFENCE" + + NOT_FOUND = "NOT_FOUND" + NO_CONTENT = "NO_CONTENT" + JOB_NOT_FOUND = "JOB_NOT_FOUND" + SESSION_NOT_FOUND = "SESSION_NOT_FOUND" + TRACK_NOT_FOUND = "TRACK_NOT_FOUND" + + CONFLICT = "CONFLICT" + + RATE_LIMITED = "RATE_LIMITED" + + INTERNAL_ERROR = "INTERNAL_ERROR" + SERVICE_ERROR = "SERVICE_ERROR" + NETWORK_ERROR = "NETWORK_ERROR" + DRM_ERROR = "DRM_ERROR" + DOWNLOAD_ERROR = "DOWNLOAD_ERROR" + SERVICE_UNAVAILABLE = "SERVICE_UNAVAILABLE" + SERVER_DRAINING = "SERVER_DRAINING" + WORKER_ERROR = "WORKER_ERROR" + + +class ClientErrorKind(StrEnum): + """The error kinds a remote client gives a failure of its own. The server never sends them. + + They share a namespace with :class:`APIErrorCode`, because ``RemoteError.kind`` holds either one. + """ + + CONNECT = "CONNECT" + TIMEOUT = "TIMEOUT" + AUTH = "AUTH" + TUNNEL_CLOSED = "TUNNEL_CLOSED" + GRANTS_CHANGED = "GRANTS_CHANGED" + UNKNOWN = "UNKNOWN" + + +class ClientLogin(TypedDict, total=False): + """The login material a client sends with a remote session or a search.""" + + credentials: dict[str, Any] + cookies: str + cache: dict[str, str] + + +class ClientInfo(TypedDict): + """What a client tells the server about itself, for the server's logs.""" + + version: str + code_hash: Optional[str] + platform: str + argv: str + + +class SessionCreate(ClientLogin, total=False): + """The body of a remote session creation.""" + + service: str + title_id: str + profile: str + service_params: dict[str, Any] + season: Any + episode: Any + part: Any + wanted: Any + proxy: Optional[str] + no_proxy: bool + client_region: str + proxy_region: str + server_cdm: bool + cdm_type: str + cdm_security_level: int + cdm_relay: bool + cdm_system_id: int + cdm_device_type: str + service_config: dict[str, Any] + range_: list[str] + vcodec: list[str] + quality: list[int] + best_available: bool + generate_dv: bool + dl_params: dict[str, Any] + client: ClientInfo + + +class SessionCreated(TypedDict, total=False): + """The reply to a remote session creation. An older server leaves out the licensing fields.""" + + session_id: str + service: str + status: str + server_account: bool + server_cdm: bool + server_cdm_max_height: Optional[int] + server_vault: bool + server_device: bool + + +class TracksRequest(TypedDict): + title_id: str + + +class TracksReply(TypedDict, total=False): + """The remote session fields of a tracks reply, beside the title, tracks and chapters in the form of ``core.wire``.""" + + session_headers: dict[str, str] + session_cookies: dict[str, str] + session_cookie_jar: list[dict[str, Any]] + server_cdm: Optional[bool] + server_cdm_type: str + sample_decrypt_tracks: list[str] + + +class SegmentFilterRequest(TypedDict): + track_id: str + + +class SegmentFilterReply(TypedDict): + """The segment URIs to skip; None when the track has no segment filter.""" + + unwanted: Optional[list[str]] + + +class LicenseRequest(TypedDict, total=False): + """A licence relay (``challenge``), a certificate request, or a server CDM key request (``mode`` server_cdm).""" + + track_id: str + track_ids: list[str] + challenge: str + drm_type: str + mode: str + pssh: str + kid: str + is_certificate: bool + + +class LicenseReply(TypedDict, total=False): + """A licence, a certificate, or the content keys of the server CDM. + + ``keys`` maps KID to content key for one ``track_id``, and track id to that map for ``track_ids``. A capped + track gets no content keys: ``capped_tracks`` holds its refusal details, ``reason`` and ``max_height``. + """ + + license: Optional[str] + keys: dict[str, Any] + vault_keys: list[str] + clear_tracks: list[str] + drm_type: str + drm_types: dict[str, str] + capped_tracks: dict[str, dict[str, Any]] + + +class BadKeyReport(TypedDict): + kid: str + key: str + + +class PromptReply(TypedDict, total=False): + """The login state of a remote session, and the prompt or CDM call that waits for the client.""" + + status: str + prompt: Optional[str] + cdm_call: dict[str, Any] + error: str + + +class PromptAnswer(TypedDict): + response: str + + +class LogRecord(TypedDict): + seq: int + level: str + message: str + ts: float + + +class LogsReply(TypedDict): + session_id: str + logs: list[LogRecord] + last_seq: int + + +class TitlesReply(TypedDict): + """The titles of a remote session, each in the form of ``core.wire``.""" + + session_id: str + titles: list[dict[str, Any]] + + +class SessionClosed(TypedDict, total=False): + """The reply to a closed remote session, with the service cache files that changed while it ran.""" + + status: str + cache: dict[str, str] + + +class SessionInfo(TypedDict, total=False): + session_id: str + service: str + valid: bool + expires_in: int + draining: bool + track_count: int + title_count: int diff --git a/unshackle/core/remote_service.py b/unshackle/core/remote_service.py index 4cdd4159..d126ff76 100644 --- a/unshackle/core/remote_service.py +++ b/unshackle/core/remote_service.py @@ -22,7 +22,7 @@ import time from collections import deque from http.cookiejar import CookieJar from threading import Event, Lock, Thread, local -from typing import Any, Callable, Dict, Iterable, Iterator, Optional, Protocol, TypeVar, Union +from typing import Any, Callable, Dict, Iterable, Iterator, Mapping, Optional, Protocol, TypeVar, Union, cast from urllib.parse import urlencode, urlsplit from uuid import UUID @@ -42,6 +42,40 @@ from unshackle.core.dl_options import remote_dl_params from unshackle.core.drm import cbcs, real_kids from unshackle.core.manifests.snapshot import match_track, restore from unshackle.core.proxies.resolve import is_loopback +from unshackle.core.remote_protocol import ( + BAD_KEY_ROUTE, + HEALTH_ROUTE, + LICENSE_ROUTE, + LOGS_ROUTE, + PROMPT_ROUTE, + SAMPLES_ROUTE, + SEARCH_ROUTE, + SEGMENT_FILTER_ROUTE, + SERVICES_ROUTE, + SESSION_CREATE_ROUTE, + SESSION_ROUTE, + TITLES_ROUTE, + TRACKS_ROUTE, + APIErrorCode, + AuthStatus, + BadKeyReport, + ClientErrorKind, + ClientLogin, + LicenseReply, + LicenseRequest, + LogsReply, + PromptAnswer, + PromptReply, + SegmentFilterReply, + SegmentFilterRequest, + SessionClosed, + SessionCreate, + SessionCreated, + SessionInfo, + TitlesReply, + TracksReply, + TracksRequest, +) from unshackle.core.search_result import SearchResult from unshackle.core.session import MAX_BACKOFF from unshackle.core.titles import Title_T, Titles_T, remap_titles @@ -65,9 +99,14 @@ SENSITIVE_DATA_KEYS = ("credential", "credentials", "password", "token", "api_ke DEFAULT_AUTH_HEADERS = ["X-Secret-Key", "X-Api-Key"] # error kinds after which the remote session may be gone: the server restarted, or the tunnel it used closed -SESSION_LOST = ("SESSION_NOT_FOUND", "CONNECT", "TIMEOUT", "TUNNEL_CLOSED") +SESSION_LOST = ( + APIErrorCode.SESSION_NOT_FOUND, + ClientErrorKind.CONNECT, + ClientErrorKind.TIMEOUT, + ClientErrorKind.TUNNEL_CLOSED, +) # what a recovering call can meet on its way, so these log only once the recovery fails -RECOVERABLE = (*SESSION_LOST, "SERVER_DRAINING") +RECOVERABLE = (*SESSION_LOST, APIErrorCode.SERVER_DRAINING) RETRY_AFTER_MAX = 3600 RETRY_AFTER_LOCK = Lock() RATE_LIMIT_TRIES = 3 @@ -108,7 +147,7 @@ def quiet() -> Iterator[None]: _mute.quiet = before -def redact_secrets(text: str, data: Optional[Dict[str, Any]] = None) -> str: +def redact_secrets(text: str, data: Optional[Mapping[str, Any]] = None) -> str: """Mask URL userinfo and any request-payload secrets before unshackle writes the text to the log.""" secrets = [v for k in SENSITIVE_DATA_KEYS if isinstance(v := (data or {}).get(k), str) and v] return redact_text(text, secrets) or "" @@ -135,7 +174,7 @@ class RemoteError(SystemExit): """A remote call that failed: logged, then exits a CLI run like ``SystemExit(1)``. A serve relaying for a REST client catches it instead and answers with ``message``; ``kind`` is the - remote server's error code, or CONNECT / TIMEOUT / AUTH when the remote session could not be reached or opened. + remote server's ``APIErrorCode``, or a ``ClientErrorKind`` when the client failed on its own side. (Not ``code``: SystemExit's ``code`` is the exit status.) """ @@ -200,7 +239,7 @@ class RemoteClient: self, method: str, endpoint: str, - data: Optional[Dict[str, Any]] = None, + data: Optional[Mapping[str, Any]] = None, optional: bool = False, expect: tuple[str, ...] = (), body: Optional[bytes] = None, @@ -223,7 +262,9 @@ class RemoteClient: if isinstance(e.args[0] if e.args else None, urllib3.exceptions.ReadTimeoutError): raise self.timed_out(endpoint) from None server_url = safe_display_url(self.server_url) - raise RemoteError(f"Could not connect to remote server at {server_url}", "CONNECT") from None + raise RemoteError( + f"Could not connect to remote server at {server_url}", ClientErrorKind.CONNECT + ) from None except requests.Timeout: raise self.timed_out(endpoint) from None # servers differ on which header carries the key, so retry the rest before giving up @@ -263,17 +304,17 @@ class RemoteClient: error_msg = redact_secrets(str(detail.get("message", fallback)), data) # a gateway's own error page means the server behind it is down, as when it restarts error_code = detail.get("error_code") or ( - "CONNECT" if resp.status_code >= 500 and not detail else "UNKNOWN" + ClientErrorKind.CONNECT if resp.status_code >= 500 and not detail else ClientErrorKind.UNKNOWN ) if error_code in expect: return detail - if optional and error_code != "SESSION_NOT_FOUND": + if optional and error_code != APIErrorCode.SESSION_NOT_FOUND: log.debug(f"Optional endpoint {endpoint} unavailable [{error_code}]: {error_msg}") return {} if self.tunnel and self.tunnel.lost: raise RemoteError( "The tunnel to the server closed", - "TUNNEL_CLOSED", + ClientErrorKind.TUNNEL_CLOSED, ) raise RemoteError(f"Server error [{error_code}]: {error_msg}", error_code) return detail @@ -281,13 +322,13 @@ class RemoteClient: def timed_out(self, endpoint: str) -> RemoteError: return RemoteError( f"Request to remote server timed out after {self.timeout}s: {endpoint}", - "TIMEOUT", + ClientErrorKind.TIMEOUT, ) - def post(self, endpoint: str, data: Dict[str, Any], expect: tuple[str, ...] = ()) -> Dict[str, Any]: + def post(self, endpoint: str, data: Mapping[str, Any], expect: tuple[str, ...] = ()) -> Dict[str, Any]: return self.request("post", endpoint, data, expect=expect) - def post_optional(self, endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]: + def post_optional(self, endpoint: str, data: Mapping[str, Any]) -> Dict[str, Any]: """POST to an endpoint that an older server may not have. Empty dict when the route is missing.""" return self.request("post", endpoint, data, optional=True) @@ -475,7 +516,7 @@ def remote_service_list(server_name: Optional[str]) -> Optional[list[dict]]: services: Optional[list[dict]] = None try: with quiet(): - services = remote_client(server_name).get("/api/services").get("services") or [] + services = remote_client(server_name).get(SERVICES_ROUTE).get("services") or [] except (Exception, SystemExit) as e: log.warning(f"Could not list the services of remote server '{server_name}': {e}") _remote_lists[server_name] = (time.monotonic(), services) @@ -904,7 +945,7 @@ class RemoteService: data["proxy"] = resolve_remote_proxy_arg(server_proxy_arg(params), providers) self.require_reachable_proxy(data["proxy"]) try: - response = self.client.post("/api/search", data) + response = self.client.post(SEARCH_ROUTE, data) finally: if self.client.tunnel: # a search is one request, so its tunnel ends with it self.client.tunnel.stop() @@ -914,16 +955,18 @@ class RemoteService: result["id"], result["title"], result.get("description"), result.get("label"), result.get("url") ) - def client_login(self, profile: Optional[str]) -> Dict[str, Any]: + def client_login(self, profile: Optional[str]) -> ClientLogin: """The credentials, cookies and cache to send, or nothing when the server manages the account.""" + login = ClientLogin() if self._server_accounts is not None: - return {} - fields = { - "credentials": load_credentials_for_transport(self.service_tag, profile), - "cookies": load_cookies_for_transport(self.service_tag, profile), - "cache": self.load_cache_files(profile), - } - return {k: v for k, v in fields.items() if v} + return login + if credentials := load_credentials_for_transport(self.service_tag, profile): + login["credentials"] = credentials + if cookies := load_cookies_for_transport(self.service_tag, profile): + login["cookies"] = cookies + if cache := self.load_cache_files(profile): + login["cache"] = cache + return login def require_reachable_proxy(self, proxy: Optional[str]) -> None: """Refuse a proxy on this machine when the server is elsewhere: the server cannot reach it.""" @@ -951,11 +994,13 @@ class RemoteService: proxy = self.ctx.parent.params.get("proxy") if self.ctx.parent else None no_proxy = self.ctx.parent.params.get("no_proxy", False) if self.ctx.parent else False - create_data: Dict[str, Any] = {"service": self.service_tag, "title_id": self.title_id} + create_data: SessionCreate = { + "service": self.service_tag, + "title_id": self.title_id, + **self.client_login(profile), + } - if self._server_accounts is None: - create_data.update(self.client_login(profile)) - else: + if self._server_accounts is not None: self.credential = None self.log.info( "The server manages the account for this service" + (" and ignores --profile" if profile else "") @@ -1079,7 +1124,7 @@ class RemoteService: } try: - result = self.client.post("/api/session/create", create_data) + result = cast(SessionCreated, self.client.post(SESSION_CREATE_ROUTE, create_data)) except BaseException: if local and self.client.tunnel: # no session, so close() never runs: free the tunnel now self.client.tunnel.stop() @@ -1104,8 +1149,8 @@ class RemoteService: # without the server vault grant the server refuses every key request, so none is sent self._local_vaults_only = self._server_device and not vault - status = result.get("status", "authenticated") - if status == "authenticating": + status = result.get("status", AuthStatus.AUTHENTICATED) + if status == AuthStatus.AUTHENTICATING: self.poll_auth_completion() if create_data.get("cdm_relay"): self.client.in_flight = self.answering_cdm_calls @@ -1166,9 +1211,9 @@ class RemoteService: a request at an interval of one third of it. The thread stops when ``close()`` or a reopen runs. A client that dies stops sending requests, so the server still expires an abandoned remote session. """ - info = self.client.get_optional(f"/api/session/{self._session_id}") + info = cast(SessionInfo, self.client.get_optional(SESSION_ROUTE.format(session_id=self._session_id))) interval = max(float(info.get("expires_in") or 300) / 3, 5.0) - url = f"{self.client.server_url}/api/session/{self._session_id}" + url = self.client.server_url + SESSION_ROUTE.format(session_id=self._session_id) stop = self._keepalive_stop = Event() def ping() -> None: @@ -1208,13 +1253,13 @@ class RemoteService: return self._session_id is not None if session_id is None or not self.wait_for_server(accepting=False): return False - url = f"{self.client.server_url}/api/session/{session_id}" + url = self.client.server_url + SESSION_ROUTE.format(session_id=session_id) try: - alive = kind != "TUNNEL_CLOSED" and self.client.session.get(url, timeout=30).ok + alive = kind != ClientErrorKind.TUNNEL_CLOSED and self.client.session.get(url, timeout=30).ok except requests.RequestException: alive = False if alive: - return kind == "CONNECT" + return kind == ClientErrorKind.CONNECT self.log.warning("The remote session was lost, opening a new one") return self.reopen() @@ -1225,7 +1270,7 @@ class RemoteService: warned = False while True: try: - health = self.client.session.get(f"{self.client.server_url}/api/health", timeout=30).json() + health = self.client.session.get(self.client.server_url + HEALTH_ROUTE, timeout=30).json() if health.get("status") == "ok" and not (accepting and health.get("draining")): return True except (requests.RequestException, ValueError, AttributeError): @@ -1257,7 +1302,9 @@ class RemoteService: try: with recovering(): self.authenticate(credential=self.credential) - listing = self.client.get(f"/api/session/{self._session_id}/titles").get("titles", []) + listing = cast(TitlesReply, self.client.get(TITLES_ROUTE.format(session_id=self._session_id))).get( + "titles", [] + ) fresh_titles = [build_title(t, self.service_tag, self.title_id) for t in listing] for old in self._titles or []: same = [t for t in fresh_titles if title_key(t) == title_key(old)] @@ -1280,7 +1327,9 @@ class RemoteService: raise return False if (self._server_cdm, self._server_device, self._server_vault) != grants: - raise RemoteError("The new remote session licenses differently from the lost one", "GRANTS_CHANGED") + raise RemoteError( + "The new remote session licenses differently from the lost one", ClientErrorKind.GRANTS_CHANGED + ) return True def reopen_after_drain(self) -> None: @@ -1290,13 +1339,17 @@ class RemoteService: self.close() self._current_title = None if not self.reopen(): - raise RemoteError(f"The remote server did not come back within {REOPEN_WAIT:.0f}s", "CONNECT") + raise RemoteError( + f"The remote server did not come back within {REOPEN_WAIT:.0f}s", ClientErrorKind.CONNECT + ) def server_draining(self) -> bool: """Whether the server announced a restart; asked once per title, as an episode can be shorter than the keepalive.""" try: - url = f"{self.client.server_url}/api/session/{self._session_id}" - return bool(self._session_id and self.client.session.get(url, timeout=30).json().get("draining")) + url = self.client.server_url + SESSION_ROUTE.format(session_id=self._session_id) + return bool( + self._session_id and cast(SessionInfo, self.client.session.get(url, timeout=30).json()).get("draining") + ) except (requests.RequestException, ValueError, AttributeError): return False @@ -1317,7 +1370,8 @@ class RemoteService: with self._log_drain_lock: try: with quiet(): - resp = self.client.get_optional(f"/api/session/{self._session_id}/logs?since={self._log_seq}") + endpoint = LOGS_ROUTE.format(session_id=self._session_id) + f"?since={self._log_seq}" + resp = cast(LogsReply, self.client.get_optional(endpoint)) except (Exception, SystemExit): return if not resp: @@ -1347,43 +1401,47 @@ class RemoteService: def poll_auth(self, deadline: float, poll_interval: float) -> None: while time.monotonic() < deadline: - resp = self.client.get(f"/api/session/{self._session_id}/prompt") + resp = cast(PromptReply, self.client.get(PROMPT_ROUTE.format(session_id=self._session_id))) status = resp.get("status") seen = self._log_seq self.drain_server_logs() - if status == "authenticated": + if status == AuthStatus.AUTHENTICATED: return - if status == "authenticating" and self._log_seq == seen and self._recent_logs: + if status == AuthStatus.AUTHENTICATING and self._log_seq == seen and self._recent_logs: notice = "\n".join(self._recent_logs) if notice != self.auth_notice: self.auth_notice = notice show_notice(notice) - if status == "failed": - raise RemoteError(f"Remote auth failed: {resp.get('error', 'Authentication failed on server')}", "AUTH") + if status == AuthStatus.FAILED: + raise RemoteError( + f"Remote auth failed: {resp.get('error', 'Authentication failed on server')}", ClientErrorKind.AUTH + ) - if status == "pending_input" and isinstance(resp.get("cdm_call"), dict): + if status == AuthStatus.PENDING_INPUT and isinstance(resp.get("cdm_call"), dict): self.answer_cdm_call(resp["cdm_call"], self._cdm_sessions) continue - if status == "pending_input": - prompt = resp.get("prompt", "Enter input: ") + if status == AuthStatus.PENDING_INPUT: + prompt = resp.get("prompt") or "Enter input: " bridge = self._input_bridge try: user_response = bridge.request_input(prompt) if bridge else prompt_user(prompt) except EOFError: - raise RemoteError("Remote auth needs interactive input but stdin is closed", "AUTH") from None + raise RemoteError( + "Remote auth needs interactive input but stdin is closed", ClientErrorKind.AUTH + ) from None self.client.post( - f"/api/session/{self._session_id}/prompt", - {"response": user_response}, + PROMPT_ROUTE.format(session_id=self._session_id), + PromptAnswer(response=user_response), ) continue time.sleep(poll_interval) - raise RemoteError("Remote authentication timed out", "AUTH") + raise RemoteError("Remote authentication timed out", ClientErrorKind.AUTH) def answer_cdm_call(self, call: Dict[str, Any], sessions: Dict[str, bytes]) -> None: """Run one of the server's CDM calls on this machine's device and post the answer.""" @@ -1391,7 +1449,7 @@ class RemoteService: answer = answer_cdm_call(self.local_cdm, call, sessions) self.log.debug(f"Answered a server CDM call: {call.get('op')} ({'refused' if 'error' in answer else 'ok'})") - self.client.post(f"/api/session/{self._session_id}/prompt", {"response": json.dumps(answer)}) + self.client.post(PROMPT_ROUTE.format(session_id=self._session_id), PromptAnswer(response=json.dumps(answer))) @contextlib.contextmanager def answering_cdm_calls(self, endpoint: str) -> Iterator[None]: @@ -1399,8 +1457,9 @@ class RemoteService: One poller serves every concurrent request, and the local CDM sessions close when the last one ends. """ - if not endpoint.startswith(f"/api/session/{self._session_id}/") or endpoint.partition("?")[0].endswith( - ("/prompt", "/logs", "/samples") + own = {route.format(session_id=self._session_id) for route in (PROMPT_ROUTE, LOGS_ROUTE, SAMPLES_ROUTE)} + if not endpoint.startswith(SESSION_ROUTE.format(session_id=self._session_id) + "/") or ( + endpoint.partition("?")[0] in own ): yield return @@ -1420,11 +1479,11 @@ class RemoteService: self._cdm_stop.set() def poll_cdm_calls(self, stop: Event, interval: float = 0.5) -> None: - url = f"{self.client.server_url}/api/session/{self._session_id}/prompt" + url = self.client.server_url + PROMPT_ROUTE.format(session_id=self._session_id) sessions: Dict[str, bytes] = {} while not stop.wait(interval): try: - call = self.client.session.get(url, timeout=30).json().get("cdm_call") + call = cast(PromptReply, self.client.session.get(url, timeout=30).json()).get("cdm_call") if isinstance(call, dict): with quiet(): self.answer_cdm_call(call, sessions) @@ -1445,7 +1504,9 @@ class RemoteService: if self._titles is not None: return self._titles try: - result = self.session_call(lambda sid: self.client.get(f"/api/session/{sid}/titles")) + result = cast( + TitlesReply, self.session_call(lambda sid: self.client.get(TITLES_ROUTE.format(session_id=sid))) + ) finally: self.drain_server_logs() titles_list = [build_title(t, self.service_tag, self.title_id) for t in result.get("titles", [])] @@ -1477,7 +1538,8 @@ class RemoteService: try: result = self.session_call( lambda sid: self.client.post( - f"/api/session/{sid}/tracks", {"title_id": self._title_alias.get(title_id, title_id)} + TRACKS_ROUTE.format(session_id=sid), + TracksRequest(title_id=self._title_alias.get(title_id, title_id)), ) ) finally: @@ -1488,7 +1550,8 @@ class RemoteService: if remote_title: apply_title_fields(title, remote_title) - for k, v in result.get("session_headers", {}).items(): + session_fields = cast(TracksReply, result) + for k, v in session_fields.get("session_headers", {}).items(): if k.lower() not in ("host", "content-length", "content-type"): self._session.headers[k] = v apply_session_cookies(self._session, result) @@ -1496,14 +1559,14 @@ class RemoteService: restore(tracks, result) apply_service_track_data(tracks, result) - server_cdm = bool(result.get("server_cdm", False)) or getattr(self, "_server_device", False) + server_cdm = bool(session_fields.get("server_cdm", False)) or getattr(self, "_server_device", False) if self._server_cdm is None: self._server_cdm = server_cdm elif self._server_cdm and not server_cdm: self._server_cdm = False self.report_local_fallback() - self.server_cdm_type = result.get("server_cdm_type", "widevine") - self._sample_decrypt_tracks.update(result.get("sample_decrypt_tracks") or []) + self.server_cdm_type = session_fields.get("server_cdm_type", "widevine") + self._sample_decrypt_tracks.update(session_fields.get("sample_decrypt_tracks") or []) for track in [*tracks.videos, *tracks.audio, *tracks.subtitles]: if track.descriptor == Track.Descriptor.HLS: @@ -1523,7 +1586,7 @@ class RemoteService: def samples(body: bytes) -> Dict[str, Any]: def call(sid: Optional[str]) -> Dict[str, Any]: query = urlencode({"track_id": self.server_track_id(track.id), "entry": entry}) - return self.client.request("post", f"/api/session/{sid}/samples?{query}", body=body) + return self.client.request("post", SAMPLES_ROUTE.format(session_id=sid) + f"?{query}", body=body) return self.session_call(call) @@ -1551,8 +1614,13 @@ class RemoteService: unwanted = self._segment_filters.get(track_id) if unwanted is None: server_id = self.server_track_id(track_id) - result = self.session_call( - lambda sid: self.client.post_optional(f"/api/session/{sid}/segment_filter", {"track_id": server_id}) + result = cast( + SegmentFilterReply, + self.session_call( + lambda sid: self.client.post_optional( + SEGMENT_FILTER_ROUTE.format(session_id=sid), SegmentFilterRequest(track_id=server_id) + ) + ), ) unwanted = segment_uri_filter(result.get("unwanted") or []) self._segment_filters[track_id] = unwanted @@ -1591,15 +1659,18 @@ class RemoteService: capped: Dict[str, Any] = {} try: with console.status("Retrieving Remote License...", spinner="dots"): - resp = self.session_call( - lambda sid: self.client.post( - f"/api/session/{sid}/license", - { - "track_ids": [self.server_track_id(t.id) for t in keyed], - "mode": "server_cdm", - "drm_type": drm_type, - }, - ) + resp = cast( + LicenseReply, + self.session_call( + lambda sid: self.client.post( + LICENSE_ROUTE.format(session_id=sid), + LicenseRequest( + track_ids=[self.server_track_id(t.id) for t in keyed], + mode="server_cdm", + drm_type=drm_type, + ), + ) + ), ) track_ids = [self.server_track_id(t.id) for t in keyed] self.drain_server_logs() @@ -1723,7 +1794,9 @@ class RemoteService: try: with quiet(): self.session_call( - lambda sid: self.client.post_optional(f"/api/session/{sid}/keys/bad", {"kid": kid.hex, "key": key}) + lambda sid: self.client.post_optional( + BAD_KEY_ROUTE.format(session_id=sid), BadKeyReport(kid=kid.hex, key=key) + ) ) except (Exception, RemoteError) as e: self.log.debug(f"Could not report the bad content key to the server: {e}") @@ -1804,18 +1877,21 @@ class RemoteService: track: AnyTrack, ) -> Optional[Union[bytes, str]]: # a missing certificate is legal (services may not use one), so a failed fetch continues without one - resp = self.session_call( - lambda sid: self.client.post_optional( - f"/api/session/{sid}/license", - { - "track_id": self.server_track_id(track.id), - "challenge": base64.b64encode(challenge).decode("ascii"), - "drm_type": "widevine", - "is_certificate": True, - }, - ) + resp = cast( + LicenseReply, + self.session_call( + lambda sid: self.client.post_optional( + LICENSE_ROUTE.format(session_id=sid), + LicenseRequest( + track_id=self.server_track_id(track.id), + challenge=base64.b64encode(challenge).decode("ascii"), + drm_type="widevine", + is_certificate=True, + ), + ) + ), ) - return base64.b64decode(resp["license"]) if resp.get("license") else None + return base64.b64decode(certificate) if (certificate := resp.get("license")) else None def proxy_license( self, challenge: Union[bytes, str], track: AnyTrack, drm_type: str, kid: Optional[UUID] = None @@ -1842,18 +1918,18 @@ class RemoteService: refusal: Optional[Dict[str, Any]] = None if pssh_b64: try: - request = {"drm_type": drm_type, "mode": "server_cdm", "pssh": pssh_b64} + request = LicenseRequest(drm_type=drm_type, mode="server_cdm", pssh=pssh_b64) if kid: request["kid"] = kid.hex with quiet(): resp = self.session_call( lambda sid: self.client.post( - f"/api/session/{sid}/license", - {**request, "track_id": self.server_track_id(track.id)}, - expect=("SERVER_CDM_CAPPED",), + LICENSE_ROUTE.format(session_id=sid), + LicenseRequest(**request, track_id=self.server_track_id(track.id)), + expect=(APIErrorCode.SERVER_CDM_CAPPED,), ) ) - if resp.get("error_code") == "SERVER_CDM_CAPPED": + if resp.get("error_code") == APIErrorCode.SERVER_CDM_CAPPED: refusal = resp.get("details") or {} self.server_cdm_type = resp.get("drm_type", server_type) keys = resp.get("keys", {}) @@ -1875,10 +1951,7 @@ class RemoteService: pssh_b64 = track_pssh(track, drm_type) - payload = { - "challenge": base64.b64encode(challenge).decode("ascii"), - "drm_type": drm_type, - } + payload = LicenseRequest(challenge=base64.b64encode(challenge).decode("ascii"), drm_type=drm_type) if pssh_b64: payload["pssh"] = pssh_b64 @@ -1886,7 +1959,8 @@ class RemoteService: with quiet(): resp = self.session_call( lambda sid: self.client.post( - f"/api/session/{sid}/license", {**payload, "track_id": self.server_track_id(track.id)} + LICENSE_ROUTE.format(session_id=sid), + LicenseRequest(**payload, track_id=self.server_track_id(track.id)), ) ) except RemoteError as e: @@ -1918,7 +1992,7 @@ class RemoteService: if session_id: try: with quiet(): - result = self.client.delete(f"/api/session/{session_id}") + result = cast(SessionClosed, self.client.delete(SESSION_ROUTE.format(session_id=session_id))) profile = self.ctx.parent.params.get("profile") if self.ctx.parent else None self.save_returned_cache(result.get("cache", {}), profile) except SystemExit: