#include "api/DevPlaceRequest.hpp" #include #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& 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 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 r) { if (!r.ok()) return done(Result(r.error())); const HttpResponse& response = r.value(); if (response.status >= HttpSpec::kFirstSuccessStatus && response.status <= HttpSpec::kLastSuccessStatus) { return done(Result(response.body)); } done(Result(ApiErrorDecoder::fromResponse(response.status, response.body))); }); } CancelPtr DevPlaceRequest::perform(Spec spec, Done done) { return exchange(std::move(spec), [done = std::move(done)](Result r) { if (!r.ok()) return done(Result(r.error())); done(Result(Unit{})); }); } // ---- auth ---------------------------------------------------------------------------------------------------- CancelPtr DevPlaceRequest::getAuthToken(const std::string& email, const std::string& password, Done done) { return fetch(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 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 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 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& before, const Token& token, Done done) { Query q; addOpt(q, ApiQueryKeys::kTab, tab); addOpt(q, ApiQueryKeys::kTopic, topic); addOpt(q, ApiQueryKeys::kSearch, search); addBefore(q, before); return fetch(makeGet(ApiPaths::kFeed, std::move(q), token), std::move(done)); } CancelPtr DevPlaceRequest::getPost(const std::string& slug, const Token& token, Done done) { return fetch(makeGet(ApiPaths::kPostPrefix + seg(slug), {}, token), std::move(done)); } CancelPtr DevPlaceRequest::createPost(const Str& title, const std::optional& topic, const std::string& content, const std::vector& attachments, const Str& pollQuestion, const std::vector& pollOptions, const Str& projectLink, const AuthToken& token, Done 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 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 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& attachments, const AuthToken& token, Done 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 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 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& before, const Token& token, Done done) { Query q; addOpt(q, ApiQueryKeys::kTab, tab); addOpt(q, ApiQueryKeys::kSearch, search); addOpt(q, ApiQueryKeys::kProjectType, projectType); addBefore(q, before); return fetch(makeGet(ApiPaths::kProjects, std::move(q), token), std::move(done)); } CancelPtr DevPlaceRequest::getProject(const std::string& slug, const Token& token, Done done) { return fetch(makeGet(ApiPaths::kProjectPrefix + seg(slug), {}, token), std::move(done)); } CancelPtr DevPlaceRequest::getGists(const Str& language, const Str& userId, const Str& search, const std::optional& before, const Token& token, Done done) { Query q; addOpt(q, ApiQueryKeys::kLanguage, language); addOpt(q, ApiQueryKeys::kUserUid, userId); addOpt(q, ApiQueryKeys::kSearch, search); addBefore(q, before); return fetch(makeGet(ApiPaths::kGists, std::move(q), token), std::move(done)); } CancelPtr DevPlaceRequest::getGist(const std::string& slug, const Token& token, Done done) { return fetch(makeGet(ApiPaths::kGistPrefix + seg(slug), {}, token), std::move(done)); } CancelPtr DevPlaceRequest::getNews(const std::optional& before, const Token& token, Done done) { Query q; addBefore(q, before); return fetch(makeGet(ApiPaths::kNews, std::move(q), token), std::move(done)); } CancelPtr DevPlaceRequest::getArticle(const std::string& slug, const Token& token, Done done) { return fetch(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 done) { Query q; addOpt(q, ApiQueryKeys::kTab, tab); const std::string path = username ? ApiPaths::kProfilePrefix + seg(*username) : std::string(ApiPaths::kProfile); return fetch(makeGet(path, std::move(q), token), std::move(done)); } CancelPtr DevPlaceRequest::searchProfiles(const std::string& q, Done done) { return fetch(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 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& page, const Token& token, Done done) { Query q; if (page) q.emplace_back(ApiQueryKeys::kPage, std::to_string(*page)); return fetch(makeGet(ApiPaths::kProfilePrefix + seg(username) + ApiPaths::kFollowersSuffix, std::move(q), token), std::move(done)); } CancelPtr DevPlaceRequest::getFollowing(const std::string& username, const std::optional& page, const Token& token, Done done) { Query q; if (page) q.emplace_back(ApiQueryKeys::kPage, std::to_string(*page)); return fetch(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 done) { return perform(makePost(ApiPaths::kFollowPrefix + seg(username), token), std::move(done)); } CancelPtr DevPlaceRequest::unfollowUser(const std::string& username, const AuthToken& token, Done done) { return perform(makePost(ApiPaths::kUnfollowPrefix + seg(username), token), std::move(done)); } CancelPtr DevPlaceRequest::blockUser(const std::string& username, const AuthToken& token, Done done) { return perform(makePost(ApiPaths::kBlockPrefix + seg(username), token), std::move(done)); } CancelPtr DevPlaceRequest::unblockUser(const std::string& username, const AuthToken& token, Done done) { return perform(makePost(ApiPaths::kUnblockPrefix + seg(username), token), std::move(done)); } CancelPtr DevPlaceRequest::muteUser(const std::string& username, const AuthToken& token, Done done) { return perform(makePost(ApiPaths::kMutePrefix + seg(username), token), std::move(done)); } CancelPtr DevPlaceRequest::unmuteUser(const std::string& username, const AuthToken& token, Done done) { return perform(makePost(ApiPaths::kUnmutePrefix + seg(username), token), std::move(done)); } CancelPtr DevPlaceRequest::getLeaderboard(const Token& token, Done done) { return fetch(makeGet(ApiPaths::kLeaderboard, {}, token), std::move(done)); } // ---- engagement ---------------------------------------------------------------------------------------------- CancelPtr DevPlaceRequest::vote(TargetType targetType, const std::string& targetId, Vote vote, const AuthToken& token, Done 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 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 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 done) { return perform(makePost(ApiPaths::kBookmarkPrefix + std::string(targetType.raw()) + "/" + seg(targetId), token), std::move(done)); } CancelPtr DevPlaceRequest::getBookmarks(const std::optional& before, const AuthToken& token, Done done) { Query q; addBefore(q, before); return fetch(makeGet(ApiPaths::kBookmarksSaved, std::move(q), token), std::move(done)); } // ---- reports ------------------------------------------------------------------------------------------------- CancelPtr DevPlaceRequest::getReportReasons(Done> done) { return exchange(makeGet(ApiPaths::kReportReasons, {}, std::nullopt), [done = std::move(done)](Result r) { if (!r.ok()) return done(Result>(r.error())); try { done(Result>(ReportReason::listFromJson(Json::parse(r.value())))); } catch (const std::exception&) { done(Result>(decodeError())); } }); } CancelPtr DevPlaceRequest::report(TargetType targetType, const std::string& targetId, const std::string& reason, const Str& detail, const AuthToken& token, Done 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 done) { Query q; addOpt(q, ApiQueryKeys::kWithUid, withUid); addOpt(q, ApiQueryKeys::kSearch, search); return fetch(makeGet(ApiPaths::kMessages, std::move(q), token), std::move(done)); } CancelPtr DevPlaceRequest::sendMessage(const std::string& receiverId, const std::string& content, const std::vector& attachments, const AuthToken& token, Done 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 done) { return fetch(makeGet(ApiPaths::kMessageSearch, {{ApiQueryKeys::kQ, q}}, token), std::move(done)); } CancelPtr DevPlaceRequest::getMessagesWebSocketTicket(const AuthToken& token, Done done) { return fetch(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(c)) != std::string::npos) { encoded.push_back(static_cast(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& before, const AuthToken& token, Done done) { Query q; addBefore(q, before); return fetch(makeGet(ApiPaths::kNotifications, std::move(q), token), std::move(done)); } CancelPtr DevPlaceRequest::openNotification(const std::string& uid, const AuthToken& token, Done done) { return fetch(makeGet(ApiPaths::kNotificationOpenPrefix + seg(uid), {}, token), std::move(done)); } CancelPtr DevPlaceRequest::getNotificationCounts(const AuthToken& token, Done done) { return fetch(makeGet(ApiPaths::kNotificationCounts, {}, token), std::move(done)); } CancelPtr DevPlaceRequest::markNotificationRead(const std::string& uid, const AuthToken& token, Done done) { return perform(makePost(ApiPaths::kNotificationMarkReadPrefix + seg(uid), token), std::move(done)); } CancelPtr DevPlaceRequest::markAllNotificationsRead(const AuthToken& token, Done done) { return perform(makePost(ApiPaths::kNotificationMarkAllRead, token), std::move(done)); } // ---- push ---------------------------------------------------------------------------------------------------- CancelPtr DevPlaceRequest::registerPushDevice(PushProvider provider, const std::string& deviceToken, const AuthToken& token, Done 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 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(std::move(s), std::move(done)); } CancelPtr DevPlaceRequest::uploadFromUrl(const std::string& url, const Str& filename, const AuthToken& token, Done done) { Json body = Json::object(); body["url"] = url; if (filename) body["filename"] = *filename; return fetch(makePostJson(ApiPaths::kUploadUrl, body, token), std::move(done)); } CancelPtr DevPlaceRequest::deleteAttachment(const std::string& uid, const AuthToken& token, Done done) { Spec s = makePost(ApiPaths::kUploadDeletePrefix + seg(uid), token); s.method = HttpSpec::kDelete; return perform(std::move(s), std::move(done)); } } // namespace dp