refactor(api): give every served service its dl options from the run plan

This commit is contained in:
imSp4rky
2026-11-28 14:02:44 -07:00
parent 63dd037ebd
commit 053d83874d
18 changed files with 285 additions and 205 deletions
+51 -63
View File
@@ -45,13 +45,10 @@ from unshackle.core.cdm.choice import choose_cdm, drm_system
from unshackle.core.cdm.detect import cdm_system, cdm_type_stub
from unshackle.core.cdm.loader import device_system
from unshackle.core.config import config
from unshackle.core.dl_options import (
DEFAULT_DOWNLOAD_PARAMS,
forwarded_dl_params,
)
from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS
from unshackle.core.drm import WHOLE_FILE_DRM, cbcs, is_null_key, real_kids, whole_file_cipher
from unshackle.core.drm.discovery import drm_from_init_segment, ensure_track_drm, fetch_init_segment, track_pssh
from unshackle.core.launch import served_context
from unshackle.core.launch import LaunchKeys, served_context
from unshackle.core.manifests.snapshot import capture
from unshackle.core.proxies.resolve import REGION_QUERY, initialize_proxy_providers, is_loopback, resolve_proxy
from unshackle.core.remote_protocol import (
@@ -75,6 +72,7 @@ from unshackle.core.remote_protocol import (
TracksReply,
TracksRequest,
)
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
@@ -90,7 +88,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, VIDEO_CODEC_LIST, ContextData
from unshackle.core.utils.click_types import QUALITY_LIST, 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
@@ -160,6 +158,25 @@ def load_full_cdm(service: str, profile: str | None, cdm_type: str | None = None
return resolve_server_cdm(service, profile, cdm_type, app_config)
def served_parent(
obj: ContextData,
data: dict[str, Any],
keys: LaunchKeys,
proxy: str | None,
profile: str | None = None,
flat: AbstractSet[str] = frozenset(),
) -> click.Context:
"""The parent context of a served service, with the dl options of :func:`served_plan` for the request ``data``.
A dl option value that the plan refuses is a ``400 INVALID_PARAMETERS``.
"""
try:
plan = served_plan(data, proxy, profile, flat)
except PlanError as e:
raise APIError(APIErrorCode.INVALID_PARAMETERS, e.message) from None
return served_context(obj, plan, keys)
def cast_or_refuse(params: Iterable[click.Parameter], ctx: Any, options: dict[str, Any]) -> dict[str, Any]:
"""``cast_service_options``, with a refused value as ``400 INVALID_PARAMETERS``."""
try:
@@ -467,10 +484,12 @@ def relay_service(
# the same server_proxy gate a local service gets: without it the providers stay empty
proxy_param, providers = resolve_handler_proxy(data, data["service"], request)
parent_ctx = served_context(
parent_ctx = served_parent(
ContextData(config={}, cdm=None, proxy_providers=providers, profile=profile),
{"proxy": proxy_param, "no_proxy": data.get("no_proxy", False), "profile": profile},
data,
{"client_argv": relay_label(data)},
proxy_param,
profile,
)
ctx = click.Context(click.Command(data["service"]), parent=parent_ctx, obj=parent_ctx.obj)
# this process is long-lived and serves local services too, so the remote's overrides stay out of config
@@ -582,10 +601,17 @@ _remote_sweeper: Optional["asyncio.Task[None]"] = None
def remote_pool_key(
data: dict[str, Any], server: str, info: dict, profile: str | None, title_id: str, request: web.Request | None
) -> tuple:
"""What opens a remote session for one API key; requests that differ only in episode selection share one."""
"""What opens a remote session for one API key; requests that differ only in episode selection share one.
The dl selection is part of it, because the relay sends it on to the remote session create.
"""
from unshackle.core.remote_service import remote_service_params
options = json.dumps(remote_service_params(info, data), sort_keys=True, default=str)
options = json.dumps(
[remote_service_params(info, data), data.get("dl_params"), *(data.get(k) for k in SESSION_DL_KEYS)],
sort_keys=True,
default=str,
)
return (
caller_key(request),
server,
@@ -758,7 +784,6 @@ def setup_list_service(
policy = request_policy(request)
service_config = policy.service_yaml(normalized_service)
no_proxy = data.get("no_proxy", False)
proxy_param, proxy_providers = resolve_handler_proxy(data, normalized_service, request)
account = resolve_server_account(policy, normalized_service, data.get("client_region"))
@@ -770,10 +795,11 @@ def setup_list_service(
cdm = load_full_cdm(normalized_service, profile, cdm_type, policy.cdm_config())
cookies, credential = server_login_material(data, normalized_service, account, profile)
parent_ctx = served_context(
parent_ctx = served_parent(
ContextData(config=service_config, cdm=cdm, proxy_providers=proxy_providers, profile=profile),
{"proxy": proxy_param, "no_proxy": no_proxy, **forwarded_dl_params(data)},
data,
{"cookies_supplied": cookies is not None},
proxy_param,
)
service_instance = instantiate_service(parent_ctx, service_module, title_id, data, LIST_HANDLER_TRANSPORT_KEYS)
@@ -805,7 +831,6 @@ def run_service_search(
"""
profile = client_profile(data)
no_proxy = data.get("no_proxy", False)
api_key = caller_key(request)
policy = request_policy(request)
@@ -823,10 +848,11 @@ def run_service_search(
(None, None) if anonymous else server_login_material(data, normalized_service, account, profile)
)
parent_ctx = served_context(
parent_ctx = served_parent(
ContextData(config=service_config, cdm=cdm, proxy_providers=proxy_providers, profile=profile),
{"proxy": proxy_param, "no_proxy": no_proxy},
data,
{"cookies_supplied": cookies is not None},
proxy_param,
)
from click import ClickException
@@ -927,9 +953,9 @@ def requested_heights(quality: Any) -> list[int]:
try:
heights = QUALITY_LIST.convert(quality or [])
except click.BadParameter as e:
raise APIError(APIErrorCode.INVALID_INPUT, f"quality: {e.message}") from e
raise APIError(APIErrorCode.INVALID_PARAMETERS, f"quality: {e.message}") from e
if any(height <= 0 for height in heights):
raise APIError(APIErrorCode.INVALID_INPUT, f"quality: every height must be above 0, not {quality!r}")
raise APIError(APIErrorCode.INVALID_PARAMETERS, f"quality: every height must be above 0, not {quality!r}")
return heights
@@ -1586,20 +1612,6 @@ async def list_tracks_handler(data: dict[str, Any], request: web.Request | None
await request_cache.cleanup()
def resolve_vcodec(value: Any) -> list | None:
"""Map a client's vcodec field to codec enums.
Session routes do not run the download job admission, so this must answer junk with a 400
instead of letting click's UsageError surface as a 500.
"""
if not value:
return None
try:
return VIDEO_CODEC_LIST.convert(value) or None
except click.UsageError as e:
raise APIError(APIErrorCode.INVALID_INPUT, f"Invalid vcodec: {e.format_message()}") from e
def wanted_refusal(wanted: Any) -> str | None:
"""Why dl could not parse ``wanted``, or None when it can."""
try:
@@ -2793,8 +2805,6 @@ def create_service_instance(
client that sends nothing authenticates with nothing, because the server never lends its
own accounts.
"""
from unshackle.core.tracks import Video
policy = policy or KeyPolicy.of(None)
server_config = service_config = policy.service_yaml(normalized_service)
service_module = Services.load(normalized_service)
@@ -2822,21 +2832,6 @@ def create_service_instance(
)
cdm = load_full_cdm(normalized_service, profile, data.get("cdm_type") if follows_client else None, key_config)
# Reconstruct enum track-selection params from client data so service code that reads
# ctx.parent.params (Service.__init__ proxy/range/vcodec/best_available block) sees enums.
range_names = data.get("range_")
range_values: list | None = None
if range_names:
range_values = []
for name in range_names:
try:
range_values.append(Video.Range[name])
except KeyError:
pass
range_values = range_values or None
vcodec_values = resolve_vcodec(data.get("vcodec"))
if server_account:
cookies = server_account_cookies(normalized_service, profile)
credential = login.get_credentials(normalized_service, profile)
@@ -2844,24 +2839,17 @@ def create_service_instance(
credential = client_credential(data)
cookies = load_client_cookies(data.get("cookies"))
parent_ctx = served_context(
parent_ctx = served_parent(
ContextData(config=service_config, cdm=cdm, proxy_providers=proxy_providers, profile=profile),
{
"proxy": proxy_param,
"no_proxy": data.get("no_proxy", False),
"range_": range_values,
"vcodec": vcodec_values,
"quality": requested_heights(data.get("quality")),
"best_available": data.get("best_available", False),
"generate_dv": data.get("generate_dv", False),
**forwarded_dl_params(data),
# Services key their token caches on this. Only sessions get it: they run on a cache
# directory of their own, where the list and search handlers share the server's cache.
"profile": profile,
},
data,
# A service with CLIENT_CONFIG reads client_device and client_identity: with client_identity it uses
# only what the client sent, and without it the server's identity, whose keys then come only from a vault.
{"cookies_supplied": cookies is not None, "client_device": client_device, "client_identity": client_identity},
proxy_param,
# Services key their token caches on this. The list and search handlers leave it out: they
# share the server's cache, where a session runs on a cache directory of its own.
profile,
SESSION_TRANSPORT_KEYS,
)
service_instance = instantiate_service(parent_ctx, service_module, title_id, data, SESSION_TRANSPORT_KEYS)
+5 -2
View File
@@ -639,6 +639,9 @@ async def search(request: web.Request) -> web.Response:
no_proxy:
type: boolean
description: Force disable all proxy use (default - false)
dl_params:
type: object
description: The dl track selection, in the same form as on `/api/session/create`.
credentials:
type: object
additionalProperties: true
@@ -2000,8 +2003,8 @@ async def session_create(request: web.Request) -> web.Response:
type: object
description: |
The dl track selection. The service reads it from ctx.parent.params, never as
service options. An absent or malformed value gets the dl default, and the
server drops an unknown codec name.
service options. An absent value gets the dl default; a malformed value or an
unknown codec name is refused with INVALID_PARAMETERS.
properties:
lang:
type: array
-48
View File
@@ -1,17 +1,13 @@
"""The dl option table: which dl options the REST API takes, their API defaults, and what a remote client forwards."""
import logging
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any, Literal, get_args
import click
from unshackle.core.utils.click_types import AUDIO_CODEC_LIST
from unshackle.core.utils.service_params import cast_service_options
log = logging.getLogger("api")
# Config keys accepted as natural names for params whose Python name dodges a builtin.
DL_OPTION_ALIASES = {"range": "range_", "list": "list_"}
DL_OPTION_API_NAMES = {click_name: api_name for api_name, click_name in DL_OPTION_ALIASES.items()}
@@ -174,47 +170,3 @@ def remote_dl_params(params: Mapping[str, Any]) -> dict[str, Any]:
elif params.get(key) is not None:
sent[key] = [c.name if option.remote == "audio_codecs" else str(c) for c in params[key]]
return sent
def forwarded_dl_params(data: dict[str, Any]) -> dict[str, Any]:
"""Read the dl track selection that a remote-dl client sends under ``dl_params``.
Services read these values from ``ctx.parent.params`` to pick the manifests they
fetch. They travel in their own object so that they never collide with a service option that
has the same name. An absent or malformed value gets the dl default, so an old client that
sends no ``dl_params`` gets the same result as a ``dl`` run with no selection flags.
``acodec`` holds codec names or aliases, which become ``Audio.Codec`` members the same way
``dl -a`` converts them; an unknown name is dropped.
"""
raw = data.get("dl_params")
if not isinstance(raw, dict):
raw = {}
def str_list(key: str) -> list[str] | None:
value = raw.get(key)
if isinstance(value, list) and all(isinstance(v, str) for v in value):
return list(value)
if value is not None:
log.warning(f"Ignoring dl_params.{key}: it must be an array of strings")
return None
params: dict[str, Any] = {}
for key, option in FORWARDED_DL_PARAMS:
if option.remote == "flag":
params[key] = raw.get(key) is True
elif option.remote == "langs":
names = str_list(key)
params[key] = names if names is not None else list(option.default)
else:
names = str_list(key)
# the dl CLI default is [], and some services test membership in it
params[key] = list(option.default)
for name in names or []:
try:
params[key].extend(AUDIO_CODEC_LIST.convert(name))
except click.BadParameter:
# imported here: unshackle.core.api imports this module
from unshackle.core.api.sanitize import sanitize_log
log.warning(f"Ignoring unknown dl_params.{key} value: {sanitize_log(name)}")
return params
+7 -6
View File
@@ -2,7 +2,7 @@
import copy
from pathlib import Path
from typing import Any, TypedDict, cast
from typing import TYPE_CHECKING, TypedDict, cast
import click
@@ -10,6 +10,9 @@ from unshackle.core.config import config, load_yaml
from unshackle.core.utils.click_types import ContextData
from unshackle.core.utils.collections import ci_get, merge_dict
if TYPE_CHECKING:
from unshackle.core.run_plan import RunPlan
class LaunchKeys(TypedDict, total=False):
"""The ``ctx.parent.params`` keys that exist only for the launch. ``dl_options.DL_OPTIONS`` holds the dl options.
@@ -39,11 +42,9 @@ def launch(ctx: click.Context, keys: LaunchKeys, obj: ContextData | None = None)
ctx.obj = obj
def served_context(obj: ContextData, params: dict[str, Any], keys: LaunchKeys) -> click.Context:
"""A new parent context for a service that a serve runs for an API client, with the dl options in ``params``."""
ctx = click.Context(click.Command("serve"))
# dl defaults -q to [], and services iterate it
ctx.params = {**params, "quality": params.get("quality") or []}
def served_context(obj: ContextData, plan: "RunPlan", keys: LaunchKeys) -> click.Context:
"""A new parent context for a service that a serve runs for an API client, with the dl options of ``plan``."""
ctx = plan.context(click.Command("serve"))
launch(ctx, {**keys, "served": True}, obj)
return ctx
+45 -9
View File
@@ -1,4 +1,4 @@
"""The dl front door: one checked run plan from a dl click parse or a REST API job, and what the run gave back."""
"""The dl front door: one run plan from a dl click parse, a REST API job or a served service, and what the run gave back."""
from collections.abc import Collection, Mapping
from dataclasses import dataclass, field
@@ -9,7 +9,7 @@ import click
from click.core import ParameterSource
from unshackle.core import providers
from unshackle.core.dl_options import DL_OPTION_API_NAMES, cast_dl_params
from unshackle.core.dl_options import DL_OPTION_API_NAMES, FORWARDED_DL_PARAMS, cast_dl_params
from unshackle.core.downloaders import parse_speed_limit
from unshackle.core.providers.anilist import parse_anilist_ref
from unshackle.core.providers.tvdb import SEASON_TYPES
@@ -18,6 +18,7 @@ from unshackle.core.utilities import inherited_exclusions, kind_only_conflict, p
ID_PROVIDER_KEYS = {"tmdb": "tmdb_api_key", "tvdb": "tvdb_api_key", "omdb": "omdb_api_key"}
PLAN_API_NAMES = {**DL_OPTION_API_NAMES, "cdm_name": "cdm", "server": "remote"}
SESSION_DL_KEYS = ("range_", "vcodec", "quality", "best_available", "generate_dv")
class PlanError(click.ClickException):
@@ -50,7 +51,7 @@ class RunPlan:
params: dict[str, Any]
sources: dict[str, ParameterSource]
def context(self, cli: click.Command, service: str) -> click.Context:
def context(self, cli: click.Command, service: str | None = None) -> click.Context:
"""A dl context for this plan, so dl and a service read the values and sources as on the CLI."""
ctx = click.Context(cli)
ctx.invoked_subcommand = service
@@ -175,11 +176,10 @@ def check_options(params: Mapping[str, Any]) -> None:
raise PlanError("Unable to run hybrid mode: dovi_tool not found")
def api_plan(params: Mapping[str, Any], client_keys: Collection[str] | None = None) -> RunPlan:
"""The checked run plan of a REST API job from its parameters, by API name.
def cast_plan(params: Mapping[str, Any], sent: Collection[str]) -> RunPlan:
"""The run plan of ``params`` by API name, cast by the dl click types but not checked by :func:`check_options`.
A value counts as typed on the command line when its API name is in ``client_keys`` (every parameter when None),
so a service's ``dl`` config replaces only the values the client did not send.
A value counts as typed on the command line when its API name is in ``sent``.
"""
from unshackle.commands.dl import dl
@@ -188,10 +188,46 @@ def api_plan(params: Mapping[str, Any], client_keys: Collection[str] | None = No
except click.BadParameter as e:
raise PlanError(e.message) from None
cast.update(cdm_name=params.get("cdm"), remote=bool(params.get("remote")), server=params.get("remote"))
check_options(cast)
sent = params.keys() if client_keys is None else client_keys
sources = {
name: ParameterSource.COMMANDLINE if PLAN_API_NAMES.get(name, name) in sent else ParameterSource.DEFAULT
for name in cast
}
return RunPlan(cast, sources)
def api_plan(params: Mapping[str, Any], client_keys: Collection[str] | None = None) -> RunPlan:
"""The checked run plan of a REST API job from its parameters, by API name.
A value counts as typed on the command line when its API name is in ``client_keys`` (every parameter when None),
so a service's ``dl`` config replaces only the values the client did not send.
"""
plan = cast_plan(params, params.keys() if client_keys is None else client_keys)
check_options(plan.params)
return plan
def served_plan(
data: Mapping[str, Any], proxy: str | None = None, profile: str | None = None, flat: Collection[str] = ()
) -> RunPlan:
"""The run plan of a served service from a request in the remote session wire form, with the server's ``proxy``.
A flat ``SESSION_DL_KEYS`` key counts as :func:`service_options` reads it: with ``service_params``, or when in
``flat``. ``no_proxy`` counts by truth value, as the server's proxy gate reads it. :func:`check_options` does not
run, because dl runs on the client.
"""
forwarded = raw if isinstance(raw := data.get("dl_params"), dict) else {}
params = {key: forwarded[key] for key, _ in FORWARDED_DL_PARAMS if key in forwarded}
nested = isinstance(data.get("service_params"), dict)
params.update(
{DL_OPTION_API_NAMES.get(k, k): data[k] for k in SESSION_DL_KEYS if k in data and (nested or k in flat)}
)
if "no_proxy" in data:
params["no_proxy"] = bool(data["no_proxy"])
if proxy is not None:
params["proxy"] = proxy
if profile is not None:
params["profile"] = profile
plan = cast_plan(params, params.keys())
if any(height <= 0 for height in plan.params["quality"]):
raise PlanError(f"Invalid quality: every height must be above 0, not {data['quality']!r}")
return plan
+2
View File
@@ -342,6 +342,8 @@ class LanguageRange(click.ParamType):
self, value: str | list, param: click.Parameter | None = None, ctx: click.Context | None = None
) -> list[str]:
if isinstance(value, list):
if not all(isinstance(v, str) for v in value):
self.fail(f"{value!r} is not a list of language strings", param, ctx)
return value
if not value:
return []