78 lines
2.3 KiB
C++
78 lines
2.3 KiB
C++
#include "vk.h"
|
|
#include "curl/curl.h"
|
|
#include "http.h"
|
|
#include "spdlog/sinks/stdout_color_sinks.h"
|
|
#include <memory>
|
|
#include <nlohmann/json.hpp>
|
|
|
|
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<long, std::string> wall, int offset, int count, std::function<void(std::optional<WallChunk>, 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<long>(wall));
|
|
} else {
|
|
url += "&domain=";
|
|
url += std::get<std::string>(wall);
|
|
}
|
|
m_logger->debug("using URL: {}", url);
|
|
|
|
m_httpClient.send_request("GET", url, {}, [this, callback](std::unique_ptr<http::HttpResponse> 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<Post> 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);
|
|
}
|
|
});
|
|
} |