// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL // KOutNet - the Telegram transport, on TDLib. #pragma once #include "core/backend/ChatBackend.h" #include "core/chat/ChatAddress.h" #include #include #include #include #include namespace koutnet { // Q_ENUM_NS, because the login page reads the state and a QML-side copy of the // numbering is one more place for the two to drift apart. Q_NAMESPACE class TelegramClient; // Telegram's own vocabulary, which the window has no business knowing: what the // account is waiting for, and what a TDLib message turned into here. enum class TelegramAuthState { Stopped = 0, NeedApiCredentials = 1, NeedPhoneNumber = 2, NeedCode = 3, NeedPassword = 4, // Signed in. The only state in which anything is sent or received. Ready = 5, Failed = 6, }; class TelegramBackend : public ChatBackend { Q_OBJECT public: explicit TelegramBackend(QObject *parent = nullptr); ~TelegramBackend() override; // apiId and apiHash are the credentials my.telegram.org issues for an Q_INVOKABLE void start(const QJsonObject &apiCredentials); Q_INVOKABLE void stop(); // What the account is waiting for. The window asks this on its own rather // than being pushed to, because a login page that opens onto a state it has // already left is a page that shows the wrong question. Q_PROPERTY(int authState READ authStateValue NOTIFY authStateChanged) Q_PROPERTY(QString qrCodeUrl READ qrCodeUrl NOTIFY authStateChanged) // What Telegram refused, in its own words: a wrong code, a flood wait. Sent // through request() rather than send(), which throws the answer away. Q_PROPERTY(QString authError READ authError NOTIFY authErrorChanged) Q_PROPERTY(QString ownDisplayName READ ownDisplayName NOTIFY ownUserChanged) Q_PROPERTY(QString ownUsername READ ownUsername NOTIFY ownUserChanged) Q_PROPERTY(QString ownAvatarUrl READ ownAvatarUrl NOTIFY ownUserChanged) // The state as a number, for QML. The enum itself is the truth; this is // only how it crosses into a language that has no other way to say it. int authStateValue() const { return static_cast(m_authState); } QString authError() const { return m_authError; } // The telegram link the app shows for the QR login, which is empty whenever // the app is not waiting for one. QString qrCodeUrl() const { return m_qrCodeUrl; } QString ownDisplayName() const; QString ownUsername() const; QString ownAvatarUrl() const; Q_INVOKABLE void sendPhoneNumber(const QString &phoneNumber); Q_INVOKABLE void sendCode(const QString &code); Q_INVOKABLE void sendPassword(const QString &password); Q_INVOKABLE void requestQrCodeLogin(); // Configure network proxy for TDLib (HTTP/SOCKS5/MTProto). Applied immediately // if the client is running; also remembered for the current session. Q_INVOKABLE void applyProxy(bool enabled, int type, const QString &server, int port, const QString &username = QString(), const QString &password = QString(), const QString &secret = QString()); // Fetch recent message history for a chat on demand (e.g. when opened). // Avoids bulk-loading all chats at startup; repeated calls are throttled. Q_INVOKABLE void requestChatHistory(const QString &chatId); // Fetch older history when the user scrolls up in a chat. // fromMessageId can be provided by the UI/model when backend state was lost (e.g. after restart). Q_INVOKABLE void requestOlderChatHistory(const QString &chatId, const QString &fromMessageId = QString()); // Inform TDLib which chat is currently open in the UI. Q_INVOKABLE void setOpenedChat(const QString &chatId); Q_INVOKABLE void setClosedChat(const QString &chatId); // The highest message id this account has already read in a chat, as // Telegram reports it. Zero when the chat is unknown. Used by the window to // avoid raising a notification for backlog replayed after a restart: those // messages were read in Telegram long before KOutNet ever saw them. Q_INVOKABLE double readInbox(const QString &chatId) const; // The read point this account has on its own messages in one chat: the // highest message id the other side has read. Zero when nothing has been // read yet or the chat is unknown. Q_INVOKABLE double readOutbox(const QString &chatId) const; chatid::Transport transport() const override { return chatid::Transport::Telegram; } bool canHandle(const QString &chatId) const override { return chatid::transportOf(chatId) == chatid::Transport::Telegram; } bool isPreview() const override { #ifdef KOUTNET_HAVE_TDLIB return false; #else return true; #endif } bool serverOwnsTimeline(const QString &) const override { return true; } bool hasRooms(const QString &chatId) const override { return m_chats.contains(telegramChatId(chatId)); } // TDLib does not carry calls: a Telegram voice chat is a live stream with a // viewer count, which is a different thing from a call between two people // and is not offered as one. bool supportsCalls(const QString &) const override { return false; } bool supportsTyping(const QString &chatId) const override { return m_chats.contains(telegramChatId(chatId)); } bool supportsEdits(const QString &) const override { return true; } bool supportsReactions(const QString &chatId) const override { return canHandle(chatId) && m_authState == TelegramAuthState::Ready; } bool sendText(const QString &chatId, const QString &text) override; bool sendFile(const QString &chatId, const QString &localFilePath) override; void markRead(const QString &chatId) override; void sendTyping(const QString &chatId) override; void sendReaction(const QString &chatId, const QVariant &identifier, const QString &emoji, bool added) override; bool sendEdit(const QString &chatId, const QVariant &identifier, const QString &newText) override; bool sendDelete(const QString &chatId, const QVariant &identifier) override; bool leaveChat(const QString &chatId) override; QVariantMap roomInfo(const QString &chatId) const override; QVariantList roomMembers(const QString &chatId) const override; QVariantMap memberInfo(const QString &chatId, const QString &userId) const override; Q_SIGNALS: void roomListed(QString chatId, QString displayName, QString avatarUrl = QString(), bool isRoom = true); void roomMessage(QString chatId, QString eventId, QString text, QString sender, bool isOwn, double ts, bool isSystem, QString senderAvatar = QString(), QString senderId = QString()); void roomAttachment(QString chatId, QString eventId, QVariantMap media, QString sender, bool isOwn, double ts, QString senderAvatar = QString(), QString senderId = QString()); void roomAttachmentUpdated(QString chatId, QString eventId, QVariantMap media); void roomLeft(QString chatId); // A send the client refused before any byte left: not signed in, or the // conversation is not one this account can write to. The window reports // the reason instead of leaving the composer wondering. void sendFailed(QString chatId, QString reason); // Telegram's read point for our own side: everything of ours up to the // named message id has been read by the other side. void roomReadOutbox(QString chatId, double maxMessageId); // The state machine moved. The login page listens to this rather than // polling, so a state it never learns about is a state it cannot show. void authStateChanged(); void authErrorChanged(); void ownUserChanged(); private Q_SLOTS: void onUpdate(const QJsonObject &update); void onAuthorizationState(const QJsonObject &state); void setAuthError(const QString &error); void setAuthState(TelegramAuthState state); private: static qint64 telegramChatId(const QString &chatId); static QString chatIdFor(qint64 chatId); // Turns one TDLib message into the row the window draws, or nothing at all // for a message that is not one it can draw. void publishMessage(qint64 chatId, const QJsonObject &message); void publishChats(); void publishChat(qint64 chatId); void requestChat(qint64 chatId); void requestHistory(qint64 chatId, qint64 fromMessageId = 0); void noteReadOutbox(qint64 chatId, double maxMessageId); void handleFileUpdate(const QJsonObject &file); QString fileUrlFor(const QJsonObject &file, bool download = true, const QString &trackChatId = QString(), const QString &trackEventId = QString(), const QString &trackField = QString()) const; QString bestPhotoFileUrl(const QJsonObject &photo, bool download = true, const QString &trackChatId = QString(), const QString &trackEventId = QString(), const QString &trackField = QString()) const; void requestDownload(qint64 fileId) const; TelegramClient *m_client = nullptr; // What the client was started with, so the settings button can tell a second // press of itself from a correction. QString m_apiId; QString m_apiHash; TelegramAuthState m_authState = TelegramAuthState::Stopped; QString m_authError; QString m_qrCodeUrl; bool m_authRequestInFlight = false; bool m_wantsQrLogin = false; // chat id as a number, which is what TDLib addresses, against the display // name and picture a row needs. QHash m_chatNames; QHash m_chats; // The read point this account has on its own messages, per chat. Kept here // because history arrives per chat, possibly long after the update that // named the point, and a row ingested later must still be marked against it. QHash m_readOutbox; QHash m_userNames; QSet m_userInfoRequests; mutable QHash m_userAvatars; // The newest/oldest message seen in each chat. QHash m_newestMessage; QHash m_oldestMessage; QJsonObject m_ownUser; qint64 m_ownAvatarFileId = 0; QList m_proxyIds; struct MediaFileRef { QString chatId; QString eventId; QString field; // "url" or "thumbnail" }; mutable QHash m_filePaths; mutable QSet m_requestedFiles; mutable QHash m_chatAvatarFileId; mutable QHash m_userAvatarFileId; mutable QHash> m_mediaFileRefs; QHash m_publishedAttachmentMedia; // key: chatId + "\n" + eventId // The last row published for a chat, so an updateChatPosition that only moved // the chat's order (TDLib sends one per incoming message and per online-status // change) does not re-emit an identical roomListed and re-request the avatar. struct PublishedChat { QString name; QString avatarUrl; bool isRoom = false; bool valid = false; }; QHash m_publishedChats; QHash m_lastPublishedAvatarFileId; QHash m_historyLastRequestedMs; QSet m_historyLoading; QSet m_historyExhausted; QSet m_historyEmptyRetried; qint64 m_openedChatId = 0; }; } // namespace koutnet