refactor(core): write a service's launch keys through one module

This commit is contained in:
imSp4rky
2026-11-24 19:28:12 -07:00
parent 43987f9809
commit e30db081c8
14 changed files with 277 additions and 139 deletions
+1 -1
View File
@@ -116,7 +116,7 @@ up the objects your methods rely on:
| `self.track_request` | A `TrackRequest` describing the requested codecs, ranges, and best-available flag (see below). | | `self.track_request` | A `TrackRequest` describing the requested codecs, ranges, and best-available flag (see below). |
The constructor also resolves proxies: it reads `--proxy` and the `proxy_query` and The constructor also resolves proxies: it reads `--proxy` and the `proxy_query` and
`proxy_provider` context params that `dl` derives from it, consults the per-service `proxy_provider` context params that `dl` and `search` derive from it, consults the per-service
`proxy_map`, and, if `GEOFENCE` is set and you did not give an explicit proxy, does a live `proxy_map`, and, if `GEOFENCE` is set and you did not give an explicit proxy, does a live
IP check and auto-fetches a proxy to `GEOFENCE[0]` when it detects a geoblock. A IP check and auto-fetches a proxy to `GEOFENCE[0]` when it detects a geoblock. A
`GEOBLOCK` hit with no `GEOFENCE` stops the run with a "not available in your region" `GEOBLOCK` hit with no `GEOFENCE` stops the run with a "not available in your region"
+1
View File
@@ -10,6 +10,7 @@ Per-service configuration, keyed by the canonical service tag (for example `EXAM
- **`proxy_map`**: remaps the region query you passed to `-p/--proxy` for this service. - **`proxy_map`**: remaps the region query you passed to `-p/--proxy` for this service.
A config key is that query, or `"provider:query"` when the flag also named a proxy provider. The value is A config key is that query, or `"provider:query"` when the flag also named a proxy provider. The value is
the query asked of the proxy provider instead. It has no effect when you give `-p` a full proxy URL. the query asked of the proxy provider instead. It has no effect when you give `-p` a full proxy URL.
`dl`, `search` and a REST API download job apply it. The other REST API routes and a `--remote` remote session do not.
- **`title_map`**: an exact-match rename map applied to fetched titles (source name → - **`title_map`**: an exact-match rename map applied to fetched titles (source name →
desired name), so a service that names a title differently from your library still matches. desired name), so a service that names a title differently from your library still matches.
- **`dl`**: per-service download defaults, using the same keys as the global - **`dl`**: per-service download defaults, using the same keys as the global
+146
View File
@@ -0,0 +1,146 @@
"""Each builder of a service's launch context, and the launch keys it sets in ``ctx.parent.params``."""
from __future__ import annotations
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Callable
import click
import pytest
from unshackle.core.launch import LaunchKeys
pytestmark = pytest.mark.unit
class Stop(Exception):
pass
class ExampleProxy:
def get_proxy(self, query: str) -> str:
return f"http://{query}.proxy.example:8080"
def cli_dl(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> click.Context:
from unshackle.commands import dl as dl_module
monkeypatch.setattr(dl_module.config, "key_vaults", [])
monkeypatch.setattr(dl_module.dl, "get_cdm", lambda self, *a, **k: None)
monkeypatch.setattr(dl_module.Services, "get_path", staticmethod(lambda tag: tmp_path))
# dl.__init__ hangs its result callback on the shared click command
monkeypatch.setattr(dl_module.dl.cli, "_result_callback", dl_module.dl.cli._result_callback)
ctx = click.Context(dl_module.dl.cli)
ctx.invoked_subcommand = "EXAMPLE"
dl_module.dl(ctx=ctx, no_proxy=False, proxy="us", proxy_providers=[ExampleProxy()])
return ctx
def cli_search(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> click.Context:
from unshackle.commands import search as search_module
monkeypatch.setattr(search_module, "load_proxy_providers", lambda: [ExampleProxy()])
monkeypatch.setattr(search_module.Services, "get_path", staticmethod(lambda tag: tmp_path))
ctx = click.Context(search_module.search)
ctx.invoked_subcommand = "EXAMPLE"
ctx.params = {"proxy": "us", "no_proxy": False}
with ctx:
assert search_module.search.callback
search_module.search.callback(no_proxy=False, proxy="us")
return ctx
def rest_handlers(monkeypatch: pytest.MonkeyPatch) -> tuple[Any, dict]:
"""The handlers module with the service, its config, CDM and proxy stubbed, and the context it builds."""
from unshackle.core.api import handlers
seen: dict = {}
def instantiate(parent_ctx: click.Context, *a: Any) -> Any:
seen["ctx"] = parent_ctx
return SimpleNamespace(authenticate=lambda cookies, credential: None)
monkeypatch.setattr(handlers, "load_service_yaml", lambda tag: {})
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *a: (None, []))
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
monkeypatch.setattr(handlers.Services, "load", lambda tag: SimpleNamespace())
monkeypatch.setattr(handlers, "instantiate_service", instantiate)
return handlers, seen
def rest_relay(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> click.Context:
from unshackle.core import remote_service
handlers, _ = rest_handlers(monkeypatch)
monkeypatch.setattr(remote_service, "make_remote_service", lambda ctx, *a, **k: ctx)
return handlers.relay_service({"service": "EXAMPLE"}, "server", None, "t").parent
def rest_list(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> click.Context:
handlers, seen = rest_handlers(monkeypatch)
handlers.setup_list_service({}, "EXAMPLE", None, "t")
return seen["ctx"]
def rest_search(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> click.Context:
handlers, seen = rest_handlers(monkeypatch)
from unshackle.core.api.errors import APIError
def instantiate(parent_ctx: click.Context, *a: Any) -> Any:
seen["ctx"] = parent_ctx
raise Stop
monkeypatch.setattr(handlers, "instantiate_service", instantiate)
with pytest.raises(APIError):
handlers.run_service_search({}, "EXAMPLE", "query")
return seen["ctx"]
def rest_session(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> click.Context:
handlers, seen = rest_handlers(monkeypatch)
handlers.create_service_instance("EXAMPLE", "t", {}, None, [], None)
return seen["ctx"]
def rest_job(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> click.Context:
from unshackle.commands import dl as dl_module
from unshackle.core.api import download_manager
class FakeDl:
cli = dl_module.dl.cli
def __init__(self, ctx: click.Context, **kwargs: Any) -> None:
raise Stop(ctx)
monkeypatch.setattr(dl_module, "dl", FakeDl)
with pytest.raises(Stop) as stopped:
download_manager.perform_download("job-1", "EXAMPLE", "t1", {})
return stopped.value.args[0]
SERVED_LOGIN: LaunchKeys = {"served": True, "cookies_supplied": False}
@pytest.mark.parametrize(
("build", "expected"),
[
(cli_dl, {"proxy_arg": "us", "proxy_query": "us", "proxy_provider": None}),
(cli_search, {"proxy_arg": "us", "proxy_query": "us", "proxy_provider": None}),
(rest_relay, {"served": True, "client_argv": "serve (REST API)"}),
(rest_list, SERVED_LOGIN),
(rest_search, SERVED_LOGIN),
(rest_session, {**SERVED_LOGIN, "client_device": False, "client_identity": False}),
(rest_job, {"client_argv": "serve (REST API) download job job-1"}),
],
ids=lambda v: v.__name__ if callable(v) else "",
)
@pytest.mark.usefixtures("example_service")
def test_each_builder_sets_its_launch_keys(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
build: Callable[[pytest.MonkeyPatch, Path], click.Context],
expected: LaunchKeys,
) -> None:
params = build(monkeypatch, tmp_path).params
assert {key: params[key] for key in LaunchKeys.__annotations__ if key in params} == expected
+8 -6
View File
@@ -19,7 +19,9 @@ from unshackle.core.api import handlers
from unshackle.core.api.errors import APIError from unshackle.core.api.errors import APIError
from unshackle.core.api.input_bridge import InputBridge from unshackle.core.api.input_bridge import InputBridge
from unshackle.core.cdm.client_relay import ClientDeviceCdm, answer_cdm_call from unshackle.core.cdm.client_relay import ClientDeviceCdm, answer_cdm_call
from unshackle.core.launch import served_context
from unshackle.core.remote_protocol import APIErrorCode, AuthStatus from unshackle.core.remote_protocol import APIErrorCode, AuthStatus
from unshackle.core.utils.click_types import ContextData
pytestmark = pytest.mark.unit pytestmark = pytest.mark.unit
@@ -171,8 +173,8 @@ def test_a_relaying_client_gets_a_stand_in_with_its_device_facts(monkeypatch: py
monkeypatch.setattr(handlers, "load_service_yaml", lambda tag: {"esn": "SERVER"}) monkeypatch.setattr(handlers, "load_service_yaml", lambda tag: {"esn": "SERVER"})
monkeypatch.setattr( monkeypatch.setattr(
handlers, handlers,
"build_parent_ctx", "served_context",
lambda profile, cdm, *a, **k: built.update(cdm=cdm, config=a[3], params=k["extra_params"]), lambda obj, params, keys: built.update(cdm=obj.cdm, config=obj.config, params={**params, **keys}),
) )
monkeypatch.setattr(handlers.Services, "load", lambda tag: Declares) monkeypatch.setattr(handlers.Services, "load", lambda tag: Declares)
monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: "service") monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: "service")
@@ -332,7 +334,7 @@ def test_a_lent_device_gives_the_service_the_server_config_back(monkeypatch: pyt
handlers, "load_service_yaml", lambda tag: {"esn": "SERVER", "esn_map": {7000: "s"}, "other": 1} handlers, "load_service_yaml", lambda tag: {"esn": "SERVER", "esn_map": {7000: "s"}, "other": 1}
) )
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: server_device) monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: server_device)
monkeypatch.setattr(handlers, "build_parent_ctx", lambda profile, cdm, *a, **k: built.update(cdm=cdm, config=a[3])) monkeypatch.setattr(handlers, "served_context", lambda obj, *a: built.update(cdm=obj.cdm, config=obj.config))
monkeypatch.setattr(handlers.Services, "load", lambda tag: Declares) monkeypatch.setattr(handlers.Services, "load", lambda tag: Declares)
monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: "service") monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: "service")
@@ -423,9 +425,9 @@ def test_a_lent_device_without_the_vault_grant_asks_the_server_for_no_key() -> N
svc.proxy_license(b"challenge", track, "widevine") svc.proxy_license(b"challenge", track, "widevine")
@pytest.mark.parametrize("extra", [None, {"quality": None}]) @pytest.mark.parametrize("params", [{}, {"quality": None}])
def test_every_service_context_defaults_quality_to_a_list(extra: Any) -> None: def test_every_service_context_defaults_quality_to_a_list(params: Any) -> None:
parent = handlers.build_parent_ctx(None, None, None, False, [], {}, extra_params=extra) parent = served_context(ContextData(config={}, cdm=None, proxy_providers=[]), params, {})
assert parent.params["quality"] == [] assert parent.params["quality"] == []
@@ -184,7 +184,6 @@ def test_setup_list_service_threads_request(monkeypatch):
monkeypatch.setattr(handlers, "load_service_yaml", lambda service: {}) monkeypatch.setattr(handlers, "load_service_yaml", lambda service: {})
monkeypatch.setattr(handlers, "resolve_handler_proxy", fake_resolve) monkeypatch.setattr(handlers, "resolve_handler_proxy", fake_resolve)
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None) monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
monkeypatch.setattr(handlers, "build_parent_ctx", lambda *args, **kwargs: None)
monkeypatch.setattr(handlers.Services, "load", lambda service: None) monkeypatch.setattr(handlers.Services, "load", lambda service: None)
monkeypatch.setattr(handlers, "instantiate_service", lambda *args: FakeService()) monkeypatch.setattr(handlers, "instantiate_service", lambda *args: FakeService())
monkeypatch.setattr("unshackle.commands.dl.dl.get_cookie_jar", staticmethod(lambda service, profile: None)) monkeypatch.setattr("unshackle.commands.dl.dl.get_cookie_jar", staticmethod(lambda service, profile: None))
@@ -203,7 +202,6 @@ def test_search_reports_failed_proxy_check_as_invalid_proxy(monkeypatch):
monkeypatch.setattr(handlers, "load_service_yaml", lambda service: {}) monkeypatch.setattr(handlers, "load_service_yaml", lambda service: {})
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: ("http://127.0.0.1:9", [])) monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: ("http://127.0.0.1:9", []))
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None) monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
monkeypatch.setattr(handlers, "build_parent_ctx", lambda *args, **kwargs: None)
monkeypatch.setattr(handlers.Services, "load", lambda service: None) monkeypatch.setattr(handlers.Services, "load", lambda service: None)
monkeypatch.setattr(handlers, "instantiate_service", failed_check) monkeypatch.setattr(handlers, "instantiate_service", failed_check)
monkeypatch.setattr("unshackle.commands.dl.dl.get_cookie_jar", staticmethod(lambda service, profile: None)) monkeypatch.setattr("unshackle.commands.dl.dl.get_cookie_jar", staticmethod(lambda service, profile: None))
@@ -480,7 +480,7 @@ def test_a_client_device_session_builds_the_service_on_a_stub_of_that_device(mon
monkeypatch.setattr(handlers, "load_service_yaml", lambda tag: {}) monkeypatch.setattr(handlers, "load_service_yaml", lambda tag: {})
monkeypatch.setattr(handlers, "load_full_cdm", no_server_device) monkeypatch.setattr(handlers, "load_full_cdm", no_server_device)
monkeypatch.setattr(handlers, "build_parent_ctx", lambda profile, cdm, *a, **k: built.update(cdm=cdm)) monkeypatch.setattr(handlers, "served_context", lambda obj, *a: built.update(cdm=obj.cdm))
monkeypatch.setattr(handlers.Services, "load", lambda tag: object) monkeypatch.setattr(handlers.Services, "load", lambda tag: object)
monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: "service") monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: "service")
@@ -241,7 +241,6 @@ def test_the_server_device_follows_the_client_only_when_both_systems_are_mapped(
monkeypatch.setattr( monkeypatch.setattr(
handlers, "load_full_cdm", lambda service, profile, cdm_type, app_config=None: asked.append(cdm_type) handlers, "load_full_cdm", lambda service, profile, cdm_type, app_config=None: asked.append(cdm_type)
) )
monkeypatch.setattr(handlers, "build_parent_ctx", lambda *a, **k: None)
monkeypatch.setattr(handlers.Services, "load", lambda tag: object) monkeypatch.setattr(handlers.Services, "load", lambda tag: object)
monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: "service") monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: "service")
+18 -12
View File
@@ -68,6 +68,7 @@ from unshackle.core.drm import (
from unshackle.core.drm.key_resolution import ContentKeyResolver from unshackle.core.drm.key_resolution import ContentKeyResolver
from unshackle.core.events import events from unshackle.core.events import events
from unshackle.core.export_name import ExportNamer, move_export, plural, season_episodes, title_label from unshackle.core.export_name import ExportNamer, move_export, plural, season_episodes, title_label
from unshackle.core.launch import LaunchKeys, launch
from unshackle.core.manifests.snapshot import capture from unshackle.core.manifests.snapshot import capture
from unshackle.core.providers.anilist import parse_anilist_ref from unshackle.core.providers.anilist import parse_anilist_ref
from unshackle.core.providers.tvdb import SEASON_TYPES, parse_int from unshackle.core.providers.tvdb import SEASON_TYPES, parse_int
@@ -1596,6 +1597,7 @@ class dl:
) )
self.proxy_providers = [] self.proxy_providers = []
keys: LaunchKeys = {}
if no_proxy: if no_proxy:
ctx.params["proxy"] = None ctx.params["proxy"] = None
else: else:
@@ -1607,7 +1609,7 @@ class dl:
with console.status("Loading Proxy Providers...", spinner="dots"): with console.status("Loading Proxy Providers...", spinner="dots"):
self.proxy_providers = load_proxy_providers() self.proxy_providers = load_proxy_providers()
ctx.params["proxy_arg"] = proxy keys["proxy_arg"] = proxy
if proxy and proxy.startswith("controld://"): if proxy and proxy.startswith("controld://"):
proxy = ctx.params["proxy"] = resolve_proxy(proxy, []) proxy = ctx.params["proxy"] = resolve_proxy(proxy, [])
if proxy: if proxy:
@@ -1635,20 +1637,24 @@ class dl:
sys.exit(1) sys.exit(1)
ctx.params["proxy"] = proxy_uri ctx.params["proxy"] = proxy_uri
self.log.info(describe_proxy(proxy_provider, proxy_uri, proxy_query)) self.log.info(describe_proxy(proxy_provider, proxy_uri, proxy_query))
ctx.params["proxy_query"] = proxy_query keys["proxy_query"] = proxy_query
ctx.params["proxy_provider"] = requested_provider keys["proxy_provider"] = requested_provider
else: else:
self.log.info(describe_explicit_proxy(ctx.params["proxy"])) self.log.info(describe_explicit_proxy(ctx.params["proxy"]))
ctx.params["proxy_query"] = None keys["proxy_query"] = None
ctx.params["proxy_provider"] = None keys["proxy_provider"] = None
ctx.obj = ContextData( launch(
config=self.service_config, ctx,
cdm=self.cdm, keys,
proxy_providers=self.proxy_providers, ContextData(
profile=self.profile, config=self.service_config,
cdm_entry=self.cdm_from_service_entry(), cdm=self.cdm,
cdm_for=self.cdm_for, proxy_providers=self.proxy_providers,
profile=self.profile,
cdm_entry=self.cdm_from_service_entry(),
cdm_for=self.cdm_for,
),
) )
if repack: if repack:
+6 -2
View File
@@ -14,6 +14,7 @@ from unshackle.commands.dl import dl
from unshackle.core.config import config, load_yaml from unshackle.core.config import config, load_yaml
from unshackle.core.console import console from unshackle.core.console import console
from unshackle.core.constants import context_settings from unshackle.core.constants import context_settings
from unshackle.core.launch import LaunchKeys, launch
from unshackle.core.proxies.proxy import Proxy from unshackle.core.proxies.proxy import Proxy
from unshackle.core.proxies.resolve import ( from unshackle.core.proxies.resolve import (
REGION, REGION,
@@ -99,13 +100,14 @@ def search(
proxy, no_proxy = ctx.params.get("proxy"), bool(ctx.params.get("no_proxy")) proxy, no_proxy = ctx.params.get("proxy"), bool(ctx.params.get("no_proxy"))
proxy_providers: list[Proxy] = [] proxy_providers: list[Proxy] = []
keys: LaunchKeys = {}
if no_proxy: if no_proxy:
ctx.params["proxy"] = None ctx.params["proxy"] = None
else: else:
with console.status("Loading Proxy Providers...", spinner="dots"): with console.status("Loading Proxy Providers...", spinner="dots"):
proxy_providers = load_proxy_providers() proxy_providers = load_proxy_providers()
ctx.params["proxy_arg"] = proxy keys["proxy_arg"] = proxy
if proxy: if proxy:
try: try:
requested_provider, query = split_proxy_query(proxy, proxy_providers) requested_provider, query = split_proxy_query(proxy, proxy_providers)
@@ -122,10 +124,12 @@ def search(
sys.exit(1) sys.exit(1)
ctx.params["proxy"] = proxy_uri ctx.params["proxy"] = proxy_uri
log.info(describe_proxy(proxy_provider, proxy_uri, query)) log.info(describe_proxy(proxy_provider, proxy_uri, query))
keys["proxy_query"] = query
keys["proxy_provider"] = requested_provider
else: else:
log.info(describe_explicit_proxy(ctx.params["proxy"])) log.info(describe_explicit_proxy(ctx.params["proxy"]))
ctx.obj = ContextData(config=service_config, cdm=None, proxy_providers=proxy_providers, profile=profile) launch(ctx, keys, ContextData(config=service_config, cdm=None, proxy_providers=proxy_providers, profile=profile))
@search.result_callback() @search.result_callback()
+4 -13
View File
@@ -393,11 +393,9 @@ def perform_download(
from unshackle.commands.dl import dl from unshackle.commands.dl import dl
from unshackle.core.api.errors import APIError from unshackle.core.api.errors import APIError
from unshackle.core.config import config, load_yaml from unshackle.core.config import config
from unshackle.core.remote_protocol import APIErrorCode from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.services import Services from unshackle.core.services import Services
from unshackle.core.utils.click_types import ContextData
from unshackle.core.utils.collections import merge_dict
log.info(f"Starting sync download for job {job_id}") log.info(f"Starting sync download for job {job_id}")
@@ -447,22 +445,15 @@ def perform_download(
params["wanted"] = season_range.parse_tokens(*wanted_raw) params["wanted"] = season_range.parse_tokens(*wanted_raw)
remote = params.get("remote") remote = params.get("remote")
service_config_path = None if remote else Services.get_path(service) / config.filenames.config
if service_config_path and service_config_path.exists():
service_config = load_yaml(service_config_path)
else:
service_config = {}
merge_dict(config.services.get(service) or {}, service_config)
from unshackle.commands.dl import dl as dl_command from unshackle.commands.dl import dl as dl_command
ctx = click.Context(dl_command.cli) ctx = click.Context(dl_command.cli)
ctx.invoked_subcommand = service ctx.invoked_subcommand = service
from unshackle.core.api.handlers import load_full_cdm, relay_label from unshackle.core.api.handlers import relay_label
from unshackle.core.dl_options import DL_OPTION_API_NAMES, cast_dl_params from unshackle.core.dl_options import DL_OPTION_API_NAMES, cast_dl_params
from unshackle.core.launch import launch
cdm = load_full_cdm(service, params.get("profile"), params.get("cdm_type"))
ctx.obj = ContextData(config=service_config, cdm=cdm, proxy_providers=[], profile=params.get("profile"))
try: try:
dl_params = cast_dl_params(dl_command.cli, params) dl_params = cast_dl_params(dl_command.cli, params)
except click.BadParameter as exc: except click.BadParameter as exc:
@@ -473,8 +464,8 @@ def perform_download(
# dl skips the local service config and guards the proxy for a remote_services server # dl skips the local service config and guards the proxy for a remote_services server
"remote": bool(remote), "remote": bool(remote),
"server": remote, "server": remote,
"client_argv": f"{relay_label(params)} download job {job_id}",
} }
launch(ctx, {"client_argv": f"{relay_label(params)} download job {job_id}"})
# Hand-built context: record parameter sources so service dl overrides # Hand-built context: record parameter sources so service dl overrides
# apply to defaults but never clobber client-sent values. # apply to defaults but never clobber client-sent values.
from click.core import ParameterSource from click.core import ParameterSource
+32 -90
View File
@@ -43,6 +43,7 @@ from unshackle.core.dl_options import (
forwarded_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
from unshackle.core.launch import served_context
from unshackle.core.manifests.snapshot import capture from unshackle.core.manifests.snapshot import capture
from unshackle.core.providers.anilist import parse_anilist_ref from unshackle.core.providers.anilist import parse_anilist_ref
from unshackle.core.proxies.resolve import initialize_proxy_providers, is_loopback, resolve_proxy from unshackle.core.proxies.resolve import initialize_proxy_providers, is_loopback, resolve_proxy
@@ -81,7 +82,7 @@ from unshackle.core.tunnel import (
tunnel_proxy, tunnel_proxy,
) )
from unshackle.core.utilities import declared_kwargs, kind_only_conflict from unshackle.core.utilities import declared_kwargs, kind_only_conflict
from unshackle.core.utils.click_types import QUALITY_LIST, VIDEO_CODEC_LIST from unshackle.core.utils.click_types import QUALITY_LIST, VIDEO_CODEC_LIST, ContextData
from unshackle.core.utils.collections import ci_get, merge_dict from unshackle.core.utils.collections import ci_get, merge_dict
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
@@ -173,45 +174,6 @@ def load_service_yaml(normalized_service: str) -> dict:
return service_config return service_config
def build_parent_ctx(
profile: Optional[str],
cdm: Any,
proxy_param: Optional[str],
no_proxy: bool,
proxy_providers: list,
service_config: dict,
extra_params: Optional[Dict[str, Any]] = None,
) -> Any:
"""Assemble a parent click Context for invoking a service.cli through ctx.invoke().
The service's CLI callback uses ``ctx.parent.params`` (proxy, range_, vcodec, and the
other dl options) and ``ctx.obj`` (ContextData). Both flow through Click's parent chain.
``extra_params`` carries ``cookies_supplied``: True when a cookie jar goes to
``authenticate()`` later in this request. A service that picks an authentication path in
``__init__`` must read that flag, because a client-sent jar is in the request body, not in
the server's ``cookies/`` directory, so a file check answers False for it.
"""
import click
from unshackle.core.utils.click_types import ContextData
@click.command()
@click.pass_context
def dummy(ctx: click.Context) -> None:
pass
parent = click.Context(dummy)
parent.obj = ContextData(config=service_config, cdm=cdm, proxy_providers=proxy_providers, profile=profile)
params: Dict[str, Any] = {"proxy": proxy_param, "no_proxy": no_proxy, "served": True}
if extra_params:
params.update(extra_params)
# dl defaults -q to [], and services iterate it
params["quality"] = params.get("quality") or []
parent.params = params
return parent
def cast_or_refuse(params: Iterable[click.Parameter], ctx: Any, options: Dict[str, Any]) -> Dict[str, Any]: 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``.""" """``cast_service_options``, with a refused value as ``400 INVALID_PARAMETERS``."""
try: try:
@@ -487,14 +449,10 @@ def relay_service(
# the same server_proxy gate a local service gets: without it the providers stay empty # 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) proxy_param, providers = resolve_handler_proxy(data, data["service"], request)
parent_ctx = build_parent_ctx( parent_ctx = served_context(
profile, ContextData(config={}, cdm=None, proxy_providers=providers, profile=profile),
None, {"proxy": proxy_param, "no_proxy": data.get("no_proxy", False), "profile": profile},
proxy_param, {"client_argv": relay_label(data)},
data.get("no_proxy", False),
providers,
{},
extra_params={"profile": profile, "client_argv": relay_label(data)},
) )
ctx = click.Context(click.Command(data["service"]), parent=parent_ctx, obj=parent_ctx.obj) 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 # this process is long-lived and serves local services too, so the remote's overrides stay out of config
@@ -790,14 +748,10 @@ def setup_list_service(
cdm = load_full_cdm(normalized_service, profile, data.get("cdm_type"), key_cdm_config(user_config)) cdm = load_full_cdm(normalized_service, profile, data.get("cdm_type"), key_cdm_config(user_config))
cookies, credential = server_login_material(data, normalized_service, account, profile) cookies, credential = server_login_material(data, normalized_service, account, profile)
parent_ctx = build_parent_ctx( parent_ctx = served_context(
profile, ContextData(config=service_config, cdm=cdm, proxy_providers=proxy_providers, profile=profile),
cdm, {"proxy": proxy_param, "no_proxy": no_proxy, **forwarded_dl_params(data)},
proxy_param, {"cookies_supplied": cookies is not None},
no_proxy,
proxy_providers,
service_config,
extra_params={"cookies_supplied": cookies is not None, **forwarded_dl_params(data)},
) )
service_module = Services.load(normalized_service) service_module = Services.load(normalized_service)
service_instance = instantiate_service(parent_ctx, service_module, title_id, data, LIST_HANDLER_TRANSPORT_KEYS) service_instance = instantiate_service(parent_ctx, service_module, title_id, data, LIST_HANDLER_TRANSPORT_KEYS)
@@ -848,14 +802,10 @@ def run_service_search(
(None, None) if anonymous else server_login_material(data, normalized_service, account, profile) (None, None) if anonymous else server_login_material(data, normalized_service, account, profile)
) )
parent_ctx = build_parent_ctx( parent_ctx = served_context(
profile, ContextData(config=service_config, cdm=cdm, proxy_providers=proxy_providers, profile=profile),
cdm, {"proxy": proxy_param, "no_proxy": no_proxy},
proxy_param, {"cookies_supplied": cookies is not None},
no_proxy,
proxy_providers,
service_config,
extra_params={"cookies_supplied": cookies is not None},
) )
from click import ClickException from click import ClickException
@@ -3479,15 +3429,6 @@ def create_service_instance(
vcodec_values = resolve_vcodec(data.get("vcodec")) vcodec_values = resolve_vcodec(data.get("vcodec"))
extra_params = {
"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),
}
if server_account: if server_account:
cookies = server_account_cookies(normalized_service, profile) cookies = server_account_cookies(normalized_service, profile)
credential = dl.get_credentials(normalized_service, profile) credential = dl.get_credentials(normalized_service, profile)
@@ -3495,23 +3436,24 @@ def create_service_instance(
credential = client_credential(data) credential = client_credential(data)
cookies = load_client_cookies(data.get("cookies")) cookies = load_client_cookies(data.get("cookies"))
extra_params["cookies_supplied"] = cookies is not None parent_ctx = served_context(
# A service with CLIENT_CONFIG reads these: with client_identity it uses only what the client sent, ContextData(config=service_config, cdm=cdm, proxy_providers=proxy_providers, profile=profile),
# and without it the server's identity, whose keys then come only from a vault. {
extra_params["client_device"] = client_device "proxy": proxy_param,
extra_params["client_identity"] = client_identity "no_proxy": data.get("no_proxy", False),
# Services key their token caches on this. Only sessions get it: they run on a cache "range_": range_values,
# directory of their own, where the list and search handlers share the server's cache. "vcodec": vcodec_values,
extra_params["profile"] = profile "quality": requested_heights(data.get("quality")),
"best_available": data.get("best_available", False),
parent_ctx = build_parent_ctx( "generate_dv": data.get("generate_dv", False),
profile, **forwarded_dl_params(data),
cdm, # Services key their token caches on this. Only sessions get it: they run on a cache
proxy_param, # directory of their own, where the list and search handlers share the server's cache.
data.get("no_proxy", False), "profile": profile,
proxy_providers, },
service_config, # A service with CLIENT_CONFIG reads client_device and client_identity: with client_identity it uses
extra_params=extra_params, # 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},
) )
service_instance = instantiate_service(parent_ctx, service_module, title_id, data, SESSION_TRANSPORT_KEYS) service_instance = instantiate_service(parent_ctx, service_module, title_id, data, SESSION_TRANSPORT_KEYS)
+51
View File
@@ -0,0 +1,51 @@
"""The launch context of a Service: ``ctx.obj`` and the launch keys in ``ctx.parent.params``."""
from typing import Any, Dict, Optional, TypedDict, cast
import click
from unshackle.core.utils.click_types import ContextData
class LaunchKeys(TypedDict, total=False):
"""The ``ctx.parent.params`` keys that exist only for the launch. ``dl_options.DL_OPTIONS`` holds the dl options.
- ``served``: a serve runs the service for an API client, so the region it checks is the server's.
- ``cookies_supplied``: ``authenticate()`` gets a cookie jar that is not in the ``cookies/`` directory.
- ``client_device``: the service licenses through the remote client's own device.
- ``client_identity``: the service config holds the device identity that the remote client sent.
- ``client_argv``: the command line that the remote server's dashboard shows for this client.
- ``proxy_arg``: the ``--proxy`` value as given, before it resolves to a URI.
- ``proxy_query``: the region part of ``--proxy``, which a service ``proxy_map`` keys on.
- ``proxy_provider``: the proxy provider that ``--proxy`` names, or None.
"""
served: bool
cookies_supplied: bool
client_device: bool
client_identity: bool
client_argv: str
proxy_arg: Optional[str]
proxy_query: Optional[str]
proxy_provider: Optional[str]
def launch(ctx: click.Context, keys: LaunchKeys, obj: Optional[ContextData] = None) -> None:
"""Write the launch ``keys`` into ``ctx.params``, and ``obj`` as ``ctx.obj`` when given."""
ctx.params.update(keys)
if obj is not 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 []}
launch(ctx, {**keys, "served": True}, obj)
return ctx
def launch_keys(ctx: click.Context) -> LaunchKeys:
"""The launch keys that a service context reads from its parent, or none without a parent."""
return cast(LaunchKeys, ctx.parent.params) if ctx.parent else {}
+3 -2
View File
@@ -51,6 +51,7 @@ from unshackle.core.constants import AnyTrack
from unshackle.core.credential import Credential from unshackle.core.credential import Credential
from unshackle.core.dl_options import remote_dl_params from unshackle.core.dl_options import remote_dl_params
from unshackle.core.drm import cbcs, real_kids from unshackle.core.drm import cbcs, real_kids
from unshackle.core.launch import launch_keys
from unshackle.core.manifests.snapshot import match_track, restore from unshackle.core.manifests.snapshot import match_track, restore
from unshackle.core.proxies.resolve import is_loopback from unshackle.core.proxies.resolve import is_loopback
from unshackle.core.remote_protocol import ( from unshackle.core.remote_protocol import (
@@ -1094,7 +1095,7 @@ class RemoteService:
resolved_proxy = resolve_remote_proxy_arg(server_proxy_arg(self.ctx.parent.params), providers) resolved_proxy = resolve_remote_proxy_arg(server_proxy_arg(self.ctx.parent.params), providers)
if resolved_proxy: if resolved_proxy:
create_data["proxy"] = resolved_proxy create_data["proxy"] = resolved_proxy
query = (self.ctx.parent.params.get("proxy_query") if self.ctx.parent else None) or proxy query = launch_keys(self.ctx).get("proxy_query") or proxy
country = re.match(r"^(?:[a-z]+:)?([a-z]{2})\d*(?:@.*)?$", query, re.IGNORECASE) country = re.match(r"^(?:[a-z]+:)?([a-z]{2})\d*(?:@.*)?$", query, re.IGNORECASE)
if country: if country:
create_data["proxy_region"] = country.group(1).lower() create_data["proxy_region"] = country.group(1).lower()
@@ -1171,7 +1172,7 @@ class RemoteService:
secrets = [v for v in (create_data.get("credentials") or {}).values() if isinstance(v, str) and len(v) >= 4] secrets = [v for v in (create_data.get("credentials") or {}).values() if isinstance(v, str) and len(v) >= 4]
# a serve relaying for a REST client names itself; its own argv is just the serve command # a serve relaying for a REST client names itself; its own argv is just the serve command
client_argv = self.ctx.parent.params.get("client_argv") if self.ctx.parent else None client_argv = launch_keys(self.ctx).get("client_argv")
argv = (redact_path(redact_text(client_argv or shlex.join(sys.argv[1:]), secrets)) or "")[:3000] argv = (redact_path(redact_text(client_argv or shlex.join(sys.argv[1:]), secrets)) or "")[:3000]
create_data["client"] = { create_data["client"] = {
"version": __version__, "version": __version__,
+6 -9
View File
@@ -24,6 +24,7 @@ from unshackle.core.console import console, prompt_user, show_notice
from unshackle.core.constants import AnyTrack from unshackle.core.constants import AnyTrack
from unshackle.core.credential import Credential from unshackle.core.credential import Credential
from unshackle.core.drm import DRM_T from unshackle.core.drm import DRM_T
from unshackle.core.launch import launch_keys
from unshackle.core.proxies.basic import Basic from unshackle.core.proxies.basic import Basic
from unshackle.core.proxies.resolve import pick_proxy from unshackle.core.proxies.resolve import pick_proxy
from unshackle.core.search_result import SearchResult from unshackle.core.search_result import SearchResult
@@ -206,16 +207,12 @@ class Service(metaclass=ABCMeta):
generate_dv=bool(generate_dv), generate_dv=bool(generate_dv),
) )
whose = "the server's" if ctx.parent and ctx.parent.params.get("served") else "your" keys = launch_keys(ctx)
whose = "the server's" if keys.get("served") else "your"
if not ctx.parent or not ctx.parent.params.get("no_proxy"): if not ctx.parent or not ctx.parent.params.get("no_proxy"):
if ctx.parent: proxy = ctx.parent.params["proxy"] if ctx.parent else None
proxy = ctx.parent.params["proxy"] proxy_query = keys.get("proxy_query")
proxy_query = ctx.parent.params.get("proxy_query") proxy_provider_name = keys.get("proxy_provider")
proxy_provider_name = ctx.parent.params.get("proxy_provider")
else:
proxy = None
proxy_query = None
proxy_provider_name = None
service_name = self.__class__.__name__ service_name = self.__class__.__name__
service_config_dict = config.services.get(service_name, {}) service_config_dict = config.services.get(service_name, {})