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