summaryrefslogtreecommitdiff
path: root/battleNetApi/src/hearthstoneApi.cpp
blob: 945425f8c7dae6407ac70e6836896f7bb6f0a565 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include "hearthstoneApi.hpp"
#include <curl/curl.h>
#include <format>

HearthstoneApi::HearthstoneApi(Token &&iToken) : mToken(iToken), mAuthorizationHeader(authorizationHeader()) {}
HearthstoneApi::HearthstoneApi(const Token &iToken) : mToken(iToken), mAuthorizationHeader(authorizationHeader()) {}

std::string HearthstoneApi::authorizationHeader() { return std::format("Authorization: Bearer {}", mToken.text()); }

size_t HearthstoneApi::curlCallbackStringOutput(void *iContent, size_t iSize, size_t iNmemb, std::string *iS) {
    const size_t kNewLength = iSize * iNmemb;
    try {
        iS->append(static_cast<char *>(iContent), kNewLength);
    } catch (std::bad_alloc &e) {
        // handle memory problem
        return 0;
    }
    return kNewLength;
}

json HearthstoneApi::makeApiRequest(const std::string &iUrl) const {
    CURL *curl = curl_easy_init();
    std::string aRequestOutput;
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, iUrl.c_str());
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlCallbackStringOutput);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &aRequestOutput);
        struct curl_slist *chunk = nullptr;
        chunk = curl_slist_append(chunk, mAuthorizationHeader.c_str());
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
        curl_easy_perform(curl);
        curl_easy_cleanup(curl);
    }
    json aOutputJson = json::parse(aRequestOutput);
    return aOutputJson;
}