forked from kenzuya/unshackle
feat(remote): license each track locally with --cdm-only over remote
This commit is contained in:
@@ -42,7 +42,7 @@ from unshackle.core.dl_options import (
|
||||
cast_dl_params,
|
||||
forwarded_dl_params,
|
||||
)
|
||||
from unshackle.core.drm import BlowfishStripe, cbcs, is_null_key
|
||||
from unshackle.core.drm import BlowfishStripe, cbcs, is_null_key, real_kids
|
||||
from unshackle.core.launch import served_context
|
||||
from unshackle.core.manifests.snapshot import capture
|
||||
from unshackle.core.providers.anilist import parse_anilist_ref
|
||||
@@ -64,6 +64,7 @@ from unshackle.core.remote_protocol import (
|
||||
SessionCreated,
|
||||
SessionInfo,
|
||||
TitlesReply,
|
||||
TrackKeys,
|
||||
TracksReply,
|
||||
TracksRequest,
|
||||
)
|
||||
@@ -5291,6 +5292,71 @@ async def session_bad_key_handler(
|
||||
return web.json_response({"flagged": True})
|
||||
|
||||
|
||||
async def session_keys_handler(data: TrackKeys, session_id: str, request: Optional[web.Request] = None) -> web.Response:
|
||||
"""Store the content keys a client proved on a track of this remote session in the server vaults.
|
||||
|
||||
The server takes a KID only when a track of the remote session names it and no local server vault holds a
|
||||
content key for it, and never a pair flagged bad or one it served, so a client can add a missing content key but
|
||||
never replace or unflag one. It answers once the local vaults hold the pairs and pushes them to the other vaults
|
||||
after, so the client never waits on a remote vault. The reply is always empty, so the client learns nothing.
|
||||
"""
|
||||
session = await get_validated_session(session_id, request)
|
||||
require_authenticated(session)
|
||||
|
||||
track_id, posted = data.get("track_id"), data.get("keys")
|
||||
pairs = {
|
||||
str(kid).replace("-", "").lower(): key.lower()
|
||||
for kid, key in (posted.items() if isinstance(posted, dict) else ())
|
||||
if isinstance(key, str) and re.fullmatch(r"[0-9a-fA-F]{32}", key)
|
||||
}
|
||||
if not pairs:
|
||||
return web.json_response({})
|
||||
service = session.service_instance
|
||||
|
||||
def named_kids() -> set[str]:
|
||||
track = session.tracks.get(track_id) if isinstance(track_id, str) else None
|
||||
if track is not None:
|
||||
ensure_track_drm(track, getattr(service, "session", None))
|
||||
return {kid.hex for t in list(session.tracks.values()) for drm in t.drm or [] for kid in real_kids(drm)}
|
||||
|
||||
def store(named: set[str]) -> tuple[Any, Dict[Any, str]]:
|
||||
vaults = load_server_vaults(service.__class__.__name__)
|
||||
local = [vault for vault in vaults.vaults if vault.local]
|
||||
|
||||
def held(vault: Any, kid: uuid.UUID) -> bool:
|
||||
"""Whether ``vault`` holds a content key for ``kid``. A failed lookup counts as held, a vault with no read access as empty."""
|
||||
try:
|
||||
return bool(vault.get_key(kid, vaults.service))
|
||||
except (PermissionError, NotImplementedError):
|
||||
return False
|
||||
except Exception:
|
||||
return True
|
||||
|
||||
new: Dict[Any, str] = {}
|
||||
for kid_hex, key in pairs.items():
|
||||
if kid_hex not in named or session.served_keys.get(kid_hex, ("",))[0].lower() == key:
|
||||
continue
|
||||
kid = uuid.UUID(hex=kid_hex)
|
||||
if not vaults.is_flagged(kid, key) and not any(held(vault, kid) for vault in local):
|
||||
new[kid] = key
|
||||
if new and sum(vaults.push_keys(vault, new) for vault in local if not vault.no_push):
|
||||
log.info(
|
||||
f"Session {sanitize_log(session_id[:12])} sent {len(new)} client content key(s) to the server vaults"
|
||||
)
|
||||
return vaults, new
|
||||
|
||||
try:
|
||||
async with session.lock:
|
||||
named = await asyncio.to_thread(named_kids)
|
||||
vaults, new = await asyncio.to_thread(store, named)
|
||||
remote = [vault for vault in vaults.vaults if not vault.local and not vault.no_push]
|
||||
if new and remote:
|
||||
asyncio.get_running_loop().run_in_executor(None, lambda: [vaults.push_keys(vault, new) for vault in remote])
|
||||
except (Exception, SystemExit) as e:
|
||||
log.debug(f"Session {sanitize_log(session_id[:12])} content keys not stored: {e!r}")
|
||||
return web.json_response({})
|
||||
|
||||
|
||||
async def session_info_handler(session_id: str, request: Optional[web.Request] = None) -> web.Response:
|
||||
"""Make sure that the remote session is valid, and get the remote session info."""
|
||||
session = await get_validated_session(session_id, request)
|
||||
|
||||
@@ -63,6 +63,7 @@ from unshackle.core.api.handlers import (
|
||||
session_create_handler,
|
||||
session_delete_handler,
|
||||
session_info_handler,
|
||||
session_keys_handler,
|
||||
session_license_handler,
|
||||
session_logs_handler,
|
||||
session_prompt_get_handler,
|
||||
@@ -82,6 +83,7 @@ from unshackle.core.remote_protocol import (
|
||||
BAD_KEY_ROUTE,
|
||||
CHANNEL_ROUTE,
|
||||
HEALTH_ROUTE,
|
||||
KEYS_ROUTE,
|
||||
LICENSE_ROUTE,
|
||||
LOGS_ROUTE,
|
||||
PROMPT_ROUTE,
|
||||
@@ -1146,7 +1148,7 @@ async def download(request: web.Request) -> web.Response:
|
||||
description: Export manifest, DRM init data, keys, and track info to a JSON file in the exports directory (default - false)
|
||||
cdm_only:
|
||||
type: boolean
|
||||
description: Only use CDM for content key retrieval (true) or only vaults (false) (default - None)
|
||||
description: Only use CDM for content key retrieval (true) or only vaults (false). With `remote`, true licenses every track with the CDM of this server and uses no CDM or vault of the remote server (default - None)
|
||||
cdm:
|
||||
type: string
|
||||
description: CDM device name on the server to license with, overriding the cdm config mapping. Requires serve.cdm_overrides to allow it (default - None)
|
||||
@@ -2483,6 +2485,52 @@ async def session_bad_key(request: web.Request) -> web.Response:
|
||||
return await session_bad_key_handler(data, session_id, request)
|
||||
|
||||
|
||||
@api_handler
|
||||
async def session_keys(request: web.Request) -> web.Response:
|
||||
"""
|
||||
Store the content keys a client proved on a track in the server vaults.
|
||||
---
|
||||
summary: Store proven content keys
|
||||
description: >-
|
||||
The client decrypted a track and the output decoded. It sends the content keys that the server
|
||||
did not serve to this remote session. The server stores a content key only for a KID that a
|
||||
track of the remote session names and that no server vault holds a content key for, and never
|
||||
a pair flagged bad. The reply is always empty.
|
||||
parameters:
|
||||
- name: session_id
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required:
|
||||
- track_id
|
||||
- keys
|
||||
properties:
|
||||
track_id:
|
||||
type: string
|
||||
description: The track the keys decrypted
|
||||
keys:
|
||||
type: object
|
||||
description: Content key as hex, by KID as hex
|
||||
additionalProperties:
|
||||
type: string
|
||||
responses:
|
||||
'200':
|
||||
description: An empty object, whatever the server stored
|
||||
'404':
|
||||
description: Remote session not found
|
||||
"""
|
||||
session_id = request.match_info["session_id"]
|
||||
data = await json_body(request)
|
||||
return await session_keys_handler(data, session_id, request)
|
||||
|
||||
|
||||
@api_handler
|
||||
async def session_info(request: web.Request) -> web.Response:
|
||||
"""
|
||||
@@ -3460,6 +3508,7 @@ ROUTES: list[tuple[str, str, Handler, bool]] = [
|
||||
("POST", SEGMENT_FILTER_ROUTE, session_segment_filter, True),
|
||||
("POST", SAMPLES_ROUTE, session_samples, True),
|
||||
("POST", LICENSE_ROUTE, session_license, True),
|
||||
("POST", KEYS_ROUTE, session_keys, True),
|
||||
("POST", BAD_KEY_ROUTE, session_bad_key, True),
|
||||
("GET", LOGS_ROUTE, session_logs, True),
|
||||
("GET", PROMPT_ROUTE, session_prompt_get, True),
|
||||
|
||||
Reference in New Issue
Block a user