#include "vk.h" #include "curl/curl.h" #include "http.h" #include "spdlog/sinks/stdout_color_sinks.h" #include #include using namespace vk; using namespace nlohmann; const char *API_BASE_URL = "https://api.vk.com/method/"; const char *API_VERSION = "5.199"; const char *LOGGER_TAG = "vk"; VKClient::VKClient(uv_loop_t *eventLoop) : m_httpClient(eventLoop) { m_logger = spdlog::get(LOGGER_TAG); if (!m_logger) { m_logger = spdlog::stdout_color_mt(LOGGER_TAG); m_logger->set_level(spdlog::level::debug); } }; VKClient::VKClient(uv_loop_t *eventLoop, std::string serviceKey) : VKClient(eventLoop) { set_service_api_key(serviceKey); } void VKClient::set_service_api_key(std::string key) { m_serviceApiKey = {key}; } void VKClient::get_posts(std::variant wall, int offset, int count, std::function, int)> callback) { if (!m_serviceApiKey) { m_logger->error("get_posts called without authorization"); return; } std::string url(API_BASE_URL); url += "wall.get?access_token="; url += *m_serviceApiKey; url += "&v="; url += API_VERSION; url += "&offset="; url += std::to_string(offset); url += "&count="; url += std::to_string(count); if (wall.index() == 0) { url += "&owner_id="; url += std::to_string(std::get(wall)); } else { url += "&domain="; url += std::get(wall); } m_logger->debug("using URL: {}", url); m_httpClient.send_request("GET", url, {}, [this, callback](std::unique_ptr resp, CURLcode r){ if (r == 0) { auto parsedResponse = json::parse(resp->body); if (parsedResponse.contains("error")) { auto err = parsedResponse["error"]; m_logger->error("get_posts error {} {}", (int)err["error_code"], (std::string)err["error_msg"]); callback({}, -1); return; } auto responsePayload = parsedResponse["response"]; int count = responsePayload["count"]; std::vector posts; for (auto post : responsePayload["items"]) { posts.emplace_back(post["id"], post["date"], post["edited"], post["from_id"], post["type"], post["text"]); } callback({{count, std::move(posts)}}, 0); } else { m_logger->error("get_posts network error"); callback({}, r); } }); }