Skip to content
Repos

mologram

C++ 10.0 KB227 lines Opens in site

Directory Raw Download

#include "mologram/ui/dialogs/LoginDialog.hpp"

#include <algorithm>
#include <filesystem>

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

namespace mologram::ui {
using namespace ttgui;
namespace fs = std::filesystem;

namespace {

void finish(UiContext* cp, Window* win) {
  cp->onAuthState = nullptr;
  cp->kit.close(win);
  if (cp->toast) cp->toast("Logged in", "Welcome");
  cp->controller.start();
}

}  // namespace

// What the user needs to know about where the code went (FR-04). Telegram's default is the Telegram app on another device, not SMS.
std::string LoginDialog::deliveryText(const std::string& type, const std::string& next) {
  std::string t;
  if (type == "app") t = "A login code was sent to the Telegram app on your other devices: open the chat named \"Telegram\" there. It is not an SMS.";
  else if (type == "sms" || type == "firebase_sms" || type == "fragment_sms" || type == "sms_word" || type == "sms_phrase") t = "A login code was sent to your phone by SMS.";
  else if (type == "call") t = "Telegram will call your phone and read the code to you.";
  else if (type == "flash_call" || type == "missed_call") t = "Telegram will ring your phone once; the code is the last digits of the calling number. Do not answer.";
  else if (type == "email_code") t = "A login code was sent to your email address.";
  else if (type.empty()) t = "A login code was requested.";
  else t = "A login code was sent (delivery: " + type + ").";
  if (!next.empty()) t += " Not arriving? Choose Resend to get it by " + (next == "sms" ? std::string("SMS") : next == "call" ? std::string("a phone call") : next) + ".";
  else if (type == "app") t += " No other Telegram device? Choose Resend.";
  t += " This is a one-time login for this computer; the session file keeps you signed in afterwards.";
  return t;
}

namespace {
std::vector<std::string> wrapLines(const std::string& text, size_t width) {
  std::vector<std::string> out;
  std::string line, word;
  auto flush = [&]() { if (!line.empty()) { out.push_back(line); line.clear(); } };
  for (size_t i = 0; i <= text.size(); i++) {
    if (i == text.size() || text[i] == ' ') {
      if (!word.empty()) {
        if (!line.empty() && line.size() + 1 + word.size() > width) flush();
        line += (line.empty() ? "" : " ") + word;
        word.clear();
      }
    } else word += text[i];
  }
  flush();
  return out;
}
}  // namespace

Window* LoginDialog::open(UiContext& c, const std::string& state, const std::string& error) {
  UiContext* cp = &c;
  if (state.empty()) {
    c.client.request("check login", "auth.state", {}, [cp](const RpcResult& r) {
      std::string s = js::getStr(r.value, "state");
      if (s == "ready") { cp->controller.start(); return; }
      LoginDialog::open(*cp, s.empty() ? "need_phone" : s, "");
    });
    return nullptr;
  }
  // The number is in the config (FR-01): request the code at once, once per run. A failure falls back to the phone field with the reason.
  if (state == "need_phone" && error.empty() && !c.loginAutoSent && !c.cfg.str("phone").empty()) {
    c.loginAutoSent = true;
    return LoginDialog::open(c, "sending", "");
  }
  std::vector<std::string> info;
  if (state == "need_code") info = wrapLines(deliveryText(c.codeType, c.codeNext), 56);
  int height = state == "qr" ? 30 : state == "need_code" ? 12 + (int)info.size() : state == "need_phone" ? 14 : 12;
  auto f = c.kit.open(c.t("title.login"), "LoginDialog", 60, height);
  auto alive = dlg::track(f.win);
  Window* win = f.win;
  c.kit.label(f, error);

  // Every step replaces this window by the next; `next` closes it first.
  auto go = [cp, win](const std::string& s, const std::string& e) {
    cp->onAuthState = nullptr;
    cp->kit.close(win);
    if (s == "ready") { if (cp->toast) cp->toast("Logged in", "Welcome"); cp->controller.start(); return; }  // the server needed no code
    LoginDialog::open(*cp, s, e);
  };
  // Asks Telegram for the code and remembers how it is delivered; empty `number` means the one in the config.
  auto sendCode = [cp, go](const std::string& number) {
    js::Object p;
    p["phone"] = js::Value(number);
    cp->client.request("send the login code", "auth.send_phone", std::move(p), [cp, go](const RpcResult& r) {
      cp->codeType = js::getStr(r.value, "type");
      cp->codeNext = js::getStr(r.value, "next_type");
      go(cp->codeType == "already_signed_in" ? "ready" : "need_code", "");
    }, [go](const RpcError& e) { go("need_phone", e.text); });
  };

  if (state == "sending") {
    c.kit.label(f, "Sending the login code to the number in your config...");
    c.kit.label(f, "Telegram needs a code once for a new session on this computer.");
    c.kit.show(f, nullptr);
    sendCode("");
  } else if (state == "need_phone") {
    c.kit.label(f, c.t("label.phone"));
    c.kit.label(f, "International format, for example +31612345678.");
    c.kit.label(f, c.cfg.str("phone").empty() ? "Telegram sends the code to the app on your other devices first." : "Leave it empty to use the number from your config.");
    auto* phone = c.kit.edit(f, "+31612345678");
    auto next = [cp, phone, sendCode]() { sendCode(phone->text); };
    phone->onEnter.connect(next);
    auto* row = c.kit.row(f);
    c.kit.rowButton(row, c.t("btn.next"), next);
    c.kit.rowButton(row, c.t("btn.qr"), [go]() { go("qr", ""); });
    c.kit.show(f, phone);
  } else if (state == "need_code") {
    for (const auto& line : info) c.kit.label(f, line);
    c.kit.label(f, c.t("label.code"));
    auto* code = c.kit.edit(f, "12345");
    auto next = [cp, code, go, win]() {
      js::Object p;
      p["code"] = js::Value(code->text);
      cp->client.request("check the code", "auth.send_code", std::move(p), [cp, go, win](const RpcResult& r) {
        std::string s = js::getStr(r.value, "state");
        if (s == "need_password") go("need_password", ""); else finish(cp, win);
      }, [go](const RpcError& e) { go("need_code", e.text); });
    };
    code->onEnter.connect(next);
    auto* row = c.kit.row(f);
    c.kit.rowButton(row, c.t("btn.next"), next);
    c.kit.rowButton(row, c.t("btn.resend"), [cp, go]() {
      cp->client.request("resend the code", "auth.resend_code", {}, [cp, go](const RpcResult& r) {
        cp->codeType = js::getStr(r.value, "type");
        cp->codeNext = js::getStr(r.value, "next_type");
        go("need_code", "A new code was sent");
      }, [go](const RpcError& e) { go("need_code", e.text); });
    });
    c.kit.show(f, code);
  } else if (state == "need_password") {
    auto* hint = c.kit.label(f, "");
    c.client.request("load the password hint", "auth.state", {}, [hint, alive](const RpcResult& r) {
      if (!*alive) return;
      std::string h = js::getStr(r.value, "hint");
      if (!h.empty()) hint->text = "Hint: " + h;
    }, [](const RpcError&) {});
    c.kit.label(f, c.t("label.password"));
    auto* pw = c.kit.edit(f, "", "", true);
    auto next = [cp, pw, go, win]() {
      js::Object p;
      p["password"] = js::Value(pw->text);
      cp->client.request("check the password", "auth.send_password", std::move(p), [cp, win](const RpcResult&) { finish(cp, win); },
                         [go](const RpcError& e) { go("need_password", e.text); });
    };
    pw->onEnter.connect(next);
    auto* row = c.kit.row(f);
    c.kit.rowButton(row, c.t("btn.next"), next);
    c.kit.show(f, pw);
  } else {  // qr
    auto* qr = new QrWidget();
    qr->cfg = &c.app.cfg;
    qr->flex = 1;
    c.kit.label(f, "Scan with Telegram on your phone: Settings, Devices, Link Desktop Device");
    f.box->addChild(std::unique_ptr<Widget>(qr));
    c.client.request("start QR login", "auth.qr_start", {}, [qr, alive](const RpcResult& r) {
      if (!*alive) return;
      qr->setText(js::getStr(r.value, "url"));
    }, [go](const RpcError& e) { go("need_phone", e.text); });
    cp->onAuthState = [cp, win, go](const std::string& s) {
      if (s == "ready") finish(cp, win);
      else if (s == "need_password") go("need_password", "");
    };
    auto* row = c.kit.row(f);
    c.kit.rowButton(row, c.t("btn.phone"), [go]() { go("need_phone", ""); });
    c.kit.rowButton(row, "Check", [cp, win]() {
      cp->client.request("check login", "auth.state", {}, [cp, win](const RpcResult& r) {
        if (js::getStr(r.value, "state") == "ready") finish(cp, win);
      });
    });
    c.kit.show(f, nullptr);
  }
  return f.win;
}

std::vector<std::string> AccountsDialog::accounts(const Config& cfg) {
  std::vector<std::string> names{"main"};
  std::error_code ec;
  for (fs::directory_iterator it(cfg.str("data_dir"), ec), end; !ec && it != end; it.increment(ec)) {
    std::string fn = it->path().filename().string();
    const std::string ext = ".session";
    if (fn.size() > ext.size() && fn.compare(fn.size() - ext.size(), ext.size(), ext) == 0) {
      std::string n = fn.substr(0, fn.size() - ext.size());
      if (std::find(names.begin(), names.end(), n) == names.end()) names.push_back(n);
    }
  }
  std::sort(names.begin() + 1, names.end());
  return names;
}

Window* AccountsDialog::open(UiContext& c) {
  UiContext* cp = &c;
  auto f = c.kit.open(c.t("title.accounts"), "AccountsDialog", 50, 18);
  auto alive = dlg::track(f.win);
  Window* win = f.win;
  auto names = std::make_shared<std::vector<std::string>>(accounts(c.cfg));
  c.kit.label(f, "Current account: " + c.cfg.str("account"));
  auto* list = c.kit.list(f, *names);
  auto* newName = c.kit.edit(f, "Name of a new account");
  auto* r = c.kit.row(f);
  c.kit.rowButton(r, c.t("btn.switch"), [cp, list, names]() {
    int i = list->selected;
    if (i >= 0 && i < (int)names->size() && cp->switchAccount) cp->switchAccount((*names)[(size_t)i]);
  });
  c.kit.rowButton(r, c.t("btn.add"), [cp, newName]() {
    if (!newName->text.empty() && cp->switchAccount) cp->switchAccount(newName->text);
  });
  c.kit.rowButton(r, c.t("btn.logout"), [cp, win]() {
    cp->client.request("log out", "auth.logout", {}, [cp, win](const RpcResult&) {
      cp->kit.close(win);
      LoginDialog::open(*cp, "need_phone", "Logged out");
    });
  });
  c.kit.rowButton(r, c.t("btn.close"), [cp, win]() { cp->kit.close(win); });
  c.kit.show(f, list);
  return f.win;
}

}  // namespace mologram::ui
42.0ms