mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-02 05:55:08 +00:00
feat(dl): add opt-in per-caller completion archive
This commit is contained in:
@@ -0,0 +1,131 @@
|
||||
"""Service-independent completion archive matching and persistence."""
|
||||
|
||||
import json
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import replace
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.download_archive import PARTIAL_MODES, ArchiveEntry, DownloadArchive, archive_entries
|
||||
from unshackle.core.titles import Episode
|
||||
from unshackle.core.tracks import Tracks, Video
|
||||
|
||||
|
||||
class EXAMPLE:
|
||||
pass
|
||||
|
||||
|
||||
def episode(height=720, **video_options):
|
||||
title = Episode(id_="example-episode-1", service=EXAMPLE, title="Example", season=1, number=1)
|
||||
title.tracks = Tracks(
|
||||
Video(
|
||||
id_="video",
|
||||
url="https://example.invalid/video",
|
||||
language="en",
|
||||
height=height,
|
||||
width=height * 16 // 9 if height else None,
|
||||
codec=Video.Codec.AVC,
|
||||
range_=Video.Range.SDR,
|
||||
**video_options,
|
||||
)
|
||||
)
|
||||
return title
|
||||
|
||||
|
||||
def test_exact_resolved_variant_not_requested_quality(tmp_path):
|
||||
archive = DownloadArchive(tmp_path)
|
||||
entries = archive_entries("EXAMPLE", episode(), {})
|
||||
assert not archive.contains(entries)
|
||||
archive.record(entries)
|
||||
assert DownloadArchive(tmp_path).contains(archive_entries("EXAMPLE", episode(), {}))
|
||||
for change in (
|
||||
{"quality": 1080},
|
||||
{"range": "DV"},
|
||||
{"codec": "H.265"},
|
||||
{"service": "EXAMPLE2"},
|
||||
{"title_id": "other-id"},
|
||||
):
|
||||
assert not archive.contains([replace(entries[0], **change)])
|
||||
# A lower explicit request is also a distinct variant.
|
||||
assert not archive.contains([replace(entries[0], quality=480)])
|
||||
|
||||
|
||||
def test_all_variants_must_be_recorded(tmp_path):
|
||||
archive = DownloadArchive(tmp_path)
|
||||
entries = archive_entries("EXAMPLE", episode(), {})
|
||||
higher = replace(entries[0], quality=1080)
|
||||
archive.record(entries)
|
||||
assert not archive.contains([*entries, higher])
|
||||
archive.record([higher])
|
||||
assert archive.contains([*entries, higher])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", PARTIAL_MODES)
|
||||
def test_partial_and_non_download_modes_never_check_or_record(mode):
|
||||
assert archive_entries("EXAMPLE", episode(), {mode: True}) == []
|
||||
|
||||
|
||||
def test_unknown_video_metadata_never_matches():
|
||||
assert archive_entries("EXAMPLE", episode(height=None), {}) == []
|
||||
title = episode()
|
||||
for attribute in ("codec", "range"):
|
||||
old = getattr(title.tracks.videos[0], attribute)
|
||||
setattr(title.tracks.videos[0], attribute, None)
|
||||
assert archive_entries("EXAMPLE", title, {}) == []
|
||||
setattr(title.tracks.videos[0], attribute, old)
|
||||
title.id = {"unsupported": "id"}
|
||||
assert archive_entries("EXAMPLE", title, {}) == []
|
||||
|
||||
|
||||
def test_scopes_and_typed_ids_do_not_cross(tmp_path):
|
||||
cli = DownloadArchive(tmp_path)
|
||||
first = DownloadArchive(tmp_path, "api-" + "a" * 64)
|
||||
second = DownloadArchive(tmp_path, "api-" + "b" * 64)
|
||||
entries = [ArchiveEntry("EXAMPLE", 1234, 720, "SDR", "H.264")]
|
||||
first.record(entries)
|
||||
assert first.contains(entries)
|
||||
assert not second.contains(entries)
|
||||
assert not cli.contains(entries)
|
||||
assert not first.contains([replace(entries[0], title_id="1234")])
|
||||
for scope in ("../cli", "api-unowned", "api-../../cli", "/tmp/receipt"):
|
||||
with pytest.raises(ValueError):
|
||||
DownloadArchive(tmp_path, scope)
|
||||
|
||||
|
||||
def test_history_and_file_deletion_have_no_effect(tmp_path):
|
||||
archive = DownloadArchive(tmp_path)
|
||||
entries = archive_entries("EXAMPLE", episode(), {})
|
||||
output = tmp_path / "output.mkv"
|
||||
history = tmp_path / "api_history.jsonl"
|
||||
output.touch()
|
||||
history.touch()
|
||||
archive.record(entries)
|
||||
output.unlink()
|
||||
history.unlink()
|
||||
assert DownloadArchive(tmp_path).contains(entries)
|
||||
text = archive.path.read_text()
|
||||
assert "output.mkv" not in text and "api_history" not in text
|
||||
|
||||
|
||||
def test_concurrent_append_and_truncated_receipt(tmp_path):
|
||||
archive = DownloadArchive(tmp_path)
|
||||
entries = [ArchiveEntry("EXAMPLE", f"episode-{n}", 720, "SDR", "H.264") for n in range(20)]
|
||||
archive.path.parent.mkdir(parents=True)
|
||||
archive.path.write_text('{"version":1,"service":"unfinished')
|
||||
with ThreadPoolExecutor(4) as pool:
|
||||
list(pool.map(lambda entry: DownloadArchive(tmp_path).record([entry]), entries))
|
||||
assert archive.contains(entries)
|
||||
archive.record(entries)
|
||||
valid = [json.loads(line) for line in archive.path.read_text().splitlines()[1:] if line]
|
||||
assert len(valid) == len(entries)
|
||||
|
||||
|
||||
def test_existing_reader_observes_another_writer(tmp_path):
|
||||
archive = DownloadArchive(tmp_path)
|
||||
first = ArchiveEntry("EXAMPLE", "episode-1", 720, "SDR", "H.264")
|
||||
second = replace(first, title_id="episode-2")
|
||||
archive.record([first])
|
||||
assert archive.contains([first])
|
||||
assert not archive.contains([second])
|
||||
DownloadArchive(tmp_path).record([second])
|
||||
assert archive.contains([first, second])
|
||||
@@ -0,0 +1,271 @@
|
||||
"""Exercise the real selection, publication and completion loop with an in-memory service."""
|
||||
|
||||
import inspect
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY
|
||||
from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS
|
||||
from unshackle.core.download_archive import DownloadArchive
|
||||
from unshackle.core.title_source import TitleSource
|
||||
from unshackle.core.titles import Episode, Series
|
||||
from unshackle.core.tracks import Audio, Tracks, Video
|
||||
|
||||
|
||||
class EXAMPLE(TitleSource):
|
||||
NO_SUBTITLES = True
|
||||
|
||||
def __init__(self, height=720, count=1):
|
||||
self.height = height
|
||||
self.count = count
|
||||
self.session = requests.Session()
|
||||
self.ctx = None
|
||||
|
||||
def authenticate(self, *args):
|
||||
pass
|
||||
|
||||
def get_titles(self):
|
||||
return Series(
|
||||
Episode(id_=f"example-episode-{n}", service=EXAMPLE, title="Example", season=1, number=n, language="en")
|
||||
for n in range(1, self.count + 1)
|
||||
)
|
||||
|
||||
def get_tracks(self, title):
|
||||
return Tracks(
|
||||
[
|
||||
Video(
|
||||
id_=f"v-{title.number}",
|
||||
url="https://example.invalid/video",
|
||||
language="en",
|
||||
codec=Video.Codec.AVC,
|
||||
range_=Video.Range.SDR,
|
||||
height=self.height,
|
||||
width=self.height * 16 // 9,
|
||||
bitrate=1_000_000,
|
||||
),
|
||||
Audio(
|
||||
id_=f"a-{title.number}",
|
||||
url="https://example.invalid/audio",
|
||||
language="en",
|
||||
codec=Audio.Codec.AAC,
|
||||
bitrate=128_000,
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
def get_chapters(self, title):
|
||||
return []
|
||||
|
||||
def close(self):
|
||||
self.session.close()
|
||||
|
||||
def __getattr__(self, name):
|
||||
if name.startswith(("on_", "get_")):
|
||||
return lambda *a, **k: None
|
||||
raise AttributeError(name)
|
||||
|
||||
|
||||
class Harness(dl):
|
||||
def __getattr__(self, name):
|
||||
return None
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def run(monkeypatch, tmp_path):
|
||||
import unshackle.commands.dl as module
|
||||
|
||||
monkeypatch.setattr(config.directories, "cache", tmp_path / "cache")
|
||||
monkeypatch.setattr(config.directories, "downloads", tmp_path / "downloads")
|
||||
monkeypatch.setattr(config.directories, "temp", tmp_path / "temp")
|
||||
monkeypatch.setattr(config, "subtitle", {})
|
||||
monkeypatch.setattr("unshackle.core.providers.search_metadata", lambda *a, **k: None)
|
||||
monkeypatch.setattr(
|
||||
module, "load_tracks", lambda service, title, **k: setattr(title, "tracks", service.get_tracks(title))
|
||||
)
|
||||
monkeypatch.setattr(module.tags, "tag_file", lambda *a, **k: None)
|
||||
monkeypatch.setattr(module.MediaInfo, "parse", lambda *a, **k: SimpleNamespace())
|
||||
monkeypatch.setattr(
|
||||
Episode,
|
||||
"get_filename",
|
||||
lambda self, *a, folder=False, **k: "Example" if folder else f"Example.S01E{self.number:02}",
|
||||
)
|
||||
monkeypatch.setattr(module, "dispatch", lambda *a, **k: None)
|
||||
downloads = []
|
||||
muxes = []
|
||||
|
||||
def download(tracks, *a, **k):
|
||||
for track in tracks:
|
||||
config.directories.temp.mkdir(parents=True, exist_ok=True)
|
||||
track.path = config.directories.temp / f"{track.id}.bin"
|
||||
track.path.write_bytes(b"test")
|
||||
downloads.append(track.id)
|
||||
|
||||
monkeypatch.setattr(module, "download_tracks_in_passes", download)
|
||||
|
||||
def mux(self, *a, **k):
|
||||
muxes.append(list(self.videos))
|
||||
path = config.directories.temp / f"mux-{len(muxes)}.mkv"
|
||||
path.write_bytes(b"test mux")
|
||||
return path, 0, []
|
||||
|
||||
monkeypatch.setattr(Tracks, "mux", mux)
|
||||
|
||||
def invoke(height=720, count=1, scope="cli", **flags):
|
||||
cmd = Harness.__new__(Harness)
|
||||
cmd.log = logging.getLogger("archive-test")
|
||||
cmd.service = "EXAMPLE"
|
||||
cmd.completed_files = []
|
||||
cmd.already_present = []
|
||||
cmd.skipped_titles = []
|
||||
cmd.skipped_subtitles = []
|
||||
cmd.archive_scope = scope
|
||||
cmd.archive_cache = None
|
||||
kwargs = {}
|
||||
for name, param in inspect.signature(dl.result).parameters.items():
|
||||
if name in DEFAULT_DOWNLOAD_PARAMS:
|
||||
kwargs[name] = DEFAULT_DOWNLOAD_PARAMS[name]
|
||||
elif name not in ("self", "service"):
|
||||
kwargs[name] = None if param.default is inspect.Parameter.empty else param.default
|
||||
kwargs.update(
|
||||
quality=[], vcodec=[], acodec=[], range_=[], wanted=[], cdm_only=None, downloads=1, skip_existing=True
|
||||
)
|
||||
kwargs.update(flags)
|
||||
try:
|
||||
cmd.result(EXAMPLE(height, count), **kwargs)
|
||||
finally:
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
DOWNLOAD_LICENCE_ONLY.clear()
|
||||
return cmd
|
||||
|
||||
invoke.downloads = downloads
|
||||
invoke.muxes = muxes
|
||||
return invoke
|
||||
|
||||
|
||||
def test_second_run_skips_and_force_downloads(run):
|
||||
first = run()
|
||||
assert len(first.completed_files) == 1 and not first.already_present
|
||||
count = len(run.downloads)
|
||||
progress = []
|
||||
second = run(progress_sink=progress.append)
|
||||
assert len(run.downloads) == count
|
||||
assert not second.completed_files and not second.skipped_titles
|
||||
assert second.already_present[0]["reason"] == "already_present"
|
||||
assert any(event.get("already_present") for event in progress)
|
||||
forced = run(force=True)
|
||||
assert len(run.downloads) > count
|
||||
assert forced.completed_files and not forced.already_present
|
||||
|
||||
|
||||
def test_new_best_quality_downloads_instead_of_skipping(run):
|
||||
run(height=720)
|
||||
count = len(run.downloads)
|
||||
assert run(height=1080).completed_files
|
||||
assert len(run.downloads) > count
|
||||
assert run(height=1080).already_present
|
||||
|
||||
|
||||
def test_failed_publication_does_not_record(monkeypatch, run):
|
||||
import unshackle.commands.dl as module
|
||||
|
||||
monkeypatch.setattr(module.os, "replace", lambda *a: (_ for _ in ()).throw(OSError("publication failed")))
|
||||
monkeypatch.setattr(module.shutil, "move", lambda *a: (_ for _ in ()).throw(OSError("publication failed")))
|
||||
with pytest.raises(OSError, match="publication failed"):
|
||||
run()
|
||||
assert not DownloadArchive(config.directories.cache).path.exists()
|
||||
|
||||
|
||||
def test_all_archived_titles_complete_successfully(run):
|
||||
run(count=2)
|
||||
result = run(count=2)
|
||||
assert len(result.already_present) == 2
|
||||
assert not result.completed_files and not result.skipped_titles
|
||||
|
||||
|
||||
def test_api_scopes_and_unowned_worker_do_not_use_cli_archive(run):
|
||||
run()
|
||||
assert run(scope="api-" + "a" * 64).completed_files
|
||||
assert run(scope="api-" + "b" * 64).completed_files
|
||||
assert run(scope="api-" + "a" * 64).already_present
|
||||
assert run(scope="api-unowned").completed_files
|
||||
|
||||
|
||||
def test_mux_failure_does_not_record(monkeypatch, run):
|
||||
monkeypatch.setattr(Tracks, "mux", lambda *a, **k: (Path("unused.mkv"), 2, ["mux failed"]))
|
||||
with pytest.raises(SystemExit) as exc:
|
||||
run()
|
||||
assert exc.value.code == 1
|
||||
assert not DownloadArchive(config.directories.cache).path.exists()
|
||||
|
||||
|
||||
def test_download_failure_does_not_record(monkeypatch, run):
|
||||
import unshackle.commands.dl as module
|
||||
|
||||
def fail(*a, **k):
|
||||
raise RuntimeError("test download failure")
|
||||
|
||||
monkeypatch.setattr(module, "download_tracks_in_passes", fail)
|
||||
result = run()
|
||||
assert result.download_error is not None
|
||||
assert not DownloadArchive(config.directories.cache).path.exists()
|
||||
|
||||
|
||||
def test_opt_out_does_not_read_or_write_archive(run):
|
||||
run()
|
||||
result = run(skip_existing=False)
|
||||
assert result.completed_files and not result.already_present
|
||||
|
||||
|
||||
def test_missing_requested_quality_still_fails(run):
|
||||
run(height=720)
|
||||
with pytest.raises(SystemExit) as exc:
|
||||
run(height=720, quality=[1080])
|
||||
assert exc.value.code == 1
|
||||
|
||||
|
||||
def test_partial_publication_of_multiple_variants_does_not_record(monkeypatch, run):
|
||||
import unshackle.commands.dl as module
|
||||
|
||||
get_tracks = EXAMPLE.get_tracks
|
||||
replace_file = module.os.replace
|
||||
|
||||
def variants(self, title):
|
||||
tracks = get_tracks(self, title)
|
||||
tracks.add(
|
||||
Video(
|
||||
id_="v-higher",
|
||||
url="https://example.invalid/video",
|
||||
language="en",
|
||||
codec=Video.Codec.AVC,
|
||||
range_=Video.Range.SDR,
|
||||
height=1080,
|
||||
width=1920,
|
||||
bitrate=2_000_000,
|
||||
)
|
||||
)
|
||||
return tracks
|
||||
|
||||
monkeypatch.setattr(EXAMPLE, "get_tracks", variants)
|
||||
published = []
|
||||
|
||||
def replace(source, target):
|
||||
if published:
|
||||
raise OSError("second variant failed")
|
||||
replace_file(source, target)
|
||||
published.append(target)
|
||||
|
||||
def fail_move(*a, **k):
|
||||
raise OSError("second variant failed")
|
||||
|
||||
monkeypatch.setattr(module.os, "replace", replace)
|
||||
monkeypatch.setattr(module.shutil, "move", fail_move)
|
||||
with pytest.raises(OSError, match="second variant failed"):
|
||||
run(quality=[720, 1080])
|
||||
assert len(published) == 1 and published[0].exists()
|
||||
assert not DownloadArchive(config.directories.cache).path.exists()
|
||||
Reference in New Issue
Block a user