refactor(dl): check dl options once in a run plan shared by the CLI and the REST download job

This commit is contained in:
imSp4rky
2026-11-25 16:16:43 -07:00
parent 7838226590
commit 4d3df8e74f
23 changed files with 501 additions and 524 deletions
+5 -5
View File
@@ -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. | | `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_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`. | | `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. | | `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. | | `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` | 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`. | | `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. | | `split_audio` | boolean | `null` | Separate files per audio codec. |
| `skip_dl` | boolean | `false` | Only fetch keys, do not download. | | `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. | | `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. | | `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. | | `repack` | boolean | `false` | Add REPACK tag. |
| `tag` | string | `null` | Release group 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. | | `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. | | `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. | | `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`. | | `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. | | `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 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 `service_params` object, or as flat top-level keys. When the body has `service_params`, the server
+1 -1
View File
@@ -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 | | `downloads` | `1` | Number of tracks to download concurrently |
| `proxy` | `null` | Proxy URI or country code | | `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" !!! 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. 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.
+7 -4
View File
@@ -18,7 +18,6 @@ import pytest
import unshackle.commands.dl as dl_module import unshackle.commands.dl as dl_module
from tests.remote.unit.test_remote_service_helpers import _sent_create_data 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 import mux_step
from unshackle.core.api import download_manager, handlers from unshackle.core.api import download_manager, handlers
from unshackle.core.api.handlers import validate_download_parameters from unshackle.core.api.handlers import validate_download_parameters
@@ -37,7 +36,12 @@ from unshackle.core.tracks.hybrid import (
nits_to_pq, nits_to_pq,
pq_to_nits, 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 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"]) raise _Captured(self.ctx.params["generate_dv"], kwargs["generate_dv"])
class FakeService: class FakeService:
def __init__(self, ctx: click.Context) -> None: cli = click.Command("svc", callback=lambda title: object())
pass
monkeypatch.setattr(dl_module, "dl", FakeDl) monkeypatch.setattr(dl_module, "dl", FakeDl)
monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path)) monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path))
+20 -14
View File
@@ -2,12 +2,11 @@
from __future__ import annotations from __future__ import annotations
import click
import pytest import pytest
from unshackle.commands.dl import validate_metadata_ids
from unshackle.core.api.handlers import validate_download_parameters from unshackle.core.api.handlers import validate_download_parameters
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.run_plan import PlanError, validate_metadata_ids
@pytest.fixture(autouse=True) @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)], [(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: 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) validate_metadata_ids(tmdb, imdb, tvdb)
assert "cannot be used together" in str(exc.value) 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: def test_tmdb_without_its_key_names_the_key(monkeypatch: pytest.MonkeyPatch) -> None:
with_keys(monkeypatch) with_keys(monkeypatch)
with pytest.raises(click.UsageError) as exc: with pytest.raises(PlanError) as exc:
validate_metadata_ids(27205, None, None) validate_metadata_ids(27205, None, None)
assert "--tmdb" in str(exc.value) and "tmdb_api_key" in str(exc.value) 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: def test_tvdb_without_its_key_names_the_key(monkeypatch: pytest.MonkeyPatch) -> None:
with_keys(monkeypatch) with_keys(monkeypatch)
with pytest.raises(click.UsageError) as exc: with pytest.raises(PlanError) as exc:
validate_metadata_ids(None, None, 73871) validate_metadata_ids(None, None, 73871)
assert "--tvdb" in str(exc.value) and "tvdb_api_key" in str(exc.value) 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: def test_a_provider_filtered_out_of_the_order_points_at_the_config(monkeypatch: pytest.MonkeyPatch) -> None:
with_keys(monkeypatch, tmdb_api_key="k") with_keys(monkeypatch, tmdb_api_key="k")
monkeypatch.setattr(config, "metadata_providers", ["imdb", "omdb"]) 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) validate_metadata_ids(27205, None, None)
assert "metadata_providers" in str(exc.value) 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: def test_imdb_is_unresolvable_when_the_order_drops_both_of_its_providers(monkeypatch: pytest.MonkeyPatch) -> None:
with_keys(monkeypatch) with_keys(monkeypatch)
monkeypatch.setattr(config, "metadata_providers", ["tmdb", "tvdb"]) 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) validate_metadata_ids(None, "tt1375666", None)
assert "metadata_providers" in str(exc.value) assert "metadata_providers" in str(exc.value)
assert "imdb" in str(exc.value) and "omdb" 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: def test_api_refuses_two_ids(payload: dict) -> None:
err = validate_download_parameters(payload) 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}, {}]) @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: def test_anilist_does_not_excuse_two_western_ids(monkeypatch: pytest.MonkeyPatch) -> None:
with_keys(monkeypatch) with_keys(monkeypatch)
with pytest.raises(click.UsageError) as exc: with pytest.raises(PlanError) as exc:
validate_metadata_ids(27205, "tt1375666", None, 21) validate_metadata_ids(27205, "tt1375666", None, 21)
assert "cannot be used together" in str(exc.value) 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"]) @pytest.mark.parametrize("value", ["tt1375666", "anilist:21", "mal:", "abc", "-3"])
def test_a_malformed_anilist_value_is_refused(monkeypatch: pytest.MonkeyPatch, value: str) -> None: def test_a_malformed_anilist_value_is_refused(monkeypatch: pytest.MonkeyPatch, value: str) -> None:
with_keys(monkeypatch) with_keys(monkeypatch)
with pytest.raises(click.UsageError) as exc: with pytest.raises(PlanError) as exc:
validate_metadata_ids(None, None, None, value) validate_metadata_ids(None, None, None, value)
assert "--anilist" in str(exc.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: def test_api_still_refuses_two_western_ids_with_anilist() -> None:
err = validate_download_parameters({"tmdb_id": 27205, "imdb_id": "tt1375666", "anilist_id": 21}) 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]) @pytest.mark.parametrize("value", [0, -3, True, "mal:", "tt1375666", "anilist:21", 1.5])
def test_api_refuses_a_malformed_anilist_id(value: object) -> None: def test_api_refuses_a_malformed_anilist_id(value: object) -> None:
err = validate_download_parameters({"anilist_id": value}) 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"]) @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: def test_a_non_positive_or_non_decimal_anilist_value_is_refused(monkeypatch: pytest.MonkeyPatch, value: str) -> None:
with_keys(monkeypatch) with_keys(monkeypatch)
with pytest.raises(click.UsageError) as exc: with pytest.raises(PlanError) as exc:
validate_metadata_ids(None, None, None, value) validate_metadata_ids(None, None, None, value)
assert "--anilist" in str(exc.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", "²"]) @pytest.mark.parametrize("value", ["0", "mal:0", "²"])
def test_api_refuses_what_the_cli_refuses(value: str) -> None: def test_api_refuses_what_the_cli_refuses(value: str) -> None:
err = validate_download_parameters({"anilist_id": value}) 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"
)
+106
View File
@@ -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)
+2 -1
View File
@@ -57,7 +57,8 @@ def test_kind_only_conflict(params, expected):
def test_api_rejects_a_conflict(): def test_api_rejects_a_conflict():
assert validate_download_parameters({**BASE, "audio_description_only": True, "no_audio": True}) == ( 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 assert validate_download_parameters({**BASE, "audio_description_only": True, "audio_only": True}) is None
@@ -14,6 +14,7 @@ from langcodes import Language
from tests.lang_selection import test_kind_only_selection as harness 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 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.tracks.selection import Kept, Skip
from unshackle.core.utilities import missing_required_langs 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"), ({"require_audio": ["-en"]}, "--require-audio: en"),
], ],
) )
def test_a_required_and_excluded_language_stops_the_run( def test_a_required_and_excluded_language_is_refused(flags: dict[str, Any], clash: str) -> None:
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, flags: dict[str, Any], clash: str with pytest.raises(PlanError, match=f"^{clash} cannot be required and excluded at the same time.$"):
) -> None: check_options(flags)
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_language_override_does_not_inherit_the_lang_exclusions( def test_a_language_override_does_not_inherit_the_lang_exclusions(
+6 -12
View File
@@ -11,7 +11,6 @@ from unshackle.commands.dl import dl
from unshackle.core.api import routes from unshackle.core.api import routes
from unshackle.core.api.handlers import validate_download_parameters from unshackle.core.api.handlers import validate_download_parameters
from unshackle.core.dl_options import ( from unshackle.core.dl_options import (
API_SHAPED_DL_PARAMS,
DEFAULT_DOWNLOAD_PARAMS, DEFAULT_DOWNLOAD_PARAMS,
DL_OPTION_ALIASES, DL_OPTION_ALIASES,
DL_OPTIONS, 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(): 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) ctx = click.Context(dl.cli)
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}
p.name: p.type_cast_value(ctx, p.get_default(ctx)) assert cast_dl_params(dl.cli, {}) == {**expected, "wanted": []}
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
def test_cli_only_options_never_reach_dl(): 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["acodec"] == [Audio.Codec.EC3]
assert cast["range_"] == [Video.Range.HDR10P, Video.Range.DV] assert cast["range_"] == [Video.Range.HDR10P, Video.Range.DV]
assert cast["lang"] == ["en"] 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["downloads"], cast["sample"], cast["tvdb_order"]) == (3, (0, 60), "dvd")
assert cast["sub_format"] is Subtitle.Codec.SubRip assert cast["sub_format"] is Subtitle.Codec.SubRip
assert (cast["output_dir"], cast["cdm_only"], cast["s_lang"]) == (None, False, ["all"]) 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(): 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.""" """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] 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(): def test_null_takes_the_api_default():
+17 -55
View File
@@ -2,7 +2,7 @@
Covers serialize_title's conditional `part` key, the list-tracks wanted filter Covers serialize_title's conditional `part` key, the list-tracks wanted filter
routing through Episode.matches_wanted, the discrete season/episode/part request 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 from __future__ import annotations
@@ -17,6 +17,7 @@ import pytest
from unshackle.core.api import handlers from unshackle.core.api import handlers
from unshackle.core.api.errors import APIError from unshackle.core.api.errors import APIError
from unshackle.core.titles.episode import Episode 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 from unshackle.core.wire import build_title, serialize_title
pytestmark = pytest.mark.unit 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"] assert selected(result) == ["1x1.1", "1x1.2", "1x1.3", "1x2"]
SNIFF = r"^!?\d+x\d+(\.\d+)?$"
@pytest.mark.parametrize( @pytest.mark.parametrize(
"wanted, internal", ("wanted", "parsed"),
[ [
(["1x1"], True), # today's pre-parsed form (["1x1"], ["1x1"]),
(["1x1", "1x2"], True), (["1x1.2"], ["1x1.2"]),
(["1x1.2"], True), # part key (["!1x1.2"], ["!1x1.2"]),
(["!1x1.2"], True), # negative part key (["1x1", "!1x1.2"], ["1x1", "!1x1.2"]),
(["1x1", "!1x1.2"], True), ("1x1, 1x2", ["1x1", "1x2"]),
(["S01E01"], False), (["1x01"], ["1x1"]),
(["s1e1.2"], False),
(["S01"], False),
(["1x1", "S01E02"], False),
], ],
) )
def test_download_manager_sniff_regex(wanted: List[str], internal: bool) -> None: def test_parsed_keys_pass_unchanged(wanted: Any, parsed: List[str]) -> None:
needs_conversion = any(not re.match(SNIFF, w) for w in wanted) """A pre-parsed part or negative key never reaches parse_tokens, which cannot read it."""
assert needs_conversion is (not internal) assert SEASON_RANGE.convert(wanted) == parsed
def test_sniff_regex_matches_the_one_in_download_manager() -> None: @pytest.mark.parametrize("wanted", [["S01E01"], "S01E01", ["s1e1"], "s1e1; S01E01"])
"""Guard the copy above against drift from the production regex.""" def test_tokens_parse_from_a_list_or_a_separated_string(wanted: Any) -> None:
from pathlib import Path assert SEASON_RANGE.convert(wanted) == ["1x1"]
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
def test_perform_download_skips_reconversion_for_preparsed_part_keys(monkeypatch) -> None: def test_a_mixed_list_parses_every_token() -> None:
"""A pre-parsed list with part and negative keys must not reach parse_tokens.""" assert sorted(SEASON_RANGE.convert(["1x1", "S01E02"])) == ["1x1", "1x2"]
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_dl_and_handlers_share_the_one_match_helper() -> None: def test_dl_and_handlers_share_the_one_match_helper() -> None:
+1 -2
View File
@@ -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"]) raise _Captured(self.ctx.params["quality"], kwargs["quality"], self.ctx.params["cdm_only"])
class FakeService: class FakeService:
def __init__(self, ctx: click.Context) -> None: cli = click.Command("svc", callback=lambda title: object())
pass
monkeypatch.setattr(dl_module, "dl", FakeDl) monkeypatch.setattr(dl_module, "dl", FakeDl)
monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path)) monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path))
@@ -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"} 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.command()
@click.option("--profile", type=int, default=1) @click.option("--profile", type=int, default=1)
@click.option("--device", default="chrome") @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)) monkeypatch.setattr(handlers.Services, "load", lambda service: SimpleNamespace(cli=cli))
params = env(body={"profile": "work", "service_params": {"profile": 2}}) params = env(body={"profile": "work", "service_params": {"profile": 2}})
assert params["profile"] == "work" assert params["profile"] == "work"
assert params["service_params"] == {"profile": 2, "device": "chrome"} assert params["service_params"] == {"profile": 2}
assert env(body={"device": "tv"})["service_params"] == {"profile": 1, "device": "tv"} assert env(body={"device": "tv"})["service_params"] == {"device": "tv"}
def use_cli(monkeypatch, *options): 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): 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")) 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"] == {}
+14 -15
View File
@@ -241,8 +241,7 @@ def test_perform_download_passes_latest_episodes_to_dl_result(tmp_path: Path, mo
raise _CapturedCtx(kwargs) raise _CapturedCtx(kwargs)
class FakeService: class FakeService:
def __init__(self, ctx: click.Context) -> None: cli = click.Command("svc", callback=lambda title: object())
pass
monkeypatch.setattr(dl_module, "dl", FakeDl) monkeypatch.setattr(dl_module, "dl", FakeDl)
monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path)) 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") raise RuntimeError("stop")
class FakeService: class FakeService:
def __init__(self, ctx: click.Context) -> None: cli = click.Command(
seen["parent"] = dict(ctx.parent.params) "svc", callback=click.pass_context(lambda ctx, title: seen.update(parent=dict(ctx.parent.params)))
)
monkeypatch.setattr(dl_module, "dl", FakeDl) monkeypatch.setattr(dl_module, "dl", FakeDl)
monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path)) 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: def __init__(self, ctx: click.Context, **kwargs: object) -> None:
pass pass
def build(title: str, episodes: object, tag: object) -> None:
raise _CapturedCtx(episodes, tag)
class FakeService: class FakeService:
cli = click.Command( 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(dl_module, "dl", FakeDl)
monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path)) monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path))
monkeypatch.setattr(Services, "load", staticmethod(lambda s: FakeService)) 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: def test_a_stopped_run_names_its_reason_in_the_job_error(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
import sys
import click import click
import unshackle.commands.dl as dl_module import unshackle.commands.dl as dl_module
from unshackle.core.api import download_manager, handlers from unshackle.core.api import download_manager, handlers
from unshackle.core.api.errors import APIError from unshackle.core.api.errors import APIError
from unshackle.core.run_plan import RunStopped
from unshackle.core.services import Services from unshackle.core.services import Services
class FakeDl: class FakeDl:
cli = dl_module.dl.cli cli = dl_module.dl.cli
def __init__(self, ctx: click.Context, **kwargs: object) -> None: def __init__(self, ctx: click.Context, **kwargs: object) -> None:
self.stop_reason = None pass
def result(self, **kwargs: object) -> None: def result(self, **kwargs: object) -> None:
self.stop_reason = "Show S01E01: Required audio language(s) not found: ko" raise RunStopped("Show S01E01: Required audio language(s) not found: ko")
sys.exit(1)
class FakeService: class FakeService:
def __init__(self, ctx: click.Context) -> None: cli = click.Command("svc", callback=lambda title: object())
pass
monkeypatch.setattr(dl_module, "dl", FakeDl) monkeypatch.setattr(dl_module, "dl", FakeDl)
monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path)) monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path))
+5 -5
View File
@@ -301,17 +301,17 @@ def test_validate_download_params_accepts_defaults() -> None:
({"vbitrate": -1}, "vbitrate"), ({"vbitrate": -1}, "vbitrate"),
({"abitrate": "no"}, "abitrate"), ({"abitrate": "no"}, "abitrate"),
({"vbitrate_range": "no-dash-but-letters"}, "MIN-MAX"), ({"vbitrate_range": "no-dash-but-letters"}, "MIN-MAX"),
({"vbitrate": 5000, "vbitrate_range": "1-2"}, "vbitrate and vbitrate_range"), ({"vbitrate": 5000, "vbitrate_range": "1-2"}, "--vbitrate and --vbitrate-range"),
({"abitrate": 128, "abitrate_range": "96-256"}, "abitrate and abitrate_range"), ({"abitrate": 128, "abitrate_range": "96-256"}, "--abitrate and --abitrate-range"),
({"abitrate_range": "1-2-3"}, "MIN-MAX"), ({"abitrate_range": "1-2-3"}, "MIN-MAX"),
({"quality": "4k"}, "Invalid quality"), ({"quality": "4k"}, "Invalid quality"),
({"quality": [0]}, "above 0"), ({"quality": [0]}, "above 0"),
({"channels": -3}, "channels"), ({"channels": -3}, "channels"),
({"workers": 0}, "workers"), ({"workers": 0}, "workers"),
({"downloads": 0}, "downloads"), ({"downloads": 0}, "downloads"),
({"video_only": True, "audio_only": True}, "exclusive"), ({"video_only": True, "audio_only": True}, None),
({"no_subs": True, "subs_only": True}, "no_subs and subs_only"), ({"no_subs": True, "subs_only": True}, "--subs-only cannot be used with --no-subs"),
({"no_audio": True, "audio_only": True}, "no_audio and audio_only"), ({"no_audio": True, "audio_only": True}, "--audio-only cannot be used with --no-audio"),
({"require_subs": "en"}, "require_subs must be an array"), ({"require_subs": "en"}, "require_subs must be an array"),
({"range": "UHD"}, "Invalid range"), ({"range": "UHD"}, "Invalid range"),
({"range": ["SDR", "UHD"]}, "Invalid range"), ({"range": ["SDR", "UHD"]}, "Invalid range"),
@@ -335,7 +335,7 @@ def test_a_service_click_default_stays_out_of_the_download_gate(monkeypatch):
monkeypatch.setattr(dm, "get_download_manager", Manager) monkeypatch.setattr(dm, "get_download_manager", Manager)
body = {"service": "EXAMPLE1", "title_id": "t1", "quality": [1080]} body = {"service": "EXAMPLE1", "title_id": "t1", "quality": [1080]}
asyncio.run(handlers.download_handler(body, request("flat"))) 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") assert not jobs[0].get("best_available")
+1 -1
View File
@@ -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: 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: def test_sample_name_uses_the_separator_of_the_template(monkeypatch: pytest.MonkeyPatch) -> None:
+32 -180
View File
@@ -66,7 +66,6 @@ from unshackle.core.launch import LaunchKeys, launch, load_service_config
from unshackle.core.manifests.snapshot import capture from unshackle.core.manifests.snapshot import capture
from unshackle.core.mux_step import mux_title from unshackle.core.mux_step import mux_title
from unshackle.core.placement import SAMPLE_DIR, Placement, sample_name 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.providers.tvdb import SEASON_TYPES, parse_int
from unshackle.core.proxies.resolve import ( from unshackle.core.proxies.resolve import (
REGION, REGION,
@@ -79,6 +78,7 @@ from unshackle.core.proxies.resolve import (
resolve_proxy, resolve_proxy,
split_proxy_query, 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.service import Service, grow_session_pool
from unshackle.core.services import ROUTING_PARAMS, Services from unshackle.core.services import ROUTING_PARAMS, Services
from unshackle.core.temp import with_task_temp 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.titles.episode import Episode
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
from unshackle.core.tracks.attachment import Attachment 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.subtitle_convert import PYCAPTION_WRITERS, SUBSTATION, build_ass_style
from unshackle.core.tracks.track import ( from unshackle.core.tracks.track import (
Track, Track,
@@ -100,8 +100,8 @@ from unshackle.core.utilities import (
find_font_with_fallbacks, find_font_with_fallbacks,
get_debug_logger, get_debug_logger,
get_system_fonts, get_system_fonts,
inherited_exclusions,
init_debug_logger, init_debug_logger,
kind_only_conflict,
log_event, log_event,
matching_languages, matching_languages,
partition_exclusions, 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()} 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: 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. 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 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( def subtitle_look(
sub_format: Optional[Union[Subtitle.Codec, str]], sub_format: Optional[Union[Subtitle.Codec, str]],
sub_font: Optional[str], sub_font: Optional[str],
@@ -1219,8 +1163,6 @@ class dl:
# report which weren't available without parsing the console output. See SkippedSubtitle. # report which weren't available without parsing the console output. See SkippedSubtitle.
self.skipped_subtitles: list[SkippedSubtitle] = [] self.skipped_subtitles: list[SkippedSubtitle] = []
self.skipped_titles: list[SkippedTitle] = [] 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 # 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 # 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. # 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.profile = profile
self.proxy_requested = bool(proxy) 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.tmdb_id = tmdb_id
self.imdb_id = imdb_id self.imdb_id = imdb_id
self.tvdb_id = tvdb_id self.tvdb_id = tvdb_id
self.anilist_id = anilist_id self.anilist_id = anilist_id
self.tvdb_order = (tvdb_order or config.tvdb_order or "").lower() 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.continuous_episodes = continuous_episodes
self.enrich = enrich self.enrich = enrich
self.daily = daily self.daily = daily
@@ -1266,11 +1206,6 @@ class dl:
self.service_anime = False self.service_anime = False
self.service_daily = 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: if self.daily and not self.enrich:
self.log.warning("--daily takes TVDB air dates only with --enrich") self.log.warning("--daily takes TVDB air dates only with --enrich")
@@ -1418,10 +1353,9 @@ class dl:
try: try:
self.cdm = self.get_cdm(self.service, self.profile) self.cdm = self.get_cdm(self.service, self.profile)
except ValueError as e: except ValueError as e:
self.log.error(f"Failed to load CDM, {e}")
if self.debug_logger: if self.debug_logger:
self.debug_logger.log_error("load_cdm", e, service=self.service) 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: if self.cdm:
cdm_info = cdm_summary(self.cdm) cdm_info = cdm_summary(self.cdm)
@@ -1462,8 +1396,7 @@ class dl:
try: try:
requested_provider, query = split_proxy_query(proxy, self.proxy_providers) requested_provider, query = split_proxy_query(proxy, self.proxy_providers)
except ValueError as e: except ValueError as e:
self.log.error(str(e)) raise PlanError(str(e)) from None
sys.exit(1)
# Match region codes (us, ca, uk1, us:ny, yul) or provider:region (nordvpn:ca, protonvpn:us:ny). # 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): 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. # 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 self.proxy_providers, proxy_query, requested_provider
) )
except ValueError as e: except ValueError as e:
self.log.error(str(e)) raise click.ClickException(str(e)) from None
sys.exit(1)
ctx.params["proxy"] = proxy_uri ctx.params["proxy"] = proxy_uri
self.log.info(describe_proxy(proxy_provider, proxy_uri, proxy_query)) self.log.info(describe_proxy(proxy_provider, proxy_uri, proxy_query))
keys["proxy_query"] = proxy_query keys["proxy_query"] = proxy_query
@@ -1514,6 +1446,10 @@ class dl:
# able to keep `self` as the first positional # able to keep `self` as the first positional
self.cli._result_callback = self.result 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 @with_task_temp
def result( def result(
self, self,
@@ -1591,7 +1527,7 @@ class dl:
generate_dv: bool = False, generate_dv: bool = False,
*_: Any, *_: Any,
**__: Any, **__: Any,
) -> None: ) -> RunOutcome:
if all_drm: if all_drm:
DOWNLOAD_ALL_DRM.set() DOWNLOAD_ALL_DRM.set()
else: else:
@@ -1601,8 +1537,6 @@ class dl:
if continue_downloads: if continue_downloads:
config.continue_downloads = True config.continue_downloads = True
config.sample = sample config.sample = sample
if sample and include_sample:
raise click.ClickException("--sample and --include-sample cannot be used together.")
self.tmdb_searched = False self.tmdb_searched = False
self.search_source = None self.search_source = None
self.service_anime = bool(getattr(service, "ANIME", False)) self.service_anime = bool(getattr(service, "ANIME", False))
@@ -1620,34 +1554,13 @@ class dl:
a_lang, a_lang_excl = partition_exclusions(a_lang) a_lang, a_lang_excl = partition_exclusions(a_lang)
s_lang, s_lang_excl = partition_exclusions(s_lang) s_lang, s_lang_excl = partition_exclusions(s_lang)
forced_s_lang, fsl_excl = partition_exclusions(forced_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 # 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: if lang_excl and not lang:
lang = ["orig"] lang = ["orig"]
if s_lang_excl and not s_lang: if s_lang_excl and not s_lang:
s_lang = ["all"] s_lang = ["all"]
# an override that names languages replaces -l entirely, so it must not inherit its exclusions video_excl = inherited_exclusions(v_lang, v_lang_excl, lang_excl)
video_excl = list(dict.fromkeys(v_lang_excl + ([] if v_lang else lang_excl))) audio_excl = inherited_exclusions(a_lang, a_lang_excl, 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)
ctx = getattr(service, "ctx", None) ctx = getattr(service, "ctx", None)
parent_params = ctx.parent.params if ctx and ctx.parent else 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: if excludes and name in parent_params:
parent_params[name] = includes 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: if audio_description_only:
audio_description = True audio_description = True
@@ -1694,11 +1590,7 @@ class dl:
if skip_dl: if skip_dl:
DOWNLOAD_LICENCE_ONLY.set() DOWNLOAD_LICENCE_ONLY.set()
try: speed_limit_bps = parse_speed_limit(speed_limit)
speed_limit_bps = parse_speed_limit(speed_limit)
except ValueError as e:
self.log.error(str(e))
sys.exit(1)
set_speed_limit(speed_limit_bps) set_speed_limit(speed_limit_bps)
if speed_limit_bps: if speed_limit_bps:
self.log.info(f"Speed limit: {format_speed(speed_limit_bps)}") self.log.info(f"Speed limit: {format_speed(speed_limit_bps)}")
@@ -1713,8 +1605,7 @@ class dl:
try: try:
proxy_download = resolve_proxy(proxy_download.lower(), self.proxy_providers) proxy_download = resolve_proxy(proxy_download.lower(), self.proxy_providers)
except ValueError as e: except ValueError as e:
self.log.error(f"--proxy-download: {e}") raise click.ClickException(f"--proxy-download: {e}") from None
sys.exit(1)
if export: if export:
config.directories.exports.mkdir(parents=True, exist_ok=True) config.directories.exports.mkdir(parents=True, exist_ok=True)
@@ -1725,37 +1616,8 @@ class dl:
else: else:
export_path = None export_path = None
vbitrate_min, vbitrate_max = None, None vbitrate_min, vbitrate_max = bitrate_range(vbitrate_range, "--vbitrate-range", "6000-7000") or (None, None)
if vbitrate_range: abitrate_min, abitrate_max = bitrate_range(abitrate_range, "--abitrate-range", "128-256") or (None, None)
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)
if not acodec: if not acodec:
acodec = [] acodec = []
@@ -1766,10 +1628,6 @@ class dl:
): ):
acodec = AUDIO_CODEC_LIST.convert(acodec) 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: try:
sub_format, ass_style = subtitle_look( sub_format, ass_style = subtitle_look(
sub_format, sub_format,
@@ -1779,18 +1637,11 @@ class dl:
typed_format="sub_format" in self.typed_params, typed_format="sub_format" in self.typed_params,
) )
except ValueError as e: except ValueError as e:
self.log.error(str(e)) raise PlanError(str(e)) from None
sys.exit(1)
if generate_dv and Video.Range.DV in range_ and Video.Range.HYBRID not in range_: 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") self.log.warning("--generate-dv ignored: DV is in the selected ranges")
range_, generated_dv_bases = generated_dv_ranges(range_, generate_dv) 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: if cdm_only is None:
vaults_only = None vaults_only = None
@@ -1861,7 +1712,7 @@ class dl:
message="No titles returned from service", message="No titles returned from service",
success=False, success=False,
) )
sys.exit(1) raise RunStopped("No titles returned")
except Exception as e: except Exception as e:
if self.debug_logger: if self.debug_logger:
self.debug_logger.log_error("get_titles", e, service=self.service) self.debug_logger.log_error("get_titles", e, service=self.service)
@@ -1943,7 +1794,7 @@ class dl:
print_listing(titles.tree(verbose=list_titles)) print_listing(titles.tree(verbose=list_titles))
if list_titles: if list_titles:
return return self.outcome()
if export_path and isinstance(titles, Series): 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 # 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: if not selected_idx:
console.print(Padding(":x: Selection Cancelled...", (0, 5, 1, 5))) console.print(Padding(":x: Selection Cancelled...", (0, 5, 1, 5)))
return return self.outcome()
start_time += time.time() - selection_start start_time += time.time() - selection_start
keep = set(selected_idx) keep = set(selected_idx)
@@ -2022,7 +1873,7 @@ class dl:
if not selected_ui_idx: if not selected_ui_idx:
console.print(Padding(":x: Selection Cancelled...", (0, 5, 1, 5))) console.print(Padding(":x: Selection Cancelled...", (0, 5, 1, 5)))
return return self.outcome()
selection_end = time.time() selection_end = time.time()
start_time += selection_end - selection_start 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. 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): if wanted_total <= 1 or not (kind_only or skip_missing):
self.stop_reason = f"{title}: {reason}" stop = f"{title}: {reason}"
self.log.error(self.stop_reason) self.log.error(stop)
sys.exit(1) raise RunStopped(stop)
self.skipped_titles.append(SkippedTitle(title=str(title), reason=reason)) self.skipped_titles.append(SkippedTitle(title=str(title), reason=reason))
if progress_sink: if progress_sink:
progress_sink({"skipped_titles": list(self.skipped_titles)}) progress_sink({"skipped_titles": list(self.skipped_titles)})
@@ -2560,7 +2411,7 @@ class dl:
self.keys.wait_vault_writes() self.keys.wait_vault_writes()
if export_path: if export_path:
self.log_export_summary() self.log_export_summary()
return return self.outcome()
except Exception as e: # noqa except Exception as e: # noqa
# Reported and swallowed (no re-raise) so the CLI exits cleanly; keep it so the # 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. # API worker sees the title failed rather than completing with no output.
@@ -2596,7 +2447,7 @@ class dl:
self.keys.wait_vault_writes() self.keys.wait_vault_writes()
if export_path: if export_path:
self.log_export_summary() self.log_export_summary()
return return self.outcome()
self.keys.wait_vault_writes() self.keys.wait_vault_writes()
if export_path: if export_path:
@@ -2924,14 +2775,15 @@ class dl:
self.log_export_summary() self.log_export_summary()
if self.skipped_titles: if self.skipped_titles:
if len(self.skipped_titles) == wanted_total: if len(self.skipped_titles) == wanted_total:
self.stop_reason = f"Skipped all {wanted_total} titles" stop = f"Skipped all {wanted_total} titles"
self.log.error(self.stop_reason) self.log.error(stop)
sys.exit(1) raise RunStopped(stop)
skipped = ", ".join(t["title"] for t in self.skipped_titles) skipped = ", ".join(t["title"] for t in self.skipped_titles)
self.log.warning(f"Skipped {len(self.skipped_titles)} of {wanted_total} titles: {skipped}") self.log.warning(f"Skipped {len(self.skipped_titles)} of {wanted_total} titles: {skipped}")
dl_time = time_elapsed_since(start_time) dl_time = time_elapsed_since(start_time)
console.print(Padding(f"Processed all titles in [progress.elapsed]{dl_time}", (0, 5, 1, 5))) 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: 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. """Cut a 60 second sample from a finished file into a ``Sample`` folder next to it.
+21 -110
View File
@@ -4,7 +4,6 @@ import importlib
import json import json
import logging import logging
import os import os
import re
import sys import sys
import tempfile import tempfile
import threading 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.api.sanitize import sanitize_log
from unshackle.core.credential import Credential 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.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: if TYPE_CHECKING:
from unshackle.core.service import Service from unshackle.core.service import Service
@@ -378,11 +376,9 @@ def perform_download(
) -> List[str]: ) -> List[str]:
"""Do the synchronous download work for a job. """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 ``params`` holds the API's form of the ``dl`` options; ``api_plan`` checks and casts them into the dl context,
options in place: `slow` accepts "MIN-MAX", a two-item list, or True (which means 60-120), and `wanted` which feeds dl() and dl.result() as on the CLI. The service is built through its click cli like every other
accepts forms such as "S01E01", "S01-S03", "s1e1", or "1x1" as well as the internal "SxE" form. Music takes track server path.
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.
""" """
from contextlib import redirect_stderr, redirect_stdout from contextlib import redirect_stderr, redirect_stdout
@@ -415,67 +411,12 @@ def perform_download(
if params.pop(banned, None) is not None: if params.pop(banned, None) is not None:
log.warning(f"Ignoring '{banned}' in API download parameters; post-scripts are config-only") log.warning(f"Ignoring '{banned}' in API download parameters; post-scripts are config-only")
client_keys = client_sent_keys(params) from unshackle.core.api.handlers import DL_TRANSPORT_KEYS, instantiate_service, relay_label
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.launch import launch from unshackle.core.launch import launch
from unshackle.core.run_plan import RunStopped, api_plan
try: ctx = api_plan(params, client_sent_keys(params)).context(dl.cli, service)
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,
}
launch(ctx, {"client_argv": f"{relay_label(params)} download job {job_id}"}) launch(ctx, {"client_argv": f"{relay_label(params)} download job {job_id}"})
# Hand-built context: record parameter sources so service dl overrides
# apply to defaults but never clobber client-sent values.
from click.core import ParameterSource
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) 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 # 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, # client can authenticate without anything being persisted to disk. Without a profile,
@@ -487,45 +428,15 @@ def perform_download(
config.credentials[service] = svc_creds = {} config.credentials[service] = svc_creds = {}
svc_creds[params.get("profile") or "default"] = params["credential"] 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: if remote:
from unshackle.core.remote_service import make_remote_service 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() # RemoteService duck-types Service for dl.result()
service_instance = cast("Service", make_remote_service(service_ctx, remote, service, title_id, params)) service_instance = cast("Service", make_remote_service(service_ctx, remote, service, title_id, params))
else: else:
service_module = Services.load(service) service_instance = instantiate_service(ctx, Services.load(service), title_id, params, DL_TRANSPORT_KEYS)
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
original_download_dir = config.directories.downloads original_download_dir = config.directories.downloads
@@ -536,20 +447,23 @@ def perform_download(
# (success/failure) is reported by the worker's result file. # (success/failure) is reported by the worker's result file.
try: try:
with redirect_stdout(stdout_capture), redirect_stderr(stderr_capture): with redirect_stdout(stdout_capture), redirect_stderr(stderr_capture):
dl_instance.result( outcome = dl_instance.result(
service=service_instance, service=service_instance,
**{**ctx.params, "select_titles": False, "list_": False, "list_titles": False}, **{**ctx.params, "select_titles": False, "list_": False, "list_titles": False},
progress_sink=progress_callback, 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: except SystemExit as exc:
if exc.code != 0: if exc.code != 0:
log.error(f"Download exited with code {exc.code}") log.error(f"Download exited with code {exc.code}")
log.debug("Stdout: %s", stdout_capture.getvalue()) log.debug("Stdout: %s", stdout_capture.getvalue())
log.debug("Stderr: %s", stderr_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}") 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 except Exception as exc: # noqa: BLE001 - propagate to caller
log.error(f"Download execution failed: {exc}") log.error(f"Download execution failed: {exc}")
@@ -557,19 +471,16 @@ def perform_download(
log.debug("Stderr: %s", stderr_capture.getvalue()) log.debug("Stderr: %s", stderr_capture.getvalue())
raise raise
# dl.result() catches a download-worker exception, reports it, but returns normally (exit 0). # dl.result() reports a download-worker exception and returns normally, so the CLI exits cleanly.
# It keeps the error in download_error, so the job isn't reported as completed with no output. if outcome.error is not None:
if (error := getattr(dl_instance, "download_error", None)) is not None:
# segment URLs carry signed CDN tokens (hmac, session IDs) that redact_text does not match # 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}") raise APIError(APIErrorCode.WORKER_ERROR, f"download worker failed: {detail}")
if progress_callback: if progress_callback and outcome.skipped_subtitles:
skipped_subs = getattr(dl_instance, "skipped_subtitles", None) progress_callback({"skipped_subtitles": outcome.skipped_subtitles})
if skipped_subs:
progress_callback({"skipped_subtitles": list(skipped_subs)})
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}") log.info(f"Download completed for job {job_id}, {len(output_files)} file(s) in {original_download_dir}")
return output_files return output_files
+19 -97
View File
@@ -1,7 +1,6 @@
import asyncio import asyncio
import base64 import base64
import copy import copy
import enum
import functools import functools
import json import json
import logging import logging
@@ -41,13 +40,11 @@ from unshackle.core.config import config
from unshackle.core.dl_options import ( from unshackle.core.dl_options import (
DEFAULT_DOWNLOAD_PARAMS, DEFAULT_DOWNLOAD_PARAMS,
DL_OPTION_API_NAMES, DL_OPTION_API_NAMES,
cast_dl_params,
forwarded_dl_params, forwarded_dl_params,
) )
from unshackle.core.drm import BlowfishStripe, cbcs, is_null_key, real_kids 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.launch import load_service_config, served_context
from unshackle.core.manifests.snapshot import capture 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.proxies.resolve import initialize_proxy_providers, is_loopback, resolve_proxy
from unshackle.core.remote_protocol import ( from unshackle.core.remote_protocol import (
HEALTH_ROUTE, HEALTH_ROUTE,
@@ -70,6 +67,7 @@ from unshackle.core.remote_protocol import (
TracksReply, TracksReply,
TracksRequest, TracksRequest,
) )
from unshackle.core.run_plan import PlanError, api_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
@@ -84,8 +82,8 @@ from unshackle.core.tunnel import (
is_public_ip, is_public_ip,
tunnel_proxy, tunnel_proxy,
) )
from unshackle.core.utilities import declared_kwargs, kind_only_conflict from unshackle.core.utilities import declared_kwargs
from unshackle.core.utils.click_types import QUALITY_LIST, VIDEO_CODEC_LIST, ContextData 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.collections import ci_get, merge_dict
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
@@ -1675,23 +1673,12 @@ async def list_tracks_handler(data: Dict[str, Any], request: Optional[web.Reques
wanted = None wanted = None
if wanted_param: if wanted_param:
from unshackle.core.utils.click_types import SeasonRange
try: try:
season_range = SeasonRange() wanted = SEASON_RANGE.convert(wanted_param)
if isinstance(wanted_param, list): except click.BadParameter as e:
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:
raise APIError( raise APIError(
APIErrorCode.INVALID_PARAMETERS, APIErrorCode.INVALID_PARAMETERS,
f"Invalid wanted parameter: {e}", f"Invalid wanted parameter: {e.message}",
details={"wanted": wanted_param, "service": normalized_service}, details={"wanted": wanted_param, "service": normalized_service},
) )
elif season is not None and episode is not None: 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]: def wanted_refusal(wanted: Any) -> Optional[str]:
"""Why the job worker could not parse ``wanted``, or None when it can.""" """Why dl 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"
try: try:
if any(not re.match(r"^!?\d+x\d+(\.\d+)?$", t) for t in tokens): SEASON_RANGE.convert(wanted or [])
SeasonRange().parse_tokens(*tokens) except click.BadParameter as e:
except (click.BadParameter, ValueError) as e: return f"Invalid wanted parameter: {e.message}"
return f"Invalid wanted parameter: {e}"
return None return None
@@ -1846,16 +1825,6 @@ def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]:
except APIError as e: except APIError as e:
return e.message 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. # The serve user would create and write any directory a client names; keep it under downloads.
if data.get("output_dir"): if data.get("output_dir"):
root = config.directories.downloads.resolve() 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: if not isinstance(data["abitrate"], int) or data["abitrate"] <= 0:
return "abitrate must be a positive integer" 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: if data.get("quality") is not None:
try: try:
heights = QUALITY_LIST.convert(data["quality"]) 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"]): 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'" 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(): 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): if isinstance(default, bool) and data.get(key) is not None and not isinstance(data[key], bool):
return f"{key} must be a boolean" 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)): 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" 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: try:
params = cast_dl_params(dl.cli, data) params = api_plan(data).params
except click.BadParameter as e: except PlanError as e:
return e.message return e.message
if params.get("sub_font"): 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}, details={"service": service_tag},
) )
validation_error = validate_download_parameters(data) validation_error = await asyncio.to_thread(validate_download_parameters, data)
if validation_error: if validation_error:
raise APIError( raise APIError(
APIErrorCode.INVALID_PARAMETERS, 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_module = None if server else Services.load(normalized_service)
service_params: Optional[Dict[str, Any]] = None service_params: Optional[Dict[str, Any]] = None
# Service defaults and options travel nested: flat, a service default would overwrite the dl value of # Service options travel nested, so a flat key the worker reads stays a dl value; click fills the defaults
# the same name. Missing required __init__ params are handled in download_manager.perform_download. # when the worker builds the service. A remote service applies its own on the remote server.
# A remote service applies its own defaults on the remote server.
cli_params = getattr(getattr(service_module, "cli", None), "params", None) cli_params = getattr(getattr(service_module, "cli", None), "params", None)
if cli_params is not None: if cli_params is not None:
defaults = { sent = service_options(data, {param.name for param in cli_params}, DL_TRANSPORT_KEYS)
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()
)
cast_or_refuse(cli_params, click.Context(click.Command(normalized_service)), sent) 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"]} 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 # 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. # "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"} SESSION_TRANSPORT_KEYS = (SessionCreate.__required_keys__ | SessionCreate.__optional_keys__) - {"client"}
+7 -10
View File
@@ -22,12 +22,11 @@ RemoteKind = Literal["langs", "audio_codecs", "flag"]
class ApiOption: class ApiOption:
"""A dl option that a REST API client can set, with its API default. """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 ``remote`` names how a remote client sends the option to the server in ``dl_params``, for a service that
sends the option to the server in ``dl_params``, for a service that reads it from ``ctx.parent.params``. reads it from ``ctx.parent.params``.
""" """
default: Any default: Any
raw: bool = False
remote: Optional[RemoteKind] = None remote: Optional[RemoteKind] = None
@@ -45,7 +44,7 @@ DL_OPTIONS: Dict[str, Optional[ApiOption]] = {
"range": ApiOption(["SDR"]), "range": ApiOption(["SDR"]),
"channels": ApiOption(None), "channels": ApiOption(None),
"no_atmos": ApiOption(False), "no_atmos": ApiOption(False),
"wanted": ApiOption([], raw=True), "wanted": ApiOption([]),
"latest_episode": ApiOption(False), "latest_episode": ApiOption(False),
"latest_episodes": ApiOption(None), "latest_episodes": ApiOption(None),
"lang": ApiOption(["orig"], remote="langs"), "lang": ApiOption(["orig"], remote="langs"),
@@ -74,7 +73,7 @@ DL_OPTIONS: Dict[str, Optional[ApiOption]] = {
"no_attachments": ApiOption(False), "no_attachments": ApiOption(False),
"audio_description": ApiOption(False), "audio_description": ApiOption(False),
"audio_description_only": ApiOption(False), "audio_description_only": ApiOption(False),
"slow": ApiOption(None, raw=True), "slow": ApiOption(None),
"split_audio": ApiOption(None), "split_audio": ApiOption(None),
"skip_dl": ApiOption(False), "skip_dl": ApiOption(False),
"all_drm": 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} 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 = [ FORWARDED_DL_PARAMS = [
(name, option) (name, option)
for kind in get_args(RemoteKind) 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. """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 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 ``output_dir: ""`` is not the working directory. A parameter outside ``DEFAULT_DOWNLOAD_PARAMS`` never reaches
outside ``DEFAULT_DOWNLOAD_PARAMS`` never reaches dl, so a new CLI option is closed to API clients by default. dl, so API clients cannot set a new CLI option until the table opens it. Raises ``click.BadParameter``.
Raises ``click.BadParameter``.
""" """
kept: Dict[str, Any] = {} kept: Dict[str, Any] = {}
to_cast: 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) value = params.get(key)
if value is None or value == "" or (key == "range" and value == []): if value is None or value == "" or (key == "range" and value == []):
value = default 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: try:
return {**kept, **cast_service_options(cli.params, click.Context(cli), to_cast)} return {**kept, **cast_service_options(cli.params, click.Context(cli), to_cast)}
except click.BadParameter as e: except click.BadParameter as e:
+196
View File
@@ -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)
+15
View File
@@ -33,6 +33,21 @@ log = logging.getLogger("download")
HYBRID_BASE_RANGES = (Video.Range.HDR10P, Video.Range.HDR10) 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) @dataclass(frozen=True)
class Skip: class Skip:
"""The title has no track the selection asks for. """The title has no track the selection asks for.
+5
View File
@@ -308,6 +308,11 @@ def partition_exclusions(tokens: Optional[Sequence[str]]) -> tuple[list[str], li
return includes, excludes 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( def matched_language_tags(
tokens: Sequence[str], tokens: Sequence[str],
available: Sequence[Union[str, Language, None]], available: Sequence[Union[str, Language, None]],
+12 -2
View File
@@ -322,10 +322,18 @@ class SeasonRange(click.ParamType):
computed = [k for k in computed if k != exclusion and not k.startswith(prefix)] computed = [k for k in computed if k != exclusion and not k.startswith(prefix)]
return list(set(computed)) return list(set(computed))
PARSED_KEY = re.compile(r"^!?(0|[1-9]\d*)x(0|[1-9]\d*)(\.[1-9]\d?)?$")
def convert( 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]: ) -> 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): class LanguageRange(click.ParamType):
@@ -500,6 +508,8 @@ class SlowDelayRange(click.ParamType):
return value return value
if isinstance(value, bool): if isinstance(value, bool):
return (60, 120) if value else None 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)) match = re.match(r"^(\d+)-(\d+)$", str(value))
if not match: if not match: