forked from kenzuya/unshackle
refactor(dl): check dl options once in a run plan shared by the CLI and the REST download job
This commit is contained in:
@@ -4,7 +4,6 @@ import importlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
@@ -21,7 +20,6 @@ from unshackle.core.api.events import bus, publish_service_event
|
||||
from unshackle.core.api.sanitize import sanitize_log
|
||||
from unshackle.core.credential import Credential
|
||||
from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_all, redact_path, redact_text
|
||||
from unshackle.core.utils.service_params import cast_service_options, service_options
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from unshackle.core.service import Service
|
||||
@@ -378,11 +376,9 @@ def perform_download(
|
||||
) -> List[str]:
|
||||
"""Do the synchronous download work for a job.
|
||||
|
||||
`params` holds the API's string form of the `dl` options. The function first normalizes the API-shaped
|
||||
options in place: `slow` accepts "MIN-MAX", a two-item list, or True (which means 60-120), and `wanted`
|
||||
accepts forms such as "S01E01", "S01-S03", "s1e1", or "1x1" as well as the internal "SxE" form. Music takes track
|
||||
numbers in the same field, such as "1-5" or "2x3" for disc 2 track 3. Then each dl click type casts its option
|
||||
into ``ctx.params``, which feeds dl() and dl.result() as on the CLI.
|
||||
``params`` holds the API's form of the ``dl`` options; ``api_plan`` checks and casts them into the dl context,
|
||||
which feeds dl() and dl.result() as on the CLI. The service is built through its click cli like every other
|
||||
server path.
|
||||
"""
|
||||
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
@@ -415,67 +411,12 @@ def perform_download(
|
||||
if params.pop(banned, None) is not None:
|
||||
log.warning(f"Ignoring '{banned}' in API download parameters; post-scripts are config-only")
|
||||
|
||||
client_keys = client_sent_keys(params)
|
||||
|
||||
slow_raw = params.get("slow")
|
||||
if slow_raw is not None and not isinstance(slow_raw, tuple):
|
||||
if isinstance(slow_raw, bool):
|
||||
params["slow"] = (60, 120) if slow_raw else None
|
||||
elif isinstance(slow_raw, list) and len(slow_raw) == 2:
|
||||
params["slow"] = (int(slow_raw[0]), int(slow_raw[1]))
|
||||
elif isinstance(slow_raw, str):
|
||||
from unshackle.core.utils.click_types import SLOW_DELAY_RANGE
|
||||
|
||||
try:
|
||||
params["slow"] = SLOW_DELAY_RANGE.convert(slow_raw, None, None)
|
||||
except click.BadParameter as exc:
|
||||
raise Exception(f"Invalid slow parameter: {exc}")
|
||||
|
||||
wanted_raw = params.get("wanted")
|
||||
if wanted_raw:
|
||||
from unshackle.core.utils.click_types import SeasonRange
|
||||
|
||||
if isinstance(wanted_raw, str):
|
||||
# the CLI splits a comma-separated value before parsing, so a raw string must too
|
||||
wanted_raw = re.split(r"\s*[,;]\s*", wanted_raw)
|
||||
# the !? keeps a pre-parsed part exclusion from being re-fed through parse_tokens
|
||||
needs_conversion = any(not re.match(r"^!?\d+x\d+(\.\d+)?$", w) for w in wanted_raw)
|
||||
if needs_conversion:
|
||||
season_range = SeasonRange()
|
||||
params["wanted"] = season_range.parse_tokens(*wanted_raw)
|
||||
|
||||
remote = params.get("remote")
|
||||
|
||||
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 relay_label
|
||||
from unshackle.core.dl_options import DL_OPTION_API_NAMES, cast_dl_params
|
||||
from unshackle.core.api.handlers import DL_TRANSPORT_KEYS, instantiate_service, relay_label
|
||||
from unshackle.core.launch import launch
|
||||
from unshackle.core.run_plan import RunStopped, api_plan
|
||||
|
||||
try:
|
||||
dl_params = cast_dl_params(dl_command.cli, params)
|
||||
except click.BadParameter as exc:
|
||||
raise APIError(APIErrorCode.INVALID_PARAMETERS, exc.message)
|
||||
ctx.params = {
|
||||
**dl_params,
|
||||
"cdm_name": params.get("cdm"),
|
||||
# dl skips the local service config and guards the proxy for a remote_services server
|
||||
"remote": bool(remote),
|
||||
"server": remote,
|
||||
}
|
||||
ctx = api_plan(params, client_sent_keys(params)).context(dl.cli, service)
|
||||
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
|
||||
|
||||
for param_name in ctx.params:
|
||||
source_key = DL_OPTION_API_NAMES.get(param_name, param_name)
|
||||
ctx.set_parameter_source(
|
||||
param_name, ParameterSource.COMMANDLINE if source_key in client_keys else ParameterSource.DEFAULT
|
||||
)
|
||||
|
||||
dl_instance = dl(ctx=ctx, proxy_providers=None if params.get("server_proxy") is True else [], **ctx.params)
|
||||
# Per-request credential ("user:pass"); feed it into the map get_credentials() reads so a
|
||||
# client can authenticate without anything being persisted to disk. Without a profile,
|
||||
@@ -487,45 +428,15 @@ def perform_download(
|
||||
config.credentials[service] = svc_creds = {}
|
||||
svc_creds[params.get("profile") or "default"] = params["credential"]
|
||||
|
||||
service_ctx = click.Context(click.Command(service), parent=ctx, obj=ctx.obj)
|
||||
remote = ctx.params["server"]
|
||||
if remote:
|
||||
from unshackle.core.remote_service import make_remote_service
|
||||
|
||||
service_ctx = click.Context(click.Command(service), parent=ctx, obj=ctx.obj)
|
||||
# RemoteService duck-types Service for dl.result()
|
||||
service_instance = cast("Service", make_remote_service(service_ctx, remote, service, title_id, params))
|
||||
else:
|
||||
service_module = Services.load(service)
|
||||
|
||||
try:
|
||||
import inspect
|
||||
|
||||
service_init_params = inspect.signature(service_module.__init__).parameters
|
||||
|
||||
service_kwargs: Dict[str, Any] = {}
|
||||
|
||||
if "title" in service_init_params:
|
||||
service_kwargs["title"] = title_id
|
||||
|
||||
cli_params = getattr(getattr(service_module, "cli", None), "params", None) or []
|
||||
options = service_options(params, service_init_params.keys() - {"title"})
|
||||
service_kwargs.update(cast_service_options(cli_params, service_ctx, options))
|
||||
|
||||
for param_name, param_info in service_init_params.items():
|
||||
if param_name not in service_kwargs and param_name not in ["self", "ctx"]:
|
||||
if param_info.default is inspect.Parameter.empty:
|
||||
if param_name == "movie":
|
||||
service_kwargs[param_name] = "/movies/" in title_id
|
||||
elif param_name == "meta_lang":
|
||||
service_kwargs[param_name] = None
|
||||
else:
|
||||
log.warning(f"Unknown required parameter '{param_name}' for service {service}, using None")
|
||||
service_kwargs[param_name] = None
|
||||
|
||||
service_instance = service_module(service_ctx, **service_kwargs)
|
||||
|
||||
except Exception as exc: # noqa: BLE001 - propagate meaningful failure
|
||||
log.error(f"Failed to create service instance: {exc}")
|
||||
raise
|
||||
service_instance = instantiate_service(ctx, Services.load(service), title_id, params, DL_TRANSPORT_KEYS)
|
||||
|
||||
original_download_dir = config.directories.downloads
|
||||
|
||||
@@ -536,20 +447,23 @@ def perform_download(
|
||||
# (success/failure) is reported by the worker's result file.
|
||||
try:
|
||||
with redirect_stdout(stdout_capture), redirect_stderr(stderr_capture):
|
||||
dl_instance.result(
|
||||
outcome = dl_instance.result(
|
||||
service=service_instance,
|
||||
**{**ctx.params, "select_titles": False, "list_": False, "list_titles": False},
|
||||
progress_sink=progress_callback,
|
||||
)
|
||||
|
||||
except RunStopped as exc:
|
||||
log.debug("Stdout: %s", stdout_capture.getvalue())
|
||||
raise APIError(APIErrorCode.DOWNLOAD_ERROR, f"Download failed: {exc.reason}")
|
||||
|
||||
except SystemExit as exc:
|
||||
if exc.code != 0:
|
||||
log.error(f"Download exited with code {exc.code}")
|
||||
log.debug("Stdout: %s", stdout_capture.getvalue())
|
||||
log.debug("Stderr: %s", stderr_capture.getvalue())
|
||||
if reason := getattr(dl_instance, "stop_reason", None):
|
||||
raise APIError(APIErrorCode.DOWNLOAD_ERROR, f"Download failed: {reason}")
|
||||
raise APIError(APIErrorCode.DOWNLOAD_ERROR, f"Download failed with exit code {exc.code}")
|
||||
outcome = dl_instance.outcome()
|
||||
|
||||
except Exception as exc: # noqa: BLE001 - propagate to caller
|
||||
log.error(f"Download execution failed: {exc}")
|
||||
@@ -557,19 +471,16 @@ def perform_download(
|
||||
log.debug("Stderr: %s", stderr_capture.getvalue())
|
||||
raise
|
||||
|
||||
# dl.result() catches a download-worker exception, reports it, but returns normally (exit 0).
|
||||
# It keeps the error in download_error, so the job isn't reported as completed with no output.
|
||||
if (error := getattr(dl_instance, "download_error", None)) is not None:
|
||||
# dl.result() reports a download-worker exception and returns normally, so the CLI exits cleanly.
|
||||
if outcome.error is not None:
|
||||
# segment URLs carry signed CDN tokens (hmac, session IDs) that redact_text does not match
|
||||
detail = redact_all(dl_instance.failure_lines(error)[1].strip())
|
||||
detail = redact_all(dl_instance.failure_lines(outcome.error)[1].strip())
|
||||
raise APIError(APIErrorCode.WORKER_ERROR, f"download worker failed: {detail}")
|
||||
|
||||
if progress_callback:
|
||||
skipped_subs = getattr(dl_instance, "skipped_subtitles", None)
|
||||
if skipped_subs:
|
||||
progress_callback({"skipped_subtitles": list(skipped_subs)})
|
||||
if progress_callback and outcome.skipped_subtitles:
|
||||
progress_callback({"skipped_subtitles": outcome.skipped_subtitles})
|
||||
|
||||
output_files = [str(p) for p in dl_instance.completed_files]
|
||||
output_files = [str(p) for p in outcome.files]
|
||||
log.info(f"Download completed for job {job_id}, {len(output_files)} file(s) in {original_download_dir}")
|
||||
|
||||
return output_files
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import asyncio
|
||||
import base64
|
||||
import copy
|
||||
import enum
|
||||
import functools
|
||||
import json
|
||||
import logging
|
||||
@@ -41,13 +40,11 @@ from unshackle.core.config import config
|
||||
from unshackle.core.dl_options import (
|
||||
DEFAULT_DOWNLOAD_PARAMS,
|
||||
DL_OPTION_API_NAMES,
|
||||
cast_dl_params,
|
||||
forwarded_dl_params,
|
||||
)
|
||||
from unshackle.core.drm import BlowfishStripe, cbcs, is_null_key, real_kids
|
||||
from unshackle.core.launch import load_service_config, 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
|
||||
from unshackle.core.remote_protocol import (
|
||||
HEALTH_ROUTE,
|
||||
@@ -70,6 +67,7 @@ from unshackle.core.remote_protocol import (
|
||||
TracksReply,
|
||||
TracksRequest,
|
||||
)
|
||||
from unshackle.core.run_plan import PlanError, api_plan
|
||||
from unshackle.core.services import Services
|
||||
from unshackle.core.session import RnetSession, utf8_text
|
||||
from unshackle.core.titles import Episode, Song
|
||||
@@ -84,8 +82,8 @@ from unshackle.core.tunnel import (
|
||||
is_public_ip,
|
||||
tunnel_proxy,
|
||||
)
|
||||
from unshackle.core.utilities import declared_kwargs, kind_only_conflict
|
||||
from unshackle.core.utils.click_types import QUALITY_LIST, VIDEO_CODEC_LIST, ContextData
|
||||
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.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
|
||||
@@ -1675,23 +1673,12 @@ async def list_tracks_handler(data: Dict[str, Any], request: Optional[web.Reques
|
||||
|
||||
wanted = None
|
||||
if wanted_param:
|
||||
from unshackle.core.utils.click_types import SeasonRange
|
||||
|
||||
try:
|
||||
season_range = SeasonRange()
|
||||
if isinstance(wanted_param, list):
|
||||
wanted = season_range.parse_tokens(*wanted_param)
|
||||
else:
|
||||
# convert(), not parse_tokens(), so a comma-separated string splits
|
||||
# into tokens the way the CLI splits it
|
||||
wanted = season_range.convert(wanted_param)
|
||||
log.debug(
|
||||
f"Parsed wanted '{sanitize_log(wanted_param)}' into {len(wanted)} episodes: {wanted[:10]}..."
|
||||
)
|
||||
except (Exception, SystemExit) as e:
|
||||
wanted = SEASON_RANGE.convert(wanted_param)
|
||||
except click.BadParameter as e:
|
||||
raise APIError(
|
||||
APIErrorCode.INVALID_PARAMETERS,
|
||||
f"Invalid wanted parameter: {e}",
|
||||
f"Invalid wanted parameter: {e.message}",
|
||||
details={"wanted": wanted_param, "service": normalized_service},
|
||||
)
|
||||
elif season is not None and episode is not None:
|
||||
@@ -1813,19 +1800,11 @@ def resolve_vcodec(value: Any) -> Optional[list]:
|
||||
|
||||
|
||||
def wanted_refusal(wanted: Any) -> Optional[str]:
|
||||
"""Why the job worker could not parse ``wanted``, or None when it can."""
|
||||
if not wanted:
|
||||
return None
|
||||
from unshackle.core.utils.click_types import SeasonRange
|
||||
|
||||
tokens = re.split(r"\s*[,;]\s*", wanted) if isinstance(wanted, str) else wanted
|
||||
if not isinstance(tokens, list) or not all(isinstance(t, str) for t in tokens):
|
||||
return "wanted must be a string or a list of strings"
|
||||
"""Why dl could not parse ``wanted``, or None when it can."""
|
||||
try:
|
||||
if any(not re.match(r"^!?\d+x\d+(\.\d+)?$", t) for t in tokens):
|
||||
SeasonRange().parse_tokens(*tokens)
|
||||
except (click.BadParameter, ValueError) as e:
|
||||
return f"Invalid wanted parameter: {e}"
|
||||
SEASON_RANGE.convert(wanted or [])
|
||||
except click.BadParameter as e:
|
||||
return f"Invalid wanted parameter: {e.message}"
|
||||
return None
|
||||
|
||||
|
||||
@@ -1846,16 +1825,6 @@ def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]:
|
||||
except APIError as e:
|
||||
return e.message
|
||||
|
||||
if data.get("sample") is not None:
|
||||
from unshackle.core.utils.click_types import SAMPLE_RANGE
|
||||
|
||||
try:
|
||||
SAMPLE_RANGE.convert(data["sample"], None, None)
|
||||
except click.BadParameter:
|
||||
return "sample must be true or a 'START-END' window in seconds, such as '60-120'."
|
||||
if data.get("sample") and data.get("include_sample"):
|
||||
return "sample and include_sample cannot be used together."
|
||||
|
||||
# The serve user would create and write any directory a client names; keep it under downloads.
|
||||
if data.get("output_dir"):
|
||||
root = config.directories.downloads.resolve()
|
||||
@@ -1881,13 +1850,6 @@ def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]:
|
||||
if not isinstance(data["abitrate"], int) or data["abitrate"] <= 0:
|
||||
return "abitrate must be a positive integer"
|
||||
|
||||
for prefix, example in (("v", "6000-7000"), ("a", "128-256")):
|
||||
value = data.get(f"{prefix}bitrate_range")
|
||||
if value and data.get(f"{prefix}bitrate") is not None:
|
||||
return f"Cannot use both {prefix}bitrate and {prefix}bitrate_range"
|
||||
if value is not None and (not isinstance(value, str) or not re.fullmatch(r"\s*\d+\s*-\s*\d+\s*", value)):
|
||||
return f"{prefix}bitrate_range must be a string in 'MIN-MAX' format (e.g., '{example}')"
|
||||
|
||||
if data.get("quality") is not None:
|
||||
try:
|
||||
heights = QUALITY_LIST.convert(data["quality"])
|
||||
@@ -1922,38 +1884,6 @@ def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]:
|
||||
if not isinstance(data["imdb_id"], str) or not re.fullmatch(r"tt\d+", data["imdb_id"]):
|
||||
return "imdb_id must be an IMDB ID like 'tt1375666'"
|
||||
|
||||
if data.get("anilist_id") is not None:
|
||||
value = data["anilist_id"]
|
||||
# same parser as --anilist so both surfaces accept and reject the same inputs
|
||||
valid = not isinstance(value, bool) and isinstance(value, (int, str)) and parse_anilist_ref(value)
|
||||
if not valid:
|
||||
return "anilist_id must be a positive integer, or a MyAnimeList ID like 'mal:21'"
|
||||
|
||||
supplied_ids = [name for name in ("tmdb_id", "imdb_id", "tvdb_id") if data.get(name)]
|
||||
if len(supplied_ids) > 1:
|
||||
return f"Cannot use multiple external IDs: {', '.join(supplied_ids)}; give one ID"
|
||||
|
||||
exclusive_flags = []
|
||||
if data.get("video_only"):
|
||||
exclusive_flags.append("video_only")
|
||||
if data.get("audio_only"):
|
||||
exclusive_flags.append("audio_only")
|
||||
if data.get("subs_only"):
|
||||
exclusive_flags.append("subs_only")
|
||||
if data.get("chapters_only"):
|
||||
exclusive_flags.append("chapters_only")
|
||||
|
||||
if len(exclusive_flags) > 1:
|
||||
return f"Cannot use multiple exclusive flags: {', '.join(exclusive_flags)}"
|
||||
|
||||
if data.get("no_subs") and data.get("subs_only"):
|
||||
return "Cannot use both no_subs and subs_only"
|
||||
if data.get("no_audio") and data.get("audio_only"):
|
||||
return "Cannot use both no_audio and audio_only"
|
||||
conflict = kind_only_conflict(data)
|
||||
if conflict:
|
||||
return f"Cannot use both {conflict[0]} and {conflict[1]}"
|
||||
|
||||
for key, default in DEFAULT_DOWNLOAD_PARAMS.items():
|
||||
if isinstance(default, bool) and data.get(key) is not None and not isinstance(data[key], bool):
|
||||
return f"{key} must be a boolean"
|
||||
@@ -1972,11 +1902,11 @@ def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]:
|
||||
if value is not None and (not isinstance(value, list) or not all(isinstance(v, str) for v in value)):
|
||||
return f"{key} must be an array of language strings"
|
||||
|
||||
from unshackle.commands.dl import dl, subtitle_look
|
||||
from unshackle.commands.dl import subtitle_look
|
||||
|
||||
try:
|
||||
params = cast_dl_params(dl.cli, data)
|
||||
except click.BadParameter as e:
|
||||
params = api_plan(data).params
|
||||
except PlanError as e:
|
||||
return e.message
|
||||
|
||||
if params.get("sub_font"):
|
||||
@@ -2129,7 +2059,7 @@ async def download_handler(data: Dict[str, Any], request: Optional[web.Request]
|
||||
details={"service": service_tag},
|
||||
)
|
||||
|
||||
validation_error = validate_download_parameters(data)
|
||||
validation_error = await asyncio.to_thread(validate_download_parameters, data)
|
||||
if validation_error:
|
||||
raise APIError(
|
||||
APIErrorCode.INVALID_PARAMETERS,
|
||||
@@ -2141,22 +2071,13 @@ async def download_handler(data: Dict[str, Any], request: Optional[web.Request]
|
||||
service_module = None if server else Services.load(normalized_service)
|
||||
service_params: Optional[Dict[str, Any]] = None
|
||||
|
||||
# Service defaults and options travel nested: flat, a service default would overwrite the dl value of
|
||||
# the same name. Missing required __init__ params are handled in download_manager.perform_download.
|
||||
# A remote service applies its own defaults on the remote server.
|
||||
# Service options travel nested, so a flat key the worker reads stays a dl value; click fills the defaults
|
||||
# when the worker builds the service. A remote service applies its own on the remote server.
|
||||
cli_params = getattr(getattr(service_module, "cli", None), "params", None)
|
||||
if cli_params is not None:
|
||||
defaults = {
|
||||
param.name: param.default
|
||||
for param in cli_params
|
||||
if param.name and param.default is not None and not isinstance(param.default, enum.Enum)
|
||||
}
|
||||
# A flat dl key (quality, lang) stays a dl value, as in instantiate_service.
|
||||
sent = service_options(
|
||||
data, {param.name for param in cli_params}, FLAT_DL_KEYS | DEFAULT_DOWNLOAD_PARAMS.keys()
|
||||
)
|
||||
sent = service_options(data, {param.name for param in cli_params}, DL_TRANSPORT_KEYS)
|
||||
cast_or_refuse(cli_params, click.Context(click.Command(normalized_service)), sent)
|
||||
service_params = {**defaults, **sent}
|
||||
service_params = sent
|
||||
|
||||
filtered_params = {k: v for k, v in data.items() if k not in ["service", "title_id", "owner_key"]}
|
||||
# Overlay any dl-relevant keys from `serve:` config (e.g. downloads, workers) so the API
|
||||
@@ -3261,6 +3182,7 @@ async def env_check_handler(request: Optional[web.Request] = None) -> web.Respon
|
||||
|
||||
|
||||
# "client" stays out: a flat "client" value with no service_params is a service option.
|
||||
DL_TRANSPORT_KEYS = FLAT_DL_KEYS | DEFAULT_DOWNLOAD_PARAMS.keys()
|
||||
SESSION_TRANSPORT_KEYS = (SessionCreate.__required_keys__ | SessionCreate.__optional_keys__) - {"client"}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user