Skip to content
Repos

mologram

C++ 12.2 KB288 lines Opens in site

Directory Raw Download

#include "mologram/ui/media/MediaModule.hpp"
#include "mologram/ui/StoryTools.hpp"

#include <cstdlib>
#include <filesystem>
#include <fstream>

#include "mologram/ui/media/MediaFormat.hpp"
#include "mologram/ui/media/ProfileMedia.hpp"
#include "mologram/ui/media/SendMediaDialog.hpp"
#include "mologram/ui/media/TransferWindow.hpp"

namespace mologram::ui::media {
namespace fs = std::filesystem;

std::unique_ptr<MediaModule> MediaModule::install(MologramApp& app) { return std::unique_ptr<MediaModule>(new MediaModule(app)); }

MediaModule::MediaModule(MologramApp& app)
    : app_(app), store_(app.client(), app.dispatcher()), images_(store_), sender_(app.client(), store_) {
  app_.service().addSink(&store_);
  images_.setAutoDownload(app_.config().flag("media.auto_download"));
  images_.setAnimate(!app_.app().cfg.reducedMotion);
  ttgui::TelegramShell& sh = app_.shell();
  sh.images = &images_;
  sh.view->images = &images_;
  sh.view->onOpenMedia.connect([this](long long id) { openMessage(id); });
  sh.view->onVoice.connect([this](long long id, bool play) { toggleVoice(id, play); });
  sh.extraMenuItems = [this](long long id, bool) { return menuFor(id); };
  auto prev = sh.menuHook;
  sh.menuHook = [this, prev](const std::string& a, long long id) {
    if (handleMenu(a, id)) return true;
    return prev ? prev(a, id) : false;
  };
  app_.actions().bind("transfers", [this]() { showTransfers(); });
  app_.actions().bind("stories", [this]() { showStories(); });
  app_.actions().bind("story_post", [this]() { postStory(); });
  app_.onPaste = [this](const std::string& text) { return offerPaste(text); };
  profile_ = std::make_unique<ProfileMedia>(app_, *this);
}

MediaModule::~MediaModule() {
  app_.onPaste = nullptr;
  app_.service().removeSink(&store_);
  audio_.stop();
}

const Message* MediaModule::media(std::int64_t id) const {
  const Message* m = app_.controller().message(id);
  return m && !m->media.token.empty() ? m : nullptr;
}

void MediaModule::note(const std::string& title, const std::string& body) { app_.app().notify(title, body); }

std::string MediaModule::downloadDir() {
  if (const char* d = std::getenv("XDG_DOWNLOAD_DIR"); d && *d) return d;
  const char* home = std::getenv("HOME");
  return std::string(home ? home : ".") + "/Downloads";
}

std::string MediaModule::uniquePath(const std::string& dir, const std::string& name) {
  fs::path p = fs::path(dir) / name;
  std::error_code ec;
  if (!fs::exists(p, ec)) return p.string();
  std::string stem = p.stem().string(), ext = p.extension().string();
  for (int i = 1;; i++) {
    fs::path q = fs::path(dir) / (stem + " (" + std::to_string(i) + ")" + ext);
    if (!fs::exists(q, ec)) return q.string();
  }
}

static std::string labelOf(const Message& m) {
  if (!m.media.fileName.empty()) return m.media.fileName;
  switch (m.media.kind) {
    case MediaKind::Photo: return "photo";
    case MediaKind::Video: return "video";
    case MediaKind::Gif: return "GIF";
    case MediaKind::Voice: return "voice note";
    case MediaKind::Audio: return "audio";
    case MediaKind::Sticker: return "sticker";
    default: return "file";
  }
}

static bool viewable(MediaKind k) { return k == MediaKind::Photo || k == MediaKind::Sticker || k == MediaKind::Gif || k == MediaKind::Video; }

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

void MediaModule::openViewer(std::vector<ViewerItem> items, size_t at, long long autoMs) {
  ttgui::Window* win = ImageViewer::open(app_.app(), images_, items, at,
      [this](const ViewerItem& it) { openToken(it.id, it.title.empty() ? "media" : it.title); },
      [this](const ViewerItem& it) { saveToken(it.id, it.title.empty() ? "media" : it.title); });
  if (!win) return;
  if (auto* v = dynamic_cast<ViewerWidget*>(win->content)) {
    v->autoMs = autoMs;
    v->cfg = &app_.app().cfg;
  }
}

void MediaModule::openMessage(std::int64_t id) {
  const Message* m = media(id);
  if (!m) return;
  if (viewable(m->media.kind)) {
    std::vector<ViewerItem> items;
    size_t at = 0;
    for (const auto& tm : app_.shell().view->msgs) {
      const Message* mm = media(tm.id);
      if (!mm || !viewable(mm->media.kind)) continue;
      if (tm.id == id) at = items.size();
      items.push_back({mm->media.token, mm->text.empty() ? labelOf(*mm) : mm->text, mm->media.kind == MediaKind::Video || mm->media.kind == MediaKind::Gif, "", 0});
    }
    openViewer(items, at);
    return;
  }
  openMedia(*m);
}

void MediaModule::openMedia(const Message& m) {
  if (m.media.token.empty()) return;
  if (viewable(m.media.kind)) { openViewer({{m.media.token, m.text.empty() ? labelOf(m) : m.text, m.media.kind == MediaKind::Video || m.media.kind == MediaKind::Gif, "", 0}}, 0); return; }
  if (m.media.kind == MediaKind::Voice || m.media.kind == MediaKind::Audio) { playToken(m.media.token, labelOf(m)); return; }
  openToken(m.media.token, labelOf(m));
}

void MediaModule::playToken(const std::string& token, const std::string& label) {
  store_.fetch(token, false, label, [this, label](bool ok, const std::string& pathOrError) {
    if (!ok) { if (pathOrError != "cancelled") note("Could not load " + label, pathOrError); return; }
    std::string err;
    if (!audio_.play(pathOrError, err)) note("Cannot play " + label, err);
  });
}

void MediaModule::openToken(const std::string& token, const std::string& label) {
  store_.fetch(token, false, label, [this, label](bool ok, const std::string& pathOrError) {
    if (!ok) { if (pathOrError != "cancelled") note("Could not load " + label, pathOrError); return; }
    std::string err;
    if (!HostTools::openExternal(pathOrError, err)) note("Cannot open " + label, err);
  });
}

void MediaModule::saveToken(const std::string& token, const std::string& label) {
  store_.fetch(token, false, label, [this, label](bool ok, const std::string& pathOrError) {
    if (!ok) { if (pathOrError != "cancelled") note("Could not load " + label, pathOrError); return; }
    std::string name = label;
    if (fs::path(name).extension().empty()) {
      std::ifstream in(pathOrError, std::ios::binary);
      std::string head(32, '\0');
      in.read(head.data(), 32);
      head.resize((size_t)in.gcount());
      std::string ext = formatExtension(sniffFormat(head));
      if (!ext.empty()) name += "." + ext;
    }
    std::string dest = uniquePath(downloadDir(), name);
    std::string err;
    if (HostTools::saveAs(pathOrError, dest, false, err)) note("Saved", dest);
    else note("Could not save " + label, err);
  });
}

void MediaModule::toggleVoice(std::int64_t id, bool play) {
  const Message* m = media(id);
  if (!m) return;
  if (!play) { audio_.stop(); return; }
  playToken(m->media.token, labelOf(*m));
}

void MediaModule::saveMessage(std::int64_t id) {
  if (const Message* m = media(id)) saveToken(m->media.token, labelOf(*m));
}

void MediaModule::openExternal(std::int64_t id) {
  if (const Message* m = media(id)) openToken(m->media.token, labelOf(*m));
}

void MediaModule::showTransfers() { TransferWindow::open(app_.app(), store_); }

void MediaModule::showStories() {
  app_.client().request("load stories", "stories.list", {}, [this](const RpcResult& r) {
    std::vector<Story> stories = StoryParser::parse(r.value);
    if (stories.empty()) { note("Stories", "There are no stories to show."); return; }
    std::vector<ViewerItem> items;
    for (const auto& s : stories) {
      std::string who = nameOf(s.peer);
      items.push_back({s.token(), who + (s.caption.empty() ? "" : ": " + s.caption), s.video, s.peer.key(), s.id});
    }
    openViewer(items, 0, kPhotoSlideMs);
    // mark each story read as it comes on screen
    ttgui::Window* win = app_.app().wm.focusedWin;
    if (win) if (auto* v = dynamic_cast<ViewerWidget*>(win->content)) {
      v->extraKeys = StoryTools::keyHelp();
      v->onExtraKey = [this](const ttgui::KeyEventData& k, const ViewerItem& it) { return StoryTools::handleKey(app_.context(), k, it); };
      v->onShown = [this](const ViewerItem& it) {
        if (it.peerKey.empty() || it.storyId == 0) return;
        js::Object p;
        p["peer"] = js::Value(it.peerKey); p["max_id"] = js::id(it.storyId);
        app_.client().request("mark story read", "stories.read", std::move(p), [](const RpcResult&) {});
      };
      v->onShown(items[0]);
    }
  });
}

void MediaModule::postStory() {
  UiContext& c = app_.context();
  UiContext* cp = &c;
  auto f = c.kit.open("Post a story", "PostStoryDialog", 64, 20);
  ttgui::Window* win = f.win;
  c.kit.label(f, "File to post (a photo):");
  auto* path = c.kit.edit(f, "/path/to/photo.jpg");
  auto* caption = c.kit.edit(f, "Caption (optional)");
  c.kit.label(f, "Who can see it:");
  auto* privacy = c.kit.combo(f, StoryTools::privacyLabels(), 0);
  c.kit.label(f, "How long it stays:");
  auto* period = c.kit.combo(f, StoryTools::periodLabels(c.premium, c.cfg.flag("ascii_mode")), 2);
  auto* keep = c.kit.check(f, "Keep on my profile", false);
  auto* row = c.kit.row(f);
  c.kit.rowButton(row, "Post", [this, cp, win, path, caption, privacy, period, keep]() {
    std::vector<std::string> files = MediaSender::pathsFromPaste(path->text);
    if (files.empty()) { note("Post a story", "That file does not exist: " + path->text); return; }
    int secs = StoryTools::periodSeconds(period->selected);
    js::Object p;
    p["path"] = js::Value(files[0]);
    if (!caption->text.empty()) p["caption"] = js::Value(caption->text);
    p["privacy"] = js::Value(StoryTools::privacyValue(privacy->selected));
    if (secs != 86400) p["period"] = js::Value(secs);
    if (keep->checked) p["pinned"] = js::Value(true);
    std::string file = files[0];
    auto post = [this, cp, win, p, file]() {
      cp->kit.close(win);
      std::string uid = store_.trackUpload("upload:" + fs::path(file).filename().string(), "Posting story " + fs::path(file).filename().string());
      RequestId req = app_.client().request("post story", "stories.send", p,
          [this, uid](const RpcResult&) { store_.finishUpload(uid, true, ""); note("Story posted", "Your story is live."); },
          [this, uid, cp](const RpcError& e) {
            store_.finishUpload(uid, false, e.text);
            if (e.code == ErrorCode::PremiumRequired) cp->premium.refused("story_extras");  // Premium lapsed since the last refresh
            else note("Could not post the story", e.text);
          });
      store_.setRequest(uid, req);
    };
    if (StoryTools::periodNeedsPremium(secs)) cp->premium.use("story_extras", post);  // the 2 day option is a Premium extra
    else post();
  });
  c.kit.rowButton(row, c.t("btn.cancel"), [cp, win]() { cp->kit.close(win); });
  c.kit.show(f, path);
}

std::vector<std::string> MediaModule::menuFor(std::int64_t id) const {
  const Message* m = media(id);
  if (!m) return {};
  switch (m->media.kind) {
    case MediaKind::Voice: case MediaKind::Audio: return {"Play", "Save as..."};
    case MediaKind::Photo: case MediaKind::Sticker: case MediaKind::Gif: case MediaKind::Video: return {"Open", "Open with system", "Save as..."};
    default: return {"Open", "Save as..."};
  }
}

bool MediaModule::handleMenu(const std::string& action, std::int64_t id) {
  if (!media(id)) return false;
  if (action == "Open") { openMessage(id); return true; }
  if (action == "Play") { toggleVoice(id, true); return true; }
  if (action == "Open with system") { openExternal(id); return true; }
  if (action == "Save as...") { saveMessage(id); return true; }
  return false;
}

bool MediaModule::offerPaste(const std::string& pasted) {
  std::vector<std::string> files = MediaSender::pathsFromPaste(pasted);
  if (files.empty()) return false;
  Peer peer = app_.controller().current();
  if (!peer.valid()) { note("Send files", "Open a chat first, then paste the file again."); return true; }
  std::string chatName = app_.shell().header->name.empty() ? "this chat" : app_.shell().header->name;
  SendMediaDialog::open(app_.app(), files, chatName, [this, peer, files](const SendChoice& c) {
    if (c.album && files.size() >= 2) { sender_.sendAlbum(peer, files, c.caption); return; }
    bool first = true;
    for (const auto& f : files) {
      MediaSender::Options o;
      o.asDocument = c.asDocument;
      if (first) o.caption = c.caption;
      first = false;
      sender_.send(peer, f, o);
    }
  });
  return true;
}

}  // namespace mologram::ui::media
49.1ms