Skip to content

feat: send and download media (#22) - #112

Merged
neoromantic merged 13 commits into
mainfrom
feat/media-download
Oct 28, 2026
Merged

neoromantic merged 13 commits into
mainfrom
feat/media-download

Conversation

@neoromantic

Copy link
Copy Markdown
Owner

Closes #22.

What changes

  • Attachment metadata. tg messages list/get/search items get attachment: kind (photo, video, round, animation, voice, audio, sticker, document), file name, MIME type, size, duration, dimensions, album ID and uniqueFileId, or null. It is read from raw_json, so messages cached before this change have it too. The new per-account table message_attachments is written in the same transaction as the message, with its own "something changed" condition, so a re-fetched unchanged message writes nothing. Older rows are filled later (Background, resumable migrations for big caches #89).
  • One message_type taxonomy. History pages now write voice, video, sticker, audio, dice and has_media exactly as live updates do. Old rows keep their values.
  • tg media download --chat <peer> --id <message> [--out <path|dir|->] [--thumb] [--fresh] [--overwrite].
    • Saves the file into accounts/<id>/media/<uniqueFileId>/<name>. A cached file needs no network and no credentials.
    • Otherwise it fetches the message again for a fresh file reference and resumes a partial .part download.
    • A stalled transfer ends with NETWORK_ERROR after 60 s. Flood waits over 10 s end with RATE_LIMITED and are recorded per account.
    • --out copies the file to a directory or a path (FILE_EXISTS unless --overwrite); - streams the bytes to stdout.
    • --thumb fetches a small preview.
  • Content protection. Chats, channels, messages and private chats with content protection, and self-destructing media, are refused with CONTENT_PROTECTED. A chat-level protection found online is kept in chat_content_protection, so later cache hits are refused offline too, until an online check finds it off.
  • tg send --file <path> [--caption <text>] [--force-document] sends one file: a JPEG, PNG or WebP image up to 10 MB as a photo, anything else as a plain document. It works with the reply and silent flags. A repeated --file is INVALID_ARGS (albums aren't supported yet). The sent message is cached with its attachment.
  • tg status --sizes reports each account's media cache apart from the cache DB. tg media clean [--older-than] [--chat] [--all] removes cached files and stale partial downloads and reports the freed bytes; a bare run removes only stale partials.
  • New error codes, all exit 1: NO_MEDIA, MESSAGE_NOT_FOUND, CONTENT_PROTECTED, MEDIA_UNSUPPORTED (files served from Telegram's CDN) and FILE_EXISTS.
  • The daemon still downloads and sends nothing.
  • Docs: docs/media.md (new), CLI commands, API design (codes), database schema, SQL, configuration, rate limiting, testing, README, CHANGELOG, ROADMAP (follow-ups Transcribe voice messages and video notes #102, Download many attachments at once, with name templates #104, Search media on the server, beyond the cached history #105, Background media download in the daemon, with a disk quota #99, Extract text from documents and images (PDF, office files, OCR) #103).

Testing

  • bun run check passes.
  • Targeted unit and e2e tests (27 files, 653 tests) pass offline. They cover the extractor over every raw_json shape (base64 and per-byte-object byte arrays; Long objects, strings and numbers), parity of uniqueFileId and message_type with mtcute, the attachment upsert writing nothing for an unchanged message, the download core with a fake client, the media cache and clean, --out modes, status sizes and send --file validation.
  • Live smoke (src/__integration__, one new test, run against a test-only session): tg send --to me --file uploads 700,000 made-up bytes, tg media download --chat me --id <id> returns them byte for byte, a second run is a cache hit, and the message is deleted afterwards. Result: 1 pass.

🤖 Generated with Claude Code

neoromantic and others added 13 commits October 29, 2026 00:07
Every item of tg messages list, get and search carries `attachment`: the
kind (photo, video, round, animation, voice, audio, sticker, document),
file name, MIME type, size, duration, dimensions, album ID and Telegram's
unique file ID, read from raw_json, so messages cached by older versions
show it too. Link previews with a photo or file report source "webpage".

A new per-account table, message_attachments, is written with each
message in the same transaction, with its own changed check: a message
written again unchanged writes nothing, and one that loses its media
loses its row. tg sql sees the table; rows exist for messages written
from now on.

History pages, tg send and the abstract sync worker now share one
message_type taxonomy with live updates: voice, video, sticker, audio,
dice and unknown instead of document and media. Existing rows keep their
type.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each account gets a media cache under accounts/<id>/media: one folder per
Telegram unique file ID holding the file under its sender's name made safe
for every file system (or <kind>.<ext>), its previews, a hidden partial
download and a lock that keeps two processes from writing one download.

tg media clean removes cached files. Bare, it removes only partial
downloads nobody wrote to for a day, so it is always safe; --all,
--older-than (a duration, a date or a date and time) and --chat (the files
of a chat's messages, keeping one another chat's message also holds)
remove complete files too. Folders a running download holds are skipped.

tg status --sizes reports each account's media cache (files, partial
downloads) apart from its cache database, and storage.media_bytes sums it.

Also: a chat_content_protection table for the last online protection
check of a chat, visible to tg sql; the error codes NO_MEDIA,
MESSAGE_NOT_FOUND, CONTENT_PROTECTED, MEDIA_UNSUPPORTED and FILE_EXISTS
(exit 1); a transfer client that sleeps through flood waits up to 10 s
only; stderr progress for a terminal; and flood waits of file transfers
no longer print a line each.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
tg media download --chat <peer> --id <message> saves the message's file
into the account's media cache (accounts/<id>/media, one copy per
Telegram unique file ID) and prints its path as JSON. A file already in
the cache needs no network and no credentials.

Otherwise the message is fetched again, for a fresh file reference, and
written back to the cache with its attachment row. The file goes to a
partial download that the next run resumes from its last whole 512 KB
part, then is renamed into the cache. A lock keeps two processes from
writing one download. A download that receives nothing for 60 s ends
with NETWORK_ERROR; flood waits longer than 10 s end it with
RATE_LIMITED and are recorded for the account, FLOOD_PREMIUM_WAIT
included. An expired file reference is refreshed once. Files served
from Telegram's CDN give MEDIA_UNSUPPORTED.

Media of a chat, channel, private chat or message with content
protection, and self-destructing media, is refused with
CONTENT_PROTECTED. The chat-level answer of every online check is kept,
so a cache hit refuses a protected chat's files offline too until
--fresh finds the protection off.

--out copies the file into a directory under its name or to a file path
(FILE_EXISTS unless --overwrite), and --out - writes the bytes alone to
stdout. --thumb downloads the small preview. Progress goes to stderr on
a terminal only; SIGINT or SIGTERM keeps the partial download and exits
130.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
tg send --file <path> uploads one file through the account's
rate-limited client and sends it with messages.sendMedia: a photo for
JPEG, PNG and WebP images up to 10 MB, otherwise a document named by
the file's base name. --caption adds text, --force-document sends an
image as a file, and --silent/--reply-to work as for text.

Wrong arguments are INVALID_ARGS before any account or network is
needed: no --message or --file, both, --caption or --force-document
without --file, a repeated --file (albums aren't supported yet), and a
missing, unreadable or empty file. The result adds the file's name,
MIME type, size and how it was sent, and its attachment (with the
uniqueFileId tg media download uses). The sent message is cached with
its attachment row like text sends.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The live smoke suite sends a 700 000-byte made-up file to Saved Messages
with tg send --file, downloads it back with tg media download (two
512 KB parts), compares the bytes and checks that a second download is
served from the media cache. The suite deletes the message afterwards.

The exit-code e2e tests now cover NO_MEDIA and FILE_EXISTS (exit 1).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add docs/media.md and document tg media download and clean, tg send --file,
the attachment field of message items, the message_attachments and
chat_content_protection tables, the new error codes, media sizes in
tg status and the unified message_type. README, CHANGELOG and ROADMAP
follow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A chats_cache row holding a raw chat or channel with noforwards kept
refusing cached files after an online check had found protection off,
since tg media download never rewrites chats_cache. The chat's flag now
counts only when its row is newer than the last online check; a positive
online answer still blocks until a check finds protection off.

When Telegram answers --fresh without the chat object (no chat, or a
forbidden one), the protection last known still holds instead of the file
being served.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A lock whose pid a reused process had was treated as live forever: a
later tg media download of that file waited with no deadline and
tg media clean skipped the folder. A running download now refreshes its
lock every 10 seconds, and a lock nobody refreshed for a minute is stale
even when its pid runs. A stale lock is renamed away before it is
removed, so a lock another process took over meanwhile is never deleted.
A download waits up to 10 minutes for another process's download of the
same file, then ends with GENERAL_ERROR naming the lock and its pid.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A sender-chosen name with a right-to-left override, such as
"report<U+202E>fdp.exe", kept it, so the cached file and the one --out
wrote displayed as "reportexe.pdf". Bidi controls (U+061C, U+200E-U+200F,
U+202A-U+202E, U+2066-U+2069) are now replaced with "_" like control
characters.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
tg send --file left force_file unset unless --force-document was given,
so Telegram could turn a GIF into an animation or an MP4 into a video
while the command reported sentAs: document. Every document upload now
sets force_file, as docs/media.md says.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- The message_type annotation of tg sql print-schema no longer pins a
  release number.
- tg media clean --chat says which messages it knows: both the chat's
  files and the shared ones come from message_attachments, which lacks
  messages cached by earlier versions until #89.
- The CHANGELOG notes that history sync now writes has_media like live
  updates; its Added list is one tight list again.
- The README comparison row says only sending albums and voice messages
  is missing; downloads handle them.
- Long lines in database-schema.md and media.md are wrapped like the
  rest of the docs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
mtcute's uploadFile reads the account's premium flag from the session,
which only a prepared client has loaded. `tg send --to me --file` resolves
the recipient offline, so nothing had prepared the client and the upload
failed with "User info is not cached yet".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
tg status now reports the media cache as storage.media_bytes (null without
--sizes), so the upgrade tests that compare the whole storage object
expect it too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@neoromantic
neoromantic merged commit 90c7654 into main Oct 28, 2026
5 checks passed
@neoromantic
neoromantic deleted the feat/media-download branch October 28, 2026 20:20
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.

Send and download media

1 participant