forked from kenzuya/unshackle
refactor(api): move the server CDM licence cap into one module that measures tracks by the -q rule
This commit is contained in:
@@ -24,10 +24,12 @@ import click
|
||||
from aiohttp import web
|
||||
|
||||
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.errors import APIError, categorize_exception, handle_api_exception
|
||||
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.sanitize import (
|
||||
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.session import RnetSession, utf8_text
|
||||
from unshackle.core.titles import Episode, Song
|
||||
from unshackle.core.tracks import Video
|
||||
from unshackle.core.tunnel import (
|
||||
HEARTBEAT,
|
||||
MAX_MESSAGE,
|
||||
@@ -88,7 +89,7 @@ from unshackle.core.tunnel import (
|
||||
tunnel_proxy,
|
||||
)
|
||||
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.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
|
||||
@@ -942,29 +943,6 @@ def drop_identity_cache(api_keys: Iterable[str]) -> None:
|
||||
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:
|
||||
"""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", ()))
|
||||
@@ -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):
|
||||
return False, None
|
||||
cap = policy.max_height(service)
|
||||
wanted = requested_height(data.get("quality"))
|
||||
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,
|
||||
)
|
||||
return licence_cap.session_fits(cap, service, data.get("quality"), bool(data.get("cdm_type"))), cap
|
||||
|
||||
|
||||
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. A track measures as the
|
||||
smallest ``-q`` that selects it: the lower of its height and the 16:9 height of its width.
|
||||
Only a live licence spends the server's device, so a vault hit always passes.
|
||||
"""
|
||||
if session.server_device:
|
||||
return APIError(
|
||||
@@ -1013,18 +982,10 @@ def live_licence_refusal(session: SessionEntry, track: Any) -> APIError | None:
|
||||
details={"reason": "server_device"},
|
||||
)
|
||||
if not session.server_cdm:
|
||||
return capped_error("This session licenses with your own device, so the server CDM makes no licence for it.")
|
||||
cap = session.server_cdm_max_height
|
||||
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.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)
|
||||
|
||||
|
||||
_account_counters: dict[str, int] = {}
|
||||
|
||||
@@ -9,7 +9,7 @@ from typing import Any
|
||||
import click
|
||||
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.errors import APIError
|
||||
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.run_plan import PlanError, api_plan, cast_plan
|
||||
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")
|
||||
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:
|
||||
try:
|
||||
handlers.requested_heights(data["quality"])
|
||||
licence_cap.requested_heights(data["quality"])
|
||||
except APIError as e:
|
||||
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,
|
||||
"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)
|
||||
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)
|
||||
licence_cap.check_job(policy.max_height(service), params)
|
||||
|
||||
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.")
|
||||
|
||||
@@ -7,6 +7,7 @@ import logging
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Literal
|
||||
|
||||
from unshackle.core.api import licence_cap
|
||||
from unshackle.core.cdm.loader import device_system
|
||||
from unshackle.core.config import 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)]
|
||||
|
||||
|
||||
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:
|
||||
"""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")
|
||||
|
||||
def max_height(self, service: str | None) -> int | None:
|
||||
"""The tallest video track the server CDM licenses live for ``service``; None for no cap.
|
||||
|
||||
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
|
||||
"""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)
|
||||
|
||||
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."""
|
||||
@@ -253,28 +242,11 @@ class KeyPolicy:
|
||||
return f"{where}.tier: no such tier '{tier}' under serve.tiers"
|
||||
return (
|
||||
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)
|
||||
)
|
||||
|
||||
|
||||
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:
|
||||
"""Why the ``services``, ``cdm`` or ``service_config`` of an entry cannot work; None when it can.
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -77,6 +77,11 @@ class APIErrorCode(str, Enum):
|
||||
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:
|
||||
"""``exc`` with the API error code that ``categorize_exception`` reports for it, whatever its message says."""
|
||||
exc.error_code = code # type: ignore[attr-defined]
|
||||
|
||||
@@ -82,6 +82,7 @@ from unshackle.core.remote_protocol import (
|
||||
TrackKeys,
|
||||
TracksReply,
|
||||
TracksRequest,
|
||||
cap_note,
|
||||
coded,
|
||||
)
|
||||
from unshackle.core.search_result import SearchResult
|
||||
@@ -1230,7 +1231,7 @@ class RemoteService(TitleSource):
|
||||
self._server_cdm = server_cdm
|
||||
if max_height is None:
|
||||
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:
|
||||
message += "; licensing with your own device"
|
||||
elif self.local_cdm is not None:
|
||||
@@ -1623,7 +1624,7 @@ class RemoteService(TitleSource):
|
||||
)
|
||||
cap = refusal.get("max_height")
|
||||
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):
|
||||
why = "The server vault holds no content key for this track"
|
||||
else:
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
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:
|
||||
"""Whether a track has this height, this height from a 16:9 width, or this standard resolution (a padded encode)."""
|
||||
return (
|
||||
video.height == res
|
||||
or bool(video.width and int(video.width * 9 / 16) == res)
|
||||
or standard_resolution(video.width, video.height) == res
|
||||
)
|
||||
"""Whether ``-q res`` selects a track; a padded encode matches by its standard resolution."""
|
||||
return video.height == res or res in quality_heights(video)
|
||||
|
||||
|
||||
def video_rank(video: Video) -> tuple[int, bool, float, int]:
|
||||
|
||||
Reference in New Issue
Block a user