forked from kenzuya/unshackle
refactor(core): write a service's launch keys through one module
This commit is contained in:
+18
-12
@@ -68,6 +68,7 @@ from unshackle.core.drm import (
|
||||
from unshackle.core.drm.key_resolution import ContentKeyResolver
|
||||
from unshackle.core.events import events
|
||||
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.providers.anilist import parse_anilist_ref
|
||||
from unshackle.core.providers.tvdb import SEASON_TYPES, parse_int
|
||||
@@ -1596,6 +1597,7 @@ class dl:
|
||||
)
|
||||
|
||||
self.proxy_providers = []
|
||||
keys: LaunchKeys = {}
|
||||
if no_proxy:
|
||||
ctx.params["proxy"] = None
|
||||
else:
|
||||
@@ -1607,7 +1609,7 @@ class dl:
|
||||
with console.status("Loading Proxy Providers...", spinner="dots"):
|
||||
self.proxy_providers = load_proxy_providers()
|
||||
|
||||
ctx.params["proxy_arg"] = proxy
|
||||
keys["proxy_arg"] = proxy
|
||||
if proxy and proxy.startswith("controld://"):
|
||||
proxy = ctx.params["proxy"] = resolve_proxy(proxy, [])
|
||||
if proxy:
|
||||
@@ -1635,20 +1637,24 @@ class dl:
|
||||
sys.exit(1)
|
||||
ctx.params["proxy"] = proxy_uri
|
||||
self.log.info(describe_proxy(proxy_provider, proxy_uri, proxy_query))
|
||||
ctx.params["proxy_query"] = proxy_query
|
||||
ctx.params["proxy_provider"] = requested_provider
|
||||
keys["proxy_query"] = proxy_query
|
||||
keys["proxy_provider"] = requested_provider
|
||||
else:
|
||||
self.log.info(describe_explicit_proxy(ctx.params["proxy"]))
|
||||
ctx.params["proxy_query"] = None
|
||||
ctx.params["proxy_provider"] = None
|
||||
keys["proxy_query"] = None
|
||||
keys["proxy_provider"] = None
|
||||
|
||||
ctx.obj = ContextData(
|
||||
config=self.service_config,
|
||||
cdm=self.cdm,
|
||||
proxy_providers=self.proxy_providers,
|
||||
profile=self.profile,
|
||||
cdm_entry=self.cdm_from_service_entry(),
|
||||
cdm_for=self.cdm_for,
|
||||
launch(
|
||||
ctx,
|
||||
keys,
|
||||
ContextData(
|
||||
config=self.service_config,
|
||||
cdm=self.cdm,
|
||||
proxy_providers=self.proxy_providers,
|
||||
profile=self.profile,
|
||||
cdm_entry=self.cdm_from_service_entry(),
|
||||
cdm_for=self.cdm_for,
|
||||
),
|
||||
)
|
||||
|
||||
if repack:
|
||||
|
||||
@@ -14,6 +14,7 @@ from unshackle.commands.dl import dl
|
||||
from unshackle.core.config import config, load_yaml
|
||||
from unshackle.core.console import console
|
||||
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.resolve import (
|
||||
REGION,
|
||||
@@ -99,13 +100,14 @@ def search(
|
||||
proxy, no_proxy = ctx.params.get("proxy"), bool(ctx.params.get("no_proxy"))
|
||||
|
||||
proxy_providers: list[Proxy] = []
|
||||
keys: LaunchKeys = {}
|
||||
if no_proxy:
|
||||
ctx.params["proxy"] = None
|
||||
else:
|
||||
with console.status("Loading Proxy Providers...", spinner="dots"):
|
||||
proxy_providers = load_proxy_providers()
|
||||
|
||||
ctx.params["proxy_arg"] = proxy
|
||||
keys["proxy_arg"] = proxy
|
||||
if proxy:
|
||||
try:
|
||||
requested_provider, query = split_proxy_query(proxy, proxy_providers)
|
||||
@@ -122,10 +124,12 @@ def search(
|
||||
sys.exit(1)
|
||||
ctx.params["proxy"] = proxy_uri
|
||||
log.info(describe_proxy(proxy_provider, proxy_uri, query))
|
||||
keys["proxy_query"] = query
|
||||
keys["proxy_provider"] = requested_provider
|
||||
else:
|
||||
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()
|
||||
|
||||
@@ -393,11 +393,9 @@ def perform_download(
|
||||
|
||||
from unshackle.commands.dl import dl
|
||||
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.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}")
|
||||
|
||||
@@ -447,22 +445,15 @@ def perform_download(
|
||||
params["wanted"] = season_range.parse_tokens(*wanted_raw)
|
||||
|
||||
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
|
||||
|
||||
ctx = click.Context(dl_command.cli)
|
||||
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.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:
|
||||
dl_params = cast_dl_params(dl_command.cli, params)
|
||||
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
|
||||
"remote": bool(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
|
||||
# apply to defaults but never clobber client-sent values.
|
||||
from click.core import ParameterSource
|
||||
|
||||
@@ -43,6 +43,7 @@ from unshackle.core.dl_options import (
|
||||
forwarded_dl_params,
|
||||
)
|
||||
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.providers.anilist import parse_anilist_ref
|
||||
from unshackle.core.proxies.resolve import initialize_proxy_providers, is_loopback, resolve_proxy
|
||||
@@ -81,7 +82,7 @@ from unshackle.core.tunnel import (
|
||||
tunnel_proxy,
|
||||
)
|
||||
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.hdr10plus import probed_tracks
|
||||
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
|
||||
|
||||
|
||||
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]:
|
||||
"""``cast_service_options``, with a refused value as ``400 INVALID_PARAMETERS``."""
|
||||
try:
|
||||
@@ -487,14 +449,10 @@ 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 = build_parent_ctx(
|
||||
profile,
|
||||
None,
|
||||
proxy_param,
|
||||
data.get("no_proxy", False),
|
||||
providers,
|
||||
{},
|
||||
extra_params={"profile": profile, "client_argv": relay_label(data)},
|
||||
parent_ctx = served_context(
|
||||
ContextData(config={}, cdm=None, proxy_providers=providers, profile=profile),
|
||||
{"proxy": proxy_param, "no_proxy": data.get("no_proxy", False), "profile": profile},
|
||||
{"client_argv": relay_label(data)},
|
||||
)
|
||||
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
|
||||
@@ -790,14 +748,10 @@ def setup_list_service(
|
||||
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)
|
||||
|
||||
parent_ctx = build_parent_ctx(
|
||||
profile,
|
||||
cdm,
|
||||
proxy_param,
|
||||
no_proxy,
|
||||
proxy_providers,
|
||||
service_config,
|
||||
extra_params={"cookies_supplied": cookies is not None, **forwarded_dl_params(data)},
|
||||
parent_ctx = served_context(
|
||||
ContextData(config=service_config, cdm=cdm, proxy_providers=proxy_providers, profile=profile),
|
||||
{"proxy": proxy_param, "no_proxy": no_proxy, **forwarded_dl_params(data)},
|
||||
{"cookies_supplied": cookies is not None},
|
||||
)
|
||||
service_module = Services.load(normalized_service)
|
||||
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)
|
||||
)
|
||||
|
||||
parent_ctx = build_parent_ctx(
|
||||
profile,
|
||||
cdm,
|
||||
proxy_param,
|
||||
no_proxy,
|
||||
proxy_providers,
|
||||
service_config,
|
||||
extra_params={"cookies_supplied": cookies is not None},
|
||||
parent_ctx = served_context(
|
||||
ContextData(config=service_config, cdm=cdm, proxy_providers=proxy_providers, profile=profile),
|
||||
{"proxy": proxy_param, "no_proxy": no_proxy},
|
||||
{"cookies_supplied": cookies is not None},
|
||||
)
|
||||
|
||||
from click import ClickException
|
||||
@@ -3479,15 +3429,6 @@ def create_service_instance(
|
||||
|
||||
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:
|
||||
cookies = server_account_cookies(normalized_service, profile)
|
||||
credential = dl.get_credentials(normalized_service, profile)
|
||||
@@ -3495,23 +3436,24 @@ def create_service_instance(
|
||||
credential = client_credential(data)
|
||||
cookies = load_client_cookies(data.get("cookies"))
|
||||
|
||||
extra_params["cookies_supplied"] = cookies is not None
|
||||
# A service with CLIENT_CONFIG reads these: 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.
|
||||
extra_params["client_device"] = client_device
|
||||
extra_params["client_identity"] = client_identity
|
||||
# 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.
|
||||
extra_params["profile"] = profile
|
||||
|
||||
parent_ctx = build_parent_ctx(
|
||||
profile,
|
||||
cdm,
|
||||
proxy_param,
|
||||
data.get("no_proxy", False),
|
||||
proxy_providers,
|
||||
service_config,
|
||||
extra_params=extra_params,
|
||||
parent_ctx = served_context(
|
||||
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,
|
||||
},
|
||||
# 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},
|
||||
)
|
||||
|
||||
service_instance = instantiate_service(parent_ctx, service_module, title_id, data, SESSION_TRANSPORT_KEYS)
|
||||
|
||||
@@ -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 {}
|
||||
@@ -51,6 +51,7 @@ from unshackle.core.constants import AnyTrack
|
||||
from unshackle.core.credential import Credential
|
||||
from unshackle.core.dl_options import remote_dl_params
|
||||
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.proxies.resolve import is_loopback
|
||||
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)
|
||||
if 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)
|
||||
if country:
|
||||
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]
|
||||
# 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]
|
||||
create_data["client"] = {
|
||||
"version": __version__,
|
||||
|
||||
@@ -24,6 +24,7 @@ from unshackle.core.console import console, prompt_user, show_notice
|
||||
from unshackle.core.constants import AnyTrack
|
||||
from unshackle.core.credential import Credential
|
||||
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.resolve import pick_proxy
|
||||
from unshackle.core.search_result import SearchResult
|
||||
@@ -206,16 +207,12 @@ class Service(metaclass=ABCMeta):
|
||||
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 ctx.parent:
|
||||
proxy = ctx.parent.params["proxy"]
|
||||
proxy_query = ctx.parent.params.get("proxy_query")
|
||||
proxy_provider_name = ctx.parent.params.get("proxy_provider")
|
||||
else:
|
||||
proxy = None
|
||||
proxy_query = None
|
||||
proxy_provider_name = None
|
||||
proxy = ctx.parent.params["proxy"] if ctx.parent else None
|
||||
proxy_query = keys.get("proxy_query")
|
||||
proxy_provider_name = keys.get("proxy_provider")
|
||||
|
||||
service_name = self.__class__.__name__
|
||||
service_config_dict = config.services.get(service_name, {})
|
||||
|
||||
Reference in New Issue
Block a user