feat(dl): add --license-first to license every track of a title before any download

This commit is contained in:
imSp4rky
2026-12-05 19:23:40 -07:00
parent 3a0a74e694
commit ce7cb41eac
7 changed files with 238 additions and 10 deletions
+158
View File
@@ -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