Skip to content
Repos

DevPlaceApp

C++ 17.0 KB409 lines Opens in site

Directory Raw Download

#include "api/mock/MockFixtures.hpp"

#include <chrono>

namespace dp {

namespace {

Date ago(double seconds) {
  return DateCodec::now() - std::chrono::duration_cast<std::chrono::system_clock::duration>(std::chrono::duration<double>(seconds));
}

constexpr double kMinute = 60;
constexpr double kHour = 60 * 60;
constexpr double kDay = 60 * 60 * 24;

User makeUser(const char* id, const char* name, const char* bio, const char* location, const char* git, const char* site,
              std::int64_t level, std::int64_t xp, std::int64_t stars, double createdAgo) {
  User u;
  u.id = id;
  u.username = name;
  u.role = Role::Member;
  u.bio = bio;
  u.location = location;
  u.gitLink = git;
  u.website = site;
  u.level = level;
  u.xp = xp;
  u.stars = stars;
  u.createdAt = ago(createdAgo);
  return u;
}

Attachment makeAttachment(const char* id, const char* filename, const char* url, bool image, bool video, const char* mime,
                          double createdAgo) {
  Attachment a;
  a.id = id;
  a.filename = filename;
  a.url = url;
  a.isImage = image;
  a.isVideo = video;
  a.mimeType = mime;
  a.createdAt = ago(createdAgo);
  return a;
}

Comment makeComment(const char* id, const char* userId, const char* content, std::optional<std::string> parent, double createdAgo,
                    const User& author, Vote myVote, std::int64_t up, std::int64_t down, std::vector<Comment> children,
                    Reactions reactions) {
  Comment c;
  c.data.id = id;
  c.data.userId = userId;
  c.data.content = content;
  c.data.parentId = std::move(parent);
  c.data.targetType = "post";
  c.data.targetId = "1";
  c.data.createdAt = ago(createdAgo);
  c.author = author;
  c.myVote = myVote;
  c.votes = Comment::Votes{up, down};
  c.children = std::move(children);
  c.reactions = std::move(reactions);
  return c;
}

Post makePost(const char* id, std::optional<std::string> title, std::optional<std::string> topic, const char* content,
              const char* slug, std::int64_t stars, double createdAgo, std::optional<double> updatedAgo, const User& author,
              Vote vote, std::int64_t commentCount, std::vector<Comment> recent, bool bookmarked,
              std::vector<Attachment> attachments, std::optional<Poll> poll, Reactions reactions) {
  Post p;
  p.data.id = id;
  p.data.title = std::move(title);
  p.data.topic = std::move(topic);
  p.data.content = content;
  p.data.slug = slug;
  p.data.userId = "u1";
  p.data.stars = stars;
  p.data.createdAt = ago(createdAgo);
  if (updatedAgo) p.data.updatedAt = ago(*updatedAgo);
  p.author = author;
  p.myVote = vote;
  p.commentCount = commentCount;
  p.recentComments = std::move(recent);
  p.bookmarked = bookmarked;
  p.attachments = std::move(attachments);
  p.poll = std::move(poll);
  p.reactions = std::move(reactions);
  return p;
}

PollOption opt(const char* id, const char* label, std::int64_t count, std::int64_t pct) {
  return PollOption{id, label, count, count, pct};
}

Message makeMessage(const char* id, const User& from, const User& to, const char* content, bool mine, bool read,
                    double minutesAgo, std::vector<Attachment> attachments = {}) {
  Message m;
  m.data.id = id;
  m.data.senderId = from.id;
  m.data.receiverId = to.id;
  m.data.content = content;
  m.data.read = read;
  m.data.createdAt = ago(kMinute * minutesAgo);
  m.sender = from;
  m.isMine = mine;
  m.attachments = std::move(attachments);
  return m;
}

Notification makeNotification(const char* id, std::optional<NotificationType> type, const char* message, bool read,
                              const char* related, const char* url, double createdAgo, const User& actor) {
  Notification n;
  n.data.id = id;
  n.data.type = type;
  n.data.message = message;
  n.data.read = read;
  n.data.relatedId = related;
  n.data.targetUrl = url;
  n.data.createdAt = ago(createdAgo);
  n.actor = actor;
  return n;
}

}  // namespace

User MockFixtures::user() {
  return makeUser("u1", "cheeze_on_wheels", "No cheeze, no wheels.", "Bali, Indonesia", "https://github.com/cheeze-on-wheels",
                  "https://cheeze-on-wheels.dev", 1337, 180, 0, kDay * 10);
}

User MockFixtures::user2() {
  return makeUser("u2", "null_void", "Voice of the Void", "Moscow, Russia", "https://github.com/avoid-void",
                  "https://avoid-void.dev", 1, 54, 13, kDay * 9);
}

User MockFixtures::alice() {
  return makeUser("u10", "alice", "Building things on the web.", "Berlin, Germany", "https://github.com/alice", "", 42, 9001,
                  128, kDay * 400);
}

User MockFixtures::bob() {
  return makeUser("u11", "bob", "Backend enthusiast.", "Reykjavik, Iceland", "https://github.com/bob", "", 7, 320, 12,
                  kDay * 120);
}

User MockFixtures::carol() {
  return makeUser("u12", "carol", "Shipping features.", "Lisbon, Portugal", "https://github.com/carol", "", 19, 1500, 44,
                  kDay * 90);
}

std::vector<Badge> MockFixtures::badges() {
  auto badge = [](const char* name, const char* icon, double agoSeconds) {
    Badge b;
    b.name = name;
    b.icon = icon;
    b.createdAt = ago(agoSeconds);
    return b;
  };
  return {badge("Early Adopter", "\xF0\x9F\x8C\xB1", kDay * 365), badge("Top Contributor", "\xF0\x9F\x8F\x86", kDay * 90),
          badge("Bug Hunter", "\xF0\x9F\x90\x9B", kDay * 30), badge("Star Gazer", "\xE2\xAD\x90\xEF\xB8\x8F", kDay * 7)};
}

Poll MockFixtures::pollLayoutContainer() {
  Poll p;
  p.id = "poll-1";
  p.question = "Which SwiftUI layout container do you reach for first?";
  p.options = {opt("poll-1-opt-1", "VStack", 12, 60), opt("poll-1-opt-2", "HStack", 4, 20), opt("poll-1-opt-3", "ZStack", 2, 10),
               opt("poll-1-opt-4", "LazyVGrid", 2, 10)};
  p.total = 20;
  return p;
}

Poll MockFixtures::pollTestingFrameworkAlreadyVoted() {
  Poll p;
  p.id = "poll-2";
  p.question = "Which testing framework do you prefer for new Swift code?";
  p.options = {opt("poll-2-opt-1", "Swift Testing", 27, 75), opt("poll-2-opt-2", "XCTest", 9, 25)};
  p.total = 36;
  p.myChoice = "poll-2-opt-1";
  p.voted = "poll-2-opt-1";
  return p;
}

Poll MockFixtures::pollConcurrency() {
  Poll p;
  p.id = "poll-3";
  p.question = "What's your preferred concurrency style in Swift today?";
  p.options = {opt("poll-3-opt-1", "async/await", 41, 82), opt("poll-3-opt-2", "Combine", 5, 10), opt("poll-3-opt-3", "GCD", 3, 6),
               opt("poll-3-opt-4", "OperationQueue", 1, 2)};
  p.total = 50;
  return p;
}

std::vector<Comment> MockFixtures::comments() {
  const User u1 = user();
  const User u2 = user2();
  const Reactions none;
  Comment c5 = makeComment("c5", "u2",
                           "Ah, that explains it. This reply is deep enough to be capped at the max indentation level.", "c4",
                           kMinute * 20, u2, Vote::Down, 0, 1, {}, none);
  Comment c4 = makeComment("c4", "u1", "The ones from the last release notes.", "c3", kMinute * 30, u1, Vote::None, 0, 0, {c5}, none);
  Comment c3 = makeComment("c3", "u2", "Which benchmarks are you referring to?", "c2", kMinute * 40, u2, Vote::None, 1, 0, {c4}, none);
  Comment c2 = makeComment("c2", "u1", "Good point, but the benchmarks tell a different story.", "c1", kMinute * 50, u1, Vote::Up, 2, 0,
                           {c3}, Reactions{{"\xF0\x9F\x91\x8D"}, {{"\xF0\x9F\x91\x8D", 1}}});
  Comment c1 = makeComment("c1", "u2", "Interesting. I'm not sure I buy that this is a feature worth investing in.", std::nullopt,
                           kHour, u2, Vote::None, 3, 1, {c2},
                           Reactions{{"\xF0\x9F\x94\xA5"}, {{"\xF0\x9F\x9A\x80", 2}, {"\xF0\x9F\x94\xA5", 2}}});
  Comment c6 = makeComment("c6", "u1", "Great write-up, thanks for sharing!", std::nullopt, kMinute * 10, u1, Vote::None, 5, 0, {}, none);
  return {c1, c6};
}

std::vector<Post> MockFixtures::posts() {
  const User u1 = user();
  const User u2 = user2();
  const Reactions none;
  std::vector<Post> out;
  out.push_back(makePost("1", "How we cut our cold launch time by 60%", "devlog",
                         "Spent the week profiling our app's startup with *Instruments* and found we were doing way too much work on "
                         "the main thread before the first frame. Full write-up with benchmarks below.",
                         "mock-post-1", 3, 30, 15, u1, Vote::None, 2, comments(), false,
                         {makeAttachment("att-1-1", "photo.jpg", "https://picsum.photos/id/1015/600/400", true, false, "image/jpeg", 30)},
                         std::nullopt, Reactions{{"\xF0\x9F\x94\xA5"}, {{"\xF0\x9F\x9A\x80", 2}, {"\xF0\x9F\x94\xA5", 2}}}));
  out.push_back(makePost("2", "Settling a team debate", "SwiftUI",
                         "We keep going back and forth on this in code review, so let's put it to a vote. Which layout container do "
                         "you reach for first?",
                         "mock-post-2", 0, 30, std::nullopt, u1, Vote::None, 0, {}, false, {}, pollLayoutContainer(), none));
  out.push_back(makePost("3", std::nullopt, "Testing",
                         "Migrated our whole suite to Swift Testing this sprint and the parameterized tests alone made it worth it. "
                         "Here's a 30-second clip of the new run in action.",
                         "mock-post-3", 1, 60, std::nullopt, u2, Vote::Up, 0, {}, true,
                         {makeAttachment("att-3-1", "clip.mp4",
                                         "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4", false,
                                         true, "video/mp4", 60)},
                         pollTestingFrameworkAlreadyVoted(), Reactions{{"\xF0\x9F\x91\x8D"}, {{"\xF0\x9F\x91\x8D", 4}, {"\xF0\x9F\x8E\x89", 1}}}));
  out.push_back(makePost("4", "Finally deleted the last of our Combine code", std::nullopt,
                         "Two years after we started, the networking layer is now 100% async/await. Callback pyramids gone, "
                         "cancellation is trivial, and the diff removed more lines than it added. What's everyone else standardizing "
                         "on these days?",
                         "mock-post-4", 42, kHour, std::nullopt, u1, Vote::None, 0, {}, false, {}, pollConcurrency(), none));
  out.push_back(makePost("5", std::nullopt, std::nullopt,
                         "A few Markdown tricks I lean on for writing clear posts\n"
                         "Here is some *italic* text and here is some **bold** text.\n"
                         "> blockquote\n"
                         "asdf\n\n"
                         "lorem ipsum\n\n"
                         "```\ncode block\nline 2\n```\n\n"
                         "Text with `inline code` in it.\n\n"
                         "end",
                         "mock-post-5", 1337, kDay, std::nullopt, u2, Vote::Down, 0, {}, false,
                         {makeAttachment("att-5-1", "landscape.jpg", "https://picsum.photos/id/1018/800/500", true, false, "image/jpeg", kDay)},
                         std::nullopt, none));
  return out;
}

Feed MockFixtures::feed() {
  Feed f;
  f.posts = posts();
  f.currentTab = "all";
  f.currentTopic = "random";
  f.search = "";
  f.topAuthors = {user(), user2()};
  return f;
}

PostDetail MockFixtures::postDetail() {
  PostDetail d;
  d.post.id = "1";
  d.post.title = "A post with several attachments";
  d.post.topic = "swift";
  d.post.content =
      "This is the full post detail content.\nHere is some *italic* text and some **bold** text.\n\n```\nlet answer = 42\n```\n\nend";
  d.post.slug = "a-post-with-several-attachments";
  d.post.userId = "u1";
  d.post.stars = 12;
  d.post.createdAt = ago(kHour);
  d.author = user();
  d.isOwner = false;
  d.starCount = 12;
  d.myVote = Vote::Up;
  d.comments = comments();
  d.attachments = {
      makeAttachment("att-detail-1", "photo.jpg", "https://picsum.photos/id/1015/600/400", true, false, "image/jpeg", kHour),
      makeAttachment("att-detail-2", "landscape.jpg", "https://picsum.photos/id/1018/800/500", true, false, "image/jpeg", kHour),
      makeAttachment("att-detail-3", "clip.mp4", "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4",
                     false, true, "video/mp4", kHour)};
  d.poll = pollConcurrency();
  d.commentCount = 2;
  d.topics = {"swift", "ios"};
  d.reactions = Reactions{{"\xF0\x9F\x94\xA5"}, {{"\xF0\x9F\x9A\x80", 2}, {"\xF0\x9F\x94\xA5", 2}}};
  return d;
}

Profile MockFixtures::profile() {
  auto project = [](const char* id, const char* slug, const char* title, const char* description, const char* type,
                    std::int64_t stars) {
    Project::Data d;
    d.id = id;
    d.slug = slug;
    d.userId = "user-1";
    d.title = title;
    d.description = description;
    d.projectType = type;
    d.status = "active";
    d.stars = stars;
    d.isPrivate = false;
    d.readOnly = false;
    d.createdAt = Date(std::chrono::seconds(1'700'000'000));
    return d;
  };
  Profile p;
  p.user = user();
  p.posts = posts();
  p.badges = badges();
  p.projects = {project("project-1", "devplace-ios", "DevPlace iOS", "The native iOS client for DevPlace.", "app", 42),
                project("project-2", "kree-request", "KreeRequest", "A lightweight HTTP client wrapper.", "library", 17)};
  p.currentTab = "posts";
  p.postsCount = 5;
  p.isOwner = true;
  p.canViewApiKey = true;
  p.apiKey = "mock-api-key";
  p.canManageCustomization = true;
  p.rank = 1;
  p.xpProgressPercent = 42;
  return p;
}

MessagesInbox MockFixtures::inbox() {
  auto iso = [](double secondsAgo) { return DateCodec::formatIso8601(ago(secondsAgo)); };
  auto conversation = [](const User& other, const char* last, std::string at, bool unread) {
    Conversation c;
    c.otherUser = other;
    c.lastMessage = last;
    c.lastMessageAt = std::move(at);
    c.unread = unread;
    return c;
  };
  MessagesInbox m;
  m.conversations = {conversation(alice(), "Sounds good, let's ship it!", iso(60 * 60), false),
                     conversation(bob(), "Could you review my pull request?", iso(60 * 90), true),
                     conversation(carol(), "Here's the link: https://example.com/demo", iso(60 * 60 * 24 * 4), false)};
  m.otherUser = alice();
  m.currentConversation = "";
  m.search = "";
  m.otherOnline = false;
  m.otherLastSeen = "2m ago";
  return m;
}

MessagesInbox MockFixtures::conversation() {
  const User me = user();
  const User other = alice();
  MessagesInbox m;
  m.conversations = inbox().conversations;
  m.messages = {
      makeMessage("m1", me, other, "Hey, how's it going?", true, true, 16 * 60),
      makeMessage("m2", other, me, "Pretty good! Working on the new feature.", false, true, 15 * 60),
      makeMessage("m3", other, me, "It supports **markdown** and even *emphasis*.", false, true, 14 * 60),
      makeMessage("m4", other, me, "I should really finish it today.", false, true, 3 * 60),
      makeMessage("m5", other, me, "Here's a quick screenshot.", false, true, 2 * 60,
                  {makeAttachment("a1", "screenshot.jpg", "https://picsum.photos/id/1015/600/400", true, false, "image/jpeg", kHour * 2)}),
      makeMessage("m6", me, other, "Looks great!", true, true, 60),
      makeMessage("m7", other, me, "Thanks \xF0\x9F\x98\x84", false, false, 55),
      makeMessage("m8", me, other, "Sounds good, let's ship it!", true, false, 1)};
  m.otherUser = other;
  m.currentConversation = "c-alice";
  m.search = "";
  m.otherOnline = true;
  m.otherLastSeen = "just now";
  return m;
}

Notifications MockFixtures::notifications() {
  const User u1 = user();
  const User u2 = user2();
  Notifications n;
  NotificationGroup today;
  today.label = "Today";
  today.entries = {
      makeNotification("n0", NotificationType::Message, "null_void sent you a message", false, "u2", "/messages?with_uid=u2", kMinute * 3, u2),
      makeNotification("n1", std::nullopt, "null_void reacted \xF0\x9F\x8E\x89 to your post \"Shipping the new build system\"", false,
                       "p1", "/posts/shipping-the-new-build-system", kMinute * 8, u2),
      makeNotification("n2", NotificationType::Comment, "cheeze_on_wheels commented on your post", false, "c6",
                       "/posts/a-post-with-several-attachments#comment-c6", kMinute * 47, u1)};
  NotificationGroup earlier;
  earlier.label = "Earlier";
  earlier.entries = {
      makeNotification("n3", std::nullopt, "null_void started following you", true, "u2", "/users/null_void", kHour * 26, u2),
      makeNotification("n4", NotificationType::Vote, "cheeze_on_wheels upvoted your comment", true, "c1", "/posts/late-night-refactor",
                       kDay * 4, u1)};
  n.groups = {today, earlier};
  return n;
}

UserSearch MockFixtures::userSearch() {
  UserSearch s;
  s.results = {{"u1", "cheeze_on_wheels", std::nullopt}, {"u2", "null_void", std::nullopt}, {"u3", "async_await", std::nullopt},
               {"u4", "pixel_pusher", std::nullopt}, {"u5", "segfault_sally", std::nullopt}};
  return s;
}

std::vector<ReportReason> MockFixtures::reportReasons() {
  return {{"hate", "Hate speech or discriminatory content"},
          {"violence", "Realistic violence or threats"},
          {"harassment", "Harassment or bullying"},
          {"spam", "Spam or unwanted promotion"},
          {"other", "Something else"}};
}

}  // namespace dp
43.0ms