"""Resume in every download mode: a run that fails after some segments, then a second run, gives the bytes of a run that never failed, and the second run fetches and decrypts only what the first did not finish.""" from __future__ import annotations import importlib from collections import Counter from functools import partial from pathlib import Path from uuid import UUID import pytest import requests from tests.core.test_ism_init import piff_fragment from tests.core.test_rolling_merge_hls_ism import ( KID, PARTS, PIFF_PARTS, FakeDRM, dash_track, hls_track, ism_track, make_ctx, ) from tests.core.test_rolling_merge_hls_ism import no_cancel as no_cancel # noqa: F401 from tests.core.test_rolling_merge_hls_ism import ( no_decrypt, ) from tests.core.test_rolling_merge_hls_ism import no_ffprobe as no_ffprobe # noqa: F401 from tests.core.test_rolling_merge_hls_ism import server as server # noqa: F401 from tests.core.test_rolling_merge_hls_ism import ( widevine, ) from unshackle.core import binaries from unshackle.core.config import config from unshackle.core.constants import DOWNLOAD_CANCELLED from unshackle.core.drm.segment_decrypt import SegmentDecrypter from unshackle.core.manifests import DASH, HLS, ISM from unshackle.core.manifests import dash as dash_module from unshackle.core.manifests import hls as hls_module from unshackle.core.temp import RESUME_STASH, task_temp_dir from unshackle.core.tracks.segment_store import SegmentStore, _index KEY_A, KEY_B = "aa" * 16, "bb" * 16 FAIL_AT = 3 class Routes(dict): """The server routes, counting each request by path.""" hits: Counter def get(self, key, default=None): self.hits[key] += 1 return super().get(key, default) @pytest.fixture def routes(server): server.routes = Routes(server.routes) server.routes.hits = Counter() return server.routes @pytest.fixture(autouse=True) def resume(monkeypatch): monkeypatch.setattr(config, "continue_downloads", True) monkeypatch.setattr(importlib.import_module("unshackle.core.downloaders.requests"), "MAX_ATTEMPTS", 1) @pytest.fixture def decrypted(monkeypatch) -> list[str]: """Segment decryption without mp4decrypt: the output is the input behind a mark of the key. Returns the name of each file it decrypts. """ names: list[str] = [] def run(self, args): source, target = Path(args[-2]), Path(args[-1]) names.append(source.name) key = next(arg for arg in self.key_args if ":" in arg).split(":")[1] target.write_bytes(f"[{key[:2]}]".encode() + source.read_bytes()) monkeypatch.setattr(SegmentDecrypter, "run", run) monkeypatch.setattr(binaries, "Mp4decrypt", Path("mp4decrypt")) return names def segment_indices(names: list[str]) -> list[int]: """The segment indices among the decrypted file names; the init has none.""" return [index for name in names if (index := _index(Path(name))) is not None] def segment_decryption(monkeypatch, on: bool) -> None: for module in (dash_module, hls_module): monkeypatch.setattr(module, "can_use", lambda *a, **kw: on) # a 16-byte IV that only fragment 0 can tell the merge, as a PIFF override the CENC rewrite must agree with PIFF16_PARTS = [ piff_fragment(override=True, iv_size=16).replace(b"\xab" * 64, bytes([0xD0 + i]) * 64) for i in range(len(PARTS)) ] def maker(server, parser, fragments=PIFF_PARTS): """A fresh track of the parser for each run, encrypted as a licence step and the decrypt step see it.""" if parser is ISM: for i, fragment in enumerate(fragments): server.routes[f"/x.ism/part{i}.m4s"] = fragment def make(): if parser is ISM: track = ism_track(server) track.drm = [FakeDRM()] else: track = dash_track(server) if parser is DASH else hls_track(server, False) track.drm = [widevine()] return track return make def context(tmp_path, name: str, key: str): ctx = make_ctx(tmp_path, name) ctx.max_workers = 1 ctx.license_widevine = lambda drm, **kw: drm.content_keys.update({KID: key}) return ctx def part(parser, index: int) -> str: return f"/x.ism/part{index}.m4s" if parser is ISM else f"/part{index}.m4s" def fail_once(server, parser, make, ctx) -> None: """Run a download that fails on segment FAIL_AT.""" body = server.routes.pop(part(parser, FAIL_AT)) with pytest.raises(requests.HTTPError): parser.download_track(make(), ctx) server.routes[part(parser, FAIL_AT)] = body DOWNLOAD_CANCELLED.clear() MODES = [ pytest.param(parser, segment_decrypt, merge, id=f"{parser.__name__.lower()}-{name}") for parser in (DASH, HLS, ISM) for segment_decrypt, merge, name in [ (False, False, "plain"), (False, True, "rolling"), (True, False, "segment-decrypt"), (True, True, "segment-decrypt-rolling"), ] if parser is not ISM or not segment_decrypt ] @pytest.mark.parametrize("parser, segment_decrypt, merge", MODES) def test_a_resumed_download_matches_one_that_never_failed( server, routes, tmp_path, monkeypatch, decrypted, parser, segment_decrypt, merge ): monkeypatch.setattr(config, "merge_segments", merge) segment_decryption(monkeypatch, segment_decrypt) no_decrypt(monkeypatch, mark=b"whole:") make = maker(server, parser) whole = context(tmp_path, "whole.mp4", KEY_A) parser.download_track(make(), whole) # a DASH licence step reads segment 0 for the KID; every other request is the download probes = Counter({path: hits - 1 for path, hits in routes.hits.items()}) ctx = context(tmp_path, "resumed.mp4", KEY_A) decrypted.clear() fail_once(server, parser, make, ctx) first = segment_indices(decrypted) routes.hits.clear() decrypted.clear() parser.download_track(make(), ctx) assert ctx.save_path.read_bytes() == whole.save_path.read_bytes() assert all(routes.hits[part(parser, i)] == probes[part(parser, i)] for i in range(FAIL_AT)) # a segment that the failure stopped before its decrypt is decrypted on resume; no segment is decrypted twice assert sorted(first + segment_indices(decrypted)) == (list(range(len(PARTS))) if segment_decrypt else []) assert not ctx.save_dir.exists() assert not SegmentStore(make(), ctx.save_dir).sidecar.exists() def test_a_resumed_ism_merge_keeps_the_iv_size_of_fragment_zero(server, routes, tmp_path, monkeypatch): monkeypatch.setattr(config, "merge_segments", True) no_decrypt(monkeypatch) make = maker(server, ISM, PIFF16_PARTS) whole = context(tmp_path, "whole.mp4", KEY_A) ISM.download_track(make(), whole) ctx = context(tmp_path, "resumed.mp4", KEY_A) fail_once(server, ISM, make, ctx) routes.hits.clear() ISM.download_track(make(), ctx) assert ctx.save_path.read_bytes() == whole.save_path.read_bytes() assert not routes.hits[part(ISM, 0)] @pytest.mark.parametrize("merge", [False, True], ids=["segment-decrypt", "segment-decrypt-rolling"]) def test_keys_of_other_tracks_do_not_discard_what_the_track_key_decrypted( server, routes, tmp_path, monkeypatch, decrypted, merge ): monkeypatch.setattr(config, "merge_segments", merge) segment_decryption(monkeypatch, True) no_decrypt(monkeypatch) make = maker(server, DASH) whole = context(tmp_path, "whole.mp4", KEY_A) DASH.download_track(make(), whole) probes = Counter({path: hits - 1 for path, hits in routes.hits.items()}) ctx = context(tmp_path, "resumed.mp4", KEY_A) # the first run licenses and gets the keys of other tracks too; the second takes the track key from a vault ctx.license_widevine = lambda drm, **kw: drm.content_keys.update({KID: KEY_A, UUID(int=7): KEY_B}) fail_once(server, DASH, make, ctx) ctx.license_widevine = whole.license_widevine routes.hits.clear() DASH.download_track(make(), ctx) assert ctx.save_path.read_bytes() == whole.save_path.read_bytes() assert all(routes.hits[part(DASH, i)] == probes[part(DASH, i)] for i in range(FAIL_AT)) @pytest.mark.parametrize("merge", [False, True], ids=["segment-decrypt", "segment-decrypt-rolling"]) def test_a_new_key_discards_what_the_old_key_decrypted(server, tmp_path, monkeypatch, decrypted, merge): monkeypatch.setattr(config, "merge_segments", merge) segment_decryption(monkeypatch, True) no_decrypt(monkeypatch) make = maker(server, DASH) whole = context(tmp_path, "whole.mp4", KEY_B) DASH.download_track(make(), whole) ctx = context(tmp_path, "resumed.mp4", KEY_A) fail_once(server, DASH, make, ctx) ctx.license_widevine = whole.license_widevine DASH.download_track(make(), ctx) assert ctx.save_path.read_bytes() == whole.save_path.read_bytes() assert b"[aa]" not in ctx.save_path.read_bytes() def test_kept_decrypted_segments_past_the_checkpoint_are_merged_without_a_request( server, routes, tmp_path, monkeypatch, decrypted ): monkeypatch.setattr(config, "merge_segments", True) segment_decryption(monkeypatch, True) no_decrypt(monkeypatch) make = maker(server, DASH) whole = context(tmp_path, "whole.mp4", KEY_A) DASH.download_track(make(), whole) ctx = context(tmp_path, "resumed.mp4", KEY_A) probes = Counter({path: hits - 1 for path, hits in routes.hits.items()}) fail_once(server, DASH, make, ctx) # segment 4 finished before the failure: its decrypt replaced it, but a lock kept the downloaded file raw = routes[part(DASH, 4)] (ctx.save_dir / "4.clear").write_bytes(b"[aa]" + raw) (ctx.save_dir / "4.mp4").write_bytes(raw) (ctx.save_dir / "3.clear.!dev").write_bytes(b"half a decrypt") with open(ctx.save_path, "ab") as output: output.write(b"\xff" * 100_000) routes.hits.clear() decrypted.clear() DASH.download_track(make(), ctx) assert ctx.save_path.read_bytes() == whole.save_path.read_bytes() assert {path for path, hits in routes.hits.items() if path.startswith("/part") and hits > probes[path]} == { part(DASH, FAIL_AT) } assert [name for name in decrypted if name[0].isdigit()] == ["3.mp4"] def test_a_rolling_output_crosses_the_run_boundary_in_the_stash(server, routes, tmp_path, monkeypatch, decrypted): monkeypatch.setattr(config, "merge_segments", True) monkeypatch.setattr(config.directories, "temp", tmp_path / "temp") segment_decryption(monkeypatch, True) no_decrypt(monkeypatch) make = maker(server, DASH) def download(key: str) -> object: track = make() track.download( session=requests.Session(), prepare_drm=lambda drm, **kw: drm.content_keys.update({KID: key}), progress=partial(lambda **kw: None), max_workers=1, ) return track with task_temp_dir(): whole = download(KEY_A).path.read_bytes() probes = Counter({path: hits - 1 for path, hits in routes.hits.items()}) body = server.routes.pop(part(DASH, FAIL_AT)) with task_temp_dir(): with pytest.raises(requests.HTTPError): download(KEY_A) stash = config.directories.temp / RESUME_STASH assert sorted(p.name for p in stash.iterdir()) == [ "Video_" + make().id + ".mp4", "Video_" + make().id + ".mp4_segments", "Video_" + make().id + ".mp4_segments.resume.json", ] assert not list(stash.rglob("*.!dev")) server.routes[part(DASH, FAIL_AT)] = body DOWNLOAD_CANCELLED.clear() routes.hits.clear() with task_temp_dir(): assert download(KEY_A).path.read_bytes() == whole assert all(routes.hits[part(DASH, i)] == probes[part(DASH, i)] for i in range(FAIL_AT))