"""The free-space preflight warns before the downloads when the temp volume cannot hold a title's tracks.""" from functools import partial from pathlib import Path from types import SimpleNamespace from typing import Any import m3u8 import pytest import requests from unshackle.commands import dl as dl_module from unshackle.commands.dl import DiskCheck from unshackle.core.config import config from unshackle.core.manifests import DASH, HLS, ISM from unshackle.core.tracks import Audio, Tracks from unshackle.core.tracks.track import Track from unshackle.core.utils.bitrate import manifest_seconds GB = 1_000_000_000 def mpd(periods: str, total: str = "PT1H") -> str: return ( f'{periods}' ) def period(attrs: str = "") -> str: return ( f"" '' '' '' "" '' '' '' "" "" ) def dash_tracks(manifest: str) -> Tracks: return DASH.from_text(manifest, "https://cdn.example/x.mpd").to_tracks("en") def new_check(tracks: Tracks | None = None) -> tuple[DiskCheck, list[str]]: """A check of ``tracks`` and the list of lines it warns with.""" lines: list[str] = [] return DiskCheck(tracks or Tracks(), lines.append), lines def low_disk_warning(tracks: Tracks) -> str | None: """The line a new check of ``tracks`` warns with, else None.""" lines = new_check(tracks)[1] return lines[0] if lines else None HLS_MASTER = '#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=16000000,RESOLUTION=3840x2160,CODECS="hvc1.2.4.L153"\nv.m3u8\n' def media_segments(count: int, byterange: str | None = None) -> list[Any]: """``count`` media segments of 6 s, each with ``byterange`` when one is given.""" entry = (f"#EXT-X-BYTERANGE:{byterange}\n" if byterange else "") + "#EXTINF:6.0,\nseg.m4s\n" return list(m3u8.loads("#EXTM3U\n#EXT-X-TARGETDURATION:6\n" + entry * count + "#EXT-X-ENDLIST\n").segments) def hls_audio() -> Audio: return Audio( url="https://cdn.example/a.m3u8", language="en", descriptor=Track.Descriptor.HLS, codec=Audio.Codec.AAC ) @pytest.fixture def free_space(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> list[int]: """Report the bytes in the returned list as the free space of the temp volume.""" monkeypatch.setattr(config.directories, "temp", tmp_path) free = [100 * GB] monkeypatch.setattr(dl_module.shutil, "disk_usage", lambda path: SimpleNamespace(free=free[0])) return free def test_a_temp_volume_too_small_for_twice_the_tracks_gets_one_warning_line( free_space: list[int], tmp_path: Path ) -> None: free_space[0] = 3_100_000_000 line = low_disk_warning(dash_tracks(mpd(period()))) assert line == f"Temp volume {tmp_path} has 3.1 GB free, the selected tracks need about 15.0 GB" def test_a_dash_track_counts_only_its_content_periods() -> None: manifest = mpd(period('id="ad" duration="PT10M"') + period('id="main" duration="PT50M"')) track = DASH.from_text(manifest, "https://cdn.example/x.mpd").to_tracks("en").videos[0] track.data["dash"]["filtered_period_ids"] = ["ad"] assert manifest_seconds(track) == 3000 def test_a_dash_period_of_unknown_length_takes_the_presentation_length() -> None: manifest = mpd(period('id="a"') + period('id="b"'), total="PT1H") assert manifest_seconds(dash_tracks(manifest).videos[0]) == 3600 def test_a_dash_manifest_with_no_length_gives_no_estimate() -> None: manifest = '' + period() + "" assert manifest_seconds(dash_tracks(manifest).videos[0]) is None def test_an_ism_track_takes_the_manifest_duration() -> None: manifest = ( '' '' '' '' "" ) video = ISM.from_text(manifest, url="https://cdn.example/x/manifest").to_tracks(language="en").videos[0] assert manifest_seconds(video) == 3600 def test_an_unreadable_temp_volume_gives_no_warning(free_space: list[int], monkeypatch: pytest.MonkeyPatch) -> None: def broken(path: Any) -> Any: raise PermissionError(13, "Access is denied") monkeypatch.setattr(dl_module.shutil, "disk_usage", broken) assert low_disk_warning(dash_tracks(mpd(period()))) is None def test_an_hls_track_warns_once_when_its_playlist_is_read(free_space: list[int], tmp_path: Path) -> None: free_space[0] = 3_100_000_000 video = HLS.from_text(HLS_MASTER, "https://cdn.example/x.m3u8").to_tracks("en").videos[0] check, lines = new_check(Tracks([video])) assert lines == [] check.add_segments(video, media_segments(600)) check.add_segments(video, media_segments(600)) assert lines == [f"Temp volume {tmp_path} has 3.1 GB free, the selected tracks need about 14.4 GB"] def test_a_mixed_title_counts_each_track_once_against_one_free_space_reading( free_space: list[int], tmp_path: Path ) -> None: free_space[0] = 20 * GB check, lines = new_check(dash_tracks(mpd(period()))) assert lines == [] free_space[0] = 0 check.add_segments(hls_audio(), media_segments(3, byterange="1000000000")) assert lines == [f"Temp volume {tmp_path} has 20.0 GB free, the selected tracks need about 21.0 GB"] def test_an_estimate_error_ends_the_check(free_space: list[int]) -> None: free_space[0] = 0 check, lines = new_check() check.add(lambda: 1 / 0) check.add_segments(hls_audio(), media_segments(1, byterange="1000000000")) assert lines == [] def test_the_hls_step_hands_over_its_wanted_segments_before_any_segment_downloads( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.setattr(config.directories, "temp", tmp_path) playlist = tmp_path / "media.m3u8" playlist.write_text( "#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXTINF:6.0,\nad.m4s\n#EXTINF:6.0,\nseg.m4s\n#EXT-X-ENDLIST\n", encoding="utf-8", ) track = hls_audio() track.from_file = playlist track.OnSegmentFilter = lambda segment: segment.uri == "ad.m4s" handed: list[tuple[Any, list[str]]] = [] class Stop(Exception): pass def on_segments(track: Any, segments: list[Any]) -> None: handed.append((track, [segment.uri for segment in segments])) raise Stop with pytest.raises(Stop): track.download( requests.Session(), partial(lambda *a, **k: None), progress=partial(lambda **_: None), on_segments=on_segments, ) assert handed == [(track, ["seg.m4s"])] assert not list(tmp_path.glob("*_segments/*"))