Skip to content

feat(media): download several messages in one run, with name templates - #181

Merged
neoromantic merged 27 commits into
neoromantic:mainfrom
ertembiyik:ertembiyik/NO-TASK/batch-download
Nov 22, 2026
Merged

neoromantic merged 27 commits into
neoromantic:mainfrom
ertembiyik:ertembiyik/NO-TASK/batch-download

Conversation

@ertembiyik

@ertembiyik ertembiyik commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

What and why

tg media download now takes several --id values and downloads them in one process, and --out takes a name template. This is the first part of #104; the filters and the config.json defaults are left for later (see below). Refs #104

The need, from a real agent session on 0.10: 63 voice notes fetched with one tg media download per message, four at a time through xargs -P4. Stderr showed [flood-wait] users.getFullUser: waiting 7s before retry ten times and 7 downloads failed; the same 7 passed when rerun one by one.

Why that happened. Before its first byte, every tg media download process starts its own client, resolves --chat, fetches the message, and for a private chat checks content protection with users.getFullUser. Four processes over 63 files made 63 getFullUser calls for the same user, and no process could see another's flood wait: mtcute remembers a wait only inside one client.

What one run does instead: one client, one chat resolution, one getMessages per 100 IDs, one getFullUser per batch, and a flood wait pauses the whole batch and then continues, instead of failing a file.

Before (one process per message, two photos into one directory):

$ tg media download --chat me --id 1 --out exports/ && tg media download --chat me --id 2 --out exports/
{"success":true,"data":{"path":"…/exports/photo.jpg",…}}
{"success":false,"error":{"code":"FILE_EXISTS","message":"File already exists: …/exports/photo.jpg","details":{"path":"…/exports/photo.jpg"},"suggestion":"pass --overwrite or another --out"}}

After (real output from the e2e fake client: four files, the third hits FLOOD_WAIT_2 once, one is refused):

$ tg media download --chat 5550003 --id 11 --id 12 --id 13 --id 15 --out 'exports/{chat}/{date}_{id}_{name}'
{"success":true,"data":{"path":"…/exports/5550003/2025-10-09_13_example-notes.txt",…,"messageId":13,"cached":false,…}}
{"success":true,"data":{"path":"…/exports/5550003/2025-10-09_11_example-voice.ogg",…,"messageId":11,"cached":false,…}}
{"success":false,"error":{"code":"TELEGRAM_ERROR","message":"Telegram refused the download: FILE_ID_INVALID","details":{"chatId":5550003,"messageId":15,"method":"upload.getFile","error":"FILE_ID_INVALID"}}}
{"success":true,"data":{"path":"…/exports/5550003/2025-10-09_12_example-clip.mp4",…,"messageId":12,"cached":false,…}}
stderr:  [flood-wait] upload.getFile: pausing the batch for 2s
         Downloaded 3 of 4 files, 1 failed
exit 1

The fake client's call log for that run shows one messages.getMessages for all four IDs and one users.getFullUser.

How it behaves:

  • Output: one compact JSON line per file on stdout as each finishes, in finishing order. A success line has the fields a single download prints; a failure line uses the error schema with chatId and messageId in details. Stderr gets pause notices and a final count. Exit 0 when all succeed, 1 when any file failed.
  • One --id prints exactly what it printed before, including errors and -f pretty (8 cases compared against main).
  • Cache and resume as today: a cached file is served without a network call, a partial file resumes.
  • --out templates: {chat}, {id}, {date} (the message's UTC day), {name} and {kind}. Each path part that holds a placeholder goes through sanitizeFileName once filled. In a batch, a plain directory gets {id}_{name}, which can't collide inside a chat. An unknown placeholder, and --out - with several IDs, are INVALID_ARGS.
  • Read-only mode and allowedChats apply unchanged: still one --chat.

How many files at once, and why. Telegram's file docs say "clients should limit the parallelism to download at most" a number of files set by two config values (api/files), and api/config gives small_queue_max_active_operations_count = 5 for files under 20 MB and large_queue_max_active_operations_count = 2 for bigger ones, each "a soft limit, specifying the maximum number of files that should be downloaded in parallel from the same DC". So: five at a time, at most two of them 20 MB or more. mtcute already parallelizes inside each file. There is no flag for it.

Decisions you may want to change:

  • A repeated download succeeds. An --out file that already holds the same bytes (size and sha256) is left in place instead of FILE_EXISTS. This applies to a single download too, and is the only behaviour change outside a batch; without it, rerunning a batch fails every file.
  • No --concurrency flag, and the limits are Telegram's documented defaults, not read from the live app config.
  • Flood waits of five minutes or less pause the batch, at most five times per file; a longer one fails that file.
  • No per-file byte progress in a batch, since concurrent progress lines would overwrite each other.
  • {date} is the UTC day.

Left out of #104, on purpose:

  • The filters (--type, --since, --until, --limit). feat(messages): filter messages list by --type, --since and --until #180 adds --type, --since and --until to tg messages list; the batch should reuse that instead of growing a second copy. Until then any command that prints IDs can feed it, for example tg sql "SELECT message_id FROM message_attachments WHERE chat_id = … AND kind = 'voice'" | jq -r '.data.rows[] | "--id=\(.message_id)"' | xargs tg media download --chat … --out voice/.
  • Defaults in config.json: the config module has no string-valued key yet, so it needs a new value type and validation, which is more than this PR should carry.

Found on the way, not changed here: createDefaultClientFactory passes network.middlewares: [floodWaiter], which replaces mtcute's default stack, so mediaThrottle and internalErrorsHandler are dropped for every client. That looks worth its own small PR.

This touches src/commands/media/download-media.ts by one word; #177 changed that file and errors.ts; main is merged in, see the update below.

Update: main merged in (5443e73)

  • main moved to oxfmt and oxlint with the landmines rules, and moved every test beside its code. This branch follows, on top of your 008476c and the two fixes from my review comment: the same behaviour and output, the code restyled, prose comments and explicit return types removed.
  • Tests moved with main's layout: the batch cases are in src/commands/media/media-download.test.ts, the flood-wait case in src/db/rate-limits.test.ts, the e2e cases in src/test/media.e2e.test.ts, and src/commands/media/out.test.ts is new.
  • No test doubles. The tests for a filesystem without hard links stubbed linkSync. The fallback is now split into the error check (lacksHardLinks) and the exclusive copy (publishByCopy), each tested directly with real files; the three lines that join them are not covered by a test.
  • One lint exemption, for you to judge: src/test/fake-media-cli.test-utils.ts is added to the no-restricted-properties override list in .oxlintrc.json, next to fake-client-cli.test-utils.ts. It replaces the Telegram client module for the media e2e tests the same way. The alternative is rewriting those e2e tests on the record and replay fixtures.
  • This and feat(media): transcribe voice notes and video notes with a local Whisper program #183 will conflict in download-media.ts (both rework the online check); whichever lands second gets the fold-in from me.
  • After the merge: bun run check clean (format, lint, types, Knip), bun run test 1224 pass, bun run test:e2e 353 pass, 0 fail. Totals are lower than before because main merged and removed many tests.

How I checked it

  • E2E with a fake client (7 new tests): several IDs with one fetch and one protection check; a cached file with no network; a partial file resumed; one failing file among several; a flood wait in the middle of a batch; templates, including two photos into one directory and a name that needs sanitizing; the argument errors.

  • A single --id on main and on this branch, 8 cases (cached, --out dir/, FILE_EXISTS, --out file, NO_MEDIA, -f pretty, an online download run twice): identical stdout, stderr and exit code.

  • Live, on a personal account, the short run Download many attachments at once, with name templates #104 asks for: six files (photos and documents, 32 KB to 215 KB) from Saved Messages in one command finished in 3 seconds with six success lines; the same command again reported all six without downloading.

  • Not verified live: a batch in a private chat with someone else, which is where the getFullUser flood waits came from (Saved Messages has no protection check); five parallel files on a non-Premium account; 100 IDs in one getMessages.

  • bun run check: clean. bun run test: 2301 pass, 0 fail. bun run test:e2e: 439 pass, 0 fail.

  • Tests pass locally and use made-up data only

  • README, docs and affected demos follow the product content standard (docs/media.md, docs/cli-commands.md, docs/rate-limiting.md, README, CHANGELOG)

  • Title follows the repo's commit style: Conventional Commits (feat: …, fix: …) unless AGENTS.md says otherwise

Update: second code review (3fb3524)

A second, independent review of this branch. Each point below was first shown by a failing test, then fixed.

  • The copy fallback removed the target after a failed copy even when another writer had created it. It now creates the target itself, exclusively, and removes only a file it created.
  • A path part filled from a placeholder is refused when it is a symlink (exports/{name} with a sender's file name that matches an existing link); that item fails and the others go on.
  • Content protection, both introduced by this PR: --fresh --thumb saved the fetched message after reporting a missing preview, so a newly protected message could still be exported from the cache later; and a queued batch item could record an older, unprotected verdict over a newer one. The save now comes first, and a verdict older than the stored one is ignored.
  • {date} is filled from the downloaded message, so it is no longer unknown when the cache skips the row (a group the account takes no part in).
  • The same --id given twice is a batch of one, so --out is a directory as in any batch; it used to write a file named after the directory.
  • Not added: a test of the real link-fails-then-copy dispatch. It needs a stub of linkSync or a filesystem without hard links, and the first needs a lint exemption.
  • Left as it is: in a private chat a batch shares one users.getFullUser answer, so protection turned on in the middle of a batch is not seen there.

After these commits: bun run check clean, bun run test 1231 pass, bun run test:e2e 354 pass, 0 fail.

Update: main merged in (649eef9)

main up to #220 merged in, no conflicts and no changes to this branch's code.

After the merge: bun run check clean, bun run test 1242 pass, bun run test:e2e 355 pass, 0 fail.

Update: main merged in (853a651)

main up to 0.15.1 and #232 merged in, on top of 1244791 and d9142a8. Conflicts: CHANGELOG.md (the entries of this PR now sit under the new ## [Unreleased]) and src/commands/media/download.ts. getClientForAccount() is async since #226, so the single and the batch path await the client. No behaviour change.

After the merge: bun run check clean, bun run test 1259 pass, bun run test:e2e 381 pass, 0 fail.

Update: final pass on 1244791 and d9142a8

No defect found in either commit or in the merge above. Checked: open descriptors counted around the exclusive copy (success, missing source, abort at the start, abort mid-copy: unchanged in all four), and each guarantee broken in turn to see a test fail.

  • 037e379: the equal-timestamp rule of the protection store could be removed with every test green, because the test recorded the protected verdict first. It now records both orders.
  • 5e0a1e5: docs/media.md says that only a newer online check clears a stored protection.

Not verified: live Telegram, physical exFAT or SMB volumes, Windows.

bun run check clean, bun run test 1259 pass, bun run test:e2e 381 pass, 0 fail.

Update: main merged in (ac85803)

main up to 0.15.2 (#234) merged in. One conflict: CHANGELOG.md (the entries of this PR stay under ## [Unreleased], above the new 0.15.2 section). No code change in this PR. The Windows download fix of #234 in src/commands/media/download-media.ts merged without a conflict.

After the merge: bun run check clean, bun run test 1259 pass, bun run test:e2e 381 pass, 0 fail.

🤖 Generated with Claude Code

tg media download takes several --id values and handles them in one
process: one fetch of the messages, one content-protection check, up to
five files at a time (two of 20 MB or more, Telegram's soft limits), and a
flood wait pauses the batch instead of failing a file. Each file prints
one JSON line as it finishes; the exit code says whether any failed.
--out takes a name template, so files sent to one directory no longer
collide, and an --out file that already holds the same bytes is left in
place. One --id prints what it printed before.

Refs neoromantic#104

Co-Authored-By: Claude Fable 5.2 <[email protected]>
ertembiyik and others added 4 commits November 18, 2026 14:24
CHANGELOG: both sides' entries kept. Per-file error lines carry retryable (neoromantic#177) and the shared rate-limit wording.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
main now has neoromantic#179 (neoromantic#188). CHANGELOG: both Changed entries kept.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
main is now the 0.14.0 release (neoromantic#189). This PR's changelog entries move
back under Unreleased: a plain merge left them in the released section.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@neoromantic

Copy link
Copy Markdown
Owner

@ertembiyik, I pushed 008476c to your branch. Could you give the updated download path another review before we merge? I’d especially like your take on the flood-wait behavior with mtcute and the output collision rules.

  • Chat and content protection. The batch resolves the chat once and validates each returned message’s peer before writing to the cache. Single and batch downloads now share the online protection check. This matters when the attachment bytes are already on disk from another message.
  • Partial results and flood waits. Each page of up to 100 IDs finishes independently, so an error on page two preserves page one’s results. New RPCs observe the longest outstanding pause, including short waits that mtcute previously handled internally. Retries are bounded per file and per page. Ctrl-C interrupts the wait and also works during a cache-only batch.
  • Output files. Repeating a batch accepts identical bytes. A single ID retains the v0.14.0 FILE_EXISTS behavior. If two IDs map different bytes to the same path, the first completed export keeps it, even with --overwrite. Each copy gets its own temporary file. Atomic publication without overwrite requires hard-link support on the output filesystem.
  • CLI output. A template ending in a slash creates a directory. Both json and pretty emit one JSON line per batch result, and a terminal shows the completed-file count on stderr.

I added regression tests before fixing these cases. Lint and typecheck passed, as did 190 focused offline tests. A separate CLI smoke test interrupted a 60-second simulated flood wait and confirmed exit 130. Live Telegram behavior remains unverified for this revision.

ertembiyik and others added 6 commits November 18, 2026 20:28
main now has neoromantic#175 (neoromantic#194), neoromantic#174 and neoromantic#155. fetch.ts: the batch fetch is built
on main's shared fetchMessagesByIdRaw, with the peer check kept. README
and CHANGELOG: both sides' entries kept.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
main now has neoromantic#195: Knip in bun run check, and long as a runtime dependency. No conflict; the check is clean.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Without hard links (exFAT, FAT, some network shares) link() fails with
EPERM, ENOTSUP, ENOSYS or EXDEV. Fall back to an exclusive copy that
still refuses an existing target. A batch collision with a file an
earlier run left now points at --overwrite.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Batch calls surface every flood wait, including the speed-limit waits a
download without Premium meets throughout a large file. Each one counted
toward the five retries for the file, so a long download that kept
moving failed with RATE_LIMITED. A wait now counts only when no part
arrived since the previous one; a stuck file still gives up after six.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ertembiyik

Copy link
Copy Markdown
Contributor Author

Reviewed 008476c. The design holds: one layer sleeps, the pause is shared without races, pages finish independently, an interrupt leaves resumable partials, and the collision rules behave as you describe. Two things I changed, both pushed with tests that fail without them:

  1. Flood waits (12285c7). With floodSleepThreshold: 0 every FLOOD_PREMIUM_WAIT from upload.getFile counted toward MAX_RETRIES = 5, and the counter never reset when bytes arrived. A non-Premium account downloading a large video in a batch could fail on the sixth speed-limit wait, while the same ID alone completes, because mtcute sleeps through those. A wait now counts against a file only when no part arrived since its previous wait: six waits in a row with nothing received still fail it. The page-level bound, the shared pause, the 300 s ceiling and Ctrl-C are unchanged.

  2. Output files (4fca3d0). Without --overwrite, publishing used linkSync, for a single ID too. On exFAT/FAT or a share without hard links that was GENERAL_ERROR, where 0.14.0 (stat, temp file, rename) worked. It now falls back to an exclusive copy on EPERM, ENOTSUP, ENOSYS or EXDEV. The no-clobber rule holds; the fallback is not atomic, and docs/media.md says so.

Also: a batch that hits a file left by an earlier run now suggests --overwrite instead of "use a distinct output path", and the "surfaces short waits" test checks the behaviour (a short wait on one file holds back the other's upload.getFile) instead of the threshold value.

Smaller, not changed: a second Ctrl-C can leave a .tg-*.part in the output directory, and "identical bytes" hashes both files in full (8 GB read for a repeated 4 GB video).

Not verified live: a real FLOOD_PREMIUM_WAIT and a real volume without hard links; both are covered by fakes only. main is merged in; bun run check clean, bun run test 2061 pass, bun run test:e2e 471 pass, 0 fail.

ertembiyik and others added 11 commits November 19, 2026 12:41
Conflicts came from main's oxfmt reformat, comment and return-type sweeps and the test colocation; the batch changes were reapplied onto main's download-media, fetch, protection, rate-limits and download, and the branch's tests moved to main's layout (batch cases into media-download.test.ts, the flood-wait case into src/db/rate-limits.test.ts, the --out cases into out.test.ts beside out.ts, the e2e cases into src/test/media.e2e.test.ts with the fake CLI as src/test/fake-media-cli.test-utils.ts). The branch's new code and tests now follow main's lint: no prose comments, inferred return types.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
main forbids test doubles: the stub of linkSync is gone. The fallback is
split into the error check and the exclusive copy, each tested directly.
The fake media client joins main's fake client on the mock.module
exempt list in .oxlintrc.json.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The copy fallback without hard links now creates the target exclusively
itself and removes it only on its own failed copy, never a file another
writer claimed in between.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
A path part filled from a placeholder, such as {name} from the sender's
file name, could match an existing symlink and send the file outside the
template's folder. Such a part now fails that file with GENERAL_ERROR.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
With --fresh --thumb, a message without a preview returned NO_MEDIA
before the fetched message was saved, so a later offline run could still
export the full file after Telegram turned on its content protection.
The protection check and the save now come first, as before the batch
change.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
A batch checks each queued file against the chat object of its page.
When a refreshed file reference had meanwhile found the chat protected,
a later file still recorded the page's older answer and exported cached
bytes. A verdict older than the recorded one is now ignored, and the
recorded one decides.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
{date} read the message's row from the cache, so a group the account
takes no part in, whose messages the cache skips, got "unknown" and two
days could collide under one name. The download result now carries the
message date; the JSON output is unchanged.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
--id 42 --id 42 was deduplicated before the mode was chosen, so it ran as
one download and wrote a file named after --out instead of filling the
directory. Two or more --id flags now always run as a batch; a repeated
ID is still downloaded once.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@neoromantic

Copy link
Copy Markdown
Owner

@ertembiyik, thanks for the flood-wait and filesystem fixes. I pushed two follow-ups to your branch.

  • 1244791 — chat protection. A batch still makes one successful users.getFullUser call. Each page now reuses the time of that check. SQLite keeps the newest verdict and gives protection priority when two checks have the same timestamp. This prevents an older answer from clearing a newer protection setting.
  • d9142a8 — exports without hard links. An exclusive copy now writes through an abortable stream. Another export in the same batch waits for that file to finish before comparing its bytes. An error closes the descriptor and leaves the public path alone, so cleanup cannot delete a replacement written by another process. A failed or interrupted copy can leave partial bytes at the destination. The docs explain how to replace them with --overwrite.

I wrote regression tests before the fixes. All 176 focused offline tests and bun run check passed. A real SIGINT delivered to the single-file CLI during the simulated no-hard-link fallback gave exit 130 and empty stdout. The pinned mtcute downloader also finished a 4 MiB fixture byte-for-byte across seven simulated premium flood waits. Live Telegram and physical exFAT/SMB volumes remain untested.

Could you take the final pass on d9142a8, make any adjustments you want in your branch, and let us know here when you consider the PR ready to merge?

ertembiyik and others added 3 commits November 20, 2026 20:21
…tch-download

# Conflicts:
#	CHANGELOG.md
#	src/commands/media/download.ts
…e time

The equal-timestamp rule only mattered when the protected verdict came
second; the test recorded it first, so removing the rule kept it green.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@ertembiyik

Copy link
Copy Markdown
Contributor Author

Final pass on 1244791 and d9142a8 is done. I found no defect and consider the PR ready to merge.

Checked: open descriptors counted around the exclusive copy (success, missing source, abort at the start, abort mid-copy: unchanged in all four), and each guarantee broken in turn to see a test fail. One gap: the equal-timestamp rule could be removed with every test green, because the test recorded the protected verdict first. 037e379 records both orders. 5e0a1e5 tightens one sentence in docs/media.md. main (0.15.1) is merged in. bun run check clean, bun run test 1259 pass, bun run test:e2e 381 pass.

Not blocking, your call:

  • Without hard links an export copies the bytes twice (into the temp file, then into the target), and only the second copy can be aborted, so the first Ctrl-C on a large file waits for the temp copy. Copying straight from the cached file into the target opened with wx would halve the I/O and make the whole copy abortable.
  • After Ctrl-C during that copy stderr says "run the command again to resume", but the rerun is FILE_EXISTS until --overwrite is passed.
  • When one copy fails (disk full, say), a later file of the batch that maps to the same target fails with the first file's message.
  • On Windows, removing the temp file right after an abort may hit EBUSY while the read stream still has it open. Not tested here.

Not verified: live Telegram, physical exFAT or SMB volumes, Windows.

@neoromantic
neoromantic merged commit c16120b into neoromantic:main Nov 22, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants