Skip to content
Repos

mologram

C++ 8.4 KB208 lines Opens in site

Directory Raw Download

#include "mologram/ui/SecretChats.hpp"

#include "mologram/ui/dialogs/DialogUtil.hpp"
#include "mologram/ui/dialogs/PeopleDialogs.hpp"

namespace mologram::ui {
using namespace ttgui;

SecretChatModel SecretChatModel::fromJson(const js::Value& v) {
  SecretChatModel m;
  m.id = js::getInt(v, "id");
  if (const js::Value* u = v.find("user")) m.user = Peer::fromJson(*u);
  m.status = js::getStr(v, "status");
  m.ttl = js::getInt(v, "ttl");
  return m;
}

const std::vector<int>& SecretChats::ttlSeconds() {
  static const std::vector<int> v = {0, 5, 60, 3600, 86400, 604800};
  return v;
}

const std::vector<std::string>& SecretChats::ttlLabels() {
  static const std::vector<std::string> v = {"Off", "5 seconds", "1 minute", "1 hour", "1 day", "1 week"};
  return v;
}

std::string SecretChats::lineFor(const std::string& who, const js::Value& m) {
  std::string line = who + ": " + js::getStr(m, "text");
  int ttl = js::getInt(m, "ttl");
  if (ttl > 0) line += "  (self-destructs after " + std::to_string(ttl) + " s)";
  return line;
}

std::string SecretChats::statusText(const std::string& s) {
  if (s == "waiting") return "waiting for them to accept";
  if (s == "requested") return "wants a secret chat with you";
  if (s == "ready") return "encrypted, ready";
  if (s == "discarded") return "ended";
  return s;
}

std::string SecretChats::nameOf(const Peer& p) const {
  for (const auto& d : c_.controller.dialogs()) if (d.peer == p) return d.name;
  return p.key();
}

struct SecretChats::Conv {
  int chat = 0;
  std::string name;
  Window* win = nullptr;
  ListBox* list = nullptr;
  std::shared_ptr<bool> alive;
  int ttlIndex = 0;
};

void SecretChats::startWith(const Peer& user) {
  js::Object p;
  p["user"] = user.toJson();
  c_.client.request("start secret chat", "secret.request", std::move(p), [this](const RpcResult&) { openList(); });
}

void SecretChats::refreshList() {
  c_.client.request("load secret chats", "secret.list", {}, [this](const RpcResult& r) {
    chats_.clear();
    if (const js::Array* a = js::getArr(r.value, "chats")) for (const auto& e : *a) chats_.push_back(SecretChatModel::fromJson(e));
    if (!table_ || !listAlive_ || !*listAlive_) return;
    std::vector<std::vector<std::string>> rows;
    for (const auto& ch : chats_) rows.push_back({nameOf(ch.user), statusText(ch.status), std::to_string(ch.id)});
    table_->rows = rows;
  });
}

Window* SecretChats::openList() {
  if (listWin_ && listAlive_ && *listAlive_) { refreshList(); c_.kit.app().wm.focusWindow(listWin_); return listWin_; }
  auto f = c_.kit.open("Secret chats", "SecretChatsDialog", 66, 18, false);
  listWin_ = f.win;
  listAlive_ = dlg::track(f.win);
  c_.kit.label(f, "End-to-end encrypted chats. Compare the key fingerprint with the other person.");
  table_ = c_.kit.table(f, {"Person", "State", "Id"}, {}, {22, 32, 8});
  auto* row = c_.kit.row(f);
  UiContext* cp = &c_;
  Window* win = f.win;
  Table* table = table_;
  auto selected = [this, table]() -> const SecretChatModel* {
    int i = table->selected;
    return i >= 0 && i < (int)chats_.size() ? &chats_[(size_t)i] : nullptr;
  };
  c_.kit.rowButton(row, "New", [this, cp]() {
    ContactsDialog::pick(*cp, "Secret chat with", [this](const Peer& p) { startWith(p); });
  });
  c_.kit.rowButton(row, "Open", [this, selected]() {
    if (const SecretChatModel* s = selected(); s && s->status == "ready") openConversation(s->id);
    else if (c_.toast) c_.toast("Secret chat", "Select a chat that is ready.");
  });
  c_.kit.rowButton(row, "Accept", [this, selected, cp]() {
    const SecretChatModel* s = selected();
    if (!s || s->status != "requested") { if (cp->toast) cp->toast("Secret chat", "Select a chat that asks for acceptance."); return; }
    js::Object p;
    p["chat"] = js::Value(s->id);
    cp->client.request("accept secret chat", "secret.accept", std::move(p), [this](const RpcResult&) { refreshList(); });
  });
  c_.kit.rowButton(row, "Discard", [this, selected, cp]() {
    const SecretChatModel* s = selected();
    if (!s) return;
    js::Object p;
    p["chat"] = js::Value(s->id);
    cp->client.request("discard secret chat", "secret.discard", std::move(p), [this](const RpcResult&) { refreshList(); });
  });
  c_.kit.rowButton(row, "Close", [cp, win]() { cp->kit.close(win); });
  c_.kit.show(f, table_);
  refreshList();
  return f.win;
}

Window* SecretChats::openConversation(int chat) {
  auto it = convs_.find(chat);
  if (it != convs_.end() && it->second->alive && *it->second->alive) { c_.kit.app().wm.focusWindow(it->second->win); return it->second->win; }
  std::string name = "?";
  for (const auto& ch : chats_) if (ch.id == chat) name = nameOf(ch.user);
  auto conv = std::make_shared<Conv>();
  conv->chat = chat;
  conv->name = name;
  auto f = c_.kit.open("Secret chat with " + name, "SecretChatWindow", 66, 22, false);
  conv->win = f.win;
  conv->alive = dlg::track(f.win);
  convs_[chat] = conv;
  auto* fp = c_.kit.label(f, "Key fingerprint: loading...");
  auto* ttl = c_.kit.combo(f, ttlLabels(), 0);
  conv->list = c_.kit.list(f, {});
  auto* input = c_.kit.edit(f, "Type a message and press Enter");
  auto* row = c_.kit.row(f);
  UiContext* cp = &c_;
  std::weak_ptr<Conv> weak = conv;
  auto send = [cp, weak, input, ttl]() {
    auto cv = weak.lock();
    if (!cv || !cv->alive || !*cv->alive || input->text.empty()) return;
    js::Object p;
    p["chat"] = js::Value(cv->chat);
    p["text"] = js::Value(input->text);
    int secs = ttlSeconds()[(size_t)std::max(0, std::min(ttl->selected, (int)ttlSeconds().size() - 1))];
    if (secs > 0) p["ttl"] = js::Value(secs);
    std::string typed = input->text;
    cp->client.request("send secret message", "secret.send", std::move(p), [weak, typed](const RpcResult& r) {
      auto cv2 = weak.lock();
      if (!cv2 || !cv2->alive || !*cv2->alive) return;
      cv2->list->items.push_back(SecretChats::lineFor("You", r.value));
      cv2->list->selected = (int)cv2->list->items.size() - 1;
    }, [](const RpcError&) {});
    input->text.clear();
  };
  input->onEnter.connect([send]() { send(); });
  c_.kit.rowButton(row, "Send", send);
  Window* win = f.win;
  c_.kit.rowButton(row, "Close", [cp, win]() { cp->kit.close(win); });
  ttl->onSelected.connect([cp, weak](int i) {
    auto cv = weak.lock();
    if (!cv) return;
    js::Object p;
    p["chat"] = js::Value(cv->chat);
    p["seconds"] = js::Value(ttlSeconds()[(size_t)std::max(0, std::min(i, (int)ttlSeconds().size() - 1))]);
    cp->client.request("set the timer", "secret.ttl", std::move(p), [](const RpcResult&) {});
  });
  c_.kit.show(f, input);
  js::Object fpParams;
  fpParams["chat"] = js::Value(chat);
  c_.client.request("load key fingerprint", "secret.fingerprint", fpParams, [fp, weak](const RpcResult& r) {
    auto cv = weak.lock();
    if (!cv || !cv->alive || !*cv->alive) return;
    fp->text = "Key fingerprint: " + js::getStr(r.value, "fingerprint") + "  (compare with the other person)";
  });
  js::Object hp;
  hp["chat"] = js::Value(chat);
  std::string who = name;
  c_.client.request("load secret history", "secret.history", hp, [weak, who](const RpcResult& r) {
    auto cv = weak.lock();
    if (!cv || !cv->alive || !*cv->alive) return;
    if (const js::Array* a = js::getArr(r.value, "messages"))
      for (const auto& m : *a) cv->list->items.push_back(SecretChats::lineFor(js::getBool(m, "out") ? "You" : who, m));
    cv->list->selected = (int)cv->list->items.size() - 1;
  });
  return f.win;
}

void SecretChats::onEvent(const Event& e) {
  if (e.name == "secret.chat") {
    const js::Value* cv = e.data.find("chat");
    if (!cv) return;
    SecretChatModel m = SecretChatModel::fromJson(*cv);
    if (m.status == "requested" && c_.toast) c_.toast("Secret chat", nameOf(m.user) + " " + statusText(m.status));
    refreshList();
  } else if (e.name == "secret.message") {
    const js::Value* mv = e.data.find("message");
    if (!mv || js::getBool(*mv, "out")) return;  // our own messages are shown from the send reply
    int chat = js::getInt(*mv, "chat");
    auto it = convs_.find(chat);
    if (it != convs_.end() && it->second->alive && *it->second->alive) {
      it->second->list->items.push_back(lineFor(it->second->name, *mv));
      it->second->list->selected = (int)it->second->list->items.size() - 1;
    } else if (c_.toast) {
      std::string who = "secret chat";
      for (const auto& ch : chats_) if (ch.id == chat) who = nameOf(ch.user);
      c_.toast("Secret message from " + who, js::getStr(*mv, "text"));
    }
  }
}

}  // namespace mologram::ui
36.4ms