#include "mologram/ui/ChatController.hpp"
#include <algorithm>
#include <ctime>
namespace mologram::ui {
using namespace ttgui;
ChatController::ChatController(ServiceClient& svc, UiDispatcher& ui, TelegramShell& shell, PremiumModel& premium)
: svc_(svc), ui_(ui), shell_(shell), premium_(premium) {
ChatSurface surface;
surface.header = shell_.header;
surface.view = shell_.view;
surface.composer = shell_.composer;
surface.typing = shell_.typing;
surface.pinned = shell_.pinned;
surface.profile = shell_.profile;
surface.relayout = [this]() { shell_.layout(); };
main_ = std::make_unique<ChatSession>(svc_, premium_, surface);
main_->attach();
main_->toast = [this](const std::string& t, const std::string& b) { if (toast) toast(t, b); };
main_->copyToClipboard = [this](const std::string& s) { if (copyToClipboard) copyToClipboard(s); };
main_->now = [this]() { return nowSeconds(); };
main_->isBotUsername = [this](const std::string& n) { return isBotUsername(n); };
shell_.optimisticSend = false;
shell_.loadChats = []() { return std::vector<TgChatRow>{}; };
shell_.loadPageAsync = [this](long long chat, long long before, int n, std::function<void(std::vector<TgMessage>, bool)> done) {
main_->loadPage(TgAdapter::peerOf(chat), before, n, std::move(done));
};
shell_.folderFilter = [this](const TgChatRow& r, int idx) {
Peer p = TgAdapter::peerOf(r.id);
const Dialog* d = dialog(p);
if (!d) return false;
if (idx == (int)folders_.size() + 1) return d->archived; // last tab: Archive
if (d->archived) return false;
if (idx == 0) return true; // All
int fid = folders_[(size_t)idx - 1].id;
return std::find(d->folders.begin(), d->folders.end(), fid) != d->folders.end();
};
shell_.menuHook = [this](const std::string& a, long long id) { return main_->onMenu(a, id); };
shell_.onSend.connect([this](std::string t) { main_->send(t); });
shell_.onChatOpened.connect([this](long long h) { handleOpened(h); });
svc_.onPremiumRefused = [this](const std::string& feature) {
if (feature.empty()) { premium_.set(PremiumState::NotPremium); if (toast) toast("Telegram Premium", "This needs Telegram Premium. Nothing was lost."); }
else premium_.refused(feature);
};
svc_.onError = [this](const std::string& what, const RpcError& e) {
if (e.code == ErrorCode::Disconnected) return; // shown as connection state in the status bar; start() runs again on reconnect
if (toast) toast("Could not " + what, e.text);
};
}
ChatController::~ChatController() { *alive_ = false; }
Dialog* ChatController::dialogFor(const Peer& p) {
for (auto& d : dialogs_) if (d.peer == p) return &d;
for (auto& d : archived_) if (d.peer == p) return &d;
return nullptr;
}
const Dialog* ChatController::dialog(const Peer& p) const { return const_cast<ChatController*>(this)->dialogFor(p); }
void ChatController::removeSession(ChatSession* s) { extra_.erase(std::remove(extra_.begin(), extra_.end(), s), extra_.end()); }
bool ChatController::openSomewhere(const Peer& p) const {
if (main_->peer() == p) return true;
for (auto* s : extra_) if (s->peer() == p) return true;
return false;
}
long long ChatController::selectedMessage() const { return main_->target(); }
void ChatController::start() {
ServiceClient::Scope scope(svc_, global_); // start() runs right after the login dialog closed: its replies must not inherit that dialog's scope
shell_.pinned->pins.clear();
// Ask who we are first: before the login finished there is nothing to load, and asking anyway only produces "log in first" errors.
svc_.hello([this](const std::string& premium, const std::string& account, const std::string& auth) {
account_ = account;
connection_ = "connected"; // a reply from the service proves the connection (the connect event may precede our subscription)
premium_.set(premiumFrom(premium));
if (!auth.empty() && auth != "ready") return; // the login dialog calls start() again when it is done
loadChats();
});
}
void ChatController::loadChats() {
svc_.folders([this](std::vector<Folder> f) {
folders_ = std::move(f);
applyFolders();
rebuildRows();
});
svc_.dialogs("", [this](std::vector<Dialog> d) {
dialogs_ = std::move(d);
for (auto& x : dialogs_) x.archived = false;
rebuildRows();
learnBotUsernames();
});
svc_.dialogs("archive", [this](std::vector<Dialog> d) {
archived_ = std::move(d);
for (auto& x : archived_) x.archived = true;
rebuildRows();
});
}
bool ChatController::isBotUsername(const std::string& name) const {
std::string l = name;
std::transform(l.begin(), l.end(), l.begin(), [](unsigned char c) { return (char)std::tolower(c); });
return botUsernames_.count(l) > 0;
}
void ChatController::learnBotUsernames() {
for (const auto* list : {&dialogs_, &archived_})
for (const auto& d : *list) {
if (!d.isBot) continue;
svc_.peerInfo(d.peer, [this](PeerInfo i) {
if (i.username.empty()) return;
std::string l = i.username;
std::transform(l.begin(), l.end(), l.begin(), [](unsigned char c) { return (char)std::tolower(c); });
botUsernames_.insert(l);
});
}
}
void ChatController::applyFolders() {
std::vector<std::string> titles{"All"};
for (const auto& f : folders_) titles.push_back(f.title);
titles.push_back("Archive");
shell_.folders->setFolders(titles);
}
void ChatController::rebuildRows() {
std::vector<const Dialog*> all;
for (const auto& d : dialogs_) all.push_back(&d);
for (const auto& d : archived_) all.push_back(&d);
std::stable_sort(all.begin(), all.end(), [](const Dialog* a, const Dialog* b) { return a->pinned != b->pinned ? a->pinned : a->date > b->date; });
std::vector<TgChatRow> rows;
std::int64_t t = nowSeconds();
for (const Dialog* d : all) rows.push_back(TgAdapter::row(*d, t));
shell_.allChats = std::move(rows);
shell_.applyFilter();
if (main_->peer().valid()) {
long long h = TgAdapter::handle(main_->peer());
for (size_t i = 0; i < shell_.shownRows.size(); i++) if (shell_.shownRows[i].id == h) shell_.list->selected = (int)i;
}
}
void ChatController::openPeer(const Peer& p) {
long long h = TgAdapter::handle(p);
for (size_t i = 0; i < shell_.shownRows.size(); i++) if (shell_.shownRows[i].id == h) { shell_.openChatAt((int)i); return; }
}
void ChatController::handleOpened(long long h) {
Peer p = TgAdapter::peerOf(h);
int unread = 0;
std::string draft;
if (Dialog* d = dialogFor(p)) {
unread = d->unread;
draft = d->draft;
shell_.header->status = d->online ? "online" : "";
if (d->unread > 0) { d->unread = 0; svc_.markRead(p); rebuildRows(); }
}
main_->open(p, unread, draft, false);
if (onOpened) onOpened(p);
}
std::vector<std::string> ChatController::chatMenuFor(const Peer& p) const {
const Dialog* d = dialog(p);
std::vector<std::string> m{"Open", "Open in new window", "Open floating window"};
if (!d) return m;
m.push_back(d->pinned ? "Unpin" : "Pin");
m.push_back(d->muted ? "Unmute" : "Mute");
m.push_back(d->archived ? "Unarchive" : "Archive");
if (d->unread > 0) m.push_back("Mark as read");
m.push_back(p.kind == PeerKind::User ? "Delete chat" : "Leave");
return m;
}
void ChatController::chatAction(const Peer& p, const std::string& action) {
Dialog* d = dialogFor(p);
js::Object q;
q["peer"] = p.toJson();
std::string method;
if (action == "Pin" || action == "Unpin") { method = "dialogs.pin"; q["on"] = js::Value(action == "Pin"); }
else if (action == "Mute" || action == "Unmute") { method = "dialogs.mute"; q["until"] = js::id(action == "Mute" ? 2147483647LL : 0LL); }
else if (action == "Archive" || action == "Unarchive") { method = "dialogs.archive"; q["on"] = js::Value(action == "Archive"); }
else if (action == "Mark as read") method = "dialogs.mark_read";
else if (action == "Delete chat") method = "dialogs.delete";
else if (action == "Leave") method = "chat.leave";
else return;
(void)d;
svc_.request(action, method, std::move(q), [this, p, action](const RpcResult&) {
Dialog* dl = dialogFor(p);
if (!dl) { start(); return; }
if (action == "Pin") dl->pinned = true; else if (action == "Unpin") dl->pinned = false;
else if (action == "Mute") dl->muted = true; else if (action == "Unmute") dl->muted = false;
else if (action == "Mark as read") dl->unread = 0;
else if (action == "Archive" || action == "Unarchive") start(); // the dialog moves between the two lists
else if (action == "Delete chat" || action == "Leave") {
dialogs_.erase(std::remove_if(dialogs_.begin(), dialogs_.end(), [&](const Dialog& x) { return x.peer == p; }), dialogs_.end());
archived_.erase(std::remove_if(archived_.begin(), archived_.end(), [&](const Dialog& x) { return x.peer == p; }), archived_.end());
}
rebuildRows();
});
}
void ChatController::onEvent(const Event& e) {
std::weak_ptr<bool> alive = alive_;
ui_.post([this, alive, e]() {
auto a = alive.lock();
if (!a || !*a) return;
handleEvent(e);
});
}
void ChatController::handleEvent(const Event& e) {
const js::Value& d = e.data;
if (e.name == "message.new" || e.name == "message.edited") {
const js::Value* mv = d.find("message");
if (mv) {
Message m = Message::fromJson(*mv);
if (Dialog* dl = dialogFor(m.peer)) {
if (e.name == "message.new") {
dl->preview = m.text.empty() ? "[media]" : m.text; dl->date = m.date; dl->topMessageId = m.id;
if (!m.outgoing && !openSomewhere(m.peer)) {
dl->unread++;
if (!dl->muted && onIncoming) onIncoming(*dl, m);
}
} else if (dl->topMessageId == m.id) dl->preview = m.text;
dl->typing.clear();
rebuildRows();
} else if (e.name == "message.new") {
svc_.dialogs("", [this](std::vector<Dialog> v) { dialogs_ = std::move(v); rebuildRows(); }); // a chat we do not know yet
}
}
} else if (e.name == "dialog.updated") {
const js::Value* dv = d.find("dialog");
if (dv) {
Dialog nd = Dialog::fromJson(*dv);
Dialog* old = dialogFor(nd.peer);
if (old) *old = nd; else (nd.archived ? archived_ : dialogs_).push_back(nd);
rebuildRows();
}
} else if (e.name == "typing") {
const js::Value* pv = d.find("peer");
if (pv) {
Peer p = Peer::fromJson(*pv);
std::string who = js::getStr(d, "action").empty() ? "" : js::getStr(d, "name");
if (Dialog* dl = dialogFor(p)) { dl->typing = who; rebuildRows(); }
}
} else if (e.name == "presence") {
const js::Value* pv = d.find("peer");
if (pv) { if (Dialog* dl = dialogFor(Peer::fromJson(*pv))) { dl->online = js::getBool(d, "online"); rebuildRows(); } }
} else if (e.name == "premium.changed") {
premium_.set(premiumFrom(js::getStr(d, "state")));
} else if (e.name == "connection.state") {
connection_ = js::getStr(d, "state");
if (connection_ == "connected") { // first connection or the daemon came back: reload what we show (FR-64: typed text stays)
start();
main_->reload();
for (auto* s : std::vector<ChatSession*>(extra_)) s->reload();
}
}
main_->handleEvent(e);
for (auto* s : std::vector<ChatSession*>(extra_)) s->handleEvent(e);
if (onAnyEvent) onAnyEvent(e);
}
} // namespace mologram::ui