Skip to content
Repos

mologram

C++ 2.0 KB55 lines Opens in site

Directory Raw Download

#include "mologram/ui/media/Stories.hpp"

namespace mologram::ui::media {

Peer StoryParser::peerOfTl(const js::Value& tl) {
  Peer p;
  std::string t = js::getStr(tl, "_");
  if (t == "peerUser") { p.kind = PeerKind::User; p.id = js::getId(tl, "user_id"); }
  else if (t == "peerChat") { p.kind = PeerKind::Chat; p.id = js::getId(tl, "chat_id"); }
  else if (t == "peerChannel") { p.kind = PeerKind::Channel; p.id = js::getId(tl, "channel_id"); }
  return p;
}

static void walk(const js::Value& v, const Peer& owner, std::vector<Story>& out) {
  if (const js::Array* a = v.asArr()) { for (const auto& e : *a) walk(e, owner, out); return; }
  const js::Object* o = v.asObj();
  if (!o) return;
  std::string type = js::getStr(v, "_");
  Peer here = owner;
  if (type == "peerStories") {
    if (const js::Value* pv = v.find("peer")) { Peer p = StoryParser::peerOfTl(*pv); if (p.valid()) here = p; }
  }
  if (type == "storyItem") {
    Story s;
    s.peer = owner;
    s.id = js::getId(v, "id");
    s.date = js::getId(v, "date");
    s.caption = js::getStr(v, "caption");
    if (const js::Value* m = v.find("media")) {
      if (js::getStr(*m, "_") == "messageMediaDocument") {
        if (const js::Value* d = m->find("document")) {
          std::string mime = js::getStr(*d, "mime_type");
          s.video = mime.rfind("video/", 0) == 0;
          if (const js::Array* attrs = js::getArr(*d, "attributes"))
            for (const auto& at : *attrs) if (js::getStr(at, "_") == "documentAttributeVideo") s.durationSec = (int)(at.find("duration") ? at.find("duration")->asNum() : 0);
        }
      }
    }
    if (s.peer.valid() && s.id != 0) out.push_back(s);
    return;
  }
  if (type == "storyItemDeleted" || type == "storyItemSkipped") return;
  for (const auto& kv : *o) {
    if (kv.first == "users" || kv.first == "chats") continue;   // lookup tables, not stories
    walk(kv.second, here, out);
  }
}

std::vector<Story> StoryParser::parse(const js::Value& answer) {
  std::vector<Story> out;
  walk(answer, Peer{}, out);
  return out;
}

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