mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-05 15:35:06 +00:00
feat(remote): send the client's services.<TAG>.preferences to the server in every licensing mode
This commit is contained in:
@@ -68,6 +68,13 @@ unshackle dl EX 20914 # via an ALIAS
|
|||||||
placeholders while the secrets that fill them stay out of it. Both halves
|
placeholders while the secrets that fill them stay out of it. Both halves
|
||||||
read back through the same `self.config[...]`.
|
read back through the same `self.config[...]`.
|
||||||
|
|
||||||
|
!!! tip "User choices go under `preferences`"
|
||||||
|
Put each choice a user makes (a metadata language, a subtitle format) under
|
||||||
|
`preferences` in `config.yaml`, and read it from `self.config["preferences"]`.
|
||||||
|
Over `--remote`, the client's own `services.<TAG>.preferences` values reach
|
||||||
|
that block on the server with no extra code. See
|
||||||
|
[Your preferences](rest-api/remote-sessions.md#your-preferences).
|
||||||
|
|
||||||
!!! warning "Split across files? Use relative imports"
|
!!! warning "Split across files? Use relative imports"
|
||||||
If your service grows beyond a single `__init__.py`, import your own
|
If your service grows beyond a single `__init__.py`, import your own
|
||||||
modules **relatively**:
|
modules **relatively**:
|
||||||
|
|||||||
@@ -376,7 +376,7 @@ licence at all: each content key comes from the server vault or the client's own
|
|||||||
and a content key that no vault holds stops the download with an error that names its KID,
|
and a content key that no vault holds stops the download with an error that names its KID,
|
||||||
when the client knows it. The create response sets `server_device` to `true` for such a
|
when the client knows it. The create response sets `server_device` to `true` for such a
|
||||||
remote session. The service then uses the server's own config: the client's identity
|
remote session. The service then uses the server's own config: the client's identity
|
||||||
values do not apply. The client reads the
|
values do not apply, but its preferences do (see [Your preferences](#your-preferences)). The client reads the
|
||||||
server vault only when the API key has the `server_vault` grant (or `server_cdm`); without
|
server vault only when the API key has the `server_vault` grant (or `server_cdm`); without
|
||||||
it, the client reads only its own vaults. The login tokens of such a remote session hold the
|
it, the client reads only its own vaults. The login tokens of such a remote session hold the
|
||||||
server's device identity, so the server keeps them: `DELETE` returns no cache files, and the
|
server's device identity, so the server keeps them: `DELETE` returns no cache files, and the
|
||||||
@@ -388,6 +388,27 @@ HTTP session headers and `track.data` lose their secret-looking keys, as for a s
|
|||||||
vault first. A track that no server vault holds goes back to your device. See
|
vault first. A track that no server vault holds goes back to your device. See
|
||||||
[`server_vault`](../../reference/configuration/services.md).
|
[`server_vault`](../../reference/configuration/services.md).
|
||||||
|
|
||||||
|
### Your preferences
|
||||||
|
|
||||||
|
The `preferences` block of a service is the place for user choices, such as a metadata
|
||||||
|
language or a subtitle format. It is not an identity, so it crosses `--remote` in every
|
||||||
|
licensing mode, whatever CDM the client has, and no service declares anything for it:
|
||||||
|
|
||||||
|
- The client sends each entry of its own `services: <TAG>: preferences:` block in
|
||||||
|
`unshackle.yaml` that is a string, a number or a boolean. It leaves out other entries and
|
||||||
|
logs one debug line for each.
|
||||||
|
- The server merges the entries key by key over its own `preferences` block for that
|
||||||
|
service. An entry that the client sends replaces the server's value, and a config key that
|
||||||
|
the client does not send keeps the server's value. The entries never count as an identity,
|
||||||
|
and they stay when the service builds the remote session on the server's device.
|
||||||
|
- The server refuses a `preferences` value that is not an object of strings, numbers and
|
||||||
|
booleans with `INVALID_INPUT`.
|
||||||
|
|
||||||
|
A service reads its preferences from `self.config["preferences"]`, locally and over
|
||||||
|
`--remote` alike. Keep a value that changes the server's account (a profile, an account
|
||||||
|
type) out of `preferences` unless every client of the server may choose it: a server
|
||||||
|
account is shared, and the service can store the choice in its cache.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Remote session lifecycle and expiry
|
## Remote session lifecycle and expiry
|
||||||
@@ -497,7 +518,8 @@ session when the new one is stored, and the server answers the ID of another API
|
|||||||
`no_proxy`, `profile`, `cache` (a map of `filename → base64(zlib(bytes))`),
|
`no_proxy`, `profile`, `cache` (a map of `filename → base64(zlib(bytes))`),
|
||||||
`client_region`, `server_cdm` (`false` when the user picked the local CDM), `cdm_type`, `cdm_security_level`, `cdm_relay` (`true` when the client
|
`client_region`, `server_cdm` (`false` when the user picked the local CDM), `cdm_type`, `cdm_security_level`, `cdm_relay` (`true` when the client
|
||||||
answers CDM calls; a plugin `cdm_type` gets no relay), `cdm_system_id` and `cdm_device_type` (Widevine only), `service_config`
|
answers CDM calls; a plugin `cdm_type` gets no relay), `cdm_system_id` and `cdm_device_type` (Widevine only), `service_config`
|
||||||
(the identity config keys the service lists in `client_config`), `plugins` (the version of each DRM plugin of the
|
(the identity config keys the service lists in `client_config`, and the client's
|
||||||
|
[preferences](#your-preferences)), `plugins` (the version of each DRM plugin of the
|
||||||
client and the values of the plugin device attributes that the plugin names in `device_facts`; see
|
client and the values of the plugin device attributes that the plugin names in `device_facts`; see
|
||||||
[endpoints](endpoints.md#post-apisessioncreate)), `client` (a freeform identity
|
[endpoints](endpoints.md#post-apisessioncreate)), `client` (a freeform identity
|
||||||
object the dashboard shows as sent), and the track-selection hints `range_`, `vcodec`,
|
object the dashboard shows as sent), and the track-selection hints `range_`, `vcodec`,
|
||||||
|
|||||||
@@ -31,7 +31,10 @@ other values in the same section stay.
|
|||||||
|
|
||||||
Over `--remote`, the server builds the service from its own config. The client sends only the
|
Over `--remote`, the server builds the service from its own config. The client sends only the
|
||||||
config keys that the service lists for a client identity, see
|
config keys that the service lists for a client identity, see
|
||||||
[your own device identity](../../dev/rest-api/remote-sessions.md#your-own-device-identity).
|
[your own device identity](../../dev/rest-api/remote-sessions.md#your-own-device-identity),
|
||||||
|
and the strings, numbers and booleans of its `preferences` block. Each preference that you set
|
||||||
|
replaces the server's value for that config key, in every licensing mode, see
|
||||||
|
[your preferences](../../dev/rest-api/remote-sessions.md#your-preferences).
|
||||||
For every other setting, the value in the server's config applies.
|
For every other setting, the value in the server's config applies.
|
||||||
|
|
||||||
User- or device-specific values (API keys, account IDs, device attributes) belong in this block
|
User- or device-specific values (API keys, account IDs, device attributes) belong in this block
|
||||||
|
|||||||
@@ -0,0 +1,178 @@
|
|||||||
|
"""The services.<TAG>.preferences block: a remote client sends its own entries in every licensing mode."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from tests.remote.key_source import remote_session
|
||||||
|
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.remote_protocol import Licensor
|
||||||
|
from unshackle.core.remote_service import RemoteService
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.unit
|
||||||
|
|
||||||
|
SERVER = {"preferences": {"language": "en-US", "profile": 0}, "esn": "SERVER", "other": 1}
|
||||||
|
CLIENT = {"language": "ja-JP", "remove_dub_cards": True, "ratio": 1.5}
|
||||||
|
MERGED = {"language": "ja-JP", "profile": 0, "remove_dub_cards": True, "ratio": 1.5}
|
||||||
|
WIDEVINE_CDM = SimpleNamespace(is_playready=False)
|
||||||
|
|
||||||
|
|
||||||
|
class Plain:
|
||||||
|
"""A service that declares nothing about its config."""
|
||||||
|
|
||||||
|
|
||||||
|
class Identity:
|
||||||
|
CLIENT_CONFIG = ("esn",)
|
||||||
|
|
||||||
|
|
||||||
|
def launched(monkeypatch: pytest.MonkeyPatch, licensor: Licensor, supplied: Any, service: type = Plain) -> dict:
|
||||||
|
"""The config and launch keys that the server gives a remote session of ``service``."""
|
||||||
|
built: dict = {}
|
||||||
|
monkeypatch.setattr(
|
||||||
|
key_policy, "load_service_config", lambda tag: {**SERVER, "preferences": {**SERVER["preferences"]}}
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: "server-device")
|
||||||
|
monkeypatch.setattr(
|
||||||
|
handlers, "served_context", lambda obj, plan, keys: built.update(cdm=obj.cdm, config=obj.config, keys=keys)
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(handlers.Services, "load", lambda tag: service)
|
||||||
|
monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: SimpleNamespace())
|
||||||
|
data = {"cdm_type": "widevine", "cdm_relay": True, "service_config": supplied}
|
||||||
|
launch_session("EXAMPLE1", "t", data, licensor=licensor)
|
||||||
|
return built
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("service", [Plain, Identity])
|
||||||
|
def test_a_server_cdm_session_takes_the_client_preferences(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, service: type
|
||||||
|
) -> None:
|
||||||
|
built = launched(monkeypatch, Licensor.SERVER_CDM, {"preferences": CLIENT, "esn": "CLIENT"}, service)
|
||||||
|
|
||||||
|
assert built["config"]["preferences"] == MERGED
|
||||||
|
assert built["config"]["esn"] == "SERVER"
|
||||||
|
assert built["keys"]["client_identity"] is False
|
||||||
|
assert "Ignoring service_config.preferences" not in caplog.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_client_device_session_takes_the_identity_and_the_preferences(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
built = launched(monkeypatch, Licensor.CLIENT_DEVICE, {"preferences": CLIENT, "esn": "CLIENT"}, Identity)
|
||||||
|
|
||||||
|
assert built["config"] == {"preferences": MERGED, "esn": "CLIENT", "other": 1}
|
||||||
|
assert built["keys"]["client_identity"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_preferences_alone_are_no_identity(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
built = launched(monkeypatch, Licensor.CLIENT_DEVICE, {"preferences": {"language": "ja-JP"}}, Identity)
|
||||||
|
|
||||||
|
assert built["config"] == {**SERVER, "preferences": {"language": "ja-JP", "profile": 0}}
|
||||||
|
assert built["keys"]["client_identity"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_service_that_lists_preferences_as_an_identity_still_merges_them(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
class Listed:
|
||||||
|
CLIENT_CONFIG = ("esn", "preferences")
|
||||||
|
|
||||||
|
built = launched(monkeypatch, Licensor.SERVER_CDM, {"preferences": {"language": "ja-JP"}}, Listed)
|
||||||
|
|
||||||
|
assert built["config"]["preferences"] == {"language": "ja-JP", "profile": 0}
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_lent_device_keeps_the_client_preferences(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
built = launched(monkeypatch, Licensor.CLIENT_DEVICE, {"preferences": CLIENT, "esn": "CLIENT"}, Identity)
|
||||||
|
|
||||||
|
assert built["cdm"].lend_server_device() == "server-device"
|
||||||
|
assert built["config"] == {**SERVER, "preferences": MERGED}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"supplied",
|
||||||
|
[
|
||||||
|
{"preferences": "ja-JP"},
|
||||||
|
{"preferences": ["ja-JP"]},
|
||||||
|
{"preferences": {"language": None}},
|
||||||
|
{"preferences": {"language": ["ja"]}},
|
||||||
|
{"preferences": {"language": {"nested": "ja"}}},
|
||||||
|
{"preferences": {"ratio": float("inf")}},
|
||||||
|
pytest.param({"preferences": {"language": "x" * 20000}}, id="over-the-cap"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_ill_formed_preferences_are_refused(monkeypatch: pytest.MonkeyPatch, supplied: Any) -> None:
|
||||||
|
with pytest.raises(APIError):
|
||||||
|
launched(monkeypatch, Licensor.SERVER_CDM, supplied)
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_identity_rules_stay_as_they_are() -> None:
|
||||||
|
merged, identity = handlers.client_config_overlay({"esn": "SERVER", "Kph": "k"}, ("esn", "Kph"), {"esn": "CLIENT"})
|
||||||
|
|
||||||
|
assert (merged, identity) == ({"esn": "CLIENT"}, True)
|
||||||
|
with pytest.raises(APIError):
|
||||||
|
handlers.client_config_overlay({}, ("esn",), {"esn": True})
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_client_reads_its_own_preferences(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||||
|
) -> None:
|
||||||
|
import unshackle.core.remote_service as remote_mod
|
||||||
|
|
||||||
|
own = {
|
||||||
|
"preferences": {"language": "ja-JP", "dub": False, "skip": None, "nested": {"a": 1}, "nan": float("nan")},
|
||||||
|
"password": "secret",
|
||||||
|
}
|
||||||
|
listing = [{"tag": "EXAMPLE1", "client_config": ["preferences"]}]
|
||||||
|
monkeypatch.setattr(remote_mod, "resolve_server", lambda name: ("http://127.0.0.1:1", "", {}))
|
||||||
|
monkeypatch.setattr(remote_mod, "remote_service_list", lambda name: listing)
|
||||||
|
monkeypatch.setattr(handlers.config, "services", {"example1": own})
|
||||||
|
caplog.set_level(logging.DEBUG)
|
||||||
|
name = RemoteService.__name__
|
||||||
|
try:
|
||||||
|
svc = remote_mod.make_remote_service(SimpleNamespace(obj=None), None, "EXAMPLE1", "t1", {})
|
||||||
|
finally:
|
||||||
|
RemoteService.__name__ = name # the constructor renames the class
|
||||||
|
assert svc._client_preferences == {"language": "ja-JP", "dub": False}
|
||||||
|
assert svc._client_config == {}
|
||||||
|
assert "preferences.skip" in caplog.text
|
||||||
|
assert "preferences.nested" in caplog.text
|
||||||
|
|
||||||
|
|
||||||
|
class _SentCreate(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def sent_service_config(local_cdm: Any) -> Any:
|
||||||
|
"""The service_config of the session create body of a client with ``local_cdm``, an identity and a preference."""
|
||||||
|
|
||||||
|
def post(path: str, data: dict) -> dict:
|
||||||
|
raise _SentCreate(data)
|
||||||
|
|
||||||
|
svc = remote_session(local_cdm, {})
|
||||||
|
svc.ctx.obj.cdm_entry = False
|
||||||
|
svc.licensing = None
|
||||||
|
svc._server_cdm_request = None
|
||||||
|
svc.service_tag = "EXAMPLE1"
|
||||||
|
svc.title_id = "t1"
|
||||||
|
svc._server_accounts = {"global": True}
|
||||||
|
svc._service_params = {}
|
||||||
|
svc._client_config = {"esn": "CLIENT"}
|
||||||
|
svc._client_preferences = {"language": "ja-JP"}
|
||||||
|
svc.ctx.parent = SimpleNamespace(params={"no_proxy": True})
|
||||||
|
svc.client = SimpleNamespace(post=post)
|
||||||
|
with pytest.raises(_SentCreate) as exc:
|
||||||
|
svc.authenticate()
|
||||||
|
return exc.value.args[0].get("service_config")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("local_cdm", "expected"),
|
||||||
|
[
|
||||||
|
pytest.param(None, {"preferences": {"language": "ja-JP"}}, id="no-local-cdm"),
|
||||||
|
pytest.param(WIDEVINE_CDM, {"preferences": {"language": "ja-JP"}, "esn": "CLIENT"}, id="local-cdm"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_the_client_sends_its_preferences_whatever_its_cdm(local_cdm: Any, expected: dict) -> None:
|
||||||
|
assert sent_service_config(local_cdm) == expected
|
||||||
@@ -720,7 +720,8 @@ def _remote_service(parent_params: dict, service_params: dict) -> RemoteService:
|
|||||||
svc._server_accounts = {"global": True}
|
svc._server_accounts = {"global": True}
|
||||||
svc._server_cdm_request = True
|
svc._server_cdm_request = True
|
||||||
svc._service_params = service_params
|
svc._service_params = service_params
|
||||||
svc._client_config = None
|
svc._client_config = {}
|
||||||
|
svc._client_preferences = {}
|
||||||
svc.session = requests.Session()
|
svc.session = requests.Session()
|
||||||
svc.log = logging.getLogger("test")
|
svc.log = logging.getLogger("test")
|
||||||
svc.client = SimpleNamespace(post=post, server_url="https://server.example")
|
svc.client = SimpleNamespace(post=post, server_url="https://server.example")
|
||||||
|
|||||||
@@ -535,7 +535,8 @@ def sent_create(server_cdm, cdm_name=None, local_cdm=WIDEVINE_CDM, cdm_entry=Fal
|
|||||||
svc.title_id = "t1"
|
svc.title_id = "t1"
|
||||||
svc._server_accounts = {"global": True}
|
svc._server_accounts = {"global": True}
|
||||||
svc._service_params = {}
|
svc._service_params = {}
|
||||||
svc._client_config = None
|
svc._client_config = {}
|
||||||
|
svc._client_preferences = {}
|
||||||
svc.ctx.parent = SimpleNamespace(params={"no_proxy": True, "cdm_name": cdm_name})
|
svc.ctx.parent = SimpleNamespace(params={"no_proxy": True, "cdm_name": cdm_name})
|
||||||
svc.client = SimpleNamespace(post=post)
|
svc.client = SimpleNamespace(post=post)
|
||||||
with pytest.raises(_SentCreate) as exc:
|
with pytest.raises(_SentCreate) as exc:
|
||||||
|
|||||||
@@ -50,7 +50,8 @@ def sent_create(cdm_for: Any, local_cdm: Any = WIDEVINE_CDM) -> dict:
|
|||||||
svc.title_id = "t1"
|
svc.title_id = "t1"
|
||||||
svc._server_accounts = {"global": True}
|
svc._server_accounts = {"global": True}
|
||||||
svc._service_params = {}
|
svc._service_params = {}
|
||||||
svc._client_config = None
|
svc._client_config = {}
|
||||||
|
svc._client_preferences = {}
|
||||||
svc.ctx.parent = SimpleNamespace(params={"no_proxy": True})
|
svc.ctx.parent = SimpleNamespace(params={"no_proxy": True})
|
||||||
svc.client = SimpleNamespace(post=post)
|
svc.client = SimpleNamespace(post=post)
|
||||||
with pytest.raises(_SentCreate) as exc:
|
with pytest.raises(_SentCreate) as exc:
|
||||||
|
|||||||
@@ -81,6 +81,7 @@ from unshackle.core.remote_protocol import (
|
|||||||
TrackKeys,
|
TrackKeys,
|
||||||
TracksReply,
|
TracksReply,
|
||||||
TracksRequest,
|
TracksRequest,
|
||||||
|
is_preference,
|
||||||
)
|
)
|
||||||
from unshackle.core.run_plan import SESSION_DL_KEYS, PlanError, served_plan
|
from unshackle.core.run_plan import SESSION_DL_KEYS, PlanError, served_plan
|
||||||
from unshackle.core.services import Services
|
from unshackle.core.services import Services
|
||||||
@@ -882,6 +883,8 @@ def launch_served(
|
|||||||
api_key = caller_key(request)
|
api_key = caller_key(request)
|
||||||
policy = session.policy if session else request_policy(request)
|
policy = session.policy if session else request_policy(request)
|
||||||
server_config = service_config = policy.service_yaml(service)
|
server_config = service_config = policy.service_yaml(service)
|
||||||
|
if session:
|
||||||
|
server_config = service_config = merge_preferences(server_config, data.get("service_config"))
|
||||||
proxy_param, proxy_providers = session.proxy if session else resolve_handler_proxy(data, service, request)
|
proxy_param, proxy_providers = session.proxy if session else resolve_handler_proxy(data, service, request)
|
||||||
|
|
||||||
if session:
|
if session:
|
||||||
@@ -904,7 +907,7 @@ def launch_served(
|
|||||||
)
|
)
|
||||||
|
|
||||||
def lend_server_device() -> Any:
|
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``."""
|
"""The server's device, with the server's own config and the client's preferences back in ``self.config``."""
|
||||||
if service_config is not server_config:
|
if service_config is not server_config:
|
||||||
service_config.clear()
|
service_config.clear()
|
||||||
service_config.update(server_config)
|
service_config.update(server_config)
|
||||||
@@ -2790,6 +2793,30 @@ SESSION_TRANSPORT_KEYS = (SessionCreate.__required_keys__ | SessionCreate.__opti
|
|||||||
MAX_CLIENT_CONFIG_BYTES = 16384
|
MAX_CLIENT_CONFIG_BYTES = 16384
|
||||||
|
|
||||||
|
|
||||||
|
def supplied_config(supplied: Any) -> dict[str, Any]:
|
||||||
|
"""The ``service_config`` a remote client sent, refused unless it is an object under the size cap."""
|
||||||
|
if supplied is None:
|
||||||
|
return {}
|
||||||
|
if not isinstance(supplied, dict) or len(json.dumps(supplied, default=str)) > MAX_CLIENT_CONFIG_BYTES:
|
||||||
|
raise APIError(
|
||||||
|
APIErrorCode.INVALID_INPUT, f"service_config must be an object under {MAX_CLIENT_CONFIG_BYTES} bytes"
|
||||||
|
)
|
||||||
|
return supplied
|
||||||
|
|
||||||
|
|
||||||
|
def merge_preferences(service_config: dict[str, Any], supplied: Any) -> dict[str, Any]:
|
||||||
|
"""The service config with the client's ``preferences`` merged key by key over the server's, in every remote session."""
|
||||||
|
preferences = supplied_config(supplied).get("preferences")
|
||||||
|
if preferences is None:
|
||||||
|
return service_config
|
||||||
|
if not isinstance(preferences, dict) or not all(map(is_preference, preferences.values())):
|
||||||
|
raise APIError(
|
||||||
|
APIErrorCode.INVALID_INPUT, "service_config.preferences must be an object of strings, numbers or booleans"
|
||||||
|
)
|
||||||
|
own = service_config.get("preferences")
|
||||||
|
return {**service_config, "preferences": {**(own if isinstance(own, dict) else {}), **preferences}}
|
||||||
|
|
||||||
|
|
||||||
def client_config_overlay(
|
def client_config_overlay(
|
||||||
service_config: dict[str, Any], allowed: Iterable[str], supplied: Any
|
service_config: dict[str, Any], allowed: Iterable[str], supplied: Any
|
||||||
) -> tuple[dict[str, Any], bool]:
|
) -> tuple[dict[str, Any], bool]:
|
||||||
@@ -2799,13 +2826,8 @@ def client_config_overlay(
|
|||||||
When the client sends any scalar value (an identity such as an ESN), the server's scalar values for
|
When the client sends any scalar value (an identity such as an ESN), the server's scalar values for
|
||||||
the allowed keys are dropped, so the two identities never mix. With none, the server's stay.
|
the allowed keys are dropped, so the two identities never mix. With none, the server's stay.
|
||||||
"""
|
"""
|
||||||
allowed = set(allowed)
|
allowed = set(allowed) - {"preferences"}
|
||||||
if supplied is None:
|
supplied = supplied_config(supplied)
|
||||||
supplied = {}
|
|
||||||
if not isinstance(supplied, dict) or len(json.dumps(supplied, default=str)) > MAX_CLIENT_CONFIG_BYTES:
|
|
||||||
raise APIError(
|
|
||||||
APIErrorCode.INVALID_INPUT, f"service_config must be an object under {MAX_CLIENT_CONFIG_BYTES} bytes"
|
|
||||||
)
|
|
||||||
|
|
||||||
def scalar(value: Any) -> bool:
|
def scalar(value: Any) -> bool:
|
||||||
return isinstance(value, str) or is_whole_number(value)
|
return isinstance(value, str) or is_whole_number(value)
|
||||||
@@ -2819,6 +2841,8 @@ def client_config_overlay(
|
|||||||
identity = any(key in allowed and scalar(value) for key, value in supplied.items())
|
identity = any(key in allowed and scalar(value) for key, value in supplied.items())
|
||||||
merged = {k: v for k, v in service_config.items() if not identity or k not in allowed or isinstance(v, dict)}
|
merged = {k: v for k, v in service_config.items() if not identity or k not in allowed or isinstance(v, dict)}
|
||||||
for key, value in supplied.items():
|
for key, value in supplied.items():
|
||||||
|
if key == "preferences":
|
||||||
|
continue
|
||||||
if key not in allowed:
|
if key not in allowed:
|
||||||
log.warning(f"Ignoring service_config.{sanitize_log(str(key))}: the service does not take it from a client")
|
log.warning(f"Ignoring service_config.{sanitize_log(str(key))}: the service does not take it from a client")
|
||||||
elif isinstance(value, dict):
|
elif isinstance(value, dict):
|
||||||
|
|||||||
@@ -2107,8 +2107,10 @@ async def session_create(request: web.Request) -> web.Response:
|
|||||||
type: object
|
type: object
|
||||||
additionalProperties: true
|
additionalProperties: true
|
||||||
description: |
|
description: |
|
||||||
The client's own identity config for the service. The server takes only the keys
|
The client's own config for the service. The server takes the keys the service lists
|
||||||
the service lists in `client_config`, and only when the client's device licenses.
|
in `client_config` only when the client's device licenses. It merges `preferences`, an
|
||||||
|
object of strings, numbers and booleans, over its own `preferences` block in every
|
||||||
|
remote session.
|
||||||
plugins:
|
plugins:
|
||||||
type: object
|
type: object
|
||||||
description: |
|
description: |
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ older peer.
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import math
|
||||||
from dataclasses import dataclass, replace
|
from dataclasses import dataclass, replace
|
||||||
from enum import Enum, StrEnum
|
from enum import Enum, StrEnum
|
||||||
from typing import Any, NotRequired, TypedDict, TypeVar
|
from typing import Any, NotRequired, TypedDict, TypeVar
|
||||||
@@ -123,6 +124,11 @@ class ClientInfo(TypedDict):
|
|||||||
DEVICE_FACT_TYPES = (str, int, float, bool, type(None))
|
DEVICE_FACT_TYPES = (str, int, float, bool, type(None))
|
||||||
|
|
||||||
|
|
||||||
|
def is_preference(value: Any) -> bool:
|
||||||
|
"""True for a value that a remote client sends in its ``preferences`` block: a string, a number or a boolean."""
|
||||||
|
return isinstance(value, (str, int, bool)) or (isinstance(value, float) and math.isfinite(value))
|
||||||
|
|
||||||
|
|
||||||
class ClientPlugin(TypedDict, total=False):
|
class ClientPlugin(TypedDict, total=False):
|
||||||
"""A DRM plugin of a remote client: its version, and the facts of the plugin device the client licenses with."""
|
"""A DRM plugin of a remote client: its version, and the facts of the plugin device the client licenses with."""
|
||||||
|
|
||||||
|
|||||||
@@ -86,6 +86,7 @@ from unshackle.core.remote_protocol import (
|
|||||||
TracksRequest,
|
TracksRequest,
|
||||||
cap_note,
|
cap_note,
|
||||||
coded,
|
coded,
|
||||||
|
is_preference,
|
||||||
)
|
)
|
||||||
from unshackle.core.run_plan import session_request
|
from unshackle.core.run_plan import session_request
|
||||||
from unshackle.core.search_result import SearchResult
|
from unshackle.core.search_result import SearchResult
|
||||||
@@ -154,6 +155,21 @@ def session_plugins(cdm_for: Callable[..., Any] | None) -> dict[str, ClientPlugi
|
|||||||
return listed
|
return listed
|
||||||
|
|
||||||
|
|
||||||
|
def sendable_preferences(preferences: Any) -> dict[str, Any]:
|
||||||
|
"""The entries of the client's own ``preferences`` block that a remote server takes."""
|
||||||
|
if not isinstance(preferences, dict):
|
||||||
|
if preferences is not None:
|
||||||
|
log.debug(f"Not sending preferences to the remote server: a {type(preferences).__name__}, not a mapping")
|
||||||
|
return {}
|
||||||
|
sent = {}
|
||||||
|
for key, value in preferences.items():
|
||||||
|
if is_preference(value):
|
||||||
|
sent[key] = value
|
||||||
|
else:
|
||||||
|
log.debug(f"Not sending preferences.{key} to the remote server: a {type(value).__name__} value")
|
||||||
|
return sent
|
||||||
|
|
||||||
|
|
||||||
RETRY_AFTER_MAX = 3600
|
RETRY_AFTER_MAX = 3600
|
||||||
RETRY_AFTER_LOCK = Lock()
|
RETRY_AFTER_LOCK = Lock()
|
||||||
RATE_LIMIT_TRIES = 3
|
RATE_LIMIT_TRIES = 3
|
||||||
@@ -989,7 +1005,10 @@ class RemoteService(TitleSource):
|
|||||||
self._anonymous_search = bool(services_config.get("_anonymous_search"))
|
self._anonymous_search = bool(services_config.get("_anonymous_search"))
|
||||||
# read before apply_service_config merges the server's values into the same section
|
# read before apply_service_config merges the server's values into the same section
|
||||||
own = ci_get(config.services, service_tag) or {}
|
own = ci_get(config.services, service_tag) or {}
|
||||||
self._client_config = {k: own[k] for k in services_config.get("_client_config") or [] if k in own}
|
self._client_config = {
|
||||||
|
k: own[k] for k in services_config.get("_client_config") or [] if k in own and k != "preferences"
|
||||||
|
}
|
||||||
|
self._client_preferences = sendable_preferences(own.get("preferences"))
|
||||||
self.apply_service_config(svc_config)
|
self.apply_service_config(svc_config)
|
||||||
|
|
||||||
def apply_service_config(self, svc_config: dict) -> None:
|
def apply_service_config(self, svc_config: dict) -> None:
|
||||||
@@ -1200,8 +1219,11 @@ class RemoteService(TitleSource):
|
|||||||
create_data["cdm_system_id"] = system_id
|
create_data["cdm_system_id"] = system_id
|
||||||
if device_type := getattr(getattr(cdm, "device_type", None), "name", None):
|
if device_type := getattr(getattr(cdm, "device_type", None), "name", None):
|
||||||
create_data["cdm_device_type"] = device_type
|
create_data["cdm_device_type"] = device_type
|
||||||
if self._client_config:
|
service_config = dict(self._client_config) if cdm is not None else {}
|
||||||
create_data["service_config"] = self._client_config
|
if self._client_preferences:
|
||||||
|
service_config["preferences"] = self._client_preferences
|
||||||
|
if service_config:
|
||||||
|
create_data["service_config"] = service_config
|
||||||
|
|
||||||
from unshackle.core import __code_hash__, __version__
|
from unshackle.core import __code_hash__, __version__
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user