mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-29 12:35:13 +00:00
fix(events): emit TRACK_DOWNLOADED once per track after decryption
This commit is contained in:
@@ -687,7 +687,8 @@ See the [DRM & CDM reference](../guide/drm-and-cdm.md) for the full picture.
|
||||
|
||||
Override any of these to react to pipeline stages (all no-ops by default):
|
||||
`on_segment_downloaded`, `on_track_downloaded`, `on_track_decrypted`,
|
||||
`on_track_repacked`, `on_track_multiplex`. Also override `search()` to yield
|
||||
`on_track_repacked`, `on_track_multiplex`. `on_track_downloaded` runs once per track, after
|
||||
unshackle decrypted the `drm` of the track. Also override `search()` to yield
|
||||
`SearchResult` objects for `unshackle search`.
|
||||
|
||||
!!! warning "Set `ANONYMOUS_SEARCH` only for a search that needs no account"
|
||||
|
||||
@@ -6,6 +6,7 @@ identical with no segment directory left behind, and the rolling run must report
|
||||
phase (the post-download run must). A second HLS case with a discontinuity checks that an
|
||||
ineligible playlist keeps the post-download merge and still produces the same bytes. The shared
|
||||
download, rolling merge and decrypt hand-off are tested on their own in test_segment_pipeline.
|
||||
The last test runs Track.download for each descriptor and counts the TRACK_DOWNLOADED events.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -30,12 +31,14 @@ from unshackle.core.config import config
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED
|
||||
from unshackle.core.drm import ClearKeyCENC, MonaLisa, Widevine
|
||||
from unshackle.core.drm import cenc as cenc_module
|
||||
from unshackle.core.events import events
|
||||
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.manifests import segment_pipeline
|
||||
from unshackle.core.manifests.ism_init import PIFF_SENC_UUID
|
||||
from unshackle.core.tracks import Video
|
||||
from unshackle.core.tracks import track as track_module
|
||||
from unshackle.core.tracks.track import DownloadContext
|
||||
|
||||
INIT = bytes(range(100))
|
||||
@@ -236,18 +239,20 @@ class FakeSegmentDecrypter:
|
||||
pass
|
||||
|
||||
|
||||
def no_decrypt(monkeypatch) -> list[tuple[object, bool]]:
|
||||
def no_decrypt(monkeypatch, mark: bytes = b"") -> list[tuple[object, bool]]:
|
||||
"""Stub the decrypt step and its check, and return the (drm, decrypt) of each decrypt call.
|
||||
|
||||
The merged file is compared byte for byte. The pipeline decrypts a merged track; HLS itself
|
||||
decrypts each key range of a post-download merge.
|
||||
The merged file is compared byte for byte; the stub puts `mark` in front of it. The pipeline decrypts
|
||||
a merged track; HLS itself decrypts each key range of a post-download merge.
|
||||
"""
|
||||
calls: list[tuple[object, bool]] = []
|
||||
|
||||
def decrypt_track(drm, path, licence=None, track_kid=None, decrypt=True, track=None):
|
||||
calls.append((drm, decrypt))
|
||||
if mark:
|
||||
path.write_bytes(mark + path.read_bytes())
|
||||
|
||||
for module in (segment_pipeline, hls_module):
|
||||
for module in (segment_pipeline, hls_module, track_module):
|
||||
monkeypatch.setattr(module, "decrypt_track", decrypt_track)
|
||||
monkeypatch.setattr(module, "assert_fragments_decrypted", lambda *a, **kw: None)
|
||||
return calls
|
||||
@@ -419,11 +424,8 @@ def test_each_manifest_kind_licenses_through_the_licence_step(server, tmp_path,
|
||||
def licence(drm, track_kid=None):
|
||||
licensed.append((drm, track_kid))
|
||||
|
||||
if kind == "url":
|
||||
track = Video(url=f"{base(server)}init.mp4", language="en", descriptor=Video.Descriptor.URL, drm=[drm])
|
||||
else:
|
||||
track = {"dash": dash_track, "hls": lambda srv: hls_track(srv, False), "ism": ism_track}[kind](server)
|
||||
track.drm = [drm]
|
||||
track = make_track(server, kind, encrypted=False)
|
||||
track.drm = [drm]
|
||||
ctx = make_ctx(tmp_path, f"{kind}.mp4")
|
||||
ctx.license_widevine = licence
|
||||
monkeypatch.setattr(constants.DOWNLOAD_LICENCE_ONLY, "is_set", lambda: True)
|
||||
@@ -444,3 +446,84 @@ def test_each_manifest_kind_licenses_through_the_licence_step(server, tmp_path,
|
||||
("url", "ClearKeyCENC"): [(drm, None)],
|
||||
}
|
||||
assert licensed == expected[(kind, system)]
|
||||
|
||||
|
||||
MARK = b"clear:"
|
||||
|
||||
|
||||
def make_track(srv, kind: str, encrypted: bool):
|
||||
if kind == "url":
|
||||
track = Video(url=f"{base(srv)}init.mp4", language="en", descriptor=Video.Descriptor.URL)
|
||||
elif kind == "ism":
|
||||
if encrypted:
|
||||
for i, part in enumerate(PIFF_PARTS):
|
||||
srv.routes[f"/x.ism/part{i}.m4s"] = part
|
||||
track = ism_track(srv)
|
||||
elif kind == "hls":
|
||||
track = hls_track(srv, False)
|
||||
else:
|
||||
track = dash_track(srv)
|
||||
if encrypted:
|
||||
track.drm = [widevine()]
|
||||
return track
|
||||
|
||||
|
||||
@pytest.mark.parametrize("encrypted", [False, True], ids=["clear", "drm"])
|
||||
@pytest.mark.parametrize(
|
||||
"kind, merge_segments",
|
||||
[("dash", False), ("dash", True), ("hls", False), ("hls", True), ("ism", False), ("ism", True), ("url", False)],
|
||||
ids=["dash-post-merge", "dash-rolling", "hls-post-merge", "hls-rolling", "ism-post-merge", "ism-rolling", "url"],
|
||||
)
|
||||
def test_track_downloaded_fires_once_on_the_decrypted_file(
|
||||
server, tmp_path, monkeypatch, kind, merge_segments, encrypted
|
||||
):
|
||||
monkeypatch.setattr(config.directories, "temp", tmp_path)
|
||||
monkeypatch.setattr(config, "merge_segments", merge_segments)
|
||||
monkeypatch.setattr(track_module.Track, "get_key_id", lambda *a, **kw: None)
|
||||
no_decrypt(monkeypatch, mark=MARK)
|
||||
order: list[str] = []
|
||||
downloaded: list[tuple[object, bytes]] = []
|
||||
|
||||
def on_downloaded(track):
|
||||
order.append("downloaded")
|
||||
downloaded.append((track.drm, track.path.read_bytes()[: len(MARK)]))
|
||||
|
||||
def on_decrypted(track, drm, segment):
|
||||
order.append("decrypted")
|
||||
|
||||
events.subscribe(events.Types.TRACK_DOWNLOADED, on_downloaded)
|
||||
events.subscribe(events.Types.TRACK_DECRYPTED, on_decrypted)
|
||||
try:
|
||||
make_track(server, kind, encrypted).download(
|
||||
requests.Session(), partial(lambda *a, **kw: None), progress=partial(lambda **kw: None)
|
||||
)
|
||||
finally:
|
||||
events.unsubscribe(events.Types.TRACK_DOWNLOADED, on_downloaded)
|
||||
events.unsubscribe(events.Types.TRACK_DECRYPTED, on_decrypted)
|
||||
|
||||
assert order.count("downloaded") == 1 and order[-1] == "downloaded"
|
||||
drm, head = downloaded[0]
|
||||
assert not drm
|
||||
assert (head == MARK) == encrypted
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["dash", "hls", "ism", "url"])
|
||||
def test_a_failing_track_downloaded_hook_fails_the_track_and_removes_its_file(server, tmp_path, monkeypatch, kind):
|
||||
monkeypatch.setattr(config.directories, "temp", tmp_path)
|
||||
ctx = make_ctx(tmp_path, "unused")
|
||||
|
||||
def reject(track):
|
||||
raise ValueError("EXAMPLE rejected the track")
|
||||
|
||||
events.subscribe(events.Types.TRACK_DOWNLOADED, reject)
|
||||
try:
|
||||
with pytest.raises(ValueError, match="EXAMPLE rejected the track"):
|
||||
make_track(server, kind, encrypted=False).download(
|
||||
requests.Session(), partial(lambda *a, **kw: None), progress=ctx.progress
|
||||
)
|
||||
finally:
|
||||
events.unsubscribe(events.Types.TRACK_DOWNLOADED, reject)
|
||||
|
||||
assert DOWNLOAD_CANCELLED.is_set()
|
||||
assert ctx.statuses[-1] == "[red]FAILED"
|
||||
assert not list(tmp_path.glob("Video_*")) and not list(tmp_path.glob("Audio_*"))
|
||||
|
||||
@@ -324,7 +324,7 @@ def no_hook(monkeypatch):
|
||||
monkeypatch.setattr(verify, "DECRYPT_HOOK", None)
|
||||
|
||||
|
||||
def test_complete_track_emits_downloaded_then_decrypts_then_cleans_up(tmp_path, seen, no_hook):
|
||||
def test_complete_track_decrypts_then_cleans_up(tmp_path, seen, no_hook):
|
||||
ctx = make_ctx(tmp_path)
|
||||
ctx.save_dir.mkdir()
|
||||
ctx.save_path.write_bytes(b"merged")
|
||||
@@ -333,8 +333,8 @@ def test_complete_track_emits_downloaded_then_decrypts_then_cleans_up(tmp_path,
|
||||
|
||||
complete_track(track, ctx, drm) # type: ignore[arg-type]
|
||||
|
||||
assert drm.events_before == ["downloaded"]
|
||||
assert seen == [("downloaded", ctx.save_path), ("decrypted", drm)]
|
||||
assert drm.events_before == []
|
||||
assert seen == [("decrypted", drm)]
|
||||
assert ctx.save_path.read_bytes() == b"clear:merged"
|
||||
assert track.path == ctx.save_path and track.drm is None
|
||||
assert ctx.statuses == ["Decrypting", "Decrypted", "Downloaded"]
|
||||
@@ -349,14 +349,17 @@ def test_complete_track_after_segment_decryption_only_checks(tmp_path, seen, no_
|
||||
complete_track(SimpleNamespace(path=None, drm=[drm]), ctx, drm, decrypt=False) # type: ignore[arg-type]
|
||||
|
||||
assert ctx.save_path.read_bytes() == b"merged"
|
||||
assert [name for name, _ in seen] == ["downloaded", "decrypted"]
|
||||
assert [name for name, _ in seen] == ["decrypted"]
|
||||
|
||||
|
||||
def test_complete_track_without_drm_skips_the_decryption(tmp_path, seen):
|
||||
ctx = make_ctx(tmp_path)
|
||||
ctx.save_path.write_bytes(b"merged")
|
||||
|
||||
complete_track(SimpleNamespace(path=None, drm=None), ctx, None) # type: ignore[arg-type]
|
||||
track = SimpleNamespace(path=None, drm=None)
|
||||
|
||||
assert seen == [("downloaded", ctx.save_path)]
|
||||
complete_track(track, ctx, None) # type: ignore[arg-type]
|
||||
|
||||
assert seen == []
|
||||
assert track.path == ctx.save_path
|
||||
assert ctx.statuses == ["Downloaded"]
|
||||
|
||||
@@ -871,7 +871,6 @@ class HLS:
|
||||
decrypt_output(track, ctx, session_drm, decrypt=not segment_decrypter)
|
||||
progress(downloaded="Downloaded", completed=100, total=100)
|
||||
track.path = save_path
|
||||
events.emit(events.Types.TRACK_DOWNLOADED, track=track)
|
||||
return
|
||||
|
||||
progress(total=total_segments, completed=0, downloaded="Merging")
|
||||
@@ -1162,8 +1161,6 @@ class HLS:
|
||||
if session_drm:
|
||||
track.drm = None
|
||||
|
||||
events.emit(events.Types.TRACK_DOWNLOADED, track=track)
|
||||
|
||||
@staticmethod
|
||||
def discontinuity_starts(wanted_segments: list[Any]) -> list[float]:
|
||||
"""Start in seconds of each discontinuity block, counted as download_track numbers the blocks, then the end."""
|
||||
|
||||
@@ -253,9 +253,8 @@ def remove_segment_dir(save_dir: Path) -> None:
|
||||
|
||||
|
||||
def complete_track(track: AnyTrack, ctx: DownloadContext, drm: DRM_T | None, decrypt: bool = True) -> None:
|
||||
"""Hand the merged file to the track: TRACK_DOWNLOADED, then the decryption, then the segment directory cleanup."""
|
||||
"""Hand the merged file to the track, decrypt it, and remove the segment directory."""
|
||||
track.path = ctx.save_path
|
||||
events.emit(events.Types.TRACK_DOWNLOADED, track=track)
|
||||
|
||||
if drm:
|
||||
decrypt_output(track, ctx, drm, decrypt)
|
||||
|
||||
@@ -266,7 +266,8 @@ class TitleSource(metaclass=ABCMeta):
|
||||
|
||||
def on_track_downloaded(self, track: AnyTrack) -> None:
|
||||
"""
|
||||
Called when a Track has finished downloading.
|
||||
Called once when a Track has finished downloading, after unshackle decrypted its `drm`.
|
||||
In a licence-only run the track has no file.
|
||||
|
||||
Parameters:
|
||||
track: The downloaded Track object.
|
||||
|
||||
@@ -733,7 +733,7 @@ class Track:
|
||||
track's init data and stores it on the track, so a service need not declare `drm` itself.
|
||||
"""
|
||||
from unshackle.core.manifests import DASH, HLS, ISM
|
||||
from unshackle.core.manifests.segment_pipeline import license_drm
|
||||
from unshackle.core.manifests.segment_pipeline import license_drm, licensing
|
||||
from unshackle.core.tracks.audio import Audio
|
||||
from unshackle.core.tracks.subtitle import Subtitle
|
||||
from unshackle.core.tracks.video import Video
|
||||
@@ -889,7 +889,6 @@ class Track:
|
||||
media_path.unlink()
|
||||
|
||||
self.path = save_path
|
||||
events.emit(events.Types.TRACK_DOWNLOADED, track=self)
|
||||
|
||||
if drm:
|
||||
progress(downloaded="Decrypting", completed=0, total=None)
|
||||
@@ -926,6 +925,17 @@ class Track:
|
||||
DOWNLOAD_CANCELLED.set()
|
||||
progress(downloaded="[red]FAILED")
|
||||
raise
|
||||
|
||||
if DOWNLOAD_CANCELLED.is_set():
|
||||
return
|
||||
|
||||
if not DOWNLOAD_LICENCE_ONLY.is_set():
|
||||
assert self.path is not None
|
||||
if self.path.stat().st_size <= 3: # Empty UTF-8 BOM == 3 bytes
|
||||
raise OSError("Download failed, the downloaded file is empty.")
|
||||
|
||||
with licensing(ctx):
|
||||
events.emit(events.Types.TRACK_DOWNLOADED, track=self)
|
||||
except DownloadCancelled:
|
||||
abandon()
|
||||
progress(downloaded="[yellow]SKIPPED")
|
||||
@@ -935,16 +945,6 @@ class Track:
|
||||
abandon()
|
||||
raise
|
||||
|
||||
if DOWNLOAD_CANCELLED.is_set():
|
||||
return
|
||||
|
||||
if not DOWNLOAD_LICENCE_ONLY.is_set():
|
||||
assert self.path is not None
|
||||
if self.path.stat().st_size <= 3: # Empty UTF-8 BOM == 3 bytes
|
||||
raise OSError("Download failed, the downloaded file is empty.")
|
||||
|
||||
events.emit(events.Types.TRACK_DOWNLOADED, track=self)
|
||||
|
||||
def delete(self) -> None:
|
||||
if self.path:
|
||||
self.path.unlink()
|
||||
|
||||
Reference in New Issue
Block a user