Messaging Domain Controllers
Overview
This doc covers the account-scoped messaging/domain controller layer in TMessagesProj/src/main/java/org/telegram/messenger/: AccountInstance.java, BaseController.java, MessagesController.java, SendMessagesHelper.java, MessageObject.java, ChatObject.java, DialogObject.java, UserObject.java, UserConfig.java, SharedConfig.java, MediaDataController.java, ContactsController.java, DownloadController.java, TopicsController.java, ChatMessagesMetadataController.java, MemberRequestsController.java, NotificationCenter.java, Utilities.java, AndroidUtilities.java, and DispatchQueue*.java.
AccountInstance.java is the per-account service locator. Each account index has one AccountInstance, and it routes callers to the matching MessagesController, MessagesStorage, ContactsController, MediaDataController, ConnectionsManager, NotificationCenter, UserConfig, DownloadController, SendMessagesHelper, and neighboring controllers. BaseController.java is the common superclass for most owned controllers; its constructor captures the currentAccount and the account's AccountInstance, so controller methods should use getMessagesController(), getMessagesStorage(), getConnectionsManager(), and similar accessors instead of global account 0 state.
The main account state lives in MessagesController.java. It caches users, chats, encrypted chats, dialogs, dialog top messages, read maxima, printing state, privacy-like online state, blocked peers, filters, update queues, channel pts, full user/chat records, and notification preferences. MessagesController.getInstance(int) is a double-checked singleton per UserConfig.MAX_ACCOUNT_COUNT; its constructor initializes storage/location dependencies, registers for upload/load/send notifications on the UI thread, and loads account-specific SharedPreferences (Notifications, mainconfig, emoji, with account suffixes for nonzero accounts). Domain objects from the network and storage are merged through putUsers(...), putChats(...), and putChat(...); username indexes, min-user/min-chat replacement, forum flag changes, active voice-chat state, and interface notifications are handled there.
Dialog and peer routing is convention-based. DialogObject.java turns Telegram peers into dialog ids: positive ids are users, negative ids are chats/channels, 0x4000000000000000L marks encrypted dialogs, and 0x2000000000000000L marks folder dialogs. MessagesController.getInputPeer(long) and getPeer(long) use that sign convention and cached TLRPC.User/TLRPC.Chat access hashes to build API peers. MessageObject.java wraps TLRPC.Message for UI/domain use, assigns local message types (TYPE_TEXT, TYPE_PHOTO, TYPE_FILE, etc.), tracks send state (SENDING, SENT, SEND_ERROR, EDITING), computed text/caption/media metadata, dialog ids, reply objects, file existence, reactions, and scheduled/preview state. ChatObject.java centralizes chat/channel kind checks and send/admin permission predicates; UserObject.java centralizes deleted/self/reply/contact checks, display names, public username lookup, photos, and emoji status ids.
The outbound send flow is coordinated by SendMessagesHelper.java. Public overloads normalize text, media, contact, poll, invoice, game, location, forward, retry, screenshot, scheduled, and secret-chat sends into the private sendMessage(...) pipeline. That pipeline creates a local TLRPC.Message with a negative id from UserConfig.getNewMessageId(), assigns a random_id, wraps it in MessageObject, persists it through MessagesStorage.putMessages(...), updates MessagesController.updateInterfaceWithMessages(...), posts dialogsNeedReload, and then builds the matching RPC (TL_messages_sendMessage, TL_messages_sendMedia, TL_messages_sendMultiMedia, inline bot send, or encrypted request). Media that needs upload is parked in DelayedMessage structures keyed by local file/http paths; SendMessagesHelper listens to fileUploaded, fileUploadProgressChanged, fileUploadFailed, filePreparing*, httpFileDidLoad, and fileLoaded events and resumes or fails the pending request when the file/thumbnail/video conversion is ready. Successful server responses are fed back through MessagesController.processUpdates(...); failures mark storage send error and post messageSendError.
The inbound/update flow also terminates in MessagesController.java. processUpdates(...) handles short updates, combined updates, pts/qts/seq ordering, channel-specific pts, missing min users/chats, unknown dialogs/channels, and holes that require getDifference(). Valid updates are grouped and passed to processUpdateArray(...), which resolves users/chats from the update payload, in-memory maps, or MessagesStorage, then builds MessageObject instances for new/scheduled messages, updates read/delete/content state, typing state, reactions, replies, polls, web pages, folders, contacts, and topics. New message objects are stored with MessagesStorage.putMessages(...), UI state is updated on the main thread, NotificationCenter events such as didReceiveNewMessages, dialogsNeedReload, messagesDeleted, updateInterfaces, and media/reaction events are posted, and NotificationsController is invoked for push/in-app notification fan-out.
Dialog loading is split between cache and network in MessagesController.loadDialogs(...). Cache loads go through MessagesStorage.getDialogs(...); network loads build TL_messages_getDialogs offsets from UserConfig.getDialogLoadOffsets(...) or the last non-pinned top message, process the result via processLoadedDialogs(...), and maintain end/offset state. Unknown dialogs and channels are recovered with messages.getPeerDialogs from loadUnknownDialog(...) and loadUnknownChannel(...), with pending tasks persisted in MessagesStorage for retry.
Specialized controllers own adjacent domain state. MediaDataController.java loads draft preferences on construction, owns drafts/reply drafts, stickers, recent GIFs/stickers, reactions, emoji statuses/themes, attach-menu bots, premium promos, ringtone data, and posts events such as recentDocumentsDidLoad, stickersDidLoad, reactionsDidLoad, and draft-related reloads; SendMessagesHelper calls MediaDataController.cleanDraft(...) after successful new sends. ContactsController.java owns Telegram contacts, phone book snapshots, contact sections, Android contacts observation, contact import/sync, add/delete contact RPCs, blocked/privacy-like rules, global privacy settings, and posts contactsDidLoad and privacyRulesUpdated. DownloadController.java owns auto-download presets, per-type download queues, loading-file observers, unviewed/recent downloads, and receives file/http load progress events before notifying observers and onDownloadingFilesChanged. TopicsController.java owns forum topic lists/maps per chat, cache/network loading via channels.getForumTopics, topic offsets in UserConfig preferences, topic create/edit/delete/pin/close/show state, storage persistence, and topicsDidLoaded fan-out. MemberRequestsController.java caches the first page of join request importers per chat and updates ChatFull.requests_pending on TL_updatePendingJoinRequests. ChatMessagesMetadataController.java is chat-UI scoped rather than account-singleton: it checks visible ChatActivity messages for stale reactions/extended media metadata, issues messages.getMessagesReactions/messages.getExtendedMedia, then routes responses back into MessagesController.processUpdates(...).
Eventing and threading are explicit. NotificationCenter.java has one instance per account plus a global instance; events are integer constants, observers implement NotificationCenterDelegate, and posting/observer mutation is expected on the main thread in debug builds. It delays notifications during transition animations unless an event is allowed, tracks heavy-operation stop/start flags through the global center, debounces updateInterfaces in debug builds, and defers observer add/remove while broadcasting. AndroidUtilities.runOnUIThread(...) posts to ApplicationLoader.applicationHandler; Utilities.java owns long-lived background DispatchQueues (stageQueue, globalQueue, cacheClearQueue, searchQueue, phoneBookQueue, themeQueue, externalNetworkQueue) plus parsing/crypto/hash helpers. DispatchQueue.java is a named Thread with its own Looper and Handler; DispatchQueuePool.java and DispatchQueuePoolBackground.java multiplex short tasks across temporary dispatch queues and recycle idle queues after 30 seconds.
Configuration is split by account and global scope. UserConfig.java is per-account and stores the current user, client user id, negative local message id counter, contacts/drafts/filter flags, notification-load flags, dialog load offsets, billing wait state, sticker pack timestamps, password cache, and save-to-gallery exceptions; saveConfig(...) writes account preferences on NotificationCenter.doOnIdle(...) and also calls SharedConfig.saveConfig(). SharedConfig.java is process/global user configuration for passcode, push token/auth key, media and UI behavior, proxy/app update data, storage paths, performance/device flags, and local ids. MessagesController.java, DownloadController.java, and MediaDataController.java read many limits and feature switches from these config classes and account SharedPreferences.
Coupling
- If dialog id encoding changes in DialogObject.java, update every peer/message route that assumes positive=user and negative=chat/channel:
MessagesController.getInputPeer(long),MessagesController.getPeer(long),SendMessagesHelper.sendMessage(...),TopicsControllercalls using-chatId/-dialogId,MemberRequestsController.getImporters(...), andChatMessagesMetadataController.load*ForMessages(...). - If
UserConfig.getNewMessageId()orSharedConfig.getLastLocalId()local id ranges change, verify SendMessagesHelper.java,MessagesController.dialogMessagesByIds, resend/error handling, and storage replacement paths; outgoing messages rely on negative ids untilmessageReceivedByServer/updates replace them with server ids. - If a new send media type or message type is added in MessageObject.java, update
SendMessagesHelper.sendMessage(...)request construction, delayed upload handling,DownloadControllertype/queue classification if it can be downloaded, andMessagesController.processUpdateArray(...)UI/update masks if the type changes dialog appearance. - If NotificationCenter.java adds or changes an event's argument contract, update both posters and observers. This module has many raw
Object...event payloads (messageReceivedByServer,messageSendError,dialogsNeedReload,topicsDidLoaded, file load/upload events), so argument drift will compile but fail at runtime. - If
MessagesController.processUpdates(...)pts/qts/seq validation changes, verifySendMessagesHelper.performSendMessageRequest(...),ChatMessagesMetadataController, chat/admin RPC methods in MessagesController.java, andTopicsControllerupdate hooks; all route serverUpdatesback into the same ordering/difference machinery. - If
MessagesController.putUser/putChat/putUsers/putChatsmerge rules change, checkMediaDataController,TopicsController,ContactsController, and dialog loading. These controllers often persist users/chats throughMessagesStorage.putUsersAndChats(...)and then refresh the in-memory controller cache separately. - If file upload/load notifications change, update
SendMessagesHelper.didReceivedNotification(...)andDownloadController.didReceivedNotification(...)together. Both listen tofileUploaded,fileUploadFailed, progress, and HTTP/file load events but interpret them differently: one resumes delayed sends, the other informs download observers and queues. - If
UserConfigpreference keys for dialog offsets, pinned-dialog loaded state, notification flags, or account suffixes change, verifyMessagesController.loadDialogs(...), notification settings load,TopicsControllerload offsets/end flags, andDownloadControllerauto-download config timestamps. - If background queue semantics change in DispatchQueue.java, Utilities.java, or DispatchQueuePool*.java, audit callers that assume main-thread callbacks after background work:
ContactsControllerphone-book sync,MessagesControllerread tasks/update queues,NotificationCenter.doOnIdle(...), and storage callbacks that post back withAndroidUtilities.runOnUIThread(...).
Risks
- NotificationCenter.java uses untyped integer event ids and
Object...payloads. If a poster changes the argument order for events such asmessageReceivedByServer,topicsDidLoaded, or file upload/load events, observers in MessagesController.java, SendMessagesHelper.java, DownloadController.java, and UI code will cast the wrong object at runtime rather than fail compilation. - MessagesController.java update ordering is fragile around pts/qts/seq holes:
processUpdates(...)queues updates for only a short wait beforegetDifference(), andprocessUpdateArray(...)returnsfalsewhen required users/chats are missing. If a new update path skipsputUsersAndChats(...)or min-entity resolution, message delivery can stall into repeated difference fetches or drop UI updates. - SendMessagesHelper.java delayed media sends are keyed by local path/http strings in
delayedMessages. If media conversion/upload code changesattachPath, thumbnail paths, or HTTP cache keys without updating delayed-message maps, sends can remain stuck in uploading state or be failed byfileUploadFailedfor the wrong local message. MessagesController.getInputPeer(long)in MessagesController.java depends on in-memoryusers/chatshaving valid access hashes. Calling it for a user/channel beforeputUsers(...)/putChats(...)or storage recovery can produce an input peer with missing access hash and fail downstream RPCs in SendMessagesHelper.java, TopicsController.java, or MemberRequestsController.java.