From 4d3df8e74fd4c6b2d9063b146ce4143e362a87db Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Wed, 25 Nov 2026 16:16:43 -0700 Subject: [PATCH] refactor(dl): check dl options once in a run plan shared by the CLI and the REST download job --- docs/dev/rest-api/endpoints.md | 10 +- docs/dev/rest-api/quickstart.md | 2 +- tests/core/test_hybrid_hdr10plus.py | 11 +- tests/core/test_metadata_id_validation.py | 34 +-- tests/core/test_run_plan.py | 106 +++++++++ tests/lang_selection/test_kind_only_flags.py | 3 +- .../test_required_langs_gate.py | 9 +- tests/remote/unit/test_api_dl_options.py | 18 +- tests/remote/unit/test_api_episode_part.py | 72 ++---- tests/remote/unit/test_api_quality_param.py | 3 +- .../unit/test_api_service_dl_overrides.py | 8 +- tests/remote/unit/test_download_manager.py | 29 ++- tests/remote/unit/test_handlers_serialize.py | 10 +- .../remote/unit/test_server_cdm_max_height.py | 2 +- tests/test_sample.py | 2 +- unshackle/commands/dl.py | 212 +++--------------- unshackle/core/api/download_manager.py | 131 ++--------- unshackle/core/api/handlers.py | 116 ++-------- unshackle/core/dl_options.py | 17 +- unshackle/core/run_plan.py | 196 ++++++++++++++++ unshackle/core/tracks/selection.py | 15 ++ unshackle/core/utilities.py | 5 + unshackle/core/utils/click_types.py | 14 +- 23 files changed, 501 insertions(+), 524 deletions(-) create mode 100644 tests/core/test_run_plan.py create mode 100644 unshackle/core/run_plan.py diff --git a/docs/dev/rest-api/endpoints.md b/docs/dev/rest-api/endpoints.md index 0f2fa497..866503de 100644 --- a/docs/dev/rest-api/endpoints.md +++ b/docs/dev/rest-api/endpoints.md @@ -462,12 +462,12 @@ Make a download job. It requires `service` and `title_id`. Every other field is | `exact_lang` | boolean | `false` | A language tag without a region never falls back to another variant. A tag with a region is always exact. | | `sub_format` | string | `null` | Output subtitle format. | | `sub_font` | string | `null` | Font for subtitles converted to ASS; implies `sub_format` ASS. With another `sub_format` the request returns `400`. | -| `video_only` / `audio_only` / `subs_only` / `chapters_only` | boolean | `false` | Track-type restriction (at most one). | +| `video_only` / `audio_only` / `subs_only` / `chapters_only` | boolean | `false` | Track-type restriction. Two or more combine, as on the CLI. | | `no_subs` / `no_audio` / `no_chapters` / `no_video` / `no_attachments` | boolean | `false` | Skip a track type. | | `skip_subtitle_errors` | boolean | `false` | Skip a subtitle that fails to download and keep the other tracks. | | `audio_description` | boolean | `false` | Download audio description. | | `audio_description_only` | boolean | `false` | Download audio description and no standard audio. Not valid with `no_audio`, `video_only`, `subs_only` or `chapters_only`. | -| `slow` | boolean/string | `null` | Randomized delay between downloads. | +| `slow` | boolean/string/array | `null` | Randomized delay between downloads: `true` (60-120 seconds), `"MIN-MAX"`, or `[MIN, MAX]`. | | `split_audio` | boolean | `null` | Separate files per audio codec. | | `skip_dl` | boolean | `false` | Only fetch keys, do not download. | | `all_drm` | boolean | `false` | License each track with both Widevine and PlayReady. Needs a CDM for each DRM system. Key vaults are read first; `cdm_only: true` sends a challenge for each system. The server refuses it with `cdm`, which selects one device. | @@ -486,15 +486,15 @@ Make a download job. It requires `service` and `title_id`. Every other field is | `generate_dv` | boolean | `false` | With `HYBRID` in `range`, make Dolby Vision from the HDR10+ metadata or the decoded video when a title has no DV track. With `HDR10` or `HDR10P` in `range` and no `HYBRID`, make it for that base and ignore a DV track. With none of the three in `range`, the field has no effect. | | `repack` | boolean | `false` | Add REPACK tag. | | `tag` | string | `null` | Release group tag. | -| `tmdb_id` / `imdb_id` / `tvdb_id` / `anilist_id` | - | `null` | External ID overrides. Each resolves its metadata directly instead of by a title search, and is used for tagging. Set `enrich` to also take the title, year and original language. Give at most one of `tmdb_id`, `imdb_id` and `tvdb_id`, since unshackle resolves the others from it. Sending two returns `400`. `anilist_id` still combines with one of them. `tmdb_id` and `tvdb_id` must be positive integers, `imdb_id` must look like `tt1375666`, and `anilist_id` must be a positive integer or a string like `mal:12345`, or the request returns `400`. An ID whose provider is unconfigured, such as `tmdb_id` with no `tmdb_api_key`, fails the job rather than returning `400`. `anilist_id` needs no API key. | +| `tmdb_id` / `imdb_id` / `tvdb_id` / `anilist_id` | - | `null` | External ID overrides. Each resolves its metadata directly instead of by a title search, and is used for tagging. Set `enrich` to also take the title, year and original language. Give at most one of `tmdb_id`, `imdb_id` and `tvdb_id`, since unshackle resolves the others from it. Sending two returns `400`. `anilist_id` still combines with one of them. `tmdb_id` and `tvdb_id` must be positive integers, `imdb_id` must look like `tt1375666`, and `anilist_id` must be a positive integer or a string like `mal:12345`, or the request returns `400`. An ID whose provider is unconfigured, such as `tmdb_id` with no `tmdb_api_key`, returns `400`. `anilist_id` needs no API key. | | `tvdb_order` | `official`, `dvd`, `absolute`, `alternate`, `regional` | `null` | Renumber episodes to a TVDB season order. Falls back to the `tvdb_order` config option. | | `continuous_episodes` | boolean | `false` | Number each season on from the season before it, so season two starts at episode 5 after four episodes. Season 0 and episode 0 keep their numbers. `wanted` selects by the new numbers, but the list endpoints show the numbers of the service. | -| `enrich` | boolean | `false` | Overwrite title, year and original language with the external source's. Needs one of `tmdb_id`, `imdb_id`, `tvdb_id` or `anilist_id`. Without one the job fails instead of returning `400`. | +| `enrich` | boolean | `false` | Overwrite title, year and original language with the external source's. Needs one of `tmdb_id`, `imdb_id`, `tvdb_id` or `anilist_id`. Without one the request returns `400`. | | `daily` | boolean | `false` | Treat the title as daily/date-based content and fill missing episode air dates from TVDB. The fill needs `enrich` and a TVDB ID. An air date the service already set is kept. | | `output_dir` | string | `null` | Output directory, relative to the server's downloads directory. The server rejects a path that resolves outside it with `400`. | | `no_cache` / `reset_cache` | boolean | `false` | Title cache controls. | -**Validation.** Invalid values return `400 INVALID_PARAMETERS`. `vcodec`, `acodec` and `sub_format` take the same spellings as the CLI options of the same name (`unshackle dl --help` prints each list). The API and the CLI read one list, so they cannot disagree. `range` must be one of SDR/HDR10/HDR10P/VIVID/DV/HLG/HYBRID, and `HDR10+` and `HDR Vivid` are also valid. The bitrate, download worker, and download counts must be positive integers. You may set at most one of the `*_only` flags. You cannot combine `no_subs` with `subs_only`, or `no_audio` with `audio_only`. The language fields (`lang`, `v_lang`, `a_lang`, `s_lang`, `forced_s_lang` and the `require_*` fields) must be arrays of strings: a single string such as `"en"` returns `400`. The server checks every other field with the type of its `dl` option. A `null` or an empty string gets the default from the table. +**Validation.** Invalid values return `400 INVALID_PARAMETERS`. `vcodec`, `acodec` and `sub_format` take the same spellings as the CLI options of the same name (`unshackle dl --help` prints each list). The API and the CLI read one list, so they cannot disagree. `range` must be one of SDR/HDR10/HDR10P/VIVID/DV/HLG/HYBRID, and `HDR10+` and `HDR Vivid` are also valid. The bitrate, download worker, and download counts must be positive integers. You cannot combine `no_subs` with `subs_only`, or `no_audio` with `audio_only`. The server runs the same option checks as `unshackle dl`, so a request that `dl` would refuse returns `400` when you submit it, and the message names the `dl` option. The language fields (`lang`, `v_lang`, `a_lang`, `s_lang`, `forced_s_lang` and the `require_*` fields) must be arrays of strings: a single string such as `"en"` returns `400`. The server checks every other field with the type of its `dl` option. A `null` or an empty string gets the default from the table. **Service options.** A service's own CLI options travel in the same body. Send them in a nested `service_params` object, or as flat top-level keys. When the body has `service_params`, the server diff --git a/docs/dev/rest-api/quickstart.md b/docs/dev/rest-api/quickstart.md index 7181df9f..4136fbd3 100644 --- a/docs/dev/rest-api/quickstart.md +++ b/docs/dev/rest-api/quickstart.md @@ -243,7 +243,7 @@ The request body accepts the full download parameter set. A few of the most usef | `downloads` | `1` | Number of tracks to download concurrently | | `proxy` | `null` | Proxy URI or country code | -Validation is strict: invalid codecs, subtitle formats, dynamic-range names, non-positive counts, or mutually exclusive flags (for example both `video_only` and `audio_only`) come back as `400` with error code `INVALID_PARAMETERS`. See the full reference on the [download reference page](endpoints.md) for every accepted field. +Validation is strict: invalid codecs, subtitle formats, dynamic-range names, non-positive counts, or flags that conflict (for example both `no_subs` and `subs_only`) come back as `400` with error code `INVALID_PARAMETERS`. See the full reference on the [download reference page](endpoints.md) for every accepted field. !!! note "Gated fields" The server refuses a per-request CDM (`cdm`) or inline credentials (`credential` / `credentials`) with `403 FORBIDDEN`, unless the server operator has explicitly opted in with `serve.cdm_overrides` and `serve.allow_job_credentials`. Both are off by default. diff --git a/tests/core/test_hybrid_hdr10plus.py b/tests/core/test_hybrid_hdr10plus.py index 3586f7d6..14d84bc8 100644 --- a/tests/core/test_hybrid_hdr10plus.py +++ b/tests/core/test_hybrid_hdr10plus.py @@ -18,7 +18,6 @@ import pytest import unshackle.commands.dl as dl_module from tests.remote.unit.test_remote_service_helpers import _sent_create_data -from unshackle.commands.dl import generated_dv_ranges from unshackle.core import mux_step from unshackle.core.api import download_manager, handlers from unshackle.core.api.handlers import validate_download_parameters @@ -37,7 +36,12 @@ from unshackle.core.tracks.hybrid import ( nits_to_pq, pq_to_nits, ) -from unshackle.core.tracks.selection import hybrid_gate_failure, keep_generated_dv_bases, select_hybrid_bases +from unshackle.core.tracks.selection import ( + generated_dv_ranges, + hybrid_gate_failure, + keep_generated_dv_bases, + select_hybrid_bases, +) pytestmark = pytest.mark.unit @@ -803,8 +807,7 @@ def test_a_rest_job_gives_the_flag_to_the_service_ctx_and_to_dl( raise _Captured(self.ctx.params["generate_dv"], kwargs["generate_dv"]) class FakeService: - def __init__(self, ctx: click.Context) -> None: - pass + cli = click.Command("svc", callback=lambda title: object()) monkeypatch.setattr(dl_module, "dl", FakeDl) monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path)) diff --git a/tests/core/test_metadata_id_validation.py b/tests/core/test_metadata_id_validation.py index d4803d03..0552f171 100644 --- a/tests/core/test_metadata_id_validation.py +++ b/tests/core/test_metadata_id_validation.py @@ -2,12 +2,11 @@ from __future__ import annotations -import click import pytest -from unshackle.commands.dl import validate_metadata_ids from unshackle.core.api.handlers import validate_download_parameters from unshackle.core.config import config +from unshackle.core.run_plan import PlanError, validate_metadata_ids @pytest.fixture(autouse=True) @@ -25,7 +24,7 @@ def with_keys(monkeypatch: pytest.MonkeyPatch, **keys: str) -> None: [(27205, "tt1375666", None), (27205, None, 73871), (None, "tt1375666", 73871), (27205, "tt1375666", 73871)], ) def test_two_ids_are_refused(tmdb: int | None, imdb: str | None, tvdb: int | None) -> None: - with pytest.raises(click.UsageError) as exc: + with pytest.raises(PlanError) as exc: validate_metadata_ids(tmdb, imdb, tvdb) assert "cannot be used together" in str(exc.value) @@ -41,14 +40,14 @@ def test_imdb_alone_passes_on_the_keyless_provider(monkeypatch: pytest.MonkeyPat def test_tmdb_without_its_key_names_the_key(monkeypatch: pytest.MonkeyPatch) -> None: with_keys(monkeypatch) - with pytest.raises(click.UsageError) as exc: + with pytest.raises(PlanError) as exc: validate_metadata_ids(27205, None, None) assert "--tmdb" in str(exc.value) and "tmdb_api_key" in str(exc.value) def test_tvdb_without_its_key_names_the_key(monkeypatch: pytest.MonkeyPatch) -> None: with_keys(monkeypatch) - with pytest.raises(click.UsageError) as exc: + with pytest.raises(PlanError) as exc: validate_metadata_ids(None, None, 73871) assert "--tvdb" in str(exc.value) and "tvdb_api_key" in str(exc.value) @@ -61,7 +60,7 @@ def test_tmdb_with_its_key_passes(monkeypatch: pytest.MonkeyPatch) -> None: def test_a_provider_filtered_out_of_the_order_points_at_the_config(monkeypatch: pytest.MonkeyPatch) -> None: with_keys(monkeypatch, tmdb_api_key="k") monkeypatch.setattr(config, "metadata_providers", ["imdb", "omdb"]) - with pytest.raises(click.UsageError) as exc: + with pytest.raises(PlanError) as exc: validate_metadata_ids(27205, None, None) assert "metadata_providers" in str(exc.value) @@ -69,7 +68,7 @@ def test_a_provider_filtered_out_of_the_order_points_at_the_config(monkeypatch: def test_imdb_is_unresolvable_when_the_order_drops_both_of_its_providers(monkeypatch: pytest.MonkeyPatch) -> None: with_keys(monkeypatch) monkeypatch.setattr(config, "metadata_providers", ["tmdb", "tvdb"]) - with pytest.raises(click.UsageError) as exc: + with pytest.raises(PlanError) as exc: validate_metadata_ids(None, "tt1375666", None) assert "metadata_providers" in str(exc.value) assert "imdb" in str(exc.value) and "omdb" in str(exc.value) @@ -92,7 +91,7 @@ def test_one_kind_keeping_the_provider_is_enough(monkeypatch: pytest.MonkeyPatch ) def test_api_refuses_two_ids(payload: dict) -> None: err = validate_download_parameters(payload) - assert err and "multiple external IDs" in err + assert err and "cannot be used together" in err @pytest.mark.parametrize("payload", [{"tmdb_id": 27205}, {"imdb_id": "tt1375666"}, {"tvdb_id": 73871}, {}]) @@ -118,7 +117,7 @@ def test_anilist_pairs_with_one_other_id(monkeypatch: pytest.MonkeyPatch) -> Non def test_anilist_does_not_excuse_two_western_ids(monkeypatch: pytest.MonkeyPatch) -> None: with_keys(monkeypatch) - with pytest.raises(click.UsageError) as exc: + with pytest.raises(PlanError) as exc: validate_metadata_ids(27205, "tt1375666", None, 21) assert "cannot be used together" in str(exc.value) @@ -126,7 +125,7 @@ def test_anilist_does_not_excuse_two_western_ids(monkeypatch: pytest.MonkeyPatch @pytest.mark.parametrize("value", ["tt1375666", "anilist:21", "mal:", "abc", "-3"]) def test_a_malformed_anilist_value_is_refused(monkeypatch: pytest.MonkeyPatch, value: str) -> None: with_keys(monkeypatch) - with pytest.raises(click.UsageError) as exc: + with pytest.raises(PlanError) as exc: validate_metadata_ids(None, None, None, value) assert "--anilist" in str(exc.value) @@ -142,19 +141,19 @@ def test_api_accepts_anilist_alongside_one_western_id() -> None: def test_api_still_refuses_two_western_ids_with_anilist() -> None: err = validate_download_parameters({"tmdb_id": 27205, "imdb_id": "tt1375666", "anilist_id": 21}) - assert err and "multiple external IDs" in err + assert err and "cannot be used together" in err @pytest.mark.parametrize("value", [0, -3, True, "mal:", "tt1375666", "anilist:21", 1.5]) def test_api_refuses_a_malformed_anilist_id(value: object) -> None: err = validate_download_parameters({"anilist_id": value}) - assert err and "anilist_id" in err + assert err and "anilist" in err @pytest.mark.parametrize("value", ["0", "mal:0", "²", "21.5"]) def test_a_non_positive_or_non_decimal_anilist_value_is_refused(monkeypatch: pytest.MonkeyPatch, value: str) -> None: with_keys(monkeypatch) - with pytest.raises(click.UsageError) as exc: + with pytest.raises(PlanError) as exc: validate_metadata_ids(None, None, None, value) assert "--anilist" in str(exc.value) @@ -168,4 +167,11 @@ def test_api_accepts_what_the_cli_accepts(payload: dict) -> None: @pytest.mark.parametrize("value", ["0", "mal:0", "²"]) def test_api_refuses_what_the_cli_refuses(value: str) -> None: err = validate_download_parameters({"anilist_id": value}) - assert err and "anilist_id" in err + assert err and "anilist" in err + + +def test_api_refuses_an_id_no_configured_provider_can_find(monkeypatch: pytest.MonkeyPatch) -> None: + with_keys(monkeypatch) + assert validate_download_parameters({"tmdb_id": 27205}) == ( + "--tmdb needs the tmdb provider: set tmdb_api_key in your config" + ) diff --git a/tests/core/test_run_plan.py b/tests/core/test_run_plan.py new file mode 100644 index 00000000..2badfe70 --- /dev/null +++ b/tests/core/test_run_plan.py @@ -0,0 +1,106 @@ +"""The run plan: one check of the dl options for the CLI and the REST download job.""" + +from __future__ import annotations + +from typing import Any + +import click +import pytest +from click.core import ParameterSource + +from unshackle.commands.dl import dl +from unshackle.core.api.errors import categorize_exception +from unshackle.core.remote_protocol import APIErrorCode +from unshackle.core.run_plan import PlanError, api_plan, bitrate_range, check_options +from unshackle.core.tracks import Video + + +def cli_params(*args: str) -> dict[str, Any]: + """The dl params a CLI parse of ``args`` gives, with the service subcommand left out.""" + ctx = dl.cli.make_context("dl", [*args, "EXAMPLE"], resilient_parsing=True) + return ctx.params + + +@pytest.mark.parametrize( + ("args", "data", "message"), + [ + (["--sample", "--include-sample"], {"sample": True, "include_sample": True}, "--sample and --include-sample"), + (["--vbitrate", "5000", "--vbitrate-range", "1-2"], {"vbitrate": 5000, "vbitrate_range": "1-2"}, "--vbitrate"), + (["--abitrate-range", "1-2-3"], {"abitrate_range": "1-2-3"}, "Invalid --abitrate-range"), + (["-l", "all,-all"], {"lang": ["all", "-all"]}, "'all' cannot be excluded"), + (["--require-audio", "-en"], {"require_audio": ["-en"]}, "--require-audio: en cannot be required"), + (["-ado", "--no-audio"], {"audio_description_only": True, "no_audio": True}, "--audio-description-only"), + (["--enrich"], {"enrich": True}, "--enrich requires"), + (["-S", "--no-subs"], {"subs_only": True, "no_subs": True}, "--subs-only cannot be used with --no-subs"), + (["-V", "-A"], {"video_only": True, "audio_only": True}, None), + (["--tvdb-order", "official"], {"tvdb_order": "absolute", "tvdb_id": 1}, None), + ], +) +def test_the_cli_and_the_api_refuse_the_same_run(args: list[str], data: dict, message: str | None) -> None: + """Both front doors go through check_options, so a run dl refuses is a submit-time refusal over the API.""" + if message is None: + check_options(cli_params(*args)) + return + with pytest.raises(PlanError, match=message): + check_options(cli_params(*args)) + with pytest.raises(PlanError, match=message): + api_plan(data) + + +def test_select_titles_and_wanted_are_refused() -> None: + with pytest.raises(PlanError, match="--select-titles"): + check_options({"select_titles": True, "wanted": ["1x1"]}) + + +def test_hybrid_needs_dovi_tool(monkeypatch: pytest.MonkeyPatch) -> None: + import unshackle.core.binaries as binaries + + monkeypatch.setattr(binaries, "DoviTool", None) + with pytest.raises(PlanError, match="dovi_tool"): + check_options({"range_": [Video.Range.HDR10], "generate_dv": True}) + check_options({"range_": [Video.Range.HDR10]}) + + +def test_a_plan_error_exits_1_without_a_usage_block() -> None: + assert PlanError("x").exit_code == 1 + assert not isinstance(PlanError("x"), click.UsageError) + + +def test_a_plan_error_is_an_invalid_parameters_api_error() -> None: + error = categorize_exception(PlanError("--sample and --include-sample cannot be used together.")) + assert error.error_code is APIErrorCode.INVALID_PARAMETERS + assert error.message == "--sample and --include-sample cannot be used together." + + +@pytest.mark.parametrize(("value", "expected"), [("6000-7000", (6000, 7000)), ("7000-6000", (6000, 7000)), ("", None)]) +def test_bitrate_range_orders_its_ends(value: str, expected: Any) -> None: + assert bitrate_range(value, "--vbitrate-range", "6000-7000") == expected + + +def test_the_api_plan_shapes_wanted_and_slow() -> None: + plan = api_plan({"wanted": "S01E01, S01E02", "slow": [20, 40]}) + assert sorted(plan.params["wanted"]) == ["1x1", "1x2"] + assert plan.params["slow"] == (20, 40) + assert api_plan({"slow": True}).params["slow"] == (60, 120) + with pytest.raises(PlanError, match="slow"): + api_plan({"slow": [1, 2]}) + with pytest.raises(PlanError, match="wanted"): + api_plan({"wanted": [1]}) + + +def test_the_api_plan_records_where_each_value_came_from() -> None: + plan = api_plan({"workers": 4, "quality": [1080], "cdm": "dev", "remote": "box"}, client_keys={"workers", "cdm"}) + assert plan.sources["workers"] is ParameterSource.COMMANDLINE + assert plan.sources["cdm_name"] is ParameterSource.COMMANDLINE + assert plan.sources["quality"] is ParameterSource.DEFAULT + assert plan.sources["server"] is ParameterSource.DEFAULT + assert (plan.params["cdm_name"], plan.params["remote"], plan.params["server"]) == ("dev", True, "box") + ctx = plan.context(dl.cli, "EXAMPLE") + assert ctx.invoked_subcommand == "EXAMPLE" + assert ctx.get_parameter_source("workers") is ParameterSource.COMMANDLINE + assert ctx.params == plan.params + + +def test_dl_checks_the_plan_before_the_service_loads() -> None: + with pytest.raises(PlanError, match="--sample and --include-sample"): + dl.cli.main(["--sample", "--include-sample", "EXAMPLE", "t"], standalone_mode=False) diff --git a/tests/lang_selection/test_kind_only_flags.py b/tests/lang_selection/test_kind_only_flags.py index 4888c33b..42777ac4 100644 --- a/tests/lang_selection/test_kind_only_flags.py +++ b/tests/lang_selection/test_kind_only_flags.py @@ -57,7 +57,8 @@ def test_kind_only_conflict(params, expected): def test_api_rejects_a_conflict(): assert validate_download_parameters({**BASE, "audio_description_only": True, "no_audio": True}) == ( - "Cannot use both audio_description_only and no_audio" + "--audio-description-only cannot be used with --no-audio: --no-audio drops the tracks that " + "--audio-description-only selects." ) assert validate_download_parameters({**BASE, "audio_description_only": True, "audio_only": True}) is None diff --git a/tests/lang_selection/test_required_langs_gate.py b/tests/lang_selection/test_required_langs_gate.py index d06e169b..28907843 100644 --- a/tests/lang_selection/test_required_langs_gate.py +++ b/tests/lang_selection/test_required_langs_gate.py @@ -14,6 +14,7 @@ from langcodes import Language from tests.lang_selection import test_kind_only_selection as harness from tests.lang_selection.test_track_selection import audio, episode, selection, standard, video +from unshackle.core.run_plan import PlanError, check_options from unshackle.core.tracks.selection import Kept, Skip from unshackle.core.utilities import missing_required_langs @@ -98,11 +99,9 @@ def test_every_kind_misses_in_one_reason() -> None: ({"require_audio": ["-en"]}, "--require-audio: en"), ], ) -def test_a_required_and_excluded_language_stops_the_run( - monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, flags: dict[str, Any], clash: str -) -> None: - assert harness.run(monkeypatch, caplog, {1: {}}, **flags) == 1 - assert f"{clash} cannot be required and excluded at the same time." in caplog.text +def test_a_required_and_excluded_language_is_refused(flags: dict[str, Any], clash: str) -> None: + with pytest.raises(PlanError, match=f"^{clash} cannot be required and excluded at the same time.$"): + check_options(flags) def test_a_language_override_does_not_inherit_the_lang_exclusions( diff --git a/tests/remote/unit/test_api_dl_options.py b/tests/remote/unit/test_api_dl_options.py index 1e281c0d..0d9b05ae 100644 --- a/tests/remote/unit/test_api_dl_options.py +++ b/tests/remote/unit/test_api_dl_options.py @@ -11,7 +11,6 @@ from unshackle.commands.dl import dl 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, @@ -54,15 +53,10 @@ def test_the_server_reads_back_what_a_remote_client_forwards(): def test_api_defaults_cast_to_the_dl_defaults(): - """An API-shaped option keeps its own empty default, which perform_download normalizes.""" + """``wanted`` keeps its API default of no keys, which dl reads as every title, like the CLI's None.""" ctx = click.Context(dl.cli) - expected = { - p.name: p.type_cast_value(ctx, p.get_default(ctx)) - for p in dl.cli.params - if p.name not in CLI_ONLY | API_SHAPED_DL_PARAMS - } - cast = cast_dl_params(dl.cli, {}) - assert {k: v for k, v in cast.items() if k not in API_SHAPED_DL_PARAMS} == expected + expected = {p.name: p.type_cast_value(ctx, p.get_default(ctx)) for p in dl.cli.params if p.name not in CLI_ONLY} + assert cast_dl_params(dl.cli, {}) == {**expected, "wanted": []} def test_cli_only_options_never_reach_dl(): @@ -107,7 +101,7 @@ def test_values_are_cast_by_the_dl_click_types(): 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["slow"], cast["wanted"]) == ((20, 40), ["1x1"]) 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"]) @@ -186,8 +180,8 @@ def test_api_refuses_a_value_the_dl_option_cannot_take(data, error): def test_no_dl_option_needs_a_parse_step_the_cast_skips(): - """type_cast_value runs no callback and no required check, so neither may appear on a dl option.""" - assert not [p.name for p in dl.cli.params if p.callback or p.required] + """type_cast_value runs no callback, required check or envvar lookup, so none may appear on a dl option.""" + assert not [p.name for p in dl.cli.params if p.callback or p.required or getattr(p, "envvar", None)] def test_null_takes_the_api_default(): diff --git a/tests/remote/unit/test_api_episode_part.py b/tests/remote/unit/test_api_episode_part.py index 5ba870e7..c808469f 100644 --- a/tests/remote/unit/test_api_episode_part.py +++ b/tests/remote/unit/test_api_episode_part.py @@ -2,7 +2,7 @@ Covers serialize_title's conditional `part` key, the list-tracks wanted filter routing through Episode.matches_wanted, the discrete season/episode/part request -fields, and download_manager's already-internal wanted sniff. +fields, and SeasonRange.convert passing already-parsed wanted keys through. """ from __future__ import annotations @@ -17,6 +17,7 @@ import pytest from unshackle.core.api import handlers from unshackle.core.api.errors import APIError from unshackle.core.titles.episode import Episode +from unshackle.core.utils.click_types import SEASON_RANGE from unshackle.core.wire import build_title, serialize_title pytestmark = pytest.mark.unit @@ -202,68 +203,29 @@ def test_rest_multi_episode_order_is_stable_across_parts(monkeypatch) -> None: assert selected(result) == ["1x1.1", "1x1.2", "1x1.3", "1x2"] -SNIFF = r"^!?\d+x\d+(\.\d+)?$" - - @pytest.mark.parametrize( - "wanted, internal", + ("wanted", "parsed"), [ - (["1x1"], True), # today's pre-parsed form - (["1x1", "1x2"], True), - (["1x1.2"], True), # part key - (["!1x1.2"], True), # negative part key - (["1x1", "!1x1.2"], True), - (["S01E01"], False), - (["s1e1.2"], False), - (["S01"], False), - (["1x1", "S01E02"], False), + (["1x1"], ["1x1"]), + (["1x1.2"], ["1x1.2"]), + (["!1x1.2"], ["!1x1.2"]), + (["1x1", "!1x1.2"], ["1x1", "!1x1.2"]), + ("1x1, 1x2", ["1x1", "1x2"]), + (["1x01"], ["1x1"]), ], ) -def test_download_manager_sniff_regex(wanted: List[str], internal: bool) -> None: - needs_conversion = any(not re.match(SNIFF, w) for w in wanted) - assert needs_conversion is (not internal) +def test_parsed_keys_pass_unchanged(wanted: Any, parsed: List[str]) -> None: + """A pre-parsed part or negative key never reaches parse_tokens, which cannot read it.""" + assert SEASON_RANGE.convert(wanted) == parsed -def test_sniff_regex_matches_the_one_in_download_manager() -> None: - """Guard the copy above against drift from the production regex.""" - from pathlib import Path - - import unshackle.core.api.download_manager as dm - - source = Path(dm.__file__).read_text(encoding="utf8") - assert f'needs_conversion = any(not re.match(r"{SNIFF}", w) for w in wanted_raw)' in source +@pytest.mark.parametrize("wanted", [["S01E01"], "S01E01", ["s1e1"], "s1e1; S01E01"]) +def test_tokens_parse_from_a_list_or_a_separated_string(wanted: Any) -> None: + assert SEASON_RANGE.convert(wanted) == ["1x1"] -def test_perform_download_skips_reconversion_for_preparsed_part_keys(monkeypatch) -> None: - """A pre-parsed list with part and negative keys must not reach parse_tokens.""" - from unshackle.core.api.download_manager import perform_download - from unshackle.core.utils.click_types import SeasonRange - - calls = [] - monkeypatch.setattr(SeasonRange, "parse_tokens", lambda self, *t: calls.append(t) or []) - - params: Dict[str, Any] = {"wanted": ["1x1", "1x1.2", "!1x1.3"]} - with pytest.raises(BaseException): - # blows up later on the unknown service; the wanted block runs first - perform_download("job-1", "NoSuchServiceXYZ", "t1", params) - - assert calls == [] - assert params["wanted"] == ["1x1", "1x1.2", "!1x1.3"] - - -def test_perform_download_still_converts_cli_style_tokens(monkeypatch) -> None: - from unshackle.core.api.download_manager import perform_download - from unshackle.core.utils.click_types import SeasonRange - - calls = [] - monkeypatch.setattr(SeasonRange, "parse_tokens", lambda self, *t: calls.append(t) or ["1x1"]) - - params: Dict[str, Any] = {"wanted": "S01E01"} - with pytest.raises(BaseException): - perform_download("job-2", "NoSuchServiceXYZ", "t1", params) - - assert calls == [("S01E01",)] - assert params["wanted"] == ["1x1"] +def test_a_mixed_list_parses_every_token() -> None: + assert sorted(SEASON_RANGE.convert(["1x1", "S01E02"])) == ["1x1", "1x2"] def test_dl_and_handlers_share_the_one_match_helper() -> None: diff --git a/tests/remote/unit/test_api_quality_param.py b/tests/remote/unit/test_api_quality_param.py index 567a4570..c44acbe0 100644 --- a/tests/remote/unit/test_api_quality_param.py +++ b/tests/remote/unit/test_api_quality_param.py @@ -36,8 +36,7 @@ def test_a_rest_job_converts_quality_and_passes_cdm_only(tmp_path: Path, monkeyp raise _Captured(self.ctx.params["quality"], kwargs["quality"], self.ctx.params["cdm_only"]) class FakeService: - def __init__(self, ctx: click.Context) -> None: - pass + cli = click.Command("svc", callback=lambda title: object()) monkeypatch.setattr(dl_module, "dl", FakeDl) monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path)) diff --git a/tests/remote/unit/test_api_service_dl_overrides.py b/tests/remote/unit/test_api_service_dl_overrides.py index ed628129..53b04bf5 100644 --- a/tests/remote/unit/test_api_service_dl_overrides.py +++ b/tests/remote/unit/test_api_service_dl_overrides.py @@ -109,7 +109,7 @@ def test_client_sent_keys_without_stamp_counts_all_keys(): assert dm.client_sent_keys({"workers": 1, "quality": None}) == {"workers", "quality"} -def test_service_defaults_and_options_travel_nested(env, monkeypatch): +def test_service_options_travel_nested_without_their_defaults(env, monkeypatch): @click.command() @click.option("--profile", type=int, default=1) @click.option("--device", default="chrome") @@ -119,8 +119,8 @@ def test_service_defaults_and_options_travel_nested(env, monkeypatch): monkeypatch.setattr(handlers.Services, "load", lambda service: SimpleNamespace(cli=cli)) params = env(body={"profile": "work", "service_params": {"profile": 2}}) assert params["profile"] == "work" - assert params["service_params"] == {"profile": 2, "device": "chrome"} - assert env(body={"device": "tv"})["service_params"] == {"profile": 1, "device": "tv"} + assert params["service_params"] == {"profile": 2} + assert env(body={"device": "tv"})["service_params"] == {"device": "tv"} def use_cli(monkeypatch, *options): @@ -157,4 +157,4 @@ def test_a_json_shape_click_cannot_convert_is_a_400(env, monkeypatch, name, valu def test_a_flat_dl_key_never_fills_a_service_option_of_the_same_name(env, monkeypatch): use_cli(monkeypatch, click.Option(["--quality"], type=click.Choice(["SD", "HD"]), default="HD")) - assert env(body={"quality": [1080]})["service_params"] == {"quality": "HD"} + assert env(body={"quality": [1080]})["service_params"] == {} diff --git a/tests/remote/unit/test_download_manager.py b/tests/remote/unit/test_download_manager.py index f08ea3fc..a0bf0f98 100644 --- a/tests/remote/unit/test_download_manager.py +++ b/tests/remote/unit/test_download_manager.py @@ -241,8 +241,7 @@ def test_perform_download_passes_latest_episodes_to_dl_result(tmp_path: Path, mo raise _CapturedCtx(kwargs) class FakeService: - def __init__(self, ctx: click.Context) -> None: - pass + cli = click.Command("svc", callback=lambda title: object()) monkeypatch.setattr(dl_module, "dl", FakeDl) monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path)) @@ -277,8 +276,9 @@ def test_perform_download_gives_dl_the_defaults_for_null_and_empty_values( raise RuntimeError("stop") class FakeService: - def __init__(self, ctx: click.Context) -> None: - seen["parent"] = dict(ctx.parent.params) + cli = click.Command( + "svc", callback=click.pass_context(lambda ctx, title: seen.update(parent=dict(ctx.parent.params))) + ) monkeypatch.setattr(dl_module, "dl", FakeDl) monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path)) @@ -307,14 +307,16 @@ def test_perform_download_casts_service_options(tmp_path: Path, monkeypatch: pyt def __init__(self, ctx: click.Context, **kwargs: object) -> None: pass + def build(title: str, episodes: object, tag: object) -> None: + raise _CapturedCtx(episodes, tag) + class FakeService: cli = click.Command( - "svc", params=[click.Option(["--episodes"], type=int), click.Option(["--tag"], multiple=True)] + "svc", + params=[click.Option(["--episodes"], type=int), click.Option(["--tag"], multiple=True)], + callback=build, ) - def __init__(self, ctx: click.Context, episodes: object = None, tag: object = ()) -> None: - raise _CapturedCtx(episodes, tag) - monkeypatch.setattr(dl_module, "dl", FakeDl) monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path)) monkeypatch.setattr(Services, "load", staticmethod(lambda s: FakeService)) @@ -669,28 +671,25 @@ async def test_a_skip_written_just_before_the_worker_exits_reaches_the_job( def test_a_stopped_run_names_its_reason_in_the_job_error(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - import sys - import click import unshackle.commands.dl as dl_module from unshackle.core.api import download_manager, handlers from unshackle.core.api.errors import APIError + from unshackle.core.run_plan import RunStopped from unshackle.core.services import Services class FakeDl: cli = dl_module.dl.cli def __init__(self, ctx: click.Context, **kwargs: object) -> None: - self.stop_reason = None + pass def result(self, **kwargs: object) -> None: - self.stop_reason = "Show S01E01: Required audio language(s) not found: ko" - sys.exit(1) + raise RunStopped("Show S01E01: Required audio language(s) not found: ko") class FakeService: - def __init__(self, ctx: click.Context) -> None: - pass + cli = click.Command("svc", callback=lambda title: object()) monkeypatch.setattr(dl_module, "dl", FakeDl) monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path)) diff --git a/tests/remote/unit/test_handlers_serialize.py b/tests/remote/unit/test_handlers_serialize.py index b0411335..d23406fb 100644 --- a/tests/remote/unit/test_handlers_serialize.py +++ b/tests/remote/unit/test_handlers_serialize.py @@ -301,17 +301,17 @@ def test_validate_download_params_accepts_defaults() -> None: ({"vbitrate": -1}, "vbitrate"), ({"abitrate": "no"}, "abitrate"), ({"vbitrate_range": "no-dash-but-letters"}, "MIN-MAX"), - ({"vbitrate": 5000, "vbitrate_range": "1-2"}, "vbitrate and vbitrate_range"), - ({"abitrate": 128, "abitrate_range": "96-256"}, "abitrate and abitrate_range"), + ({"vbitrate": 5000, "vbitrate_range": "1-2"}, "--vbitrate and --vbitrate-range"), + ({"abitrate": 128, "abitrate_range": "96-256"}, "--abitrate and --abitrate-range"), ({"abitrate_range": "1-2-3"}, "MIN-MAX"), ({"quality": "4k"}, "Invalid quality"), ({"quality": [0]}, "above 0"), ({"channels": -3}, "channels"), ({"workers": 0}, "workers"), ({"downloads": 0}, "downloads"), - ({"video_only": True, "audio_only": True}, "exclusive"), - ({"no_subs": True, "subs_only": True}, "no_subs and subs_only"), - ({"no_audio": True, "audio_only": True}, "no_audio and audio_only"), + ({"video_only": True, "audio_only": True}, None), + ({"no_subs": True, "subs_only": True}, "--subs-only cannot be used with --no-subs"), + ({"no_audio": True, "audio_only": True}, "--audio-only cannot be used with --no-audio"), ({"require_subs": "en"}, "require_subs must be an array"), ({"range": "UHD"}, "Invalid range"), ({"range": ["SDR", "UHD"]}, "Invalid range"), diff --git a/tests/remote/unit/test_server_cdm_max_height.py b/tests/remote/unit/test_server_cdm_max_height.py index de23ba24..da486eb3 100644 --- a/tests/remote/unit/test_server_cdm_max_height.py +++ b/tests/remote/unit/test_server_cdm_max_height.py @@ -335,7 +335,7 @@ def test_a_service_click_default_stays_out_of_the_download_gate(monkeypatch): monkeypatch.setattr(dm, "get_download_manager", Manager) body = {"service": "EXAMPLE1", "title_id": "t1", "quality": [1080]} asyncio.run(handlers.download_handler(body, request("flat"))) - assert jobs[0]["service_params"] == {"best_available": True} + assert jobs[0]["service_params"] == {} assert not jobs[0].get("best_available") diff --git a/tests/test_sample.py b/tests/test_sample.py index 0c1b397a..ab49565c 100644 --- a/tests/test_sample.py +++ b/tests/test_sample.py @@ -296,7 +296,7 @@ def test_the_api_refuses_a_bad_sample_window(sample: object) -> None: def test_the_api_refuses_sample_with_include_sample() -> None: - assert "include_sample" in (validate_download_parameters({"sample": True, "include_sample": True}) or "") + assert "--include-sample" in (validate_download_parameters({"sample": True, "include_sample": True}) or "") def test_sample_name_uses_the_separator_of_the_template(monkeypatch: pytest.MonkeyPatch) -> None: diff --git a/unshackle/commands/dl.py b/unshackle/commands/dl.py index 4d76f2c6..d0a058c5 100644 --- a/unshackle/commands/dl.py +++ b/unshackle/commands/dl.py @@ -66,7 +66,6 @@ from unshackle.core.launch import LaunchKeys, launch, load_service_config from unshackle.core.manifests.snapshot import capture from unshackle.core.mux_step import mux_title from unshackle.core.placement import SAMPLE_DIR, Placement, sample_name -from unshackle.core.providers.anilist import parse_anilist_ref from unshackle.core.providers.tvdb import SEASON_TYPES, parse_int from unshackle.core.proxies.resolve import ( REGION, @@ -79,6 +78,7 @@ from unshackle.core.proxies.resolve import ( resolve_proxy, split_proxy_query, ) +from unshackle.core.run_plan import PlanError, RunOutcome, RunStopped, bitrate_range, check_options from unshackle.core.service import Service, grow_session_pool from unshackle.core.services import ROUTING_PARAMS, Services from unshackle.core.temp import with_task_temp @@ -87,7 +87,7 @@ from unshackle.core.titles import Movie, Movies, Series, Song, Title_T from unshackle.core.titles.episode import Episode from unshackle.core.tracks import Audio, Subtitle, Tracks, Video from unshackle.core.tracks.attachment import Attachment -from unshackle.core.tracks.selection import HYBRID_BASE_RANGES, Skip, TrackSelection +from unshackle.core.tracks.selection import Skip, TrackSelection, generated_dv_ranges from unshackle.core.tracks.subtitle_convert import PYCAPTION_WRITERS, SUBSTATION, build_ass_style from unshackle.core.tracks.track import ( Track, @@ -100,8 +100,8 @@ from unshackle.core.utilities import ( find_font_with_fallbacks, get_debug_logger, get_system_fonts, + inherited_exclusions, init_debug_logger, - kind_only_conflict, log_event, matching_languages, partition_exclusions, @@ -166,47 +166,6 @@ def normalize_dl_config(dl_config: dict[str, Any]) -> dict[str, Any]: return {DL_OPTION_ALIASES.get(key, key): value for key, value in dl_config.items()} -ID_PROVIDER_KEYS = {"tmdb": "tmdb_api_key", "tvdb": "tvdb_api_key", "omdb": "omdb_api_key"} - - -def validate_metadata_ids( - tmdb_id: Optional[int], - imdb_id: Optional[str], - tvdb_id: Optional[int], - anilist_id: Optional[Union[int, str]] = None, -) -> None: - """Reject ID flags that conflict, or that no configured metadata provider could ever find. - - --anilist stays outside the mutual exclusion: AniList knows no western IDs, so pairing - it with one of the other three is how an anime title gets both. - """ - if anilist_id and not parse_anilist_ref(anilist_id): - raise click.UsageError("--anilist takes an AniList ID like 21, or a MyAnimeList ID like mal:21.") - - supplied = [ - (flag, value) for flag, value in (("--tmdb", tmdb_id), ("--imdb", imdb_id), ("--tvdb", tvdb_id)) if value - ] - if len(supplied) > 1: - raise click.UsageError(f"{', '.join(flag for flag, _ in supplied)} cannot be used together; give one ID") - if not supplied: - return - - flag, _ = supplied[0] - id_kind = flag.lstrip("-") - ordered = {cls.NAME: cls for kind in ("tv", "movie") for cls in providers.provider_order(kind)} - consumers = [cls for cls in ordered.values() if cls.ID_KIND == id_kind] - if any(cls().is_available() for cls in consumers): - return - - if consumers: - keys = sorted({ID_PROVIDER_KEYS[cls.NAME] for cls in consumers if cls.NAME in ID_PROVIDER_KEYS}) - raise click.UsageError(f"{flag} needs the {consumers[0].NAME} provider: set {' or '.join(keys)} in your config") - names = sorted({cls.NAME for cls in providers.REGISTRY.values() if cls.ID_KIND == id_kind}) - raise click.UsageError( - f"{flag} needs the {' or '.join(names)} provider, which your metadata_providers config leaves out." - ) - - def convert_scc(subtitle: Subtitle, sub_format: Optional[Union[Subtitle.Codec, str]]) -> Subtitle.Codec: """ Convert an SCC subtitle to sub_format when pycaption can write it, else to SRT, and return the new codec. @@ -221,21 +180,6 @@ def convert_scc(subtitle: Subtitle, sub_format: Optional[Union[Subtitle.Codec, s return target -def generated_dv_ranges( - range_: Sequence[Video.Range], generate_dv: bool -) -> tuple[list[Video.Range], list[Video.Range]]: - """Turn ``-r HDR10 --generate-dv`` (or HDR10P) into a HYBRID run on that base alone. - - Returns the ranges to run with, and the base ranges the user named. The second list is empty when - the flag is off, HYBRID or DV is in the ranges, or no base range is. The service still gets the - ranges the user gave, so it fetches no DV track. - """ - bases = [r for r in range_ if r in HYBRID_BASE_RANGES] - if not generate_dv or not bases or Video.Range.HYBRID in range_ or Video.Range.DV in range_: - return list(range_), [] - return [Video.Range.HYBRID, *(r for r in range_ if r not in bases)], bases - - def subtitle_look( sub_format: Optional[Union[Subtitle.Codec, str]], sub_font: Optional[str], @@ -1219,8 +1163,6 @@ class dl: # report which weren't available without parsing the console output. See SkippedSubtitle. self.skipped_subtitles: list[SkippedSubtitle] = [] self.skipped_titles: list[SkippedTitle] = [] - # Why a missing track or language stopped the run, for the API job error. - self.stop_reason: Optional[str] = None # result() catches a download-worker failure, reports it, and returns rather than # re-raising (so the CLI still exits cleanly). Keep it so an embedding caller (the API # worker) can tell the title did not complete instead of reading it as a success. @@ -1251,14 +1193,12 @@ class dl: self.profile = profile self.proxy_requested = bool(proxy) - validate_metadata_ids(tmdb_id, imdb_id, tvdb_id, anilist_id) + check_options(ctx.params) self.tmdb_id = tmdb_id self.imdb_id = imdb_id self.tvdb_id = tvdb_id self.anilist_id = anilist_id self.tvdb_order = (tvdb_order or config.tvdb_order or "").lower() - if self.tvdb_order and self.tvdb_order not in SEASON_TYPES: - raise click.UsageError(f"tvdb_order must be one of {', '.join(SEASON_TYPES)}, not {self.tvdb_order!r}") self.continuous_episodes = continuous_episodes self.enrich = enrich self.daily = daily @@ -1266,11 +1206,6 @@ class dl: self.service_anime = False self.service_daily = False - if self.enrich and not (self.tmdb_id or self.imdb_id or self.tvdb_id or self.anilist_id): - raise click.UsageError( - "--enrich requires --tmdb, --imdb, --tvdb, or --anilist to provide a metadata source." - ) - if self.daily and not self.enrich: self.log.warning("--daily takes TVDB air dates only with --enrich") @@ -1418,10 +1353,9 @@ class dl: try: self.cdm = self.get_cdm(self.service, self.profile) except ValueError as e: - self.log.error(f"Failed to load CDM, {e}") if self.debug_logger: self.debug_logger.log_error("load_cdm", e, service=self.service) - sys.exit(1) + raise click.ClickException(f"Failed to load CDM, {e}") from None if self.cdm: cdm_info = cdm_summary(self.cdm) @@ -1462,8 +1396,7 @@ class dl: try: requested_provider, query = split_proxy_query(proxy, self.proxy_providers) except ValueError as e: - self.log.error(str(e)) - sys.exit(1) + raise PlanError(str(e)) from None # Match region codes (us, ca, uk1, us:ny, yul) or provider:region (nordvpn:ca, protonvpn:us:ny). if re.fullmatch(rf"(?:[a-z]+:)?{REGION}", query, re.IGNORECASE): # Kept apart from ctx.params["proxy"], which becomes the URI: a service proxy_map keys on it. @@ -1479,8 +1412,7 @@ class dl: self.proxy_providers, proxy_query, requested_provider ) except ValueError as e: - self.log.error(str(e)) - sys.exit(1) + raise click.ClickException(str(e)) from None ctx.params["proxy"] = proxy_uri self.log.info(describe_proxy(proxy_provider, proxy_uri, proxy_query)) keys["proxy_query"] = proxy_query @@ -1514,6 +1446,10 @@ class dl: # able to keep `self` as the first positional self.cli._result_callback = self.result + def outcome(self) -> RunOutcome: + """What the run gave back so far, for an embedding caller such as the API job.""" + return RunOutcome(list(self.completed_files), list(self.skipped_subtitles), self.download_error) + @with_task_temp def result( self, @@ -1591,7 +1527,7 @@ class dl: generate_dv: bool = False, *_: Any, **__: Any, - ) -> None: + ) -> RunOutcome: if all_drm: DOWNLOAD_ALL_DRM.set() else: @@ -1601,8 +1537,6 @@ class dl: if continue_downloads: config.continue_downloads = True config.sample = sample - if sample and include_sample: - raise click.ClickException("--sample and --include-sample cannot be used together.") self.tmdb_searched = False self.search_source = None self.service_anime = bool(getattr(service, "ANIME", False)) @@ -1620,34 +1554,13 @@ class dl: a_lang, a_lang_excl = partition_exclusions(a_lang) s_lang, s_lang_excl = partition_exclusions(s_lang) forced_s_lang, fsl_excl = partition_exclusions(forced_s_lang) - for flag, excludes in ( - ("-l/--lang", lang_excl), - ("-vl/--v-lang", v_lang_excl), - ("-al/--a-lang", a_lang_excl), - ("-sl/--s-lang", s_lang_excl), - ("-fsl/--forced-s-lang", fsl_excl), - ): - if any(token.lower() == "all" for token in excludes): - self.log.error(f"{flag}: 'all' cannot be excluded") - sys.exit(1) # exclusion-only use falls back to the flag's own default; -vl/-al have none, they cascade to -l if lang_excl and not lang: lang = ["orig"] if s_lang_excl and not s_lang: s_lang = ["all"] - # an override that names languages replaces -l entirely, so it must not inherit its exclusions - video_excl = list(dict.fromkeys(v_lang_excl + ([] if v_lang else lang_excl))) - audio_excl = list(dict.fromkeys(a_lang_excl + ([] if a_lang else lang_excl))) - for flag, tokens, excludes in ( - ("--require-audio", require_audio, audio_excl), - ("--require-video", require_video, video_excl), - ("--require-subs", require_subs, s_lang_excl), - ): - required, own_excl = partition_exclusions(tokens) - clash = own_excl + [t for t in required if any(t.lower() == e.lower() for e in excludes)] - if clash: - self.log.error(f"{flag}: {clash[0]} cannot be required and excluded at the same time.") - sys.exit(1) + video_excl = inherited_exclusions(v_lang, v_lang_excl, lang_excl) + audio_excl = inherited_exclusions(a_lang, a_lang_excl, lang_excl) ctx = getattr(service, "ctx", None) parent_params = ctx.parent.params if ctx and ctx.parent else None @@ -1663,23 +1576,6 @@ class dl: if excludes and name in parent_params: parent_params[name] = includes - conflict = kind_only_conflict( - { - "audio_description_only": audio_description_only, - "forced_subs_only": forced_subs_only, - "no_audio": no_audio, - "no_subs": no_subs, - "video_only": video_only, - "audio_only": audio_only, - "subs_only": subs_only, - "chapters_only": chapters_only, - } - ) - if conflict: - first, second = (f"--{name.replace('_', '-')}" for name in conflict) - self.log.error(f"{first} cannot be used with {second}: {second} drops the tracks that {first} selects.") - sys.exit(1) - if audio_description_only: audio_description = True @@ -1694,11 +1590,7 @@ class dl: if skip_dl: DOWNLOAD_LICENCE_ONLY.set() - try: - speed_limit_bps = parse_speed_limit(speed_limit) - except ValueError as e: - self.log.error(str(e)) - sys.exit(1) + speed_limit_bps = parse_speed_limit(speed_limit) set_speed_limit(speed_limit_bps) if speed_limit_bps: self.log.info(f"Speed limit: {format_speed(speed_limit_bps)}") @@ -1713,8 +1605,7 @@ class dl: try: proxy_download = resolve_proxy(proxy_download.lower(), self.proxy_providers) except ValueError as e: - self.log.error(f"--proxy-download: {e}") - sys.exit(1) + raise click.ClickException(f"--proxy-download: {e}") from None if export: config.directories.exports.mkdir(parents=True, exist_ok=True) @@ -1725,37 +1616,8 @@ class dl: else: export_path = None - vbitrate_min, vbitrate_max = None, None - if vbitrate_range: - if vbitrate and vbitrate_range: - self.log.error("Cannot use both --vbitrate and --vbitrate-range at the same time.") - sys.exit(1) - try: - parts = vbitrate_range.split("-") - if len(parts) != 2: - raise ValueError - vbitrate_min, vbitrate_max = int(parts[0]), int(parts[1]) - if vbitrate_min > vbitrate_max: - vbitrate_min, vbitrate_max = vbitrate_max, vbitrate_min - except (ValueError, IndexError): - self.log.error("Invalid --vbitrate-range: expected MIN-MAX, such as 6000-7000") - sys.exit(1) - - abitrate_min, abitrate_max = None, None - if abitrate_range: - if abitrate and abitrate_range: - self.log.error("Cannot use both --abitrate and --abitrate-range at the same time.") - sys.exit(1) - try: - parts = abitrate_range.split("-") - if len(parts) != 2: - raise ValueError - abitrate_min, abitrate_max = int(parts[0]), int(parts[1]) - if abitrate_min > abitrate_max: - abitrate_min, abitrate_max = abitrate_max, abitrate_min - except (ValueError, IndexError): - self.log.error("Invalid --abitrate-range: expected MIN-MAX, such as 128-256") - sys.exit(1) + vbitrate_min, vbitrate_max = bitrate_range(vbitrate_range, "--vbitrate-range", "6000-7000") or (None, None) + abitrate_min, abitrate_max = bitrate_range(abitrate_range, "--abitrate-range", "128-256") or (None, None) if not acodec: acodec = [] @@ -1766,10 +1628,6 @@ class dl: ): acodec = AUDIO_CODEC_LIST.convert(acodec) - if select_titles and wanted: - self.log.error("--select-titles and -w/--wanted cannot be used together") - sys.exit(1) - try: sub_format, ass_style = subtitle_look( sub_format, @@ -1779,18 +1637,11 @@ class dl: typed_format="sub_format" in self.typed_params, ) except ValueError as e: - self.log.error(str(e)) - sys.exit(1) + raise PlanError(str(e)) from None if generate_dv and Video.Range.DV in range_ and Video.Range.HYBRID not in range_: self.log.warning("--generate-dv ignored: DV is in the selected ranges") range_, generated_dv_bases = generated_dv_ranges(range_, generate_dv) - if any(r == Video.Range.HYBRID for r in range_): - from unshackle.core.binaries import DoviTool - - if not DoviTool: - self.log.error("Unable to run hybrid mode: dovi_tool not found") - sys.exit(1) if cdm_only is None: vaults_only = None @@ -1861,7 +1712,7 @@ class dl: message="No titles returned from service", success=False, ) - sys.exit(1) + raise RunStopped("No titles returned") except Exception as e: if self.debug_logger: self.debug_logger.log_error("get_titles", e, service=self.service) @@ -1943,7 +1794,7 @@ class dl: print_listing(titles.tree(verbose=list_titles)) if list_titles: - return + return self.outcome() if export_path and isinstance(titles, Series): # before --select-titles and -w drop titles, so a whole season can be told from part of one @@ -1961,7 +1812,7 @@ class dl: ) if not selected_idx: console.print(Padding(":x: Selection Cancelled...", (0, 5, 1, 5))) - return + return self.outcome() start_time += time.time() - selection_start keep = set(selected_idx) @@ -2022,7 +1873,7 @@ class dl: if not selected_ui_idx: console.print(Padding(":x: Selection Cancelled...", (0, 5, 1, 5))) - return + return self.outcome() selection_end = time.time() start_time += selection_end - selection_start @@ -2121,9 +1972,9 @@ class dl: stops the run. A run with one title always stops, because it has nothing else to download. """ if wanted_total <= 1 or not (kind_only or skip_missing): - self.stop_reason = f"{title}: {reason}" - self.log.error(self.stop_reason) - sys.exit(1) + stop = f"{title}: {reason}" + self.log.error(stop) + raise RunStopped(stop) self.skipped_titles.append(SkippedTitle(title=str(title), reason=reason)) if progress_sink: progress_sink({"skipped_titles": list(self.skipped_titles)}) @@ -2560,7 +2411,7 @@ class dl: self.keys.wait_vault_writes() if export_path: self.log_export_summary() - return + return self.outcome() except Exception as e: # noqa # Reported and swallowed (no re-raise) so the CLI exits cleanly; keep it so the # API worker sees the title failed rather than completing with no output. @@ -2596,7 +2447,7 @@ class dl: self.keys.wait_vault_writes() if export_path: self.log_export_summary() - return + return self.outcome() self.keys.wait_vault_writes() if export_path: @@ -2924,14 +2775,15 @@ class dl: self.log_export_summary() if self.skipped_titles: if len(self.skipped_titles) == wanted_total: - self.stop_reason = f"Skipped all {wanted_total} titles" - self.log.error(self.stop_reason) - sys.exit(1) + stop = f"Skipped all {wanted_total} titles" + self.log.error(stop) + raise RunStopped(stop) skipped = ", ".join(t["title"] for t in self.skipped_titles) self.log.warning(f"Skipped {len(self.skipped_titles)} of {wanted_total} titles: {skipped}") dl_time = time_elapsed_since(start_time) console.print(Padding(f"Processed all titles in [progress.elapsed]{dl_time}", (0, 5, 1, 5))) + return self.outcome() def write_sample(self, source: Path, title: Title_T, media_info: MediaInfo) -> None: """Cut a 60 second sample from a finished file into a ``Sample`` folder next to it. diff --git a/unshackle/core/api/download_manager.py b/unshackle/core/api/download_manager.py index 69cdf642..9a84229c 100644 --- a/unshackle/core/api/download_manager.py +++ b/unshackle/core/api/download_manager.py @@ -4,7 +4,6 @@ import importlib import json import logging import os -import re import sys import tempfile import threading @@ -21,7 +20,6 @@ from unshackle.core.api.events import bus, publish_service_event from unshackle.core.api.sanitize import sanitize_log from unshackle.core.credential import Credential from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_all, redact_path, redact_text -from unshackle.core.utils.service_params import cast_service_options, service_options if TYPE_CHECKING: from unshackle.core.service import Service @@ -378,11 +376,9 @@ def perform_download( ) -> List[str]: """Do the synchronous download work for a job. - `params` holds the API's string form of the `dl` options. The function first normalizes the API-shaped - options in place: `slow` accepts "MIN-MAX", a two-item list, or True (which means 60-120), and `wanted` - accepts forms such as "S01E01", "S01-S03", "s1e1", or "1x1" as well as the internal "SxE" form. Music takes track - numbers in the same field, such as "1-5" or "2x3" for disc 2 track 3. Then each dl click type casts its option - into ``ctx.params``, which feeds dl() and dl.result() as on the CLI. + ``params`` holds the API's form of the ``dl`` options; ``api_plan`` checks and casts them into the dl context, + which feeds dl() and dl.result() as on the CLI. The service is built through its click cli like every other + server path. """ from contextlib import redirect_stderr, redirect_stdout @@ -415,67 +411,12 @@ def perform_download( if params.pop(banned, None) is not None: log.warning(f"Ignoring '{banned}' in API download parameters; post-scripts are config-only") - client_keys = client_sent_keys(params) - - slow_raw = params.get("slow") - if slow_raw is not None and not isinstance(slow_raw, tuple): - if isinstance(slow_raw, bool): - params["slow"] = (60, 120) if slow_raw else None - elif isinstance(slow_raw, list) and len(slow_raw) == 2: - params["slow"] = (int(slow_raw[0]), int(slow_raw[1])) - elif isinstance(slow_raw, str): - from unshackle.core.utils.click_types import SLOW_DELAY_RANGE - - try: - params["slow"] = SLOW_DELAY_RANGE.convert(slow_raw, None, None) - except click.BadParameter as exc: - raise Exception(f"Invalid slow parameter: {exc}") - - wanted_raw = params.get("wanted") - if wanted_raw: - from unshackle.core.utils.click_types import SeasonRange - - if isinstance(wanted_raw, str): - # the CLI splits a comma-separated value before parsing, so a raw string must too - wanted_raw = re.split(r"\s*[,;]\s*", wanted_raw) - # the !? keeps a pre-parsed part exclusion from being re-fed through parse_tokens - needs_conversion = any(not re.match(r"^!?\d+x\d+(\.\d+)?$", w) for w in wanted_raw) - if needs_conversion: - season_range = SeasonRange() - params["wanted"] = season_range.parse_tokens(*wanted_raw) - - remote = params.get("remote") - - from unshackle.commands.dl import dl as dl_command - - ctx = click.Context(dl_command.cli) - ctx.invoked_subcommand = service - from unshackle.core.api.handlers import relay_label - from unshackle.core.dl_options import DL_OPTION_API_NAMES, cast_dl_params + from unshackle.core.api.handlers import DL_TRANSPORT_KEYS, instantiate_service, relay_label from unshackle.core.launch import launch + from unshackle.core.run_plan import RunStopped, api_plan - try: - dl_params = cast_dl_params(dl_command.cli, params) - except click.BadParameter as exc: - raise APIError(APIErrorCode.INVALID_PARAMETERS, exc.message) - ctx.params = { - **dl_params, - "cdm_name": params.get("cdm"), - # dl skips the local service config and guards the proxy for a remote_services server - "remote": bool(remote), - "server": remote, - } + ctx = api_plan(params, client_sent_keys(params)).context(dl.cli, service) launch(ctx, {"client_argv": f"{relay_label(params)} download job {job_id}"}) - # Hand-built context: record parameter sources so service dl overrides - # apply to defaults but never clobber client-sent values. - from click.core import ParameterSource - - for param_name in ctx.params: - source_key = DL_OPTION_API_NAMES.get(param_name, param_name) - ctx.set_parameter_source( - param_name, ParameterSource.COMMANDLINE if source_key in client_keys else ParameterSource.DEFAULT - ) - dl_instance = dl(ctx=ctx, proxy_providers=None if params.get("server_proxy") is True else [], **ctx.params) # Per-request credential ("user:pass"); feed it into the map get_credentials() reads so a # client can authenticate without anything being persisted to disk. Without a profile, @@ -487,45 +428,15 @@ def perform_download( config.credentials[service] = svc_creds = {} svc_creds[params.get("profile") or "default"] = params["credential"] - service_ctx = click.Context(click.Command(service), parent=ctx, obj=ctx.obj) + remote = ctx.params["server"] if remote: from unshackle.core.remote_service import make_remote_service + service_ctx = click.Context(click.Command(service), parent=ctx, obj=ctx.obj) # RemoteService duck-types Service for dl.result() service_instance = cast("Service", make_remote_service(service_ctx, remote, service, title_id, params)) else: - service_module = Services.load(service) - - try: - import inspect - - service_init_params = inspect.signature(service_module.__init__).parameters - - service_kwargs: Dict[str, Any] = {} - - if "title" in service_init_params: - service_kwargs["title"] = title_id - - cli_params = getattr(getattr(service_module, "cli", None), "params", None) or [] - options = service_options(params, service_init_params.keys() - {"title"}) - service_kwargs.update(cast_service_options(cli_params, service_ctx, options)) - - for param_name, param_info in service_init_params.items(): - if param_name not in service_kwargs and param_name not in ["self", "ctx"]: - if param_info.default is inspect.Parameter.empty: - if param_name == "movie": - service_kwargs[param_name] = "/movies/" in title_id - elif param_name == "meta_lang": - service_kwargs[param_name] = None - else: - log.warning(f"Unknown required parameter '{param_name}' for service {service}, using None") - service_kwargs[param_name] = None - - service_instance = service_module(service_ctx, **service_kwargs) - - except Exception as exc: # noqa: BLE001 - propagate meaningful failure - log.error(f"Failed to create service instance: {exc}") - raise + service_instance = instantiate_service(ctx, Services.load(service), title_id, params, DL_TRANSPORT_KEYS) original_download_dir = config.directories.downloads @@ -536,20 +447,23 @@ def perform_download( # (success/failure) is reported by the worker's result file. try: with redirect_stdout(stdout_capture), redirect_stderr(stderr_capture): - dl_instance.result( + outcome = dl_instance.result( service=service_instance, **{**ctx.params, "select_titles": False, "list_": False, "list_titles": False}, progress_sink=progress_callback, ) + except RunStopped as exc: + log.debug("Stdout: %s", stdout_capture.getvalue()) + raise APIError(APIErrorCode.DOWNLOAD_ERROR, f"Download failed: {exc.reason}") + except SystemExit as exc: if exc.code != 0: log.error(f"Download exited with code {exc.code}") log.debug("Stdout: %s", stdout_capture.getvalue()) log.debug("Stderr: %s", stderr_capture.getvalue()) - if reason := getattr(dl_instance, "stop_reason", None): - raise APIError(APIErrorCode.DOWNLOAD_ERROR, f"Download failed: {reason}") raise APIError(APIErrorCode.DOWNLOAD_ERROR, f"Download failed with exit code {exc.code}") + outcome = dl_instance.outcome() except Exception as exc: # noqa: BLE001 - propagate to caller log.error(f"Download execution failed: {exc}") @@ -557,19 +471,16 @@ def perform_download( log.debug("Stderr: %s", stderr_capture.getvalue()) raise - # dl.result() catches a download-worker exception, reports it, but returns normally (exit 0). - # It keeps the error in download_error, so the job isn't reported as completed with no output. - if (error := getattr(dl_instance, "download_error", None)) is not None: + # dl.result() reports a download-worker exception and returns normally, so the CLI exits cleanly. + if outcome.error is not None: # segment URLs carry signed CDN tokens (hmac, session IDs) that redact_text does not match - detail = redact_all(dl_instance.failure_lines(error)[1].strip()) + detail = redact_all(dl_instance.failure_lines(outcome.error)[1].strip()) raise APIError(APIErrorCode.WORKER_ERROR, f"download worker failed: {detail}") - if progress_callback: - skipped_subs = getattr(dl_instance, "skipped_subtitles", None) - if skipped_subs: - progress_callback({"skipped_subtitles": list(skipped_subs)}) + if progress_callback and outcome.skipped_subtitles: + progress_callback({"skipped_subtitles": outcome.skipped_subtitles}) - output_files = [str(p) for p in dl_instance.completed_files] + output_files = [str(p) for p in outcome.files] log.info(f"Download completed for job {job_id}, {len(output_files)} file(s) in {original_download_dir}") return output_files diff --git a/unshackle/core/api/handlers.py b/unshackle/core/api/handlers.py index fbdaf8ed..a970d7a4 100644 --- a/unshackle/core/api/handlers.py +++ b/unshackle/core/api/handlers.py @@ -1,7 +1,6 @@ import asyncio import base64 import copy -import enum import functools import json import logging @@ -41,13 +40,11 @@ from unshackle.core.config import config from unshackle.core.dl_options import ( DEFAULT_DOWNLOAD_PARAMS, DL_OPTION_API_NAMES, - cast_dl_params, forwarded_dl_params, ) from unshackle.core.drm import BlowfishStripe, cbcs, is_null_key, real_kids from unshackle.core.launch import load_service_config, served_context from unshackle.core.manifests.snapshot import capture -from unshackle.core.providers.anilist import parse_anilist_ref from unshackle.core.proxies.resolve import initialize_proxy_providers, is_loopback, resolve_proxy from unshackle.core.remote_protocol import ( HEALTH_ROUTE, @@ -70,6 +67,7 @@ from unshackle.core.remote_protocol import ( TracksReply, TracksRequest, ) +from unshackle.core.run_plan import PlanError, api_plan from unshackle.core.services import Services from unshackle.core.session import RnetSession, utf8_text from unshackle.core.titles import Episode, Song @@ -84,8 +82,8 @@ from unshackle.core.tunnel import ( is_public_ip, tunnel_proxy, ) -from unshackle.core.utilities import declared_kwargs, kind_only_conflict -from unshackle.core.utils.click_types import QUALITY_LIST, VIDEO_CODEC_LIST, ContextData +from unshackle.core.utilities import declared_kwargs +from unshackle.core.utils.click_types import QUALITY_LIST, SEASON_RANGE, VIDEO_CODEC_LIST, ContextData from unshackle.core.utils.collections import ci_get, merge_dict from unshackle.core.utils.hdr10plus import probed_tracks from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_all, redact_secrets, redact_text @@ -1675,23 +1673,12 @@ async def list_tracks_handler(data: Dict[str, Any], request: Optional[web.Reques wanted = None if wanted_param: - from unshackle.core.utils.click_types import SeasonRange - try: - season_range = SeasonRange() - if isinstance(wanted_param, list): - wanted = season_range.parse_tokens(*wanted_param) - else: - # convert(), not parse_tokens(), so a comma-separated string splits - # into tokens the way the CLI splits it - wanted = season_range.convert(wanted_param) - log.debug( - f"Parsed wanted '{sanitize_log(wanted_param)}' into {len(wanted)} episodes: {wanted[:10]}..." - ) - except (Exception, SystemExit) as e: + wanted = SEASON_RANGE.convert(wanted_param) + except click.BadParameter as e: raise APIError( APIErrorCode.INVALID_PARAMETERS, - f"Invalid wanted parameter: {e}", + f"Invalid wanted parameter: {e.message}", details={"wanted": wanted_param, "service": normalized_service}, ) elif season is not None and episode is not None: @@ -1813,19 +1800,11 @@ def resolve_vcodec(value: Any) -> Optional[list]: def wanted_refusal(wanted: Any) -> Optional[str]: - """Why the job worker could not parse ``wanted``, or None when it can.""" - if not wanted: - return None - from unshackle.core.utils.click_types import SeasonRange - - tokens = re.split(r"\s*[,;]\s*", wanted) if isinstance(wanted, str) else wanted - if not isinstance(tokens, list) or not all(isinstance(t, str) for t in tokens): - return "wanted must be a string or a list of strings" + """Why dl could not parse ``wanted``, or None when it can.""" try: - if any(not re.match(r"^!?\d+x\d+(\.\d+)?$", t) for t in tokens): - SeasonRange().parse_tokens(*tokens) - except (click.BadParameter, ValueError) as e: - return f"Invalid wanted parameter: {e}" + SEASON_RANGE.convert(wanted or []) + except click.BadParameter as e: + return f"Invalid wanted parameter: {e.message}" return None @@ -1846,16 +1825,6 @@ def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]: except APIError as e: return e.message - if data.get("sample") is not None: - from unshackle.core.utils.click_types import SAMPLE_RANGE - - try: - SAMPLE_RANGE.convert(data["sample"], None, None) - except click.BadParameter: - return "sample must be true or a 'START-END' window in seconds, such as '60-120'." - if data.get("sample") and data.get("include_sample"): - return "sample and include_sample cannot be used together." - # The serve user would create and write any directory a client names; keep it under downloads. if data.get("output_dir"): root = config.directories.downloads.resolve() @@ -1881,13 +1850,6 @@ def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]: if not isinstance(data["abitrate"], int) or data["abitrate"] <= 0: return "abitrate must be a positive integer" - for prefix, example in (("v", "6000-7000"), ("a", "128-256")): - value = data.get(f"{prefix}bitrate_range") - if value and data.get(f"{prefix}bitrate") is not None: - return f"Cannot use both {prefix}bitrate and {prefix}bitrate_range" - if value is not None and (not isinstance(value, str) or not re.fullmatch(r"\s*\d+\s*-\s*\d+\s*", value)): - return f"{prefix}bitrate_range must be a string in 'MIN-MAX' format (e.g., '{example}')" - if data.get("quality") is not None: try: heights = QUALITY_LIST.convert(data["quality"]) @@ -1922,38 +1884,6 @@ def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]: if not isinstance(data["imdb_id"], str) or not re.fullmatch(r"tt\d+", data["imdb_id"]): return "imdb_id must be an IMDB ID like 'tt1375666'" - if data.get("anilist_id") is not None: - value = data["anilist_id"] - # same parser as --anilist so both surfaces accept and reject the same inputs - valid = not isinstance(value, bool) and isinstance(value, (int, str)) and parse_anilist_ref(value) - if not valid: - return "anilist_id must be a positive integer, or a MyAnimeList ID like 'mal:21'" - - supplied_ids = [name for name in ("tmdb_id", "imdb_id", "tvdb_id") if data.get(name)] - if len(supplied_ids) > 1: - return f"Cannot use multiple external IDs: {', '.join(supplied_ids)}; give one ID" - - exclusive_flags = [] - if data.get("video_only"): - exclusive_flags.append("video_only") - if data.get("audio_only"): - exclusive_flags.append("audio_only") - if data.get("subs_only"): - exclusive_flags.append("subs_only") - if data.get("chapters_only"): - exclusive_flags.append("chapters_only") - - if len(exclusive_flags) > 1: - return f"Cannot use multiple exclusive flags: {', '.join(exclusive_flags)}" - - if data.get("no_subs") and data.get("subs_only"): - return "Cannot use both no_subs and subs_only" - if data.get("no_audio") and data.get("audio_only"): - return "Cannot use both no_audio and audio_only" - conflict = kind_only_conflict(data) - if conflict: - return f"Cannot use both {conflict[0]} and {conflict[1]}" - for key, default in DEFAULT_DOWNLOAD_PARAMS.items(): if isinstance(default, bool) and data.get(key) is not None and not isinstance(data[key], bool): return f"{key} must be a boolean" @@ -1972,11 +1902,11 @@ def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]: if value is not None and (not isinstance(value, list) or not all(isinstance(v, str) for v in value)): return f"{key} must be an array of language strings" - from unshackle.commands.dl import dl, subtitle_look + from unshackle.commands.dl import subtitle_look try: - params = cast_dl_params(dl.cli, data) - except click.BadParameter as e: + params = api_plan(data).params + except PlanError as e: return e.message if params.get("sub_font"): @@ -2129,7 +2059,7 @@ async def download_handler(data: Dict[str, Any], request: Optional[web.Request] details={"service": service_tag}, ) - validation_error = validate_download_parameters(data) + validation_error = await asyncio.to_thread(validate_download_parameters, data) if validation_error: raise APIError( APIErrorCode.INVALID_PARAMETERS, @@ -2141,22 +2071,13 @@ async def download_handler(data: Dict[str, Any], request: Optional[web.Request] service_module = None if server else Services.load(normalized_service) service_params: Optional[Dict[str, Any]] = None - # Service defaults and options travel nested: flat, a service default would overwrite the dl value of - # the same name. Missing required __init__ params are handled in download_manager.perform_download. - # A remote service applies its own defaults on the remote server. + # Service options travel nested, so a flat key the worker reads stays a dl value; click fills the defaults + # when the worker builds the service. A remote service applies its own on the remote server. cli_params = getattr(getattr(service_module, "cli", None), "params", None) if cli_params is not None: - defaults = { - param.name: param.default - for param in cli_params - if param.name and param.default is not None and not isinstance(param.default, enum.Enum) - } - # A flat dl key (quality, lang) stays a dl value, as in instantiate_service. - sent = service_options( - data, {param.name for param in cli_params}, FLAT_DL_KEYS | DEFAULT_DOWNLOAD_PARAMS.keys() - ) + sent = service_options(data, {param.name for param in cli_params}, DL_TRANSPORT_KEYS) cast_or_refuse(cli_params, click.Context(click.Command(normalized_service)), sent) - service_params = {**defaults, **sent} + service_params = sent filtered_params = {k: v for k, v in data.items() if k not in ["service", "title_id", "owner_key"]} # Overlay any dl-relevant keys from `serve:` config (e.g. downloads, workers) so the API @@ -3261,6 +3182,7 @@ async def env_check_handler(request: Optional[web.Request] = None) -> web.Respon # "client" stays out: a flat "client" value with no service_params is a service option. +DL_TRANSPORT_KEYS = FLAT_DL_KEYS | DEFAULT_DOWNLOAD_PARAMS.keys() SESSION_TRANSPORT_KEYS = (SessionCreate.__required_keys__ | SessionCreate.__optional_keys__) - {"client"} diff --git a/unshackle/core/dl_options.py b/unshackle/core/dl_options.py index a1060899..f44fb2d5 100644 --- a/unshackle/core/dl_options.py +++ b/unshackle/core/dl_options.py @@ -22,12 +22,11 @@ RemoteKind = Literal["langs", "audio_codecs", "flag"] 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``. + ``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 @@ -45,7 +44,7 @@ DL_OPTIONS: Dict[str, Optional[ApiOption]] = { "range": ApiOption(["SDR"]), "channels": ApiOption(None), "no_atmos": ApiOption(False), - "wanted": ApiOption([], raw=True), + "wanted": ApiOption([]), "latest_episode": ApiOption(False), "latest_episodes": ApiOption(None), "lang": ApiOption(["orig"], remote="langs"), @@ -74,7 +73,7 @@ DL_OPTIONS: Dict[str, Optional[ApiOption]] = { "no_attachments": ApiOption(False), "audio_description": ApiOption(False), "audio_description_only": ApiOption(False), - "slow": ApiOption(None, raw=True), + "slow": ApiOption(None), "split_audio": ApiOption(None), "skip_dl": ApiOption(False), "all_drm": ApiOption(False), @@ -131,7 +130,6 @@ An option the REST API takes has an ``ApiOption``; a ``CLI_ONLY`` option never r """ 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) @@ -144,9 +142,8 @@ 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``. + ``output_dir: ""`` is not the working directory. A parameter outside ``DEFAULT_DOWNLOAD_PARAMS`` never reaches + dl, so API clients cannot set a new CLI option until the table opens it. Raises ``click.BadParameter``. """ kept: Dict[str, Any] = {} to_cast: Dict[str, Any] = {} @@ -154,7 +151,7 @@ def cast_dl_params(cli: click.Command, params: Dict[str, Any]) -> Dict[str, Any] 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 + (kept if value is None 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: diff --git a/unshackle/core/run_plan.py b/unshackle/core/run_plan.py new file mode 100644 index 00000000..5f24afb1 --- /dev/null +++ b/unshackle/core/run_plan.py @@ -0,0 +1,196 @@ +"""The dl front door: one checked run plan from a dl click parse or a REST API job, and what the run gave back.""" + +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Collection, Mapping, Optional, Union + +import click +from click.core import ParameterSource + +from unshackle.core import providers +from unshackle.core.dl_options import DL_OPTION_API_NAMES, cast_dl_params +from unshackle.core.downloaders import parse_speed_limit +from unshackle.core.providers.anilist import parse_anilist_ref +from unshackle.core.providers.tvdb import SEASON_TYPES +from unshackle.core.remote_protocol import APIErrorCode +from unshackle.core.utilities import inherited_exclusions, kind_only_conflict, partition_exclusions + +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"} + + +class PlanError(click.ClickException): + """A dl option value or combination that dl refuses, in one line.""" + + error_code = APIErrorCode.INVALID_PARAMETERS + + +class RunStopped(SystemExit): + """A run that a missing track or language stopped, with the reason dl logged.""" + + def __init__(self, reason: str) -> None: + super().__init__(1) + self.reason = reason + + +@dataclass +class RunOutcome: + """What a dl run gave back: the files it wrote, the subtitles it skipped, and a download failure it reported.""" + + files: list[Path] = field(default_factory=list) + skipped_subtitles: list[Any] = field(default_factory=list) + error: Optional[BaseException] = None + + +@dataclass(frozen=True) +class RunPlan: + """The checked dl parameters of one run, by dl click name, with the source of each value.""" + + params: dict[str, Any] + sources: dict[str, ParameterSource] + + def context(self, cli: click.Command, service: str) -> click.Context: + """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.invoked_subcommand = service + ctx.params = dict(self.params) + for name, source in self.sources.items(): + ctx.set_parameter_source(name, source) + return ctx + + +def validate_metadata_ids( + tmdb_id: Optional[int], + imdb_id: Optional[str], + tvdb_id: Optional[int], + anilist_id: Optional[Union[int, str]] = None, +) -> None: + """Reject ID flags that conflict, or that no configured metadata provider could ever find. + + --anilist stays outside the mutual exclusion: AniList knows no western IDs, so pairing + it with one of the other three is how an anime title gets both. + """ + if anilist_id and not parse_anilist_ref(anilist_id): + raise PlanError("--anilist takes an AniList ID like 21, or a MyAnimeList ID like mal:21.") + + supplied = [ + (flag, value) for flag, value in (("--tmdb", tmdb_id), ("--imdb", imdb_id), ("--tvdb", tvdb_id)) if value + ] + if len(supplied) > 1: + raise PlanError(f"{', '.join(flag for flag, _ in supplied)} cannot be used together; give one ID") + if not supplied: + return + + flag, _ = supplied[0] + id_kind = flag.lstrip("-") + ordered = {cls.NAME: cls for kind in ("tv", "movie") for cls in providers.provider_order(kind)} + consumers = [cls for cls in ordered.values() if cls.ID_KIND == id_kind] + if any(cls().is_available() for cls in consumers): + return + + if consumers: + keys = sorted({ID_PROVIDER_KEYS[cls.NAME] for cls in consumers if cls.NAME in ID_PROVIDER_KEYS}) + raise PlanError(f"{flag} needs the {consumers[0].NAME} provider: set {' or '.join(keys)} in your config") + names = sorted({cls.NAME for cls in providers.REGISTRY.values() if cls.ID_KIND == id_kind}) + raise PlanError(f"{flag} needs the {' or '.join(names)} provider, which your metadata_providers config leaves out.") + + +def bitrate_range(value: Optional[str], flag: str, example: str) -> Optional[tuple[int, int]]: + """A ``MIN-MAX`` bitrate range as (low, high), in either order.""" + if not value: + return None + try: + low, high = (int(part) for part in value.split("-")) + except ValueError: + raise PlanError(f"Invalid {flag}: expected MIN-MAX, such as {example}") from None + return min(low, high), max(low, high) + + +def check_options(params: Mapping[str, Any]) -> None: + """Refuse the dl option values and combinations that dl cannot run, from cast params by dl click name.""" + from unshackle.core.config import config + from unshackle.core.tracks import Video + from unshackle.core.tracks.selection import generated_dv_ranges + + validate_metadata_ids(params.get("tmdb_id"), params.get("imdb_id"), params.get("tvdb_id"), params.get("anilist_id")) + tvdb_order = (params.get("tvdb_order") or config.tvdb_order or "").lower() + if tvdb_order and tvdb_order not in SEASON_TYPES: + raise PlanError(f"tvdb_order must be one of {', '.join(SEASON_TYPES)}, not {tvdb_order!r}") + if params.get("enrich") and not any(params.get(k) for k in ("tmdb_id", "imdb_id", "tvdb_id", "anilist_id")): + raise PlanError("--enrich requires --tmdb, --imdb, --tvdb, or --anilist to provide a metadata source.") + if params.get("sample") and params.get("include_sample"): + raise PlanError("--sample and --include-sample cannot be used together.") + + included: dict[str, list[str]] = {} + excluded: dict[str, list[str]] = {} + for name, flag in ( + ("lang", "-l/--lang"), + ("v_lang", "-vl/--v-lang"), + ("a_lang", "-al/--a-lang"), + ("s_lang", "-sl/--s-lang"), + ("forced_s_lang", "-fsl/--forced-s-lang"), + ): + included[name], excluded[name] = partition_exclusions(params.get(name)) + if any(token.lower() == "all" for token in excluded[name]): + raise PlanError(f"{flag}: 'all' cannot be excluded") + for flag, key, own, fallback in ( + ("--require-audio", "require_audio", "a_lang", "lang"), + ("--require-video", "require_video", "v_lang", "lang"), + ("--require-subs", "require_subs", "s_lang", None), + ): + excludes = inherited_exclusions(included[own], excluded[own], excluded[fallback] if fallback else []) + required, own_excl = partition_exclusions(params.get(key)) + clash = own_excl + [t for t in required if any(t.lower() == e.lower() for e in excludes)] + if clash: + raise PlanError(f"{flag}: {clash[0]} cannot be required and excluded at the same time.") + + for only, drop in (("subs_only", "no_subs"), ("audio_only", "no_audio")): + if params.get(only) and params.get(drop): + raise PlanError(f"--{only.replace('_', '-')} cannot be used with --{drop.replace('_', '-')}.") + conflict = kind_only_conflict(params) + if conflict: + first, second = (f"--{name.replace('_', '-')}" for name in conflict) + raise PlanError(f"{first} cannot be used with {second}: {second} drops the tracks that {first} selects.") + + try: + parse_speed_limit(params.get("speed_limit")) + except ValueError as e: + raise PlanError(str(e)) from None + + for kind, example in (("v", "6000-7000"), ("a", "128-256")): + if params.get(f"{kind}bitrate_range"): + if params.get(f"{kind}bitrate"): + raise PlanError(f"Cannot use both --{kind}bitrate and --{kind}bitrate-range at the same time.") + bitrate_range(params[f"{kind}bitrate_range"], f"--{kind}bitrate-range", example) + + if params.get("select_titles") and params.get("wanted"): + raise PlanError("--select-titles and -w/--wanted cannot be used together") + + ranges, _ = generated_dv_ranges(params.get("range_") or [], bool(params.get("generate_dv"))) + if Video.Range.HYBRID in ranges: + from unshackle.core.binaries import DoviTool + + if not DoviTool: + raise PlanError("Unable to run hybrid mode: dovi_tool not found") + + +def api_plan(params: Mapping[str, Any], client_keys: Optional[Collection[str]] = 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. + """ + from unshackle.commands.dl import dl + + try: + cast = cast_dl_params(dl.cli, dict(params)) + except click.BadParameter as e: + raise PlanError(e.message) from None + 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 = { + name: ParameterSource.COMMANDLINE if PLAN_API_NAMES.get(name, name) in sent else ParameterSource.DEFAULT + for name in cast + } + return RunPlan(cast, sources) diff --git a/unshackle/core/tracks/selection.py b/unshackle/core/tracks/selection.py index 1242c0ef..0f4ca6b6 100644 --- a/unshackle/core/tracks/selection.py +++ b/unshackle/core/tracks/selection.py @@ -33,6 +33,21 @@ log = logging.getLogger("download") HYBRID_BASE_RANGES = (Video.Range.HDR10P, Video.Range.HDR10) +def generated_dv_ranges( + range_: Sequence[Video.Range], generate_dv: bool +) -> tuple[list[Video.Range], list[Video.Range]]: + """Turn ``-r HDR10 --generate-dv`` (or HDR10P) into a HYBRID run on that base alone. + + Returns the ranges to run with, and the base ranges the user named. The second list is empty when + the flag is off, HYBRID or DV is in the ranges, or no base range is. The service still gets the + ranges the user gave, so it fetches no DV track. + """ + bases = [r for r in range_ if r in HYBRID_BASE_RANGES] + if not generate_dv or not bases or Video.Range.HYBRID in range_ or Video.Range.DV in range_: + return list(range_), [] + return [Video.Range.HYBRID, *(r for r in range_ if r not in bases)], bases + + @dataclass(frozen=True) class Skip: """The title has no track the selection asks for. diff --git a/unshackle/core/utilities.py b/unshackle/core/utilities.py index b002dc5d..34c74dd8 100644 --- a/unshackle/core/utilities.py +++ b/unshackle/core/utilities.py @@ -308,6 +308,11 @@ def partition_exclusions(tokens: Optional[Sequence[str]]) -> tuple[list[str], li return includes, excludes +def inherited_exclusions(own: Sequence[str], own_excl: Sequence[str], fallback_excl: Sequence[str]) -> list[str]: + """A language flag's exclusions plus those of the flag it falls back to, unless it names languages of its own.""" + return list(dict.fromkeys([*own_excl, *([] if own else fallback_excl)])) + + def matched_language_tags( tokens: Sequence[str], available: Sequence[Union[str, Language, None]], diff --git a/unshackle/core/utils/click_types.py b/unshackle/core/utils/click_types.py index 5303c1f3..ca08388e 100644 --- a/unshackle/core/utils/click_types.py +++ b/unshackle/core/utils/click_types.py @@ -322,10 +322,18 @@ class SeasonRange(click.ParamType): computed = [k for k in computed if k != exclusion and not k.startswith(prefix)] return list(set(computed)) + PARSED_KEY = re.compile(r"^!?(0|[1-9]\d*)x(0|[1-9]\d*)(\.[1-9]\d?)?$") + def convert( - self, value: str, param: Optional[click.Parameter] = None, ctx: Optional[click.Context] = None + self, value: Union[str, list], param: Optional[click.Parameter] = None, ctx: Optional[click.Context] = None ) -> list[str]: - return self.parse_tokens(*re.split(r"\s*[,;]\s*", value)) + """Parse a comma or semicolon separated string, or a list of tokens; parsed keys such as ``!1x2.3`` pass.""" + tokens = re.split(r"\s*[,;]\s*", value) if isinstance(value, str) else value + if not isinstance(tokens, list) or not all(isinstance(t, str) for t in tokens): + self.fail("expected a string or a list of strings", param, ctx) + if all(self.PARSED_KEY.match(t) for t in tokens): + return list(tokens) + return self.parse_tokens(*tokens) class LanguageRange(click.ParamType): @@ -500,6 +508,8 @@ class SlowDelayRange(click.ParamType): return value if isinstance(value, bool): return (60, 120) if value else None + if isinstance(value, list) and len(value) == 2: + value = f"{value[0]}-{value[1]}" match = re.match(r"^(\d+)-(\d+)$", str(value)) if not match: