// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL #include "TelegramBackend.h" #include "TelegramClient.h" #include #include #include #include #include #include #include #include #include #include #include namespace koutnet { namespace { // TDLib leaves fields out rather than sending them empty, and a chat with no // description is not an error, so the reads are this short. QString textField(const QJsonObject &o, const char *key) { return o.value(QString::fromLatin1(key)).toString(); } QJsonObject objectField(const QJsonObject &o, const char *key) { return o.value(QString::fromLatin1(key)).toObject(); } qint64 intField(const QJsonObject &o, const char *key) { // TDLib's JSON interface encodes int53 fields (chat ids, message ids) as JSON const QJsonValue value = o.value(QString::fromLatin1(key)); if (value.isString()) return value.toString().toLongLong(); return static_cast(value.toDouble()); } // The user behind a message or a member entry. Telegram names the sender by a QString displayNameFor(const QJsonObject &user) { if (user.isEmpty()) return {}; const QString first = textField(user, "first_name"); const QString last = textField(user, "last_name"); const QString joined = QString(first + QLatin1Char(' ') + last).trimmed(); return joined.isEmpty() ? textField(user, "username") : joined; } QString localPathFromFile(const QJsonObject &file) { const QJsonObject local = objectField(file, "local"); if (local.value(QStringLiteral("is_downloading_completed")).toBool(false)) { const QString path = textField(local, "path"); if (!path.isEmpty()) return path; } return {}; } enum class ChatListVisibility { Show, Hide, Unknown, }; ChatListVisibility mainChatListVisibility(const QJsonObject &chat) { // TDLib delivers a chat's list membership in two steps: updateNewChat often const QJsonArray positions = chat.value(QStringLiteral("positions")).toArray(); if (positions.isEmpty()) return ChatListVisibility::Unknown; // defer until a position arrives bool mainKnown = false; // a chatListMain entry is present, whatever its order bool inMain = false; // present in chatListMain with a non-zero order for (const QJsonValue &value : positions) { const QJsonObject pos = value.toObject(); const QString listType = textField(objectField(pos, "list"), "@type"); const qint64 order = intField(pos, "order"); if (listType == QLatin1String("chatListMain")) { mainKnown = true; if (order != 0) inMain = true; } } // Positive membership in the main list is the only thing that shows a chat. if (inMain) return ChatListVisibility::Show; // A chatListMain entry with order 0 is TDLib saying the chat left the main // list (archived, folder-only, or gone): a definite hide. if (mainKnown) return ChatListVisibility::Hide; // Positions exist but say nothing about the main list (archive/folder only). // Not shown, but this is a known state, so it is a hide rather than a defer. return ChatListVisibility::Hide; } // Merge a freshly received chat object into a cached one without losing the QJsonObject mergeChat(const QJsonObject &existing, const QJsonObject &incoming) { QJsonObject merged = incoming; const QJsonArray incomingPositions = incoming.value(QStringLiteral("positions")).toArray(); if (incomingPositions.isEmpty()) { const QJsonArray existingPositions = existing.value(QStringLiteral("positions")).toArray(); if (!existingPositions.isEmpty()) merged.insert(QStringLiteral("positions"), existingPositions); } return merged; } } // namespace TelegramBackend::TelegramBackend(QObject *parent) : ChatBackend(parent) { } TelegramBackend::~TelegramBackend() { stop(); } qint64 TelegramBackend::telegramChatId(const QString &chatId) { // tg:1234 is what the window carries; 1234 is what TDLib addresses. bool ok = false; const qint64 id = chatid::telegramChatKey(chatId).toLongLong(&ok); return ok ? id : 0; } QString TelegramBackend::chatIdFor(qint64 chatId) { return chatid::telegramChatId(QString::number(chatId)); } void TelegramBackend::start(const QJsonObject &apiCredentials) { const QString apiId = textField(apiCredentials, "api_id"); const QString apiHash = textField(apiCredentials, "api_hash"); if (apiId.isEmpty() || apiHash.isEmpty()) { // Said rather than started: TDLib would sit at "waiting for parameters" // for ever, and a login page with no question on it is a dead end. setAuthError({}); setAuthState(TelegramAuthState::NeedApiCredentials); return; } // The same pair twice is the button being pressed twice. A different pair // is a correction, and TDLib only reads its parameters once, so the client // is taken down and brought up again for it to take effect. if (m_client != nullptr) { if (m_apiId == apiId && m_apiHash == apiHash) return; stop(); } m_apiId = apiId; m_apiHash = apiHash; setAuthState(TelegramAuthState::Stopped); m_client = new TelegramClient(this); connect(m_client, &TelegramClient::update, this, &TelegramBackend::onUpdate); const QString database = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QStringLiteral("/tdlib"); m_client->start(apiId.toUInt(), apiHash.toLatin1(), database); // Apply proxy settings if provided. if (apiCredentials.value(QStringLiteral("proxy_enabled")).toBool(false)) { applyProxy(true, apiCredentials.value(QStringLiteral("proxy_type")).toInt(0), textField(apiCredentials, "proxy_server"), apiCredentials.value(QStringLiteral("proxy_port")).toInt(8080), textField(apiCredentials, "proxy_username"), textField(apiCredentials, "proxy_password"), textField(apiCredentials, "proxy_secret")); } else { // Ensure no stale proxies remain in a fresh client session. applyProxy(false, 0, QString(), 0); } } void TelegramBackend::stop() { if (m_client == nullptr) return; m_client->stop(); m_client->deleteLater(); m_client = nullptr; m_authRequestInFlight = false; m_chats.clear(); m_chatNames.clear(); m_userNames.clear(); m_userInfoRequests.clear(); m_userAvatars.clear(); m_newestMessage.clear(); m_oldestMessage.clear(); m_readOutbox.clear(); m_filePaths.clear(); m_requestedFiles.clear(); m_chatAvatarFileId.clear(); m_userAvatarFileId.clear(); m_mediaFileRefs.clear(); m_publishedAttachmentMedia.clear(); m_historyLastRequestedMs.clear(); m_historyLoading.clear(); m_historyExhausted.clear(); m_historyEmptyRetried.clear(); m_openedChatId = 0; m_proxyIds.clear(); m_qrCodeUrl.clear(); m_wantsQrLogin = false; m_apiId.clear(); m_apiHash.clear(); m_ownAvatarFileId = 0; if (!m_ownUser.isEmpty()) { m_ownUser = {}; Q_EMIT ownUserChanged(); } setAuthState(TelegramAuthState::Stopped); } void TelegramBackend::onUpdate(const QJsonObject &update) { const QString type = textField(update, "@type"); if (type == QLatin1String("updateAuthorizationState")) { const QJsonObject state = objectField(update, "authorization_state"); onAuthorizationState(state); return; } // Response to getAuthorizationState() or similar when delivered as an update. if (type.startsWith(QLatin1String("authorizationState"))) { onAuthorizationState(update); return; } if (type == QLatin1String("updateFile")) { handleFileUpdate(objectField(update, "file")); return; } if (type == QLatin1String("updateUser")) { const QJsonObject user = objectField(update, "user"); const qint64 userId = intField(user, "id"); m_userInfoRequests.remove(userId); m_userNames.insert(userId, displayNameFor(user)); const QJsonObject profilePhoto = objectField(user, "profile_photo"); if (!profilePhoto.isEmpty()) { const QJsonObject small = objectField(profilePhoto, "small"); const qint64 fid = intField(small, "id"); if (fid > 0) m_userAvatarFileId.insert(userId, fid); const QString avatarUrl = fileUrlFor(small, true); if (!avatarUrl.isEmpty()) m_userAvatars.insert(userId, avatarUrl); } if (!m_ownUser.isEmpty() && userId == intField(m_ownUser, "id")) { m_ownUser = user; m_ownAvatarFileId = 0; if (!profilePhoto.isEmpty()) { const qint64 fid = intField(objectField(profilePhoto, "small"), "id"); if (fid > 0) m_ownAvatarFileId = fid; } Q_EMIT ownUserChanged(); } return; } if (type == QLatin1String("updateNewChat")) { const QJsonObject chat = objectField(update, "chat"); const qint64 id = intField(chat, "id"); if (id != 0) { m_chats.insert(id, mergeChat(m_chats.value(id), chat)); noteReadOutbox(id, chat.value(QStringLiteral("last_read_outbox_message_id")).toDouble()); publishChat(id); } return; } if (type == QLatin1String("updateChat")) { const QJsonObject chat = objectField(update, "chat"); const qint64 id = intField(chat, "id"); m_chats.insert(id, mergeChat(m_chats.value(id), chat)); noteReadOutbox(id, chat.value(QStringLiteral("last_read_outbox_message_id")).toDouble()); publishChat(id); return; } if (type == QLatin1String("updateChatPhoto")) { const qint64 id = intField(update, "chat_id"); if (id != 0 && m_chats.contains(id)) { QJsonObject chat = m_chats.value(id); chat.insert(QStringLiteral("photo"), update.value(QStringLiteral("photo"))); m_chats.insert(id, chat); publishChat(id); } return; } if (type == QLatin1String("updateChatReadOutbox")) { // The far side read something of ours. The id, not a stamp, is what // TDLib names, so the window marks its rows by id against it. const qint64 chatId = intField(update, "chat_id"); noteReadOutbox(chatId, update.value(QStringLiteral("read_outbox_max_message_id")).toDouble()); return; } if (type == QLatin1String("updateChatReadInbox")) { // Our own read point moved, either because we called viewMessages or // because the chat was read in another Telegram client. Keep it in the // cached chat so readInbox() can tell backlog from genuinely new mail. const qint64 chatId = intField(update, "chat_id"); if (chatId != 0 && m_chats.contains(chatId)) { QJsonObject chat = m_chats.value(chatId); chat.insert(QStringLiteral("last_read_inbox_message_id"), update.value(QStringLiteral("last_read_inbox_message_id"))); chat.insert(QStringLiteral("unread_count"), update.value(QStringLiteral("unread_count"))); m_chats.insert(chatId, chat); publishChat(chatId); } return; } if (type == QLatin1String("updateNewMessage")) { const QJsonObject message = objectField(update, "message"); publishMessage(intField(message, "chat_id"), message); return; } if (type == QLatin1String("updateMessageContent")) { const qint64 chatId = intField(update, "chat_id"); const qint64 messageId = intField(update, "message_id"); if (chatId != 0 && messageId != 0 && m_client != nullptr) { m_client->request(QJsonObject{{QStringLiteral("@type"), QStringLiteral("getMessage")}, {QStringLiteral("chat_id"), chatId}, {QStringLiteral("message_id"), messageId}}, [this](const QJsonObject &message, const QString &error) { if (!error.isEmpty() || message.isEmpty()) return; publishMessage(intField(message, "chat_id"), message); }); } return; } if (type == QLatin1String("updateChatLastMessage")) { const qint64 chatId = intField(update, "chat_id"); const QJsonObject lastMessage = objectField(update, "last_message"); if (chatId != 0) { if (m_chats.contains(chatId)) { QJsonObject chat = m_chats.value(chatId); chat.insert(QStringLiteral("last_message"), update.value(QStringLiteral("last_message"))); if (update.contains(QStringLiteral("positions"))) chat.insert(QStringLiteral("positions"), update.value(QStringLiteral("positions"))); m_chats.insert(chatId, chat); publishChat(chatId); } else { requestChat(chatId); } // Publish last message so chat previews/new activity can update, // but avoid creating a "history of one message" impression; full // history is requested when the chat is opened. if (!lastMessage.isEmpty()) publishMessage(chatId, lastMessage); } return; } if (type == QLatin1String("updateChatPosition")) { const qint64 chatId = intField(update, "chat_id"); const QJsonObject position = objectField(update, "position"); if (chatId != 0 && m_chats.contains(chatId) && !position.isEmpty()) { QJsonObject chat = m_chats.value(chatId); QJsonArray positions = chat.value(QStringLiteral("positions")).toArray(); const QString posListType = textField(objectField(position, "list"), "@type"); bool replaced = false; for (int i = 0; i < positions.size(); ++i) { const QJsonObject p = positions.at(i).toObject(); if (textField(objectField(p, "list"), "@type") == posListType) { positions[i] = position; replaced = true; break; } } if (!replaced) positions.append(position); chat.insert(QStringLiteral("positions"), positions); m_chats.insert(chatId, chat); publishChat(chatId); } else if (chatId != 0 && !m_chats.contains(chatId)) { requestChat(chatId); } return; } if (type == QLatin1String("updateNewChatList")) { publishChats(); return; } } void TelegramBackend::onAuthorizationState(const QJsonObject &state) { const QString stateType = textField(state, "@type"); if (stateType == QLatin1String("authorizationStateWaitTdlibParameters")) { // The parameters went out when the client was started; TDLib asking for // them again means it did not get them, and there is nothing to do here // but wait: it will ask once more if they are on their way. return; } if (stateType == QLatin1String("authorizationStateWaitPhoneNumber") || stateType == QLatin1String("authorizationStateWaitRegistration")) { setAuthState(TelegramAuthState::NeedPhoneNumber); return; } if (stateType == QLatin1String("authorizationStateWaitQrCodeAuthentication")) { // The link the app shows. Empty until TDLib sends one, which is why this // is read rather than composed here. const QString url = textField(objectField(state, "qr_code"), "url"); const QString oldQr = m_qrCodeUrl; if (!url.isEmpty()) { m_qrCodeUrl = url; // QR flow is active; keep refreshing automatically if the token expires. m_wantsQrLogin = true; } setAuthState(TelegramAuthState::NeedPhoneNumber); if (m_qrCodeUrl != oldQr) Q_EMIT authStateChanged(); return; } if (stateType == QLatin1String("authorizationStateWaitOtherDeviceConfirmation")) { // TDLib provides a tg:// login link for QR/device confirmation. const QString link = textField(state, "link"); const QString oldQr = m_qrCodeUrl; if (!link.isEmpty()) { m_qrCodeUrl = link; // Treat an offered device-confirmation link as an active QR/device login flow. m_wantsQrLogin = true; } // Keep in a state where the login page remains usable (phone flow also possible). setAuthState(TelegramAuthState::NeedPhoneNumber); if (m_qrCodeUrl != oldQr) Q_EMIT authStateChanged(); // TDLib can refresh/expire the confirmation link; if QR login is active, keep it fresh. if (m_wantsQrLogin && link.isEmpty()) { QTimer::singleShot(500, this, [this] { if (m_wantsQrLogin && m_client != nullptr && m_authState == TelegramAuthState::NeedPhoneNumber && m_qrCodeUrl.isEmpty() && !m_authRequestInFlight) requestQrCodeLogin(); }); } return; } if (stateType == QLatin1String("authorizationStateWaitCode")) { setAuthState(TelegramAuthState::NeedCode); return; } if (stateType == QLatin1String("authorizationStateWaitPassword")) { setAuthState(TelegramAuthState::NeedPassword); return; } if (stateType == QLatin1String("authorizationStateReady")) { setAuthError({}); setAuthState(TelegramAuthState::Ready); qWarning() << "TelegramBackend: authorizationStateReady, starting chat list load"; // A signed-in session is worth nothing until the chat list is in it. if (m_client != nullptr) { const auto batchesLoaded = std::make_shared(0); const auto loadMoreChats = std::make_shared>(); *loadMoreChats = [this, loadMoreChats, batchesLoaded]() { if (m_client == nullptr || m_authState != TelegramAuthState::Ready) { qWarning() << "TelegramBackend: loadChats aborted (client/state)" << (m_client != nullptr) << static_cast(m_authState); return; } if (*batchesLoaded >= 4) { // initial ~200 chats max qWarning() << "TelegramBackend: initial chat list load capped after" << *batchesLoaded << "batches, cached chats:" << m_chats.size(); return; } qWarning() << "TelegramBackend: sending loadChats batch" << (*batchesLoaded + 1); m_client->request(QJsonObject{{QStringLiteral("@type"), QStringLiteral("loadChats")}, {QStringLiteral("chat_list"), QJsonObject{{QStringLiteral("@type"), QStringLiteral("chatListMain")}}}, {QStringLiteral("limit"), 50}}, [this, loadMoreChats, batchesLoaded](const QJsonObject &result, const QString &error) { if (!error.isEmpty()) { // TDLib returns 404/"Not Found" when all chats are loaded. qWarning() << "TelegramBackend: chat list load finished:" << error << "cached chats:" << m_chats.size(); return; } ++(*batchesLoaded); qWarning() << "TelegramBackend: loadChats batch ok, batches=" << *batchesLoaded << "cached chats:" << m_chats.size() << "result=" << textField(result, "@type"); // Continue loading initial batches with a small delay to reduce UI/TDLib spikes. QTimer::singleShot(250, this, [loadMoreChats]() { (*loadMoreChats)(); }); }); }; (*loadMoreChats)(); // the account's own id, so its own messages are // recognised as its own rather than as a // stranger's. m_client->request(QJsonObject{{QStringLiteral("@type"), QStringLiteral("getMe")}}, [this](const QJsonObject &me, const QString &) { if (me.isEmpty()) return; m_ownUser = me; m_ownAvatarFileId = 0; const QJsonObject profilePhoto = objectField(me, "profile_photo"); if (!profilePhoto.isEmpty()) { const qint64 fid = intField(objectField(profilePhoto, "small"), "id"); if (fid > 0) m_ownAvatarFileId = fid; } Q_EMIT ownUserChanged(); }); } return; } if (stateType == QLatin1String("authorizationStateClosed")) { setAuthState(TelegramAuthState::Stopped); return; } if (stateType == QLatin1String("authorizationStateLoggingOut") || stateType == QLatin1String("authorizationStateClosing")) { setAuthState(TelegramAuthState::Stopped); } } void TelegramBackend::setAuthState(TelegramAuthState state) { if (m_authState == state) return; m_authState = state; // A state transition means the previous auth step finished (or became irrelevant). m_authRequestInFlight = false; // If we've moved past the phone/QR entry point to code/password/ready, stop auto-requesting QR. if (state == TelegramAuthState::NeedCode || state == TelegramAuthState::NeedPassword || state == TelegramAuthState::Ready || state == TelegramAuthState::Stopped || state == TelegramAuthState::NeedApiCredentials) { m_wantsQrLogin = false; } Q_EMIT authStateChanged(); } void TelegramBackend::setAuthError(const QString &error) { // QR login tokens expire; automatically request a fresh QR when the user opted into QR login. if (m_wantsQrLogin && !error.isEmpty() && error.contains(QLatin1String("AUTH_TOKEN_EXPIRED"), Qt::CaseInsensitive) && m_authState == TelegramAuthState::NeedPhoneNumber) { // Avoid spamming the UI with the same transient error while refreshing. if (!m_authError.isEmpty()) { m_authError.clear(); Q_EMIT authErrorChanged(); } QTimer::singleShot(500, this, [this] { if (m_wantsQrLogin && m_client != nullptr && m_authState == TelegramAuthState::NeedPhoneNumber && !m_authRequestInFlight) requestQrCodeLogin(); }); return; } if (m_authError == error) return; m_authError = error; Q_EMIT authErrorChanged(); } // The three answers a person gives are refused in the same way, and a refusal // is all Telegram says about a wrong code, a wrong password or a flood wait. A // form that waits for the next state instead is a form that never explains. void TelegramBackend::sendPhoneNumber(const QString &phoneNumber) { if (m_client == nullptr || m_authRequestInFlight) return; if (m_authState != TelegramAuthState::NeedPhoneNumber) return; const QString trimmed = phoneNumber.trimmed(); if (trimmed.isEmpty()) return; m_wantsQrLogin = false; m_authRequestInFlight = true; setAuthError({}); m_client->request(QJsonObject{{QStringLiteral("@type"), QStringLiteral("setAuthenticationPhoneNumber")}, {QStringLiteral("phone_number"), trimmed}}, [this](const QJsonObject &, const QString &error) { m_authRequestInFlight = false; if (!error.isEmpty()) setAuthError(error); }); } void TelegramBackend::sendCode(const QString &code) { if (m_client == nullptr || m_authRequestInFlight) return; if (m_authState != TelegramAuthState::NeedCode) return; const QString trimmed = code.trimmed(); if (trimmed.isEmpty()) return; m_authRequestInFlight = true; setAuthError({}); m_client->request(QJsonObject{{QStringLiteral("@type"), QStringLiteral("checkAuthenticationCode")}, {QStringLiteral("code"), trimmed}}, [this](const QJsonObject &, const QString &error) { m_authRequestInFlight = false; if (!error.isEmpty()) { setAuthError(error); } }); } void TelegramBackend::sendPassword(const QString &password) { if (m_client == nullptr || m_authRequestInFlight) return; if (m_authState != TelegramAuthState::NeedPassword) return; if (password.isEmpty()) return; m_authRequestInFlight = true; setAuthError({}); m_client->request(QJsonObject{{QStringLiteral("@type"), QStringLiteral("checkAuthenticationPassword")}, {QStringLiteral("password"), password}}, [this](const QJsonObject &, const QString &error) { m_authRequestInFlight = false; if (!error.isEmpty()) { setAuthError(error); } }); } void TelegramBackend::requestQrCodeLogin() { if (m_client == nullptr || m_authRequestInFlight) return; if (m_authState != TelegramAuthState::NeedPhoneNumber) return; m_wantsQrLogin = true; m_authRequestInFlight = true; setAuthError({}); m_client->request(QJsonObject{{QStringLiteral("@type"), QStringLiteral("requestQrCodeAuthentication")}, {QStringLiteral("other_user_ids"), QJsonArray{}}}, [this](const QJsonObject &, const QString &error) { m_authRequestInFlight = false; if (!error.isEmpty()) { const bool expired = error.contains(QLatin1String("AUTH_TOKEN_EXPIRED"), Qt::CaseInsensitive) || error.contains(QLatin1String("AUTH_TOKEN_EXCEPTION"), Qt::CaseInsensitive); if (expired && m_wantsQrLogin && m_authState == TelegramAuthState::NeedPhoneNumber) { // Token expired before/while requesting; try again shortly. QTimer::singleShot(500, this, [this] { if (m_wantsQrLogin && m_client != nullptr && m_authState == TelegramAuthState::NeedPhoneNumber && !m_authRequestInFlight) requestQrCodeLogin(); }); return; } setAuthError(error); } }); } void TelegramBackend::requestChat(qint64 chatId) { if (m_client == nullptr) return; m_client->request(QJsonObject{{QStringLiteral("@type"), QStringLiteral("getChat")}, {QStringLiteral("chat_id"), chatId}}, [this](const QJsonObject &chat, const QString &) { if (chat.isEmpty()) return; const qint64 id = intField(chat, "id"); m_chats.insert(id, mergeChat(m_chats.value(id), chat)); publishChat(id); }); } void TelegramBackend::requestChatHistory(const QString &chatId) { const qint64 id = telegramChatId(chatId); if (id == 0 || m_client == nullptr || m_authState != TelegramAuthState::Ready) { qWarning() << "TelegramBackend::requestChatHistory skipped" << chatId << "id=" << id << "ready=" << (m_authState == TelegramAuthState::Ready) << "client=" << (m_client != nullptr); return; } const qint64 now = QDateTime::currentMSecsSinceEpoch(); const qint64 last = m_historyLastRequestedMs.value(id, 0); // Allow refresh on reopen, but avoid spamming repeated opens. if (last != 0 && now - last < 500) return; m_historyLastRequestedMs.insert(id, now); qInfo() << "TelegramBackend::requestChatHistory requesting recent history for" << chatId << "chatIdNum=" << id; // Load latest messages. requestHistory(id, 0); // If there are unread messages, also load around the first unread/read boundary // so history isn't missing when the latest window doesn't include that area. const QJsonObject chat = m_chats.value(id); const qint64 unreadCount = intField(chat, "unread_count"); const qint64 lastReadInbox = intField(chat, "last_read_inbox_message_id"); if (unreadCount > 0 && lastReadInbox > 0) { const qint64 fromUnread = lastReadInbox; // fetch around/after last read qInfo() << "TelegramBackend::requestChatHistory requesting around unread for" << chatId << "from" << fromUnread; m_client->request(QJsonObject{{QStringLiteral("@type"), QStringLiteral("getChatHistory")}, {QStringLiteral("chat_id"), id}, {QStringLiteral("from_message_id"), fromUnread}, {QStringLiteral("offset"), -20}, {QStringLiteral("limit"), 40}, {QStringLiteral("only_local"), false}}, [this, id](const QJsonObject &result, const QString &error) { if (!error.isEmpty()) { qWarning() << "TelegramBackend::getChatHistory(unread) error chat" << id << "error" << error; return; } const QJsonArray messages = result.value(QStringLiteral("messages")).toArray(); qInfo() << "TelegramBackend::getChatHistory(unread) result chat" << id << "count" << messages.size(); for (auto it = messages.size() - 1; it >= 0; --it) publishMessage(id, messages.at(it).toObject()); }); } } void TelegramBackend::setOpenedChat(const QString &chatId) { if (m_client == nullptr) return; const qint64 id = telegramChatId(chatId); if (id == 0) return; if (m_openedChatId != 0 && m_openedChatId != id) { m_client->send(QJsonObject{{QStringLiteral("@type"), QStringLiteral("closeChat")}, {QStringLiteral("chat_id"), m_openedChatId}}); } m_openedChatId = id; m_client->send(QJsonObject{{QStringLiteral("@type"), QStringLiteral("openChat")}, {QStringLiteral("chat_id"), id}}); } void TelegramBackend::setClosedChat(const QString &chatId) { if (m_client == nullptr) return; const qint64 id = telegramChatId(chatId); if (id == 0) return; if (m_openedChatId == id) m_openedChatId = 0; m_client->send(QJsonObject{{QStringLiteral("@type"), QStringLiteral("closeChat")}, {QStringLiteral("chat_id"), id}}); } void TelegramBackend::requestOlderChatHistory(const QString &chatId, const QString &fromMessageId) { const qint64 id = telegramChatId(chatId); if (id == 0 || m_client == nullptr || m_authState != TelegramAuthState::Ready) { qWarning() << "TelegramBackend::requestOlderChatHistory skipped" << chatId << "id=" << id << "ready=" << (m_authState == TelegramAuthState::Ready); return; } if (m_historyLoading.contains(id) || m_historyExhausted.contains(id)) { qInfo() << "TelegramBackend::requestOlderChatHistory busy/exhausted" << chatId << "loading=" << m_historyLoading.contains(id) << "exhausted=" << m_historyExhausted.contains(id); return; } qint64 from = m_oldestMessage.value(id, 0); if (from <= 0 && !fromMessageId.isEmpty()) { bool ok = false; const qint64 parsed = fromMessageId.toLongLong(&ok); if (ok && parsed > 0) from = parsed; } if (from <= 0) { qWarning() << "TelegramBackend::requestOlderChatHistory no anchor for" << chatId << "hint=" << fromMessageId; return; } qInfo() << "TelegramBackend::requestOlderChatHistory requesting older history for" << chatId << "from=" << from; requestHistory(id, from); } void TelegramBackend::requestHistory(qint64 chatId, qint64 fromMessageId) { if (m_client == nullptr) return; // Older-history paging is serialized per chat; initial/recent loads are allowed to retry. if (fromMessageId != 0 && m_historyLoading.contains(chatId)) return; if (fromMessageId != 0) m_historyLoading.insert(chatId); const int limit = (fromMessageId == 0) ? 100 : 50; // For older history, request messages starting from fromMessageId (exclusive in effect // with offset -1 to avoid re-including the anchor message). const int offset = (fromMessageId == 0) ? 0 : -1; qInfo() << "TelegramBackend::getChatHistory send chat" << chatId << "from" << fromMessageId << "offset" << offset << "limit" << limit; m_client->request(QJsonObject{{QStringLiteral("@type"), QStringLiteral("getChatHistory")}, {QStringLiteral("chat_id"), chatId}, {QStringLiteral("from_message_id"), fromMessageId}, {QStringLiteral("offset"), offset}, {QStringLiteral("limit"), limit}, {QStringLiteral("only_local"), false}}, [this, chatId, fromMessageId, limit](const QJsonObject &result, const QString &error) { if (fromMessageId != 0) m_historyLoading.remove(chatId); if (!error.isEmpty()) { qWarning() << "TelegramBackend::getChatHistory error chat" << chatId << "from" << fromMessageId << "error" << error; // Retry once on transient failures for recent history. if (fromMessageId == 0 && !m_historyEmptyRetried.contains(chatId)) { m_historyEmptyRetried.insert(chatId); QTimer::singleShot(800, this, [this, chatId]() { if (m_client != nullptr && m_authState == TelegramAuthState::Ready) requestHistory(chatId, 0); }); } return; } // oldest first: a timeline fills from the bottom, and // TDLib answers newest first. const QJsonArray messages = result.value(QStringLiteral("messages")).toArray(); qInfo() << "TelegramBackend::getChatHistory result chat" << chatId << "from" << fromMessageId << "count" << messages.size(); if (fromMessageId == 0) { // Allow older-history paging attempts after a fresh open/load. m_historyExhausted.remove(chatId); if (messages.isEmpty() && !m_historyEmptyRetried.contains(chatId)) { m_historyEmptyRetried.insert(chatId); QTimer::singleShot(1200, this, [this, chatId]() { if (m_client != nullptr && m_authState == TelegramAuthState::Ready) requestHistory(chatId, 0); }); } } else { if (messages.isEmpty() || messages.size() < limit) m_historyExhausted.insert(chatId); } for (auto it = messages.size() - 1; it >= 0; --it) publishMessage(chatId, messages.at(it).toObject()); }); } void TelegramBackend::requestDownload(qint64 fileId) const { if (m_client == nullptr || fileId <= 0 || m_requestedFiles.contains(fileId)) return; m_requestedFiles.insert(fileId); m_client->send(QJsonObject{{QStringLiteral("@type"), QStringLiteral("downloadFile")}, {QStringLiteral("file_id"), fileId}, {QStringLiteral("priority"), 16}, {QStringLiteral("offset"), 0}, {QStringLiteral("limit"), 0}, {QStringLiteral("synchronous"), false}}); } QString TelegramBackend::fileUrlFor(const QJsonObject &file, bool download, const QString &trackChatId, const QString &trackEventId, const QString &trackField) const { if (file.isEmpty()) return {}; const qint64 id = intField(file, "id"); if (id <= 0) return {}; if (!trackChatId.isEmpty() && !trackEventId.isEmpty() && !trackField.isEmpty()) { // A message can be republished many times while TDLib updates its file // state. Do not append the same reverse reference on every pass. auto &refs = m_mediaFileRefs[id]; const bool alreadyTracked = std::any_of(refs.cbegin(), refs.cend(), [&](const MediaFileRef &ref) { return ref.chatId == trackChatId && ref.eventId == trackEventId && ref.field == trackField; }); if (!alreadyTracked) refs.append(MediaFileRef{trackChatId, trackEventId, trackField}); } if (const QString local = localPathFromFile(file); !local.isEmpty()) { m_filePaths.insert(id, local); return QUrl::fromLocalFile(local).toString(); } if (const auto it = m_filePaths.constFind(id); it != m_filePaths.constEnd() && !it->isEmpty()) return QUrl::fromLocalFile(*it).toString(); const QJsonObject local = objectField(file, "local"); if (download && local.value(QStringLiteral("can_be_downloaded")).toBool(true)) requestDownload(id); return {}; } QString TelegramBackend::ownDisplayName() const { return displayNameFor(m_ownUser); } QString TelegramBackend::ownUsername() const { if (m_ownUser.isEmpty()) return {}; QStringList usernames; const QJsonObject active = objectField(m_ownUser, "usernames"); if (!active.isEmpty()) { for (const QJsonValue &value : active.value(QStringLiteral("active_usernames")).toArray()) { const QString name = value.toString(); if (!name.isEmpty()) usernames.append(name); } } if (usernames.isEmpty()) { const QString legacy = textField(m_ownUser, "username"); if (!legacy.isEmpty()) usernames.append(legacy); } if (!usernames.isEmpty()) return QStringLiteral("@") + usernames.first(); const QString phone = textField(m_ownUser, "phone_number"); if (!phone.isEmpty()) return phone.startsWith(QLatin1Char('+')) ? phone : (QStringLiteral("+") + phone); return {}; } QString TelegramBackend::ownAvatarUrl() const { if (m_ownUser.isEmpty()) return {}; return bestPhotoFileUrl(objectField(m_ownUser, "profile_photo"), true); } QString TelegramBackend::bestPhotoFileUrl(const QJsonObject &photo, bool download, const QString &trackChatId, const QString &trackEventId, const QString &trackField) const { if (photo.isEmpty()) return {}; // Message photo content: { ..., "sizes": [ { "photo": , "width": ..., "height": ... }, ... ] } const QJsonArray sizes = photo.value(QStringLiteral("sizes")).toArray(); if (!sizes.isEmpty()) { // Prefer a size that is already downloaded; otherwise pick the largest. QJsonObject best; QJsonObject bestReady; for (const QJsonValue &value : sizes) { const QJsonObject size = value.toObject(); const QJsonObject file = objectField(size, "photo"); if (file.isEmpty()) continue; const qint64 area = intField(size, "width") * intField(size, "height"); if (best.isEmpty() || area > intField(best, "width") * intField(best, "height")) best = size; if (!localPathFromFile(file).isEmpty()) { if (bestReady.isEmpty() || area > intField(bestReady, "width") * intField(bestReady, "height")) bestReady = size; } } const QJsonObject chosen = bestReady.isEmpty() ? best : bestReady; if (chosen.isEmpty()) return {}; return fileUrlFor(objectField(chosen, "photo"), download, trackChatId, trackEventId, trackField); } // Chat/user profile photos: chatPhotoInfo/profilePhoto with "small" and "big" file objects. QJsonObject file = objectField(photo, "small"); if (file.isEmpty()) file = objectField(photo, "big"); if (file.isEmpty()) return {}; return fileUrlFor(file, download, trackChatId, trackEventId, trackField); } void TelegramBackend::handleFileUpdate(const QJsonObject &file) { const qint64 id = intField(file, "id"); if (id <= 0) return; const QString local = localPathFromFile(file); if (local.isEmpty()) return; const QString url = QUrl::fromLocalFile(local).toString(); m_filePaths.insert(id, local); // Refresh chat avatars that depend on this file. for (auto it = m_chatAvatarFileId.cbegin(); it != m_chatAvatarFileId.cend(); ++it) { if (it.value() == id) publishChat(it.key()); } for (auto it = m_userAvatarFileId.cbegin(); it != m_userAvatarFileId.cend(); ++it) { if (it.value() == id) m_userAvatars.insert(it.key(), url); } if (id == m_ownAvatarFileId && m_ownAvatarFileId != 0) Q_EMIT ownUserChanged(); const auto refsIt = m_mediaFileRefs.constFind(id); if (refsIt != m_mediaFileRefs.constEnd()) { QSet updatedKeys; for (const MediaFileRef &ref : refsIt.value()) { if (ref.chatId.isEmpty() || ref.eventId.isEmpty() || ref.field.isEmpty()) continue; const QString key = ref.chatId + QLatin1Char('\n') + ref.eventId; auto mediaIt = m_publishedAttachmentMedia.find(key); if (mediaIt == m_publishedAttachmentMedia.end()) continue; mediaIt->insert(ref.field, url); // For image attachments (e.g. animated TGS sticker thumbnails), // the UI displays from mediaUrl/previewUrl; if only a thumbnail // file arrived later, use it as the display URL too. if (ref.field == QLatin1String("thumbnail")) { const QString kind = mediaIt->value(QStringLiteral("kind")).toString(); if (kind == QLatin1String("image") && mediaIt->value(QStringLiteral("url")).toString().isEmpty()) mediaIt->insert(QStringLiteral("url"), url); } updatedKeys.insert(key); } for (const QString &key : std::as_const(updatedKeys)) { const int sep = key.indexOf(QLatin1Char('\n')); if (sep <= 0) continue; const QString chatId = key.left(sep); const QString eventId = key.mid(sep + 1); Q_EMIT roomAttachmentUpdated(chatId, eventId, m_publishedAttachmentMedia.value(key)); } } } void TelegramBackend::publishChat(qint64 chatId) { const QJsonObject chat = m_chats.value(chatId); if (chat.isEmpty()) return; // Only expose chats that are actually in the main chat list. // This avoids showing left/archived/hidden chats loaded from TDLib updates. const ChatListVisibility visibility = mainChatListVisibility(chat); if (visibility == ChatListVisibility::Unknown) return; if (visibility == ChatListVisibility::Hide) { // Only announce a departure once: a hidden chat keeps receiving position // updates, and emitting roomLeft on each is work the window has to undo. if (m_publishedChats.contains(chatId)) { m_publishedChats.remove(chatId); Q_EMIT roomLeft(chatIdFor(chatId)); } return; } const QString name = textField(chat, "title"); if (!name.isEmpty()) m_chatNames.insert(chatId, name); const QJsonObject photo = objectField(chat, "photo"); qint64 avatarFileId = 0; // chatPhotoInfo/profilePhoto: prefer small avatar for chat list. QJsonObject avatarFile = objectField(photo, "small"); if (avatarFile.isEmpty()) avatarFile = objectField(photo, "big"); if (avatarFile.isEmpty()) { // Fallback for photo-like objects with sizes. const QJsonArray sizes = photo.value(QStringLiteral("sizes")).toArray(); QJsonObject best; for (const QJsonValue &value : sizes) { const QJsonObject size = value.toObject(); if (best.isEmpty() || intField(size, "width") * intField(size, "height") > intField(best, "width") * intField(best, "height")) best = size; } if (!best.isEmpty()) avatarFile = objectField(best, "photo"); } avatarFileId = intField(avatarFile, "id"); if (avatarFileId > 0) m_chatAvatarFileId.insert(chatId, avatarFileId); const QString type = textField(objectField(chat, "type"), "@type"); const bool isRoom = type != QLatin1String("chatTypePrivate") && type != QLatin1String("chatTypeSecret"); // The avatar url is only recomputed, and the download only re-requested, when // the avatar file actually changed; otherwise the cached url is reused so a // bare position move does not kick off a fresh fetch. const PublishedChat &prev = m_publishedChats[chatId]; QString avatarUrl = prev.avatarUrl; if (!prev.valid || avatarFileId != m_lastPublishedAvatarFileId.value(chatId, -1)) { avatarUrl = bestPhotoFileUrl(photo, true); m_lastPublishedAvatarFileId.insert(chatId, avatarFileId); } // Nothing the window draws changed, so nothing is sent. This is what turns a // storm of position updates into no work at all. if (prev.valid && prev.name == name && prev.avatarUrl == avatarUrl && prev.isRoom == isRoom) return; m_publishedChats.insert(chatId, PublishedChat{name, avatarUrl, isRoom, true}); Q_EMIT roomListed(chatIdFor(chatId), name, avatarUrl, isRoom); } void TelegramBackend::publishChats() { for (auto it = m_chats.cbegin(); it != m_chats.cend(); ++it) publishChat(it.key()); } void TelegramBackend::publishMessage(qint64 chatId, const QJsonObject &message) { if (message.isEmpty() || chatId == 0) return; const qint64 messageId = intField(message, "id"); if (messageId > m_newestMessage.value(chatId)) m_newestMessage.insert(chatId, messageId); if (messageId > 0) { const qint64 prevOldest = m_oldestMessage.value(chatId, 0); if (prevOldest == 0 || messageId < prevOldest) m_oldestMessage.insert(chatId, messageId); } const QString chat = chatIdFor(chatId); const QJsonObject sender = objectField(message, "sender_id"); const QString senderType = textField(sender, "@type"); const qint64 senderUserId = senderType == QLatin1String("messageSenderUser") ? intField(sender, "user_id") : 0; const qint64 senderChatId = senderType == QLatin1String("messageSenderChat") ? intField(sender, "chat_id") : 0; const bool isOwn = message.value(QStringLiteral("is_outgoing")).toBool(false) || (!m_ownUser.isEmpty() && senderUserId != 0 && senderUserId == intField(m_ownUser, "id")); const QString senderName = isOwn ? QStringLiteral("You") : (senderUserId != 0 ? (m_userNames.value(senderUserId).isEmpty() ? QStringLiteral("Telegram user") : m_userNames.value(senderUserId)) : (senderChatId != 0 ? (m_chatNames.value(senderChatId).isEmpty() ? QStringLiteral("Telegram chat") : m_chatNames.value(senderChatId)) : QStringLiteral("Telegram user"))); if (!isOwn && senderUserId > 0 && m_userNames.value(senderUserId).isEmpty() && m_client != nullptr && !m_userInfoRequests.contains(senderUserId)) { m_userInfoRequests.insert(senderUserId); m_client->request(QJsonObject{{QStringLiteral("@type"), QStringLiteral("getUser")}, {QStringLiteral("user_id"), senderUserId}}, [this, senderUserId](const QJsonObject &user, const QString &) { m_userInfoRequests.remove(senderUserId); if (user.isEmpty()) return; m_userNames.insert(senderUserId, displayNameFor(user)); const QJsonObject photo = objectField(objectField(user, "profile_photo"), "small"); const qint64 fileId = intField(photo, "id"); if (fileId > 0) m_userAvatarFileId.insert(senderUserId, fileId); const QString avatar = fileUrlFor(photo, true); if (!avatar.isEmpty()) m_userAvatars.insert(senderUserId, avatar); }); } const QString senderAvatar = senderUserId != 0 ? m_userAvatars.value(senderUserId) : QString(); const double ts = static_cast(intField(message, "date")); const QString eventId = QString::number(messageId); const QString senderIdStr = senderUserId != 0 ? QString::number(senderUserId) : (senderChatId != 0 ? QString::number(senderChatId) : QString()); const QJsonObject content = objectField(message, "content"); const QString contentType = textField(content, "@type"); if (contentType == QLatin1String("messageText")) { Q_EMIT roomMessage(chat, eventId, textField(objectField(content, "text"), "text"), senderName, isOwn, ts, false, senderAvatar, senderIdStr); return; } // Everything else is carried as an attachment with the kind spelled the way // the window already spells it, so a Telegram picture and a Matrix one are // drawn by the same code. QVariantMap media; if (contentType == QLatin1String("messagePhoto")) { media.insert(QStringLiteral("kind"), QStringLiteral("image")); // Download photos so they can be viewed; local files are reused if present. const QString url = bestPhotoFileUrl(objectField(content, "photo"), true, chat, eventId, QStringLiteral("url")); if (!url.isEmpty()) media.insert(QStringLiteral("url"), url); const QString caption = textField(objectField(content, "caption"), "text"); if (!caption.isEmpty()) media.insert(QStringLiteral("caption"), caption); } else if (contentType == QLatin1String("messageVideo")) { const QJsonObject video = objectField(content, "video"); media.insert(QStringLiteral("kind"), QStringLiteral("video")); // Avoid auto-downloading full videos; fetch thumbnail for preview if possible. const QString videoUrl = fileUrlFor(objectField(video, "video"), false, chat, eventId, QStringLiteral("url")); if (!videoUrl.isEmpty()) media.insert(QStringLiteral("url"), videoUrl); const QJsonObject thumb = objectField(video, "thumbnail"); const QString thumbUrl = fileUrlFor(objectField(thumb, "file"), true, chat, eventId, QStringLiteral("thumbnail")); if (!thumbUrl.isEmpty()) media.insert(QStringLiteral("thumbnail"), thumbUrl); media.insert(QStringLiteral("duration"), intField(video, "duration")); const QString caption = textField(objectField(content, "caption"), "text"); if (!caption.isEmpty()) media.insert(QStringLiteral("caption"), caption); } else if (contentType == QLatin1String("messageAnimation")) { const QJsonObject anim = objectField(content, "animation"); media.insert(QStringLiteral("kind"), QStringLiteral("video")); // Animations/GIFs can be large; prefer thumbnail/locally available file. const QString url = fileUrlFor(objectField(anim, "animation"), false, chat, eventId, QStringLiteral("url")); if (!url.isEmpty()) media.insert(QStringLiteral("url"), url); const QString thumbUrl = fileUrlFor(objectField(objectField(anim, "thumbnail"), "file"), true, chat, eventId, QStringLiteral("thumbnail")); if (!thumbUrl.isEmpty()) media.insert(QStringLiteral("thumbnail"), thumbUrl); } else if (contentType == QLatin1String("messageVoiceNote") || contentType == QLatin1String("messageVoice")) { const QJsonObject voice = objectField(content, "voice_note").isEmpty() ? objectField(content, "voice") : objectField(content, "voice_note"); media.insert(QStringLiteral("kind"), QStringLiteral("audio")); // Voice messages are usually small; allow download for playback if UI supports it. const QString url = fileUrlFor(objectField(voice, "voice"), true, chat, eventId, QStringLiteral("url")); if (!url.isEmpty()) media.insert(QStringLiteral("url"), url); media.insert(QStringLiteral("duration"), intField(voice, "duration")); } else if (contentType == QLatin1String("messageAudio")) { const QJsonObject audio = objectField(content, "audio"); media.insert(QStringLiteral("kind"), QStringLiteral("audio")); const QString url = fileUrlFor(objectField(audio, "audio"), false, chat, eventId, QStringLiteral("url")); if (!url.isEmpty()) media.insert(QStringLiteral("url"), url); const QString thumbUrl = fileUrlFor(objectField(objectField(audio, "album_cover_thumbnail"), "file"), true, chat, eventId, QStringLiteral("thumbnail")); if (!thumbUrl.isEmpty()) media.insert(QStringLiteral("thumbnail"), thumbUrl); media.insert(QStringLiteral("duration"), intField(audio, "duration")); const QString name = textField(audio, "file_name"); if (!name.isEmpty()) media.insert(QStringLiteral("name"), name); } else if (contentType == QLatin1String("messageDocument")) { const QJsonObject doc = objectField(content, "document"); media.insert(QStringLiteral("kind"), QStringLiteral("file")); const QString url = fileUrlFor(objectField(doc, "document"), false, chat, eventId, QStringLiteral("url")); if (!url.isEmpty()) media.insert(QStringLiteral("url"), url); const QString name = textField(doc, "file_name"); if (!name.isEmpty()) media.insert(QStringLiteral("name"), name); const QString mime = textField(doc, "mime_type"); if (!mime.isEmpty()) media.insert(QStringLiteral("mime"), mime); const QString thumbUrl = fileUrlFor(objectField(objectField(doc, "thumbnail"), "file"), true, chat, eventId, QStringLiteral("thumbnail")); if (!thumbUrl.isEmpty()) media.insert(QStringLiteral("thumbnail"), thumbUrl); } else if (contentType == QLatin1String("messageSticker")) { const QJsonObject sticker = objectField(content, "sticker"); const QString format = textField(objectField(sticker, "format"), "@type"); const QString emoji = textField(sticker, "emoji"); if (!emoji.isEmpty()) media.insert(QStringLiteral("caption"), emoji); if (format == QLatin1String("stickerFormatWebm")) { // A WebM sticker is a video, not a still. The timeline draws stickers // through QML Image, which cannot decode it; handing the file to // previewUrl made every such row log "unsupported image format". // Show the still thumbnail when TDLib has one, otherwise the row // falls back to its caption instead of a broken picture. media.insert(QStringLiteral("kind"), QStringLiteral("sticker")); const QString thumbUrl = fileUrlFor(objectField(objectField(sticker, "thumbnail"), "file"), true, chat, eventId, QStringLiteral("thumbnail")); if (!thumbUrl.isEmpty()) media.insert(QStringLiteral("url"), thumbUrl); else if (emoji.isEmpty()) media.insert(QStringLiteral("caption"), i18nc("@info caption fallback for animated Telegram sticker", "Animated sticker")); media.insert(QStringLiteral("width"), intField(sticker, "width")); media.insert(QStringLiteral("height"), intField(sticker, "height")); } else if (format == QLatin1String("stickerFormatTgs")) { // Animated (Lottie) stickers are not rendered natively here; show static thumbnail if available. media.insert(QStringLiteral("kind"), QStringLiteral("image")); const QString thumbUrl = fileUrlFor(objectField(objectField(sticker, "thumbnail"), "file"), true, chat, eventId, QStringLiteral("thumbnail")); if (!thumbUrl.isEmpty()) { media.insert(QStringLiteral("thumbnail"), thumbUrl); media.insert(QStringLiteral("url"), thumbUrl); } // If a static sticker thumbnail exists separately, try it as fallback preview too. if (thumbUrl.isEmpty()) { const QString staticThumbUrl = fileUrlFor(objectField(objectField(sticker, "thumbnail"), "file"), true, chat, eventId, QStringLiteral("url")); if (!staticThumbUrl.isEmpty()) media.insert(QStringLiteral("url"), staticThumbUrl); } if (emoji.isEmpty()) media.insert(QStringLiteral("caption"), i18nc("@info caption fallback for animated Telegram sticker", "Animated sticker")); } else { // Static WebP stickers (and unknown formats): try as image. media.insert(QStringLiteral("kind"), QStringLiteral("image")); const QString url = fileUrlFor(objectField(sticker, "sticker"), true, chat, eventId, QStringLiteral("url")); if (!url.isEmpty()) media.insert(QStringLiteral("url"), url); const QString thumbUrl = fileUrlFor(objectField(objectField(sticker, "thumbnail"), "file"), true, chat, eventId, QStringLiteral("thumbnail")); if (!thumbUrl.isEmpty()) media.insert(QStringLiteral("thumbnail"), thumbUrl); } media.insert(QStringLiteral("width"), intField(sticker, "width")); media.insert(QStringLiteral("height"), intField(sticker, "height")); } else { // A poll, a service notice, or other unsupported type. Q_EMIT roomMessage(chat, eventId, i18nc("@info in-timeline notice, a Telegram message this program cannot show", "A message this program cannot show yet."), senderName, isOwn, ts, false, senderAvatar, senderIdStr); return; } const bool hasVisualOrFileInfo = !media.value(QStringLiteral("url")).toString().isEmpty() || !media.value(QStringLiteral("thumbnail")).toString().isEmpty() || !media.value(QStringLiteral("name")).toString().isEmpty() || !media.value(QStringLiteral("caption")).toString().isEmpty() || media.value(QStringLiteral("duration")).toInt() > 0; if (!hasVisualOrFileInfo) { // Keep as attachment so the UI can show a media placeholder for known types // (e.g. photo/video/file) instead of a generic text notice. const QString kind = media.value(QStringLiteral("kind")).toString(); if (kind.isEmpty()) { Q_EMIT roomMessage(chat, eventId, i18nc("@info in-timeline notice, a Telegram file not yet available", "Media is loading or unavailable."), senderName, isOwn, ts, false, senderAvatar, senderIdStr); return; } } m_publishedAttachmentMedia.insert(chat + QLatin1Char('\n') + eventId, media); // Bound memory: keep recent attachment media maps for in-place file updates. if (m_publishedAttachmentMedia.size() > 2000) m_publishedAttachmentMedia.clear(); Q_EMIT roomAttachment(chat, eventId, media, senderName, isOwn, ts, senderAvatar, senderIdStr); } bool TelegramBackend::sendText(const QString &chatId, const QString &text) { if (m_client == nullptr || m_authState != TelegramAuthState::Ready) { Q_EMIT sendFailed(chatId, i18nc("@info:status Telegram messages before sign-in", "Sign in to Telegram to send messages.")); return false; } const qint64 id = telegramChatId(chatId); if (id == 0) { Q_EMIT sendFailed(chatId, i18nc("@info:status the conversation is not known to Telegram", "This conversation is not available in Telegram yet.")); return false; } m_client->request(QJsonObject{{QStringLiteral("@type"), QStringLiteral("sendMessage")}, {QStringLiteral("chat_id"), id}, {QStringLiteral("input_message_content"), QJsonObject{{QStringLiteral("@type"), QStringLiteral("inputMessageText")}, {QStringLiteral("text"), QJsonObject{{QStringLiteral("@type"), QStringLiteral("formattedText")}, {QStringLiteral("text"), text}, {QStringLiteral("entities"), QJsonArray{}}}}, {QStringLiteral("link_preview_options"), QJsonValue::Null}, {QStringLiteral("clear_draft"), false}}}}, [this, chatId](const QJsonObject &, const QString &error) { if (!error.isEmpty()) Q_EMIT sendFailed(chatId, error); }); return true; } bool TelegramBackend::sendFile(const QString &chatId, const QString &localFilePath) { if (m_client == nullptr || m_authState != TelegramAuthState::Ready) { Q_EMIT sendFailed(chatId, i18nc("@info:status Telegram attachments before sign-in", "Sign in to Telegram to send files.")); return false; } const qint64 id = telegramChatId(chatId); if (id == 0) { Q_EMIT sendFailed(chatId, i18nc("@info:status the conversation is not known to Telegram", "This conversation is not available in Telegram yet.")); return false; } const QString lower = localFilePath.toLower(); QJsonObject content; const QJsonObject inputFile{{QStringLiteral("@type"), QStringLiteral("inputFileLocal")}, {QStringLiteral("path"), localFilePath}}; if (lower.endsWith(QLatin1String(".jpg")) || lower.endsWith(QLatin1String(".jpeg")) || lower.endsWith(QLatin1String(".png")) || lower.endsWith(QLatin1String(".webp")) || lower.endsWith(QLatin1String(".bmp"))) { content = QJsonObject{ {QStringLiteral("@type"), QStringLiteral("inputMessagePhoto")}, {QStringLiteral("photo"), inputFile}, {QStringLiteral("thumbnail"), QJsonObject{}}, {QStringLiteral("added_sticker_file_ids"), QJsonArray{}}, {QStringLiteral("width"), 0}, {QStringLiteral("height"), 0}, {QStringLiteral("caption"), QJsonObject{{QStringLiteral("@type"), QStringLiteral("formattedText")}, {QStringLiteral("text"), QString()}}}}; } else if (lower.endsWith(QLatin1String(".mp4")) || lower.endsWith(QLatin1String(".mov")) || lower.endsWith(QLatin1String(".mkv")) || lower.endsWith(QLatin1String(".webm"))) { content = QJsonObject{ {QStringLiteral("@type"), QStringLiteral("inputMessageVideo")}, {QStringLiteral("video"), inputFile}, {QStringLiteral("thumbnail"), QJsonObject{}}, {QStringLiteral("added_sticker_file_ids"), QJsonArray{}}, {QStringLiteral("duration"), 0}, {QStringLiteral("width"), 0}, {QStringLiteral("height"), 0}, {QStringLiteral("supports_streaming"), true}, {QStringLiteral("caption"), QJsonObject{{QStringLiteral("@type"), QStringLiteral("formattedText")}, {QStringLiteral("text"), QString()}}}}; } else { content = QJsonObject{ {QStringLiteral("@type"), QStringLiteral("inputMessageDocument")}, {QStringLiteral("document"), inputFile}, {QStringLiteral("thumbnail"), QJsonObject{}}, {QStringLiteral("disable_content_type_detection"), false}, {QStringLiteral("caption"), QJsonObject{{QStringLiteral("@type"), QStringLiteral("formattedText")}, {QStringLiteral("text"), QString()}}}}; } m_client->send(QJsonObject{{QStringLiteral("@type"), QStringLiteral("sendMessage")}, {QStringLiteral("chat_id"), id}, {QStringLiteral("input_message_content"), content}}); return true; } void TelegramBackend::noteReadOutbox(qint64 chatId, double maxMessageId) { if (chatId == 0 || maxMessageId <= 0) return; // Emitted only on a real move: the login replay fires updateChat for every // chat with the same point, and a per-chat signal storm would make the // window mark every model it owns once per chat for no change at all. const double previous = m_readOutbox.value(chatId, 0.0); if (previous >= maxMessageId) return; m_readOutbox.insert(chatId, maxMessageId); Q_EMIT roomReadOutbox(chatIdFor(chatId), maxMessageId); } double TelegramBackend::readInbox(const QString &chatId) const { const qint64 id = telegramChatId(chatId); if (id == 0) return 0.0; const QJsonObject chat = m_chats.value(id); const qint64 lastRead = intField(chat, "last_read_inbox_message_id"); return static_cast(lastRead); } double TelegramBackend::readOutbox(const QString &chatId) const { return m_readOutbox.value(telegramChatId(chatId), 0.0); } void TelegramBackend::markRead(const QString &chatId) { const qint64 chat = telegramChatId(chatId); // Telegram has no seen flag; the read point is a message id. The newest // message from updates is normally in m_newestMessage, but on a cold start // the chat's last_message arrives from getChat before any update does and // history is still loading. Without the fallback markRead saw a zero and // silently sent nothing, which is why opening a chat left it unread on the // other side until some new message happened to arrive. qint64 newest = m_newestMessage.value(chat); if (newest == 0) { const QJsonObject info = m_chats.value(chat); newest = intField(objectField(info, "last_message"), "id"); } if (m_client == nullptr || chat == 0 || newest == 0) return; m_client->send(QJsonObject{{QStringLiteral("@type"), QStringLiteral("viewMessages")}, {QStringLiteral("chat_id"), chat}, {QStringLiteral("message_ids"), QJsonArray{QJsonValue(newest)}}, {QStringLiteral("force_read"), true}}); } void TelegramBackend::sendTyping(const QString &chatId) { if (m_client == nullptr) return; const qint64 id = telegramChatId(chatId); if (id == 0) return; m_client->send(QJsonObject{{QStringLiteral("@type"), QStringLiteral("sendChatAction")}, {QStringLiteral("chat_id"), id}, {QStringLiteral("action"), QJsonObject{{QStringLiteral("@type"), QStringLiteral("chatActionTyping")}}}}); } void TelegramBackend::sendReaction(const QString &chatId, const QVariant &identifier, const QString &emoji, bool added) { if (m_client == nullptr || m_authState != TelegramAuthState::Ready) return; const qint64 id = telegramChatId(chatId); bool ok = false; const qint64 messageId = identifier.toString().toLongLong(&ok); if (id == 0 || !ok || emoji.trimmed().isEmpty()) return; const QJsonObject reactionType{{QStringLiteral("@type"), QStringLiteral("reactionTypeEmoji")}, {QStringLiteral("emoji"), emoji}}; if (added) { m_client->request(QJsonObject{{QStringLiteral("@type"), QStringLiteral("addMessageReaction")}, {QStringLiteral("chat_id"), id}, {QStringLiteral("message_id"), messageId}, {QStringLiteral("reaction_type"), reactionType}, {QStringLiteral("is_big"), false}, {QStringLiteral("update_recent_reactions"), true}}, [this, chatId](const QJsonObject &, const QString &error) { if (!error.isEmpty()) Q_EMIT sendFailed(chatId, error); }); } else { m_client->request(QJsonObject{{QStringLiteral("@type"), QStringLiteral("removeMessageReaction")}, {QStringLiteral("chat_id"), id}, {QStringLiteral("message_id"), messageId}, {QStringLiteral("reaction_type"), reactionType}}, [this, chatId](const QJsonObject &, const QString &error) { if (!error.isEmpty()) Q_EMIT sendFailed(chatId, error); }); } } bool TelegramBackend::sendEdit(const QString &chatId, const QVariant &identifier, const QString &newText) { if (m_client == nullptr) return false; const qint64 id = telegramChatId(chatId); bool ok = false; const qint64 messageId = identifier.toString().toLongLong(&ok); if (id == 0 || !ok) return false; m_client->send(QJsonObject{{QStringLiteral("@type"), QStringLiteral("editMessageText")}, {QStringLiteral("chat_id"), id}, {QStringLiteral("message_id"), messageId}, {QStringLiteral("input_message_content"), QJsonObject{{QStringLiteral("@type"), QStringLiteral("inputMessageText")}, {QStringLiteral("text"), QJsonObject{{QStringLiteral("@type"), QStringLiteral("formattedText")}, {QStringLiteral("text"), newText}, {QStringLiteral("entities"), QJsonArray{}}}}, {QStringLiteral("link_preview_options"), QJsonValue::Null}, {QStringLiteral("clear_draft"), false}}}}); return true; } bool TelegramBackend::sendDelete(const QString &chatId, const QVariant &identifier) { if (m_client == nullptr) return false; const qint64 id = telegramChatId(chatId); bool ok = false; const qint64 messageId = identifier.toString().toLongLong(&ok); if (id == 0 || !ok) return false; m_client->send(QJsonObject{{QStringLiteral("@type"), QStringLiteral("deleteMessages")}, {QStringLiteral("chat_id"), id}, {QStringLiteral("message_ids"), QJsonArray{QJsonValue(messageId)}}, {QStringLiteral("revoke"), true}}); return true; } bool TelegramBackend::leaveChat(const QString &chatId) { if (m_client == nullptr) return false; const qint64 id = telegramChatId(chatId); if (id == 0) return false; m_client->send(QJsonObject{{QStringLiteral("@type"), QStringLiteral("leaveChat")}, {QStringLiteral("chat_id"), id}}); m_chats.remove(id); m_chatNames.remove(id); Q_EMIT roomLeft(chatId); return true; } QVariantMap TelegramBackend::roomInfo(const QString &chatId) const { QVariantMap info; const QJsonObject chat = m_chats.value(telegramChatId(chatId)); if (chat.isEmpty()) return info; info.insert(QStringLiteral("roomId"), chatId); info.insert(QStringLiteral("displayName"), textField(chat, "title")); info.insert(QStringLiteral("topic"), QString()); info.insert(QStringLiteral("canonicalAlias"), QString()); info.insert(QStringLiteral("altAliases"), QVariantList()); info.insert(QStringLiteral("joinedCount"), 2); info.insert(QStringLiteral("invitedCount"), 0); // Telegram encrypts its transport but not its chats in the way this window // means it: there is no end-to-end secret chat behind TDLib any more, and // saying there is would be the worse lie. info.insert(QStringLiteral("encrypted"), false); info.insert(QStringLiteral("encryptionActive"), false); info.insert(QStringLiteral("trustKnown"), false); info.insert(QStringLiteral("ownSessionsVerified"), false); info.insert(QStringLiteral("keyBackupAvailable"), false); info.insert(QStringLiteral("keyBackupUnlocked"), false); info.insert(QStringLiteral("version"), QString()); info.insert(QStringLiteral("isDirect"), textField(objectField(chat, "type"), "@type") == QLatin1String("chatTypePrivate")); info.insert(QStringLiteral("ownPowerLevel"), 0); info.insert(QStringLiteral("avatarUrl"), bestPhotoFileUrl(objectField(chat, "photo"), true)); return info; } QVariantList TelegramBackend::roomMembers(const QString &chatId) const { QVariantList members; const QJsonObject chat = m_chats.value(telegramChatId(chatId)); if (chat.isEmpty()) return members; // Best-effort from cached chat data; full member lists require dedicated // TDLib requests per chat type (not fetched here). for (const QJsonValue &value : chat.value(QStringLiteral("positions")).toArray()) { const QJsonObject user = objectField(value.toObject(), "user"); if (user.isEmpty()) continue; const qint64 uid = intField(user, "id"); const QString userId = QString::number(uid); QVariantMap member; member.insert(QStringLiteral("id"), userId); member.insert(QStringLiteral("name"), displayNameFor(user)); member.insert(QStringLiteral("avatar"), bestPhotoFileUrl(objectField(user, "profile_photo"), true)); member.insert(QStringLiteral("power"), 0); member.insert(QStringLiteral("isOwn"), !m_ownUser.isEmpty() && uid == intField(m_ownUser, "id")); members.append(member); } return members; } QVariantMap TelegramBackend::memberInfo(const QString &chatId, const QString &userId) const { QVariantMap info; bool ok = false; const qint64 id = userId.toLongLong(&ok); if (!ok) return info; // Answered out of the chat's own member cache, the same table roomMembers() // reads: a card opened from a message avatar is wanted while the click is // warm, so there is nothing to ask the server and wait for. const QJsonObject chat = m_chats.value(telegramChatId(chatId)); for (const QJsonValue &value : chat.value(QStringLiteral("positions")).toArray()) { const QJsonObject user = objectField(value.toObject(), "user"); if (intField(user, "id") != id) continue; info.insert(QStringLiteral("userId"), userId); info.insert(QStringLiteral("displayName"), displayNameFor(user)); info.insert(QStringLiteral("powerLevel"), 0); info.insert(QStringLiteral("isLocalMember"), !m_ownUser.isEmpty() && id == intField(m_ownUser, "id")); info.insert(QStringLiteral("avatarUrl"), bestPhotoFileUrl(objectField(user, "profile_photo"), true)); // No device tables behind a Telegram account, so there is nothing to // report and the card says so rather than inventing a number. info.insert(QStringLiteral("trustKnown"), false); break; } return info; } void TelegramBackend::applyProxy(bool enabled, int type, const QString &server, int port, const QString &username, const QString &password, const QString &secret) { if (m_client == nullptr) return; // Remove proxies we previously added in this session to avoid stacking. for (const qint64 proxyId : std::as_const(m_proxyIds)) { m_client->send(QJsonObject{{QStringLiteral("@type"), QStringLiteral("removeProxy")}, {QStringLiteral("proxy_id"), proxyId}}); } m_proxyIds.clear(); if (!enabled || server.trimmed().isEmpty() || port <= 0 || port > 65535) return; QJsonObject proxyType; switch (type) { case 1: // SOCKS5 proxyType.insert(QStringLiteral("@type"), QStringLiteral("proxyTypeSocks5")); proxyType.insert(QStringLiteral("username"), username); proxyType.insert(QStringLiteral("password"), password); break; case 2: // MTProto proxyType.insert(QStringLiteral("@type"), QStringLiteral("proxyTypeMtproto")); proxyType.insert(QStringLiteral("secret"), secret.trimmed()); break; case 0: // HTTP default: proxyType.insert(QStringLiteral("@type"), QStringLiteral("proxyTypeHttp")); proxyType.insert(QStringLiteral("username"), username); proxyType.insert(QStringLiteral("password"), password); proxyType.insert(QStringLiteral("http_only"), false); break; } QJsonObject proxy{{QStringLiteral("@type"), QStringLiteral("proxy")}, {QStringLiteral("server"), server.trimmed()}, {QStringLiteral("port"), port}, {QStringLiteral("type"), proxyType}}; QJsonObject req{{QStringLiteral("@type"), QStringLiteral("addProxy")}, {QStringLiteral("proxy"), proxy}, {QStringLiteral("enable"), true}}; m_client->request(req, [this](const QJsonObject &result, const QString &error) { if (!error.isEmpty()) return; const QString resultType = result.value(QStringLiteral("@type")).toString(); if (resultType == QLatin1String("addedProxy") || resultType == QLatin1String("proxy")) { const qint64 id = static_cast(result.value(QStringLiteral("id")).toDouble()); if (id != 0) m_proxyIds.append(id); } }); } } // namespace koutnet