forked from kenzuya/unshackle
refactor(remote): hold who licenses a remote session as one licensing mode
This commit is contained in:
@@ -60,6 +60,8 @@ from unshackle.core.remote_protocol import (
|
||||
BadKeyReport,
|
||||
LicenseReply,
|
||||
LicenseRequest,
|
||||
LicensingMode,
|
||||
Licensor,
|
||||
LogsReply,
|
||||
PromptAnswer,
|
||||
PromptReply,
|
||||
@@ -971,22 +973,36 @@ def choose_session_cdm(policy: KeyPolicy, service: str, data: dict[str, Any]) ->
|
||||
return licence_cap.session_fits(cap, service, data.get("quality"), bool(data.get("cdm_type"))), cap
|
||||
|
||||
|
||||
def session_licensing(policy: KeyPolicy, service: str, data: dict[str, Any]) -> LicensingMode:
|
||||
"""The licensing mode of a new remote session, before the service is built.
|
||||
|
||||
An older client that sends no ``cdm_relay`` gets no client device outside a capped session.
|
||||
"""
|
||||
use_server_cdm, max_height = choose_session_cdm(policy, service, data)
|
||||
if use_server_cdm:
|
||||
return LicensingMode(Licensor.SERVER_CDM, max_height)
|
||||
if data.get("cdm_type") and (max_height is not None or data.get("cdm_relay") is True):
|
||||
return LicensingMode(Licensor.CLIENT_DEVICE, max_height, policy.allows("server_vault", service))
|
||||
return LicensingMode(Licensor.NO_DEVICE, max_height)
|
||||
|
||||
|
||||
def live_licence_refusal(session: SessionEntry, track: Any) -> APIError | None:
|
||||
"""Why the server CDM must not make a live licence for ``track`` in ``session``; None when it may.
|
||||
|
||||
Only a live licence spends the server's device, so a vault hit always passes.
|
||||
"""
|
||||
if session.server_device:
|
||||
licensing = session.licensing
|
||||
if licensing.server_device:
|
||||
return APIError(
|
||||
APIErrorCode.SERVER_CDM_CAPPED,
|
||||
"This session runs on the server's device, so its keys come only from a vault.",
|
||||
details={"reason": "server_device"},
|
||||
)
|
||||
if not session.server_cdm:
|
||||
if not licensing.server_cdm:
|
||||
return licence_cap.capped_error(
|
||||
"This session licenses with your own device, so the server CDM makes no licence for it."
|
||||
)
|
||||
return licence_cap.track_refusal(session.server_cdm_max_height, track)
|
||||
return licence_cap.track_refusal(licensing.max_height, track)
|
||||
|
||||
|
||||
_account_counters: dict[str, int] = {}
|
||||
@@ -2861,13 +2877,7 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
|
||||
profile = next_server_profile(normalized_service, region)
|
||||
log.info(f"Using server account '{sanitize_log(profile or 'default')}' for {normalized_service}")
|
||||
|
||||
use_server_cdm, max_height = choose_session_cdm(policy, normalized_service, data)
|
||||
# an old client without cdm_relay keeps the server's device outside a capped session
|
||||
client_device = (
|
||||
not use_server_cdm
|
||||
and bool(data.get("cdm_type"))
|
||||
and (max_height is not None or data.get("cdm_relay") is True)
|
||||
)
|
||||
licensing = session_licensing(policy, normalized_service, data)
|
||||
bridge = InputBridge()
|
||||
log_buffer = None if server_account else SessionLogBuffer()
|
||||
service_class_name = getattr(Services.load(normalized_service), "__name__", normalized_service)
|
||||
@@ -2882,8 +2892,8 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
|
||||
proxy_providers,
|
||||
profile,
|
||||
server_account=server_account,
|
||||
server_cdm=use_server_cdm,
|
||||
client_device=client_device,
|
||||
server_cdm=licensing.server_cdm,
|
||||
client_device=licensing.client_device,
|
||||
input_bridge=bridge,
|
||||
policy=policy,
|
||||
)
|
||||
@@ -2894,7 +2904,8 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
|
||||
|
||||
# the service asked for the server's device in __init__, so the session never licenses live
|
||||
stand_in = getattr(getattr(getattr(service_instance, "ctx", None), "obj", None), "cdm", None)
|
||||
server_device = getattr(stand_in, "lent", False) is True
|
||||
if getattr(stand_in, "lent", False) is True:
|
||||
licensing = licensing.lent()
|
||||
cache_tag = f"_accounts/{normalized_service}/{profile or 'default'}" if server_account else session_cache_dir
|
||||
if server_account:
|
||||
session_cache_tag = None
|
||||
@@ -2905,7 +2916,7 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
|
||||
api_key,
|
||||
policy,
|
||||
temporary=not server_account,
|
||||
client_identity=client_device and not server_device,
|
||||
client_identity=licensing.client_identity,
|
||||
)
|
||||
|
||||
cache_data = data.get("cache", {})
|
||||
@@ -2924,10 +2935,7 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
|
||||
server_account=(profile or "default") if server_account else None,
|
||||
cache_tag=session_cache_tag,
|
||||
policy=policy,
|
||||
server_cdm=use_server_cdm,
|
||||
server_cdm_max_height=max_height,
|
||||
server_vault=client_device and policy.allows("server_vault", normalized_service),
|
||||
server_device=server_device,
|
||||
licensing=licensing,
|
||||
client_auth=not server_account
|
||||
and (cookies is not None or credential is not None or bool(cache_data and session_cache_tag)),
|
||||
# Echoed to every dashboard viewer, so cap what an arbitrary client can push into it.
|
||||
@@ -2965,10 +2973,7 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
|
||||
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,
|
||||
**licensing.created_fields(),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -3073,7 +3078,7 @@ def client_owns_login(session: SessionEntry) -> bool:
|
||||
|
||||
A remote session on the server's lent device logs in with the server's device identity, so its tokens stay there.
|
||||
"""
|
||||
return bool(session.client_auth) and not session.server_device
|
||||
return bool(session.client_auth) and not session.licensing.server_device
|
||||
|
||||
|
||||
def scrub_secret_keys(value: Any) -> Any:
|
||||
@@ -3152,7 +3157,7 @@ async def session_tracks_handler(
|
||||
|
||||
service_tag = session.service_tag
|
||||
config_cdm_type = detect_cdm_type_for_service(service_tag, app_config)
|
||||
if not config_cdm_type and session.server_cdm and choose_cdm(app_config.cdm, service_tag).both:
|
||||
if not config_cdm_type and session.licensing.server_cdm and choose_cdm(app_config.cdm, service_tag).both:
|
||||
loaded = getattr(getattr(getattr(service_instance, "ctx", None), "obj", None), "cdm", None)
|
||||
config_cdm_type = cdm_system(loaded) or "widevine"
|
||||
|
||||
@@ -3188,7 +3193,7 @@ async def session_tracks_handler(
|
||||
session_headers=session_headers,
|
||||
session_cookies=cookie_values(session_cookies),
|
||||
session_cookie_jar=session_cookies,
|
||||
server_cdm=session.server_cdm,
|
||||
server_cdm=session.licensing.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)
|
||||
@@ -4175,10 +4180,10 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
||||
drm_type = data.get("drm_type", "widevine")
|
||||
mode = data.get("mode", "proxy")
|
||||
|
||||
# a session the client's device licenses reaches the server vault only; its live licences stay client-side
|
||||
vault_only = not session.server_cdm
|
||||
licensing = session.licensing
|
||||
vault_only = licensing.vault_only
|
||||
if mode == "server_cdm" and not (
|
||||
session.server_vault if vault_only else request_policy(request).allows("server_cdm", session.service_tag)
|
||||
licensing.server_vault if vault_only else request_policy(request).allows("server_cdm", session.service_tag)
|
||||
):
|
||||
raise APIError(
|
||||
APIErrorCode.FORBIDDEN,
|
||||
@@ -4284,7 +4289,7 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
||||
ensure_track_drm(track, svc_session, init_data)
|
||||
cipher = whole_file_cipher(track)
|
||||
if cipher is not None:
|
||||
if not (vault_only or session.server_device):
|
||||
if not vault_only:
|
||||
try:
|
||||
file_keys[tid] = cipher.content_key().hex()
|
||||
except (Exception, SystemExit) as e:
|
||||
@@ -4377,7 +4382,7 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
||||
|
||||
cipher = whole_file_cipher(track)
|
||||
if cipher is not None and (mode == "server_cdm" or cipher.key is not None):
|
||||
if (vault_only or session.server_device) and cipher.key is None:
|
||||
if vault_only and cipher.key is None:
|
||||
raise APIError(
|
||||
APIErrorCode.FORBIDDEN, "Server licensing is not enabled for this session on this service"
|
||||
)
|
||||
@@ -4444,7 +4449,7 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
||||
track.pr_pssh = pssh_b64
|
||||
|
||||
certificate = data.get("is_certificate") is True
|
||||
if session.server_device and not certificate:
|
||||
if licensing.server_device and not certificate:
|
||||
denied = live_licence_refusal(session, track)
|
||||
if denied:
|
||||
raise denied
|
||||
|
||||
@@ -22,13 +22,14 @@ from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, InputBridge
|
||||
from unshackle.core.api.sanitize import sanitize_log
|
||||
from unshackle.core.api.session_channel import SessionChannel, drain_message
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.remote_protocol import AuthStatus
|
||||
from unshackle.core.remote_protocol import AuthStatus, LicensingMode, Licensor
|
||||
from unshackle.core.tracks import Track, Tracks
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from unshackle.core.api.key_policy import KeyPolicy
|
||||
|
||||
log = logging.getLogger("api.session")
|
||||
NO_DEVICE = LicensingMode(Licensor.NO_DEVICE)
|
||||
|
||||
DRAIN_WARNING = "This server restarts for an update after the open downloads finish; this download continues"
|
||||
|
||||
@@ -54,10 +55,7 @@ class SessionEntry:
|
||||
owner_key: str | None = None # X-Secret-Key that owns this session
|
||||
cache_tag: str | None = None
|
||||
server_account: str | None = None # profile name when the server lent its own account
|
||||
server_cdm: bool = False # False: the client's own device licenses this session
|
||||
server_cdm_max_height: int | None = None
|
||||
server_vault: bool = False # a session the client's device licenses may still take keys from the server vault
|
||||
server_device: bool = False # its service runs on the server's lent device, so keys come only from a vault
|
||||
licensing: LicensingMode = NO_DEVICE
|
||||
client_auth: bool = False # the login is the client's: it succeeded without a server account
|
||||
policy: KeyPolicy | None = field(default=None, repr=False) # the API key policy the session was created with
|
||||
input_bridge: InputBridge | None = None
|
||||
@@ -126,8 +124,8 @@ class SessionEntry:
|
||||
"auth_status": self.auth_status.value,
|
||||
"auth_error": self.auth_error,
|
||||
"server_account": self.server_account,
|
||||
"server_cdm": self.server_cdm,
|
||||
"server_cdm_max_height": self.server_cdm_max_height,
|
||||
"server_cdm": self.licensing.server_cdm,
|
||||
"server_cdm_max_height": self.licensing.max_height,
|
||||
"log_seq": self.log_buffer.last_seq if self.log_buffer else 0,
|
||||
"client": self.client,
|
||||
**({"actions": list(self.actions)} if include_actions else {}),
|
||||
@@ -194,10 +192,7 @@ class SessionStore:
|
||||
server_account: str | None = None,
|
||||
cache_tag: str | None = None,
|
||||
policy: KeyPolicy | None = None,
|
||||
server_cdm: bool = False,
|
||||
server_cdm_max_height: int | None = None,
|
||||
server_vault: bool = False,
|
||||
server_device: bool = False,
|
||||
licensing: LicensingMode = NO_DEVICE,
|
||||
client_auth: bool = False,
|
||||
client: dict[str, Any] | None = None,
|
||||
input_bridge: InputBridge | None = None,
|
||||
@@ -231,10 +226,7 @@ class SessionStore:
|
||||
server_account=server_account,
|
||||
cache_tag=cache_tag,
|
||||
policy=policy,
|
||||
server_cdm=server_cdm,
|
||||
server_cdm_max_height=server_cdm_max_height,
|
||||
server_vault=server_vault,
|
||||
server_device=server_device,
|
||||
licensing=licensing,
|
||||
client_auth=client_auth,
|
||||
client=client or {},
|
||||
input_bridge=input_bridge,
|
||||
|
||||
@@ -8,6 +8,7 @@ older peer.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, replace
|
||||
from enum import Enum, StrEnum
|
||||
from typing import Any, NotRequired, TypedDict, TypeVar
|
||||
|
||||
@@ -163,6 +164,106 @@ class SessionCreated(TypedDict, total=False):
|
||||
server_device: bool
|
||||
|
||||
|
||||
class Licensor(StrEnum):
|
||||
"""Who licenses a remote session."""
|
||||
|
||||
SERVER_CDM = "server_cdm"
|
||||
"""The server's device licenses live, up to the licence cap."""
|
||||
CLIENT_DEVICE = "client_device"
|
||||
"""The client's own device licenses, and the service sees a stand-in for it."""
|
||||
LENT_DEVICE = "lent_device"
|
||||
"""The client's stand-in lent the server's device to the service, so the keys come only from a vault."""
|
||||
NO_DEVICE = "no_device"
|
||||
"""No server CDM, and no client device that the service can see."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LicensingMode:
|
||||
"""Who licenses a remote session, its licence cap and its access to the server vault, fixed at session create.
|
||||
|
||||
Only a client-device session, lent or not, can read the server vault. The wire keeps the older fields
|
||||
``server_cdm``, ``server_cdm_max_height``, ``server_vault`` and ``server_device``.
|
||||
"""
|
||||
|
||||
licensor: Licensor
|
||||
max_height: int | None = None
|
||||
server_vault: bool = False
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.server_vault and not self.client_device:
|
||||
raise ValueError(f"A {self.licensor} session cannot read the server vault")
|
||||
|
||||
@classmethod
|
||||
def from_created(cls, reply: SessionCreated) -> LicensingMode:
|
||||
"""The mode that the reply to a remote session creation gives."""
|
||||
vault = bool(reply.get("server_vault"))
|
||||
if reply.get("server_device"):
|
||||
return cls(Licensor.LENT_DEVICE, reply.get("server_cdm_max_height"), vault)
|
||||
if reply.get("server_cdm"):
|
||||
return cls(Licensor.SERVER_CDM, reply.get("server_cdm_max_height"))
|
||||
return cls(Licensor.CLIENT_DEVICE, reply.get("server_cdm_max_height"), vault)
|
||||
|
||||
def created_fields(self) -> SessionCreated:
|
||||
"""The licensing fields of the reply to a remote session creation."""
|
||||
return SessionCreated(
|
||||
server_cdm=self.server_cdm,
|
||||
server_cdm_max_height=self.max_height,
|
||||
server_vault=self.server_vault,
|
||||
server_device=self.server_device,
|
||||
)
|
||||
|
||||
def lent(self) -> LicensingMode:
|
||||
"""This client-device mode after the service took the server's device in its place."""
|
||||
if self.licensor is not Licensor.CLIENT_DEVICE:
|
||||
raise ValueError(f"A {self.licensor} session has no client device to lend the server's device")
|
||||
return replace(self, licensor=Licensor.LENT_DEVICE)
|
||||
|
||||
@property
|
||||
def server_cdm(self) -> bool:
|
||||
"""True when the server's device can license live."""
|
||||
return self.licensor is Licensor.SERVER_CDM
|
||||
|
||||
@property
|
||||
def server_device(self) -> bool:
|
||||
"""True when the service runs on the server's lent device."""
|
||||
return self.licensor is Licensor.LENT_DEVICE
|
||||
|
||||
@property
|
||||
def client_device(self) -> bool:
|
||||
"""True when the service gets the stand-in for the client's device, lent or not."""
|
||||
return self.licensor in (Licensor.CLIENT_DEVICE, Licensor.LENT_DEVICE)
|
||||
|
||||
@property
|
||||
def client_identity(self) -> bool:
|
||||
"""True when the device identity that the service builds is the client's own."""
|
||||
return self.licensor is Licensor.CLIENT_DEVICE
|
||||
|
||||
@property
|
||||
def vault_only(self) -> bool:
|
||||
"""True when the server keys come only from a vault, so both DRM systems are candidates."""
|
||||
return not self.server_cdm
|
||||
|
||||
@property
|
||||
def keys_from_server(self) -> bool:
|
||||
"""True when dl takes the content keys from the server and not from the challenge relay."""
|
||||
return self.licensor in (Licensor.SERVER_CDM, Licensor.LENT_DEVICE)
|
||||
|
||||
@property
|
||||
def reads_server_keys(self) -> bool:
|
||||
"""True when the client asks the server for keys: its CDM licenses, or the API key reads the server vault."""
|
||||
return self.server_cdm or self.server_vault
|
||||
|
||||
@property
|
||||
def vault_first(self) -> bool:
|
||||
"""True when the server vault answers before the client's own device licenses."""
|
||||
return self.licensor is Licensor.CLIENT_DEVICE and self.server_vault
|
||||
|
||||
@property
|
||||
def local_vaults_only(self) -> bool:
|
||||
"""True for a lent-device session whose API key cannot read the server vault."""
|
||||
return self.server_device and not self.server_vault
|
||||
|
||||
|
||||
class TracksRequest(TypedDict):
|
||||
title_id: str
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ import shlex
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import Callable, Iterable, Iterator, Mapping
|
||||
from dataclasses import replace
|
||||
from functools import partial
|
||||
from http.cookiejar import CookieJar
|
||||
from threading import Lock, local
|
||||
@@ -72,6 +73,8 @@ from unshackle.core.remote_protocol import (
|
||||
ClientLogin,
|
||||
LicenseReply,
|
||||
LicenseRequest,
|
||||
LicensingMode,
|
||||
Licensor,
|
||||
SegmentFilterReply,
|
||||
SegmentFilterRequest,
|
||||
SegmentsRequest,
|
||||
@@ -841,6 +844,10 @@ class RemoteService(TitleSource):
|
||||
|
||||
server_cdm_type: str = "widevine"
|
||||
channel: Channel | None = None
|
||||
licensing: LicensingMode | None = None
|
||||
"""The server's answer to who licenses this remote session; an older server gives it in the tracks reply."""
|
||||
_server_cdm_request: bool | None = None
|
||||
"""This client's own server CDM choice; None leaves it to the server."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -903,10 +910,7 @@ class RemoteService(TitleSource):
|
||||
record_requests(self.session)
|
||||
|
||||
svc_config = services_config.get(service_tag, {})
|
||||
self._server_cdm: bool | None = services_config.get("_server_cdm")
|
||||
self._server_vault = False
|
||||
self._server_device = False
|
||||
self._local_vaults_only = False
|
||||
self._server_cdm_request = services_config.get("_server_cdm")
|
||||
self._server_accounts: dict | None = services_config.get("_server_accounts")
|
||||
self._anonymous_search = bool(services_config.get("_anonymous_search"))
|
||||
# read before apply_service_config merges the server's values into the same section
|
||||
@@ -1109,8 +1113,9 @@ class RemoteService(TitleSource):
|
||||
cdm_only = bool(self.ctx.parent and self.ctx.parent.params.get("cdm_only"))
|
||||
if cdm_only and cdm is None:
|
||||
raise click.ClickException(f"--cdm-only over --remote needs a local CDM for {self.service_tag}")
|
||||
cdm_entry = cdm is not None and self.ctx.obj.cdm_entry and self._server_cdm is None
|
||||
if not (cdm_entry or cdm_name or self._server_cdm is not None) and ci_get(config.cdm, self.service_tag):
|
||||
expected = self.expected_server_cdm
|
||||
cdm_entry = cdm is not None and self.ctx.obj.cdm_entry and expected is None
|
||||
if not (cdm_entry or cdm_name or expected is not None) and ci_get(config.cdm, self.service_tag):
|
||||
self.log.warning(
|
||||
f"The cdm entry for {self.service_tag} did not load a device for this remote session, "
|
||||
"so the server decides who licenses it"
|
||||
@@ -1119,8 +1124,8 @@ class RemoteService(TitleSource):
|
||||
from unshackle.core.cdm.detect import cdm_system
|
||||
|
||||
if cdm_entry or cdm_name or cdm_only:
|
||||
self._server_cdm = False
|
||||
if self._server_cdm is False:
|
||||
self._server_cdm_request = expected = False
|
||||
if expected is False:
|
||||
create_data["server_cdm"] = False
|
||||
create_data["cdm_type"] = cdm_system(cdm) or "widevine"
|
||||
level = getattr(cdm, "security_level", None)
|
||||
@@ -1161,25 +1166,21 @@ class RemoteService(TitleSource):
|
||||
atexit.register(self.close)
|
||||
# an older server omits the field, and the tracks response settles it
|
||||
if "server_cdm" in result:
|
||||
self.adopt_session_cdm(bool(result["server_cdm"]), result.get("server_cdm_max_height"))
|
||||
self._server_device = bool(result.get("server_device"))
|
||||
if cdm_only and self._server_device:
|
||||
answer = LicensingMode.from_created(result)
|
||||
self.adopt_session_cdm(replace(answer, server_vault=False) if cdm_only else answer, expected)
|
||||
lent = bool(self.licensing and self.licensing.server_device)
|
||||
if cdm_only and lent:
|
||||
raise click.ClickException(
|
||||
f"--cdm-only cannot license {self.service_tag}: the remote session runs on the server's device"
|
||||
)
|
||||
if cdm_entry and self._server_cdm is False and not self._server_device:
|
||||
if cdm_entry and self.expected_server_cdm is False:
|
||||
self.log.info(
|
||||
f"The cdm config has an entry for {self.service_tag}, so your own device licenses "
|
||||
"this remote session and not the server CDM"
|
||||
)
|
||||
vault = bool(result.get("server_vault"))
|
||||
if self._server_device:
|
||||
self._server_cdm = True
|
||||
whose = "the server vault or yours" if vault else "your vaults only"
|
||||
if lent:
|
||||
whose = "your vaults only" if self.local_vaults_only else "the server vault or yours"
|
||||
self.log.info(f"This session runs on the server's device: keys come from {whose}")
|
||||
self._server_vault = vault and not self._server_cdm and not cdm_only
|
||||
# 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
|
||||
|
||||
from unshackle.core.remote_channel import open_channel
|
||||
|
||||
@@ -1199,7 +1200,12 @@ class RemoteService(TitleSource):
|
||||
@property
|
||||
def local_vaults_only(self) -> bool:
|
||||
"""True for a remote session on the server's device whose API key cannot read the server vault."""
|
||||
return getattr(self, "_local_vaults_only", False)
|
||||
return self.licensing is not None and self.licensing.local_vaults_only
|
||||
|
||||
@property
|
||||
def expected_server_cdm(self) -> bool | None:
|
||||
"""Whether the server gives this remote session its keys: the server's answer, else this client's request."""
|
||||
return self.licensing.keys_from_server if self.licensing else self._server_cdm_request
|
||||
|
||||
def report_local_fallback(self) -> None:
|
||||
"""Say the local CDM licenses because the server CDM is not granted.
|
||||
@@ -1212,27 +1218,26 @@ class RemoteService(TitleSource):
|
||||
"falling back to the local CDM"
|
||||
)
|
||||
|
||||
def adopt_session_cdm(self, server_cdm: bool, max_height: int | None) -> None:
|
||||
def adopt_session_cdm(self, answer: LicensingMode, expected: bool | None) -> None:
|
||||
"""Take the server's choice of who licenses this remote session, and say why when a cap made it.
|
||||
|
||||
A remote session on the server's lent device keeps the server-CDM flow: dl checks the local vaults, then asks the
|
||||
server, which answers only from its vault. ``_server_cdm`` is False on entry when the user picked the local
|
||||
device, so a server that keeps its own CDM gets a warning.
|
||||
server, which answers only from its vault. ``expected`` is False when the user picked the local device, so a
|
||||
server that keeps its own CDM gets a warning.
|
||||
"""
|
||||
if getattr(self, "_server_device", False):
|
||||
self._server_cdm = True
|
||||
was_lent = self.licensing is not None and self.licensing.server_device
|
||||
self.licensing = answer
|
||||
if was_lent:
|
||||
return
|
||||
if self._server_cdm is False and server_cdm:
|
||||
self._server_cdm = True
|
||||
if expected is False and answer.server_cdm:
|
||||
self.log.warning("The server CDM licenses this remote session, so your own device is not used")
|
||||
return
|
||||
if self._server_cdm and not server_cdm and max_height is None:
|
||||
if expected and not answer.server_cdm and answer.max_height is None:
|
||||
self.report_local_fallback()
|
||||
self._server_cdm = server_cdm
|
||||
if max_height is None:
|
||||
if answer.max_height is None:
|
||||
return
|
||||
message = cap_note(max_height)
|
||||
if not server_cdm:
|
||||
message = cap_note(answer.max_height)
|
||||
if not answer.server_cdm:
|
||||
message += "; licensing with your own device"
|
||||
elif self.local_cdm is not None:
|
||||
message += "; pass a higher -q to license above it with your own device"
|
||||
@@ -1293,12 +1298,20 @@ class RemoteService(TitleSource):
|
||||
time.sleep(random.uniform(delay / 2, delay)) # nosec B311
|
||||
delay = min(delay * 2, 30.0)
|
||||
|
||||
def licence_path(self) -> object:
|
||||
"""Where this remote session takes its keys from, which a reopened session must keep.
|
||||
|
||||
A lent-device session that loses the server vault goes on with the local vaults only.
|
||||
"""
|
||||
licensing = self.licensing
|
||||
return (licensing.licensor, licensing.vault_first) if licensing else self._server_cdm_request
|
||||
|
||||
def reopen(self) -> bool:
|
||||
"""Open a new remote session after the server lost this one, and load the current title's tracks on it again.
|
||||
|
||||
A track the new remote session gives another id keeps its old one here, and calls translate it.
|
||||
"""
|
||||
grants = (self._server_cdm, self._server_device, self._server_vault)
|
||||
grants = self.licence_path()
|
||||
self.close_channel()
|
||||
self._session_id = None
|
||||
if self.client.tunnel: # the server forgot the tunnel too
|
||||
@@ -1334,7 +1347,7 @@ class RemoteService(TitleSource):
|
||||
if e.kind not in RECOVERABLE:
|
||||
raise
|
||||
return False
|
||||
if (self._server_cdm, self._server_device, self._server_vault) != grants:
|
||||
if self.licence_path() != grants:
|
||||
raise RemoteError(
|
||||
"The new remote session licenses differently from the lost one", ClientErrorKind.GRANTS_CHANGED
|
||||
)
|
||||
@@ -1430,11 +1443,15 @@ class RemoteService(TitleSource):
|
||||
restore(tracks, result)
|
||||
apply_service_track_data(tracks, result)
|
||||
|
||||
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
|
||||
server_cdm = bool(session_fields.get("server_cdm", False))
|
||||
if self.licensing is None:
|
||||
request = self._server_cdm_request
|
||||
if request and not server_cdm:
|
||||
self.report_local_fallback()
|
||||
server_cdm = server_cdm and request is not False
|
||||
self.licensing = LicensingMode(Licensor.SERVER_CDM if server_cdm else Licensor.CLIENT_DEVICE)
|
||||
elif self.licensing.server_cdm and not server_cdm:
|
||||
self.licensing = replace(self.licensing, licensor=Licensor.CLIENT_DEVICE)
|
||||
self.report_local_fallback()
|
||||
self.server_cdm_type = session_fields.get("server_cdm_type", "widevine")
|
||||
self._sample_decrypt_tracks.update(session_fields.get("sample_decrypt_tracks") or [])
|
||||
@@ -1517,7 +1534,8 @@ class RemoteService(TitleSource):
|
||||
# track ids can repeat across titles, so a refusal for the last title must not carry over
|
||||
self.client_licensed.clear()
|
||||
self.deferred_refusals.clear()
|
||||
if not (self._server_cdm or getattr(self, "_server_vault", False)) or self.local_vaults_only:
|
||||
licensing = self.licensing
|
||||
if licensing is None or not licensing.reads_server_keys:
|
||||
return
|
||||
|
||||
from uuid import UUID
|
||||
@@ -1527,7 +1545,7 @@ class RemoteService(TitleSource):
|
||||
return
|
||||
|
||||
drm_type = self.server_cdm_type
|
||||
if getattr(self, "_server_vault", False):
|
||||
if licensing.vault_first:
|
||||
from unshackle.core.cdm.detect import cdm_system
|
||||
|
||||
drm_type = cdm_system(self.local_cdm) or "widevine"
|
||||
@@ -1600,7 +1618,7 @@ class RemoteService(TitleSource):
|
||||
try:
|
||||
self.license_locally(track, refusal)
|
||||
except click.ClickException as e:
|
||||
if not self._server_cdm:
|
||||
if not licensing.keys_from_server:
|
||||
raise
|
||||
self.deferred_refusals[str(track.id)] = e.message
|
||||
self.log.debug(f"{e.message}; trying the local vaults first")
|
||||
@@ -1625,7 +1643,7 @@ class RemoteService(TitleSource):
|
||||
cap = refusal.get("max_height")
|
||||
if cap:
|
||||
why = cap_note(cap)
|
||||
elif getattr(self, "_server_vault", False):
|
||||
elif self.licensing and self.licensing.vault_first:
|
||||
why = "The server vault holds no content key for this track"
|
||||
else:
|
||||
why = "The server CDM refused this track"
|
||||
@@ -1660,7 +1678,7 @@ class RemoteService(TitleSource):
|
||||
@property
|
||||
def key_arrival(self) -> KeyArrival:
|
||||
"""``SERVER`` when the server CDM licenses this remote session, else ``CALLBACK``: the challenge relay."""
|
||||
return KeyArrival.SERVER if self._server_cdm else KeyArrival.CALLBACK
|
||||
return KeyArrival.SERVER if self.expected_server_cdm else KeyArrival.CALLBACK
|
||||
|
||||
@property
|
||||
def key_source(self) -> RemoteService:
|
||||
@@ -1788,7 +1806,7 @@ class RemoteService(TitleSource):
|
||||
|
||||
def license_file(self, track: AnyTrack) -> str:
|
||||
"""The content key the server licenses for the whole-file cipher of ``track``, or raise ClickException."""
|
||||
if self.local_vaults_only or not self._server_cdm:
|
||||
if self.local_vaults_only or not self.expected_server_cdm:
|
||||
raise coded(
|
||||
click.ClickException(f"Track {track.id} needs a server licence that this session does not allow"),
|
||||
APIErrorCode.DRM_ERROR,
|
||||
|
||||
Reference in New Issue
Block a user