// 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: messages.* handlers (FR-20 to FR-25).
#include <algorithm>
#include "mologram/tapi/TapiCodec.hpp"
#include "tapi/messages.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;
static std::vector<std::int32_t> idList(const Value& p, const char* key) {
std::vector<std::int32_t> ids;
if (const Array* a = js::getArr(p, key))
for (const auto& e : *a) ids.push_back(e.isStr() ? (std::int32_t)std::stoll(e.asStr()) : e.asInt());
return ids;
}
static RpcResult messagesResult(std::vector<tapi::Message>& list, bool ascending) {
Array a;
if (ascending) std::reverse(list.begin(), list.end());
for (auto& m : list) a.push_back(TapiCodec::message(m).toJson());
Object r;
r["messages"] = Value(std::move(a));
return RpcResult::success(Value(std::move(r)));
}
RpcResult TapiService::hHistory(const Value& p, const CancelFlag&) {
tapi::IterMessagesOptions o;
o.entity = entity(p, "peer");
o.limit = js::getInt(p, "count", 30);
o.offset_id = (std::int32_t)js::getId(p, "offset_id");
bool newer = js::getStr(p, "direction", "older") == "newer";
o.reverse = newer;
auto list = client_->messages().get_messages(o);
std::vector<tapi::Message> v(list.begin(), list.end());
return messagesResult(v, !newer); // client expects ascending ids; "older" arrives newest first
}
namespace {
/// `format` of messages.send / messages.edit: absent or "plain" = no parsing at all, "html" = our formatting tags (SPEC contract).
/// Returns false and fills `err` for anything else.
bool parseMode(const Value& p, std::string& mode, std::string& err) {
std::string f = js::getStr(p, "format");
if (f.empty() || f == "plain") { mode = ""; return true; }
if (f == "html") { mode = "html"; return true; }
err = "format must be html (or absent for plain text), not " + f;
return false;
}
} // namespace
RpcResult TapiService::hSend(const Value& p, const CancelFlag&) {
tapi::SendMessageOptions o;
std::string mode, err;
if (!parseMode(p, mode, err)) return RpcResult::failure(ErrorCode::BadParams, "messages.send: " + err);
const js::Array* ents = js::getArr(p, "entities");
if (mode == "html" && ents && !ents->empty()) return RpcResult::failure(ErrorCode::BadParams, "messages.send: entities and format are not combined");
o.parse_mode = mode; // "" = the text goes out exactly as typed
o.clear_draft = true; // sending clears the draft of that chat on the server (SPEC contract)
if (std::int64_t r = js::getId(p, "reply_to")) o.reply_to = (std::int32_t)r;
if (std::int64_t fx = js::getId(p, "effect")) o.effect = fx; // message effect (Premium)
if (std::int64_t at = js::getId(p, "schedule")) o.schedule = (tapi::tl::TlDate)at; // scheduled, not sent
if (ents) { // custom emoji entities (Premium)
std::vector<tapi::tl::TlObjectPtr> v;
for (const auto& e : *ents)
if (js::getStr(e, "type") == "custom_emoji")
v.push_back(tapi::Premium::custom_emoji_entity(js::getInt(e, "offset"), js::getInt(e, "length"), js::getId(e, "document_id")));
if (!v.empty()) o.formatting_entities = v;
}
tapi::Message m = client_->messages().send_message(entity(p, "peer"), tapi::MessageLike(js::getStr(p, "text")), o);
return RpcResult::success(TapiCodec::message(m).toJson());
}
RpcResult TapiService::hEdit(const Value& p, const CancelFlag&) {
tapi::EditOptions o;
std::string mode, err;
if (!parseMode(p, mode, err)) return RpcResult::failure(ErrorCode::BadParams, "messages.edit: " + err);
o.parse_mode = mode;
tapi::Message m = client_->messages().edit_message(entity(p, "peer"), (std::int32_t)js::getId(p, "id"), js::getStr(p, "text"), o);
return RpcResult::success(TapiCodec::message(m).toJson());
}
RpcResult TapiService::hDelete(const Value& p, const CancelFlag&) {
std::vector<tapi::DeleteId> ids;
for (auto i : idList(p, "ids")) ids.push_back(tapi::DeleteId(i));
client_->messages().delete_messages(entity(p, "peer"), ids, js::getBool(p, "revoke", true));
return RpcResult::success(Value(Object{}));
}
RpcResult TapiService::hForward(const Value& p, const CancelFlag&) {
tapi::ForwardOptions o;
o.from_peer = entity(p, "from");
std::vector<tapi::ForwardId> ids;
for (auto i : idList(p, "ids")) ids.push_back(tapi::ForwardId(i));
auto sent = client_->messages().forward_messages(entity(p, "to"), ids, o);
std::vector<tapi::Message> v;
for (auto& m : sent) if (m) v.push_back(*m);
return messagesResult(v, false);
}
RpcResult TapiService::hPin(const Value& p, const CancelFlag&) {
tapi::EntityLike e = entity(p, "peer");
std::int32_t id = (std::int32_t)js::getId(p, "id");
if (js::getBool(p, "on")) client_->messages().pin_message(e, tapi::PinTarget(id), true);
else client_->messages().unpin_message(e, tapi::PinTarget(id), true);
return RpcResult::success(Value(Object{}));
}
RpcResult TapiService::hReact(const Value& p, const CancelFlag&) {
std::vector<tapi::Reaction> rs;
if (const Array* a = js::getArr(p, "reactions"))
for (const auto& e : *a) {
Reaction r = Reaction::fromJson(e);
rs.push_back(r.isCustom() ? tapi::Reaction::custom(r.customEmojiId) : tapi::Reaction::emoji(r.emoji));
}
client_->messages().send_reaction(entity(p, "peer"), (std::int32_t)js::getId(p, "id"), rs);
return RpcResult::success(Value(Object{}));
}
/// SPEC filter names (photo video file link voice gif music); the plural spellings of the first service version still work.
/// Returns false for an unknown name (`out` stays null for the empty filter).
static bool filterFor(const std::string& f, tapi::tl::TlObjectPtr& out) {
out = nullptr;
if (f.empty()) return true;
if (f == "photo" || f == "photos") out = std::make_shared<T::InputMessagesFilterPhotos>();
else if (f == "video" || f == "videos") out = std::make_shared<T::InputMessagesFilterVideo>();
else if (f == "file" || f == "files") out = std::make_shared<T::InputMessagesFilterDocument>();
else if (f == "link" || f == "links") out = std::make_shared<T::InputMessagesFilterUrl>();
else if (f == "voice") out = std::make_shared<T::InputMessagesFilterVoice>();
else if (f == "gif" || f == "gifs") out = std::make_shared<T::InputMessagesFilterGif>();
else if (f == "music") out = std::make_shared<T::InputMessagesFilterMusic>();
else return false;
return true;
}
RpcResult TapiService::hSearch(const Value& p, const CancelFlag& cancel) {
tapi::IterMessagesOptions o;
if (!filterFor(js::getStr(p, "filter"), o.filter)) return RpcResult::failure(ErrorCode::BadParams, "messages.search: unknown filter " + js::getStr(p, "filter"));
if (p.find("peer")) o.entity = entity(p, "peer");
o.search = js::getStr(p, "query");
if (std::int64_t off = js::getId(p, "offset_id")) o.offset_id = (std::int32_t)off; // continue below this message id
// Incremental: every match is returned (no row cap, D-02) but a cancel stops the search between server pages.
auto it = client_->messages().iter_messages(o);
std::vector<tapi::Message> v;
tapi::Message m;
while (it.next(m)) {
if (cancel.cancelled()) return RpcResult::failure(ErrorCode::Cancelled, "search cancelled");
v.push_back(m);
}
return messagesResult(v, false);
}
RpcResult TapiService::hDraft(const Value& p, const CancelFlag&) {
auto req = std::make_shared<tapi::tl::functions::messages::SaveDraftRequest>();
req->peer = client_->get_input_entity(entity(p, "peer"));
req->message = js::getStr(p, "text");
client_->invoke(req);
// a changed draft is announced to every UI process, the writer included (the server does not echo it to this session)
emitDialogUpdated(Peer::fromJson(*p.find("peer")));
return RpcResult::success(Value(Object{}));
}
RpcResult TapiService::hSendPoll(const Value& p, const CancelFlag&) {
std::vector<std::string> opts;
if (const Array* a = js::getArr(p, "options")) for (const auto& e : *a) opts.push_back(e.asStr());
tapi::PollOptions po;
po.multiple = js::getBool(p, "multiple");
po.quiz = js::getBool(p, "quiz");
if (const Value* c = p.find("correct"); c && !c->isNull()) {
int idx = c->isStr() ? std::atoi(c->asStr().c_str()) : c->asInt();
if (idx < 0 || idx >= (int)opts.size()) return RpcResult::failure(ErrorCode::BadParams, "messages.send_poll: correct is not an option index");
po.correct = {idx};
}
if (po.quiz && po.correct.empty()) return RpcResult::failure(ErrorCode::BadParams, "messages.send_poll: a quiz needs correct");
if (opts.size() < 2) return RpcResult::failure(ErrorCode::RpcError, "POLL_OPTION_INVALID: a poll needs at least two options");
tapi::Message m = client_->messages().send_poll(entity(p, "peer"), js::getStr(p, "question"), opts, po);
return RpcResult::success(TapiCodec::message(m).toJson());
}
RpcResult TapiService::hVote(const Value& p, const CancelFlag&) {
std::vector<tapi::tl::TlBytes> opts;
if (const Array* a = js::getArr(p, "options"))
for (const auto& e : *a) opts.push_back(tapi::tl::TlBytes{(std::uint8_t)(e.isStr() ? std::stoi(e.asStr()) : e.asInt())});
client_->messages().vote(entity(p, "peer"), (std::int32_t)js::getId(p, "id"), opts);
return RpcResult::success(Value(Object{}));
}
RpcResult TapiService::hClickButton(const Value& p, const CancelFlag&) {
tapi::IterMessagesOptions o;
o.entity = entity(p, "peer");
o.ids.push_back(tapi::IdArg((std::int32_t)js::getId(p, "id")));
auto list = client_->messages().get_messages(o);
if (list.empty()) return RpcResult::failure(ErrorCode::RpcError, "MESSAGE_ID_INVALID");
tapi::Message m = list[0];
tapi::Message::ClickSelector sel;
std::string data = js::getStr(p, "data");
sel.data = tapi::tl::TlBytes(data.begin(), data.end());
auto res = m.click(sel);
Object r;
std::string answer;
if (auto cb = tapi::tl::as_tl<T::messages::BotCallbackAnswer>(res.response)) answer = cb->message ? *cb->message : std::string();
if (res.url) answer = *res.url;
r["answer"] = Value(answer);
return RpcResult::success(Value(std::move(r)));
}
RpcResult TapiService::hPinned(const Value& p, const CancelFlag&) {
auto list = client_->messages().get_pinned(entity(p, "peer"));
std::vector<tapi::Message> v(list.begin(), list.end());
std::sort(v.begin(), v.end(), [](const tapi::Message& x, const tapi::Message& y) { return x.id() < y.id(); });
return messagesResult(v, false);
}
RpcResult TapiService::hScheduled(const Value& p, const CancelFlag&) {
auto list = client_->messages().get_scheduled(entity(p, "peer"));
std::vector<tapi::Message> v(list.begin(), list.end());
std::sort(v.begin(), v.end(), [](const tapi::Message& x, const tapi::Message& y) { return x.id() < y.id(); });
return messagesResult(v, false);
}
RpcResult TapiService::hScheduledDelete(const Value& p, const CancelFlag&) {
client_->messages().delete_scheduled(entity(p, "peer"), idList(p, "ids"));
return RpcResult::success(Value(Object{}));
}
RpcResult TapiService::hScheduledSendNow(const Value& p, const CancelFlag&) {
client_->messages().send_scheduled_now(entity(p, "peer"), idList(p, "ids"));
return RpcResult::success(Value(Object{}));
}
void TapiService::registerMessages() {
reg("messages.history", &TapiService::hHistory);
reg("messages.send", &TapiService::hSend);
reg("messages.edit", &TapiService::hEdit);
reg("messages.delete", &TapiService::hDelete);
reg("messages.forward", &TapiService::hForward);
reg("messages.pin", &TapiService::hPin);
reg("messages.react", &TapiService::hReact);
reg("messages.search", &TapiService::hSearch);
reg("messages.draft", &TapiService::hDraft);
reg("messages.pinned", &TapiService::hPinned);
reg("messages.scheduled", &TapiService::hScheduled);
reg("messages.scheduled_delete", &TapiService::hScheduledDelete);
reg("messages.scheduled_send_now", &TapiService::hScheduledSendNow);
reg("messages.send_poll", &TapiService::hSendPoll);
reg("messages.vote", &TapiService::hVote);
reg("messages.click_button", &TapiService::hClickButton);
}
} // namespace mologram