Repository navigation
feat(media): download several messages in one run, with name templates - #181
Conversation
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]>
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]>
|
@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.
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. |
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]>
…inks Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
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:
Also: a batch that hits a file left by an earlier run now suggests Smaller, not changed: a second Ctrl-C can leave a Not verified live: a real |
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]>
|
@ertembiyik, thanks for the flood-wait and filesystem fixes. I pushed two follow-ups to your branch.
I wrote regression tests before the fixes. All 176 focused offline tests and 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? |
…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]>
…ction Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
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 Not blocking, your call:
Not verified: live Telegram, physical exFAT or SMB volumes, Windows. |
…tch-download # Conflicts: # CHANGELOG.md
What and why
tg media downloadnow takes several--idvalues and downloads them in one process, and--outtakes a name template. This is the first part of #104; the filters and theconfig.jsondefaults are left for later (see below). Refs #104The need, from a real agent session on 0.10: 63 voice notes fetched with one
tg media downloadper message, four at a time throughxargs -P4. Stderr showed[flood-wait] users.getFullUser: waiting 7s before retryten times and 7 downloads failed; the same 7 passed when rerun one by one.Why that happened. Before its first byte, every
tg media downloadprocess starts its own client, resolves--chat, fetches the message, and for a private chat checks content protection withusers.getFullUser. Four processes over 63 files made 63getFullUsercalls 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
getMessagesper 100 IDs, onegetFullUserper 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):
After (real output from the e2e fake client: four files, the third hits
FLOOD_WAIT_2once, one is refused):The fake client's call log for that run shows one
messages.getMessagesfor all four IDs and oneusers.getFullUser.How it behaves:
chatIdandmessageIdindetails. Stderr gets pause notices and a final count. Exit 0 when all succeed, 1 when any file failed.--idprints exactly what it printed before, including errors and-f pretty(8 cases compared againstmain).--outtemplates:{chat},{id},{date}(the message's UTC day),{name}and{kind}. Each path part that holds a placeholder goes throughsanitizeFileNameonce 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, areINVALID_ARGS.allowedChatsapply 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 andlarge_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:
--outfile that already holds the same bytes (size and sha256) is left in place instead ofFILE_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.--concurrencyflag, and the limits are Telegram's documented defaults, not read from the live app config.{date}is the UTC day.Left out of #104, on purpose:
--type,--since,--until,--limit). feat(messages): filter messages list by --type, --since and --until #180 adds--type,--sinceand--untiltotg messages list; the batch should reuse that instead of growing a second copy. Until then any command that prints IDs can feed it, for exampletg 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/.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:
createDefaultClientFactorypassesnetwork.middlewares: [floodWaiter], which replaces mtcute's default stack, somediaThrottleandinternalErrorsHandlerare dropped for every client. That looks worth its own small PR.This touches
src/commands/media/download-media.tsby one word; #177 changed that file anderrors.ts;mainis merged in, see the update below.Update:
mainmerged in (5443e73)mainmoved to oxfmt and oxlint with the landmines rules, and moved every test beside its code. This branch follows, on top of your008476cand the two fixes from my review comment: the same behaviour and output, the code restyled, prose comments and explicit return types removed.main's layout: the batch cases are insrc/commands/media/media-download.test.ts, the flood-wait case insrc/db/rate-limits.test.ts, the e2e cases insrc/test/media.e2e.test.ts, andsrc/commands/media/out.test.tsis new.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.src/test/fake-media-cli.test-utils.tsis added to theno-restricted-propertiesoverride list in.oxlintrc.json, next tofake-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.download-media.ts(both rework the online check); whichever lands second gets the fold-in from me.bun run checkclean (format, lint, types, Knip),bun run test1224 pass,bun run test:e2e353 pass, 0 fail. Totals are lower than before becausemainmerged 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
--idonmainand 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
getFullUserflood waits came from (Saved Messages has no protection check); five parallel files on a non-Premium account; 100 IDs in onegetMessages.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: …) unlessAGENTS.mdsays otherwiseUpdate: second code review (3fb3524)
A second, independent review of this branch. Each point below was first shown by a failing test, then fixed.
exports/{name}with a sender's file name that matches an existing link); that item fails and the others go on.--fresh --thumbsaved 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 longerunknownwhen the cache skips the row (a group the account takes no part in).--idgiven twice is a batch of one, so--outis a directory as in any batch; it used to write a file named after the directory.linkSyncor a filesystem without hard links, and the first needs a lint exemption.users.getFullUseranswer, so protection turned on in the middle of a batch is not seen there.After these commits:
bun run checkclean,bun run test1231 pass,bun run test:e2e354 pass, 0 fail.Update:
mainmerged in (649eef9)mainup to #220 merged in, no conflicts and no changes to this branch's code.After the merge:
bun run checkclean,bun run test1242 pass,bun run test:e2e355 pass, 0 fail.Update:
mainmerged in (853a651)mainup 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]) andsrc/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 checkclean,bun run test1259 pass,bun run test:e2e381 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.
docs/media.mdsays that only a newer online check clears a stored protection.Not verified: live Telegram, physical exFAT or SMB volumes, Windows.
bun run checkclean,bun run test1259 pass,bun run test:e2e381 pass, 0 fail.Update:
mainmerged in (ac85803)mainup 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 insrc/commands/media/download-media.tsmerged without a conflict.After the merge:
bun run checkclean,bun run test1259 pass,bun run test:e2e381 pass, 0 fail.🤖 Generated with Claude Code