Skip to content
Repos

DevPlaceApp

C++ 22.1 KB466 lines Opens in site

Directory Raw Download

#include "api/DevPlaceRequest.hpp"

#include <cctype>

#include "api/ApiErrorDecoder.hpp"
#include "core/Uuid.hpp"
#include "core/UrlCodec.hpp"
#include "spec/ApiPaths.hpp"
#include "spec/UiMessages.hpp"

namespace dp {

using spec::ApiPaths;
using spec::ApiQueryKeys;
using spec::HttpSpec;

namespace {

std::string dumpJson(const Json& body) { return body.dump(-1, ' ', false, Json::error_handler_t::replace); }

}  // namespace

// ---- helpers -------------------------------------------------------------------------------------------------

DevPlaceRequest::Spec DevPlaceRequest::makeGet(std::string path, Query query, const Token& token) {
  Spec s;
  s.method = HttpSpec::kGet;
  s.path = std::move(path);
  s.query = std::move(query);
  s.token = token;
  return s;
}

DevPlaceRequest::Spec DevPlaceRequest::makePost(std::string path, const Token& token) {
  Spec s;
  s.method = HttpSpec::kPost;
  s.path = std::move(path);
  s.token = token;
  return s;
}

DevPlaceRequest::Spec DevPlaceRequest::makePostJson(std::string path, const Json& body, const Token& token) {
  Spec s = makePost(std::move(path), token);
  s.kind = BodyKind::Json;
  s.body = dumpJson(body);
  return s;
}

std::string DevPlaceRequest::seg(const std::string& segment) { return UrlCodec::encode(segment); }

void DevPlaceRequest::addBefore(Query& query, const std::optional<Date>& before) {
  if (before) query.emplace_back(ApiQueryKeys::kBefore, DateCodec::formatIso8601(*before));
}

void DevPlaceRequest::addOpt(Query& query, const char* key, const Str& value) {
  if (value) query.emplace_back(key, *value);
}

Error DevPlaceRequest::decodeError() {
  return Error{Error::Kind::Decode, 0, spec::UiMessages::kResponseUnreadable, false};
}

CancelPtr DevPlaceRequest::exchange(Spec spec, Done<std::string> done) {
  HttpRequest request;
  request.method = spec.method;
  request.path = std::move(spec.path);
  request.query = std::move(spec.query);
  if (spec.token) {
    request.headers.emplace_back(HttpSpec::kAuthorizationHeader, std::string(HttpSpec::kBearerPrefix) + spec.token->accessToken);
  }
  request.headers.emplace_back(HttpSpec::kAcceptHeader, HttpSpec::kAcceptJson);
  switch (spec.kind) {
    case BodyKind::UrlEncoded: request.contentType = HttpSpec::kContentUrlEncoded; break;
    case BodyKind::Json: request.contentType = HttpSpec::kContentJson; break;
    case BodyKind::Multipart: request.contentType = std::string(HttpSpec::kContentMultipartPrefix) + spec.boundary; break;
  }
  request.body = std::move(spec.body);
  return network_.send(std::move(request), [done = std::move(done)](Result<HttpResponse> r) {
    if (!r.ok()) return done(Result<std::string>(r.error()));
    const HttpResponse& response = r.value();
    if (response.status >= HttpSpec::kFirstSuccessStatus && response.status <= HttpSpec::kLastSuccessStatus) {
      return done(Result<std::string>(response.body));
    }
    done(Result<std::string>(ApiErrorDecoder::fromResponse(response.status, response.body)));
  });
}

CancelPtr DevPlaceRequest::perform(Spec spec, Done<Unit> done) {
  return exchange(std::move(spec), [done = std::move(done)](Result<std::string> r) {
    if (!r.ok()) return done(Result<Unit>(r.error()));
    done(Result<Unit>(Unit{}));
  });
}

// ---- auth ----------------------------------------------------------------------------------------------------

CancelPtr DevPlaceRequest::getAuthToken(const std::string& email, const std::string& password, Done<AuthToken> done) {
  return fetch<AuthToken>(makePostJson(ApiPaths::kAuthToken, Json{{"email", email}, {"password", password}}, std::nullopt),
                          std::move(done));
}

CancelPtr DevPlaceRequest::signUp(const std::string& username, const std::string& email, const std::string& password,
                                  const std::string& confirmPassword, const BirthDate& birthDate, bool acceptTerms,
                                  Done<Unit> done) {
  Json body{{"username", username},
            {"email", email},
            {"password", password},
            {"confirm_password", confirmPassword},
            {"birth_date", birthDate.toString()},
            {"accept_terms", acceptTerms ? "on" : "off"}};
  return perform(makePostJson(ApiPaths::kSignUp, body, std::nullopt), std::move(done));
}

CancelPtr DevPlaceRequest::forgotPassword(const std::string& email, Done<Unit> done) {
  return perform(makePostJson(ApiPaths::kForgotPassword, Json{{"email", email}}, std::nullopt), std::move(done));
}

CancelPtr DevPlaceRequest::resetPassword(const std::string& resetToken, const std::string& password,
                                         const std::string& confirmPassword, Done<Unit> done) {
  return perform(makePostJson(ApiPaths::kResetPasswordPrefix + seg(resetToken),
                              Json{{"password", password}, {"confirm_password", confirmPassword}}, std::nullopt),
                 std::move(done));
}

// ---- feed and posts ------------------------------------------------------------------------------------------

CancelPtr DevPlaceRequest::getFeed(const Str& tab, const Str& topic, const Str& search, const std::optional<Date>& before,
                                   const Token& token, Done<Feed> done) {
  Query q;
  addOpt(q, ApiQueryKeys::kTab, tab);
  addOpt(q, ApiQueryKeys::kTopic, topic);
  addOpt(q, ApiQueryKeys::kSearch, search);
  addBefore(q, before);
  return fetch<Feed>(makeGet(ApiPaths::kFeed, std::move(q), token), std::move(done));
}

CancelPtr DevPlaceRequest::getPost(const std::string& slug, const Token& token, Done<PostDetail> done) {
  return fetch<PostDetail>(makeGet(ApiPaths::kPostPrefix + seg(slug), {}, token), std::move(done));
}

CancelPtr DevPlaceRequest::createPost(const Str& title, const std::optional<PostTopic>& topic, const std::string& content,
                                      const std::vector<UploadResponse>& attachments, const Str& pollQuestion,
                                      const std::vector<std::string>& pollOptions, const Str& projectLink,
                                      const AuthToken& token, Done<Unit> done) {
  Json body = Json::object();
  if (title) body["title"] = *title;
  if (topic) body["topic"] = topic->raw();
  body["content"] = content;
  Json uids = Json::array();
  for (const auto& a : attachments) uids.push_back(a.id);
  body["attachment_uids"] = uids;
  if (pollQuestion) body["poll_question"] = *pollQuestion;
  body["poll_options"] = pollOptions;
  if (projectLink) body["project_uid"] = *projectLink;
  return perform(makePostJson(ApiPaths::kPostCreate, body, token), std::move(done));
}

CancelPtr DevPlaceRequest::editPost(const std::string& slug, const std::string& title, PostTopic topic,
                                    const std::string& content, const std::string& projectLink, const AuthToken& token,
                                    Done<Unit> done) {
  Json body{{"title", title}, {"topic", topic.raw()}, {"content", content}, {"project_uid", projectLink}};
  return perform(makePostJson(ApiPaths::kPostEditPrefix + seg(slug), body, token), std::move(done));
}

CancelPtr DevPlaceRequest::deletePost(const std::string& slug, const AuthToken& token, Done<Unit> done) {
  return perform(makePost(ApiPaths::kPostDeletePrefix + seg(slug), token), std::move(done));
}

// ---- comments ------------------------------------------------------------------------------------------------

CancelPtr DevPlaceRequest::createComment(TargetType targetType, const std::string& targetId, const std::string& content,
                                         const Str& parentId, const std::vector<UploadResponse>& attachments,
                                         const AuthToken& token, Done<Unit> done) {
  Json body = Json::object();
  body["target_type"] = targetType.raw();
  body["target_uid"] = targetId;
  body["content"] = content;
  if (parentId) body["parent_uid"] = *parentId;
  Json uids = Json::array();
  for (const auto& a : attachments) uids.push_back(a.id);
  body["attachment_uids"] = uids;
  return perform(makePostJson(ApiPaths::kCommentCreate, body, token), std::move(done));
}

CancelPtr DevPlaceRequest::editComment(const std::string& uid, const std::string& content, const AuthToken& token,
                                       Done<Unit> done) {
  return perform(makePostJson(ApiPaths::kCommentEditPrefix + seg(uid), Json{{"content", content}}, token), std::move(done));
}

CancelPtr DevPlaceRequest::deleteComment(const std::string& uid, const AuthToken& token, Done<Unit> done) {
  return perform(makePost(ApiPaths::kCommentDeletePrefix + seg(uid), token), std::move(done));
}

// ---- projects, gists, news -----------------------------------------------------------------------------------

CancelPtr DevPlaceRequest::getProjects(const Str& tab, const Str& search, const Str& projectType,
                                       const std::optional<Date>& before, const Token& token, Done<Projects> done) {
  Query q;
  addOpt(q, ApiQueryKeys::kTab, tab);
  addOpt(q, ApiQueryKeys::kSearch, search);
  addOpt(q, ApiQueryKeys::kProjectType, projectType);
  addBefore(q, before);
  return fetch<Projects>(makeGet(ApiPaths::kProjects, std::move(q), token), std::move(done));
}

CancelPtr DevPlaceRequest::getProject(const std::string& slug, const Token& token, Done<ProjectDetail> done) {
  return fetch<ProjectDetail>(makeGet(ApiPaths::kProjectPrefix + seg(slug), {}, token), std::move(done));
}

CancelPtr DevPlaceRequest::getGists(const Str& language, const Str& userId, const Str& search,
                                    const std::optional<Date>& before, const Token& token, Done<Gists> done) {
  Query q;
  addOpt(q, ApiQueryKeys::kLanguage, language);
  addOpt(q, ApiQueryKeys::kUserUid, userId);
  addOpt(q, ApiQueryKeys::kSearch, search);
  addBefore(q, before);
  return fetch<Gists>(makeGet(ApiPaths::kGists, std::move(q), token), std::move(done));
}

CancelPtr DevPlaceRequest::getGist(const std::string& slug, const Token& token, Done<GistDetail> done) {
  return fetch<GistDetail>(makeGet(ApiPaths::kGistPrefix + seg(slug), {}, token), std::move(done));
}

CancelPtr DevPlaceRequest::getNews(const std::optional<Date>& before, const Token& token, Done<News> done) {
  Query q;
  addBefore(q, before);
  return fetch<News>(makeGet(ApiPaths::kNews, std::move(q), token), std::move(done));
}

CancelPtr DevPlaceRequest::getArticle(const std::string& slug, const Token& token, Done<ArticleDetail> done) {
  return fetch<ArticleDetail>(makeGet(ApiPaths::kNewsPrefix + seg(slug), {}, token), std::move(done));
}

// ---- profile and social graph --------------------------------------------------------------------------------

CancelPtr DevPlaceRequest::getProfile(const Str& username, const Str& tab, const Token& token, Done<Profile> done) {
  Query q;
  addOpt(q, ApiQueryKeys::kTab, tab);
  const std::string path = username ? ApiPaths::kProfilePrefix + seg(*username) : std::string(ApiPaths::kProfile);
  return fetch<Profile>(makeGet(path, std::move(q), token), std::move(done));
}

CancelPtr DevPlaceRequest::searchProfiles(const std::string& q, Done<UserSearch> done) {
  return fetch<UserSearch>(makeGet(ApiPaths::kProfileSearch, {{ApiQueryKeys::kQ, q}}, std::nullopt), std::move(done));
}

CancelPtr DevPlaceRequest::deleteAccount(const std::string& username, const std::string& password, const AuthToken& token,
                                         Done<Unit> done) {
  return perform(makePostJson(ApiPaths::kProfilePrefix + seg(username) + ApiPaths::kProfileDeleteSuffix,
                              Json{{"password", password}}, token),
                 std::move(done));
}

CancelPtr DevPlaceRequest::getFollowers(const std::string& username, const std::optional<int>& page, const Token& token,
                                        Done<Followers> done) {
  Query q;
  if (page) q.emplace_back(ApiQueryKeys::kPage, std::to_string(*page));
  return fetch<Followers>(makeGet(ApiPaths::kProfilePrefix + seg(username) + ApiPaths::kFollowersSuffix, std::move(q), token),
                          std::move(done));
}

CancelPtr DevPlaceRequest::getFollowing(const std::string& username, const std::optional<int>& page, const Token& token,
                                        Done<Following> done) {
  Query q;
  if (page) q.emplace_back(ApiQueryKeys::kPage, std::to_string(*page));
  return fetch<Following>(makeGet(ApiPaths::kProfilePrefix + seg(username) + ApiPaths::kFollowingSuffix, std::move(q), token),
                          std::move(done));
}

CancelPtr DevPlaceRequest::followUser(const std::string& username, const AuthToken& token, Done<Unit> done) {
  return perform(makePost(ApiPaths::kFollowPrefix + seg(username), token), std::move(done));
}

CancelPtr DevPlaceRequest::unfollowUser(const std::string& username, const AuthToken& token, Done<Unit> done) {
  return perform(makePost(ApiPaths::kUnfollowPrefix + seg(username), token), std::move(done));
}

CancelPtr DevPlaceRequest::blockUser(const std::string& username, const AuthToken& token, Done<Unit> done) {
  return perform(makePost(ApiPaths::kBlockPrefix + seg(username), token), std::move(done));
}

CancelPtr DevPlaceRequest::unblockUser(const std::string& username, const AuthToken& token, Done<Unit> done) {
  return perform(makePost(ApiPaths::kUnblockPrefix + seg(username), token), std::move(done));
}

CancelPtr DevPlaceRequest::muteUser(const std::string& username, const AuthToken& token, Done<Unit> done) {
  return perform(makePost(ApiPaths::kMutePrefix + seg(username), token), std::move(done));
}

CancelPtr DevPlaceRequest::unmuteUser(const std::string& username, const AuthToken& token, Done<Unit> done) {
  return perform(makePost(ApiPaths::kUnmutePrefix + seg(username), token), std::move(done));
}

CancelPtr DevPlaceRequest::getLeaderboard(const Token& token, Done<Leaderboard> done) {
  return fetch<Leaderboard>(makeGet(ApiPaths::kLeaderboard, {}, token), std::move(done));
}

// ---- engagement ----------------------------------------------------------------------------------------------

CancelPtr DevPlaceRequest::vote(TargetType targetType, const std::string& targetId, Vote vote, const AuthToken& token,
                                Done<Unit> done) {
  return perform(makePostJson(ApiPaths::kVotePrefix + std::string(targetType.raw()) + "/" + seg(targetId),
                              Json{{"value", vote.value()}}, token),
                 std::move(done));
}

CancelPtr DevPlaceRequest::submitPollChoice(const std::string& pollId, const std::string& optionId, const AuthToken& token,
                                            Done<Unit> done) {
  return perform(makePostJson(ApiPaths::kPollPrefix + seg(pollId) + ApiPaths::kPollVoteSuffix, Json{{"option_uid", optionId}},
                              token),
                 std::move(done));
}

CancelPtr DevPlaceRequest::react(TargetType targetType, const std::string& targetId, const std::string& emoji,
                                 const AuthToken& token, Done<Unit> done) {
  return perform(makePostJson(ApiPaths::kReactionPrefix + std::string(targetType.raw()) + "/" + seg(targetId),
                              Json{{"emoji", emoji}}, token),
                 std::move(done));
}

CancelPtr DevPlaceRequest::toggleBookmark(TargetType targetType, const std::string& targetId, const AuthToken& token,
                                          Done<Unit> done) {
  return perform(makePost(ApiPaths::kBookmarkPrefix + std::string(targetType.raw()) + "/" + seg(targetId), token),
                 std::move(done));
}

CancelPtr DevPlaceRequest::getBookmarks(const std::optional<Date>& before, const AuthToken& token, Done<Bookmarks> done) {
  Query q;
  addBefore(q, before);
  return fetch<Bookmarks>(makeGet(ApiPaths::kBookmarksSaved, std::move(q), token), std::move(done));
}

// ---- reports -------------------------------------------------------------------------------------------------

CancelPtr DevPlaceRequest::getReportReasons(Done<std::vector<ReportReason>> done) {
  return exchange(makeGet(ApiPaths::kReportReasons, {}, std::nullopt), [done = std::move(done)](Result<std::string> r) {
    if (!r.ok()) return done(Result<std::vector<ReportReason>>(r.error()));
    try {
      done(Result<std::vector<ReportReason>>(ReportReason::listFromJson(Json::parse(r.value()))));
    } catch (const std::exception&) {
      done(Result<std::vector<ReportReason>>(decodeError()));
    }
  });
}

CancelPtr DevPlaceRequest::report(TargetType targetType, const std::string& targetId, const std::string& reason,
                                  const Str& detail, const AuthToken& token, Done<Unit> done) {
  Json body = Json::object();
  body["reason"] = reason;
  if (detail) body["detail"] = *detail;
  return perform(makePostJson(ApiPaths::kReportPrefix + std::string(targetType.raw()) + "/" + seg(targetId), body, token),
                 std::move(done));
}

// ---- messaging -----------------------------------------------------------------------------------------------

CancelPtr DevPlaceRequest::getMessages(const Str& withUid, const Str& search, const AuthToken& token, Done<MessagesInbox> done) {
  Query q;
  addOpt(q, ApiQueryKeys::kWithUid, withUid);
  addOpt(q, ApiQueryKeys::kSearch, search);
  return fetch<MessagesInbox>(makeGet(ApiPaths::kMessages, std::move(q), token), std::move(done));
}

CancelPtr DevPlaceRequest::sendMessage(const std::string& receiverId, const std::string& content,
                                       const std::vector<UploadResponse>& attachments, const AuthToken& token,
                                       Done<Unit> done) {
  Json uids = Json::array();
  for (const auto& a : attachments) uids.push_back(a.id);
  Json body{{"receiver_uid", receiverId}, {"content", content}, {"attachment_uids", uids}};
  return perform(makePostJson(ApiPaths::kMessageSend, body, token), std::move(done));
}

CancelPtr DevPlaceRequest::searchMessageRecipients(const std::string& q, const AuthToken& token, Done<UserSearch> done) {
  return fetch<UserSearch>(makeGet(ApiPaths::kMessageSearch, {{ApiQueryKeys::kQ, q}}, token), std::move(done));
}

CancelPtr DevPlaceRequest::getMessagesWebSocketTicket(const AuthToken& token, Done<MessagesWebSocketTicket> done) {
  return fetch<MessagesWebSocketTicket>(makePost(ApiPaths::kMessageTicket, token), std::move(done));
}

std::string DevPlaceRequest::messagesWebSocketUrl(const std::string& ticket) const {
  std::string base = network_.baseUrl();
  if (base.rfind("https://", 0) == 0) base = "wss://" + base.substr(8);
  else if (base.rfind("http://", 0) == 0) base = "ws://" + base.substr(7);
  if (base.empty() || base.back() != '/') base.push_back('/');
  std::string encoded;
  const std::string allowed = HttpSpec::kUrlQueryAllowedExtra;
  for (const unsigned char c : ticket) {
    if (std::isalnum(c) || allowed.find(static_cast<char>(c)) != std::string::npos) {
      encoded.push_back(static_cast<char>(c));
    } else {
      static const char* hex = "0123456789ABCDEF";
      encoded.push_back('%');
      encoded.push_back(hex[c >> 4]);
      encoded.push_back(hex[c & 0x0F]);
    }
  }
  return base + ApiPaths::kMessageSocket + encoded;
}

// ---- notifications -------------------------------------------------------------------------------------------

CancelPtr DevPlaceRequest::getNotifications(const std::optional<Date>& before, const AuthToken& token,
                                            Done<Notifications> done) {
  Query q;
  addBefore(q, before);
  return fetch<Notifications>(makeGet(ApiPaths::kNotifications, std::move(q), token), std::move(done));
}

CancelPtr DevPlaceRequest::openNotification(const std::string& uid, const AuthToken& token, Done<NotificationOpen> done) {
  return fetch<NotificationOpen>(makeGet(ApiPaths::kNotificationOpenPrefix + seg(uid), {}, token), std::move(done));
}

CancelPtr DevPlaceRequest::getNotificationCounts(const AuthToken& token, Done<NotificationCounts> done) {
  return fetch<NotificationCounts>(makeGet(ApiPaths::kNotificationCounts, {}, token), std::move(done));
}

CancelPtr DevPlaceRequest::markNotificationRead(const std::string& uid, const AuthToken& token, Done<Unit> done) {
  return perform(makePost(ApiPaths::kNotificationMarkReadPrefix + seg(uid), token), std::move(done));
}

CancelPtr DevPlaceRequest::markAllNotificationsRead(const AuthToken& token, Done<Unit> done) {
  return perform(makePost(ApiPaths::kNotificationMarkAllRead, token), std::move(done));
}

// ---- push ----------------------------------------------------------------------------------------------------

CancelPtr DevPlaceRequest::registerPushDevice(PushProvider provider, const std::string& deviceToken, const AuthToken& token,
                                              Done<Unit> done) {
  return perform(makePostJson(ApiPaths::kPush, Json{{"provider", provider.raw()}, {"token", deviceToken}}, token),
                 std::move(done));
}

// ---- uploads -------------------------------------------------------------------------------------------------

CancelPtr DevPlaceRequest::uploadFile(const std::string& data, const std::string& filename, const std::string& mimeType,
                                      const AuthToken& token, Done<UploadResponse> done) {
  const std::string boundary = std::string(HttpSpec::kBoundaryPrefix) + Uuid::random();
  const std::string lb = HttpSpec::kLineBreak;
  Spec s = makePost(ApiPaths::kUpload, token);
  s.kind = BodyKind::Multipart;
  s.boundary = boundary;
  s.body.reserve(data.size() + 256);
  s.body += "--" + boundary + lb;
  s.body += std::string("Content-Disposition: form-data; name=\"") + HttpSpec::kUploadFieldName + "\"; filename=\"" + filename + "\"" + lb;
  s.body += "Content-Type: " + mimeType + lb + lb;
  s.body += data;
  s.body += lb + "--" + boundary + "--" + lb;
  return fetch<UploadResponse>(std::move(s), std::move(done));
}

CancelPtr DevPlaceRequest::uploadFromUrl(const std::string& url, const Str& filename, const AuthToken& token,
                                         Done<UploadResponse> done) {
  Json body = Json::object();
  body["url"] = url;
  if (filename) body["filename"] = *filename;
  return fetch<UploadResponse>(makePostJson(ApiPaths::kUploadUrl, body, token), std::move(done));
}

CancelPtr DevPlaceRequest::deleteAttachment(const std::string& uid, const AuthToken& token, Done<Unit> done) {
  Spec s = makePost(ApiPaths::kUploadDeletePrefix + seg(uid), token);
  s.method = HttpSpec::kDelete;
  return perform(std::move(s), std::move(done));
}

}  // namespace dp
25.1ms