feat(dl): add --max-downloads to stop a run after N downloaded titles

This commit is contained in:
imSp4rky
2026-12-04 12:33:18 -07:00
parent 516ae82f4d
commit 8e850d168e
10 changed files with 119 additions and 2 deletions
+1
View File
@@ -453,6 +453,7 @@ Make a download job. It requires `service` and `title_id`. Every other field is
| `wanted` | string / string[] | `[]` | Episode/season selectors, as a list or as one comma-separated string. Accepts the part form, `"S01E01.2"`, and the air-date form, `"2026-08-11"` or `"2026-08-01:2026-08-31"`. For a music release, a selector is a number of the track list, `"1-5"` or `"1,3,7"`, or `"{disc}x{track}"` such as `"2x3"`. | | `wanted` | string / string[] | `[]` | Episode/season selectors, as a list or as one comma-separated string. Accepts the part form, `"S01E01.2"`, and the air-date form, `"2026-08-11"` or `"2026-08-01:2026-08-31"`. For a music release, a selector is a number of the track list, `"1-5"` or `"1,3,7"`, or `"{disc}x{track}"` such as `"2x3"`. |
| `latest_episode` | boolean | `false` | Only the newest episode. | | `latest_episode` | boolean | `false` | Only the newest episode. |
| `latest_episodes` | integer | `null` | Only the N newest episodes. A positive integer. When set, it overrides `latest_episode`. | | `latest_episodes` | integer | `null` | Only the N newest episodes. A positive integer. When set, it overrides `latest_episode`. |
| `max_downloads` | integer | `null` | Stop the job after N titles have downloaded. A positive integer. A title in `skipped_titles` or `already_present` does not count. |
| `lang` / `v_lang` / `a_lang` / `s_lang` | string[] | `["orig"]` / `[]` / `[]` / `["all"]` | Language filters. A missing `s_lang` language gives a warning and the job continues. | | `lang` / `v_lang` / `a_lang` / `s_lang` | string[] | `["orig"]` / `[]` / `[]` / `["all"]` | Language filters. A missing `s_lang` language gives a warning and the job continues. |
| `require_audio` | string[] | `[]` | Audio languages that must exist. The job fails if one is missing, even with `best_available`, or skips the title with `skip_missing`. | | `require_audio` | string[] | `[]` | Audio languages that must exist. The job fails if one is missing, even with `best_available`, or skips the title with `skip_missing`. |
| `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_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`. |
+1
View File
@@ -128,6 +128,7 @@ unshackle honours the special language tokens `orig`, `all`, and `best` everywhe
| `--select-titles` | Interactively select what to download: episodes of a series, or films when a title has more than one. **Cannot combine with `-w`.** | | `--select-titles` | Interactively select what to download: episodes of a series, or films when a title has more than one. **Cannot combine with `-w`.** |
| `--latest-episode` | Download only the single most recent episode. | | `--latest-episode` | Download only the single most recent episode. |
| `--latest-episodes N` | Download only the N most recent episodes. | | `--latest-episodes N` | Download only the N most recent episodes. |
| `--max-downloads N` | Stop after N titles have downloaded. A skipped title, or a title already in the completion archive, does not count. |
| `--list-titles` | List titles only; do not download. | | `--list-titles` | List titles only; do not download. |
### Track-type inclusion / exclusion ### Track-type inclusion / exclusion
+13
View File
@@ -761,6 +761,7 @@ when you want a part on its own.
| `--select-titles` | Interactively pick episodes of a series, or films when a title has more than one. **Cannot combine with `-w`.** | | `--select-titles` | Interactively pick episodes of a series, or films when a title has more than one. **Cannot combine with `-w`.** |
| `--latest-episode` | Download only the single most recent episode. | | `--latest-episode` | Download only the single most recent episode. |
| `--latest-episodes N` | Download only the N most recent episodes. The newest episodes can come from more than one season. A [split episode](#split-episodes) counts as one episode, and all its parts download. | | `--latest-episodes N` | Download only the N most recent episodes. The newest episodes can come from more than one season. A [split episode](#split-episodes) counts as one episode, and all its parts download. |
| `--max-downloads N` | Stop after N titles have downloaded. A skipped title, or a title already in the completion archive, does not count. With `--skip-dl` or `--no-mux`, a title counts when its run completes. Each part of a [split episode](#split-episodes) counts as one title. unshackle does not open the titles after the limit. |
| `--list-titles` | List every title the service returned, then stop. `-w`, `--latest-episode` and `--latest-episodes` are not applied to this listing. | | `--list-titles` | List every title the service returned, then stop. `-w`, `--latest-episode` and `--latest-episodes` are not applied to this listing. |
When `--latest-episode` or `--latest-episodes` is set, `-w` has no effect. When `--latest-episode` or `--latest-episodes` is set, `-w` has no effect.
@@ -773,6 +774,17 @@ unshackle dl --latest-episode EXAMPLE 81234567
unshackle dl --latest-episodes 3 EXAMPLE 81234567 unshackle dl --latest-episodes 3 EXAMPLE 81234567
``` ```
`--latest-episodes` takes the newest episodes. `--max-downloads` takes the first episodes in order.
With `--skip-existing`, it takes the next episodes that the
[completion archive](../reference/configuration/download.md#completion-archive) does not have, so
the same command can run each day:
```shell title="Grab the next two episodes not downloaded yet"
unshackle dl --skip-existing --max-downloads 2 -w S01 EXAMPLE 81234567
```
A season that the limit stops before its last episode gets no `season` post-script event.
## Including and excluding track types ## Including and excluding track types
You can restrict a download to certain track categories, either positively (only these) You can restrict a download to certain track categories, either positively (only these)
@@ -1280,6 +1292,7 @@ authoritative list.
| `--select-titles` | | Interactively pick episodes or films. | | `--select-titles` | | Interactively pick episodes or films. |
| `--latest-episode` | | Only the newest episode. | | `--latest-episode` | | Only the newest episode. |
| `--latest-episodes N` | | Only the N newest episodes. | | `--latest-episodes N` | | Only the N newest episodes. |
| `--max-downloads N` | | Stop after N downloaded titles. |
| `--video-only` / `--audio-only` / `--subs-only` | `-V` / `-A` / `-S` | Restrict track types. | | `--video-only` / `--audio-only` / `--subs-only` | `-V` / `-A` / `-S` | Restrict track types. |
| `--no-video` / `--no-audio` / `--no-subs` / `--no-chapters` / `--no-attachments` | `-nv` / `-na` / `-ns` / `-nc` / `-nt` | Skip track types. | | `--no-video` / `--no-audio` / `--no-subs` / `--no-chapters` / `--no-attachments` | `-nv` / `-na` / `-ns` / `-nc` / `-nt` | Skip track types. |
| `--worst` | | Lowest-bitrate video at each requested resolution, or at the lowest resolution if none is set. | | `--worst` | | Lowest-bitrate video at each requested resolution, or at the lowest resolution if none is set. |
+4
View File
@@ -159,6 +159,10 @@ 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 `--skip-subtitle-errors`, which can publish incomplete output. `--include-sample` still records
the complete output, not the sample. the complete output, not the sample.
With `--max-downloads N`, a run downloads the next N titles that have no receipt. A title
that the archive skips does not count. A mode above that does not update the archive writes no
receipt, so each run downloads the same first N titles again.
This is a completion log, not a media inventory: deleting or moving an output does not remove 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 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, `--force` when an archived variant needs to be downloaded again. It does not import job history,
+73 -1
View File
@@ -92,7 +92,7 @@ def run(monkeypatch, tmp_path):
module, "load_tracks", lambda service, title, **k: setattr(title, "tracks", service.get_tracks(title)) 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.tags, "tag_file", lambda *a, **k: None)
monkeypatch.setattr(module.MediaInfo, "parse", lambda *a, **k: SimpleNamespace()) monkeypatch.setattr(module.MediaInfo, "parse", lambda *a, **k: SimpleNamespace(general_tracks=[]))
monkeypatch.setattr( monkeypatch.setattr(
Episode, Episode,
"get_filename", "get_filename",
@@ -290,3 +290,75 @@ def test_wall_clock_step_back_prints_no_negative_elapsed_time(run, monkeypatch):
elapsed = re.findall(r"(?:finished|downloaded|titles) in (-?[\dhms]+)", captured.get()) elapsed = re.findall(r"(?:finished|downloaded|titles) in (-?[\dhms]+)", captured.get())
assert len(elapsed) == 3 assert len(elapsed) == 3
assert all(re.fullmatch(r"0m\d+s", value) for value in elapsed), elapsed assert all(re.fullmatch(r"0m\d+s", value) for value in elapsed), elapsed
@pytest.fixture
def get_tracks_calls(monkeypatch):
calls = []
get_tracks = EXAMPLE.get_tracks
def counted(self, title):
calls.append(title.number)
return get_tracks(self, title)
monkeypatch.setattr(EXAMPLE, "get_tracks", counted)
return calls
def test_max_downloads_counts_only_downloaded_titles_and_leaves_the_rest_untouched(run, get_tracks_calls):
run(count=1)
get_tracks_calls.clear()
result = run(count=4, max_downloads=2)
assert get_tracks_calls == [1, 2, 3]
assert [path.stem for path in result.completed_files] == ["Example.S01E02", "Example.S01E03"]
assert [entry["title"] for entry in result.already_present] == ["Example S01E01"]
assert not result.skipped_titles
get_tracks_calls.clear()
following = run(count=4, max_downloads=2)
assert get_tracks_calls == [1, 2, 3, 4]
assert [path.stem for path in following.completed_files] == ["Example.S01E04"]
@pytest.mark.parametrize("flags", [{}, {"skip_dl": True}, {"no_mux": True}])
def test_max_downloads_without_the_archive_takes_the_first_titles(run, get_tracks_calls, flags):
run(count=3, max_downloads=2, skip_existing=False, **flags)
assert get_tracks_calls == [1, 2]
def test_a_title_skipped_for_a_missing_track_does_not_count(monkeypatch, run):
get_tracks = EXAMPLE.get_tracks
monkeypatch.setattr(
EXAMPLE, "get_tracks", lambda self, title: get_tracks(self, title) if title.number > 1 else Tracks()
)
result = run(count=3, max_downloads=2, skip_missing=True)
assert [entry["title"] for entry in result.skipped_titles] == ["Example S01E01"]
assert len(result.completed_files) == 2
def test_a_title_that_published_no_file_does_not_count(monkeypatch, run, get_tracks_calls):
import unshackle.commands.dl as module
download = module.download_tracks_in_passes
def lose_first_title(tracks, *a, **k):
download(tracks, *a, **k)
for track in tracks:
if track.id.endswith("-1"):
track.path.unlink()
monkeypatch.setattr(module, "download_tracks_in_passes", lose_first_title)
result = run(count=3, max_downloads=2, no_mux=True)
assert get_tracks_calls == [1, 2, 3]
assert len(result.completed_files) == 4
def test_a_season_cut_short_by_max_downloads_gets_no_season_event(monkeypatch, run):
import unshackle.commands.dl as module
events = []
monkeypatch.setattr(module, "dispatch", lambda status, scope, *a, **k: events.append(scope))
run(count=3, max_downloads=2)
assert events == ["file", "file", "run"]
events.clear()
run(count=3, max_downloads=3, skip_existing=False)
assert events == ["file", "file", "file", "season", "run"]
+5 -1
View File
@@ -163,12 +163,16 @@ def test_null_takes_the_api_default():
assert cast_dl_params(dl.cli, {key: None for key in DEFAULT_DOWNLOAD_PARAMS}) == cast_dl_params(dl.cli, {}) assert cast_dl_params(dl.cli, {key: None for key in DEFAULT_DOWNLOAD_PARAMS}) == cast_dl_params(dl.cli, {})
@pytest.mark.parametrize("key", ["downloads", "workers", "channels", "latest_episodes"]) @pytest.mark.parametrize("key", ["downloads", "workers", "channels", "latest_episodes", "max_downloads"])
def test_a_boolean_is_not_a_number(key): def test_a_boolean_is_not_a_number(key):
with pytest.raises(click.BadParameter, match=f"Invalid {key}: expected a number"): with pytest.raises(click.BadParameter, match=f"Invalid {key}: expected a number"):
cast_dl_params(dl.cli, {key: True}) cast_dl_params(dl.cli, {key: True})
def test_max_downloads_must_be_a_positive_integer():
assert refusal({"max_downloads": 0}) == "max_downloads must be a positive integer"
@pytest.mark.parametrize("value", [[1], [None], {"a": 1}]) @pytest.mark.parametrize("value", [[1], [None], {"a": 1}])
def test_a_non_string_range_is_a_validation_error(value): def test_a_non_string_range_is_a_validation_error(value):
assert (refusal({"range": value}) or "").startswith("Invalid range") assert (refusal({"range": value}) or "").startswith("Invalid range")
+14
View File
@@ -796,6 +796,12 @@ class dl:
default=None, default=None,
help="Download only the N most recent episodes available.", help="Download only the N most recent episodes available.",
) )
@click.option(
"--max-downloads",
type=click.IntRange(min=1),
default=None,
help="Stop after N titles have downloaded. A skipped title, or a title already in the completion archive, does not count.",
)
@click.option( @click.option(
"-vl", "-vl",
"--v-lang", "--v-lang",
@@ -1597,6 +1603,7 @@ class dl:
generate_dv: bool = False, generate_dv: bool = False,
skip_existing: bool = False, skip_existing: bool = False,
force: bool = False, force: bool = False,
max_downloads: int | None = None,
*_: Any, *_: Any,
**__: Any, **__: Any,
) -> RunOutcome: ) -> RunOutcome:
@@ -2043,9 +2050,14 @@ class dl:
print_listing(header) print_listing(header)
header_music = None header_music = None
downloaded = 0
for i, title in enumerate(titles): for i, title in enumerate(titles):
if not title_wanted(title, wanted): if not title_wanted(title, wanted):
continue continue
if max_downloads and downloaded >= max_downloads:
self.log.info(f"Reached --max-downloads {max_downloads}: stopping before {title}")
break
published = len(self.completed_files)
if progress_sink: if progress_sink:
if isinstance(title, Episode): if isinstance(title, Episode):
@@ -2765,6 +2777,8 @@ class dl:
if progress_sink: if progress_sink:
progress_sink({"output_files": [str(p) for p in self.completed_files]}) progress_sink({"output_files": [str(p) for p in self.completed_files]})
if skip_dl or len(self.completed_files) > published:
downloaded += 1
if service.login_cookies is not None: if service.login_cookies is not None:
cookie_file = login.get_cookie_path(self.service, self.profile) cookie_file = login.get_cookie_path(self.service, self.profile)
+1
View File
@@ -41,6 +41,7 @@ POSITIVE_INT_KEYS = (
"tmdb_id", "tmdb_id",
"tvdb_id", "tvdb_id",
"latest_episodes", "latest_episodes",
"max_downloads",
) )
+6
View File
@@ -1048,6 +1048,12 @@ async def download(request: web.Request) -> web.Response:
type: integer type: integer
minimum: 1 minimum: 1
description: Download only the N most recent episodes; overrides latest_episode (default - null) description: Download only the N most recent episodes; overrides latest_episode (default - null)
max_downloads:
type: integer
minimum: 1
description: >-
Stop after N titles have downloaded. A skipped title, or a title already in the completion archive,
does not count (default - null)
lang: lang:
type: array type: array
items: items:
+1
View File
@@ -43,6 +43,7 @@ DL_OPTIONS: dict[str, ApiOption | None] = {
"wanted": ApiOption([]), "wanted": ApiOption([]),
"latest_episode": ApiOption(False), "latest_episode": ApiOption(False),
"latest_episodes": ApiOption(None), "latest_episodes": ApiOption(None),
"max_downloads": ApiOption(None),
"lang": ApiOption(["orig"], remote="langs"), "lang": ApiOption(["orig"], remote="langs"),
"v_lang": ApiOption([], remote="langs"), "v_lang": ApiOption([], remote="langs"),
"a_lang": ApiOption([], remote="langs"), "a_lang": ApiOption([], remote="langs"),