forked from kenzuya/unshackle
refactor(api): give every served service its dl options from the run plan
This commit is contained in:
@@ -154,6 +154,7 @@ For a service with `anonymous_search`, the server does not log in and ignores `c
|
|||||||
| `proxy` | string | no | `null` | Full proxy URI on a public host, a Control D resolver as `controld://<resolver>@dns.controld.com`, or a country code when the API key has `server_proxy`. |
|
| `proxy` | string | no | `null` | Full proxy URI on a public host, a Control D resolver as `controld://<resolver>@dns.controld.com`, or a country code when the API key has `server_proxy`. |
|
||||||
| `no_proxy` | boolean | no | `false` | Force-disable all proxy use. |
|
| `no_proxy` | boolean | no | `false` | Force-disable all proxy use. |
|
||||||
| `credentials`, `cookies`, `cache` | - | no | `null` | Your own login material, on a `--remote-only` server only. See [Client cache on a remote-only server](#client-cache-on-a-remote-only-server). |
|
| `credentials`, `cookies`, `cache` | - | no | `null` | Your own login material, on a `--remote-only` server only. See [Client cache on a remote-only server](#client-cache-on-a-remote-only-server). |
|
||||||
|
| `dl_params` | object | no | `null` | The `dl` track selection, as on [`POST /api/session/create`](#post-apisessioncreate). |
|
||||||
|
|
||||||
=== "Request"
|
=== "Request"
|
||||||
|
|
||||||
@@ -301,6 +302,7 @@ These keys are sent only when the title carries them, so a title without them se
|
|||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `200` | - | Titles returned. |
|
| `200` | - | Titles returned. |
|
||||||
| `400` | `INVALID_INPUT` | Missing `service` or `title_id`. |
|
| `400` | `INVALID_INPUT` | Missing `service` or `title_id`. |
|
||||||
|
| `400` | `INVALID_PARAMETERS` | Invalid `dl` value, such as an unknown codec in `dl_params`. |
|
||||||
| `400` | `INVALID_SERVICE` | Unknown or disallowed service. |
|
| `400` | `INVALID_SERVICE` | Unknown or disallowed service. |
|
||||||
| `401` | `AUTH_FAILED` | Authentication with the service failed. |
|
| `401` | `AUTH_FAILED` | Authentication with the service failed. |
|
||||||
| `404` | `NOT_FOUND` | Title not found. |
|
| `404` | `NOT_FOUND` | Title not found. |
|
||||||
@@ -392,7 +394,7 @@ Every track carries the same fields as a local track: `is_original_lang`, `name`
|
|||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `200` | - | Tracks returned. |
|
| `200` | - | Tracks returned. |
|
||||||
| `400` | `INVALID_INPUT` | Missing `service` or `title_id`. |
|
| `400` | `INVALID_INPUT` | Missing `service` or `title_id`. |
|
||||||
| `400` | `INVALID_PARAMETERS` | Invalid `wanted` range. |
|
| `400` | `INVALID_PARAMETERS` | Invalid `wanted` range, or an invalid `dl` value. |
|
||||||
| `400` | `INVALID_SERVICE` | Unknown or disallowed service. |
|
| `400` | `INVALID_SERVICE` | Unknown or disallowed service. |
|
||||||
| `404` | `NO_CONTENT` | No matching episodes, or all matches failed. |
|
| `404` | `NO_CONTENT` | No matching episodes, or all matches failed. |
|
||||||
|
|
||||||
@@ -986,7 +988,7 @@ the newlines must go out at once.
|
|||||||
|
|
||||||
Make a remote session for a service and title. Authentication runs asynchronously in the background. This call returns immediately with `status: "authenticating"`, and you then poll the prompt endpoint. The body accepts `service` and `title_id` (both required). It also accepts a broad set of optional keys, because the body allows `additionalProperties`. These are `credentials` (`{username, password, extra?}`), `cookies` (base64 of zlib-compressed Netscape cookie file), `proxy`, `no_proxy`, `profile`, `cache` (map of forwarded cache files, keyed by the file path relative to the service cache directory with `/` separators and no `.json` suffix, so a nested key such as `session_web/<sha1>` lands in a subdirectory), `client_region`, `proxy_region`, `cdm_type`, `range_`, `vcodec`, `quality`, `best_available`, `dl_params`, `client`, and any service CLI options. `proxy_region` is the country code the client resolved `proxy` from; the server matches it against its own accounts. `client` is a freeform object the dashboard shows as sent (the CLI puts `version`, `code_hash`, `platform` and a redacted `argv` in it); the server ignores it above 4096 bytes of JSON.
|
Make a remote session for a service and title. Authentication runs asynchronously in the background. This call returns immediately with `status: "authenticating"`, and you then poll the prompt endpoint. The body accepts `service` and `title_id` (both required). It also accepts a broad set of optional keys, because the body allows `additionalProperties`. These are `credentials` (`{username, password, extra?}`), `cookies` (base64 of zlib-compressed Netscape cookie file), `proxy`, `no_proxy`, `profile`, `cache` (map of forwarded cache files, keyed by the file path relative to the service cache directory with `/` separators and no `.json` suffix, so a nested key such as `session_web/<sha1>` lands in a subdirectory), `client_region`, `proxy_region`, `cdm_type`, `range_`, `vcodec`, `quality`, `best_available`, `dl_params`, `client`, and any service CLI options. `proxy_region` is the country code the client resolved `proxy` from; the server matches it against its own accounts. `client` is a freeform object the dashboard shows as sent (the CLI puts `version`, `code_hash`, `platform` and a redacted `argv` in it); the server ignores it above 4096 bytes of JSON.
|
||||||
|
|
||||||
`dl_params` is an object with the `dl` track selection: `lang`, `v_lang`, `a_lang` and `s_lang` (arrays of language strings), `acodec` (an array of audio codec names or `dl -a` aliases such as `ddp`), and `forced_subs` and `exact_lang` (booleans). The service reads these values from `ctx.parent.params`. The server uses the `dl` default for each absent or malformed value, and drops an unknown codec name.
|
`dl_params` is an object with the `dl` track selection: `lang`, `v_lang`, `a_lang` and `s_lang` (arrays of language strings), `acodec` (an array of audio codec names or `dl -a` aliases such as `ddp`), and `forced_subs` and `exact_lang` (booleans). The service reads these values from `ctx.parent.params`. The server uses the `dl` default for each absent value. It refuses a malformed value, an unknown codec, range or vcodec name, and a height of 0 or less with `INVALID_PARAMETERS`. The flat `range_`, `vcodec`, `quality`, `best_available` and `generate_dv` keys are `dl` values on this route. On the list and search routes they are `dl` values only when the body has `service_params`.
|
||||||
|
|
||||||
Service CLI options also travel in a nested `service_params` object. When the body has `service_params`, the server reads service options only from it, and a flat key with the same name stays a `dl` value. `profile` at the top level always means the credentials profile, never a service's own `--profile` option.
|
Service CLI options also travel in a nested `service_params` object. When the body has `service_params`, the server reads service options only from it, and a flat key with the same name stays a `dl` value. `profile` at the top level always means the credentials profile, never a service's own `--profile` option.
|
||||||
|
|
||||||
@@ -1009,6 +1011,7 @@ The `proxy` value must be a full proxy URI, unless the operator gives your API k
|
|||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `200` | - | Session created; authentication in progress. |
|
| `200` | - | Session created; authentication in progress. |
|
||||||
| `400` | `INVALID_INPUT` | Missing `service` or `title_id`. |
|
| `400` | `INVALID_INPUT` | Missing `service` or `title_id`. |
|
||||||
|
| `400` | `INVALID_PARAMETERS` | Invalid `range_`, `vcodec`, `quality` or `dl_params` value. |
|
||||||
| `400` | `INVALID_SERVICE` | Unknown or disallowed service. |
|
| `400` | `INVALID_SERVICE` | Unknown or disallowed service. |
|
||||||
|
|
||||||
### `GET /api/session/{session_id}/channel`
|
### `GET /api/session/{session_id}/channel`
|
||||||
|
|||||||
@@ -489,10 +489,10 @@ object the dashboard shows as sent), and the track-selection hints `range_`, `vc
|
|||||||
`EC3`), and `forced_subs` and `exact_lang` (booleans). The server gives these values to the
|
`EC3`), and `forced_subs` and `exact_lang` (booleans). The server gives these values to the
|
||||||
service in `ctx.parent.params`, never as service options, so a service option
|
service in `ctx.parent.params`, never as service options, so a service option
|
||||||
with the same name, such as an own `--lang`, does not get them. The server uses
|
with the same name, such as an own `--lang`, does not get them. The server uses
|
||||||
the `dl` default for each absent or malformed value: `lang` is `["orig"]`,
|
the `dl` default for each absent value: `lang` is `["orig"]`,
|
||||||
`v_lang`, `a_lang` and `acodec` are `[]`, and `forced_subs` and `exact_lang` are `false`. The
|
`v_lang`, `a_lang` and `acodec` are `[]`, and `forced_subs` and `exact_lang` are `false`. The
|
||||||
server drops an unknown codec name. An empty array is a valid value and stays
|
server refuses a malformed value and an unknown codec or range name with
|
||||||
empty.
|
`INVALID_PARAMETERS`. An empty array is a valid value and stays empty.
|
||||||
|
|
||||||
The server does not forward the `dl` mode flags: `video_only`, `audio_only`,
|
The server does not forward the `dl` mode flags: `video_only`, `audio_only`,
|
||||||
`subs_only`, `chapters_only`, `list_`, `skip_dl`, `sub_format`,
|
`subs_only`, `chapters_only`, `list_`, `skip_dl`, `sub_format`,
|
||||||
|
|||||||
@@ -85,6 +85,12 @@ def test_language_range_passes_exclusion_tokens_through(value, expected):
|
|||||||
assert LANGUAGE_RANGE.convert(value) == expected
|
assert LANGUAGE_RANGE.convert(value) == expected
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("value", [[None], ["en", 1], [{"x": "en"}]])
|
||||||
|
def test_language_range_refuses_a_list_item_that_is_not_a_string(value):
|
||||||
|
with pytest.raises(click.BadParameter):
|
||||||
|
LANGUAGE_RANGE.convert(value)
|
||||||
|
|
||||||
|
|
||||||
def parse(*tokens: str) -> list[str]:
|
def parse(*tokens: str) -> list[str]:
|
||||||
return SeasonRange().parse_tokens(*tokens)
|
return SeasonRange().parse_tokens(*tokens)
|
||||||
|
|
||||||
|
|||||||
@@ -146,3 +146,61 @@ def test_each_builder_sets_its_launch_keys(
|
|||||||
) -> None:
|
) -> None:
|
||||||
params = build(monkeypatch, tmp_path).params
|
params = build(monkeypatch, tmp_path).params
|
||||||
assert {key: params[key] for key in LaunchKeys.__annotations__ if key in params} == expected
|
assert {key: params[key] for key in LaunchKeys.__annotations__ if key in params} == expected
|
||||||
|
|
||||||
|
|
||||||
|
def served_paths(monkeypatch: pytest.MonkeyPatch) -> dict[str, Callable[[dict], click.Context]]:
|
||||||
|
"""Each served builder, as a function of the request body to the parent context its service gets."""
|
||||||
|
from unshackle.core import remote_service
|
||||||
|
|
||||||
|
handlers, seen = rest_handlers(monkeypatch)
|
||||||
|
monkeypatch.setattr(remote_service, "make_remote_service", lambda ctx, *a, **k: ctx)
|
||||||
|
|
||||||
|
def instantiate(parent_ctx: click.Context, *a: Any) -> Any:
|
||||||
|
seen["ctx"] = parent_ctx
|
||||||
|
return SimpleNamespace(authenticate=lambda cookies, credential: None, search=lambda: iter(()))
|
||||||
|
|
||||||
|
monkeypatch.setattr(handlers, "instantiate_service", instantiate)
|
||||||
|
|
||||||
|
def captured(call: Callable[[], Any]) -> click.Context:
|
||||||
|
call()
|
||||||
|
return seen["ctx"]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"relay": lambda data: handlers.relay_service(data, "server", None, "t").parent,
|
||||||
|
"list": lambda data: captured(lambda: handlers.setup_list_service(data, "EXAMPLE", None, "t")),
|
||||||
|
"search": lambda data: captured(lambda: handlers.run_service_search(data, "EXAMPLE", "query")),
|
||||||
|
"session": lambda data: captured(
|
||||||
|
lambda: handlers.create_service_instance("EXAMPLE", "t", data, None, [], None)
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("path", ["relay", "list", "search", "session"])
|
||||||
|
def test_every_served_path_takes_its_dl_options_from_the_served_plan(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, path: str
|
||||||
|
) -> None:
|
||||||
|
from unshackle.core.tracks import Video
|
||||||
|
|
||||||
|
data = {"service": "EXAMPLE", "service_params": {}, "range_": ["DV"], "dl_params": {"a_lang": ["en"]}}
|
||||||
|
params = served_paths(monkeypatch)[path](data).params
|
||||||
|
assert (params["range_"], params["a_lang"], params["served"]) == ([Video.Range.DV], ["en"], True)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("path", ["relay", "list", "search", "session"])
|
||||||
|
def test_every_served_path_refuses_an_unknown_range(monkeypatch: pytest.MonkeyPatch, path: str) -> None:
|
||||||
|
from unshackle.core.api.errors import APIError
|
||||||
|
from unshackle.core.remote_protocol import APIErrorCode
|
||||||
|
|
||||||
|
with pytest.raises(APIError) as exc:
|
||||||
|
served_paths(monkeypatch)[path]({"service": "EXAMPLE", "service_params": {}, "range_": ["NOPE"]})
|
||||||
|
assert exc.value.error_code is APIErrorCode.INVALID_PARAMETERS
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_relay_session_is_pooled_per_dl_selection() -> None:
|
||||||
|
from unshackle.core.api.handlers import remote_pool_key
|
||||||
|
|
||||||
|
data = {"service": "EXAMPLE", "dl_params": {"a_lang": ["en"]}}
|
||||||
|
keys = {
|
||||||
|
remote_pool_key(d, "server", {}, None, "t", None) for d in (data, {**data, "dl_params": {"a_lang": ["fr"]}})
|
||||||
|
}
|
||||||
|
assert len(keys) == 2
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
"""The run plan: one check of the dl options for the CLI and the REST download job."""
|
"""The run plan: one check of the dl options for the CLI and the REST download job, one cast for a served service."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -11,9 +11,10 @@ from click.core import ParameterSource
|
|||||||
from unshackle.commands.dl import dl
|
from unshackle.commands.dl import dl
|
||||||
from unshackle.core.api.errors import categorize_exception
|
from unshackle.core.api.errors import categorize_exception
|
||||||
from unshackle.core.config import config
|
from unshackle.core.config import config
|
||||||
|
from unshackle.core.dl_options import remote_dl_params
|
||||||
from unshackle.core.remote_protocol import APIErrorCode
|
from unshackle.core.remote_protocol import APIErrorCode
|
||||||
from unshackle.core.run_plan import PlanError, api_plan, bitrate_range, check_options
|
from unshackle.core.run_plan import PlanError, api_plan, bitrate_range, check_options, served_plan
|
||||||
from unshackle.core.tracks import Video
|
from unshackle.core.tracks import Audio, Video
|
||||||
|
|
||||||
|
|
||||||
def cli_params(*args: str) -> dict[str, Any]:
|
def cli_params(*args: str) -> dict[str, Any]:
|
||||||
@@ -107,3 +108,80 @@ def test_dl_checks_the_plan_before_the_service_loads(monkeypatch: pytest.MonkeyP
|
|||||||
monkeypatch.setattr(config, "output_template", {"movies": "{title}"})
|
monkeypatch.setattr(config, "output_template", {"movies": "{title}"})
|
||||||
with pytest.raises(PlanError, match="--sample and --include-sample"):
|
with pytest.raises(PlanError, match="--sample and --include-sample"):
|
||||||
dl.cli.main(["--sample", "--include-sample", "EXAMPLE", "t"], standalone_mode=False)
|
dl.cli.main(["--sample", "--include-sample", "EXAMPLE", "t"], standalone_mode=False)
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_served_plan_reads_what_a_remote_client_sends() -> None:
|
||||||
|
parent = {
|
||||||
|
"lang": ["orig", "es-419"],
|
||||||
|
"v_lang": [],
|
||||||
|
"a_lang": ["en"],
|
||||||
|
"s_lang": ["all"],
|
||||||
|
"acodec": [Audio.Codec.EC3],
|
||||||
|
"forced_subs": True,
|
||||||
|
"exact_lang": True,
|
||||||
|
}
|
||||||
|
data = {
|
||||||
|
"range_": ["DV", "HDR10P"],
|
||||||
|
"vcodec": ["HEVC"],
|
||||||
|
"quality": [720, 1080],
|
||||||
|
"best_available": True,
|
||||||
|
"generate_dv": True,
|
||||||
|
"no_proxy": True,
|
||||||
|
"dl_params": remote_dl_params(parent),
|
||||||
|
"service_params": {},
|
||||||
|
}
|
||||||
|
plan = served_plan(data, "http://proxy", "work")
|
||||||
|
assert plan.params["range_"] == [Video.Range.DV, Video.Range.HDR10P]
|
||||||
|
assert plan.params["vcodec"] == [Video.Codec.HEVC]
|
||||||
|
assert plan.params["quality"] == [1080, 720]
|
||||||
|
assert {k: plan.params[k] for k in ("best_available", "generate_dv", "no_proxy")} == dict.fromkeys(
|
||||||
|
("best_available", "generate_dv", "no_proxy"), True
|
||||||
|
)
|
||||||
|
assert {k: plan.params[k] for k in parent} == parent
|
||||||
|
assert (plan.params["proxy"], plan.params["profile"]) == ("http://proxy", "work")
|
||||||
|
assert plan.sources["range_"] is ParameterSource.COMMANDLINE
|
||||||
|
assert plan.sources["proxy"] is ParameterSource.COMMANDLINE
|
||||||
|
assert plan.sources["workers"] is ParameterSource.DEFAULT
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_served_plan_gives_an_old_client_the_dl_defaults() -> None:
|
||||||
|
params = served_plan({}).params
|
||||||
|
assert params["range_"] == [Video.Range.SDR]
|
||||||
|
assert (params["vcodec"], params["quality"], params["acodec"]) == ([], [], [])
|
||||||
|
assert (params["lang"], params["s_lang"]) == (["orig"], ["all"])
|
||||||
|
assert (params["forced_subs"], params["exact_lang"], params["no_proxy"]) == (False, False, False)
|
||||||
|
|
||||||
|
|
||||||
|
def test_dl_params_set_only_the_options_a_remote_client_forwards() -> None:
|
||||||
|
data = {"dl_params": {"proxy": "http://other", "no_cache": True, "range": ["DV"], "lang": ["en"]}}
|
||||||
|
params = served_plan(data, "http://server").params
|
||||||
|
assert (params["proxy"], params["no_cache"], params["range_"]) == ("http://server", False, [Video.Range.SDR])
|
||||||
|
assert params["lang"] == ["en"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_flat_key_counts_only_when_it_cannot_be_a_service_option() -> None:
|
||||||
|
assert served_plan({"quality": "UHD"}).params["quality"] == []
|
||||||
|
assert served_plan({"quality": [1080]}, flat={"quality"}).params["quality"] == [1080]
|
||||||
|
assert served_plan({"quality": [1080], "service_params": {}}).params["quality"] == [1080]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(("value", "expected"), [("false", True), (1, True), (0, False), (None, False)])
|
||||||
|
def test_no_proxy_counts_by_truth_value_as_the_proxy_gate_reads_it(value: Any, expected: bool) -> None:
|
||||||
|
assert served_plan({"no_proxy": value}).params["no_proxy"] is expected
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("data", "key"),
|
||||||
|
[
|
||||||
|
({"range_": ["SDR", "NOPE"]}, "range"),
|
||||||
|
({"vcodec": ["NOPE"]}, "vcodec"),
|
||||||
|
({"quality": ["best"]}, "quality"),
|
||||||
|
({"quality": [1080, 0]}, "quality"),
|
||||||
|
({"dl_params": {"acodec": ["NOPE"]}}, "acodec"),
|
||||||
|
({"dl_params": {"lang": [None, {"x": 1}]}}, "lang"),
|
||||||
|
({"dl_params": {"a_lang": [1]}}, "a_lang"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_the_served_plan_refuses_an_unknown_value(data: dict[str, Any], key: str) -> None:
|
||||||
|
with pytest.raises(PlanError, match=f"Invalid {key}"):
|
||||||
|
served_plan({**data, "service_params": {}})
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import inspect
|
import inspect
|
||||||
import logging
|
|
||||||
|
|
||||||
import click
|
import click
|
||||||
import pytest
|
import pytest
|
||||||
@@ -16,7 +15,6 @@ from unshackle.core.dl_options import (
|
|||||||
DL_OPTIONS,
|
DL_OPTIONS,
|
||||||
FORWARDED_DL_PARAMS,
|
FORWARDED_DL_PARAMS,
|
||||||
cast_dl_params,
|
cast_dl_params,
|
||||||
forwarded_dl_params,
|
|
||||||
remote_dl_params,
|
remote_dl_params,
|
||||||
)
|
)
|
||||||
from unshackle.core.tracks import Audio, Subtitle, Video
|
from unshackle.core.tracks import Audio, Subtitle, Video
|
||||||
@@ -39,19 +37,6 @@ def test_the_openapi_yaml_names_each_api_dl_option_and_no_other():
|
|||||||
assert properties.keys() - DEFAULT_DOWNLOAD_PARAMS.keys() == {"service", "title_id", "remote", "client_name", "cdm"}
|
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():
|
def test_api_defaults_cast_to_the_dl_defaults():
|
||||||
"""``wanted`` keeps its API default of no keys, which dl reads as every title, like the CLI's None."""
|
"""``wanted`` keeps its API default of no keys, which dl reads as every title, like the CLI's None."""
|
||||||
ctx = click.Context(dl.cli)
|
ctx = click.Context(dl.cli)
|
||||||
@@ -121,26 +106,6 @@ def test_every_dl_option_reaches_dl_result():
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
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(
|
@pytest.mark.parametrize(
|
||||||
"parent_params,sent",
|
"parent_params,sent",
|
||||||
[
|
[
|
||||||
|
|||||||
@@ -74,4 +74,4 @@ def test_a_remote_session_gets_quality_as_heights(monkeypatch: pytest.MonkeyPatc
|
|||||||
def test_a_remote_session_refuses_a_malformed_quality(monkeypatch: pytest.MonkeyPatch, quality: str) -> None:
|
def test_a_remote_session_refuses_a_malformed_quality(monkeypatch: pytest.MonkeyPatch, quality: str) -> None:
|
||||||
with pytest.raises(handlers.APIError) as exc:
|
with pytest.raises(handlers.APIError) as exc:
|
||||||
session_params(monkeypatch, {"quality": quality})
|
session_params(monkeypatch, {"quality": quality})
|
||||||
assert exc.value.error_code == handlers.APIErrorCode.INVALID_INPUT
|
assert exc.value.error_code == handlers.APIErrorCode.INVALID_PARAMETERS
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ 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.launch import served_context
|
||||||
from unshackle.core.remote_protocol import APIErrorCode, AuthStatus
|
from unshackle.core.remote_protocol import APIErrorCode, AuthStatus
|
||||||
|
from unshackle.core.run_plan import served_plan
|
||||||
from unshackle.core.utils.click_types import ContextData
|
from unshackle.core.utils.click_types import ContextData
|
||||||
|
|
||||||
pytestmark = pytest.mark.unit
|
pytestmark = pytest.mark.unit
|
||||||
@@ -174,7 +175,7 @@ def test_a_relaying_client_gets_a_stand_in_with_its_device_facts(monkeypatch: py
|
|||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
handlers,
|
handlers,
|
||||||
"served_context",
|
"served_context",
|
||||||
lambda obj, params, keys: built.update(cdm=obj.cdm, config=obj.config, params={**params, **keys}),
|
lambda obj, plan, keys: built.update(cdm=obj.cdm, config=obj.config, params={**plan.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")
|
||||||
@@ -502,7 +503,7 @@ def test_a_lent_device_without_the_vault_grant_asks_the_server_for_no_key() -> N
|
|||||||
|
|
||||||
@pytest.mark.parametrize("params", [{}, {"quality": None}])
|
@pytest.mark.parametrize("params", [{}, {"quality": None}])
|
||||||
def test_every_service_context_defaults_quality_to_a_list(params: Any) -> None:
|
def test_every_service_context_defaults_quality_to_a_list(params: Any) -> None:
|
||||||
parent = served_context(ContextData(config={}, cdm=None, proxy_providers=[]), params, {})
|
parent = served_context(ContextData(config={}, cdm=None, proxy_providers=[]), served_plan(params), {})
|
||||||
assert parent.params["quality"] == []
|
assert parent.params["quality"] == []
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -365,17 +365,3 @@ async def test_search_unknown_service_raises_invalid_service() -> None:
|
|||||||
with pytest.raises(APIError) as exc:
|
with pytest.raises(APIError) as exc:
|
||||||
await search_handler({"service": "NOPE_THIS_IS_NOT_REAL_", "query": "x"}, None)
|
await search_handler({"service": "NOPE_THIS_IS_NOT_REAL_", "query": "x"}, None)
|
||||||
assert exc.value.error_code == APIErrorCode.INVALID_SERVICE
|
assert exc.value.error_code == APIErrorCode.INVALID_SERVICE
|
||||||
|
|
||||||
|
|
||||||
def test_resolve_vcodec_rejects_junk_as_invalid_input() -> None:
|
|
||||||
"""Session routes skip the download job admission, so a bad codec must be a 400, not a 500."""
|
|
||||||
from unshackle.core.api.handlers import resolve_vcodec
|
|
||||||
from unshackle.core.remote_protocol import APIErrorCode
|
|
||||||
from unshackle.core.tracks import Video
|
|
||||||
|
|
||||||
assert resolve_vcodec(["H265"]) == [Video.Codec.HEVC]
|
|
||||||
assert resolve_vcodec(None) is None
|
|
||||||
for junk in ("XVID", 5, [5]):
|
|
||||||
with pytest.raises(APIError) as exc:
|
|
||||||
resolve_vcodec(junk)
|
|
||||||
assert exc.value.error_code == APIErrorCode.INVALID_INPUT
|
|
||||||
|
|||||||
@@ -202,9 +202,9 @@ async def test_list_tracks_service_sees_dl_params(seen):
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_search_service_gets_no_dl_params(seen):
|
async def test_search_service_sees_dl_params(seen):
|
||||||
await handlers.search_handler({"service": "EXAMPLE", "query": "q", "dl_params": {"a_lang": ["es-419"]}})
|
await handlers.search_handler({"service": "EXAMPLE", "query": "q", "dl_params": {"a_lang": ["es-419"]}})
|
||||||
assert "a_lang" not in seen["parent_params"]
|
assert seen["parent_params"]["a_lang"] == ["es-419"]
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
|
|||||||
@@ -178,7 +178,7 @@ def test_nested_dl_params_reach_the_parent_ctx(monkeypatch):
|
|||||||
"v_lang": ["ja"],
|
"v_lang": ["ja"],
|
||||||
"a_lang": ["es-419"],
|
"a_lang": ["es-419"],
|
||||||
"s_lang": ["ko"],
|
"s_lang": ["ko"],
|
||||||
"acodec": ["EC3", "NOPE", "AAC"],
|
"acodec": ["EC3", "AAC"],
|
||||||
"forced_subs": True,
|
"forced_subs": True,
|
||||||
"exact_lang": True,
|
"exact_lang": True,
|
||||||
}
|
}
|
||||||
@@ -211,20 +211,21 @@ def test_a_service_lang_option_never_gets_the_dl_lang(monkeypatch):
|
|||||||
assert "dl_params" in handlers.SESSION_TRANSPORT_KEYS
|
assert "dl_params" in handlers.SESSION_TRANSPORT_KEYS
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
def test_dl_params_that_are_not_an_object_are_ignored(monkeypatch):
|
||||||
"dl_params",
|
svc = _create_with_real_ctx(monkeypatch, {"dl_params": "en"})
|
||||||
[
|
|
||||||
"en",
|
|
||||||
{"lang": "en", "v_lang": "ja", "a_lang": {"x": 1}, "acodec": "EC3", "forced_subs": "yes", "exact_lang": "yes"},
|
|
||||||
{"lang": [1], "v_lang": [None], "a_lang": ["en", None], "acodec": [3], "forced_subs": 1, "exact_lang": 1},
|
|
||||||
],
|
|
||||||
)
|
|
||||||
def test_malformed_dl_params_are_ignored(monkeypatch, dl_params):
|
|
||||||
svc = _create_with_real_ctx(monkeypatch, {"dl_params": dl_params})
|
|
||||||
selection = {k: svc.parent_params[k] for k in (*DL_DEFAULTS,)}
|
selection = {k: svc.parent_params[k] for k in (*DL_DEFAULTS,)}
|
||||||
assert selection == DL_DEFAULTS
|
assert selection == DL_DEFAULTS
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"dl_params", [{"a_lang": {"x": 1}}, {"acodec": ["EC3", "NOPE"]}, {"acodec": [3]}, {"forced_subs": "maybe"}]
|
||||||
|
)
|
||||||
|
def test_a_malformed_dl_param_is_refused(monkeypatch, dl_params):
|
||||||
|
with pytest.raises(handlers.APIError) as exc:
|
||||||
|
_create_with_real_ctx(monkeypatch, {"dl_params": dl_params})
|
||||||
|
assert exc.value.error_code is handlers.APIErrorCode.INVALID_PARAMETERS
|
||||||
|
|
||||||
|
|
||||||
def test_profile_reaches_the_parent_ctx_params(monkeypatch):
|
def test_profile_reaches_the_parent_ctx_params(monkeypatch):
|
||||||
monkeypatch.setattr(key_policy, "load_service_config", lambda s: {})
|
monkeypatch.setattr(key_policy, "load_service_config", lambda s: {})
|
||||||
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
|
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
|
||||||
|
|||||||
@@ -108,10 +108,10 @@ def test_above_the_cap_without_a_device_is_refused_at_create():
|
|||||||
assert ei.value.details == {"reason": "server_cdm_max_height", "max_height": 1080}
|
assert ei.value.details == {"reason": "server_cdm_max_height", "max_height": 1080}
|
||||||
|
|
||||||
|
|
||||||
def test_bad_quality_is_invalid_input():
|
def test_bad_quality_is_invalid_parameters():
|
||||||
with pytest.raises(APIError) as ei:
|
with pytest.raises(APIError) as ei:
|
||||||
handlers.choose_session_cdm(KeyPolicy(USERS["flat"]), "EXAMPLE1", {"quality": ["best"]})
|
handlers.choose_session_cdm(KeyPolicy(USERS["flat"]), "EXAMPLE1", {"quality": ["best"]})
|
||||||
assert ei.value.error_code is APIErrorCode.INVALID_INPUT
|
assert ei.value.error_code is APIErrorCode.INVALID_PARAMETERS
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
@@ -249,10 +249,10 @@ def test_an_ultrawide_track_is_measured_as_the_smallest_quality_that_selects_it(
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("quality", [[-1], [0], [1080, 0]])
|
@pytest.mark.parametrize("quality", [[-1], [0], [1080, 0]])
|
||||||
def test_a_height_of_zero_or_less_is_invalid_input(quality):
|
def test_a_height_of_zero_or_less_is_invalid_parameters(quality):
|
||||||
with pytest.raises(APIError) as ei:
|
with pytest.raises(APIError) as ei:
|
||||||
job_admission.enforce_download_gates({"service": "EXAMPLE1", "quality": quality}, request("flat"))
|
job_admission.enforce_download_gates({"service": "EXAMPLE1", "quality": quality}, request("flat"))
|
||||||
assert ei.value.error_code is APIErrorCode.INVALID_INPUT
|
assert ei.value.error_code is APIErrorCode.INVALID_PARAMETERS
|
||||||
|
|
||||||
|
|
||||||
def test_a_capped_download_job_cannot_set_best_available():
|
def test_a_capped_download_job_cannot_set_best_available():
|
||||||
|
|||||||
@@ -45,13 +45,10 @@ from unshackle.core.cdm.choice import choose_cdm, drm_system
|
|||||||
from unshackle.core.cdm.detect import cdm_system, cdm_type_stub
|
from unshackle.core.cdm.detect import cdm_system, cdm_type_stub
|
||||||
from unshackle.core.cdm.loader import device_system
|
from unshackle.core.cdm.loader import device_system
|
||||||
from unshackle.core.config import config
|
from unshackle.core.config import config
|
||||||
from unshackle.core.dl_options import (
|
from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS
|
||||||
DEFAULT_DOWNLOAD_PARAMS,
|
|
||||||
forwarded_dl_params,
|
|
||||||
)
|
|
||||||
from unshackle.core.drm import WHOLE_FILE_DRM, cbcs, is_null_key, real_kids, whole_file_cipher
|
from unshackle.core.drm import WHOLE_FILE_DRM, cbcs, is_null_key, real_kids, whole_file_cipher
|
||||||
from unshackle.core.drm.discovery import drm_from_init_segment, ensure_track_drm, fetch_init_segment, track_pssh
|
from unshackle.core.drm.discovery import drm_from_init_segment, ensure_track_drm, fetch_init_segment, track_pssh
|
||||||
from unshackle.core.launch import served_context
|
from unshackle.core.launch import LaunchKeys, served_context
|
||||||
from unshackle.core.manifests.snapshot import capture
|
from unshackle.core.manifests.snapshot import capture
|
||||||
from unshackle.core.proxies.resolve import REGION_QUERY, initialize_proxy_providers, is_loopback, resolve_proxy
|
from unshackle.core.proxies.resolve import REGION_QUERY, initialize_proxy_providers, is_loopback, resolve_proxy
|
||||||
from unshackle.core.remote_protocol import (
|
from unshackle.core.remote_protocol import (
|
||||||
@@ -75,6 +72,7 @@ from unshackle.core.remote_protocol import (
|
|||||||
TracksReply,
|
TracksReply,
|
||||||
TracksRequest,
|
TracksRequest,
|
||||||
)
|
)
|
||||||
|
from unshackle.core.run_plan import SESSION_DL_KEYS, PlanError, served_plan
|
||||||
from unshackle.core.services import Services
|
from unshackle.core.services import Services
|
||||||
from unshackle.core.session import RnetSession, utf8_text
|
from unshackle.core.session import RnetSession, utf8_text
|
||||||
from unshackle.core.titles import Episode, Song
|
from unshackle.core.titles import Episode, Song
|
||||||
@@ -90,7 +88,7 @@ from unshackle.core.tunnel import (
|
|||||||
tunnel_proxy,
|
tunnel_proxy,
|
||||||
)
|
)
|
||||||
from unshackle.core.utilities import declared_kwargs
|
from unshackle.core.utilities import declared_kwargs
|
||||||
from unshackle.core.utils.click_types import QUALITY_LIST, SEASON_RANGE, VIDEO_CODEC_LIST, ContextData
|
from unshackle.core.utils.click_types import QUALITY_LIST, SEASON_RANGE, ContextData
|
||||||
from unshackle.core.utils.hdr10plus import probed_tracks
|
from unshackle.core.utils.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
|
||||||
from unshackle.core.utils.service_params import FLAT_DL_KEYS, cast_service_options, service_options
|
from unshackle.core.utils.service_params import FLAT_DL_KEYS, cast_service_options, service_options
|
||||||
@@ -160,6 +158,25 @@ def load_full_cdm(service: str, profile: str | None, cdm_type: str | None = None
|
|||||||
return resolve_server_cdm(service, profile, cdm_type, app_config)
|
return resolve_server_cdm(service, profile, cdm_type, app_config)
|
||||||
|
|
||||||
|
|
||||||
|
def served_parent(
|
||||||
|
obj: ContextData,
|
||||||
|
data: dict[str, Any],
|
||||||
|
keys: LaunchKeys,
|
||||||
|
proxy: str | None,
|
||||||
|
profile: str | None = None,
|
||||||
|
flat: AbstractSet[str] = frozenset(),
|
||||||
|
) -> click.Context:
|
||||||
|
"""The parent context of a served service, with the dl options of :func:`served_plan` for the request ``data``.
|
||||||
|
|
||||||
|
A dl option value that the plan refuses is a ``400 INVALID_PARAMETERS``.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
plan = served_plan(data, proxy, profile, flat)
|
||||||
|
except PlanError as e:
|
||||||
|
raise APIError(APIErrorCode.INVALID_PARAMETERS, e.message) from None
|
||||||
|
return served_context(obj, plan, keys)
|
||||||
|
|
||||||
|
|
||||||
def cast_or_refuse(params: Iterable[click.Parameter], ctx: Any, options: dict[str, Any]) -> dict[str, Any]:
|
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:
|
||||||
@@ -467,10 +484,12 @@ 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 = served_context(
|
parent_ctx = served_parent(
|
||||||
ContextData(config={}, cdm=None, proxy_providers=providers, profile=profile),
|
ContextData(config={}, cdm=None, proxy_providers=providers, profile=profile),
|
||||||
{"proxy": proxy_param, "no_proxy": data.get("no_proxy", False), "profile": profile},
|
data,
|
||||||
{"client_argv": relay_label(data)},
|
{"client_argv": relay_label(data)},
|
||||||
|
proxy_param,
|
||||||
|
profile,
|
||||||
)
|
)
|
||||||
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
|
||||||
@@ -582,10 +601,17 @@ _remote_sweeper: Optional["asyncio.Task[None]"] = None
|
|||||||
def remote_pool_key(
|
def remote_pool_key(
|
||||||
data: dict[str, Any], server: str, info: dict, profile: str | None, title_id: str, request: web.Request | None
|
data: dict[str, Any], server: str, info: dict, profile: str | None, title_id: str, request: web.Request | None
|
||||||
) -> tuple:
|
) -> tuple:
|
||||||
"""What opens a remote session for one API key; requests that differ only in episode selection share one."""
|
"""What opens a remote session for one API key; requests that differ only in episode selection share one.
|
||||||
|
|
||||||
|
The dl selection is part of it, because the relay sends it on to the remote session create.
|
||||||
|
"""
|
||||||
from unshackle.core.remote_service import remote_service_params
|
from unshackle.core.remote_service import remote_service_params
|
||||||
|
|
||||||
options = json.dumps(remote_service_params(info, data), sort_keys=True, default=str)
|
options = json.dumps(
|
||||||
|
[remote_service_params(info, data), data.get("dl_params"), *(data.get(k) for k in SESSION_DL_KEYS)],
|
||||||
|
sort_keys=True,
|
||||||
|
default=str,
|
||||||
|
)
|
||||||
return (
|
return (
|
||||||
caller_key(request),
|
caller_key(request),
|
||||||
server,
|
server,
|
||||||
@@ -758,7 +784,6 @@ def setup_list_service(
|
|||||||
policy = request_policy(request)
|
policy = request_policy(request)
|
||||||
service_config = policy.service_yaml(normalized_service)
|
service_config = policy.service_yaml(normalized_service)
|
||||||
|
|
||||||
no_proxy = data.get("no_proxy", False)
|
|
||||||
proxy_param, proxy_providers = resolve_handler_proxy(data, normalized_service, request)
|
proxy_param, proxy_providers = resolve_handler_proxy(data, normalized_service, request)
|
||||||
|
|
||||||
account = resolve_server_account(policy, normalized_service, data.get("client_region"))
|
account = resolve_server_account(policy, normalized_service, data.get("client_region"))
|
||||||
@@ -770,10 +795,11 @@ def setup_list_service(
|
|||||||
cdm = load_full_cdm(normalized_service, profile, cdm_type, policy.cdm_config())
|
cdm = load_full_cdm(normalized_service, profile, cdm_type, policy.cdm_config())
|
||||||
cookies, credential = server_login_material(data, normalized_service, account, profile)
|
cookies, credential = server_login_material(data, normalized_service, account, profile)
|
||||||
|
|
||||||
parent_ctx = served_context(
|
parent_ctx = served_parent(
|
||||||
ContextData(config=service_config, cdm=cdm, proxy_providers=proxy_providers, profile=profile),
|
ContextData(config=service_config, cdm=cdm, proxy_providers=proxy_providers, profile=profile),
|
||||||
{"proxy": proxy_param, "no_proxy": no_proxy, **forwarded_dl_params(data)},
|
data,
|
||||||
{"cookies_supplied": cookies is not None},
|
{"cookies_supplied": cookies is not None},
|
||||||
|
proxy_param,
|
||||||
)
|
)
|
||||||
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)
|
||||||
|
|
||||||
@@ -805,7 +831,6 @@ def run_service_search(
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
profile = client_profile(data)
|
profile = client_profile(data)
|
||||||
no_proxy = data.get("no_proxy", False)
|
|
||||||
|
|
||||||
api_key = caller_key(request)
|
api_key = caller_key(request)
|
||||||
policy = request_policy(request)
|
policy = request_policy(request)
|
||||||
@@ -823,10 +848,11 @@ def run_service_search(
|
|||||||
(None, None) if anonymous else server_login_material(data, normalized_service, account, profile)
|
(None, None) if anonymous else server_login_material(data, normalized_service, account, profile)
|
||||||
)
|
)
|
||||||
|
|
||||||
parent_ctx = served_context(
|
parent_ctx = served_parent(
|
||||||
ContextData(config=service_config, cdm=cdm, proxy_providers=proxy_providers, profile=profile),
|
ContextData(config=service_config, cdm=cdm, proxy_providers=proxy_providers, profile=profile),
|
||||||
{"proxy": proxy_param, "no_proxy": no_proxy},
|
data,
|
||||||
{"cookies_supplied": cookies is not None},
|
{"cookies_supplied": cookies is not None},
|
||||||
|
proxy_param,
|
||||||
)
|
)
|
||||||
|
|
||||||
from click import ClickException
|
from click import ClickException
|
||||||
@@ -927,9 +953,9 @@ def requested_heights(quality: Any) -> list[int]:
|
|||||||
try:
|
try:
|
||||||
heights = QUALITY_LIST.convert(quality or [])
|
heights = QUALITY_LIST.convert(quality or [])
|
||||||
except click.BadParameter as e:
|
except click.BadParameter as e:
|
||||||
raise APIError(APIErrorCode.INVALID_INPUT, f"quality: {e.message}") from e
|
raise APIError(APIErrorCode.INVALID_PARAMETERS, f"quality: {e.message}") from e
|
||||||
if any(height <= 0 for height in heights):
|
if any(height <= 0 for height in heights):
|
||||||
raise APIError(APIErrorCode.INVALID_INPUT, f"quality: every height must be above 0, not {quality!r}")
|
raise APIError(APIErrorCode.INVALID_PARAMETERS, f"quality: every height must be above 0, not {quality!r}")
|
||||||
return heights
|
return heights
|
||||||
|
|
||||||
|
|
||||||
@@ -1586,20 +1612,6 @@ async def list_tracks_handler(data: dict[str, Any], request: web.Request | None
|
|||||||
await request_cache.cleanup()
|
await request_cache.cleanup()
|
||||||
|
|
||||||
|
|
||||||
def resolve_vcodec(value: Any) -> list | None:
|
|
||||||
"""Map a client's vcodec field to codec enums.
|
|
||||||
|
|
||||||
Session routes do not run the download job admission, so this must answer junk with a 400
|
|
||||||
instead of letting click's UsageError surface as a 500.
|
|
||||||
"""
|
|
||||||
if not value:
|
|
||||||
return None
|
|
||||||
try:
|
|
||||||
return VIDEO_CODEC_LIST.convert(value) or None
|
|
||||||
except click.UsageError as e:
|
|
||||||
raise APIError(APIErrorCode.INVALID_INPUT, f"Invalid vcodec: {e.format_message()}") from e
|
|
||||||
|
|
||||||
|
|
||||||
def wanted_refusal(wanted: Any) -> str | None:
|
def wanted_refusal(wanted: Any) -> str | None:
|
||||||
"""Why dl could not parse ``wanted``, or None when it can."""
|
"""Why dl could not parse ``wanted``, or None when it can."""
|
||||||
try:
|
try:
|
||||||
@@ -2793,8 +2805,6 @@ def create_service_instance(
|
|||||||
client that sends nothing authenticates with nothing, because the server never lends its
|
client that sends nothing authenticates with nothing, because the server never lends its
|
||||||
own accounts.
|
own accounts.
|
||||||
"""
|
"""
|
||||||
from unshackle.core.tracks import Video
|
|
||||||
|
|
||||||
policy = policy or KeyPolicy.of(None)
|
policy = policy or KeyPolicy.of(None)
|
||||||
server_config = service_config = policy.service_yaml(normalized_service)
|
server_config = service_config = policy.service_yaml(normalized_service)
|
||||||
service_module = Services.load(normalized_service)
|
service_module = Services.load(normalized_service)
|
||||||
@@ -2822,21 +2832,6 @@ def create_service_instance(
|
|||||||
)
|
)
|
||||||
cdm = load_full_cdm(normalized_service, profile, data.get("cdm_type") if follows_client else None, key_config)
|
cdm = load_full_cdm(normalized_service, profile, data.get("cdm_type") if follows_client else None, key_config)
|
||||||
|
|
||||||
# Reconstruct enum track-selection params from client data so service code that reads
|
|
||||||
# ctx.parent.params (Service.__init__ proxy/range/vcodec/best_available block) sees enums.
|
|
||||||
range_names = data.get("range_")
|
|
||||||
range_values: list | None = None
|
|
||||||
if range_names:
|
|
||||||
range_values = []
|
|
||||||
for name in range_names:
|
|
||||||
try:
|
|
||||||
range_values.append(Video.Range[name])
|
|
||||||
except KeyError:
|
|
||||||
pass
|
|
||||||
range_values = range_values or None
|
|
||||||
|
|
||||||
vcodec_values = resolve_vcodec(data.get("vcodec"))
|
|
||||||
|
|
||||||
if server_account:
|
if server_account:
|
||||||
cookies = server_account_cookies(normalized_service, profile)
|
cookies = server_account_cookies(normalized_service, profile)
|
||||||
credential = login.get_credentials(normalized_service, profile)
|
credential = login.get_credentials(normalized_service, profile)
|
||||||
@@ -2844,24 +2839,17 @@ 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"))
|
||||||
|
|
||||||
parent_ctx = served_context(
|
parent_ctx = served_parent(
|
||||||
ContextData(config=service_config, cdm=cdm, proxy_providers=proxy_providers, profile=profile),
|
ContextData(config=service_config, cdm=cdm, proxy_providers=proxy_providers, profile=profile),
|
||||||
{
|
data,
|
||||||
"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
|
# 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.
|
# 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},
|
{"cookies_supplied": cookies is not None, "client_device": client_device, "client_identity": client_identity},
|
||||||
|
proxy_param,
|
||||||
|
# Services key their token caches on this. The list and search handlers leave it out: they
|
||||||
|
# share the server's cache, where a session runs on a cache directory of its own.
|
||||||
|
profile,
|
||||||
|
SESSION_TRANSPORT_KEYS,
|
||||||
)
|
)
|
||||||
|
|
||||||
service_instance = instantiate_service(parent_ctx, service_module, title_id, data, SESSION_TRANSPORT_KEYS)
|
service_instance = instantiate_service(parent_ctx, service_module, title_id, data, SESSION_TRANSPORT_KEYS)
|
||||||
|
|||||||
@@ -639,6 +639,9 @@ async def search(request: web.Request) -> web.Response:
|
|||||||
no_proxy:
|
no_proxy:
|
||||||
type: boolean
|
type: boolean
|
||||||
description: Force disable all proxy use (default - false)
|
description: Force disable all proxy use (default - false)
|
||||||
|
dl_params:
|
||||||
|
type: object
|
||||||
|
description: The dl track selection, in the same form as on `/api/session/create`.
|
||||||
credentials:
|
credentials:
|
||||||
type: object
|
type: object
|
||||||
additionalProperties: true
|
additionalProperties: true
|
||||||
@@ -2000,8 +2003,8 @@ async def session_create(request: web.Request) -> web.Response:
|
|||||||
type: object
|
type: object
|
||||||
description: |
|
description: |
|
||||||
The dl track selection. The service reads it from ctx.parent.params, never as
|
The dl track selection. The service reads it from ctx.parent.params, never as
|
||||||
service options. An absent or malformed value gets the dl default, and the
|
service options. An absent value gets the dl default; a malformed value or an
|
||||||
server drops an unknown codec name.
|
unknown codec name is refused with INVALID_PARAMETERS.
|
||||||
properties:
|
properties:
|
||||||
lang:
|
lang:
|
||||||
type: array
|
type: array
|
||||||
|
|||||||
@@ -1,17 +1,13 @@
|
|||||||
"""The dl option table: which dl options the REST API takes, their API defaults, and what a remote client forwards."""
|
"""The dl option table: which dl options the REST API takes, their API defaults, and what a remote client forwards."""
|
||||||
|
|
||||||
import logging
|
|
||||||
from collections.abc import Mapping
|
from collections.abc import Mapping
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import Any, Literal, get_args
|
from typing import Any, Literal, get_args
|
||||||
|
|
||||||
import click
|
import click
|
||||||
|
|
||||||
from unshackle.core.utils.click_types import AUDIO_CODEC_LIST
|
|
||||||
from unshackle.core.utils.service_params import cast_service_options
|
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.
|
# Config keys accepted as natural names for params whose Python name dodges a builtin.
|
||||||
DL_OPTION_ALIASES = {"range": "range_", "list": "list_"}
|
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()}
|
DL_OPTION_API_NAMES = {click_name: api_name for api_name, click_name in DL_OPTION_ALIASES.items()}
|
||||||
@@ -174,47 +170,3 @@ def remote_dl_params(params: Mapping[str, Any]) -> dict[str, Any]:
|
|||||||
elif params.get(key) is not None:
|
elif params.get(key) is not None:
|
||||||
sent[key] = [c.name if option.remote == "audio_codecs" else str(c) for c in params[key]]
|
sent[key] = [c.name if option.remote == "audio_codecs" else str(c) for c in params[key]]
|
||||||
return sent
|
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) -> list[str] | None:
|
|
||||||
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
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import copy
|
import copy
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, TypedDict, cast
|
from typing import TYPE_CHECKING, TypedDict, cast
|
||||||
|
|
||||||
import click
|
import click
|
||||||
|
|
||||||
@@ -10,6 +10,9 @@ from unshackle.core.config import config, load_yaml
|
|||||||
from unshackle.core.utils.click_types import ContextData
|
from unshackle.core.utils.click_types import ContextData
|
||||||
from unshackle.core.utils.collections import ci_get, merge_dict
|
from unshackle.core.utils.collections import ci_get, merge_dict
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from unshackle.core.run_plan import RunPlan
|
||||||
|
|
||||||
|
|
||||||
class LaunchKeys(TypedDict, total=False):
|
class LaunchKeys(TypedDict, total=False):
|
||||||
"""The ``ctx.parent.params`` keys that exist only for the launch. ``dl_options.DL_OPTIONS`` holds the dl options.
|
"""The ``ctx.parent.params`` keys that exist only for the launch. ``dl_options.DL_OPTIONS`` holds the dl options.
|
||||||
@@ -39,11 +42,9 @@ def launch(ctx: click.Context, keys: LaunchKeys, obj: ContextData | None = None)
|
|||||||
ctx.obj = obj
|
ctx.obj = obj
|
||||||
|
|
||||||
|
|
||||||
def served_context(obj: ContextData, params: dict[str, Any], keys: LaunchKeys) -> click.Context:
|
def served_context(obj: ContextData, plan: "RunPlan", 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``."""
|
"""A new parent context for a service that a serve runs for an API client, with the dl options of ``plan``."""
|
||||||
ctx = click.Context(click.Command("serve"))
|
ctx = plan.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)
|
launch(ctx, {**keys, "served": True}, obj)
|
||||||
return ctx
|
return ctx
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
"""The dl front door: one checked run plan from a dl click parse or a REST API job, and what the run gave back."""
|
"""The dl front door: one run plan from a dl click parse, a REST API job or a served service, and what the run gave back."""
|
||||||
|
|
||||||
from collections.abc import Collection, Mapping
|
from collections.abc import Collection, Mapping
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
@@ -9,7 +9,7 @@ import click
|
|||||||
from click.core import ParameterSource
|
from click.core import ParameterSource
|
||||||
|
|
||||||
from unshackle.core import providers
|
from unshackle.core import providers
|
||||||
from unshackle.core.dl_options import DL_OPTION_API_NAMES, cast_dl_params
|
from unshackle.core.dl_options import DL_OPTION_API_NAMES, FORWARDED_DL_PARAMS, cast_dl_params
|
||||||
from unshackle.core.downloaders import parse_speed_limit
|
from unshackle.core.downloaders import parse_speed_limit
|
||||||
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
|
from unshackle.core.providers.tvdb import SEASON_TYPES
|
||||||
@@ -18,6 +18,7 @@ from unshackle.core.utilities import inherited_exclusions, kind_only_conflict, p
|
|||||||
|
|
||||||
ID_PROVIDER_KEYS = {"tmdb": "tmdb_api_key", "tvdb": "tvdb_api_key", "omdb": "omdb_api_key"}
|
ID_PROVIDER_KEYS = {"tmdb": "tmdb_api_key", "tvdb": "tvdb_api_key", "omdb": "omdb_api_key"}
|
||||||
PLAN_API_NAMES = {**DL_OPTION_API_NAMES, "cdm_name": "cdm", "server": "remote"}
|
PLAN_API_NAMES = {**DL_OPTION_API_NAMES, "cdm_name": "cdm", "server": "remote"}
|
||||||
|
SESSION_DL_KEYS = ("range_", "vcodec", "quality", "best_available", "generate_dv")
|
||||||
|
|
||||||
|
|
||||||
class PlanError(click.ClickException):
|
class PlanError(click.ClickException):
|
||||||
@@ -50,7 +51,7 @@ class RunPlan:
|
|||||||
params: dict[str, Any]
|
params: dict[str, Any]
|
||||||
sources: dict[str, ParameterSource]
|
sources: dict[str, ParameterSource]
|
||||||
|
|
||||||
def context(self, cli: click.Command, service: str) -> click.Context:
|
def context(self, cli: click.Command, service: str | None = None) -> click.Context:
|
||||||
"""A dl context for this plan, so dl and a service read the values and sources as on the CLI."""
|
"""A dl context for this plan, so dl and a service read the values and sources as on the CLI."""
|
||||||
ctx = click.Context(cli)
|
ctx = click.Context(cli)
|
||||||
ctx.invoked_subcommand = service
|
ctx.invoked_subcommand = service
|
||||||
@@ -175,11 +176,10 @@ def check_options(params: Mapping[str, Any]) -> None:
|
|||||||
raise PlanError("Unable to run hybrid mode: dovi_tool not found")
|
raise PlanError("Unable to run hybrid mode: dovi_tool not found")
|
||||||
|
|
||||||
|
|
||||||
def api_plan(params: Mapping[str, Any], client_keys: Collection[str] | None = None) -> RunPlan:
|
def cast_plan(params: Mapping[str, Any], sent: Collection[str]) -> RunPlan:
|
||||||
"""The checked run plan of a REST API job from its parameters, by API name.
|
"""The run plan of ``params`` by API name, cast by the dl click types but not checked by :func:`check_options`.
|
||||||
|
|
||||||
A value counts as typed on the command line when its API name is in ``client_keys`` (every parameter when None),
|
A value counts as typed on the command line when its API name is in ``sent``.
|
||||||
so a service's ``dl`` config replaces only the values the client did not send.
|
|
||||||
"""
|
"""
|
||||||
from unshackle.commands.dl import dl
|
from unshackle.commands.dl import dl
|
||||||
|
|
||||||
@@ -188,10 +188,46 @@ def api_plan(params: Mapping[str, Any], client_keys: Collection[str] | None = No
|
|||||||
except click.BadParameter as e:
|
except click.BadParameter as e:
|
||||||
raise PlanError(e.message) from None
|
raise PlanError(e.message) from None
|
||||||
cast.update(cdm_name=params.get("cdm"), remote=bool(params.get("remote")), server=params.get("remote"))
|
cast.update(cdm_name=params.get("cdm"), remote=bool(params.get("remote")), server=params.get("remote"))
|
||||||
check_options(cast)
|
|
||||||
sent = params.keys() if client_keys is None else client_keys
|
|
||||||
sources = {
|
sources = {
|
||||||
name: ParameterSource.COMMANDLINE if PLAN_API_NAMES.get(name, name) in sent else ParameterSource.DEFAULT
|
name: ParameterSource.COMMANDLINE if PLAN_API_NAMES.get(name, name) in sent else ParameterSource.DEFAULT
|
||||||
for name in cast
|
for name in cast
|
||||||
}
|
}
|
||||||
return RunPlan(cast, sources)
|
return RunPlan(cast, sources)
|
||||||
|
|
||||||
|
|
||||||
|
def api_plan(params: Mapping[str, Any], client_keys: Collection[str] | None = None) -> RunPlan:
|
||||||
|
"""The checked run plan of a REST API job from its parameters, by API name.
|
||||||
|
|
||||||
|
A value counts as typed on the command line when its API name is in ``client_keys`` (every parameter when None),
|
||||||
|
so a service's ``dl`` config replaces only the values the client did not send.
|
||||||
|
"""
|
||||||
|
plan = cast_plan(params, params.keys() if client_keys is None else client_keys)
|
||||||
|
check_options(plan.params)
|
||||||
|
return plan
|
||||||
|
|
||||||
|
|
||||||
|
def served_plan(
|
||||||
|
data: Mapping[str, Any], proxy: str | None = None, profile: str | None = None, flat: Collection[str] = ()
|
||||||
|
) -> RunPlan:
|
||||||
|
"""The run plan of a served service from a request in the remote session wire form, with the server's ``proxy``.
|
||||||
|
|
||||||
|
A flat ``SESSION_DL_KEYS`` key counts as :func:`service_options` reads it: with ``service_params``, or when in
|
||||||
|
``flat``. ``no_proxy`` counts by truth value, as the server's proxy gate reads it. :func:`check_options` does not
|
||||||
|
run, because dl runs on the client.
|
||||||
|
"""
|
||||||
|
forwarded = raw if isinstance(raw := data.get("dl_params"), dict) else {}
|
||||||
|
params = {key: forwarded[key] for key, _ in FORWARDED_DL_PARAMS if key in forwarded}
|
||||||
|
nested = isinstance(data.get("service_params"), dict)
|
||||||
|
params.update(
|
||||||
|
{DL_OPTION_API_NAMES.get(k, k): data[k] for k in SESSION_DL_KEYS if k in data and (nested or k in flat)}
|
||||||
|
)
|
||||||
|
if "no_proxy" in data:
|
||||||
|
params["no_proxy"] = bool(data["no_proxy"])
|
||||||
|
if proxy is not None:
|
||||||
|
params["proxy"] = proxy
|
||||||
|
if profile is not None:
|
||||||
|
params["profile"] = profile
|
||||||
|
plan = cast_plan(params, params.keys())
|
||||||
|
if any(height <= 0 for height in plan.params["quality"]):
|
||||||
|
raise PlanError(f"Invalid quality: every height must be above 0, not {data['quality']!r}")
|
||||||
|
return plan
|
||||||
|
|||||||
@@ -342,6 +342,8 @@ class LanguageRange(click.ParamType):
|
|||||||
self, value: str | list, param: click.Parameter | None = None, ctx: click.Context | None = None
|
self, value: str | list, param: click.Parameter | None = None, ctx: click.Context | None = None
|
||||||
) -> list[str]:
|
) -> list[str]:
|
||||||
if isinstance(value, list):
|
if isinstance(value, list):
|
||||||
|
if not all(isinstance(v, str) for v in value):
|
||||||
|
self.fail(f"{value!r} is not a list of language strings", param, ctx)
|
||||||
return value
|
return value
|
||||||
if not value:
|
if not value:
|
||||||
return []
|
return []
|
||||||
|
|||||||
Reference in New Issue
Block a user