// 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/TapiCodec.hpp"
#include "tapi/buttons.hpp"
#include "tapi/reactions.hpp"
#include "tapi/tl/types.hpp"
namespace mologram {
namespace T = tapi::tl::types;
using tapi::tl::as_tl;
using tapi::tl::TlObjectPtr;
static constexpr std::int64_t kChannelBase = 1000000000000LL;
Peer TapiCodec::peerOfPeerObj(const TlObjectPtr& o) {
if (auto u = as_tl<T::PeerUser>(o)) return {PeerKind::User, u->user_id};
if (auto c = as_tl<T::PeerChat>(o)) return {PeerKind::Chat, c->chat_id};
if (auto c = as_tl<T::PeerChannel>(o)) return {PeerKind::Channel, c->channel_id};
return {};
}
Peer TapiCodec::peerOfEntity(const TlObjectPtr& o) {
if (auto u = as_tl<T::User>(o)) return {PeerKind::User, u->id};
if (auto c = as_tl<T::Chat>(o)) return {PeerKind::Chat, c->id};
if (auto c = as_tl<T::Channel>(o)) return {PeerKind::Channel, c->id};
return {};
}
std::int64_t TapiCodec::markedId(const Peer& p) {
switch (p.kind) {
case PeerKind::User: return p.id;
case PeerKind::Chat: return -p.id;
case PeerKind::Channel: return -kChannelBase - p.id;
}
return 0;
}
tapi::EntityLike TapiCodec::entityOf(const Peer& p) { return tapi::EntityLike(markedId(p)); }
Peer TapiCodec::peerOfMarked(std::int64_t m) {
if (m > 0) return {PeerKind::User, m};
if (m <= -kChannelBase) return {PeerKind::Channel, -m - kChannelBase};
return {PeerKind::Chat, -m};
}
std::string TapiCodec::userStatus(const TlObjectPtr& s, bool& online) {
online = false;
if (as_tl<T::UserStatusOnline>(s)) { online = true; return "online"; }
if (as_tl<T::UserStatusOffline>(s)) return "last seen";
if (as_tl<T::UserStatusRecently>(s)) return "last seen recently";
if (as_tl<T::UserStatusLastWeek>(s)) return "last seen within a week";
if (as_tl<T::UserStatusLastMonth>(s)) return "last seen within a month";
return "last seen a long time ago";
}
std::string TapiCodec::displayName(const TlObjectPtr& e) {
if (auto u = as_tl<T::User>(e)) {
std::string n = u->first_name ? *u->first_name : "";
if (u->last_name && !u->last_name->empty()) n += (n.empty() ? "" : " ") + *u->last_name;
if (n.empty() && u->username) n = *u->username;
return n.empty() ? "Deleted Account" : n;
}
if (auto c = as_tl<T::Chat>(e)) return c->title;
if (auto c = as_tl<T::Channel>(e)) return c->title;
return "";
}
std::string TapiCodec::textOf(const TlObjectPtr& t) {
if (auto tw = as_tl<T::TextWithEntities>(t)) return tw->text;
return "";
}
PeerInfo TapiCodec::info(const TlObjectPtr& e) {
PeerInfo i;
i.peer = peerOfEntity(e);
i.name = displayName(e);
if (auto u = as_tl<T::User>(e)) {
if (u->username) i.username = *u->username;
if (u->phone) i.phone = *u->phone;
i.isBot = u->bot; i.verified = u->verified; i.scam = u->scam; i.fake = u->fake; i.premium = u->premium; i.contact = u->contact;
i.status = u->bot ? "bot" : userStatus(u->status ? *u->status : nullptr, i.online);
} else if (auto c = as_tl<T::Channel>(e)) {
if (c->username) i.username = *c->username;
i.verified = c->verified; i.scam = c->scam; i.fake = c->fake;
i.members = c->participants_count ? *c->participants_count : 0;
i.status = std::to_string(i.members) + (c->megagroup ? " members" : " subscribers");
} else if (auto c = as_tl<T::Chat>(e)) {
i.members = c->participants_count;
i.status = std::to_string(i.members) + " members";
}
return i;
}
Dialog TapiCodec::dialog(tapi::DialogInfo& d) {
Dialog o;
o.peer = peerOfEntity(d.entity());
o.name = d.name();
o.unread = d.unread_count();
o.pinned = d.pinned();
o.archived = d.archived();
o.muted = d.muted();
o.date = d.date();
o.forum = d.is_forum();
if (auto u = as_tl<T::User>(d.entity())) {
o.isBot = u->bot; o.verified = u->verified;
bool online = false; userStatus(u->status ? *u->status : nullptr, online); o.online = online;
} else if (auto c = as_tl<T::Channel>(d.entity())) o.verified = c->verified;
if (d.has_message()) {
auto m = d.message();
o.topMessageId = m->id();
std::string t = m->raw_text();
o.preview = t.empty() ? (m->media() ? "[media]" : "") : t;
}
tapi::DraftEntry dr = d.draft();
(void)dr;
return o;
}
Folder TapiCodec::folder(const TlObjectPtr& f) {
Folder o;
if (auto df = as_tl<T::DialogFilter>(f)) {
o.id = df->id; o.title = textOf(df->title); o.emoticon = df->emoticon ? *df->emoticon : "";
}
return o;
}
std::string TapiCodec::mediaToken(const Peer& p, std::int64_t id) { return "msg:" + p.key() + ":" + std::to_string(id); }
bool TapiCodec::parseMediaToken(const std::string& t, Peer& p, std::int64_t& id) {
if (t.rfind("msg:", 0) != 0) return false;
size_t last = t.rfind(':');
if (last <= 3) return false;
p = Peer::fromKey(t.substr(4, last - 4));
try { id = std::stoll(t.substr(last + 1)); } catch (...) { return false; }
return p.valid() && id > 0;
}
Poll TapiCodec::poll(const TlObjectPtr& pollMedia) {
Poll out;
auto mp = as_tl<T::MessageMediaPoll>(pollMedia);
if (!mp) return out;
auto p = as_tl<T::Poll>(mp->poll);
if (!p) return out;
out.question = textOf(p->question);
out.closed = p->closed; out.quiz = p->quiz; out.multiple = p->multiple_choice;
auto res = as_tl<T::PollResults>(mp->results);
for (const auto& a : p->answers) {
auto pa = as_tl<T::PollAnswer>(a);
if (!pa) continue;
PollOption o;
o.text = textOf(pa->text);
o.data = pa->option.empty() ? "0" : std::to_string((int)pa->option[0]);
if (res && res->results)
for (const auto& r : *res->results) {
auto v = as_tl<T::PollAnswerVoters>(r);
if (v && v->option == pa->option) { o.votes = v->voters ? *v->voters : 0; o.chosen = v->chosen; o.correct = v->correct; }
}
out.options.push_back(o);
}
if (res && res->total_voters) out.totalVoters = *res->total_voters;
return out;
}
/// DocumentAttributeAudio.waveform: 5 bit samples packed little endian into bytes.
static std::vector<int> waveformOf(const std::vector<std::uint8_t>& bytes) {
std::vector<int> out;
size_t samples = bytes.size() * 8 / 5;
for (size_t i = 0; i < samples; i++) {
size_t bit = i * 5, byte = bit >> 3, shift = bit & 7;
unsigned v = bytes[byte] >> shift;
if (shift > 3 && byte + 1 < bytes.size()) v |= (unsigned)bytes[byte + 1] << (8 - shift);
out.push_back((int)(v & 31));
}
return out;
}
static MediaRef mediaOf(tapi::Message& m, const Peer& peer) {
MediaRef r;
if (!m.media()) return r;
r.token = TapiCodec::mediaToken(peer, m.id());
if (m.poll()) { r.kind = MediaKind::Poll; r.token.clear(); return r; }
if (m.geo() || m.venue()) { r.kind = MediaKind::Location; r.token.clear(); return r; }
if (m.contact()) { r.kind = MediaKind::Contact; r.token.clear(); return r; }
if (m.photo()) {
r.kind = MediaKind::Photo; r.mime = "image/jpeg";
if (auto ph = as_tl<T::Photo>(m.photo()))
for (const auto& s : ph->sizes)
if (auto ps = as_tl<T::PhotoSize>(s)) if (ps->w > r.width) { r.width = ps->w; r.height = ps->h; r.size = ps->size; }
return r;
}
if (auto d = as_tl<T::Document>(m.document())) {
r.kind = MediaKind::Document; r.mime = d->mime_type; r.size = d->size;
for (const auto& a : d->attributes) {
if (auto f = as_tl<T::DocumentAttributeFilename>(a)) r.fileName = f->file_name;
else if (auto au = as_tl<T::DocumentAttributeAudio>(a)) { r.kind = au->voice ? MediaKind::Voice : MediaKind::Audio; r.duration = au->duration; if (au->waveform) r.waveform = waveformOf(std::vector<std::uint8_t>(au->waveform->begin(), au->waveform->end())); }
else if (auto v = as_tl<T::DocumentAttributeVideo>(a)) { r.kind = MediaKind::Video; r.duration = (int)v->duration; r.width = v->w; r.height = v->h; }
else if (as_tl<T::DocumentAttributeSticker>(a)) r.kind = MediaKind::Sticker;
else if (as_tl<T::DocumentAttributeAnimated>(a)) { if (r.kind != MediaKind::Sticker) r.kind = MediaKind::Gif; }
}
if (r.kind == MediaKind::Sticker) r.animated = (d->mime_type == "application/x-tgsticker" || d->mime_type == "video/webm");
return r;
}
r.kind = MediaKind::Other;
return r;
}
Message TapiCodec::message(tapi::Message& m) {
Message o;
o.id = m.id();
o.peer = peerOfPeerObj(m.peer_id());
o.date = m.date();
o.outgoing = m.out();
o.text = m.raw_text();
o.sender = peerOfPeerObj(m.from_id());
if (!o.sender.valid() && m.sender_id()) o.sender = {PeerKind::User, *m.sender_id()};
if (o.sender.valid() && m.sender()) o.senderName = displayName(m.sender());
if (o.senderName.empty() && o.outgoing) o.senderName = "You";
if (auto rt = m.reply_to_msg_id()) o.replyTo = *rt;
if (auto fh = as_tl<T::MessageFwdHeader>(m.fwd_from())) {
o.forwardFrom = fh->from_name ? *fh->from_name : (fh->from_id ? "forwarded message" : "forwarded message");
}
if (auto v = m.via_bot_id()) o.viaBot = std::to_string(*v);
if (auto raw = as_tl<T::Message>(m.raw())) {
o.edited = raw->edit_date.has_value();
o.pinned = raw->pinned;
o.effectId = raw->effect ? *raw->effect : 0;
}
o.media = mediaOf(m, o.peer);
if (m.poll()) { o.hasPoll = true; o.poll = poll(m.media()); }
for (const auto& rc : m.reactions()) {
Reaction r;
r.emoji = rc.reaction.emoticon; r.customEmojiId = rc.reaction.custom_emoji_id; r.count = rc.count; r.mine = rc.chosen();
o.reactions.push_back(r);
}
for (const auto& row : m.buttons()) {
std::vector<Button> out;
for (const auto& b : row) {
Button x; x.text = b.text();
if (auto d = b.data()) x.data.assign(d->begin(), d->end());
if (auto u = b.url()) x.url = *u;
out.push_back(x);
}
o.buttons.push_back(std::move(out));
}
return o;
}
js::Value TapiCodec::dict(const tapi::tl::TlObjectPtr& obj) {
if (!obj) return js::Value();
ttgui::json::ParseError pe;
auto v = ttgui::json::parse(obj->to_dict().to_json_redacted(tapi::tl::Value::secret_keys()), &pe);
return v ? *v : js::Value();
}
js::Value TapiCodec::dicts(const std::vector<tapi::tl::TlObjectPtr>& objs) {
js::Array a;
for (const auto& o : objs) a.push_back(dict(o));
return js::Value(std::move(a));
}
} // namespace mologram