// GCC 15 reports a false -Wmaybe-uninitialized on moved std::variant values (ttgui::json::Value); silenced for this file only. #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" #include "mologram/tapi/TapiService.hpp" #include #include #include #include #include "mologram/tapi/EventConverter.hpp" #include "mologram/tapi/TapiCodec.hpp" #include "tapi/event_queue.hpp" #include "tapi/qr_login.hpp" #include "tapi/tl/functions/account.hpp" #include "tapi/tl/types.hpp" namespace mologram { namespace T = tapi::tl::types; using js::Object; using js::Value; namespace { /// Loads the exported auth key (development only). Values stay in memory; nothing is printed. std::unique_ptr storeFromTsv(const std::string& path) { std::ifstream in(path); if (!in) throw std::runtime_error("cannot open the auth tsv"); std::string line; std::getline(in, line); std::vector col; size_t pos = 0; for (;;) { size_t t = line.find('\t', pos); col.push_back(line.substr(pos, t == std::string::npos ? t : t - pos)); if (t == std::string::npos) break; pos = t + 1; } if (col.size() < 4) throw std::runtime_error("the auth tsv is malformed"); auto* m = new tapi::MemorySessionStore(); std::unique_ptr store(m); m->set_dc(std::stoi(col[0]), col[1], std::stoi(col[2])); tapi::tl::TlBytes key; auto hv = [](char ch) -> unsigned { return ch <= '9' ? (unsigned)(ch - '0') : (unsigned)((ch | 32) - 'a' + 10); }; for (size_t i = 0; i + 1 < col[3].size(); i += 2) key.push_back((std::uint8_t)((hv(col[3][i]) << 4) | hv(col[3][i + 1]))); m->set_auth_key(tapi::AuthKey(key)); return store; } std::unique_ptr makeStore(const TapiService::Options& o) { if (!o.authTsv.empty()) return storeFromTsv(o.authTsv); std::error_code ec; std::filesystem::path p(o.sessionPath); if (!p.parent_path().empty()) std::filesystem::create_directories(p.parent_path(), ec); return std::unique_ptr(new tapi::FileSessionStore(o.sessionPath)); } } // namespace TapiService::TapiService(Options o) : opt_(std::move(o)), cache_(opt_.cacheDir.empty() ? std::string("cache") : opt_.cacheDir), client_(new tapi::Client(opt_.apiId, opt_.apiHash, makeStore(opt_))), secretHistory_(opt_.secretHistoryPath) { catalog_.reset(new tapi::Catalog(*client_)); registerAll(); } TapiService::~TapiService() { cancelAll(); // queued requests end at once as cancelled; a running one stops at its next page pumpStop_ = true; if (queue_ && client_) client_->close_event_queue(queue_); if (pump_.joinable()) pump_.join(); // worker_ is destroyed next (declared after client_), then client_; the worker drains pending jobs first. } std::string TapiService::importAuth(const std::string& tsvPath, const std::string& sessionPath) { try { auto src = storeFromTsv(tsvPath); std::error_code ec; std::filesystem::path p(sessionPath); if (!p.parent_path().empty()) std::filesystem::create_directories(p.parent_path(), ec); tapi::FileSessionStore dst(sessionPath); dst.set_dc(src->dc_id(), src->server_address(), src->port()); dst.set_auth_key(src->auth_key()); dst.save(); return ""; } catch (const std::exception& e) { return e.what(); } } void TapiService::onResult(const std::string& method, const RpcResult& r) { if (opt_.log && !r.ok) opt_.log->warn("service", method + " failed: " + r.error.code + " " + r.error.text); } std::vector TapiService::secrets() const { return {opt_.apiHash, opt_.phone, loginPhone_, std::to_string(opt_.apiId)}; } void TapiService::runOnWorker(std::function fn) { auto pr = std::make_shared>(); auto fu = pr->get_future(); worker_.post([fn, pr]() { fn(); pr->set_value(); }); fu.wait(); } void TapiService::setAuth(const std::string& state) { if (opt_.log) opt_.log->info("auth", "state " + state); { std::lock_guard g(authMutex_); authState_ = state; } authorized_ = (state == "ready"); Object o; o["state"] = Value(state); Event e; e.name = "auth.state"; e.data = Value(std::move(o)); emit(e); } void TapiService::setPremium(PremiumState s) { int old = premium_.exchange((int)s); if (old == (int)s) return; Object o; o["state"] = Value(premiumName(s)); Event e; e.name = "premium.changed"; e.data = Value(std::move(o)); emit(e); } // A login must survive the process ending abnormally: write the session file right away, not only at disconnect. void TapiService::saveSession() { try { client_->session().save(); } catch (const std::exception& e) { if (opt_.log) opt_.log->warn("auth", std::string("saving the session failed: ") + e.what()); } } void TapiService::refreshPremium() { try { auto me = client_->get_me(); if (auto u = tapi::tl::as_tl(me)) setPremium(u->premium ? PremiumState::Premium : PremiumState::NotPremium); } catch (const std::exception&) { // Premium stays at its previous state; the next user update retries. } } void TapiService::start() { if (started_.exchange(true)) return; worker_.post([this]() { try { client_->connect(); { auto saved = secretHistory_.load(); std::lock_guard g(secretMutex_); secretLog_ = std::move(saved); } if (!opt_.secretStorePath.empty()) client_->set_secret_chat_store(std::make_shared(opt_.secretStorePath)); if (opt_.log) opt_.log->info("service", "connected to Telegram"); if (client_->peers().is_user_authorized()) { setAuth("ready"); refreshPremium(); } else { setAuth("need_phone"); } } catch (const std::exception& e) { RpcError err = ErrorMapper::map(e, secrets()); if (opt_.log) opt_.log->error("service", "connect failed: " + err.code + " " + err.text); Object o; o["state"] = Value("disconnected"); o["error"] = Value(err.text); Event ev; ev.name = "connection.state"; ev.data = Value(std::move(o)); emit(ev); } }); tapi::EventFilter f; f.builders.push_back(std::make_shared()); f.builders.push_back(std::make_shared()); f.builders.push_back(std::make_shared()); f.builders.push_back(std::make_shared()); f.builders.push_back(std::make_shared()); f.builders.push_back(std::make_shared()); f.builders.push_back(std::make_shared()); tapi::events::RawFilter rf; rf.types.insert(T::UpdateUser::kConstructorId); rf.types.insert(T::UpdateEncryption::kConstructorId); rf.types.insert(T::UpdateNewEncryptedMessage::kConstructorId); rf.types.insert(T::UpdatePhoneCall::kConstructorId); rf.types.insert(T::UpdateTranscribedAudio::kConstructorId); rf.types.insert(T::UpdateStory::kConstructorId); rf.types.insert(T::UpdateDraftMessage::kConstructorId); rf.types.insert(T::UpdateDialogPinned::kConstructorId); rf.types.insert(T::UpdateDialogUnreadMark::kConstructorId); rf.types.insert(T::UpdateNotifySettings::kConstructorId); f.builders.push_back(std::make_shared(rf)); // Unbounded: no event is ever dropped (D-02). Memory is the only bound. queue_ = client_->event_queue(f, 1, tapi::OverflowPolicy::Unbounded); pump_ = std::thread([this]() { pumpLoop(); }); } void TapiService::pumpLoop() { while (!pumpStop_.load()) { auto ev = queue_->pop(std::chrono::milliseconds(200)); if (!ev) { if (queue_->closed()) return; continue; } if (auto* raw = dynamic_cast(ev.get())) { if (auto uu = tapi::tl::as_tl(raw->raw)) { if (uu->user_id == client_->self_id()) worker_.post([this]() { refreshPremium(); }); } else if (auto ta = tapi::tl::as_tl(raw->raw)) { Object d; d["peer"] = TapiCodec::peerOfPeerObj(ta->peer).toJson(); d["id"] = js::id(ta->msg_id); d["transcription_id"] = js::id(ta->transcription_id); d["text"] = Value(ta->text); d["pending"] = Value(ta->pending); Event e; e.name = "transcription"; e.data = Value(std::move(d)); emit(e); } else if (auto us = tapi::tl::as_tl(raw->raw)) { Object d; d["peer"] = TapiCodec::peerOfPeerObj(us->peer).toJson(); d["story"] = TapiCodec::dict(us->story); Event e; e.name = "story.updated"; e.data = Value(std::move(d)); emit(e); } else if (auto dr = tapi::tl::as_tl(raw->raw)) { Peer pr = TapiCodec::peerOfPeerObj(dr->peer); worker_.post([this, pr]() { emitDialogUpdated(pr); }); } else if (auto dp = tapi::tl::as_tl(raw->raw)) { auto w = tapi::tl::as_tl(dp->peer); Peer pr = w ? TapiCodec::peerOfPeerObj(w->peer) : Peer{}; if (pr.valid()) worker_.post([this, pr]() { emitDialogUpdated(pr); }); } else if (auto um = tapi::tl::as_tl(raw->raw)) { auto w = tapi::tl::as_tl(um->peer); Peer pr = w ? TapiCodec::peerOfPeerObj(w->peer) : Peer{}; if (pr.valid()) worker_.post([this, pr]() { emitDialogUpdated(pr); }); } else if (auto ns = tapi::tl::as_tl(raw->raw)) { auto w = tapi::tl::as_tl(ns->peer); Peer pr = w ? TapiCodec::peerOfPeerObj(w->peer) : Peer{}; if (pr.valid()) worker_.post([this, pr]() { emitDialogUpdated(pr); }); } else { tapi::tl::TlObjectPtr upd = raw->raw; worker_.post([this, upd]() { onSecretOrCallUpdate(upd); }); } continue; } try { if (auto converted = EventConverter::convert(*ev)) emit(*converted); } catch (const std::exception&) { // A malformed event is skipped, never fatal for the pump. } } } void TapiService::reg(const char* name, Member m, bool needsAuth) { regFn(name, [this, m](const Value& p, const CancelFlag& c) { return (this->*m)(p, c); }, needsAuth); } void TapiService::regFn(const char* name, std::function fn, bool needsAuth) { on(name, [this, fn, needsAuth](const Value& p, const CancelFlag& c) -> RpcResult { if (needsAuth && !authorized_.load()) return RpcResult::failure(ErrorCode::NotLoggedIn, "log in first"); try { return fn(p, c); } catch (const std::exception& e) { RpcError err = ErrorMapper::map(e, secrets()); if (err.code == ErrorCode::NotLoggedIn) authorized_ = false; if (err.code == ErrorCode::PremiumRequired) { // The server refused although we may have believed in Premium: re-read the truth on the worker (FR-64). if (premium_.load() == (int)PremiumState::Premium) refreshPremium(); } return RpcResult::failure(err.code, err.text); } }); } tapi::EntityLike TapiService::entityOf(const Peer& peer) { if (!peer.valid()) throw PeerNotFound("(invalid peer)"); tapi::EntityLike e = TapiCodec::entityOf(peer); try { client_->get_input_entity(e); } catch (const tapi::errors::Error&) { throw; } catch (const std::exception&) { throw PeerNotFound(peer.key()); } return e; } tapi::EntityLike TapiService::entity(const Value& p, const char* key) { const Value* v = p.find(key); if (!v) throw PeerNotFound(std::string("(missing ") + key + ")"); return entityOf(Peer::fromJson(*v)); } void TapiService::registerAll() { registerAuth(); registerDialogs(); registerMessages(); registerMedia(); registerPeople(); registerPremium(); registerExtras(); registerStickers(); registerBots(); } // ---- hello and auth ---- RpcResult TapiService::hHello(const Value&, const CancelFlag&) { Object o; o["proto_version"] = Value(1); o["account"] = Value(std::string(authorized_.load() ? "logged in" : "")); o["premium"] = Value(premiumName(premiumState())); { std::lock_guard g(authMutex_); o["auth"] = Value(authState_); } return RpcResult::success(Value(std::move(o))); } RpcResult TapiService::hAuthState(const Value&, const CancelFlag&) { Object o; std::string state; { std::lock_guard g(authMutex_); state = authState_; } o["state"] = Value(state); if (state == "need_password") { // the 2FA password hint, as the server stores it (FR-04); failing to read it must not hide the state try { if (auto pw = tapi::tl::as_tl(client_->invoke(std::make_shared()))) if (pw->hint && !pw->hint->empty()) o["hint"] = Value(*pw->hint); } catch (const std::exception&) { } } return RpcResult::success(Value(std::move(o))); } RpcResult TapiService::hAuthSendPhone(const Value& p, const CancelFlag&) { std::string phone = js::getStr(p, "phone"); if (phone.empty()) phone = opt_.phone; loginPhone_ = phone; auto sent = client_->auth().send_code_request(phone, opt_.apiId, opt_.apiHash); Object o; o["sent"] = Value(true); if (tapi::tl::as_tl(sent)) { // the server signed us in without a code (the key was already authorized) setAuth("ready"); refreshPremium(); o["type"] = Value("already_signed_in"); o["next_type"] = Value(""); return RpcResult::success(Value(std::move(o))); } tapi::SentCodeInfo info = tapi::Auth::describe_sent_code(sent); o["type"] = Value(info.type); o["next_type"] = Value(info.next_type); if (info.timeout > 0) o["timeout"] = Value(info.timeout); if (opt_.log) opt_.log->info("auth", "login code requested, delivery " + info.type + (info.next_type.empty() ? "" : ", resend by " + info.next_type)); setAuth("need_code"); return RpcResult::success(Value(std::move(o))); } RpcResult TapiService::hAuthResendCode(const Value&, const CancelFlag&) { if (loginPhone_.empty()) return RpcResult::failure(ErrorCode::BadParams, "auth.resend_code: send the phone number first"); auto sent = client_->auth().resend_code(opt_.apiId, opt_.apiHash); tapi::SentCodeInfo info = tapi::Auth::describe_sent_code(sent); Object o; o["sent"] = Value(true); o["type"] = Value(info.type); o["next_type"] = Value(info.next_type); if (info.timeout > 0) o["timeout"] = Value(info.timeout); if (opt_.log) opt_.log->info("auth", "login code requested again, delivery " + info.type + (info.next_type.empty() ? "" : ", resend by " + info.next_type)); setAuth("need_code"); return RpcResult::success(Value(std::move(o))); } RpcResult TapiService::hAuthSendCode(const Value& p, const CancelFlag&) { Object o; try { client_->auth().sign_in(loginPhone_, js::getStr(p, "code"), std::nullopt, std::nullopt, std::nullopt, opt_.apiId, opt_.apiHash); } catch (const tapi::errors::SessionPasswordNeededError&) { setAuth("need_password"); o["state"] = Value("need_password"); return RpcResult::success(Value(std::move(o))); } saveSession(); setAuth("ready"); refreshPremium(); o["state"] = Value("ready"); return RpcResult::success(Value(std::move(o))); } RpcResult TapiService::hAuthSendPassword(const Value& p, const CancelFlag&) { client_->auth().sign_in(std::nullopt, std::nullopt, std::nullopt, js::getStr(p, "password"), std::nullopt, opt_.apiId, opt_.apiHash); saveSession(); setAuth("ready"); refreshPremium(); Object o; o["state"] = Value("ready"); return RpcResult::success(Value(std::move(o))); } RpcResult TapiService::hAuthQrStart(const Value&, const CancelFlag&) { auto token = client_->auth().raw_qr_token({}, opt_.apiId, opt_.apiHash); auto qr = tapi::QrLogin::from_raw(client_.get(), token, opt_.apiId, opt_.apiHash); Object o; o["url"] = Value(qr.url()); return RpcResult::success(Value(std::move(o))); } RpcResult TapiService::hAuthLogout(const Value&, const CancelFlag&) { client_->auth().log_out(); setAuth("need_phone"); setPremium(PremiumState::Unknown); if (opt_.authTsv.empty() && !opt_.sessionPath.empty()) { std::error_code ec; std::filesystem::remove(opt_.sessionPath, ec); } return RpcResult::success(Value(Object{})); } void TapiService::registerAuth() { reg("hello", &TapiService::hHello, false); reg("auth.state", &TapiService::hAuthState, false); reg("auth.send_phone", &TapiService::hAuthSendPhone, false); reg("auth.send_code", &TapiService::hAuthSendCode, false); reg("auth.send_password", &TapiService::hAuthSendPassword, false); reg("auth.resend_code", &TapiService::hAuthResendCode, false); reg("auth.qr_start", &TapiService::hAuthQrStart, false); reg("auth.logout", &TapiService::hAuthLogout); } } // namespace mologram namespace mologram { // dialog.updated carries the whole dialog (the UI replaces the row), so the row is read again from the server: pinned and recent // dialogs come first, so the search ends early for the dialogs that change. void TapiService::emitDialogUpdated(const Peer& peer) { try { tapi::IterDialogsOptions o; auto it = client_->dialogs().iter_dialogs(o); tapi::DialogInfo d; while (it.next(d)) { if (TapiCodec::peerOfEntity(d.entity()) == peer) { Dialog dl = TapiCodec::dialog(d); tapi::DraftEntry dr = d.draft(); if (!dr.is_empty()) dl.draft = dr.text(); Object data; data["dialog"] = dl.toJson(); Event e; e.name = "dialog.updated"; e.data = Value(std::move(data)); emit(e); return; } } } catch (const std::exception&) { // the next update or a dialogs.list refresh corrects the row } } } // namespace mologram