// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL #include "TelegramClient.h" // Compiled either way. Without TDLib every entry point says so rather than // pretending to be connected, because a client that accepts requests and answers // nothing leaves a login page waiting on an answer that is never coming. #ifdef KOUTNET_HAVE_TDLIB #include #include #include #include #include #include #include #include namespace koutnet { // how long one receive call waits before handing control back to the loop. // A short wait is what lets the thread notice m_client going away and finish // instead of sitting inside TDLib for a second it will never be given. constexpr double kReceiveTimeout = 0.2; TelegramClient::TelegramClient(QObject *parent) : QObject(parent) { } TelegramClient::~TelegramClient() { stop(); } void TelegramClient::start(quint32 apiId, const QByteArray &apiHash, const QString &databaseDirectory) { if (m_client != nullptr) return; QDir().mkpath(databaseDirectory); m_client = td_json_client_create(); if (m_client == nullptr) { Q_EMIT update(QJsonObject{{QStringLiteral("@type"), QStringLiteral("koutnet_clientFailed")}}); return; } // TDLib defaults to verbosity 5, which prints every receive-loop wakeup and send(QJsonObject{{QStringLiteral("@type"), QStringLiteral("setLogVerbosityLevel")}, {QStringLiteral("new_verbosity_level"), 1}}); // Parameters first: TDLib asks for nothing until these arrive, and they // carry the api id and hash it will not start without. send(QJsonObject{{QStringLiteral("@type"), QStringLiteral("setTdlibParameters")}, {QStringLiteral("database_directory"), databaseDirectory}, {QStringLiteral("use_message_database"), true}, {QStringLiteral("use_secret_chats"), false}, {QStringLiteral("api_id"), QString::number(apiId)}, {QStringLiteral("api_hash"), QString::fromLatin1(apiHash)}, {QStringLiteral("system_language_code"), QLocale::system().name()}, {QStringLiteral("device_model"), QStringLiteral("KOutNet desktop")}, {QStringLiteral("application_version"), QStringLiteral("1.0")}}); // asked for explicitly, so a session that is already signed in says so // instead of waiting for a state change that will never come. send(QJsonObject{{QStringLiteral("@type"), QStringLiteral("getAuthorizationState")}}); m_thread = QThread::create([this] { pump(); }); m_thread->start(); } void TelegramClient::stop() { if (m_client == nullptr) return; QThread *thread = m_thread; m_thread = nullptr; m_client = nullptr; // The pump is inside TDLib and not interruptible, so the thread is joined // rather than killed if it does not come out on its own. The client object // itself is never destroyed: TDLib documents no way to do that. if (thread != nullptr) { thread->quit(); if (!thread->wait(3000)) thread->terminate(); delete thread; } } void TelegramClient::send(const QJsonObject &request) { if (m_client == nullptr) return; QJsonObject stamped = request; const quint64 id = ++m_nextRequestId; stamped.insert(QStringLiteral("@extra"), QJsonValue(qint64(id))); m_pending.insert(qint64(id), nullptr); const QByteArray payload = QJsonDocument(stamped).toJson(QJsonDocument::Compact); td_json_client_send(m_client, payload.constData()); } void TelegramClient::request(const QJsonObject &request, Response callback) { if (m_client == nullptr) { if (callback) callback(QJsonObject(), QStringLiteral("Telegram is not running.")); return; } QJsonObject stamped = request; const quint64 id = ++m_nextRequestId; stamped.insert(QStringLiteral("@extra"), QJsonValue(qint64(id))); m_pending.insert(qint64(id), std::move(callback)); const QByteArray payload = QJsonDocument(stamped).toJson(QJsonDocument::Compact); td_json_client_send(m_client, payload.constData()); } void TelegramClient::deliver(const QJsonObject &response) { // TDLib echoes the request's @extra in the response; updates have no @extra. const QJsonValue idValue = response.value(QStringLiteral("@extra")); if (!idValue.isDouble() && !idValue.isString()) { const QString t = response.value(QStringLiteral("@type")).toString(); if (t == QLatin1String("ok") || t == QLatin1String("error")) qWarning() << "TelegramClient: response without @extra" << t; Q_EMIT update(response); return; } qint64 reqId = 0; if (idValue.isDouble()) reqId = qint64(idValue.toDouble()); else reqId = idValue.toString().toLongLong(); const auto it = m_pending.find(reqId); if (it == m_pending.end()) { qWarning() << "TelegramClient: response @extra not pending" << reqId << response.value(QStringLiteral("@type")).toString(); Q_EMIT update(response); return; } const Response callback = it.value(); m_pending.erase(it); const QString type = response.value(QStringLiteral("@type")).toString(); // A refused request is an ordinary document with an @type of its own and a // message in it, not an exception and not an absence: treating it as one of // those two is what makes a refused login look like a hang. if (type == QLatin1String("error")) { if (callback) callback(QJsonObject(), response.value(QStringLiteral("message")).toString()); else Q_EMIT update(response); return; } if (callback) { callback(response, QString()); return; } // Fire-and-forget requests (send()) have no callback, but some responses // (e.g. getAuthorizationState) carry state we must process. Q_EMIT update(response); } void TelegramClient::pump() { while (m_client != nullptr) { const char *raw = td_json_client_receive(m_client, kReceiveTimeout); if (raw == nullptr) continue; // The buffer belongs to TDLib and is freed by the next receive, so it is // parsed into a document of our own before anything else is done with it. QJsonParseError error{}; const QJsonDocument document = QJsonDocument::fromJson(QByteArray(raw), &error); if (error.error != QJsonParseError::NoError || !document.isObject()) continue; const QJsonObject response = document.object(); // Drop noisy progress-only file updates before flooding the UI thread. // We only care when a download has completed (local path becomes available). if (!response.contains(QStringLiteral("@extra")) && response.value(QStringLiteral("@type")).toString() == QLatin1String("updateFile")) { const QJsonObject file = response.value(QStringLiteral("file")).toObject(); const QJsonObject local = file.value(QStringLiteral("local")).toObject(); if (!local.value(QStringLiteral("is_downloading_completed")).toBool(false)) { continue; } } // Every signal leaves from here, and a slot may delete whatever it was // connected to, including this object. Queued to the thread that owns // the client so nothing runs there by accident. QMetaObject::invokeMethod( this, [this, response] { deliver(response); }, Qt::QueuedConnection); } } } // namespace koutnet #else // KOUTNET_HAVE_TDLIB namespace koutnet { namespace { const QString kNoTdlib = QStringLiteral("Telegram is not available in this build: TDLib was not found."); } TelegramClient::TelegramClient(QObject *parent) : QObject(parent) { } TelegramClient::~TelegramClient() = default; void TelegramClient::start(quint32, const QByteArray &, const QString &) { Q_EMIT update(QJsonObject{{QStringLiteral("@type"), QStringLiteral("koutnet_clientFailed")}}); } void TelegramClient::stop() { } void TelegramClient::send(const QJsonObject &) { } void TelegramClient::request(const QJsonObject &, Response callback) { if (callback) callback(QJsonObject(), kNoTdlib); } } // namespace koutnet #endif // KOUTNET_HAVE_TDLIB