Introducing a new way to review your PRs.

Read the announcement

ayugram / ayugramdesktop

Desktop Telegram client with good customization and Ghost mode.

View on GitHub

13 documents · Updated Nov 16, 2026

docs / api-request-layer

API request layer

Overview

The Telegram API request layer is centered on ApiWrap in Telegram/…/apiwrap.h and Telegram/…/apiwrap.cpp. ApiWrap inherits from MTP::Sender, is constructed from Main::Session, and owns the session-scoped request managers exposed by methods such as updates(), premium(), userPrivacy(), peerPhoto(), chatParticipants(), composeWithAi(), and websites(). Its constructor wires those managers to the session MTProto instance (session->account().mtp()), starts session-bound reactive subscriptions, and keeps per-request state such as dialog/history request de-duplication sets, delayed draft saves, upload queues, pending file-reference refresh handlers, and statistics request registration.

Most code in Telegram/SourceFiles/api/** follows one of two patterns. Small feature managers hold a MTP::Sender or use ApiWrap::request(...), send a TL request, process users/chats into Data::Session, translate TL payloads into data-layer structs, and publish results through callbacks or rpl::producers. Api::UserPrivacy in api_user_privacy.cpp, for example, maps local privacy keys/rules to MTPInputPrivacyKey and MTPInputPrivacyRule, sends MTPaccount_SetPrivacy / MTPaccount_GetPrivacy, then caches and emits UserPrivacy::Rule values. Larger flows stay in ApiWrap: dialogs, full-peer loading, drafts, web page previews, stickers, notify settings, history slices, shared media, sending, file upload completion, and delete/history operations all keep in-flight request IDs or keys in apiwrap.h fields and complete by updating Data::Session, histories, storage, or peer models.

Incoming updates are handled by Api::Updates in Telegram/…/api_updates.h and api_updates.cpp. The constructor subscribes to Main::Account::mtpUpdates() and mtpNewSessionCreated(), requests MTPupdates_GetState, and maintains global pts, date, qts, seq, timers, and channel-specific difference state. ApiWrap::applyUpdates() delegates to this manager. Updates::applyUpdates() first orders updates / updatesCombined by seq, processes users and chats into Data::Session, and then feeds individual updates through feedUpdate(). Short updates validate that referenced peers and mention users are loaded; if not, they call getDifference(). Channel updates use channel pts and channel difference requests, while global updatesTooLong and sequence/PTS gaps also fall back to difference requests. The same manager sends online/offline status via MTPaccount_UpdateStatus, saves drafts when going offline, and registers send-action, streamed draft, emoji interaction, and call speaking updates into data/history managers.

Sending is split between shared send structs in Telegram/…/api_common.h, helper functions in api_sending.cpp, media preparation in api_media.cpp, editing helpers in api_editing.cpp, and orchestration in apiwrap.cpp. Api::SendOptions carries flags such as scheduled time, send-as peer, business shortcut id, paid-stars approval, effects, caption inversion, spoilers, TTL, and suggested post metadata. Api::SendAction binds those options to a Data::Thread, derives the owning History, and builds MTProto reply data through Data::ReplyToForMTP. ApiWrap::sendMessage() creates local outgoing history items, registers random IDs in Data::Session, splits long text by the current premium message length limit, handles web page media, clears/saves drafts, sets scheduled/quick-reply/suggested/paid flags, and sends MTPmessages_SendMessage or MTPmessages_SendMedia; update application later maps updateMessageID back to the local item. api_sending.cpp provides paths for existing photos/documents, music selections, dice, locations, venues, and confirmed files, and uses FillMessagePostFlags() to keep local MessageFlags aligned with outgoing MTProto flags. ApiWrap::sendFiles() and editMedia() enqueue FileLoadTasks on _fileLoader; when uploads complete, sendUploadedPhoto() / sendUploadedDocument() use api_media.cpp to build uploaded photo/document input media and either send a single media request or add it to an album.

Message editing uses the same send model but converts it to MTPmessages_EditMessage in Telegram/…/api_editing.cpp. EditTextMessage(), EditCaption(), EditRichMessage(), EditTodoList(), and uploaded-media edit helpers compute edit flags for text, media, entities, web page removal/inversion, schedule dates, business shortcut IDs, and rich messages. Suggested-post edits are special: SuggestMessage() / SuggestMedia() may send a new suggested reply with MTPmessages_SendMedia rather than editing the original item. Edit request IDs are also remapped for scheduled messages and business shortcut messages before sending.

History and search requests share parsing helpers and de-duplication. ApiWrap::requestHistory() prepares a history request, sends it through Data::Histories::sendRequest() so history loading is serialized with the data layer, parses the TL result, and appends a slice to History::messages(). ApiWrap::requestSharedMedia() prepares a messages.search-style request for a peer/topic/monoforum sublist and writes parsed results into local shared-media storage. ApiWrap::requestGlobalMedia() returns parsed global media search results through a callback. Dedicated search controllers in api_peer_search.cpp, api_messages_search.cpp, api_messages_search_merged.cpp, and api_single_message_search.h provide peer search (including sponsored peers when enabled and query length allows), paged in-chat message search with first-page caching, merged search across migrated histories, and single-message lookup from public links.

Feature-specific managers under Telegram/SourceFiles/api/ are thin but stateful adapters around MTProto and data models:

  • Account/session controls such as authorizations, attached stickers, blocked peers, cloud password, self-destruct, sensitive content, reactions notification settings, confirm phone, ringtones, user names, and websites are owned by ApiWrap and usually expose reload/update methods plus cached reactive values. api_websites.h / api_websites.cpp, for instance, load connected bot website sessions, publish list/total changes, and terminate one or all sessions, optionally blocking a bot.
  • Peer and chat management includes invite links, chat links, chat participants, communities, peer photos, peer colors, polls, todo lists, rich tasks, unread things, views/read metrics, who-reacted lists, and report flows. api_peer_photo.h manages photo/video profile uploads with per-peer progress streams, upload cancellation, emoji-markup list requests, and non-personal photo bookkeeping.
  • Privacy is split between global account settings in api_global_privacy.cpp and per-key privacy rules in api_user_privacy.cpp. Global privacy tracks auto-archive, hide-read-time, new-message premium/stars restrictions, disallowed gift types, and paid-reaction identity; per-key privacy translates local allow/deny exceptions for users, chats, premium users, and bots into TL privacy rules.
  • Premium, credits, earn, and statistics APIs translate payment/statistics TL responses into data-layer structs. api_premium.cpp loads premium promo text, subscription options, premium videos/stickers/cloud/hello sticker sets, gift code and giveaway data, and message-money restrictions. api_credits.h / api_credits.cpp cover credit top-up/giveaway options, star transaction history, subscriptions, earn statistics, and saved-star-gift input conversion. api_statistics_sender.h registers statistics requests with ApiWrap and shifts them to the stats DC; api_statistics.cpp deserializes broadcast/supergroup/message/story/earn/boost statistics into Data::Statistics* models and queues async graph zoom loads.
  • AI, transcription, premium-adjacent and business-style helpers include api_compose_with_ai.h / .cpp for AI compose requests and diff parsing, api_transcribes.* for voice transcription state, sendShortcutMessages() in apiwrap.cpp for business quick replies, and BusinessShortcutId / shortcutId propagation through SendOptions, local message flags, update handling, and edit flags.

Coupling

  • If Api::SendOptions or Api::SendAction in Telegram/…/api_common.h gains a user-visible send option, update every flag-building path that mirrors it: ApiWrap::sendMessage() and sendRichMessage() in apiwrap.cpp, SendSimpleMedia() / SendExistingMedia() / FillMessagePostFlags() in api_sending.cpp, upload completion in api_media.cpp if it affects input media, and ComputeEditMessageFlags() in api_editing.cpp. These paths separately construct local MessageFlags and MTProto flags; missing one path causes local history state to disagree with the server request.
  • If message random-ID handling changes in ApiWrap::sendMessage() or media sending in apiwrap.cpp, verify Api::Updates::feedUpdate() in api_updates.cpp. updateMessageID uses Data::Session::messageIdByRandomId() and messageSentData() to replace local IDs, apply scheduled/business shortcut sends, update topics/saved sublists, and unregister sent metadata.
  • If update sequencing or PTS behavior changes in api_updates.cpp, check both global and channel flows. Updates::applyUpdates() gates by seq; feedUpdate() chooses between global updateAndApply(), channel ptsUpdateAndApply(), applyUpdateNoPtsCheck(), and getDifference(). A change that only handles global PTS can silently break channel histories.
  • If history/search result parsing changes, keep ApiWrap::requestHistory(), ApiWrap::requestSharedMedia(), ApiWrap::requestGlobalMedia(), and Api::MessagesSearch::searchReceived() aligned. They all process TL users/chats/messages into Data::Session, but write results to different consumers (History::messages(), shared-media storage, callback results, or search event streams).
  • If privacy keys or rules are added, update both directions in api_user_privacy.cpp: KeyToTL() for outgoing requests and TLToKey() / TLToRules() for updates and reloads. UserPrivacy::apply() is called from update handling as well as explicit reloads, so missing reverse mapping leaves UI caches stale even if saving works.
  • If statistics request routing changes, verify both ApiWrap::registerStatsRequest() / unregisterStatsRequest() in apiwrap.cpp and StatisticsRequestSender::makeRequest() in api_statistics_sender.h. Statistics requests can be shifted to a stats DC and overridden with a preallocated request id; the wrapper tracks them separately so session teardown and DC routing remain consistent.

Risks

  • Telegram/…/api_updates.cpp is a high-fragility choke point: it interleaves global seq ordering, global PTS, channel PTS, difference retries, online/offline status, send-action updates, scheduled-message conversion, and local-ID reconciliation. If a new update type is applied without the right PTS path, histories can miss messages until a full difference is requested, or local outgoing messages can remain with temporary IDs.
  • Telegram/…/apiwrap.cpp and Telegram/…/api_sending.cpp duplicate send-flag decisions for text, existing media, uploaded media, rich messages, albums, scheduled sends, quick replies, suggested posts, paid messages, and ephemeral/bot commands. If a new send option is added to only one path, users can see a locally rendered outgoing message that does not match what was sent to MTProto.
  • Telegram/…/api_editing.cpp reuses sending semantics but has separate request-id remapping for scheduled and business shortcut messages. If EditMessageRequestId() or ComputeEditMessageFlags() falls behind send-model changes, edits may target the wrong server object or omit required flags for scheduled/shortcut/rich-message edits.
  • Telegram/…/api_statistics_sender.cpp unregisters stats requests by polling _api.pending() and on destruction. If a statistics request is created without makeRequest() or without the overridden id/DC shift, ApiWrap will not know about the stats DC request and session-level stats cleanup can become inaccurate.