mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-25 10:25:09 +00:00
refactor(api): keep the dl option facts in one table in core/dl_options.py
This commit is contained in:
@@ -18,8 +18,8 @@ import requests
|
||||
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.api.handlers import DEFAULT_DOWNLOAD_PARAMS
|
||||
from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY
|
||||
from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS
|
||||
from unshackle.core.service import Service
|
||||
from unshackle.core.titles import Episode, Series
|
||||
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
|
||||
|
||||
@@ -5,7 +5,7 @@ import inspect
|
||||
import pytest
|
||||
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.api.handlers import DEFAULT_DOWNLOAD_PARAMS, cast_dl_params
|
||||
from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS, cast_dl_params
|
||||
from unshackle.core.utilities import missing_required_langs
|
||||
|
||||
|
||||
|
||||
@@ -1,41 +1,56 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import logging
|
||||
|
||||
import click
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.api.handlers import (
|
||||
from unshackle.core.api import routes
|
||||
from unshackle.core.api.handlers import validate_download_parameters
|
||||
from unshackle.core.dl_options import (
|
||||
API_SHAPED_DL_PARAMS,
|
||||
DEFAULT_DOWNLOAD_PARAMS,
|
||||
DL_OPTION_ALIASES,
|
||||
DL_OPTIONS,
|
||||
FORWARDED_DL_PARAMS,
|
||||
cast_dl_params,
|
||||
validate_download_parameters,
|
||||
forwarded_dl_params,
|
||||
remote_dl_params,
|
||||
)
|
||||
from unshackle.core.tracks import Video
|
||||
from unshackle.core.tracks import Audio, Subtitle, Video
|
||||
|
||||
CLI_ONLY = {
|
||||
"select_titles",
|
||||
"list_",
|
||||
"list_titles",
|
||||
"import_file",
|
||||
"cdm_name",
|
||||
"remote",
|
||||
"server",
|
||||
"local_proxy",
|
||||
"postscript",
|
||||
"no_postscript",
|
||||
"merge_video",
|
||||
"real_video_bitrate",
|
||||
"real_audio_bitrate",
|
||||
"speed_limit",
|
||||
}
|
||||
CLI_ONLY = {DL_OPTION_ALIASES.get(name, name) for name, option in DL_OPTIONS.items() if option is None}
|
||||
|
||||
|
||||
def test_every_dl_option_is_an_api_param_or_cli_only():
|
||||
"""A new dl option fails here until it is added to DEFAULT_DOWNLOAD_PARAMS or to CLI_ONLY."""
|
||||
api_names = set(cast_dl_params(dl.cli, {}))
|
||||
def test_the_table_decides_every_dl_option():
|
||||
"""A new dl option fails here until DL_OPTIONS says whether the REST API takes it."""
|
||||
cli_names = {p.name for p in dl.cli.params}
|
||||
assert api_names - cli_names == set()
|
||||
assert cli_names - api_names == CLI_ONLY
|
||||
assert {DL_OPTION_ALIASES.get(name, name) for name in DL_OPTIONS} == cli_names
|
||||
assert set(cast_dl_params(dl.cli, {})) == cli_names - CLI_ONLY
|
||||
|
||||
|
||||
def test_the_openapi_yaml_names_each_api_dl_option_and_no_other():
|
||||
"""The download request body documents every dl option the API takes, beside its own request keys."""
|
||||
schema = yaml.safe_load((routes.download.__doc__ or "").split("---", 1)[1])
|
||||
properties = schema["requestBody"]["content"]["application/json"]["schema"]["properties"]
|
||||
assert DEFAULT_DOWNLOAD_PARAMS.keys() <= properties.keys()
|
||||
assert properties.keys() - DEFAULT_DOWNLOAD_PARAMS.keys() == {"service", "title_id", "remote", "client_name", "cdm"}
|
||||
|
||||
|
||||
def test_the_server_reads_back_what_a_remote_client_forwards():
|
||||
params = {
|
||||
"lang": ["orig", "es-419"],
|
||||
"v_lang": [],
|
||||
"a_lang": ["en"],
|
||||
"s_lang": ["all"],
|
||||
"acodec": [Audio.Codec.EC3],
|
||||
"forced_subs": True,
|
||||
"exact_lang": True,
|
||||
}
|
||||
assert forwarded_dl_params({"dl_params": remote_dl_params(params)}) == params
|
||||
|
||||
|
||||
def test_api_defaults_cast_to_the_dl_defaults():
|
||||
@@ -69,11 +84,86 @@ def test_range_takes_the_api_spellings(value, expected):
|
||||
|
||||
|
||||
def test_values_are_cast_by_the_dl_click_types():
|
||||
cast = cast_dl_params(dl.cli, {"quality": "1080p,720", "vcodec": "H265", "acodec": ["EC3"], "sample": True})
|
||||
cast = cast_dl_params(
|
||||
dl.cli,
|
||||
{
|
||||
"quality": "1080p,720",
|
||||
"vcodec": "H265",
|
||||
"acodec": ["EC3"],
|
||||
"range": ["HDR10+", "dv"],
|
||||
"lang": ["en"],
|
||||
"slow": "20-40",
|
||||
"wanted": ["S01E01"],
|
||||
"downloads": 3,
|
||||
"sub_format": "srt",
|
||||
"output_dir": "",
|
||||
"cdm_only": False,
|
||||
"sample": "0-60",
|
||||
"tvdb_order": "dvd",
|
||||
},
|
||||
)
|
||||
assert cast["quality"] == [1080, 720]
|
||||
assert cast["vcodec"] == [Video.Codec.HEVC]
|
||||
assert [c.name for c in cast["acodec"]] == ["EC3"]
|
||||
assert cast["sample"] is not None
|
||||
assert cast["acodec"] == [Audio.Codec.EC3]
|
||||
assert cast["range_"] == [Video.Range.HDR10P, Video.Range.DV]
|
||||
assert cast["lang"] == ["en"]
|
||||
assert (cast["slow"], cast["wanted"]) == ("20-40", ["S01E01"])
|
||||
assert (cast["downloads"], cast["sample"], cast["tvdb_order"]) == (3, (0, 60), "dvd")
|
||||
assert cast["sub_format"] is Subtitle.Codec.SubRip
|
||||
assert (cast["output_dir"], cast["cdm_only"], cast["s_lang"]) == (None, False, ["all"])
|
||||
|
||||
|
||||
def test_every_dl_option_reaches_dl_result():
|
||||
"""An option outside the dl.__init__ and dl.result signatures is read from ctx.params elsewhere."""
|
||||
named = set(inspect.signature(dl.__init__).parameters) | set(inspect.signature(dl.result).parameters)
|
||||
assert {p.name for p in dl.cli.params} - named == {
|
||||
"server",
|
||||
"remote",
|
||||
"local_proxy",
|
||||
"reset_cache",
|
||||
"no_cache",
|
||||
"cdm_name",
|
||||
"import_file",
|
||||
}
|
||||
|
||||
|
||||
def test_the_server_reads_the_forwarded_dl_params(caplog):
|
||||
data = {
|
||||
"dl_params": {"a_lang": "x", "acodec": ["ddp", "NOPE"], "exact_lang": 1, "forced_subs": True, "lang": ["en"]}
|
||||
}
|
||||
with caplog.at_level(logging.WARNING, logger="api"):
|
||||
assert list(forwarded_dl_params(data).items()) == [
|
||||
("lang", ["en"]),
|
||||
("v_lang", []),
|
||||
("a_lang", []),
|
||||
("s_lang", ["all"]),
|
||||
("acodec", [Audio.Codec.EC3]),
|
||||
("forced_subs", True),
|
||||
("exact_lang", False),
|
||||
]
|
||||
assert [(r.name, r.getMessage()) for r in caplog.records] == [
|
||||
("api", "Ignoring dl_params.a_lang: it must be an array of strings"),
|
||||
("api", "Ignoring unknown dl_params.acodec value: NOPE"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"parent_params,sent",
|
||||
[
|
||||
(
|
||||
{"lang": ["orig"], "v_lang": None, "a_lang": [], "s_lang": ["all"], "acodec": None, "forced_subs": 0},
|
||||
{"lang": ["orig"], "a_lang": [], "s_lang": ["all"], "forced_subs": False},
|
||||
),
|
||||
({"exact_lang": None, "quality": [1080]}, {"exact_lang": False}),
|
||||
],
|
||||
)
|
||||
def test_the_client_sends_what_it_has_a_value_for(parent_params, sent):
|
||||
assert remote_dl_params(parent_params) == sent
|
||||
|
||||
|
||||
def test_no_forwarded_option_has_an_alias():
|
||||
"""remote_dl_params reads the API name from the click context, so an aliased option cannot be forwarded."""
|
||||
assert not {name for name, _ in FORWARDED_DL_PARAMS} & DL_OPTION_ALIASES.keys()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", ["lang", "v_lang", "a_lang", "s_lang", "forced_s_lang"])
|
||||
|
||||
@@ -10,6 +10,7 @@ import pytest
|
||||
from unshackle.core.api import download_manager as dm
|
||||
from unshackle.core.api import handlers
|
||||
from unshackle.core.api.errors import APIError, APIErrorCode
|
||||
from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
@@ -91,10 +92,10 @@ def test_relayed_job_skips_service_dl(env, monkeypatch):
|
||||
return "remote-server", {"tag": "EXAMPLE1"}, data
|
||||
|
||||
monkeypatch.setattr(handlers, "relay_target", relay)
|
||||
baseline_workers = handlers.DEFAULT_DOWNLOAD_PARAMS["workers"]
|
||||
baseline_workers = DEFAULT_DOWNLOAD_PARAMS["workers"]
|
||||
params = env(dl={"workers": 7})
|
||||
assert params["workers"] == baseline_workers
|
||||
assert set(params["client_keys"]) >= set(handlers.DEFAULT_DOWNLOAD_PARAMS)
|
||||
assert set(params["client_keys"]) >= set(DEFAULT_DOWNLOAD_PARAMS)
|
||||
|
||||
|
||||
def test_client_sent_keys_uses_the_stamp():
|
||||
|
||||
@@ -138,7 +138,7 @@ def test_job_status_values() -> None:
|
||||
def test_api_sub_format_keeps_the_original_sentinel() -> None:
|
||||
"""sub_format "original" keeps the source format, so the API cast must not turn it into a codec or None."""
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.api.handlers import cast_dl_params
|
||||
from unshackle.core.dl_options import cast_dl_params
|
||||
from unshackle.core.tracks import Subtitle
|
||||
|
||||
assert cast_dl_params(dl.cli, {"sub_format": "ORIGINAL"})["sub_format"] == "original"
|
||||
|
||||
@@ -50,6 +50,7 @@ from unshackle.core.constants import (
|
||||
context_settings,
|
||||
)
|
||||
from unshackle.core.credential import Credential
|
||||
from unshackle.core.dl_options import DL_OPTION_ALIASES
|
||||
from unshackle.core.downloaders import (
|
||||
default_max_workers,
|
||||
format_speed,
|
||||
@@ -157,10 +158,6 @@ class SkippedSubtitle(TypedDict):
|
||||
title: str
|
||||
|
||||
|
||||
# Config keys accepted as natural names for params whose Python name dodges a builtin.
|
||||
DL_OPTION_ALIASES = {"range": "range_", "list": "list_"}
|
||||
|
||||
|
||||
def parse_language(tag: Optional[str]) -> Optional[Language]:
|
||||
"""A provider's original-language tag as a Language, or None if it is absent or not a real tag."""
|
||||
tag = (tag or "").strip()
|
||||
|
||||
@@ -430,7 +430,8 @@ def perform_download(
|
||||
|
||||
ctx = click.Context(dl_command.cli)
|
||||
ctx.invoked_subcommand = service
|
||||
from unshackle.core.api.handlers import cast_dl_params, load_full_cdm, relay_label
|
||||
from unshackle.core.api.handlers import load_full_cdm, relay_label
|
||||
from unshackle.core.dl_options import DL_OPTION_API_NAMES, cast_dl_params
|
||||
|
||||
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"))
|
||||
@@ -451,7 +452,7 @@ def perform_download(
|
||||
from click.core import ParameterSource
|
||||
|
||||
for param_name in ctx.params:
|
||||
source_key = "range" if param_name == "range_" else param_name
|
||||
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
|
||||
)
|
||||
|
||||
@@ -17,7 +17,7 @@ from dataclasses import dataclass, field
|
||||
from functools import partial
|
||||
from http.cookiejar import CookieJar
|
||||
from pathlib import Path
|
||||
from typing import AbstractSet, Any, Callable, Dict, Iterable, List, Optional, Set, cast
|
||||
from typing import AbstractSet, Any, Callable, Dict, Iterable, List, Optional, Set
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import click
|
||||
@@ -35,6 +35,12 @@ from unshackle.core.cacher import Cacher
|
||||
from unshackle.core.cdm.detect import cdm_type_stub, is_playready_cdm
|
||||
from unshackle.core.config import config, load_yaml
|
||||
from unshackle.core.constants import AnyTrack
|
||||
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
|
||||
from unshackle.core.manifests.snapshot import capture
|
||||
from unshackle.core.providers.anilist import parse_anilist_ref
|
||||
@@ -54,7 +60,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 AUDIO_CODEC_LIST, QUALITY_LIST, VIDEO_CODEC_LIST
|
||||
from unshackle.core.utils.click_types import QUALITY_LIST, VIDEO_CODEC_LIST
|
||||
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
|
||||
@@ -70,113 +76,6 @@ from unshackle.core.wire import (
|
||||
log = logging.getLogger("api")
|
||||
|
||||
|
||||
DEFAULT_DOWNLOAD_PARAMS = {
|
||||
"profile": None,
|
||||
"quality": [],
|
||||
"vcodec": [],
|
||||
"acodec": [],
|
||||
"vbitrate": None,
|
||||
"abitrate": None,
|
||||
"vbitrate_range": None,
|
||||
"abitrate_range": None,
|
||||
"range": ["SDR"],
|
||||
"channels": None,
|
||||
"no_atmos": False,
|
||||
"wanted": [],
|
||||
"latest_episode": False,
|
||||
"latest_episodes": None,
|
||||
"lang": ["orig"],
|
||||
"v_lang": [],
|
||||
"a_lang": [],
|
||||
"s_lang": ["all"],
|
||||
"require_audio": [],
|
||||
"require_video": [],
|
||||
"require_subs": [],
|
||||
"skip_missing": False,
|
||||
"forced_subs": False,
|
||||
"forced_subs_only": False,
|
||||
"forced_s_lang": [],
|
||||
"exact_lang": False,
|
||||
"sub_format": None,
|
||||
"sub_font": None,
|
||||
"video_only": False,
|
||||
"audio_only": False,
|
||||
"subs_only": False,
|
||||
"chapters_only": False,
|
||||
"no_subs": False,
|
||||
"skip_subtitle_errors": False,
|
||||
"no_audio": False,
|
||||
"no_chapters": False,
|
||||
"no_video": False,
|
||||
"no_attachments": False,
|
||||
"audio_description": False,
|
||||
"audio_description_only": False,
|
||||
"slow": None,
|
||||
"split_audio": None,
|
||||
"skip_dl": False,
|
||||
"all_drm": False,
|
||||
"export": False,
|
||||
"cdm_only": None,
|
||||
"proxy": None,
|
||||
"no_proxy": False,
|
||||
"no_proxy_download": False,
|
||||
"proxy_download": None,
|
||||
"no_folder": False,
|
||||
"no_source": False,
|
||||
"no_mux": False,
|
||||
"sample": None,
|
||||
"include_sample": False,
|
||||
"workers": None,
|
||||
"adaptive_workers": False,
|
||||
"download_processes": 1,
|
||||
"continue_downloads": False,
|
||||
"downloads": 1,
|
||||
"worst": False,
|
||||
"best_available": False,
|
||||
"generate_dv": False,
|
||||
"repack": False,
|
||||
"tag": None,
|
||||
"tmdb_id": None,
|
||||
"imdb_id": None,
|
||||
"tvdb_id": None,
|
||||
"tvdb_order": None,
|
||||
"continuous_episodes": False,
|
||||
"anilist_id": None,
|
||||
"enrich": False,
|
||||
"daily": False,
|
||||
"output_dir": None,
|
||||
"no_cache": False,
|
||||
"reset_cache": False,
|
||||
}
|
||||
|
||||
API_SHAPED_DL_PARAMS = frozenset({"slow", "wanted"})
|
||||
|
||||
|
||||
def cast_dl_params(cli: click.Command, params: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Cast each ``DEFAULT_DOWNLOAD_PARAMS`` parameter in ``params`` by its dl click type, under its dl option name.
|
||||
|
||||
A missing, ``None`` or empty-string parameter, and an empty ``range``, take the API default, so
|
||||
``output_dir: ""`` is not the working directory. An ``API_SHAPED_DL_PARAMS`` value stays as sent. A parameter
|
||||
outside ``DEFAULT_DOWNLOAD_PARAMS`` never reaches dl, so a new CLI option is closed to API clients by default.
|
||||
Raises ``click.BadParameter``.
|
||||
"""
|
||||
from unshackle.commands.dl import DL_OPTION_ALIASES
|
||||
|
||||
kept: Dict[str, Any] = {}
|
||||
to_cast: Dict[str, Any] = {}
|
||||
for key, default in DEFAULT_DOWNLOAD_PARAMS.items():
|
||||
value = params.get(key)
|
||||
if value is None or value == "" or (key == "range" and value == []):
|
||||
value = default
|
||||
(kept if value is None or key in API_SHAPED_DL_PARAMS else to_cast)[DL_OPTION_ALIASES.get(key, key)] = value
|
||||
try:
|
||||
return {**kept, **cast_service_options(cli.params, click.Context(cli), to_cast)}
|
||||
except click.BadParameter as e:
|
||||
name = (e.param.name if e.param else None) or ""
|
||||
key = next((k for k, v in DL_OPTION_ALIASES.items() if v == name), name)
|
||||
raise click.BadParameter(f"Invalid {key}: {e.message}") from e
|
||||
|
||||
|
||||
# Keys that are part of the API transport envelope, not service.cli options.
|
||||
# Used by instantiate_service to avoid passing them as kwargs to a service.
|
||||
LIST_HANDLER_TRANSPORT_KEYS = {
|
||||
@@ -2216,13 +2115,11 @@ def enforce_download_gates(params: Dict[str, Any], request: Optional[web.Request
|
||||
|
||||
def service_dl_defaults(service: str) -> Dict[str, Any]:
|
||||
"""The ``services.<TAG>.dl`` values that name an API download parameter, keyed as the API names them."""
|
||||
from unshackle.commands.dl import DL_OPTION_ALIASES
|
||||
from unshackle.core.services import ROUTING_PARAMS
|
||||
|
||||
api_names = {click_name: api_name for api_name, click_name in DL_OPTION_ALIASES.items()}
|
||||
result: Dict[str, Any] = {}
|
||||
for key, value in ((ci_get(config.services, service) or {}).get("dl") or {}).items():
|
||||
key = api_names.get(key, key)
|
||||
key = DL_OPTION_API_NAMES.get(key, key)
|
||||
if value is None or key in ROUTING_PARAMS:
|
||||
continue
|
||||
if key not in DEFAULT_DOWNLOAD_PARAMS:
|
||||
@@ -3431,44 +3328,6 @@ SESSION_TRANSPORT_KEYS = {
|
||||
}
|
||||
|
||||
|
||||
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) -> Optional[List[str]]:
|
||||
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 in ("lang", "v_lang", "a_lang", "s_lang"):
|
||||
langs = str_list(key)
|
||||
params[key] = langs if langs is not None else list(cast(List[str], DEFAULT_DOWNLOAD_PARAMS[key]))
|
||||
# the dl CLI default is [], and some services test membership in it
|
||||
params["acodec"] = []
|
||||
for name in str_list("acodec") or []:
|
||||
try:
|
||||
params["acodec"].extend(AUDIO_CODEC_LIST.convert(name))
|
||||
except click.BadParameter:
|
||||
log.warning(f"Ignoring unknown dl_params.acodec value: {sanitize_log(name)}")
|
||||
params["forced_subs"] = raw.get("forced_subs") is True
|
||||
params["exact_lang"] = raw.get("exact_lang") is True
|
||||
return params
|
||||
|
||||
|
||||
# A client's service config carries a device identity (an ESN, a few keys), never a bulk payload.
|
||||
MAX_CLIENT_CONFIG_BYTES = 16384
|
||||
|
||||
|
||||
@@ -959,6 +959,16 @@ async def download(request: web.Request) -> web.Response:
|
||||
abitrate:
|
||||
type: integer
|
||||
description: Audio bitrate in kbps (default - None)
|
||||
vbitrate_range:
|
||||
type: string
|
||||
description: >-
|
||||
Video bitrate range in kbps as "MIN-MAX" (e.g., "6000-7000"). Selects the highest bitrate in the
|
||||
range. Cannot be used with vbitrate (default - None)
|
||||
abitrate_range:
|
||||
type: string
|
||||
description: >-
|
||||
Audio bitrate range in kbps as "MIN-MAX" (e.g., "128-256"). Selects the highest bitrate in the
|
||||
range. Cannot be used with abitrate (default - None)
|
||||
range:
|
||||
type: array
|
||||
items:
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
"""The dl option table: which dl options the REST API takes, their API defaults, and what a remote client forwards."""
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Dict, List, Literal, Mapping, Optional, 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()}
|
||||
|
||||
RemoteKind = Literal["langs", "audio_codecs", "flag"]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ApiOption:
|
||||
"""A dl option that a REST API client can set, with its API default.
|
||||
|
||||
``raw`` keeps the API value uncast, because perform_download parses it. ``remote`` names how a remote client
|
||||
sends the option to the server in ``dl_params``, for a service that reads it from ``ctx.parent.params``.
|
||||
"""
|
||||
|
||||
default: Any
|
||||
raw: bool = False
|
||||
remote: Optional[RemoteKind] = None
|
||||
|
||||
|
||||
CLI_ONLY = None
|
||||
|
||||
DL_OPTIONS: Dict[str, Optional[ApiOption]] = {
|
||||
"profile": ApiOption(None),
|
||||
"quality": ApiOption([]),
|
||||
"vcodec": ApiOption([]),
|
||||
"acodec": ApiOption([], remote="audio_codecs"),
|
||||
"vbitrate": ApiOption(None),
|
||||
"abitrate": ApiOption(None),
|
||||
"vbitrate_range": ApiOption(None),
|
||||
"abitrate_range": ApiOption(None),
|
||||
"range": ApiOption(["SDR"]),
|
||||
"channels": ApiOption(None),
|
||||
"no_atmos": ApiOption(False),
|
||||
"wanted": ApiOption([], raw=True),
|
||||
"latest_episode": ApiOption(False),
|
||||
"latest_episodes": ApiOption(None),
|
||||
"lang": ApiOption(["orig"], remote="langs"),
|
||||
"v_lang": ApiOption([], remote="langs"),
|
||||
"a_lang": ApiOption([], remote="langs"),
|
||||
"s_lang": ApiOption(["all"], remote="langs"),
|
||||
"require_audio": ApiOption([]),
|
||||
"require_video": ApiOption([]),
|
||||
"require_subs": ApiOption([]),
|
||||
"skip_missing": ApiOption(False),
|
||||
"forced_subs": ApiOption(False, remote="flag"),
|
||||
"forced_subs_only": ApiOption(False),
|
||||
"forced_s_lang": ApiOption([]),
|
||||
"exact_lang": ApiOption(False, remote="flag"),
|
||||
"sub_format": ApiOption(None),
|
||||
"sub_font": ApiOption(None),
|
||||
"video_only": ApiOption(False),
|
||||
"audio_only": ApiOption(False),
|
||||
"subs_only": ApiOption(False),
|
||||
"chapters_only": ApiOption(False),
|
||||
"no_subs": ApiOption(False),
|
||||
"skip_subtitle_errors": ApiOption(False),
|
||||
"no_audio": ApiOption(False),
|
||||
"no_chapters": ApiOption(False),
|
||||
"no_video": ApiOption(False),
|
||||
"no_attachments": ApiOption(False),
|
||||
"audio_description": ApiOption(False),
|
||||
"audio_description_only": ApiOption(False),
|
||||
"slow": ApiOption(None, raw=True),
|
||||
"split_audio": ApiOption(None),
|
||||
"skip_dl": ApiOption(False),
|
||||
"all_drm": ApiOption(False),
|
||||
"export": ApiOption(False),
|
||||
"cdm_only": ApiOption(None),
|
||||
"proxy": ApiOption(None),
|
||||
"no_proxy": ApiOption(False),
|
||||
"no_proxy_download": ApiOption(False),
|
||||
"proxy_download": ApiOption(None),
|
||||
"no_folder": ApiOption(False),
|
||||
"no_source": ApiOption(False),
|
||||
"no_mux": ApiOption(False),
|
||||
"sample": ApiOption(None),
|
||||
"include_sample": ApiOption(False),
|
||||
"workers": ApiOption(None),
|
||||
"adaptive_workers": ApiOption(False),
|
||||
"download_processes": ApiOption(1),
|
||||
"continue_downloads": ApiOption(False),
|
||||
"downloads": ApiOption(1),
|
||||
"worst": ApiOption(False),
|
||||
"best_available": ApiOption(False),
|
||||
"generate_dv": ApiOption(False),
|
||||
"repack": ApiOption(False),
|
||||
"tag": ApiOption(None),
|
||||
"tmdb_id": ApiOption(None),
|
||||
"imdb_id": ApiOption(None),
|
||||
"tvdb_id": ApiOption(None),
|
||||
"tvdb_order": ApiOption(None),
|
||||
"continuous_episodes": ApiOption(False),
|
||||
"anilist_id": ApiOption(None),
|
||||
"enrich": ApiOption(False),
|
||||
"daily": ApiOption(False),
|
||||
"output_dir": ApiOption(None),
|
||||
"no_cache": ApiOption(False),
|
||||
"reset_cache": ApiOption(False),
|
||||
"select_titles": CLI_ONLY,
|
||||
"list": CLI_ONLY,
|
||||
"list_titles": CLI_ONLY,
|
||||
"import_file": CLI_ONLY,
|
||||
"cdm_name": CLI_ONLY,
|
||||
"remote": CLI_ONLY,
|
||||
"server": CLI_ONLY,
|
||||
"local_proxy": CLI_ONLY,
|
||||
"postscript": CLI_ONLY,
|
||||
"no_postscript": CLI_ONLY,
|
||||
"merge_video": CLI_ONLY,
|
||||
"real_video_bitrate": CLI_ONLY,
|
||||
"real_audio_bitrate": CLI_ONLY,
|
||||
"speed_limit": CLI_ONLY,
|
||||
}
|
||||
"""Every dl option, by its API and config name (``DL_OPTION_ALIASES`` gives the click name where it differs).
|
||||
|
||||
An option the REST API takes has an ``ApiOption``; a ``CLI_ONLY`` option never reaches dl from the API.
|
||||
"""
|
||||
|
||||
DEFAULT_DOWNLOAD_PARAMS: Dict[str, Any] = {name: option.default for name, option in DL_OPTIONS.items() if option}
|
||||
API_SHAPED_DL_PARAMS = frozenset(name for name, option in DL_OPTIONS.items() if option and option.raw)
|
||||
FORWARDED_DL_PARAMS = [
|
||||
(name, option)
|
||||
for kind in get_args(RemoteKind)
|
||||
for name, option in DL_OPTIONS.items()
|
||||
if option and option.remote == kind
|
||||
]
|
||||
|
||||
|
||||
def cast_dl_params(cli: click.Command, params: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Cast each ``DEFAULT_DOWNLOAD_PARAMS`` parameter in ``params`` by its dl click type, under its dl option name.
|
||||
|
||||
A missing, ``None`` or empty-string parameter, and an empty ``range``, take the API default, so
|
||||
``output_dir: ""`` is not the working directory. An ``API_SHAPED_DL_PARAMS`` value stays as sent. A parameter
|
||||
outside ``DEFAULT_DOWNLOAD_PARAMS`` never reaches dl, so a new CLI option is closed to API clients by default.
|
||||
Raises ``click.BadParameter``.
|
||||
"""
|
||||
kept: Dict[str, Any] = {}
|
||||
to_cast: Dict[str, Any] = {}
|
||||
for key, default in DEFAULT_DOWNLOAD_PARAMS.items():
|
||||
value = params.get(key)
|
||||
if value is None or value == "" or (key == "range" and value == []):
|
||||
value = default
|
||||
(kept if value is None or key in API_SHAPED_DL_PARAMS else to_cast)[DL_OPTION_ALIASES.get(key, key)] = value
|
||||
try:
|
||||
return {**kept, **cast_service_options(cli.params, click.Context(cli), to_cast)}
|
||||
except click.BadParameter as e:
|
||||
name = (e.param.name if e.param else None) or ""
|
||||
key = DL_OPTION_API_NAMES.get(name, name)
|
||||
raise click.BadParameter(f"Invalid {key}: {e.message}") from e
|
||||
|
||||
|
||||
def remote_dl_params(params: Mapping[str, Any]) -> Dict[str, Any]:
|
||||
"""The ``dl_params`` a remote client sends when it creates a remote session, from its dl context params.
|
||||
|
||||
An empty list is sent as-is, because only an absent key falls back to the dl default on the server.
|
||||
"""
|
||||
sent: Dict[str, Any] = {}
|
||||
for key, option in FORWARDED_DL_PARAMS:
|
||||
if option.remote == "flag":
|
||||
if key in params:
|
||||
sent[key] = bool(params[key])
|
||||
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) -> Optional[List[str]]:
|
||||
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
|
||||
@@ -38,6 +38,7 @@ from unshackle.core.config import config
|
||||
from unshackle.core.console import SyncLive, console, prompt_user, show_notice
|
||||
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.manifests.snapshot import match_track, restore
|
||||
from unshackle.core.proxies.resolve import is_loopback
|
||||
@@ -1027,18 +1028,7 @@ class RemoteService:
|
||||
create_data["generate_dv"] = True
|
||||
# Services pick the manifests to fetch from these. They go in their own
|
||||
# object: flat, a service option with the same name would take them (or override them).
|
||||
# An empty list is sent as-is, because only an absent key falls back to the dl default.
|
||||
params = self.ctx.parent.params
|
||||
dl_params: dict[str, Any] = {
|
||||
key: [str(x) for x in params[key]]
|
||||
for key in ("lang", "v_lang", "a_lang", "s_lang")
|
||||
if params.get(key) is not None
|
||||
}
|
||||
if params.get("acodec") is not None:
|
||||
dl_params["acodec"] = [c.name for c in params["acodec"]]
|
||||
for key in ("forced_subs", "exact_lang"):
|
||||
if key in params:
|
||||
dl_params[key] = bool(params[key])
|
||||
dl_params = remote_dl_params(self.ctx.parent.params)
|
||||
if dl_params:
|
||||
create_data["dl_params"] = dl_params
|
||||
|
||||
|
||||
Reference in New Issue
Block a user