Skip to content
Repos

mologram

C++ 8.4 KB186 lines Opens in site

Directory Raw Download

// 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"
// TapiService: file transfers (FR-30, FR-31): messages.send_file and media.download, with progress events and cancel.
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <iterator>

#include "mologram/ProcessRunner.hpp"
#include "mologram/Sha256.hpp"
#include "mologram/tapi/TapiCodec.hpp"
#include "mologram/tapi/TapiService.hpp"
#include "mologram/tapi/VideoProbe.hpp"
#include "tapi/cancel.hpp"

namespace mologram {
using js::Object;
using js::Value;
namespace fs = std::filesystem;

namespace {
/// Progress callback shared by uploads and downloads: emits transfer.progress and turns the request's CancelFlag into the
/// CancelToken that tapi checks between chunks.
std::function<void(std::int64_t, std::int64_t)> progressFor(TableService* /*unused*/, const std::function<void(const Event&)>& emitFn,
                                                           const std::string& token, tapi::CancelToken tok, CancelFlag flag) {
  return [emitFn, token, tok, flag](std::int64_t done, std::int64_t total) mutable {
    if (flag.cancelled()) tok.cancel();
    Object o;
    o["id"] = Value(token);
    o["done"] = js::id(done);
    o["total"] = js::id(total);
    Event e;
    e.name = "transfer.progress";
    e.data = Value(std::move(o));
    emitFn(e);
  };
}
}  // namespace

RpcResult TapiService::hSendFile(const Value& p, const CancelFlag& c) {
  std::string path = js::getStr(p, "path");
  std::error_code ec;
  if (!fs::exists(path, ec)) return RpcResult::failure(ErrorCode::RpcError, "FILE_NOT_FOUND: " + path);
  tapi::FileInput fi;
  fi.payload = path;
  tapi::SendFileOptions so;
  so.caption = js::getStr(p, "caption");
  std::string kind = js::getStr(p, "kind");
  if (kind == "document") so.force_document = true;
  else if (kind == "voice") so.voice_note = true;
  else if (kind == "video") {
    so.supports_streaming = true;
    // tapi cannot read a video's size and length; ffprobe (when installed) can, and Telegram needs them to treat the file as a video
    if (auto attr = VideoProbe::attribute(VideoProbe::probe(path))) so.attributes.push_back(attr);
  }
  so.cancel = tapi::CancelToken();
  so.progress_callback = progressFor(this, [this](const Event& e) { emit(e); }, "upload:" + fs::path(path).filename().string(), so.cancel, c);
  tapi::Message m = client_->media().send_file(entity(p, "peer"), fi, so);
  return RpcResult::success(TapiCodec::message(m).toJson());
}

RpcResult TapiService::hSendAlbum(const Value& p, const CancelFlag& c) {
  std::vector<tapi::FileInput> files;
  if (const js::Array* a = js::getArr(p, "paths")) {
    for (const auto& e : *a) {
      std::string path = e.asStr();
      std::error_code ec;
      if (!fs::exists(path, ec)) return RpcResult::failure(ErrorCode::RpcError, "FILE_NOT_FOUND: " + path);
      tapi::FileInput fi;
      fi.payload = path;
      files.push_back(std::move(fi));
    }
  }
  if (files.empty()) return RpcResult::failure(ErrorCode::RpcError, "ALBUM_EMPTY");
  tapi::SendFileOptions so;
  so.caption = js::getStr(p, "caption");
  so.cancel = tapi::CancelToken();
  so.progress_callback = progressFor(this, [this](const Event& e) { emit(e); }, "upload:album", so.cancel, c);
  auto msgs = client_->media().send_album(entity(p, "peer"), files, so);
  js::Array out;
  for (auto& m : msgs) out.push_back(TapiCodec::message(m).toJson());
  Object o;
  o["messages"] = Value(std::move(out));
  return RpcResult::success(Value(std::move(o)));
}

RpcResult TapiService::hDownload(const Value& p, const CancelFlag& c) {
  std::string token = js::getStr(p, "media");
  std::string dest = js::getStr(p, "dest");
  bool thumb = js::getBool(p, "thumb");
  std::string cacheKey = thumb ? token + "#thumb" : token;
  Peer peer;
  std::int64_t id = 0;
  // a story's media: "story:<peer key>:<story id>"; every other token names a message
  bool isStory = token.rfind("story:", 0) == 0;
  Peer storyPeer;
  std::int32_t storyId = 0;
  if (isStory) {
    std::string rest = token.substr(6);
    size_t colon = rest.rfind(':');
    if (colon == std::string::npos) return RpcResult::failure(ErrorCode::RpcError, "MEDIA_TOKEN_INVALID");
    storyPeer = Peer::fromKey(rest.substr(0, colon));
    try { storyId = std::stoi(rest.substr(colon + 1)); } catch (...) { return RpcResult::failure(ErrorCode::RpcError, "MEDIA_TOKEN_INVALID"); }
    if (!storyPeer.valid()) return RpcResult::failure(ErrorCode::RpcError, "MEDIA_TOKEN_INVALID");
  } else if (!TapiCodec::parseMediaToken(token, peer, id)) return RpcResult::failure(ErrorCode::RpcError, "MEDIA_TOKEN_INVALID");
  if (dest.empty()) {
    if (auto hit = cache_.get(cacheKey)) {
      Object o;
      o["path"] = Value(*hit);
      return RpcResult::success(Value(std::move(o)));
    }
  }
  tapi::tl::TlObjectPtr mediaObj;
  if (isStory) {
    auto outer = tapi::tl::as_tl<tapi::tl::types::stories::PeerStories>(client_->stories().peer_stories(entityOf(storyPeer)));
    auto inner = outer ? tapi::tl::as_tl<tapi::tl::types::PeerStories>(outer->stories) : nullptr;
    if (inner)
      for (const auto& item : inner->stories)
        if (auto si = tapi::tl::as_tl<tapi::tl::types::StoryItem>(item)) if (si->id == storyId) mediaObj = si->media;
    if (!mediaObj) return RpcResult::failure(ErrorCode::RpcError, "STORY_ID_INVALID");
  } else {
    tapi::IterMessagesOptions mo;
    mo.entity = entityOf(peer);
    mo.ids.push_back(tapi::IdArg((std::int32_t)id));
    auto list = client_->messages().get_messages(mo);
    if (list.empty()) return RpcResult::failure(ErrorCode::RpcError, "MESSAGE_ID_INVALID");
    mediaObj = list[0].raw();
  }
  std::string tmp = dest;
  if (dest.empty()) {
    std::error_code ec;
    fs::create_directories(fs::path(opt_.cacheDir.empty() ? "cache" : opt_.cacheDir) / "tmp", ec);
    tmp = (fs::path(opt_.cacheDir.empty() ? "cache" : opt_.cacheDir) / "tmp" / Sha256::hexOf(cacheKey)).string();
  }
  tapi::DownloadOptions dopt;
  dopt.cancel = tapi::CancelToken();
  dopt.progress_callback = progressFor(this, [this](const Event& e) { emit(e); }, token, dopt.cancel, c);
  // tapi may add a file extension to the path it was given: the result says where the file really is
  std::string actual = tmp;
  auto noteResult = [&](const tapi::tl::TlObjectPtr& res) {
    try {
      auto dr = tapi::tl::unbox<tapi::DownloadResult>(res);
      if (!dr.empty && !dr.path.empty()) actual = dr.path;
    } catch (const std::exception&) {}
  };
  if (!thumb) noteResult(client_->media().download_media(mediaObj, tmp, dopt));
  else {
    // the preview: the medium size, else the small one, else the first the message offers
    bool got = false;
    std::vector<tapi::ThumbSelector> choices{tapi::ThumbSelector(std::string("m")), tapi::ThumbSelector(std::string("s")), tapi::ThumbSelector(0)};
    for (auto& sel : choices) {
      dopt.thumb = sel;
      try { noteResult(client_->media().download_media(mediaObj, tmp, dopt)); } catch (const std::exception&) { if (c.cancelled()) break; continue; }
      std::error_code ec2;
      if (fs::exists(actual, ec2)) { got = true; break; }
    }
    if (!got && !c.cancelled()) return RpcResult::failure(ErrorCode::RpcError, "NO_THUMB: this media has no preview");
  }
  if (c.cancelled()) return RpcResult::failure(ErrorCode::Cancelled, "cancelled");
  std::error_code ec;
  if (!fs::exists(actual, ec)) return RpcResult::failure(ErrorCode::RpcError, "DOWNLOAD_FAILED: no file was written");
  Object o;
  if (!dest.empty()) {
    if (actual != dest) { fs::rename(actual, dest, ec); if (ec) return RpcResult::failure(ErrorCode::RpcError, "DOWNLOAD_FAILED: cannot move the file to " + dest + ": " + ec.message()); }
    o["path"] = Value(dest);
    return RpcResult::success(Value(std::move(o)));
  }
  std::ifstream in(actual, std::ios::binary);
  std::string bytes((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
  in.close();
  std::string err;
  std::string cached = cache_.put(cacheKey, bytes, err);
  fs::remove(actual, ec);
  fs::remove(tmp, ec);
  if (cached.empty()) return RpcResult::failure(ErrorCode::RpcError, "CACHE_WRITE_FAILED: " + err);
  o["path"] = Value(cached);
  return RpcResult::success(Value(std::move(o)));
}

void TapiService::registerMedia() {
  reg("messages.send_file", &TapiService::hSendFile);
  reg("messages.send_album", &TapiService::hSendAlbum);
  reg("media.download", &TapiService::hDownload);
}

} // namespace mologram
32.7ms