diff --git a/docs/guide/cli-reference.md b/docs/guide/cli-reference.md index 449d34568..34499d201 100644 --- a/docs/guide/cli-reference.md +++ b/docs/guide/cli-reference.md @@ -216,6 +216,7 @@ Keep only certain track types, or skip certain track types. | `--vaults-only` | Get no licence. A content key that no key vault, export or earlier track gives fails the title. With both flags, the last one wins. | | `--cdm ` | Use the named CDM device for this run, and ignore the `cdm` config mapping, its quality and Widevine/PlayReady entries included. Over `--remote`, that device licenses the remote session, not the server CDM. | | `--skip-dl` | Skip the download but still retrieve keys. | +| `--license-first` | Get the content keys of every track of a title before any track of that title downloads. A failed licence then stops the run before that title downloads data. Over `--remote` it applies on the client. No effect with `--skip-dl`. | | `--all-drm` | License each track with both Widevine and PlayReady. Needs a CDM for each DRM system. Key Vaults are read first; `--cdm-only` sends a challenge for each system. Not for use with `--cdm`. | | `--export` | Write an [export](downloading.md#keys-vaults-and-export) of each title's tracks, DRM init data and content keys to the exports directory. | diff --git a/docs/guide/downloading.md b/docs/guide/downloading.md index 878afea78..9064bcb85 100644 --- a/docs/guide/downloading.md +++ b/docs/guide/downloading.md @@ -66,6 +66,8 @@ with `--skip-dl`. `--list` prints the tracks a title exposes and stops before selection. `--list-titles` prints every title the service returned and stops before `--wanted`/`--latest-episode`/`--latest-episodes` filtering. `--skip-dl` runs the licence step but skips the segment download. +`--license-first` runs the licence step of every track of a title before any segment of that title downloads, +so a failed licence stops the run before that title downloads data. The download then sends no second licence. ## Choosing quality diff --git a/docs/reference/configuration/download.md b/docs/reference/configuration/download.md index 22de5783e..c4c60ccf1 100644 --- a/docs/reference/configuration/download.md +++ b/docs/reference/configuration/download.md @@ -56,6 +56,7 @@ Common config keys. This is a useful subset, and every `dl` flag works: | `slow` | str | *(unset)* | Inter-title delay, e.g. `"20-40"`. | | `best_available` | bool | `false` | Warn instead of failing when a requested resolution, range, video language, or audio language is missing, or when one DRM system does not license under `--all-drm`. The CLI flag is `--best-available`, also spelled `--warn-only`. | | `skip_missing` | bool | `false` | Skip a title that misses a required language (`require_audio`, `require_video`, `require_subs`) or a track that a filter asks for, and continue with the next title. A run with one title, or a run that skips every title, still fails. The CLI flag is `--skip-missing`. For REST API jobs, set it in the [`serve`](services.md#serve) block. | +| `license_first` | bool | `false` | Get the content keys of every track of a title before any track of that title downloads. A failed licence stops the run before that title downloads data. The CLI flag is `--license-first`. For REST API jobs, set it in the [`serve`](services.md#serve) block or send `license_first` in the request. | | `generate_dv` | bool | `false` | With `-r HYBRID`, make Dolby Vision from the HDR10+ metadata or the decoded video when a title has no DV track. With `-r HDR10` or `-r HDR10P`, make it for that base and ignore a DV track. See [Dolby Vision without a DV track](../../guide/downloading.md#dolby-vision-without-a-dv-track). | | `proxy` | str | *(unset)* | Default proxy URI or 2-letter country. | | `no_folder` | bool | `false` | Do not create a per-title folder. | diff --git a/tests/commands/test_license_first.py b/tests/commands/test_license_first.py new file mode 100644 index 000000000..44e94ab84 --- /dev/null +++ b/tests/commands/test_license_first.py @@ -0,0 +1,158 @@ +"""dl --license-first: every track of a title holds its content keys before any track downloads.""" + +from functools import partial +from pathlib import Path +from typing import Any +from uuid import UUID + +import click +import pytest +from click.testing import CliRunner, Result + +from unshackle.commands import dl as dl_module +from unshackle.core.constants import DOWNLOAD_CANCELLED +from unshackle.core.drm import ClearKeyCENC +from unshackle.core.drm.clearkey_cenc import b64url_encode_nopad +from unshackle.core.drm.key_resolution import ContentKeyResolver +from unshackle.core.manifests import url +from unshackle.core.titles import Movie, Movies +from unshackle.core.tracks import Audio, Chapters, Track, Tracks, Video + +pytestmark = pytest.mark.usefixtures("example_service") + +KIDS = {"video": UUID(int=1), "audio": UUID(int=2)} + + +class Run: + """One ``dl EXAMPLE`` run of a movie with an encrypted video and audio track; only the file fetch is fake.""" + + def __init__(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, refuse: str | None = None) -> None: + self.licences: list[str] = [] + self.fetched: list[str] = [] + self.downloaded: list[Path | None] = [] + self.monkeypatch = monkeypatch + self.tmp_path = tmp_path + self.refuse = refuse + + def licence(self, *_: Any, challenge: bytes, track: Track, **__: Any) -> dict: + self.licences.append(track.id) + if track.id == self.refuse: + raise click.ClickException(f"Licence refused for track {track.id}") + kid = KIDS[track.id] + return { + "keys": [ + {"kty": "oct", "kid": b64url_encode_nopad(kid.bytes), "k": b64url_encode_nopad(bytes(range(1, 17)))} + ] + } + + def fetch(self, *, output_dir: Path, filename: str, **_: Any) -> Any: + self.fetched.append(filename) + (output_dir / filename).write_bytes(b"media bytes") + yield {"file_downloaded": output_dir / filename} + + @staticmethod + def complete(track: Track, ctx: Any, drm: Any, **_: Any) -> None: + """Hand the fetched file to the track as decrypted, as the media bytes are not CENC.""" + track.path = ctx.save_path + track.drm = None + + def tracks(self) -> Tracks: + tracks = Tracks( + Video(id_="video", url="https://example.invalid/v.mp4", language="en", codec=Video.Codec.AVC), + Audio(id_="audio", url="https://example.invalid/a.mp4", language="en", codec=Audio.Codec.AAC), + ) + for track in tracks: + track.drm = [ClearKeyCENC(kids=[KIDS[track.id]])] + track.downloader = self.fetch + return tracks + + def __call__(self, *args: str) -> Result: + from unshackle.core import services + + service = services.ensure_loaded("EXAMPLE") + assert service is not None + movie = Movie(id_="movie-1", service=service, name="Title", year=2020, language="en") + patch = self.monkeypatch.setattr + patch(service, "authenticate", lambda self, *a, **k: None) + patch(service, "get_titles", lambda self: Movies([movie])) + patch(service, "get_tracks", lambda _, title: self.tracks()) + patch(service, "get_chapters", lambda self, title: Chapters()) + patch(service, "get_clearkey_license", self.licence) + patch(service, "on_track_downloaded", lambda _, track: self.downloaded.append(track.path)) + patch(Track, "get_key_id", lambda track, *a, **k: KIDS[track.id]) + patch(url, "complete_track", self.complete) + patch(ContentKeyResolver, "LICENSE_KEY_CACHE", {}) + patch(dl_module.TitleMetadata, "search", lambda self, *a, **k: None) + patch(dl_module.config, "key_vaults", []) + patch(dl_module.config, "output_template", {"movies": "{title}"}) + patch(dl_module.config.directories, "temp", self.tmp_path / "temp") + patch(dl_module.dl, "get_cdm", lambda self, *a, **k: None) + patch(dl_module.dl.cli, "_result_callback", dl_module.dl.cli._result_callback) + cli = ( + "-o", + str(self.tmp_path / "out"), + "-l", + "en", + "--downloads", + "1", + "--no-mux", + *args, + "EXAMPLE", + "--movie", + "movie-1", + ) + return CliRunner().invoke(dl_module.dl.cli, cli) + + +def test_a_licence_failure_stops_the_title_before_any_track_downloads( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + run = Run(monkeypatch, tmp_path, refuse="audio") + + result = run("--license-first") + + assert "Licence refused for track audio" in result.output + assert result.exit_code == 1 + assert run.licences == ["video", "audio"] + assert run.fetched == [] + + +def test_without_the_flag_a_track_downloads_before_a_later_licence_fails( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + run = Run(monkeypatch, tmp_path, refuse="audio") + + result = run() + + assert result.exit_code == 1, result.output + assert run.fetched == ["Video_video.mp4"], result.output + + +def test_the_download_pass_sends_no_second_licence(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + run = Run(monkeypatch, tmp_path) + + result = run("--license-first") + + assert result.exit_code == 0, result.output + assert run.licences == ["video", "audio"] + assert sorted(run.fetched) == ["Audio_audio.mp4", "Video_video.mp4"] + assert len(run.downloaded) == 2 and all(run.downloaded) + + +@pytest.mark.parametrize( + ("cancelled", "shown"), + [(False, ["LICENSED"]), (True, ["LICENSED", "[yellow]SKIPPED"])], + ids=["licensed", "cancelled"], +) +def test_the_licence_pass_does_not_end_the_progress_bar(cancelled: bool, shown: list[str]) -> None: + states: list[str] = [] + progress = partial(dl_module.without_skip_states, lambda **kw: states.append(kw["downloaded"])) + if cancelled: + DOWNLOAD_CANCELLED.set() + try: + for state in ("[yellow]SKIPPING", "LICENSED", "[yellow]SKIPPED"): + progress(downloaded=state) + finally: + DOWNLOAD_CANCELLED.clear() + + assert states == shown diff --git a/unshackle/commands/dl.py b/unshackle/commands/dl.py index f489c1624..65378914e 100644 --- a/unshackle/commands/dl.py +++ b/unshackle/commands/dl.py @@ -423,6 +423,45 @@ def download_tracks_in_passes( DOWNLOAD_CANCELLED.clear() # never leave a failed track's cancel set for later code +def license_before_download( + tracks: Iterable[AnyTrack], + max_concurrent: int, + run_one: Callable[[AnyTrack, int], None], + on_track_downloaded: Callable[[AnyTrack], None], + *, + skip_subtitle_errors: bool, +) -> None: + """Run each track of a title as a licence-only download, as ``--skip-dl`` does (``--license-first``). + + The download after it finds the content keys held and sends no licence. A failed licence raises before any + segment of the title downloads; a subtitle that ``skip_subtitle_errors`` lets fail is left to the download. + The service gets no TRACK_DOWNLOADED event for a track that has no file yet. + """ + DOWNLOAD_LICENCE_ONLY.set() + events.unsubscribe(events.Types.TRACK_DOWNLOADED, on_track_downloaded) + try: + download_tracks_in_passes( + tracks, + max_concurrent, + run_one, + skip_subtitle_errors=skip_subtitle_errors, + on_subtitle_skipped=lambda _: None, + ) + finally: + DOWNLOAD_LICENCE_ONLY.clear() + events.subscribe(events.Types.TRACK_DOWNLOADED, on_track_downloaded) + + +def without_skip_states(progress: Callable[..., None], **kwargs: Any) -> None: + """Pass an update to ``progress``, but not the SKIPPING or SKIPPED state that ends a licence-only download. + + A SKIPPED track that a failed licence cancelled still shows SKIPPED. + """ + state = kwargs.get("downloaded") + if state != "[yellow]SKIPPING" and (state != "[yellow]SKIPPED" or DOWNLOAD_CANCELLED.is_set()): + progress(**kwargs) + + DISK_NEED_FACTOR = 2 """Times its estimated track size that a title needs on the temp volume: each encrypted track and its decrypted copy.""" @@ -1031,6 +1070,12 @@ class dl: @click.option( "--skip-dl", is_flag=True, default=False, help="Skip downloading while still retrieving the decryption keys." ) + @click.option( + "--license-first", + is_flag=True, + default=False, + help="Get the content keys of every track of a title before any track of the title downloads.", + ) @click.option( "--all-drm", is_flag=True, @@ -1609,6 +1654,7 @@ class dl: skip_existing: bool = False, force: bool = False, max_downloads: int | None = None, + license_first: bool = False, *_: Any, **__: Any, ) -> RunOutcome: @@ -2364,9 +2410,13 @@ class dl: prepare_drm_for: Callable[[AnyTrack], partial], progress_callables: list[partial], disk_check: DiskCheck | None, + licence_only: bool = False, ) -> None: + if licence_only and isinstance(track, Subtitle) and not track.drm: + return # read before the download, whose decrypt of a held-key DRM clears track.drm held = next((drm for drm in track.drm or [] if held_key(drm)), None) + progress = progress_callables[i] track.download( session=track.session or service.session, no_proxy_download=no_proxy_download, @@ -2376,12 +2426,12 @@ class dl: max_workers=workers, adaptive_workers=adaptive_workers, download_processes=download_processes, - progress=progress_callables[i], - on_segments=disk_check.add_segments if disk_check else None, + progress=partial(without_skip_states, progress) if licence_only else progress, + on_segments=disk_check.add_segments if disk_check and not licence_only else None, sample_decrypter=service.sample_decrypter(track), fairplay_bridge=service.fairplay_bridge() is not None, ) - if self.export: + if self.export and not licence_only: self.export.record(title, track, held) def on_subtitle_skipped(track: Subtitle, *, title: Title_T) -> None: @@ -2395,16 +2445,25 @@ class dl: skipped_before = len(self.skipped_subtitles) grow_session_pool(service.session, downloads * (workers or default_max_workers())) + run_one = partial( + download_track, + title=title, + prepare_drm_for=prepare_drm_for, + progress_callables=tracks_progress_callables, + disk_check=disk_check, + ) + if license_first and not skip_dl: + license_before_download( + title.tracks, + downloads, + partial(run_one, licence_only=True), + service.on_track_downloaded, + skip_subtitle_errors=skip_subtitle_errors, + ) download_tracks_in_passes( title.tracks, downloads, - partial( - download_track, - title=title, - prepare_drm_for=prepare_drm_for, - progress_callables=tracks_progress_callables, - disk_check=disk_check, - ), + run_one, skip_subtitle_errors=skip_subtitle_errors, on_subtitle_skipped=partial(on_subtitle_skipped, title=title), ) diff --git a/unshackle/core/api/routes.py b/unshackle/core/api/routes.py index 20c3ba787..e5bebcfa0 100644 --- a/unshackle/core/api/routes.py +++ b/unshackle/core/api/routes.py @@ -1258,6 +1258,12 @@ async def download(request: web.Request) -> web.Response: default: false description: >- Skip the download and get only the content keys. + license_first: + type: boolean + default: false + description: >- + Get the content keys of every track of a title before any track of the title downloads. A licence + failure stops the run before that title downloads data. No effect with `skip_dl`. all_drm: type: boolean default: false diff --git a/unshackle/core/dl_options.py b/unshackle/core/dl_options.py index ed5d35113..405114848 100644 --- a/unshackle/core/dl_options.py +++ b/unshackle/core/dl_options.py @@ -75,6 +75,7 @@ DL_OPTIONS: dict[str, ApiOption | None] = { "slow": ApiOption(None), "split_audio": ApiOption(None), "skip_dl": ApiOption(False), + "license_first": ApiOption(False), "all_drm": ApiOption(False), "export": ApiOption(False), "cdm_only": ApiOption(None),