refactor(api): move the server CDM licence cap into one module that measures tracks by the -q rule

This commit is contained in:
imSp4rky
2026-11-29 09:16:18 -07:00
parent 6fc2d84bd7
commit 8e67081e11
13 changed files with 318 additions and 168 deletions
+1 -1
View File
@@ -72,7 +72,7 @@ unshackle dl [OPTIONS] SERVICE [SERVICE ARGS...]
| Flag | Default | Description | | Flag | Default | Description |
|---|---|---| |---|---|---|
| `-p`, `--profile` | - | Profile for credentials and cookies. | | `-p`, `--profile` | - | Profile for credentials and cookies. |
| `-q`, `--quality` | best | Resolution(s), comma-separated, e.g. `1080,720`. `-q 1080` also matches anamorphic tracks by 16:9 canvas. | | `-q`, `--quality` | best | Resolution(s), comma-separated, e.g. `1080,720`. `-q 1080` also matches anamorphic tracks by 16:9 canvas, and padded encodes by standard resolution. |
| `-v`, `--vcodec` | any | Video codec(s). Accepts names or values: `AVC`/`H.264`/`H264`, `HEVC`/`H.265`/`H265`, `VVC`/`H.266`/`H266`, `VC1`/`VC-1`, `VP8`, `VP9`, `AV1`. | | `-v`, `--vcodec` | any | Video codec(s). Accepts names or values: `AVC`/`H.264`/`H264`, `HEVC`/`H.265`/`H265`, `VVC`/`H.266`/`H266`, `VC1`/`VC-1`, `VP8`, `VP9`, `AV1`. |
| `-a`, `--acodec` | any | Audio codec(s), comma-separated. Accepts `AAC`, `AC3`/`DD`, `EC3`/`DD+`/`eac3`/`ddp`, `AC4`/`AC-4`, `OPUS`, `OGG`/`VORB`/`vorbis`, `DTS`, `DTSX`/`DTS-X`, `ALAC`, `FLAC`, `MP3`. | | `-a`, `--acodec` | any | Audio codec(s), comma-separated. Accepts `AAC`, `AC3`/`DD`, `EC3`/`DD+`/`eac3`/`ddp`, `AC4`/`AC-4`, `OPUS`, `OGG`/`VORB`/`vorbis`, `DTS`, `DTSX`/`DTS-X`, `ALAC`, `FLAC`, `MP3`. |
| `-vb`, `--vbitrate` | highest | Exact video bitrate in kbps. | | `-vb`, `--vbitrate` | highest | Exact video bitrate in kbps. |
+3 -1
View File
@@ -87,7 +87,9 @@ unshackle dl -q 2160,1080,720 EXAMPLE 81234567
!!! note "16:9 canvas matching" !!! note "16:9 canvas matching"
Resolution matching is by track **height** first. If no track height matches exactly, Resolution matching is by track **height** first. If no track height matches exactly,
unshackle falls back to a 16:9-canvas match, so `-q 1080` also selects an unshackle falls back to a 16:9-canvas match, so `-q 1080` also selects an
anamorphic `1920×804` track (computed as `int(width × 9 / 16)`). unshackle applies the anamorphic `1920×804` track (computed as `int(width × 9 / 16)`). A padded or cropped encode
also matches its standard resolution, the nearest standard height within 10%, so `-q 1080`
selects a `2048×1088` track. unshackle applies the
fallback to each range and codec on its own. A service that crops only its HDR10 tracks fallback to each range and codec on its own. A service that crops only its HDR10 tracks
therefore keeps its `3840×1920` HDR10 track, even when another range has an exact therefore keeps its `3840×1920` HDR10 track, even when another range has an exact
`2160` height match. `2160` height match.
+4 -2
View File
@@ -215,8 +215,10 @@ server-identity flag, keeps the server CDM.
Set it to a height in pixels for every service, or to a map of service tag to height with an Set it to a height in pixels for every service, or to a map of service tag to height with an
optional `default` entry. A service the map does not name or sets to `null` gets the `default`, and optional `default` entry. A service the map does not name or sets to `null` gets the `default`, and
with no `default` it has no limit. The server compares the limit with the lowest `-q` that selects with no `default` it has no limit. The server compares the limit with the lowest `-q` that selects
the track: the track height, or the 16:9 height from the width when that is lower. The server reads the track, by the rule of `dl -q`: the track height, the 16:9 height from the width, or the standard
the remote client's `-q` when the remote session starts: resolution of a padded or cropped encode (the nearest standard height within 10%). Thus the server
never refuses a track that `-q` at the limit selects: a padded `2048x1088` track passes a `1080`
limit. The server reads the remote client's `-q` when the remote session starts:
- With no `-q`, or a `-q` at or below the limit, the server CDM licenses the remote session. The server - With no `-q`, or a `-q` at or below the limit, the server CDM licenses the remote session. The server
refuses a live licence for a video track taller than the limit, and the client licenses that refuses a live licence for a video track taller than the limit, and the client licenses that
+3 -14
View File
@@ -108,20 +108,9 @@ def test_the_named_services_are_the_global_list_else_every_keys_list():
assert api_keys({"users": users}) == ["a", "b", "c", "d"] assert api_keys({"users": users}) == ["a", "b", "c", "d"]
@pytest.mark.parametrize( def test_the_policy_hands_over_the_cap_of_the_service():
("setting", "service", "cap"), policy = KeyPolicy({"server_cdm_max_height": {"example1": 720, "default": 1080}})
[ assert (policy.max_height("EXAMPLE1"), policy.max_height(None)) == (720, 1080)
(1080, "EXAMPLE1", 1080),
({"example1": 720, "default": 1080}, "EXAMPLE1", 720),
({"example1": 720, "default": 1080}, "EXAMPLE2", 1080),
({"EXAMPLE1": 1080}, "EXAMPLE2", None),
({"EXAMPLE1": None, "default": 1080}, "EXAMPLE1", 1080),
(None, "EXAMPLE1", None),
(True, "EXAMPLE1", None),
],
)
def test_the_height_cap_per_service(setting, service, cap):
assert KeyPolicy({"server_cdm_max_height": setting}).max_height(service) == cap
def test_a_key_with_no_entry_gets_every_server_device(): def test_a_key_with_no_entry_gets_every_server_device():
+149
View File
@@ -0,0 +1,149 @@
"""The licence cap module: the setting, the track measure, and the request and track questions."""
import pytest
from unshackle.core.api import licence_cap
from unshackle.core.api.errors import APIError
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.tracks import Audio, Video
from unshackle.core.tracks.tracks import at_resolution
pytestmark = pytest.mark.unit
CAP_DETAILS = {"reason": "server_cdm_max_height", "max_height": 1080}
def video(height, width=None):
track = Video.__new__(Video)
track.height = height
track.width = width
return track
@pytest.mark.parametrize(
("setting", "service", "cap"),
[
(1080, "EXAMPLE1", 1080),
({"example1": 720, "default": 1080}, "EXAMPLE1", 720),
({"example1": 720, "default": 1080}, "EXAMPLE2", 1080),
({"example1": 720, "default": 1080}, None, 1080),
({"EXAMPLE1": 1080}, "EXAMPLE2", None),
({"EXAMPLE1": None, "default": 1080}, "EXAMPLE1", 1080),
(None, "EXAMPLE1", None),
(True, "EXAMPLE1", None),
],
)
def test_the_cap_per_service(setting, service, cap):
assert licence_cap.cap_for(setting, service) == cap
@pytest.mark.parametrize(
("value", "problem"),
[
("1080", "u.server_cdm_max_height must be"),
(True, "u.server_cdm_max_height must be"),
({"EXAMPLE": -1}, "u.server_cdm_max_height values"),
(None, None),
(1080, None),
({"EXAMPLE1": 720, "default": None}, None),
],
)
def test_the_setting_check(value, problem):
error = licence_cap.setting_error("u", value)
assert error is None if problem is None else problem in error
@pytest.mark.parametrize(
("track", "refused"),
[
(video(2160), True),
(video(1080), False),
(video(None), False),
(Audio.__new__(Audio), False),
(video(1088, 2048), False),
(video(1600, 3840), True),
(video(None, 3840), True),
(video(1080, 2560), False),
(video(1080, 1920), False),
],
)
def test_a_track_above_the_cap_gets_no_live_licence(track, refused):
assert (licence_cap.track_refusal(1080, track) is not None) is refused
def test_no_cap_refuses_no_track():
assert licence_cap.track_refusal(None, video(4320)) is None
def test_the_track_refusal_gives_the_client_the_cap():
refusal = licence_cap.track_refusal(1080, video(2160))
assert refusal.error_code is APIErrorCode.SERVER_CDM_CAPPED
assert refusal.details == CAP_DETAILS
assert "2160p track" in refusal.message
@pytest.mark.parametrize("size", [(1088, 2048), (1188, 2112), (800, 1920), (1080, 2560), (1080, 1920), (None, 1920)])
def test_a_track_that_the_cap_quality_selects_gets_a_live_licence(size):
track = video(*size)
assert at_resolution(track, 1080)
assert licence_cap.track_refusal(1080, track) is None
@pytest.mark.parametrize(
("cap", "quality", "has_device", "server_cdm"),
[
(None, [2160], False, True),
(1080, [1080], False, True),
(1080, [], False, True),
(1080, [2160, 1080], True, False),
(1080, ["2160p"], True, False),
],
)
def test_the_session_question(cap, quality, has_device, server_cdm):
assert licence_cap.session_fits(cap, "EXAMPLE1", quality, has_device) is server_cdm
def test_a_session_above_the_cap_without_a_device_is_refused():
with pytest.raises(APIError) as ei:
licence_cap.session_fits(1080, "EXAMPLE1", [2160], False)
assert ei.value.error_code is APIErrorCode.SERVER_CDM_CAPPED
assert ei.value.details == CAP_DETAILS
@pytest.mark.parametrize("quality", [["best"], [-1], [0], [1080, 0]])
@pytest.mark.parametrize("cap", [None, 1080])
def test_a_bad_quality_is_invalid_parameters(quality, cap):
with pytest.raises(APIError) as ei:
licence_cap.session_fits(cap, "EXAMPLE1", quality, True)
assert ei.value.error_code is APIErrorCode.INVALID_PARAMETERS
@pytest.mark.parametrize(
"params",
[
{"quality": [2160]},
{"quality": []},
{},
{"quality": [1080], "best_available": True},
{"quality": [1080], "range": "HYBRID"},
{"quality": [1080], "range": ["SDR", "hybrid"]},
{"quality": [1080], "range": [Video.Range.HYBRID]},
],
)
def test_a_job_that_could_pass_the_cap_is_refused(params):
with pytest.raises(APIError) as ei:
licence_cap.check_job(1080, params)
assert ei.value.error_code is APIErrorCode.SERVER_CDM_CAPPED
assert ei.value.details == CAP_DETAILS
@pytest.mark.parametrize(
("cap", "params"),
[
(1080, {"quality": [1080]}),
(1080, {"quality": [720, 1080], "range": ["HDR10"]}),
(None, {"best_available": True}),
],
)
def test_a_job_inside_the_cap_passes(cap, params):
licence_cap.check_job(cap, params)
@@ -108,19 +108,11 @@ def test_above_the_cap_without_a_device_is_refused_at_create():
assert ei.value.details == {"reason": "server_cdm_max_height", "max_height": 1080} assert ei.value.details == {"reason": "server_cdm_max_height", "max_height": 1080}
def test_bad_quality_is_invalid_parameters():
with pytest.raises(APIError) as ei:
handlers.choose_session_cdm(KeyPolicy(USERS["flat"]), "EXAMPLE1", {"quality": ["best"]})
assert ei.value.error_code is APIErrorCode.INVALID_PARAMETERS
@pytest.mark.parametrize( @pytest.mark.parametrize(
("session", "track", "refused"), ("session", "track", "refused"),
[ [
(session_entry(server_cdm_max_height=1080), video(2160), True), (session_entry(server_cdm_max_height=1080), video(2160), True),
(session_entry(server_cdm_max_height=1080), video(1080), False), (session_entry(server_cdm_max_height=1080), video(1080), False),
(session_entry(server_cdm_max_height=1080), video(None), False),
(session_entry(server_cdm_max_height=1080), Audio.__new__(Audio), False),
(session_entry(server_cdm_max_height=None), video(2160), False), (session_entry(server_cdm_max_height=None), video(2160), False),
(session_entry(server_cdm=False, server_cdm_max_height=1080), video(720), True), (session_entry(server_cdm=False, server_cdm_max_height=1080), video(720), True),
(session_entry(), video(2160), False), (session_entry(), video(2160), False),
@@ -167,7 +159,7 @@ def test_a_vault_miss_raises_the_refusal_before_the_device_loads(widevine_env, m
assert ei.value is refusal assert ei.value is refusal
@pytest.mark.parametrize(("quality", "allowed"), [([1080], True), ([720, 1080], True), ([2160], False), ([], False)]) @pytest.mark.parametrize(("quality", "allowed"), [([1080], True), ([2160], False)])
def test_download_jobs_stay_inside_the_cap(quality, allowed): def test_download_jobs_stay_inside_the_cap(quality, allowed):
params = {"service": "EXAMPLE1", "quality": quality} params = {"service": "EXAMPLE1", "quality": quality}
if allowed: if allowed:
@@ -239,30 +231,6 @@ def test_a_server_vault_miss_without_the_local_drm_system_fails_at_once():
assert "-q" not in ei.value.message assert "-q" not in ei.value.message
def test_an_ultrawide_track_is_measured_as_the_smallest_quality_that_selects_it():
"""-q matches a height or a 16:9 width, so a track passes the cap when either one is inside it."""
session = session_entry(server_cdm_max_height=1080)
assert handlers.live_licence_refusal(session, video(1600, 3840)) is not None
assert handlers.live_licence_refusal(session, video(None, 3840)) is not None
assert handlers.live_licence_refusal(session, video(1080, 2560)) is None # -q 1080 selects it
assert handlers.live_licence_refusal(session, video(1080, 1920)) is None
@pytest.mark.parametrize("quality", [[-1], [0], [1080, 0]])
def test_a_height_of_zero_or_less_is_invalid_parameters(quality):
with pytest.raises(APIError) as ei:
job_admission.enforce_download_gates({"service": "EXAMPLE1", "quality": quality}, request("flat"))
assert ei.value.error_code is APIErrorCode.INVALID_PARAMETERS
def test_a_capped_download_job_cannot_set_best_available():
with pytest.raises(APIError) as ei:
job_admission.enforce_download_gates(
{"service": "EXAMPLE1", "quality": [1080], "best_available": True}, request("flat")
)
assert ei.value.error_code is APIErrorCode.SERVER_CDM_CAPPED
def test_the_download_gate_reads_the_serve_dl_defaults(monkeypatch): def test_the_download_gate_reads_the_serve_dl_defaults(monkeypatch):
serve = {"users": USERS, "quality": [1080], "best_available": True} serve = {"users": USERS, "quality": [1080], "best_available": True}
monkeypatch.setattr(handlers.config, "serve", serve, raising=False) monkeypatch.setattr(handlers.config, "serve", serve, raising=False)
@@ -280,19 +248,6 @@ def test_the_download_gate_reads_the_serve_dl_defaults(monkeypatch):
admit() admit()
@pytest.mark.parametrize("hdr_range", ["HYBRID", ["SDR", "hybrid"], [Video.Range.HYBRID]])
def test_a_capped_download_job_cannot_ask_for_hybrid(hdr_range):
"""HYBRID always keeps the lowest DV track, whatever the quality."""
with pytest.raises(APIError) as ei:
job_admission.enforce_download_gates(
{"service": "EXAMPLE1", "quality": [1080], "range": hdr_range}, request("flat")
)
assert ei.value.error_code is APIErrorCode.SERVER_CDM_CAPPED
job_admission.enforce_download_gates(
{"service": "EXAMPLE1", "quality": [1080], "range": ["HDR10"]}, request("flat")
)
def test_a_service_click_default_stays_out_of_the_download_gate(monkeypatch): def test_a_service_click_default_stays_out_of_the_download_gate(monkeypatch):
"""A service's own option is not the dl option of the same name, so its default never trips the gate.""" """A service's own option is not the dl option of the same name, so its default never trips the gate."""
import asyncio import asyncio
@@ -437,14 +392,16 @@ def test_batch_restores_the_manifest_drm_on_a_track_refused_twice(licence_env, i
def test_batch_serves_a_capped_track_from_a_vault_hit_on_its_init_pssh(licence_env, init_segment): def test_batch_serves_a_capped_track_from_a_vault_hit_on_its_init_pssh(licence_env, init_segment):
licence_env.vault["init"] = {INIT_KID.hex: "v"} licence_env.vault["init"] = {INIT_KID.hex: "v"}
track = media(Video, "vid", [_PSSHDrm("manifest", [KID])], height=2160, get_key_id=lambda init: INIT_KID) track = media(
Video, "vid", [_PSSHDrm("manifest", [KID])], height=2160, width=3840, get_key_id=lambda init: INIT_KID
)
payload = batch(licence_env, track) payload = batch(licence_env, track)
assert "capped_tracks" not in payload assert "capped_tracks" not in payload
assert payload["keys"] == {"vid": {INIT_KID.hex: "v"}} assert payload["keys"] == {"vid": {INIT_KID.hex: "v"}}
def test_single_licence_refuses_a_capped_track_with_details(licence_env): def test_single_licence_refuses_a_capped_track_with_details(licence_env):
track = media(Video, "vid", [_PSSHDrm("manifest", [KID])], height=2160) track = media(Video, "vid", [_PSSHDrm("manifest", [KID])], height=2160, width=3840)
licence_env.session.tracks = {"vid": track} licence_env.session.tracks = {"vid": track}
data = {"mode": "server_cdm", "track_id": "vid", "drm_type": "widevine"} data = {"mode": "server_cdm", "track_id": "vid", "drm_type": "widevine"}
with pytest.raises(APIError) as ei: with pytest.raises(APIError) as ei:
+9 -48
View File
@@ -24,10 +24,12 @@ import click
from aiohttp import web from aiohttp import web
from unshackle.core import login from unshackle.core import login
from unshackle.core.api import licence_cap
from unshackle.core.api.compression import InflateLimitError, safe_inflate from unshackle.core.api.compression import InflateLimitError, safe_inflate
from unshackle.core.api.errors import APIError, categorize_exception, handle_api_exception 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.input_bridge import InputBridge, NoUserBridge
from unshackle.core.api.key_policy import KeyPolicy, api_keys, is_whole_number, named_services from unshackle.core.api.key_policy import KeyPolicy, api_keys, named_services
from unshackle.core.api.licence_cap import is_whole_number
from unshackle.core.api.progress import track_log_label from unshackle.core.api.progress import track_log_label
from unshackle.core.api.sanitize import ( from unshackle.core.api.sanitize import (
MAX_SESSION_CACHE_BYTES, MAX_SESSION_CACHE_BYTES,
@@ -76,7 +78,6 @@ from unshackle.core.run_plan import SESSION_DL_KEYS, PlanError, served_plan
from unshackle.core.services import Services from unshackle.core.services import Services
from unshackle.core.session import RnetSession, utf8_text from unshackle.core.session import RnetSession, utf8_text
from unshackle.core.titles import Episode, Song from unshackle.core.titles import Episode, Song
from unshackle.core.tracks import Video
from unshackle.core.tunnel import ( from unshackle.core.tunnel import (
HEARTBEAT, HEARTBEAT,
MAX_MESSAGE, MAX_MESSAGE,
@@ -88,7 +89,7 @@ from unshackle.core.tunnel import (
tunnel_proxy, tunnel_proxy,
) )
from unshackle.core.utilities import declared_kwargs from unshackle.core.utilities import declared_kwargs
from unshackle.core.utils.click_types import QUALITY_LIST, SEASON_RANGE, ContextData from unshackle.core.utils.click_types import SEASON_RANGE, ContextData
from unshackle.core.utils.hdr10plus import probed_tracks from unshackle.core.utils.hdr10plus import probed_tracks
from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_all, redact_secrets, redact_text from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_all, redact_secrets, redact_text
from unshackle.core.utils.service_params import FLAT_DL_KEYS, cast_service_options, service_options from unshackle.core.utils.service_params import FLAT_DL_KEYS, cast_service_options, service_options
@@ -942,29 +943,6 @@ def drop_identity_cache(api_keys: Iterable[str]) -> None:
SessionStore.cleanup_cache_dir(f"_identity/{key_namespace(api_key)}") SessionStore.cleanup_cache_dir(f"_identity/{key_namespace(api_key)}")
def capped_error(message: str, cap: int | None = None) -> APIError:
"""The SERVER_CDM_CAPPED refusal; a client reads ``details`` to license the track itself."""
details = {"reason": "server_cdm_max_height", "max_height": cap} if cap is not None else {"reason": "client_device"}
return APIError(APIErrorCode.SERVER_CDM_CAPPED, message, details=details)
def requested_heights(quality: Any) -> list[int]:
"""The heights a client asked for with ``-q``, as the dl option gives them; empty for the best there is."""
try:
heights = QUALITY_LIST.convert(quality or [])
except click.BadParameter as e:
raise APIError(APIErrorCode.INVALID_PARAMETERS, f"quality: {e.message}") from e
if any(height <= 0 for height in heights):
raise APIError(APIErrorCode.INVALID_PARAMETERS, f"quality: every height must be above 0, not {quality!r}")
return heights
def requested_height(quality: Any) -> int | None:
"""The tallest height a client asked for with ``-q``; None when it asked for the best there is."""
heights = requested_heights(quality)
return max(heights) if heights else None
def server_device_requested(service_module: Any, data: dict[str, Any]) -> bool: def server_device_requested(service_module: Any, data: dict[str, Any]) -> bool:
"""True when the request sets one of the service's ``SERVER_DEVICE_OPTIONS``, cast as the service's own options cast it.""" """True when the request sets one of the service's ``SERVER_DEVICE_OPTIONS``, cast as the service's own options cast it."""
options = service_options(data, getattr(service_module, "SERVER_DEVICE_OPTIONS", ())) options = service_options(data, getattr(service_module, "SERVER_DEVICE_OPTIONS", ()))
@@ -989,22 +967,13 @@ def choose_session_cdm(policy: KeyPolicy, service: str, data: dict[str, Any]) ->
if not server_device_requested(Services.load(service), data): if not server_device_requested(Services.load(service), data):
return False, None return False, None
cap = policy.max_height(service) cap = policy.max_height(service)
wanted = requested_height(data.get("quality")) return licence_cap.session_fits(cap, service, data.get("quality"), bool(data.get("cdm_type"))), cap
if cap is None or wanted is None or wanted <= cap:
return True, cap
if data.get("cdm_type"):
return False, cap
raise capped_error(
f"The server CDM licenses {service} up to {cap}p for this API key, {wanted}p needs a local CDM",
cap,
)
def live_licence_refusal(session: SessionEntry, track: Any) -> APIError | None: 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. """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. A track measures as the Only a live licence spends the server's device, so a vault hit always passes.
smallest ``-q`` that selects it: the lower of its height and the 16:9 height of its width.
""" """
if session.server_device: if session.server_device:
return APIError( return APIError(
@@ -1013,18 +982,10 @@ def live_licence_refusal(session: SessionEntry, track: Any) -> APIError | None:
details={"reason": "server_device"}, details={"reason": "server_device"},
) )
if not session.server_cdm: if not session.server_cdm:
return capped_error("This session licenses with your own device, so the server CDM makes no licence for it.") return licence_cap.capped_error(
cap = session.server_cdm_max_height "This session licenses with your own device, so the server CDM makes no licence for it."
height = getattr(track, "height", None) if isinstance(track, Video) else None
width = getattr(track, "width", None) if isinstance(track, Video) else None
measures = [m for m in (height, int(width * 9 / 16) if width else None) if m]
height = min(measures) if measures else None
if cap is None or not height or height <= cap:
return None
return capped_error(
f"The server CDM licenses up to {cap}p for this API key; license this {height}p track with your own device.",
cap,
) )
return licence_cap.track_refusal(session.server_cdm_max_height, track)
_account_counters: dict[str, int] = {} _account_counters: dict[str, int] = {}
+4 -13
View File
@@ -9,7 +9,7 @@ from typing import Any
import click import click
from aiohttp import web from aiohttp import web
from unshackle.core.api import handlers from unshackle.core.api import handlers, licence_cap
from unshackle.core.api.download_manager import plan_keys, stamped_keys from unshackle.core.api.download_manager import plan_keys, stamped_keys
from unshackle.core.api.errors import APIError from unshackle.core.api.errors import APIError
from unshackle.core.config import config from unshackle.core.config import config
@@ -17,7 +17,7 @@ from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS, DL_OPTION_ALIASES
from unshackle.core.remote_protocol import APIErrorCode from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.run_plan import PlanError, api_plan, cast_plan from unshackle.core.run_plan import PlanError, api_plan, cast_plan
from unshackle.core.services import ROUTING_PARAMS, Services from unshackle.core.services import ROUTING_PARAMS, Services
from unshackle.core.utils.collections import as_list, ci_get from unshackle.core.utils.collections import ci_get
ENVELOPE_KEYS = ("service", "title_id", "owner_key") ENVELOPE_KEYS = ("service", "title_id", "owner_key")
log = logging.getLogger("api") log = logging.getLogger("api")
@@ -160,7 +160,7 @@ def check_parameters(data: dict[str, Any]) -> dict[str, Any]:
if data.get("quality") is not None: if data.get("quality") is not None:
try: try:
handlers.requested_heights(data["quality"]) licence_cap.requested_heights(data["quality"])
except APIError as e: except APIError as e:
raise invalid(e.message, data) from None raise invalid(e.message, data) from None
@@ -242,16 +242,7 @@ def enforce_download_gates(params: dict[str, Any], request: web.Request | None =
APIErrorCode.FORBIDDEN, APIErrorCode.FORBIDDEN,
"Download jobs run on the server's own device config, and this API key has its own for this service", "Download jobs run on the server's own device config, and this API key has its own for this service",
) )
cap = policy.max_height(service) licence_cap.check_job(policy.max_height(service), params)
if cap is not None:
capped = f"Download jobs license with the server CDM, up to {cap}p for this API key"
wanted = handlers.requested_height(params.get("quality"))
if wanted is None or wanted > cap:
raise handlers.capped_error(f"{capped}: pass a quality", cap)
if params.get("best_available"):
raise handlers.capped_error(f"{capped}: drop best_available", cap)
if any(str(getattr(r, "value", r)).upper() == "HYBRID" for r in as_list(params.get("range") or [])):
raise handlers.capped_error(f"{capped}: drop HYBRID", cap)
if params.get("proxy_download") is not None and not isinstance(params["proxy_download"], str): if params.get("proxy_download") is not None and not isinstance(params["proxy_download"], str):
raise APIError(APIErrorCode.INVALID_INPUT, "proxy_download must be a string.") raise APIError(APIErrorCode.INVALID_INPUT, "proxy_download must be a string.")
+4 -32
View File
@@ -7,6 +7,7 @@ import logging
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Any, Literal from typing import Any, Literal
from unshackle.core.api import licence_cap
from unshackle.core.cdm.loader import device_system from unshackle.core.cdm.loader import device_system
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.launch import load_service_config from unshackle.core.launch import load_service_config
@@ -45,11 +46,6 @@ def named_services(serve: dict[str, Any] | None = None) -> list[str]:
return [Services.get_tag(s) for names in lists if isinstance(names, list) for s in names if isinstance(s, str)] return [Services.get_tag(s) for names in lists if isinstance(names, list) for s in names if isinstance(s, str)]
def is_whole_number(value: Any) -> bool:
"""True for a non-negative int that is not a bool."""
return isinstance(value, int) and not isinstance(value, bool) and value >= 0
def rate_limit_error(where: str, value: Any) -> str | None: def rate_limit_error(where: str, value: Any) -> str | None:
"""Why *value* cannot serve as a rate limit, or None when it can. Unset is fine. """Why *value* cannot serve as a rate limit, or None when it can. Unset is fine.
@@ -155,15 +151,8 @@ class KeyPolicy:
return self._entry.get("server_cdm_max_height") return self._entry.get("server_cdm_max_height")
def max_height(self, service: str | None) -> int | None: def max_height(self, service: str | None) -> int | None:
"""The tallest video track the server CDM licenses live for ``service``; None for no cap. """The licence cap of ``service``, as :func:`licence_cap.cap_for` reads the setting; None for no cap."""
return licence_cap.cap_for(self.max_height_setting, Services.get_tag(service) if service else None)
In a map, ``default`` covers a missing or null tag.
"""
cap = self.max_height_setting
if isinstance(cap, dict):
own = ci_get(cap, Services.get_tag(service)) if service else None
cap = own if own is not None else ci_get(cap, "default")
return cap if is_whole_number(cap) else None
def devices(self, kind: Literal["devices", "playready_devices"]) -> list[str]: def devices(self, kind: Literal["devices", "playready_devices"]) -> list[str]:
"""The API key's device names of ``kind``; every device the server loaded for an API key with no entry.""" """The API key's device names of ``kind``; every device the server loaded for an API key with no entry."""
@@ -253,28 +242,11 @@ class KeyPolicy:
return f"{where}.tier: no such tier '{tier}' under serve.tiers" return f"{where}.tier: no such tier '{tier}' under serve.tiers"
return ( return (
rate_limit_error(where, entry.get("rate_limit")) rate_limit_error(where, entry.get("rate_limit"))
or _max_height_error(where, entry.get("server_cdm_max_height")) or licence_cap.setting_error(where, entry.get("server_cdm_max_height"))
or _identity_error(where, entry, app_config or config) or _identity_error(where, entry, app_config or config)
) )
def _max_height_error(where: str, value: Any) -> str | None:
"""Why *value* cannot serve as ``server_cdm_max_height``, or None when it can (unset included)."""
def bad(height: Any) -> bool:
return height is not None and not is_whole_number(height)
if isinstance(value, dict):
if any(bad(height) for height in value.values()):
return f"{where}.server_cdm_max_height values must be whole numbers of pixels, not {value!r}"
return None
if bad(value):
return (
f"{where}.server_cdm_max_height must be a whole number of pixels or a map of service to one, not {value!r}"
)
return None
def _identity_error(where: str, entry: dict[str, Any], app_config: Any) -> str | None: def _identity_error(where: str, entry: dict[str, Any], app_config: Any) -> str | None:
"""Why the ``services``, ``cdm`` or ``service_config`` of an entry cannot work; None when it can. """Why the ``services``, ``cdm`` or ``service_config`` of an entry cannot work; None when it can.
+119
View File
@@ -0,0 +1,119 @@
"""The server CDM licence cap: ``server_cdm_max_height``, the tallest video the server's device licenses live.
:class:`KeyPolicy` reads the setting from ``serve.users``; this module validates it, measures tracks, and answers the
request and track questions with the SERVER_CDM_CAPPED refusal that a remote client reads.
"""
from __future__ import annotations
from typing import Any
import click
from unshackle.core.api.errors import APIError
from unshackle.core.remote_protocol import APIErrorCode, cap_note
from unshackle.core.tracks.tracks import quality_heights
from unshackle.core.tracks.video import Video
from unshackle.core.utils.click_types import QUALITY_LIST
from unshackle.core.utils.collections import as_list, ci_get
def is_whole_number(value: Any) -> bool:
"""True for a non-negative int that is not a bool."""
return isinstance(value, int) and not isinstance(value, bool) and value >= 0
def setting_error(where: str, value: Any) -> str | None:
"""Why *value* cannot serve as ``server_cdm_max_height``, or None when it can (unset included)."""
def bad(height: Any) -> bool:
return height is not None and not is_whole_number(height)
if isinstance(value, dict):
if any(bad(height) for height in value.values()):
return f"{where}.server_cdm_max_height values must be whole numbers of pixels, not {value!r}"
return None
if bad(value):
return (
f"{where}.server_cdm_max_height must be a whole number of pixels or a map of service to one, not {value!r}"
)
return None
def cap_for(setting: Any, service: str | None) -> int | None:
"""The cap that *setting* gives the service tag *service*; None for no cap. In a map, ``default`` covers a
missing or null tag."""
if isinstance(setting, dict):
own = ci_get(setting, service) if service else None
setting = own if own is not None else ci_get(setting, "default")
return setting if is_whole_number(setting) else None
def capped_error(message: str, cap: int | None = None) -> APIError:
"""The SERVER_CDM_CAPPED refusal; a client reads ``details`` to license the track itself."""
details = {"reason": "server_cdm_max_height", "max_height": cap} if cap is not None else {"reason": "client_device"}
return APIError(APIErrorCode.SERVER_CDM_CAPPED, message, details=details)
def requested_heights(quality: Any) -> list[int]:
"""The heights a client asked for with ``-q``, as the dl option gives them; empty for the best there is."""
try:
heights = QUALITY_LIST.convert(quality or [])
except click.BadParameter as e:
raise APIError(APIErrorCode.INVALID_PARAMETERS, f"quality: {e.message}") from e
if any(height <= 0 for height in heights):
raise APIError(APIErrorCode.INVALID_PARAMETERS, f"quality: every height must be above 0, not {quality!r}")
return heights
def requested_height(quality: Any) -> int | None:
"""The tallest height a client asked for with ``-q``; None when it asked for the best there is."""
heights = requested_heights(quality)
return max(heights) if heights else None
def session_fits(cap: int | None, service: str, quality: Any, has_device: bool) -> bool:
"""Whether the server CDM licenses a remote session that asks for *quality*.
Above the cap the client's own device licenses the whole session, and a client with no device gets the refusal.
"""
wanted = requested_height(quality)
if cap is None or wanted is None or wanted <= cap:
return True
if has_device:
return False
raise capped_error(
f"The server CDM licenses {service} up to {cap}p for this API key, {wanted}p needs a local CDM",
cap,
)
def check_job(cap: int | None, params: dict[str, Any]) -> None:
"""Refuse a download job that could license a track above *cap*.
A job has no client device to hand a track to, so it must pass a quality at or under the cap, no
``best_available`` and no HYBRID range.
"""
if cap is None:
return
capped = f"Download jobs license with the server CDM, up to {cap}p for this API key"
wanted = requested_height(params.get("quality"))
if wanted is None or wanted > cap:
raise capped_error(f"{capped}: pass a quality", cap)
if params.get("best_available"):
raise capped_error(f"{capped}: drop best_available", cap)
if any(str(getattr(r, "value", r)).upper() == "HYBRID" for r in as_list(params.get("range") or [])):
raise capped_error(f"{capped}: drop HYBRID", cap)
def track_refusal(cap: int | None, track: Any) -> APIError | None:
"""The refusal of a live licence for *track* above *cap*; None when it may have one.
A video measures as the smallest ``-q`` that selects it, by dl's own rule, so a track that ``-q <cap>`` selects
always passes. Another track, or a video with no size, passes.
"""
heights = quality_heights(track) if isinstance(track, Video) else set()
height = min(heights, default=None)
if cap is None or height is None or height <= cap:
return None
return capped_error(f"{cap_note(cap)}; license this {height}p track with your own device.", cap)
+5
View File
@@ -77,6 +77,11 @@ class APIErrorCode(str, Enum):
E = TypeVar("E", bound=BaseException) E = TypeVar("E", bound=BaseException)
def cap_note(cap: int) -> str:
"""The sentence that names a ``server_cdm_max_height`` cap, on the server and on the client."""
return f"The server CDM licenses up to {cap}p for this API key"
def coded(exc: E, code: APIErrorCode) -> E: def coded(exc: E, code: APIErrorCode) -> E:
"""``exc`` with the API error code that ``categorize_exception`` reports for it, whatever its message says.""" """``exc`` with the API error code that ``categorize_exception`` reports for it, whatever its message says."""
exc.error_code = code # type: ignore[attr-defined] exc.error_code = code # type: ignore[attr-defined]
+3 -2
View File
@@ -82,6 +82,7 @@ from unshackle.core.remote_protocol import (
TrackKeys, TrackKeys,
TracksReply, TracksReply,
TracksRequest, TracksRequest,
cap_note,
coded, coded,
) )
from unshackle.core.search_result import SearchResult from unshackle.core.search_result import SearchResult
@@ -1230,7 +1231,7 @@ class RemoteService(TitleSource):
self._server_cdm = server_cdm self._server_cdm = server_cdm
if max_height is None: if max_height is None:
return return
message = f"The server CDM licenses up to {max_height}p for this API key" message = cap_note(max_height)
if not server_cdm: if not server_cdm:
message += "; licensing with your own device" message += "; licensing with your own device"
elif self.local_cdm is not None: elif self.local_cdm is not None:
@@ -1623,7 +1624,7 @@ class RemoteService(TitleSource):
) )
cap = refusal.get("max_height") cap = refusal.get("max_height")
if cap: if cap:
why = f"The server CDM licenses up to {cap}p for this API key" why = cap_note(cap)
elif getattr(self, "_server_vault", False): elif getattr(self, "_server_vault", False):
why = "The server vault holds no content key for this track" why = "The server vault holds no content key for this track"
else: else:
+8 -6
View File
@@ -53,13 +53,15 @@ MP4BOX_PROGRESS = re.compile(r"\((\d{1,3})/100\)")
MP4BOX_OPEN_FAILED = re.compile(r"error while opening|Error opening file|Invalid IsoMedia File", re.I) MP4BOX_OPEN_FAILED = re.compile(r"error while opening|Error opening file|Invalid IsoMedia File", re.I)
def quality_heights(video: Video) -> set[int]:
"""Every ``-q`` height that selects a track: its height, the height from a 16:9 width, its standard resolution."""
width_height = int(video.width * 9 / 16) if video.width else None
return {r for r in (video.height, width_height, standard_resolution(video.width, video.height)) if r}
def at_resolution(video: Video, res: int) -> bool: def at_resolution(video: Video, res: int) -> bool:
"""Whether a track has this height, this height from a 16:9 width, or this standard resolution (a padded encode).""" """Whether ``-q res`` selects a track; a padded encode matches by its standard resolution."""
return ( return video.height == res or res in quality_heights(video)
video.height == res
or bool(video.width and int(video.width * 9 / 16) == res)
or standard_resolution(video.width, video.height) == res
)
def video_rank(video: Video) -> tuple[int, bool, float, int]: def video_rank(video: Video) -> tuple[int, bool, float, int]: