diff --git a/docs/dev/rest-api/endpoints.md b/docs/dev/rest-api/endpoints.md index 30755bc4..9a05e3ef 100644 --- a/docs/dev/rest-api/endpoints.md +++ b/docs/dev/rest-api/endpoints.md @@ -456,6 +456,8 @@ Make a download job. It requires `service` and `title_id`. Every other field is | `require_video` | string[] | `[]` | Video languages that must exist. The job fails if one is missing, even with `best_available`, or skips the title with `skip_missing`. | | `require_subs` | string[] | `[]` | Subtitle languages that must exist. The job fails if one is missing, or skips the title with `skip_missing`. `s_lang` still decides what to keep. | | `skip_missing` | boolean | `false` | Skip a title that misses a required language or track, and continue with the next title. The job's `skipped_titles` lists each skip. The job fails when it has one title or skips every title. | +| `skip_existing` | boolean | `false` | Skip variants recorded as completed for this API key, matched after selection by service, title ID, quality, range and codec. Does not verify files on disk or compare audio/subtitle choices. | +| `force` | boolean | `false` | Bypass the completion archive check for this job. Does not change overwrite behaviour. | | `forced_subs` | boolean | `false` | Include forced subtitles. | | `forced_subs_only` | boolean | `false` | Download forced subtitles and no other subtitle; implies `forced_subs`. Not valid with `no_subs`, `video_only`, `audio_only` or `chapters_only`. | | `forced_s_lang` | string[] | `[]` | Forced subtitle language(s); implies `forced_subs`. | @@ -593,6 +595,7 @@ Show download jobs, with optional filtering and sorting. "speed": "5.2 MB/s", "skipped_subtitles": [], "skipped_titles": [], + "already_present": [], "input_prompt": null, "notice": null, "qr": null @@ -865,6 +868,7 @@ Read the persisted history of jobs that reached a terminal state, newest first. "completed_time": "2026-07-03T12:08:00+00:00", "output_files": ["/downloads/Example.S01E01.mkv"], "skipped_titles": [], + "already_present": [], "error_message": null, "parameters": { "...": "redacted" } } @@ -878,6 +882,12 @@ Read the persisted history of jobs that reached a terminal state, newest first. | `200` | - | History returned. | | `400` | `INVALID_PARAMETERS` | Invalid `limit`. | +`already_present` lists completion-archive skips separately from newly produced `output_files` +and missing-track `skipped_titles`. Each entry contains `service`, `title_id`, `title`, +`reason: "already_present"`, and `variants` (objects with `quality`, `range`, `codec`). The same +field is present in job progress/details. A job with only archive matches completes successfully. +The archive is independent of history retention, isolated per API key, and has no inventory endpoint. + ### `DELETE /api/history/{job_id}` Remove a single persisted history entry. Returns **`204 No Content`** (empty body) on success. diff --git a/docs/guide/cli-reference.md b/docs/guide/cli-reference.md index 21fe7107..e97e997c 100644 --- a/docs/guide/cli-reference.md +++ b/docs/guide/cli-reference.md @@ -103,6 +103,8 @@ unshackle dl [OPTIONS] SERVICE [SERVICE ARGS...] | `--require-video` | - | Video langs that must exist. The title fails even with `--best-available`. Does not select tracks. | | `--require-subs` | - | Subtitle langs that must exist. Fails the title if one is missing. `--s-lang` still decides what to keep. | | `--skip-missing` | off | Skip a title that misses a required language or track, and continue with the next title. A run with one title, or a run that skips every title, still fails. | +| `--skip-existing` | off | Skip a resolved video variant recorded in the completion archive. Does not verify that files still exist. | +| `--force` | off | Bypass the completion archive check for this run; does not change overwrite behaviour. | | `-fs`, `--forced-subs` | off | Include forced subtitle tracks. | | `-fso`, `--forced-subs-only` | off | Keep only forced subtitle tracks; drop the other subtitles. Implies `-fs`. | | `-fsl`, `--forced-s-lang` | none | Language(s) wanted for forced subtitles; implies `-fs`. A `-` prefix excludes. | diff --git a/docs/reference/configuration/download.md b/docs/reference/configuration/download.md index d12e160e..e2fabc43 100644 --- a/docs/reference/configuration/download.md +++ b/docs/reference/configuration/download.md @@ -109,6 +109,39 @@ dl: request body, `workers: 0` for example, makes each job that uses it fail at submit with `400 INVALID_PARAMETERS`. +### Completion archive + +`dl.skip_existing: true` opts CLI downloads into an append-only completion archive under +`directories.cache/download-archive/cli.jsonl`. `--skip-existing` enables it for one run; +`--force` bypasses its check and still records successful full outputs when the archive is enabled. + +A receipt holds the canonical service tag, title ID (string or integer), and the resolved video +quality, range and codec. Selection runs normally before checking the archive: a best-available +720p result can match 720p again, but a later 1080p selection downloads. A different quality, +range or codec does not match. All selected variants must have receipts to skip the title. +A higher resolution does not satisfy an explicitly lower request. + +Receipts are written only after a full movie/episode has been muxed and its output files have +been published. Samples, `--skip-dl`, `--no-mux`, track-only and omitted-track modes do not check +or update the archive. Unknown video metadata, non-string/non-integer IDs, music, stereoscopic +and generated/hybrid video outputs also fall back to normal downloading. So does +`--skip-subtitle-errors`, which can publish incomplete output. `--include-sample` still records +the complete output, not the sample. + +This is a completion log, not a media inventory: deleting or moving an output does not remove +its receipt. It does not compare audio or subtitle choices or inspect existing files. Use +`--force` when an archived variant needs to be downloaded again. It does not import job history, +and history trimming or deletion does not affect it. Clearing the cache removes these receipts. +Concurrent writers lock only local archive I/O; simultaneous downloads may both proceed. + +API jobs use separate files named `api-.jsonl` in the same directory. +They never consult the CLI archive or another caller's archive. Enable this with the request's +`skip_existing: true`, a `serve.skip_existing` default, or a `services..dl.skip_existing` +default. API callers cannot choose a scope or archive path. An ownerless internal job does not +use the archive. Remote service selection uses the local job's completion archive, not a remote +server's library. Skipped receipts are reported as `already_present` and complete successfully; +this does not change the separate missing-track `skipped_titles` behaviour. + ## `continue_downloads` - **Type:** `bool`  ยท  **Default:** `false` diff --git a/tests/core/test_download_archive.py b/tests/core/test_download_archive.py new file mode 100644 index 00000000..ef880cf2 --- /dev/null +++ b/tests/core/test_download_archive.py @@ -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]) diff --git a/tests/core/test_download_archive_loop.py b/tests/core/test_download_archive_loop.py new file mode 100644 index 00000000..cf30027c --- /dev/null +++ b/tests/core/test_download_archive_loop.py @@ -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() diff --git a/tests/remote/unit/test_download_archive_api.py b/tests/remote/unit/test_download_archive_api.py new file mode 100644 index 00000000..94e4c531 --- /dev/null +++ b/tests/remote/unit/test_download_archive_api.py @@ -0,0 +1,156 @@ +"""Completion reporting survives the worker boundary and is scoped by the server.""" + +import asyncio +import hashlib +import json +from pathlib import Path + +import click +import pytest + +from unshackle.core.api import download_manager as dm +from unshackle.core.api import download_worker +from unshackle.core.api.job_channel import WorkerResult +from unshackle.core.config import config +from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS + +PRESENT = [ + { + "service": "EXAMPLE", + "title_id": "example-1", + "reason": "already_present", + "variants": [{"quality": 720, "range": "SDR", "codec": "H.264"}], + } +] + + +@pytest.mark.parametrize("fails", [False, True], ids=["success", "later-failure"]) +def test_worker_takes_the_payload_scope_and_reports_already_present(monkeypatch, tmp_path, fails): + seen = {} + + def perform(*args, **kwargs): + seen.update(kwargs) + kwargs["progress_callback"]({"already_present": PRESENT}) + if fails: + raise RuntimeError("later title failed") + return [] + + monkeypatch.setattr(download_worker, "perform_download", perform) + monkeypatch.setattr(download_worker, "relay_prompts", lambda *a: None) + payload = tmp_path / "payload.json" + progress = tmp_path / "progress.json" + scope = "api-" + "a" * 64 + payload.write_text( + json.dumps( + { + "job_id": "test", + "service": "EXAMPLE", + "title_id": "example-1", + "archive_scope": scope, + "parameters": {"archive_scope": "cli"}, + } + ) + ) + assert download_worker.main(["worker", str(payload), str(tmp_path / "result.json"), str(progress)]) == int(fails) + assert seen["archive_scope"] == scope + assert json.loads(progress.read_text())["already_present"] == PRESENT + + +def test_api_options_default_off(): + assert DEFAULT_DOWNLOAD_PARAMS["skip_existing"] is False + assert DEFAULT_DOWNLOAD_PARAMS["force"] is False + + +def test_manager_uses_owner_scope_and_keeps_already_present_in_history(monkeypatch, tmp_path): + payloads = [] + + class FakeWorker: + returncode = 0 + + async def wait(self, timeout): + return True + + def read_progress(self): + return {"already_present": PRESENT} + + def output(self): + return "", "" + + async def result(self): + return WorkerResult(status="success") + + async def close(self): + pass + + async def spawn(payload): + payloads.append(payload) + return FakeWorker() + + monkeypatch.setattr(dm.WorkerProcess, "spawn", spawn) + history = tmp_path / "api_history.jsonl" + monkeypatch.setattr(dm, "history_path", lambda: history) + manager = dm.DownloadQueueManager() + job = manager.create_job("EXAMPLE", "example-1", owner_key="test-owner", archive_scope="cli") + assert asyncio.run(manager.run_download_async(job)) == [] + assert [p.archive_scope for p in payloads] == ["api-" + hashlib.sha256(b"test-owner").hexdigest()] + assert job.to_dict()["already_present"] == PRESENT + assert job.skipped_titles == [] + job.status = dm.JobStatus.COMPLETED + dm.record_job_history(job) + assert json.loads(history.read_text())["already_present"] == PRESENT + + +def test_ownerless_job_has_no_archive_scope(monkeypatch): + payloads = [] + + async def spawn(payload): + payloads.append(payload) + raise RuntimeError("stop") + + monkeypatch.setattr(dm.WorkerProcess, "spawn", spawn) + manager = dm.DownloadQueueManager() + with pytest.raises(RuntimeError, match="stop"): + asyncio.run(manager.run_download_async(manager.create_job("EXAMPLE", "example-1"))) + assert payloads[0].archive_scope == "api-unowned" + + +def test_request_cannot_choose_archive_scope_or_credential_namespace(monkeypatch, tmp_path): + import unshackle.commands.dl as dl_module + from unshackle.core.api import handlers + from unshackle.core.services import Services + + seen = {} + + class Captured(Exception): + pass + + class FakeDl: + cli = dl_module.dl.cli + + def __init__(self, ctx, **kwargs): + pass + + def result(self, **kwargs): + seen.update(scope=self.archive_scope, cache=self.archive_cache) + raise Captured + + class FakeService: + cli = click.Command("svc", callback=lambda title: object()) + + monkeypatch.setattr(dl_module, "dl", FakeDl) + monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path)) + monkeypatch.setattr(Services, "load", staticmethod(lambda s: FakeService)) + monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None) + monkeypatch.setattr(config.directories, "cache", tmp_path / "cache") + monkeypatch.setattr(config, "credentials", {}) + scope = "api-" + "c" * 64 + with pytest.raises(Captured): + dm.perform_download( + "test", + "EXAMPLE", + "example-1", + {"archive_scope": "cli", "archive_cache": "/not-allowed", "credential": "test-user:test-password"}, + archive_scope=scope, + ) + assert seen == {"scope": scope, "cache": tmp_path / "cache"} + assert Path(config.directories.cache) != tmp_path / "cache" diff --git a/tests/remote/unit/test_process_exit.py b/tests/remote/unit/test_process_exit.py index 166ec9aa..69219073 100644 --- a/tests/remote/unit/test_process_exit.py +++ b/tests/remote/unit/test_process_exit.py @@ -542,7 +542,7 @@ import sys, time from unshackle.core import process_exit from unshackle.core.api import download_worker -def perform(*args, progress_callback): +def perform(*args, progress_callback, **kwargs): process_exit.ends.add(lambda: time.sleep(0.3)) progress_callback({"title": "EXAMPLE"}) print("ready", flush=True) diff --git a/unshackle/commands/dl.py b/unshackle/commands/dl.py index 5773f917..71f61b2e 100644 --- a/unshackle/commands/dl.py +++ b/unshackle/commands/dl.py @@ -737,6 +737,18 @@ class dl: default=None, help="Create separate output files per audio codec instead of merging all audio.", ) + @click.option( + "--skip-existing", + is_flag=True, + default=False, + help="Skip resolved variants recorded in the completion archive (does not check files on disk).", + ) + @click.option( + "--force", + is_flag=True, + default=False, + help="Bypass the completion archive check for this run.", + ) @click.option( "--merge-video", "merge_video", @@ -1222,6 +1234,9 @@ class dl: # report which weren't available without parsing the console output. See SkippedSubtitle. self.skipped_subtitles: list[SkippedSubtitle] = [] self.skipped_titles: list[SkippedTitle] = [] + self.already_present: list[dict[str, Any]] = [] + self.archive_scope = "cli" + self.archive_cache: Path | None = None # result() catches a download-worker failure, reports it, and returns rather than # re-raising (so the CLI still exits cleanly). Keep it so an embedding caller (the API # worker) can tell the title did not complete instead of reading it as a success. @@ -1565,6 +1580,8 @@ class dl: no_postscript: bool = False, all_drm: bool = False, generate_dv: bool = False, + skip_existing: bool = False, + force: bool = False, *_: Any, **__: Any, ) -> RunOutcome: @@ -1891,6 +1908,35 @@ class dl: # replaces -w; a base SxE key selects every part of a split episode wanted = [f"{season}x{number}" for season, number in latest_keys] + from unshackle.core.download_archive import DownloadArchive, archive_entries + + archive = ( + DownloadArchive(self.archive_cache or config.directories.cache, self.archive_scope) + if skip_existing and self.archive_scope != "api-unowned" + else None + ) + archive_options = { + "sample": sample, + "skip_dl": skip_dl, + "no_mux": no_mux, + "video_only": video_only, + "audio_only": audio_only, + "subs_only": subs_only, + "chapters_only": chapters_only, + "no_video": no_video, + "no_audio": no_audio, + "no_subs": no_subs, + "no_chapters": no_chapters, + "no_attachments": no_attachments, + "audio_description_only": audio_description_only, + "forced_subs_only": forced_subs_only, + "cdm_only": cdm_only, + "list_": list_, + "list_titles": list_titles, + "skip_subtitle_errors": skip_subtitle_errors, + "generate_dv": generate_dv, + } + selection = TrackSelection( quality=quality, vcodec=vcodec, @@ -2149,6 +2195,26 @@ class dl: continue range_ = outcome.ranges + receipt_entries = archive_entries(self.service, title, archive_options) if archive else [] + if archive and receipt_entries and not force and archive.contains(receipt_entries): + self.already_present.append( + { + "service": self.service, + "title_id": title.id, + "title": str(title), + "reason": "already_present", + "variants": [ + {"quality": entry.quality, "range": entry.range, "codec": entry.codec} + for entry in receipt_entries + ], + } + ) + self.log.info(f"Already present in completion archive: {title}") + if progress_sink: + progress_sink({"already_present": list(self.already_present)}) + settle_post_script_group(title) + continue + selected_tracks, tracks_progress_callables = title.tracks.tree(add_progress=True) log_event( @@ -2666,6 +2732,9 @@ class dl: post_script_folders.append(final_path.parent) settle_post_script_group(title) + if archive and receipt_entries and not skip_mux and outputs: + archive.record(receipt_entries) + title_dl_time = time_elapsed_since(dl_start_time) downloaded_label = "Track" if isinstance(title, Song) else "Title" console.print( diff --git a/unshackle/core/api/download_manager.py b/unshackle/core/api/download_manager.py index 2b69d885..82805ba7 100644 --- a/unshackle/core/api/download_manager.py +++ b/unshackle/core/api/download_manager.py @@ -218,6 +218,7 @@ HISTORY_FIELDS = ( "completed_time", "output_files", "skipped_titles", + "already_present", "parameters", "error_message", ) @@ -354,6 +355,8 @@ def perform_download( title_id: str, params: dict[str, Any], progress_callback: ProgressSink | None = None, + *, + archive_scope: str = "api-unowned", ) -> list[str]: """Do the synchronous download work for a job. @@ -379,6 +382,7 @@ def perform_download( # A service caches tokens under cache//, keyed by service name only, so two jobs on # one service with different credentials would share a cache. When a per-job credential is set, # namespace the cache dir by a hash of it so the sessions can't cross. + archive_cache = config.directories.cache job_credential = params.get("credential") if job_credential: import hashlib @@ -401,6 +405,8 @@ def perform_download( launch(ctx, {"client_argv": f"{relay_label(params)} download job {job_id}"}) providers = initialize_proxy_providers(quiet=True) if params.get("server_proxy") is True else [] dl_instance = dl(ctx=ctx, proxy_providers=providers, **ctx.params) + dl_instance.archive_scope = archive_scope + dl_instance.archive_cache = archive_cache # Per-request credential ("user:pass"); feed it into the map get_credentials() reads so a # client can authenticate without anything being persisted to disk. Without a profile, # get_credentials() falls back to "default", so store it there too rather than dropping it @@ -809,8 +815,16 @@ class DownloadQueueManager: async def run_download_async(self, job: DownloadJob) -> list[str]: """Invoke a job worker subprocess to do the download.""" + owner = getattr(job, "owner_key", None) worker = await WorkerProcess.spawn( - JobPayload(job.job_id, job.service, job.title_id, job.parameters, self.worker_speed_limit()) + JobPayload( + job.job_id, + job.service, + job.title_id, + job.parameters, + self.worker_speed_limit(), + archive_scope=f"api-{hashlib.sha256(owner.encode()).hexdigest()}" if owner else "api-unowned", + ) ) self._workers[job.job_id] = worker diff --git a/unshackle/core/api/download_worker.py b/unshackle/core/api/download_worker.py index 1fd26a6b..7db44b5e 100644 --- a/unshackle/core/api/download_worker.py +++ b/unshackle/core/api/download_worker.py @@ -105,7 +105,12 @@ def main(argv: list[str]) -> int: remote = payload.parameters.get("remote") with process_exit.unwinding(STOP_DEADLINE, linger=False) if remote else nullcontext(): output_files = perform_download( - payload.job_id, payload.service, payload.title_id, payload.parameters, progress_callback=progress + payload.job_id, + payload.service, + payload.title_id, + payload.parameters, + progress_callback=progress, + archive_scope=payload.archive_scope, ) result = WorkerResult(status="success", output_files=output_files) diff --git a/unshackle/core/api/job_channel.py b/unshackle/core/api/job_channel.py index e55c98b2..99b2ff71 100644 --- a/unshackle/core/api/job_channel.py +++ b/unshackle/core/api/job_channel.py @@ -52,6 +52,7 @@ class JobProgress: qr: str | None = None skipped_subtitles: list[dict[str, Any]] = field(default_factory=list) skipped_titles: list[dict[str, Any]] = field(default_factory=list) + already_present: list[dict[str, Any]] = field(default_factory=list) output_files: list[str] = field(default_factory=list) @@ -152,6 +153,7 @@ class JobPayload: title_id: str parameters: dict[str, Any] = field(default_factory=dict) speed_limit: float | None = None + archive_scope: str = "api-unowned" @classmethod def read(cls, path: Path) -> JobPayload: diff --git a/unshackle/core/api/routes.py b/unshackle/core/api/routes.py index a120c3f1..b47337ff 100644 --- a/unshackle/core/api/routes.py +++ b/unshackle/core/api/routes.py @@ -1148,6 +1148,12 @@ async def download(request: web.Request) -> web.Response: split_audio: type: boolean description: Make separate output files per audio codec instead of merging all audio (default - null) + skip_existing: + type: boolean + description: Skip resolved variants in the caller completion archive without checking files on disk (default - false) + force: + type: boolean + description: Bypass the completion archive check without changing overwrite behaviour (default - false) skip_dl: type: boolean description: Skip downloading, only retrieve decryption keys (default - false) diff --git a/unshackle/core/dl_options.py b/unshackle/core/dl_options.py index 0d16e7fe..e62d4222 100644 --- a/unshackle/core/dl_options.py +++ b/unshackle/core/dl_options.py @@ -52,6 +52,8 @@ DL_OPTIONS: dict[str, ApiOption | None] = { "require_video": ApiOption([]), "require_subs": ApiOption([]), "skip_missing": ApiOption(False), + "skip_existing": ApiOption(False), + "force": ApiOption(False), "forced_subs": ApiOption(False, remote="flag"), "forced_subs_only": ApiOption(False), "forced_s_lang": ApiOption([]), diff --git a/unshackle/core/download_archive.py b/unshackle/core/download_archive.py new file mode 100644 index 00000000..b0c6a141 --- /dev/null +++ b/unshackle/core/download_archive.py @@ -0,0 +1,149 @@ +"""Opt-in completion receipts, not an inventory of files currently on disk.""" + +from __future__ import annotations + +import json +import os +import re +from collections.abc import Iterable +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Any + +from filelock import FileLock + +from unshackle.core.tracks import Video +from unshackle.core.utilities import standard_resolution + +PARTIAL_MODES = ( + "sample", + "skip_dl", + "no_mux", + "video_only", + "audio_only", + "subs_only", + "chapters_only", + "no_video", + "no_audio", + "no_subs", + "no_chapters", + "no_attachments", + "audio_description_only", + "forced_subs_only", + "cdm_only", + "list_", + "list_titles", + "skip_subtitle_errors", + "generate_dv", +) + + +@dataclass(frozen=True) +class ArchiveEntry: + service: str + title_id: str | int + quality: int + range: str + codec: str + + @classmethod + def from_video(cls, service: str, title_id: Any, video: Video) -> ArchiveEntry | None: + """Use the resolved video, never the requested quality or a filename.""" + quality = standard_resolution(video.width, video.height) + if ( + type(title_id) not in (str, int) + or not title_id + or not quality + or not isinstance(video.codec, Video.Codec) + or not isinstance(video.range, Video.Range) + or video.range == Video.Range.HYBRID + or video.hybrid_ingredient + or video.finished_hybrid + or video.stereo + ): + return None + return cls(service, title_id, quality, video.range.value, video.codec.value) + + def token(self) -> str: + return json.dumps(asdict(self), sort_keys=True, ensure_ascii=True, separators=(",", ":")) + + +def archive_entries(service: str, title: Any, options: dict[str, Any]) -> list[ArchiveEntry]: + """Only fully known ordinary movie/episode variants may use completion receipts.""" + from unshackle.core.titles import Episode, Movie + + if not isinstance(title, (Episode, Movie)) or any(options.get(mode) for mode in PARTIAL_MODES): + return [] + entries = [ArchiveEntry.from_video(service, title.id, video) for video in title.tracks.videos] + if not entries or any(entry is None for entry in entries): + return [] + return list(dict.fromkeys(entry for entry in entries if entry is not None)) + + +class DownloadArchive: + def __init__(self, cache: Path, scope: str = "cli") -> None: + if scope != "cli" and not re.fullmatch(r"api-[0-9a-f]{64}", scope): + raise ValueError("Invalid download archive scope") + self.path = cache / "download-archive" / f"{scope}.jsonl" + self.lock = FileLock(str(self.path) + ".lock", timeout=30) + self._snapshot: tuple[int, int, int] | None = None + self._records: set[str] = set() + + def _read(self) -> set[str]: + if not self.path.exists(): + return set() + stat = self.path.stat() + snapshot = (stat.st_ino, stat.st_size, stat.st_mtime_ns) + if snapshot == self._snapshot: + return self._records + records = set() + with self.path.open(encoding="utf-8") as handle: + for line in handle: + try: + row = json.loads(line) + if not isinstance(row, dict) or row.pop("version", None) != 1: + continue + entry = ArchiveEntry(**row) + if ( + type(entry.title_id) not in (str, int) + or not entry.title_id + or not isinstance(entry.service, str) + or type(entry.quality) is not int + or entry.quality <= 0 + or entry.range not in {r.value for r in Video.Range if r != Video.Range.HYBRID} + or entry.codec not in {c.value for c in Video.Codec} + ): + continue + records.add(entry.token()) + except (ValueError, TypeError): + continue + self._snapshot = snapshot + self._records = records + return records + + def contains(self, entries: Iterable[ArchiveEntry]) -> bool: + requested = {entry.token() for entry in entries} + if not requested or not self.path.exists(): + return False + with self.lock: + return requested <= self._read() + + def record(self, entries: Iterable[ArchiveEntry]) -> None: + entries = list(entries) + if not entries: + return + self.path.parent.mkdir(parents=True, exist_ok=True) + with self.lock: + recorded = self._read() + pending = [entry for entry in entries if entry.token() not in recorded] + if not pending: + return + with self.path.open("a", encoding="utf-8") as handle: + handle.write("\n") + for entry in pending: + handle.write(json.dumps({"version": 1, **asdict(entry)}, ensure_ascii=True) + "\n") + handle.flush() + os.fsync(handle.fileno()) + stat = os.fstat(handle.fileno()) + self._records = recorded | {entry.token() for entry in pending} + self._snapshot = (stat.st_ino, stat.st_size, stat.st_mtime_ns)