// 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"
// TapiService: peers, contacts, chats and account (FR-40, FR-41, FR-50).
#include <algorithm>
#include <filesystem>
#include "mologram/tapi/TapiCodec.hpp"
#include "tapi/account.hpp"
#include "tapi/premium.hpp"
#include "tapi/util.hpp"
#include "tapi/tl/functions.hpp"
#include "mologram/tapi/TapiService.hpp"
#include "tapi/tl/functions.hpp"
#include "tapi/tl/types.hpp"
namespace mologram {
namespace T = tapi::tl::types;
using js::Array;
using js::Object;
using js::Value;
using tapi::tl::as_tl;
using tapi::tl::TlObjectPtr;
RpcResult TapiService::hPeerInfo(const Value& p, const CancelFlag&) {
auto e = client_->get_entity(entity(p, "peer"));
PeerInfo info = TapiCodec::info(e);
// bio ("about") lives in the full object; failing to read it must not hide the rest of the profile
try {
if (as_tl<T::User>(e)) {
auto req = std::make_shared<tapi::tl::functions::users::GetFullUserRequest>();
req->id = tapi::Util::get_input_user(client_->get_input_entity(entity(p, "peer")));
if (auto uf = as_tl<T::users::UserFull>(client_->invoke(req)))
if (auto full = as_tl<T::UserFull>(uf->full_user)) if (full->about) info.bio = *full->about;
}
} catch (const std::exception&) {
}
return RpcResult::success(info.toJson());
}
RpcResult TapiService::hPeerMembers(const Value& p, const CancelFlag&) {
int offset = std::max(0, js::getInt(p, "offset", 0));
tapi::EntityLike e = entity(p, "peer");
auto list = client_->groups().get_participants(e);
std::map<std::int64_t, int> roles; // user id -> 1 admin, 2 owner
try {
roles = client_->groups().admin_roles(e);
} catch (const std::exception&) {
// roles are decoration: the member list is still correct without them
}
Array a;
for (size_t i = (size_t)offset; i < list.size(); i++) {
PeerInfo info = TapiCodec::info(list[i]);
Value v = info.toJson();
Object o = *v.asObj();
auto r = roles.find(info.peer.id);
o["role"] = Value(r == roles.end() ? std::string() : r->second == 2 ? std::string("owner") : std::string("admin"));
a.push_back(Value(std::move(o)));
}
Object o;
o["members"] = Value(std::move(a));
return RpcResult::success(Value(std::move(o)));
}
RpcResult TapiService::hContactsList(const Value&, const CancelFlag&) {
Array a;
for (const auto& u : client_->contacts().get_contacts()) a.push_back(TapiCodec::info(u).toJson());
Object o;
o["contacts"] = Value(std::move(a));
return RpcResult::success(Value(std::move(o)));
}
RpcResult TapiService::hContactsSearch(const Value& p, const CancelFlag&) {
auto found = as_tl<T::contacts::Found>(client_->contacts().search(js::getStr(p, "query"), 100)); // 100 = rows the server returns per search call
Array a;
if (found) {
for (const auto& u : found->users) a.push_back(TapiCodec::info(u).toJson());
for (const auto& c : found->chats) a.push_back(TapiCodec::info(c).toJson());
}
Object o;
o["peers"] = Value(std::move(a));
return RpcResult::success(Value(std::move(o)));
}
RpcResult TapiService::hContactsAdd(const Value& p, const CancelFlag&) {
client_->contacts().add_contact(entity(p, "user"), js::getStr(p, "name"));
return RpcResult::success(Value(Object{}));
}
RpcResult TapiService::hContactsImport(const Value& p, const CancelFlag&) {
std::vector<tapi::ContactInput> in;
if (const Array* a = js::getArr(p, "contacts"))
for (const auto& e : *a) {
tapi::ContactInput c;
std::string name = js::getStr(e, "name");
size_t sp = name.find(' ');
c.first_name = sp == std::string::npos ? name : name.substr(0, sp);
c.last_name = sp == std::string::npos ? std::string() : name.substr(sp + 1);
c.phone = js::getStr(e, "phone");
if (c.phone.empty()) return RpcResult::failure(ErrorCode::BadParams, "contacts.import: every contact needs a phone");
c.client_id = (std::int64_t)in.size();
in.push_back(std::move(c));
}
auto res = as_tl<T::contacts::ImportedContacts>(client_->contacts().import_contacts(in));
Object o;
o["imported"] = Value(res ? (int)res->imported.size() : 0);
o["not_on_telegram"] = Value(res ? (int)(in.size() - res->imported.size() - res->retry_contacts.size()) : 0);
return RpcResult::success(Value(std::move(o)));
}
RpcResult TapiService::hContactsBlock(const Value& p, const CancelFlag&) {
tapi::EntityLike e = entity(p, "user");
if (js::getBool(p, "on")) client_->contacts().block(e); else client_->contacts().unblock(e);
return RpcResult::success(Value(Object{}));
}
/// First chat/channel entity found in an Updates-like reply (create/join results).
static Peer firstChatPeer(const TlObjectPtr& r) {
TlObjectPtr u = r;
if (auto inv = as_tl<T::messages::InvitedUsers>(u)) u = inv->updates;
if (auto up = as_tl<T::Updates>(u)) for (const auto& c : up->chats) { Peer p = TapiCodec::peerOfEntity(c); if (p.valid()) return p; }
if (auto up = as_tl<T::UpdatesCombined>(u)) for (const auto& c : up->chats) { Peer p = TapiCodec::peerOfEntity(c); if (p.valid()) return p; }
return {};
}
RpcResult TapiService::hChatCreate(const Value& p, const CancelFlag&) {
std::string kind = js::getStr(p, "kind");
std::string title = js::getStr(p, "title");
TlObjectPtr res;
if (kind == "group") {
std::vector<tapi::EntityLike> users;
if (const Array* a = js::getArr(p, "members")) for (const auto& e : *a) users.push_back(entityOf(Peer::fromJson(e)));
res = client_->groups().create_group(title, users);
} else {
res = client_->groups().create_channel(title, "", kind == "supergroup" || kind == "forum", kind == "forum");
}
Peer peer = firstChatPeer(res);
if (!peer.valid()) return RpcResult::failure(ErrorCode::RpcError, "CHAT_CREATE_FAILED: the server returned no chat");
return RpcResult::success(peer.toJson());
}
RpcResult TapiService::hChatJoin(const Value& p, const CancelFlag&) {
Peer peer = firstChatPeer(client_->groups().join_chat(js::getStr(p, "link_or_name")));
if (!peer.valid()) return RpcResult::failure(ErrorCode::RpcError, "CHAT_JOIN_FAILED: the server returned no chat");
return RpcResult::success(peer.toJson());
}
RpcResult TapiService::hChatLeave(const Value& p, const CancelFlag&) {
client_->groups().leave(entity(p, "peer"));
return RpcResult::success(Value(Object{}));
}
RpcResult TapiService::hChatDelete(const Value& p, const CancelFlag&) {
client_->groups().delete_chat(entity(p, "peer"));
return RpcResult::success(Value(Object{}));
}
RpcResult TapiService::hChatInviteLink(const Value& p, const CancelFlag&) {
auto inv = as_tl<T::ChatInviteExported>(client_->groups().export_invite_link(entity(p, "peer")));
if (!inv) return RpcResult::failure(ErrorCode::RpcError, "INVITE_LINK_FAILED");
Object o;
o["link"] = Value(inv->link);
return RpcResult::success(Value(std::move(o)));
}
RpcResult TapiService::hChatAddMembers(const Value& p, const CancelFlag&) {
std::vector<tapi::EntityLike> users;
if (const Array* a = js::getArr(p, "users")) for (const auto& e : *a) users.push_back(entityOf(Peer::fromJson(e)));
if (users.empty()) return RpcResult::failure(ErrorCode::BadParams, "chat.add_members: users is empty");
int missing = 0; // people the server could not add (their privacy settings), reported, not an error for the rest
for (const auto& r : client_->groups().add_participants(entity(p, "peer"), users))
if (auto inv = as_tl<T::messages::InvitedUsers>(r)) missing += (int)inv->missing_invitees.size();
Object o;
o["missing"] = Value(missing);
return RpcResult::success(Value(std::move(o)));
}
RpcResult TapiService::hChatRemoveMember(const Value& p, const CancelFlag&) {
client_->groups().kick_participant(entity(p, "peer"), entity(p, "user"));
return RpcResult::success(Value(Object{}));
}
RpcResult TapiService::hChatSetAdmin(const Value& p, const CancelFlag&) {
client_->groups().promote(entity(p, "peer"), entity(p, "user"), js::getBool(p, "on"));
return RpcResult::success(Value(Object{}));
}
RpcResult TapiService::hAccountProfile(const Value&, const CancelFlag&) {
auto me = client_->get_me();
PeerInfo i = TapiCodec::info(me);
Object o;
o["name"] = Value(i.name);
o["username"] = Value(i.username);
o["phone"] = Value(i.phone);
o["bio"] = Value(i.bio);
o["premium"] = Value(premiumName(premiumState()));
o["peer"] = i.peer.toJson(); // the account's own peer (Saved Messages)
return RpcResult::success(Value(std::move(o)));
}
RpcResult TapiService::hAccountUpdateProfile(const Value& p, const CancelFlag&) {
const Value* f = p.find("fields");
if (!f || !f->isObj()) return RpcResult::failure(ErrorCode::BadParams, "account.update_profile: fields must be an object");
auto opt = [&](const char* k) -> std::optional<std::string> { const Value* v = f->find(k); return v && v->isStr() ? std::optional<std::string>(v->asStr()) : std::nullopt; };
if (opt("first_name") || opt("last_name") || opt("about")) client_->account().update_profile(opt("first_name"), opt("last_name"), opt("about"));
if (auto un = opt("username")) client_->account().update_username(*un);
return hAccountProfile(p, CancelFlag(std::make_shared<std::atomic<bool>>(false)));
}
RpcResult TapiService::hAccountSessions(const Value&, const CancelFlag&) {
Array a;
for (const auto& s : client_->account().get_authorizations()) {
auto au = as_tl<T::Authorization>(s);
if (!au) continue;
Object o;
o["hash"] = js::id(au->hash);
o["device"] = Value(au->device_model + " (" + au->app_name + " " + au->app_version + ")");
o["platform"] = Value(au->platform);
o["ip"] = Value(au->ip);
o["current"] = Value(au->current);
a.push_back(Value(std::move(o)));
}
Object r;
r["sessions"] = Value(std::move(a));
return RpcResult::success(Value(std::move(r)));
}
RpcResult TapiService::hAccountTerminate(const Value& p, const CancelFlag&) {
std::int64_t hash = js::getId(p, "hash");
for (const auto& s : client_->account().get_authorizations())
if (auto au = as_tl<T::Authorization>(s))
if (au->hash == hash && au->current) return RpcResult::failure(ErrorCode::RpcError, "SESSION_IN_USE: this is the session mologram uses");
client_->account().reset_authorization(hash);
return RpcResult::success(Value(Object{}));
}
namespace {
struct PrivacyName { const char* name; tapi::PrivacyKey key; };
const std::vector<PrivacyName>& privacyNames() {
static const std::vector<PrivacyName> n = {
{"last_seen", tapi::PrivacyKey::StatusTimestamp}, {"profile_photo", tapi::PrivacyKey::ProfilePhoto},
{"phone_number", tapi::PrivacyKey::PhoneNumber}, {"calls", tapi::PrivacyKey::PhoneCall},
{"groups", tapi::PrivacyKey::ChatInvite}, {"forwards", tapi::PrivacyKey::Forwards}, {"about", tapi::PrivacyKey::About},
{"voice_messages", tapi::PrivacyKey::VoiceMessages}};
return n;
}
const char* ruleName(tapi::PrivacyRule r) { return r == tapi::PrivacyRule::Everybody ? "everybody" : r == tapi::PrivacyRule::Contacts ? "contacts" : "nobody"; }
bool ruleFrom(const std::string& s, tapi::PrivacyRule& r) {
if (s == "everybody") r = tapi::PrivacyRule::Everybody;
else if (s == "contacts") r = tapi::PrivacyRule::Contacts;
else if (s == "nobody") r = tapi::PrivacyRule::Nobody;
else return false; // unknown values are rejected, never guessed (a wrong guess once made a story public)
return true;
}
} // namespace
RpcResult TapiService::hAccountPrivacy(const Value& p, const CancelFlag&) {
std::string key = js::getStr(p, "key");
Object o;
o["key"] = Value(key);
if (key == "read_time") { // Premium: who sees when we read; stored as the global hide_read_marks flag
o["rule"] = Value(client_->premium().get_global_privacy().hide_read_marks ? "nobody" : "everybody");
return RpcResult::success(Value(std::move(o)));
}
for (const auto& k : privacyNames()) {
if (key != k.name) continue;
o["rule"] = Value(ruleName(client_->account().privacy_rule(k.key)));
Array rules;
if (auto pr = as_tl<T::account::PrivacyRules>(client_->account().get_privacy(k.key)))
for (const auto& r : pr->rules) rules.push_back(Value(std::string(r->type_name())));
o["rules"] = Value(std::move(rules)); // the raw rules, exceptions included
return RpcResult::success(Value(std::move(o)));
}
return RpcResult::failure(ErrorCode::BadParams, "account.privacy: unknown key " + key);
}
RpcResult TapiService::hAccountSetPrivacy(const Value& p, const CancelFlag&) {
std::string key = js::getStr(p, "key");
tapi::PrivacyRule rule;
if (!ruleFrom(js::getStr(p, "rule"), rule)) return RpcResult::failure(ErrorCode::BadParams, "account.set_privacy: rule is everybody, contacts or nobody");
if (key == "read_time") {
if (rule == tapi::PrivacyRule::Contacts) return RpcResult::failure(ErrorCode::BadParams, "account.set_privacy: read_time is everybody or nobody");
tapi::GlobalPrivacy g = client_->premium().get_global_privacy(); // read-modify-write: the other global settings stay as they are
g.hide_read_marks = (rule == tapi::PrivacyRule::Nobody);
client_->premium().set_global_privacy(g);
return RpcResult::success(Value(Object{}));
}
for (const auto& k : privacyNames()) {
if (key != k.name) continue;
client_->account().set_privacy_rule(k.key, rule);
return RpcResult::success(Value(Object{}));
}
return RpcResult::failure(ErrorCode::BadParams, "account.set_privacy: unknown key " + key);
}
namespace {
struct ScopeName { const char* name; tapi::NotifyScope scope; };
const std::vector<ScopeName>& scopeNames() {
static const std::vector<ScopeName> n = {{"private", tapi::NotifyScope::Users}, {"groups", tapi::NotifyScope::Chats}, {"channels", tapi::NotifyScope::Broadcasts}};
return n;
}
} // namespace
RpcResult TapiService::hAccountNotifications(const Value&, const CancelFlag&) {
Object o;
for (const auto& sc : scopeNames()) {
Object s;
s["muted"] = Value(client_->account().scope_muted(sc.scope));
o[sc.name] = Value(std::move(s));
}
return RpcResult::success(Value(std::move(o)));
}
RpcResult TapiService::hAccountSetNotifications(const Value& p, const CancelFlag&) {
std::string scope = js::getStr(p, "scope");
for (const auto& sc : scopeNames()) {
if (scope != sc.name) continue;
client_->account().set_scope_mute(sc.scope, js::getBool(p, "muted") ? tapi::Account::kMuteForever : 0);
return RpcResult::success(Value(Object{}));
}
return RpcResult::failure(ErrorCode::BadParams, "account.set_notifications: scope is private, groups or channels");
}
void TapiService::registerPeople() {
reg("peer.info", &TapiService::hPeerInfo);
reg("peer.members", &TapiService::hPeerMembers);
reg("contacts.list", &TapiService::hContactsList);
reg("contacts.search", &TapiService::hContactsSearch);
reg("contacts.add", &TapiService::hContactsAdd);
reg("contacts.block", &TapiService::hContactsBlock);
reg("contacts.import", &TapiService::hContactsImport);
reg("chat.create", &TapiService::hChatCreate);
reg("chat.join", &TapiService::hChatJoin);
reg("chat.leave", &TapiService::hChatLeave);
reg("chat.delete", &TapiService::hChatDelete);
reg("chat.invite_link", &TapiService::hChatInviteLink);
reg("chat.add_members", &TapiService::hChatAddMembers);
reg("chat.remove_member", &TapiService::hChatRemoveMember);
reg("chat.set_admin", &TapiService::hChatSetAdmin);
reg("account.profile", &TapiService::hAccountProfile);
reg("account.update_profile", &TapiService::hAccountUpdateProfile);
reg("account.sessions", &TapiService::hAccountSessions);
reg("account.terminate_session", &TapiService::hAccountTerminate);
reg("account.privacy", &TapiService::hAccountPrivacy);
reg("account.set_privacy", &TapiService::hAccountSetPrivacy);
reg("account.notifications", &TapiService::hAccountNotifications);
reg("account.set_notifications", &TapiService::hAccountSetNotifications);
}
} // namespace mologram