Repository navigation
feat: send and download media (#22) - #112
Merged
Merged
Conversation
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #22.
What changes
tg messages list/get/searchitems getattachment: kind (photo, video, round, animation, voice, audio, sticker, document), file name, MIME type, size, duration, dimensions, album ID anduniqueFileId, ornull. It is read fromraw_json, so messages cached before this change have it too. The new per-account tablemessage_attachmentsis 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).message_typetaxonomy. History pages now writevoice,video,sticker,audio,diceandhas_mediaexactly as live updates do. Old rows keep their values.tg media download --chat <peer> --id <message> [--out <path|dir|->] [--thumb] [--fresh] [--overwrite].accounts/<id>/media/<uniqueFileId>/<name>. A cached file needs no network and no credentials..partdownload.NETWORK_ERRORafter 60 s. Flood waits over 10 s end withRATE_LIMITEDand are recorded per account.--outcopies the file to a directory or a path (FILE_EXISTSunless--overwrite);-streams the bytes to stdout.--thumbfetches a small preview.CONTENT_PROTECTED. A chat-level protection found online is kept inchat_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--fileisINVALID_ARGS(albums aren't supported yet). The sent message is cached with its attachment.tg status --sizesreports 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.NO_MEDIA,MESSAGE_NOT_FOUND,CONTENT_PROTECTED,MEDIA_UNSUPPORTED(files served from Telegram's CDN) andFILE_EXISTS.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 checkpasses.raw_jsonshape (base64 and per-byte-object byte arrays; Long objects, strings and numbers), parity ofuniqueFileIdandmessage_typewith mtcute, the attachment upsert writing nothing for an unchanged message, the download core with a fake client, the media cache and clean,--outmodes, status sizes andsend --filevalidation.src/__integration__, one new test, run against a test-only session):tg send --to me --fileuploads 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