Skip to content
Repos

mologram

C++ 24.9 KB428 lines Opens in site

Directory Raw Download

// 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: Business, stories, gifts, payments, Passport, secret chats, calls, folder tags (SPEC section 6.4). Every handler is a thin
// translation between protocol JSON and the typed tapi wrappers; errors reach callers through the single ErrorMapper.
#include <fstream>

#include "mologram/tapi/TapiCodec.hpp"
#include "mologram/tapi/TapiService.hpp"
#include "mologram/tapi/VideoProbe.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;

static Value okv() { return Value(Object{}); }
static Value wrap(const char* key, Value v) { Object o; o[key] = std::move(v); return Value(std::move(o)); }

static tapi::BusinessRecipients recipientsOf(const Value* v) {
  tapi::BusinessRecipients r;
  if (!v || !v->isObj()) return r;
  r.existing_chats = js::getBool(*v, "existing_chats"); r.new_chats = js::getBool(*v, "new_chats");
  r.contacts = js::getBool(*v, "contacts"); r.non_contacts = js::getBool(*v, "non_contacts");
  r.exclude_selected = js::getBool(*v, "exclude_selected");
  auto fill = [](const Value* arr, std::vector<tapi::EntityLike>& out) {
    if (!arr || !arr->isArr()) return;
    for (const auto& u : *arr->asArr()) out.push_back(TapiCodec::entityOf(Peer::fromJson(u)));
  };
  fill(v->find("users"), r.users);
  fill(v->find("exclude_users"), r.exclude_users);
  return r;
}

static Value qrInfo(const tapi::QuickReplyInfo& q) {
  Object o; o["id"] = Value(q.id); o["shortcut"] = Value(q.shortcut); o["top_message"] = Value(q.top_message); o["count"] = Value(q.count);
  return Value(std::move(o));
}

static Value secretJson(const tapi::SecretChatState& s) {
  const char* st = s.status == tapi::SecretChatState::Status::Waiting ? "waiting" : s.status == tapi::SecretChatState::Status::Requested ? "requested"
                   : s.status == tapi::SecretChatState::Status::Ready ? "ready" : "discarded";
  Object o;
  o["id"] = Value((int)s.id); o["status"] = Value(st); o["originator"] = Value(s.originator);
  o["user"] = Peer{PeerKind::User, s.originator ? s.participant_id : s.admin_id}.toJson();
  o["ttl"] = Value((int)s.ttl);
  return Value(std::move(o));
}

static Value secretMessageJson(const tapi::SecretMessage& m) {
  Object o;
  o["chat"] = Value((int)m.chat_id); o["random_id"] = js::id(m.random_id); o["date"] = js::id(m.date); o["text"] = Value(m.text);
  o["ttl"] = Value((int)m.ttl); o["out"] = Value(m.outgoing);
  if (!m.service.empty()) { o["service"] = Value(m.service); o["value"] = Value((int)m.value); }
  return Value(std::move(o));
}

static const char* callStateName(tapi::CallState s) {
  switch (s) {
    case tapi::CallState::Requesting: return "requesting";
    case tapi::CallState::Ringing: return "ringing";
    case tapi::CallState::Accepting: return "accepting";
    case tapi::CallState::Exchanging: return "exchanging";
    case tapi::CallState::Active: return "active";
    case tapi::CallState::Ended: return "ended";
  }
  return "ended";
}

static Value callJson(const tapi::CallInfo& c) {
  Object o;
  o["id"] = js::id(c.id); o["user"] = Peer{PeerKind::User, c.outgoing ? c.participant_id : c.admin_id}.toJson();
  o["outgoing"] = Value(c.outgoing); o["video"] = Value(c.video); o["state"] = Value(callStateName(c.state));
  o["fingerprint"] = js::id(c.fingerprint);  // the key itself never leaves tapi
  Array conns;
  for (const auto& k : c.connections) { Object x; x["ip"] = Value(k.ip); x["port"] = Value(k.port); x["tcp"] = Value(k.tcp); conns.push_back(Value(std::move(x))); }
  o["connections"] = Value(std::move(conns));
  o["end_reason"] = Value(c.end_reason); o["duration"] = Value((int)c.duration); o["need_rating"] = Value(c.need_rating);
  o["media"] = Value("signaling_only");  // honest: no audio transport exists (BUILD-TRACK M11)
  return Value(std::move(o));
}

void TapiService::registerExtras() {
  // ---------------------------------------------------------------- folders (color tag is Premium)
  regFn("dialogs.folder_set", [this](const Value& p, const CancelFlag&) {
    const Value* f = p.find("folder");
    if (!f || !f->isObj()) return RpcResult::failure(ErrorCode::BadParams, "folder must be an object");
    int id = js::getInt(*f, "id");
    std::shared_ptr<T::DialogFilter> filter;
    for (const auto& e : client_->dialogs().get_filters()) if (auto d = tapi::tl::as_tl<T::DialogFilter>(e)) if (d->id == id) filter = std::make_shared<T::DialogFilter>(*d);
    if (!filter) filter = std::make_shared<T::DialogFilter>();
    auto title = std::make_shared<T::TextWithEntities>();
    title->text = js::getStr(*f, "title");
    filter->title = title;
    if (f->find("emoticon")) filter->emoticon = js::getStr(*f, "emoticon");
    if (f->find("color")) filter->color = js::getInt(*f, "color");
    if (id == 0) { id = client_->dialogs().create_filter(filter); }
    else client_->dialogs().update_filter(id, filter);
    Object o; o["id"] = Value(id); o["title"] = Value(title->text);
    return RpcResult::success(Value(std::move(o)));
  });

  // ---------------------------------------------------------------- Business
  regFn("business.get", [this](const Value&, const CancelFlag&) {
    tapi::BusinessSettings s = client_->business().get_settings();
    Object o;
    o["hours"] = TapiCodec::dict(s.work_hours); o["location"] = TapiCodec::dict(s.location); o["greeting"] = TapiCodec::dict(s.greeting);
    o["away"] = TapiCodec::dict(s.away); o["intro"] = TapiCodec::dict(s.intro);
    return RpcResult::success(Value(std::move(o)));
  });
  regFn("business.hours_set", [this](const Value& p, const CancelFlag&) {
    const Value* h = p.find("hours");
    std::optional<tapi::WorkHours> wh;
    if (h && h->isObj()) {
      tapi::WorkHours w; w.timezone_id = js::getStr(*h, "timezone_id");
      if (const Array* a = js::getArr(*h, "weekly")) for (const auto& e : *a) w.weekly.push_back({js::getInt(e, "start"), js::getInt(e, "end")});
      wh = w;
    }
    client_->business().set_work_hours(wh);
    return RpcResult::success(okv());
  });
  regFn("business.location_set", [this](const Value& p, const CancelFlag&) {
    const Value* l = p.find("location");
    std::optional<tapi::BusinessGeo> g;
    if (l && l->isObj()) {
      tapi::BusinessGeo geo; geo.address = js::getStr(*l, "address");
      if (l->find("lat") && l->find("lon")) { geo.lat = l->find("lat")->asNum(); geo.lon = l->find("lon")->asNum(); }
      g = geo;
    }
    client_->business().set_location(g);
    return RpcResult::success(okv());
  });
  regFn("business.greeting_set", [this](const Value& p, const CancelFlag&) {
    const Value* g = p.find("greeting");
    std::optional<tapi::GreetingMessage> m;
    if (g && g->isObj()) {
      tapi::GreetingMessage x; x.shortcut_id = js::getInt(*g, "shortcut_id"); x.no_activity_days = js::getInt(*g, "no_activity_days", 7);
      x.recipients = recipientsOf(g->find("recipients"));
      m = x;
    }
    client_->business().set_greeting(m);
    return RpcResult::success(okv());
  });
  regFn("business.away_set", [this](const Value& p, const CancelFlag&) {
    const Value* a = p.find("away");
    std::optional<tapi::AwayMessage> m;
    if (a && a->isObj()) {
      tapi::AwayMessage x; x.shortcut_id = js::getInt(*a, "shortcut_id"); x.offline_only = js::getBool(*a, "offline_only");
      std::string sch = js::getStr(*a, "schedule", "always");
      x.schedule = sch == "custom" ? tapi::AwaySchedule::Custom : sch == "outside_hours" ? tapi::AwaySchedule::OutsideWorkHours : tapi::AwaySchedule::Always;
      x.start = js::getId(*a, "start"); x.end = js::getId(*a, "end");
      x.recipients = recipientsOf(a->find("recipients"));
      m = x;
    }
    client_->business().set_away(m);
    return RpcResult::success(okv());
  });
  regFn("business.intro_set", [this](const Value& p, const CancelFlag&) {
    const Value* i = p.find("intro");
    std::optional<tapi::BusinessIntro> m;
    if (i && i->isObj()) m = tapi::BusinessIntro{js::getStr(*i, "title"), js::getStr(*i, "description")};
    client_->business().set_intro(m);
    return RpcResult::success(okv());
  });
  regFn("business.bots", [this](const Value&, const CancelFlag&) { return RpcResult::success(wrap("bots", TapiCodec::dicts(client_->business().connected_bots()))); });
  regFn("business.bot_set", [this](const Value& p, const CancelFlag&) {
    tapi::BotRights r;
    if (const Value* x = p.find("rights"); x && x->isObj()) {
      r.reply = js::getBool(*x, "reply", true); r.read_messages = js::getBool(*x, "read_messages");
      r.delete_sent_messages = js::getBool(*x, "delete_sent_messages"); r.delete_received_messages = js::getBool(*x, "delete_received_messages");
      r.edit_name = js::getBool(*x, "edit_name"); r.edit_bio = js::getBool(*x, "edit_bio"); r.edit_profile_photo = js::getBool(*x, "edit_profile_photo");
      r.edit_username = js::getBool(*x, "edit_username"); r.view_gifts = js::getBool(*x, "view_gifts"); r.sell_gifts = js::getBool(*x, "sell_gifts");
      r.change_gift_settings = js::getBool(*x, "change_gift_settings"); r.transfer_and_upgrade_gifts = js::getBool(*x, "transfer_and_upgrade_gifts");
      r.transfer_stars = js::getBool(*x, "transfer_stars"); r.manage_stories = js::getBool(*x, "manage_stories");
    }
    client_->business().set_connected_bot(entity(p, "bot"), recipientsOf(p.find("recipients")), r, js::getBool(p, "remove"));
    return RpcResult::success(okv());
  });
  regFn("business.quick_replies", [this](const Value&, const CancelFlag&) {
    Array a; for (const auto& q : client_->business().quick_replies()) a.push_back(qrInfo(q));
    return RpcResult::success(wrap("replies", Value(std::move(a))));
  });
  regFn("business.quick_reply_messages", [this](const Value& p, const CancelFlag&) {
    return RpcResult::success(wrap("messages", TapiCodec::dicts(client_->business().quick_reply_messages(js::getInt(p, "id")))));
  });
  regFn("business.quick_reply_add", [this](const Value& p, const CancelFlag&) {
    return RpcResult::success(TapiCodec::dict(client_->business().add_quick_reply_message(js::getStr(p, "shortcut"), js::getStr(p, "text"))));
  });
  regFn("business.quick_reply_rename", [this](const Value& p, const CancelFlag&) {
    client_->business().rename_shortcut(js::getInt(p, "id"), js::getStr(p, "shortcut"));
    return RpcResult::success(okv());
  });
  regFn("business.quick_reply_delete", [this](const Value& p, const CancelFlag&) {
    client_->business().delete_shortcut(js::getInt(p, "id"));
    return RpcResult::success(okv());
  });
  regFn("business.quick_reply_send", [this](const Value& p, const CancelFlag&) {
    client_->business().send_quick_reply(entity(p, "peer"), js::getInt(p, "id"));
    return RpcResult::success(okv());
  });
  regFn("business.chat_links", [this](const Value&, const CancelFlag&) { return RpcResult::success(wrap("links", TapiCodec::dicts(client_->business().chat_links()))); });
  regFn("business.chat_link_create", [this](const Value& p, const CancelFlag&) {
    std::optional<std::string> title;
    if (p.find("title")) title = js::getStr(p, "title");
    return RpcResult::success(TapiCodec::dict(client_->business().create_chat_link(js::getStr(p, "message"), title)));
  });
  regFn("business.chat_link_delete", [this](const Value& p, const CancelFlag&) {
    client_->business().delete_chat_link(js::getStr(p, "slug"));
    return RpcResult::success(okv());
  });

  // ---------------------------------------------------------------- Stories
  auto ids32 = [](const Value& p, const char* key) {
    std::vector<std::int32_t> v;
    if (const Array* a = js::getArr(p, key)) for (const auto& e : *a) v.push_back((std::int32_t)(e.isStr() ? std::stoll(e.asStr()) : (std::int64_t)e.asNum()));
    return v;
  };
  regFn("stories.list", [this](const Value& p, const CancelFlag&) {
    std::optional<std::string> state;
    if (p.find("state")) state = js::getStr(p, "state");
    return RpcResult::success(wrap("stories", TapiCodec::dict(client_->stories().all_stories(js::getBool(p, "hidden"), state.has_value(), state))));
  });
  regFn("stories.peer", [this](const Value& p, const CancelFlag&) { return RpcResult::success(wrap("stories", TapiCodec::dict(client_->stories().peer_stories(entity(p, "peer"))))); });
  regFn("stories.read", [this](const Value& p, const CancelFlag&) {
    client_->stories().mark_read(entity(p, "peer"), js::getInt(p, "max_id"));
    return RpcResult::success(okv());
  });
  regFn("stories.send", [this](const Value& p, const CancelFlag& c) {
    std::string path = js::getStr(p, "path");
    tapi::FileInput fi; fi.payload = path;
    tapi::UploadOptions up;
    tapi::tl::TlObjectPtr handle = client_->media().transfer().upload_file(fi, up);
    if (c.cancelled()) return RpcResult::failure(ErrorCode::Cancelled, "cancelled");
    std::string ext = path.substr(path.rfind('.') == std::string::npos ? path.size() : path.rfind('.'));
    for (auto& ch : ext) ch = (char)std::tolower((unsigned char)ch);
    tapi::tl::TlObjectPtr media;
    if (ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".webp") {
      auto photo = std::make_shared<T::InputMediaUploadedPhoto>();
      photo->file = handle;
      media = photo;
    } else if (VideoProbe::isVideoPath(path)) {
      // a video story needs its size and length; without ffprobe they are unknown and the story is refused, not guessed
      VideoInfo vi = VideoProbe::probe(path);
      if (!vi.known) return RpcResult::failure(ErrorCode::RpcError, "VIDEO_STORY_UNREADABLE: ffprobe is needed to read the video's size and length");
      auto doc = std::make_shared<T::InputMediaUploadedDocument>();
      doc->file = handle;
      doc->mime_type = ext == ".webm" ? "video/webm" : ext == ".mov" ? "video/quicktime" : ext == ".mkv" ? "video/x-matroska" : "video/mp4";
      doc->attributes.push_back(VideoProbe::attribute(vi));
      media = doc;
    } else {
      return RpcResult::failure(ErrorCode::BadParams, "stories.send: a story is a photo (jpg, png, webp) or a video (mp4, mov, m4v, webm, mkv)");
    }
    std::vector<tapi::tl::TlObjectPtr> rules;
    std::string who = js::getStr(p, "privacy", "everyone");
    if (who == "contacts") rules.push_back(std::make_shared<T::InputPrivacyValueAllowContacts>());
    else if (who == "close_friends") rules.push_back(std::make_shared<T::InputPrivacyValueAllowCloseFriends>());
    else if (who == "self") {  // visible to nobody but you: allow exactly one user, yourself (DisallowAll alone is refused by the server)
      auto only = std::make_shared<T::InputPrivacyValueAllowUsers>();
      only->users.push_back(std::make_shared<T::InputUserSelf>());
      rules.push_back(only);
    }
    else if (who == "everyone") rules.push_back(std::make_shared<T::InputPrivacyValueAllowAll>());
    else return RpcResult::failure(ErrorCode::BadParams, "privacy: everyone, contacts, close_friends or self");  // never fall back to a wider audience
    std::optional<std::string> caption;
    if (p.find("caption")) caption = js::getStr(p, "caption");
    std::optional<std::int32_t> period;
    if (p.find("period")) period = js::getInt(p, "period");
    auto res = client_->stories().send_story(tapi::EntityLike(std::string("me")), media, caption, rules, period, js::getBool(p, "pinned"));
    return RpcResult::success(TapiCodec::dict(res));
  });
  regFn("stories.delete", [this, ids32](const Value& p, const CancelFlag&) {
    client_->stories().delete_story(entity(p, "peer"), ids32(p, "ids"));
    return RpcResult::success(okv());
  });
  regFn("stories.views", [this, ids32](const Value& p, const CancelFlag&) { return RpcResult::success(wrap("views", TapiCodec::dict(client_->stories().story_views(entity(p, "peer"), ids32(p, "ids"))))); });
  regFn("stories.view_list", [this](const Value& p, const CancelFlag&) {
    return RpcResult::success(wrap("views", TapiCodec::dict(client_->stories().view_list(entity(p, "peer"), js::getInt(p, "id"), js::getStr(p, "offset"), js::getInt(p, "limit", 50)))));
  });
  regFn("stories.react", [this](const Value& p, const CancelFlag&) {
    const Value* r = p.find("reaction");
    tapi::Reaction rx = (r && js::getId(*r, "custom")) ? tapi::Reaction::custom(js::getId(*r, "custom")) : tapi::Reaction::emoji(r ? js::getStr(*r, "emoji") : "");
    client_->stories().react(entity(p, "peer"), js::getInt(p, "id"), rx, true);
    return RpcResult::success(okv());
  });
  regFn("stories.archive", [this](const Value& p, const CancelFlag&) {
    return RpcResult::success(wrap("stories", TapiCodec::dict(client_->stories().archive(entity(p, "peer"), js::getInt(p, "offset_id"), js::getInt(p, "limit", 50)))));
  });
  regFn("stories.stealth", [this](const Value& p, const CancelFlag&) {
    client_->stories().activate_stealth(js::getBool(p, "past", true), js::getBool(p, "future", true));
    return RpcResult::success(okv());
  });
  regFn("stories.pin", [this, ids32](const Value& p, const CancelFlag&) {
    client_->stories().set_pinned(entity(p, "peer"), ids32(p, "ids"), js::getBool(p, "pinned"));
    return RpcResult::success(okv());
  });
  regFn("stories.link", [this](const Value& p, const CancelFlag&) { return RpcResult::success(wrap("link", Value(client_->stories().export_link(entity(p, "peer"), js::getInt(p, "id"))))); });

  // ---------------------------------------------------------------- Gifts, payments, Passport
  regFn("gifts.list", [this](const Value&, const CancelFlag&) { return RpcResult::success(wrap("gifts", TapiCodec::dicts(client_->payments().star_gifts()))); });
  regFn("gifts.saved", [this](const Value& p, const CancelFlag&) {
    return RpcResult::success(wrap("gifts", TapiCodec::dict(client_->payments().saved_gifts(entity(p, "peer"), js::getStr(p, "offset"), js::getInt(p, "limit", 50)))));
  });
  regFn("gifts.stars", [this](const Value& p, const CancelFlag&) {
    tapi::EntityLike who = p.find("peer") ? entity(p, "peer") : tapi::EntityLike(std::string("me"));
    return RpcResult::success(TapiCodec::dict(client_->payments().stars_status(who)));
  });
  regFn("gifts.send", [this](const Value& p, const CancelFlag&) {
    if (!js::getBool(p, "confirm")) return RpcResult::failure(ErrorCode::RpcError, "CONFIRM_REQUIRED");
    std::optional<std::string> msg;
    if (p.find("message")) msg = js::getStr(p, "message");
    return RpcResult::success(TapiCodec::dict(client_->payments().send_gift(entity(p, "peer"), js::getId(p, "gift"), msg, js::getBool(p, "hide_name"), true)));
  });
  regFn("payments.form", [this](const Value& p, const CancelFlag&) { return RpcResult::success(TapiCodec::dict(client_->payments().payment_form(entity(p, "peer"), js::getInt(p, "id")))); });
  regFn("payments.receipt", [this](const Value& p, const CancelFlag&) { return RpcResult::success(TapiCodec::dict(client_->payments().payment_receipt(entity(p, "peer"), js::getInt(p, "id")))); });
  regFn("passport.values", [this](const Value&, const CancelFlag&) { return RpcResult::success(wrap("values", TapiCodec::dicts(client_->payments().passport_values()))); });

  // ---------------------------------------------------------------- Secret chats
  regFn("secret.list", [this](const Value&, const CancelFlag&) {
    Array a; for (const auto& s : client_->secret_chats().list()) a.push_back(secretJson(s));
    return RpcResult::success(wrap("chats", Value(std::move(a))));
  });
  regFn("secret.request", [this](const Value& p, const CancelFlag&) { return RpcResult::success(secretJson(client_->secret_chats().request(entity(p, "user")))); });
  regFn("secret.accept", [this](const Value& p, const CancelFlag&) { return RpcResult::success(secretJson(client_->secret_chats().accept(js::getInt(p, "chat")))); });
  regFn("secret.discard", [this](const Value& p, const CancelFlag&) {
    client_->secret_chats().discard(js::getInt(p, "chat"), js::getBool(p, "delete_history"));
    return RpcResult::success(okv());
  });
  regFn("secret.send", [this](const Value& p, const CancelFlag&) {
    if (js::getStr(p, "text").empty()) return RpcResult::failure(ErrorCode::RpcError, "MESSAGE_EMPTY");
    tapi::SecretMessage m = client_->secret_chats().send_text(js::getInt(p, "chat"), js::getStr(p, "text"), js::getInt(p, "ttl"));
    Value j = secretMessageJson(m);
    recordSecret(m.chat_id, j);
    return RpcResult::success(j);
  });
  regFn("secret.ttl", [this](const Value& p, const CancelFlag&) {
    client_->secret_chats().set_ttl(js::getInt(p, "chat"), js::getInt(p, "seconds"));
    return RpcResult::success(okv());
  });
  regFn("secret.typing", [this](const Value& p, const CancelFlag&) {
    client_->secret_chats().set_typing(js::getInt(p, "chat"), js::getBool(p, "on"));
    return RpcResult::success(okv());
  });
  regFn("secret.fingerprint", [this](const Value& p, const CancelFlag&) {
    std::string f = client_->secret_chats().fingerprint_hex(js::getInt(p, "chat"));
    if (f.empty()) return RpcResult::failure(ErrorCode::RpcError, "ENCRYPTION_ID_INVALID");
    return RpcResult::success(wrap("fingerprint", Value(f)));
  });
  regFn("secret.history", [this](const Value& p, const CancelFlag&) {
    Array a;
    { std::lock_guard<std::mutex> g(secretMutex_); for (const auto& m : secretLog_[js::getInt(p, "chat")]) a.push_back(m); }
    return RpcResult::success(wrap("messages", Value(std::move(a))));
  });

  // ---------------------------------------------------------------- Calls (signaling only)
  regFn("calls.request", [this](const Value& p, const CancelFlag&) { return RpcResult::success(callJson(client_->calls().request(entity(p, "user"), js::getBool(p, "video")))); });
  regFn("calls.accept", [this](const Value& p, const CancelFlag&) { return RpcResult::success(callJson(client_->calls().accept(js::getId(p, "call")))); });
  regFn("calls.discard", [this](const Value& p, const CancelFlag&) {
    std::string r = js::getStr(p, "reason", "hangup");
    tapi::CallEnd e = r == "busy" ? tapi::CallEnd::Busy : r == "missed" ? tapi::CallEnd::Missed : r == "disconnect" ? tapi::CallEnd::Disconnect : tapi::CallEnd::Hangup;
    client_->calls().discard(js::getId(p, "call"), e, js::getInt(p, "duration"));
    return RpcResult::success(okv());
  });
  regFn("calls.rate", [this](const Value& p, const CancelFlag&) {
    int stars = js::getInt(p, "stars");
    if (stars < 1 || stars > 5) return RpcResult::failure(ErrorCode::BadParams, "stars must be 1 to 5");
    client_->calls().rate(js::getId(p, "call"), stars, js::getStr(p, "comment"));
    return RpcResult::success(okv());
  });
  regFn("calls.list", [this](const Value&, const CancelFlag&) {
    Array a; for (const auto& c : client_->calls().list()) a.push_back(callJson(c));
    return RpcResult::success(wrap("calls", Value(std::move(a))));
  });
  regFn("calls.group_create", [this](const Value& p, const CancelFlag&) {
    std::optional<std::string> title;
    if (p.find("title")) title = js::getStr(p, "title");
    auto ids = client_->calls().create_group_call(entity(p, "peer"), title);
    Object o; o["id"] = js::id(ids.first); o["access_hash"] = js::id(ids.second);
    return RpcResult::success(Value(std::move(o)));
  });
  regFn("calls.group_get", [this](const Value& p, const CancelFlag&) { return RpcResult::success(TapiCodec::dict(client_->calls().get_group_call(js::getId(p, "call"), js::getId(p, "access_hash")))); });
  regFn("calls.group_discard", [this](const Value& p, const CancelFlag&) {
    client_->calls().discard_group_call(js::getId(p, "call"), js::getId(p, "access_hash"));
    return RpcResult::success(okv());
  });
}

// Raw updates the pump cannot convert itself: runs on the worker thread because the secret chat and call code answers the server.
void TapiService::recordSecret(int chatId, const Value& message) {
  SecretHistoryStore::Log copy;
  {
    std::lock_guard<std::mutex> g(secretMutex_);
    secretLog_[chatId].push_back(message);
    if (secretHistory_.enabled()) copy = secretLog_;
  }
  std::string err;
  if (secretHistory_.enabled() && !secretHistory_.save(copy, err)) {
    // the message is delivered and kept in memory; the user is told that it will not survive a restart
    Object d;
    d["what"] = Value("secret_history_not_saved");
    d["text"] = Value(err);
    Event e;
    e.name = "service.warning";
    e.data = Value(std::move(d));
    emit(e);
  }
}

void TapiService::onSecretOrCallUpdate(const tapi::tl::TlObjectPtr& update) {
  try {
    if (tapi::tl::as_tl<T::UpdateEncryption>(update) || tapi::tl::as_tl<T::UpdateNewEncryptedMessage>(update)) {
      auto inc = client_->secret_chats().handle_update(update);
      for (const auto& s : inc.changed) { Object d; d["chat"] = secretJson(s); Event e; e.name = "secret.chat"; e.data = Value(std::move(d)); emit(e); }
      for (const auto& m : inc.messages) {
        Value j = secretMessageJson(m);
        if (m.service.empty()) recordSecret(m.chat_id, j);
        Object d; d["message"] = j; Event e; e.name = "secret.message"; e.data = Value(std::move(d)); emit(e);
      }
    } else if (tapi::tl::as_tl<T::UpdatePhoneCall>(update)) {
      if (auto c = client_->calls().handle_update(update)) { Object d; d["call"] = callJson(*c); Event e; e.name = "call.state"; e.data = Value(std::move(d)); emit(e); }
    }
  } catch (const std::exception&) {
    // A protocol violation from the other side (bad DH value, wrong hash) ends that call or chat, never the daemon.
  }
}

} // namespace mologram
30.1ms