summaryrefslogtreecommitdiff
path: root/subprojects/battleNetApi/src/hearthstoneApi.cpp
blob: 706906a6cff5d31661c2ed58e268da02840262b2 (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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include "hearthstoneApi.hpp"
#include <chrono>
#include <curl/curl.h>
#include <format>
#include <fstream>
#include <iostream>
#include <regex>

HearthstoneApi::HearthstoneApi()
    : mTokenFilePath(std::format("{}/resources/token_info.txt", SOURCE_DIR_PATH)), mToken(getValidToken()),
      m_header(generateRequestHeader()) {}

size_t HearthstoneApi::curlCallbackStringOutput(void *t_contents, size_t t_size, size_t t_nmemb, std::string *t_s) {
    size_t newLength = t_size * t_nmemb;
    try {
        t_s->append(static_cast<char *>(t_contents), newLength);
    } catch (std::bad_alloc &e) {
        // handle memory problem
        return 0;
    }
    return newLength;
}

std::chrono::seconds HearthstoneApi::getCurrentTime() const {
    return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::utc_clock::now().time_since_epoch());
}

std::string HearthstoneApi::extractStringWithRegex(const std::string &t_str, const std::string t_regex) const {
    std::regex regex(t_regex);
    auto it = std::sregex_iterator(t_str.begin(), t_str.end(), regex);
    std::smatch match = *it;
    return match[1].str();
}

std::string HearthstoneApi::getValidTokenWithApi() const {
    CURL *curl = curl_easy_init();
    std::string token_info;
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "https://oauth.battle.net/token");
        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, &token_info);
        curl_easy_setopt(curl, CURLOPT_USERPWD,
                         "2b50f1123b424d5e9c21971a110fdd04:"
                         "MrMkhVMNdOeqPL4Q4XVQAsRPR14J7Yq6");
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
        CURLcode result_code;
        result_code = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        if (result_code != CURLE_OK) {
            std::cerr << "ERROR: token request failed" << std::endl;
            std::exit(EXIT_FAILURE);
        }
    }

    return extractStringWithRegex(token_info, "\"access_token\":\"(\\w+)\"");
}

void HearthstoneApi::writeNewTokenToFile() const {
    std::string aToken{getValidTokenWithApi()};
    writeTokenToFile(aToken);
}

void HearthstoneApi::writeTokenToFile(const std::string &iToken) const {
    std::ofstream token_file(mTokenFilePath);
    std::chrono::seconds expires_at = getCurrentTime() + std::chrono::hours(24);
    token_file << iToken << " " << expires_at.count() << '\n';
}

void HearthstoneApi::refreshToken() {
    std::string file_path = std::format("{}/resources/token_info.txt", SOURCE_DIR_PATH);
    std::ifstream token_file(file_path);
    std::string line;
    std::getline(token_file, line);
    if (line.empty()) {
        writeNewTokenToFile();
    } else {
        long expire_at = std::stoull(line.substr(line.find(" ") + 1));
        if (std::chrono::duration_cast<std::chrono::seconds>(std::chrono::utc_clock::now().time_since_epoch())
                .count() >= expire_at) {
            writeNewTokenToFile();
        }
    }
}
std::string HearthstoneApi::getValidToken() {
    refreshToken();
    std::ifstream token_file(mTokenFilePath);
    std::string line;
    std::getline(token_file, line);
    std::string token = line.substr(0, line.find(" "));
    return token;
}

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

const std::string HearthstoneApi::getUrl(const std::string &t_parameters) {
    return std::format("https://eu.api.blizzard.com/hearthstone/{}", t_parameters);
}

const std::string HearthstoneApi::getSetOfCardsUrl(const std::string &t_card_parameters) {
    return getUrl(std::format("cards{}", t_card_parameters));
}

std::string HearthstoneApi::makeApiRequest(const char *t_url, const char *t_header) {
    CURL *curl = curl_easy_init();
    std::string request_output;
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, t_url);
        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, &request_output);
        struct curl_slist *chunk = nullptr;
        chunk = curl_slist_append(chunk, t_header);
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
        curl_easy_perform(curl);
        curl_easy_cleanup(curl);
    }
    return request_output;
}

std::string HearthstoneApi::makeApiRequest(const std::string &t_url, const std::string &t_header) {
    return makeApiRequest(t_url.c_str(), t_header.c_str());
}

std::string HearthstoneApi::getCards(const std::string &t_card_parameters) {
    return makeApiRequest(getSetOfCardsUrl(t_card_parameters), m_header);
}