From c05901c38c6a77779807a6b224b9b624bfcaa5d3 Mon Sep 17 00:00:00 2001 From: Aotrix <9aotrix@protonmail.com> Date: Thu, 1 Jan 2026 03:35:41 +0100 Subject: removed useless files --- CMakeLists.txt | 32 ---- battleNetApi/CMakeLists.txt | 25 +++ battleNetApi/include/apiUrl.hpp | 19 +++ battleNetApi/include/hearthstoneApi.hpp | 43 +++++ battleNetApi/include/token.hpp | 25 +++ battleNetApi/resources/token_info | 1 + battleNetApi/src/apiUrl.cpp | 40 +++++ battleNetApi/src/hearthstoneApi.cpp | 40 +++++ battleNetApi/src/token.cpp | 105 ++++++++++++ battleNetApi/tests/tests.cpp | 64 ++++++++ include/cardTypeHandlerInfo.hpp | 21 --- include/hearthstoneAPI.hpp | 25 --- include/postgresHandler.hpp | 32 ---- resources/token_info.txt | 1 - src/cardTypeHandlerInfo.cpp | 32 ---- src/hearthstoneAPI.cpp | 121 -------------- src/main.cpp | 7 - src/postgresHandler.cpp | 182 --------------------- src/tests/tests.cpp | 16 -- submodules/battleNetApi/CMakeLists.txt | 25 --- submodules/battleNetApi/include/apiUrl.hpp | 19 --- submodules/battleNetApi/include/hearthstoneApi.hpp | 43 ----- submodules/battleNetApi/include/token.hpp | 25 --- submodules/battleNetApi/src/apiUrl.cpp | 40 ----- submodules/battleNetApi/src/hearthstoneApi.cpp | 40 ----- submodules/battleNetApi/src/token.cpp | 105 ------------ submodules/battleNetApi/tests/tests.cpp | 65 -------- 27 files changed, 362 insertions(+), 831 deletions(-) delete mode 100644 CMakeLists.txt create mode 100644 battleNetApi/CMakeLists.txt create mode 100644 battleNetApi/include/apiUrl.hpp create mode 100644 battleNetApi/include/hearthstoneApi.hpp create mode 100644 battleNetApi/include/token.hpp create mode 100644 battleNetApi/resources/token_info create mode 100644 battleNetApi/src/apiUrl.cpp create mode 100644 battleNetApi/src/hearthstoneApi.cpp create mode 100644 battleNetApi/src/token.cpp create mode 100644 battleNetApi/tests/tests.cpp delete mode 100644 include/cardTypeHandlerInfo.hpp delete mode 100644 include/hearthstoneAPI.hpp delete mode 100644 include/postgresHandler.hpp delete mode 100644 resources/token_info.txt delete mode 100644 src/cardTypeHandlerInfo.cpp delete mode 100644 src/hearthstoneAPI.cpp delete mode 100644 src/main.cpp delete mode 100644 src/postgresHandler.cpp delete mode 100644 src/tests/tests.cpp delete mode 100644 submodules/battleNetApi/CMakeLists.txt delete mode 100644 submodules/battleNetApi/include/apiUrl.hpp delete mode 100644 submodules/battleNetApi/include/hearthstoneApi.hpp delete mode 100644 submodules/battleNetApi/include/token.hpp delete mode 100644 submodules/battleNetApi/src/apiUrl.cpp delete mode 100644 submodules/battleNetApi/src/hearthstoneApi.cpp delete mode 100644 submodules/battleNetApi/src/token.cpp delete mode 100644 submodules/battleNetApi/tests/tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt deleted file mode 100644 index 63ba1b7..0000000 --- a/CMakeLists.txt +++ /dev/null @@ -1,32 +0,0 @@ -cmake_minimum_required(VERSION 3.15) - -get_filename_component(FNAME ${CMAKE_SOURCE_DIR} NAME) -set(ProjectName ${FNAME}) - -project(${ProjectName} LANGUAGES CXX) - -set(CMAKE_COMPILE_COMMANDS ON) -set(CMAKE_CXX_STANDARD 20) -set(CXX_STANDARD_REQUIRED ON) -set(CMAKE_BUILD_TYPE Debug) -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++20 -Wall") -set(CMAKE_EXPORT_COMPILE_COMMANDS ON) -add_definitions(-DSOURCE_DIR_PATH="${CMAKE_SOURCE_DIR}") - -set(INCLUDE_DIR ${PROJECT_SOURCE_DIR}/include) -set(SRC_COMMON - ${PROJECT_SOURCE_DIR}/src/cardTypeHandlerInfo.cpp - ${PROJECT_SOURCE_DIR}/src/hearthstoneAPI.cpp - ${PROJECT_SOURCE_DIR}/src/token.cpp - ${PROJECT_SOURCE_DIR}/src/postgresHandler.cpp) -set(SRC_FILES ${PROJECT_SOURCE_DIR}/src/main.cpp) -set(SRC_TESTS_FILES ${PROJECT_SOURCE_DIR}/src/tests/tests.cpp) - -add_executable(${FNAME} ${SRC_COMMON} ${SRC_FILES}) -target_include_directories(${FNAME} PRIVATE ${INCLUDE_DIR}) -target_link_libraries(${FNAME} pqxx pq curl) - -find_package(Catch2 3 REQUIRED) -add_executable(tests ${SRC_COMMON} ${SRC_TESTS_FILES}) -target_include_directories(tests PRIVATE ${INCLUDE_DIR}) -target_link_libraries(tests PRIVATE Catch2::Catch2WithMain pqxx pq curl) diff --git a/battleNetApi/CMakeLists.txt b/battleNetApi/CMakeLists.txt new file mode 100644 index 0000000..b4f6a48 --- /dev/null +++ b/battleNetApi/CMakeLists.txt @@ -0,0 +1,25 @@ +cmake_minimum_required(VERSION 3.15) + +get_filename_component(FNAME ${CMAKE_SOURCE_DIR} NAME) +set(ProjectName ${FNAME}) + +project(${ProjectName} LANGUAGES CXX) + +set(CMAKE_COMPILE_COMMANDS ON) +set(CMAKE_CXX_STANDARD 20) +set(CXX_STANDARD_REQUIRED ON) +set(CMAKE_BUILD_TYPE Debug) +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++20 -Wall") +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +add_definitions(-DSOURCE_DIR_PATH="${CMAKE_SOURCE_DIR}") + +set(INCLUDE_DIR ${PROJECT_SOURCE_DIR}/include) +set(SRC + ${PROJECT_SOURCE_DIR}/src/hearthstoneApi.cpp + ${PROJECT_SOURCE_DIR}/src/token.cpp ${PROJECT_SOURCE_DIR}/src/apiUrl.cpp + ${PROJECT_SOURCE_DIR}/tests/tests.cpp) + +find_package(Catch2 3 REQUIRED) +add_executable(tests ${SRC}) +target_include_directories(tests PRIVATE ${INCLUDE_DIR}) +target_link_libraries(tests PRIVATE Catch2::Catch2WithMain curl) diff --git a/battleNetApi/include/apiUrl.hpp b/battleNetApi/include/apiUrl.hpp new file mode 100644 index 0000000..509b248 --- /dev/null +++ b/battleNetApi/include/apiUrl.hpp @@ -0,0 +1,19 @@ +#pragma once +#include +#include + +class ApiUrl { + public: + ApiUrl(const std::string &iContentType, const std::string &iRegion); + + void setRegion(const std::string &iRegion); + void setLocale(const std::string &iLocale); + void setGameMode(const std::string &iGameMode); + void setPageSize(const std::string &iPageSize); + std::string operator()() const; + + private: + std::string mContentType; + std::string mRegion; + std::unordered_map aParameters; +}; diff --git a/battleNetApi/include/hearthstoneApi.hpp b/battleNetApi/include/hearthstoneApi.hpp new file mode 100644 index 0000000..c11acc7 --- /dev/null +++ b/battleNetApi/include/hearthstoneApi.hpp @@ -0,0 +1,43 @@ +#pragma once +#include "token.hpp" +#include +#include +#include + +class HearthstoneApi { + public: + HearthstoneApi(Token &&iToken); + std::uint64_t numberOfCards(const std::string &iApiResponse) const; + + private: + std::string authorizationHeader(); + std::string makeApiRequest(const std::string &iUrl) const; + static size_t curlCallbackStringOutput(void *iContent, size_t iSize, size_t iNmemb, std::string *iS); + + /** + * @brief + * @param[in] iJsonContent The std::string which contains Json (Battle.net API response for instance) + * @param[in] iKeyValueRegex The regex used to retrieve value from (key, value) pair + * An example: "\"cardCount\":(\\d+)" + */ + template T valueInJson(const std::string &iJsonContent, const std::string &iKeyValueRegex) const { + const std::regex iRegex{iKeyValueRegex}; + std::smatch aMatches; + if (std::regex_search(iJsonContent, aMatches, iRegex)) { + const std::string kValueString{aMatches[1].str()}; + T aValue; + const auto kConversionStatus = + std::from_chars(kValueString.data(), kValueString.data() + kValueString.size(), aValue); + if (kConversionStatus.ec == std::errc{}) { + return aValue; + } + } + std::cerr << std::format("Unable to find value with regex: '{}'\n", iKeyValueRegex); + return 0; + } + + Token mToken; + std::string mAuthorizationHeader; // +#include + +class Token { + public: + Token(const std::string &iTokenFilePath, const std::string &iUsername, const std::string &iPassword); + std::string toString() const; + + private: + const std::string mFilePath; //!< Path to the token file + const std::string mUsername; //!< Username for Battle.net API + const std::string mPassword; //!< Password for Battle.net API + const std::string mToken; //!< Token value + + std::string getValidToken() const; + void refreshToken() const; + void writeNewTokenToFile() const; + void writeTokenToFile(const std::string &iToken) const; + std::string getValidTokenWithApi() const; + std::chrono::seconds getCurrentTime() const; + std::string extractTokenWithRegex(const std::string &iText, const std::string &iRegex) const; + static size_t curlCallbackStringOutput(void *iPtr, size_t iSize, size_t iNmemb, std::string *iUserData); + + friend class TokenTests; +}; diff --git a/battleNetApi/resources/token_info b/battleNetApi/resources/token_info new file mode 100644 index 0000000..a3da9f6 --- /dev/null +++ b/battleNetApi/resources/token_info @@ -0,0 +1 @@ +EUmsmWh2JRYNfdfZQ2YkIzF0BEtRD3jBL3 1767267228 diff --git a/battleNetApi/src/apiUrl.cpp b/battleNetApi/src/apiUrl.cpp new file mode 100644 index 0000000..3de13cd --- /dev/null +++ b/battleNetApi/src/apiUrl.cpp @@ -0,0 +1,40 @@ +#include "apiUrl.hpp" +#include + +ApiUrl::ApiUrl(const std::string &iContentType, const std::string &iRegion) + : mContentType{iContentType}, mRegion{iRegion} {} +void ApiUrl::setRegion(const std::string &iRegion) { + if (not iRegion.empty()) { + mRegion = iRegion; //!< The region of the data to receive, e.g. "eu" + } +} +void ApiUrl::setLocale(const std::string &iLocale) { + if (not iLocale.empty()) { + aParameters["locale"] = iLocale; //!< The locale to reflect in localized data, e.g. "fr_FR" or "ko_KR" + //!< If you do not supply a value, all translations are returned. + } +} +void ApiUrl::setGameMode(const std::string &iGameMode) { + if (not iGameMode.empty()) { + aParameters["gameMode"] = + iGameMode; //!< A recognized game mode, e.g. "constructed" + //!< @see https://community.developer.battle.net/documentation/hearthstone/guides/game-modes + } +} +void ApiUrl::setPageSize(const std::string &iPageSize) { + if (not iPageSize.empty()) { + aParameters["pageSize"] = iPageSize; //!< The number of results to choose per page, e.g. "40" + } +} +std::string ApiUrl::operator()() const { + std::string aFormattedParameters; + for (const auto &[key, value] : aParameters) { + aFormattedParameters += std::format("&{}={}", key, value); + } + if (not aFormattedParameters.empty()) { + aFormattedParameters[0] = '?'; + } + aFormattedParameters = + std::format("https://{}.api.blizzard.com/hearthstone/{}/{}", mRegion, mContentType, aFormattedParameters); + return aFormattedParameters; +} diff --git a/battleNetApi/src/hearthstoneApi.cpp b/battleNetApi/src/hearthstoneApi.cpp new file mode 100644 index 0000000..c34e6ad --- /dev/null +++ b/battleNetApi/src/hearthstoneApi.cpp @@ -0,0 +1,40 @@ +#include "hearthstoneApi.hpp" +#include +#include + +HearthstoneApi::HearthstoneApi(Token &&iToken) : mToken(iToken), mAuthorizationHeader(authorizationHeader()) {} + +std::uint64_t HearthstoneApi::numberOfCards(const std::string &iApiResponse) const { + const std::string aCardCountRegex{"\"cardCount\":(\\d+)"}; + return valueInJson(iApiResponse, aCardCountRegex); +} +std::string HearthstoneApi::authorizationHeader() { return std::format("Authorization: Bearer {}", mToken.toString()); } + +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(iContent), kNewLength); + } catch (std::bad_alloc &e) { + // handle memory problem + return 0; + } + return kNewLength; +} + +std::string HearthstoneApi::makeApiRequest(const std::string &iUrl) const { + CURL *curl = curl_easy_init(); + std::string request_output; + 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, &request_output); + 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); + } + return request_output; +} diff --git a/battleNetApi/src/token.cpp b/battleNetApi/src/token.cpp new file mode 100644 index 0000000..89f0d2a --- /dev/null +++ b/battleNetApi/src/token.cpp @@ -0,0 +1,105 @@ +#include "token.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +Token::Token(const std::string &iTokenFilePath, const std::string &iUsername, const std::string &iPassword) + : mFilePath{iTokenFilePath}, mUsername{iUsername}, mPassword{iPassword}, mToken{getValidToken()} {} + +std::string Token::toString() const { return mToken; } + +std::string Token::getValidToken() const { + refreshToken(); + std::ifstream aTokenFile{mFilePath}; + std::string aLine; + std::getline(aTokenFile, aLine); + const std::string kToken{aLine.substr(0, aLine.find(" "))}; + return kToken; +} + +void Token::refreshToken() const { + std::ifstream aTokenFile{mFilePath}; + std::string aLine; + std::getline(aTokenFile, aLine); + if (aLine.empty()) { + writeNewTokenToFile(); + } else { + const std::string kTimeLimitText{aLine.substr(aLine.find(" ") + 1)}; + long int aTimeLimit; + const auto kConversionStatus{ + std::from_chars(kTimeLimitText.data(), kTimeLimitText.data() + kTimeLimitText.size(), aTimeLimit)}; + if (kConversionStatus.ec == std::errc{}) { + const bool kTokenExpired{ + std::chrono::duration_cast(std::chrono::utc_clock::now().time_since_epoch()) + .count() >= aTimeLimit}; + if (kTokenExpired) { + writeNewTokenToFile(); + } + } + } +} + +void Token::writeNewTokenToFile() const { + const std::string kToken{getValidTokenWithApi()}; + if (not kToken.empty()) { + writeTokenToFile(kToken); + } +} + +void Token::writeTokenToFile(const std::string &iToken) const { + std::ofstream aTokenFile{mFilePath}; + std::chrono::seconds aExpiresAt{getCurrentTime() + std::chrono::hours(24)}; + aTokenFile << iToken << " " << aExpiresAt.count() << '\n'; +} + +std::string Token::getValidTokenWithApi() const { + CURL *aCurl{curl_easy_init()}; + std::string aTokenInfo; + if (aCurl) { + curl_easy_setopt(aCurl, CURLOPT_URL, "https://oauth.battle.net/token"); + curl_easy_setopt(aCurl, CURLOPT_SSL_VERIFYPEER, 0L); + curl_easy_setopt(aCurl, CURLOPT_SSL_VERIFYHOST, 0L); + curl_easy_setopt(aCurl, CURLOPT_WRITEFUNCTION, curlCallbackStringOutput); + curl_easy_setopt(aCurl, CURLOPT_WRITEDATA, &aTokenInfo); + curl_easy_setopt(aCurl, CURLOPT_USERPWD, std::format("{}:{}", mUsername, mPassword).data()); + curl_easy_setopt(aCurl, CURLOPT_POSTFIELDS, "grant_type=client_credentials"); + CURLcode result_code{curl_easy_perform(aCurl)}; + curl_easy_cleanup(aCurl); + if (result_code != CURLE_OK) { + std::cerr << "ERROR: token request failed" << std::endl; + std::exit(EXIT_FAILURE); + } + } + + return extractTokenWithRegex(aTokenInfo, "\"access_token\":\"(\\w+)\""); +} + +std::chrono::seconds Token::getCurrentTime() const { + return std::chrono::duration_cast(std::chrono::utc_clock::now().time_since_epoch()); +} + +std::string Token::extractTokenWithRegex(const std::string &iText, const std::string &iRegex) const { + const std::regex kRegex{iRegex}; + std::smatch aMatches; + if (std::regex_search(iText, aMatches, kRegex)) { + return aMatches[1].str(); + } + std::cerr << std::format("Unable to retrieve token with regex '{}'", iRegex); + return ""; +} + +size_t Token::curlCallbackStringOutput(void *iPtr, size_t iSize, size_t iNmemb, std::string *iUserData) { + size_t newLength{iSize * iNmemb}; + try { + iUserData->append(static_cast(iPtr), newLength); + } catch (std::bad_alloc &e) { + // handle memory problem + return 0; + } + return newLength; +} diff --git a/battleNetApi/tests/tests.cpp b/battleNetApi/tests/tests.cpp new file mode 100644 index 0000000..2c3a2ff --- /dev/null +++ b/battleNetApi/tests/tests.cpp @@ -0,0 +1,64 @@ +#include "apiUrl.hpp" +#include "hearthstoneApi.hpp" +#include +#include + +class TokenMock { + public: + TokenMock() + : mTokenFilePath{"resources/token_info"}, mUsername{"2b50f1123b424d5e9c21971a110fdd04"}, + mPassword{"MrMkhVMNdOeqPL4Q4XVQAsRPR14J7Yq6"}, mToken{mTokenFilePath, mUsername, mPassword} {} + std::string toString() const { return mToken.toString(); } + Token &getToken() { return mToken; } + + private: + const std::string mTokenFilePath; + const std::string mUsername; + const std::string mPassword; + Token mToken; +}; + +class HearthstoneApiMock { + public: + HearthstoneApiMock() : mHearthstoneApi(std::move(mToken.getToken())) {}; + std::string makeApiRequest(const std::string &iUrl) { return mHearthstoneApi.makeApiRequest(iUrl); } + std::uint64_t numberOfCards(const std::string &iApiResponse) { + return mHearthstoneApi.numberOfCards(iApiResponse); + }; + + private: + TokenMock mToken; + const HearthstoneApi mHearthstoneApi; +}; + +TEST_CASE("Retrieve API Token", "[getApiToken]") { + TokenMock aToken; + const std::string kTokenContent{aToken.toString()}; + const std::string::size_type kTokenSize{kTokenContent.size()}; + REQUIRE(kTokenSize >= 30); + REQUIRE(kTokenSize <= 40); +} + +TEST_CASE("Retrieve number of cards", "[getCardsCount]") { + HearthstoneApiMock aHearthstoneApi; + const std::string kContentType{"cards"}; + const std::string kRegion{"eu"}; + ApiUrl aApiUrl(kContentType, kRegion); + aApiUrl.setLocale("fr_FR"); + aApiUrl.setGameMode("constructed"); + aApiUrl.setPageSize("1"); + std::uint64_t kNumberOfCards{aHearthstoneApi.numberOfCards(aHearthstoneApi.makeApiRequest(aApiUrl()))}; + REQUIRE(kNumberOfCards == 5992); +} + +TEST_CASE("Retrieve cards", "[retrieveCards]") { + HearthstoneApiMock aHearthstoneApi; + const std::string kContentType{"cards"}; + const std::string kRegion{"eu"}; + ApiUrl aApiUrl(kContentType, kRegion); + aApiUrl.setLocale("fr_FR"); + aApiUrl.setGameMode("constructed"); + aApiUrl.setPageSize("10"); + const std::string kApiResponse{aHearthstoneApi.makeApiRequest(aApiUrl())}; + REQUIRE(kApiResponse.size() > 6000); +} diff --git a/include/cardTypeHandlerInfo.hpp b/include/cardTypeHandlerInfo.hpp deleted file mode 100644 index 82eb469..0000000 --- a/include/cardTypeHandlerInfo.hpp +++ /dev/null @@ -1,21 +0,0 @@ -#include -#include - -class CardTypeHandlerInfo { - public: - CardTypeHandlerInfo() = default; - ~CardTypeHandlerInfo() = default; - CardTypeHandlerInfo(const CardTypeHandlerInfo &) = delete; - CardTypeHandlerInfo(CardTypeHandlerInfo &&) = default; - CardTypeHandlerInfo( - const std::vector &kCardTypeVector, const std::vector &kCardValueRegexVector, - const std::vector> kJSONToSQLConverterVector); - - void addCardInfo(const std::string &kCardType, const std::string &kCardValueRegex, - const std::function kJSONToSQLConverter); - - private: - std::vector mCardType; - std::vector mCardValueRegex; - std::vector> mJSONToSQLConverter; -}; diff --git a/include/hearthstoneAPI.hpp b/include/hearthstoneAPI.hpp deleted file mode 100644 index f677080..0000000 --- a/include/hearthstoneAPI.hpp +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once -#include -#include - -class HearthstoneAPI { - public: - HearthstoneAPI(); - std::string get_cards(const std::string &t_card_parameters); - - private: - static size_t curl_callback_string_output(void *t_contents, size_t t_size, size_t t_nmemb, std::string *t_s); - std::chrono::seconds get_current_time(); - std::string extract_string_with_regex(const std::string &t_str, const std::string t_regex); - void write_new_token_info_to_file(const std::string &t_file_path); - void refresh_token_if_needed(); - std::string get_valid_token(); - std::string generate_request_header(); - const std::string get_url(const std::string &t_parameters); - const std::string get_set_of_cards_url(const std::string &t_card_parameters); - std::string make_api_request(const char *t_url, const char *t_header); - std::string make_api_request(const std::string &t_url, const std::string &t_header); - - std::string m_access_token; - std::string m_header; -}; diff --git a/include/postgresHandler.hpp b/include/postgresHandler.hpp deleted file mode 100644 index 444a50f..0000000 --- a/include/postgresHandler.hpp +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once -#include "hearthstoneAPI.hpp" -#include -#include - -/** - * Execute a SQL query from a libpqxx transaction - * - * @param aTransaction The SQL transaction object used to execute the query - * @param aQuery The SQL query - * @return The result of the executed SQL query - */ -const pqxx::result executeQuery(pqxx::work &aTransaction, std::string_view aQuery); - -/** - * Get the type id of the value element in the "key": value regex match - * For instance, if the regex match is "isZilliaxCosmeticModule":false - * Then the type id is the one correponding to BOOL - * - * @param kSregexIt the regex match for a "key": value card information - * @return the type identifier of the value element - */ -const unsigned int getTypeIndexOfRegexIterator(const std::sregex_iterator &kSregexIt); -/** - * Add a list of cards (TODO: Complete documentation and function) - * - * @param kCards - * @param aTransaction - */ -void addCardsToDatabase(HearthstoneAPI &aAPIIntermediate, pqxx::work &aTransaction, const std::string &kURLOfCardsPage); - -void refresh_cards_table(); diff --git a/resources/token_info.txt b/resources/token_info.txt deleted file mode 100644 index 1bb3518..0000000 --- a/resources/token_info.txt +++ /dev/null @@ -1 +0,0 @@ -EUSfRDfuwbJnHlh1oQxDVHm0OJEr12uYbG 1761332682 diff --git a/src/cardTypeHandlerInfo.cpp b/src/cardTypeHandlerInfo.cpp deleted file mode 100644 index 46e8f56..0000000 --- a/src/cardTypeHandlerInfo.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "cardTypeHandlerInfo.hpp" - -void CardTypeHandlerInfo::addCardInfo(const std::string &kCardType, const std::string &kCardValueRegex, - const std::function kJSONToSQLConverter) { -} - -const CardTypeHandlerInfo cardTypeHandlerInfoList() { - CardTypeHandlerInfo aCardTypeHandlerInfo; - - aCardTypeHandlerInfo.addCardInfo("INT", "[0-9]+", [](const std::string &kJSONContent) { return kJSONContent; }); - - aCardTypeHandlerInfo.addCardInfo("BOOL", "true|false", - [](const std::string &kJSONContent) { return kJSONContent; }); - - aCardTypeHandlerInfo.addCardInfo("STRING", "\"[^\"?]*\"", [](const std::string &kJSONContent) { - std::string aCopyOfJSONValue = kJSONContent; - *aCopyOfJSONValue.begin() = '\''; - *std::prev(aCopyOfJSONValue.end()) = '\''; - return aCopyOfJSONValue; - }); - - aCardTypeHandlerInfo.addCardInfo("LIST_OF_INT", "\\[[0-9,]*\\]", [](const std::string &kJSONContent) { - std::string aCopyOfJSONValue = kJSONContent; - aCopyOfJSONValue.append("\'"); - aCopyOfJSONValue.insert(aCopyOfJSONValue.begin(), '\''); - return aCopyOfJSONValue; - }); - - aCardTypeHandlerInfo.addCardInfo("NULL", "null", [](const std::string &kJSONContent) { return "NULL"; }); - - return aCardTypeHandlerInfo; -} diff --git a/src/hearthstoneAPI.cpp b/src/hearthstoneAPI.cpp deleted file mode 100644 index cb72b11..0000000 --- a/src/hearthstoneAPI.cpp +++ /dev/null @@ -1,121 +0,0 @@ -#include "hearthstoneAPI.hpp" -#include -#include -#include -#include -#include -#include - -HearthstoneAPI::HearthstoneAPI() : m_access_token(get_valid_token()), m_header(generate_request_header()) {} - -size_t HearthstoneAPI::curl_callback_string_output(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((char *)t_contents, newLength); - } catch (std::bad_alloc &e) { - // handle memory problem - return 0; - } - return newLength; -} - -std::chrono::seconds HearthstoneAPI::get_current_time() { - return std::chrono::duration_cast(std::chrono::utc_clock::now().time_since_epoch()); -} - -std::string HearthstoneAPI::extract_string_with_regex(const std::string &t_str, const std::string t_regex) { - 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(); -} - -void HearthstoneAPI::write_new_token_info_to_file(const std::string &t_file_path) { - std::ofstream token_file(t_file_path); - 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, curl_callback_string_output); - 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); - } - } - std::string token = extract_string_with_regex(token_info, "\"access_token\":\"(\\w+)\""); - std::chrono::seconds expires_at = get_current_time() + std::chrono::hours(24); - token_file << token << " " << expires_at.count() << '\n'; -} - -void HearthstoneAPI::refresh_token_if_needed() { - 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()) { - write_new_token_info_to_file(file_path); - } else { - long expire_at = std::stoull(line.substr(line.find(" ") + 1)); - if (std::chrono::duration_cast(std::chrono::utc_clock::now().time_since_epoch()) - .count() >= expire_at) { - write_new_token_info_to_file(file_path); - } - } -} -std::string HearthstoneAPI::get_valid_token() { - refresh_token_if_needed(); - 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); - std::string token = line.substr(0, line.find(" ")); - return token; -} - -std::string HearthstoneAPI::generate_request_header() { - return std::format("Authorization: Bearer {}", m_access_token); -} - -const std::string HearthstoneAPI::get_url(const std::string &t_parameters) { - return std::format("https://eu.api.blizzard.com/hearthstone/{}", t_parameters); -} - -const std::string HearthstoneAPI::get_set_of_cards_url(const std::string &t_card_parameters) { - return get_url(std::format("cards{}", t_card_parameters)); -} - -std::string HearthstoneAPI::make_api_request(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, curl_callback_string_output); - 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::make_api_request(const std::string &t_url, const std::string &t_header) { - return make_api_request(t_url.c_str(), t_header.c_str()); -} - -std::string HearthstoneAPI::get_cards(const std::string &t_card_parameters) { - return make_api_request(get_set_of_cards_url(t_card_parameters), m_header); -} diff --git a/src/main.cpp b/src/main.cpp deleted file mode 100644 index 60b948a..0000000 --- a/src/main.cpp +++ /dev/null @@ -1,7 +0,0 @@ -#include "postgresHandler.hpp" -#include - -int main() { - refresh_cards_table(); - return 0; -} diff --git a/src/postgresHandler.cpp b/src/postgresHandler.cpp deleted file mode 100644 index 8ca3c20..0000000 --- a/src/postgresHandler.cpp +++ /dev/null @@ -1,182 +0,0 @@ -#include "postgresHandler.hpp" -#include "cardTypeHandlerInfo.hpp" -#include "hearthstoneAPI.hpp" -#include -#include -#include -#include -#include -#include -#include - -#define KEY_ID 1 - -const std::map aCardValueTypeToRegex = {{"INT", "[0-9]+"}, - {"STRING", "\"[^\"?]*\""}, - {"LIST_OF_INT", "\\[[0-9,]*\\]"}, - {"NULL", "null"}, - {"BOOL", "true|false"}}; - -const pqxx::result executeQuery(pqxx::work &aTransaction, std::string_view aQuery) { return aTransaction.exec(aQuery); } - -std::ostream &operator<<(std::ostream &aOstream, const pqxx::result &kResult) { - const int kNbColumnsInResult = kResult.columns(); - aOstream << "| "; - for (const auto &kResultRow : kResult) { - for (int i = 0; i < kNbColumnsInResult; i++) { - aOstream << kResultRow[i].c_str() << " | "; - } - } - return aOstream; -} - -const unsigned int getTypeIndexOfRegexIterator(const std::sregex_iterator &kSregexIt) { - // TODO: remove hardcoded variable because it is... weird. - // The input should already be the "value" part? - const unsigned int offset = 2; - for (size_t aCardInfoType = 0; aCardInfoType < aCardValueTypeToRegex.size(); aCardInfoType++) { - if ((*kSregexIt)[aCardInfoType] != "") { - return offset + aCardInfoType; - } - } - throw std::invalid_argument("regex iterator input is invalid"); -} - -const std::string format_json_value_to_sql(const std::string &kTypeOfValue, const std::string &kValueFromJSON) { - // TODO: show an error if a type is no longer here, - // to avoid having useless conditions - // FIXME: it does not scale well, a bit ugly... should be a single line - if (kTypeOfValue == "BOOL" || kTypeOfValue == "INT") { - return kValueFromJSON; - } else if (kTypeOfValue == "STRING") { - std::string aCopyOfJSONValue = kValueFromJSON; - *aCopyOfJSONValue.begin() = '\''; - *std::prev(aCopyOfJSONValue.end()) = '\''; - return aCopyOfJSONValue; - } else if (kTypeOfValue == "NULL") { - return "NULL"; - } else if (kTypeOfValue == "LIST_OF_INT") { - std::string aCopyOfJSONValue = kValueFromJSON; - aCopyOfJSONValue.append("\'"); - aCopyOfJSONValue.insert(aCopyOfJSONValue.begin(), '\''); - return aCopyOfJSONValue; - } else { - throw std::invalid_argument("ERROR: type of value is invalid"); - } -} - -std::string format_key(const std::string &key) { - std::string key_copy(key); - std::stack uppercase_indexes; - for (size_t i = 0; i < key.length(); i++) { - if (std::isupper(key[i])) { - uppercase_indexes.push(i); - } - } - while (!uppercase_indexes.empty()) { - size_t top_index = uppercase_indexes.top(); - uppercase_indexes.pop(); - key_copy[top_index] = std::tolower(key_copy[top_index]); - key_copy.insert(std::next(key_copy.begin(), top_index), '_'); - } - return key_copy; -} - -static void add_single_card_to_database(const std::string &kCards, pqxx::work &aTransaction, - const std::regex &kKeyRegex, const std::string::size_type &kIdPos, - const std::string::size_type &kClosingBracketPos) { - auto words_begin = std::sregex_iterator(std::next(kCards.begin(), kIdPos), - std::next(kCards.begin(), kClosingBracketPos), kKeyRegex); - auto words_end = std::sregex_iterator(); - if (words_begin != words_end) { - std::string insert_columns("INSERT INTO cards ("); - std::string values(" VALUES ("); - for (std::sregex_iterator kSregexIt = words_begin; kSregexIt != words_end; ++kSregexIt) { - insert_columns.append(format_key((*kSregexIt)[KEY_ID].str()) + ","); // key - const unsigned int kTypeIndexOfValue = getTypeIndexOfRegexIterator(kSregexIt); - const std::string kTypeNameOfValue = std::next(aCardValueTypeToRegex.begin(), kTypeIndexOfValue)->first; - values.append(format_json_value_to_sql(kTypeNameOfValue, (*kSregexIt)[kTypeIndexOfValue].str()) + ","); - } - *std::prev(insert_columns.end()) = ')'; - *std::prev(values.end()) = ')'; - - insert_columns.append(values); - insert_columns.append(" ON CONFLICT (id) DO NOTHING;"); - executeQuery(aTransaction, insert_columns); - } -} - -const std::regex regexKeyValueInJSON() { - std::string aRegexString = "\"([^\"?]+)\":("; - for (auto &[fieldName, regex] : aCardValueTypeToRegex) { - aRegexString += "(" + regex + ")|"; - } - aRegexString[aRegexString.length() - 1] = ')'; - return std::regex(aRegexString); -} - -const std::string::size_type startPosOfCardJSON(const std::string &kCardsPageJSON, - const std::string::size_type kSearchStartPos = 0) { - return kCardsPageJSON.find("{\"id", kSearchStartPos); -} - -const std::string::size_type endPosOfCardJSON(const std::string &kCardsPageJSON, - const std::string::size_type kSearchStartPos = 0) { - return kCardsPageJSON.find("}", kSearchStartPos); -} - -void addCardsToDatabase(HearthstoneAPI &aAPIIntermediate, pqxx::work &aTransaction, - const std::string &kURLOfCardsPage) { - const std::regex aRegexKeyValueInJSON = regexKeyValueInJSON(); - const std::string &kCardsPageJSON = aAPIIntermediate.get_cards(kURLOfCardsPage); - std::string::size_type aCardStartPos = startPosOfCardJSON(kCardsPageJSON); - std::string::size_type aCardEndPos = endPosOfCardJSON(kCardsPageJSON); - while (aCardStartPos != std::string::npos && aCardEndPos != std::string::npos) { - add_single_card_to_database(kCardsPageJSON, aTransaction, aRegexKeyValueInJSON, aCardStartPos, aCardEndPos); - aCardStartPos = startPosOfCardJSON(kCardsPageJSON, aCardStartPos + 1); - aCardEndPos = endPosOfCardJSON(kCardsPageJSON, aCardEndPos + 1); - } -} - -void clearCardDatabase(pqxx::work &aTransaction) { executeQuery(aTransaction, "DELETE FROM cards"); } - -const uint32_t numberOfPagesInSetOfCards(const std::string &cards) { - std::regex key_regex("\"pageCount\":([0-9]+)"); - auto nb_pages_begin = std::sregex_iterator(cards.begin(), cards.end(), key_regex); - auto nb_pages_end = std::sregex_iterator(); - if (nb_pages_begin != nb_pages_end) { - return std::stoi((*nb_pages_begin)[1].str()); - } - return 0; -} - -void refresh_cards_table() { - try { - pqxx::connection aConnection{ - "postgresql://aotrix@localhost:5432/hearthstonegameinfo"}; // FIXME: load a .xml file instead - pqxx::work aTransaction{aConnection}; - HearthstoneAPI aAPIConnector; - std::string aCards = - aAPIConnector.get_cards("/?locale=fr_FR&gameMode=constructed"); // FIXME: use a struct as a parameter - clearCardDatabase(aTransaction); - addCardsToDatabase(aAPIConnector, aTransaction, - "/?locale=fr_FR&gameMode=constructed"); // FIXME: To which - // table? to a more generic function - const uint32_t kNbPages = numberOfPagesInSetOfCards(aCards); - - // FIXME: [Process exited 139] - // for (int i = 2; i < kNbPages; i++) { - for (uint32_t i = 2; i < 3; i++) { - const std::string kCardsPageURL{std::format("/?locale=fr_FR&gameMode=constructed&page={}", i)}; - addCardsToDatabase(aAPIConnector, aTransaction, kCardsPageURL); - } - std::cout << "number of cards in database: " << executeQuery(aTransaction, "SELECT COUNT(*) FROM cards") - << std::endl; - aTransaction.commit(); - } catch (pqxx::sql_error const &kSqlError) { - std::cerr << "SQL error: " << kSqlError.what() << std::endl; - std::cerr << "Query was: " << kSqlError.query() << std::endl; - } catch (std::exception const &kException) { - std::cerr << "Error: " << kException.what() << std::endl; - } -} diff --git a/src/tests/tests.cpp b/src/tests/tests.cpp deleted file mode 100644 index d1a037b..0000000 --- a/src/tests/tests.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include -#include - -#include - -uint64_t fibonacci(uint64_t number) { return number < 2 ? number : fibonacci(number - 1) + fibonacci(number - 2); } - -TEST_CASE("Benchmark Fibonacci", "[fibonacci]") { - REQUIRE(fibonacci(5) == 5); - - REQUIRE(fibonacci(20) == 6'765); - BENCHMARK("fibonacci 20") { return fibonacci(20); }; - - REQUIRE(fibonacci(25) == 75'025); - BENCHMARK("fibonacci 25") { return fibonacci(25); }; -} diff --git a/submodules/battleNetApi/CMakeLists.txt b/submodules/battleNetApi/CMakeLists.txt deleted file mode 100644 index b4f6a48..0000000 --- a/submodules/battleNetApi/CMakeLists.txt +++ /dev/null @@ -1,25 +0,0 @@ -cmake_minimum_required(VERSION 3.15) - -get_filename_component(FNAME ${CMAKE_SOURCE_DIR} NAME) -set(ProjectName ${FNAME}) - -project(${ProjectName} LANGUAGES CXX) - -set(CMAKE_COMPILE_COMMANDS ON) -set(CMAKE_CXX_STANDARD 20) -set(CXX_STANDARD_REQUIRED ON) -set(CMAKE_BUILD_TYPE Debug) -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++20 -Wall") -set(CMAKE_EXPORT_COMPILE_COMMANDS ON) -add_definitions(-DSOURCE_DIR_PATH="${CMAKE_SOURCE_DIR}") - -set(INCLUDE_DIR ${PROJECT_SOURCE_DIR}/include) -set(SRC - ${PROJECT_SOURCE_DIR}/src/hearthstoneApi.cpp - ${PROJECT_SOURCE_DIR}/src/token.cpp ${PROJECT_SOURCE_DIR}/src/apiUrl.cpp - ${PROJECT_SOURCE_DIR}/tests/tests.cpp) - -find_package(Catch2 3 REQUIRED) -add_executable(tests ${SRC}) -target_include_directories(tests PRIVATE ${INCLUDE_DIR}) -target_link_libraries(tests PRIVATE Catch2::Catch2WithMain curl) diff --git a/submodules/battleNetApi/include/apiUrl.hpp b/submodules/battleNetApi/include/apiUrl.hpp deleted file mode 100644 index 509b248..0000000 --- a/submodules/battleNetApi/include/apiUrl.hpp +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once -#include -#include - -class ApiUrl { - public: - ApiUrl(const std::string &iContentType, const std::string &iRegion); - - void setRegion(const std::string &iRegion); - void setLocale(const std::string &iLocale); - void setGameMode(const std::string &iGameMode); - void setPageSize(const std::string &iPageSize); - std::string operator()() const; - - private: - std::string mContentType; - std::string mRegion; - std::unordered_map aParameters; -}; diff --git a/submodules/battleNetApi/include/hearthstoneApi.hpp b/submodules/battleNetApi/include/hearthstoneApi.hpp deleted file mode 100644 index c11acc7..0000000 --- a/submodules/battleNetApi/include/hearthstoneApi.hpp +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once -#include "token.hpp" -#include -#include -#include - -class HearthstoneApi { - public: - HearthstoneApi(Token &&iToken); - std::uint64_t numberOfCards(const std::string &iApiResponse) const; - - private: - std::string authorizationHeader(); - std::string makeApiRequest(const std::string &iUrl) const; - static size_t curlCallbackStringOutput(void *iContent, size_t iSize, size_t iNmemb, std::string *iS); - - /** - * @brief - * @param[in] iJsonContent The std::string which contains Json (Battle.net API response for instance) - * @param[in] iKeyValueRegex The regex used to retrieve value from (key, value) pair - * An example: "\"cardCount\":(\\d+)" - */ - template T valueInJson(const std::string &iJsonContent, const std::string &iKeyValueRegex) const { - const std::regex iRegex{iKeyValueRegex}; - std::smatch aMatches; - if (std::regex_search(iJsonContent, aMatches, iRegex)) { - const std::string kValueString{aMatches[1].str()}; - T aValue; - const auto kConversionStatus = - std::from_chars(kValueString.data(), kValueString.data() + kValueString.size(), aValue); - if (kConversionStatus.ec == std::errc{}) { - return aValue; - } - } - std::cerr << std::format("Unable to find value with regex: '{}'\n", iKeyValueRegex); - return 0; - } - - Token mToken; - std::string mAuthorizationHeader; // -#include - -class Token { - public: - Token(const std::string &iTokenFilePath, const std::string &iUsername, const std::string &iPassword); - std::string toString() const; - - private: - const std::string mFilePath; //!< Path to the token file - const std::string mUsername; //!< Username for Battle.net API - const std::string mPassword; //!< Password for Battle.net API - const std::string mToken; //!< Token value - - std::string getValidToken() const; - void refreshToken() const; - void writeNewTokenToFile() const; - void writeTokenToFile(const std::string &iToken) const; - std::string getValidTokenWithApi() const; - std::chrono::seconds getCurrentTime() const; - std::string extractTokenWithRegex(const std::string &iText, const std::string &iRegex) const; - static size_t curlCallbackStringOutput(void *iPtr, size_t iSize, size_t iNmemb, std::string *iUserData); - - friend class TokenTests; -}; diff --git a/submodules/battleNetApi/src/apiUrl.cpp b/submodules/battleNetApi/src/apiUrl.cpp deleted file mode 100644 index 3de13cd..0000000 --- a/submodules/battleNetApi/src/apiUrl.cpp +++ /dev/null @@ -1,40 +0,0 @@ -#include "apiUrl.hpp" -#include - -ApiUrl::ApiUrl(const std::string &iContentType, const std::string &iRegion) - : mContentType{iContentType}, mRegion{iRegion} {} -void ApiUrl::setRegion(const std::string &iRegion) { - if (not iRegion.empty()) { - mRegion = iRegion; //!< The region of the data to receive, e.g. "eu" - } -} -void ApiUrl::setLocale(const std::string &iLocale) { - if (not iLocale.empty()) { - aParameters["locale"] = iLocale; //!< The locale to reflect in localized data, e.g. "fr_FR" or "ko_KR" - //!< If you do not supply a value, all translations are returned. - } -} -void ApiUrl::setGameMode(const std::string &iGameMode) { - if (not iGameMode.empty()) { - aParameters["gameMode"] = - iGameMode; //!< A recognized game mode, e.g. "constructed" - //!< @see https://community.developer.battle.net/documentation/hearthstone/guides/game-modes - } -} -void ApiUrl::setPageSize(const std::string &iPageSize) { - if (not iPageSize.empty()) { - aParameters["pageSize"] = iPageSize; //!< The number of results to choose per page, e.g. "40" - } -} -std::string ApiUrl::operator()() const { - std::string aFormattedParameters; - for (const auto &[key, value] : aParameters) { - aFormattedParameters += std::format("&{}={}", key, value); - } - if (not aFormattedParameters.empty()) { - aFormattedParameters[0] = '?'; - } - aFormattedParameters = - std::format("https://{}.api.blizzard.com/hearthstone/{}/{}", mRegion, mContentType, aFormattedParameters); - return aFormattedParameters; -} diff --git a/submodules/battleNetApi/src/hearthstoneApi.cpp b/submodules/battleNetApi/src/hearthstoneApi.cpp deleted file mode 100644 index c34e6ad..0000000 --- a/submodules/battleNetApi/src/hearthstoneApi.cpp +++ /dev/null @@ -1,40 +0,0 @@ -#include "hearthstoneApi.hpp" -#include -#include - -HearthstoneApi::HearthstoneApi(Token &&iToken) : mToken(iToken), mAuthorizationHeader(authorizationHeader()) {} - -std::uint64_t HearthstoneApi::numberOfCards(const std::string &iApiResponse) const { - const std::string aCardCountRegex{"\"cardCount\":(\\d+)"}; - return valueInJson(iApiResponse, aCardCountRegex); -} -std::string HearthstoneApi::authorizationHeader() { return std::format("Authorization: Bearer {}", mToken.toString()); } - -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(iContent), kNewLength); - } catch (std::bad_alloc &e) { - // handle memory problem - return 0; - } - return kNewLength; -} - -std::string HearthstoneApi::makeApiRequest(const std::string &iUrl) const { - CURL *curl = curl_easy_init(); - std::string request_output; - 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, &request_output); - 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); - } - return request_output; -} diff --git a/submodules/battleNetApi/src/token.cpp b/submodules/battleNetApi/src/token.cpp deleted file mode 100644 index 89f0d2a..0000000 --- a/submodules/battleNetApi/src/token.cpp +++ /dev/null @@ -1,105 +0,0 @@ -#include "token.hpp" -#include -#include -#include -#include -#include -#include -#include -#include - -Token::Token(const std::string &iTokenFilePath, const std::string &iUsername, const std::string &iPassword) - : mFilePath{iTokenFilePath}, mUsername{iUsername}, mPassword{iPassword}, mToken{getValidToken()} {} - -std::string Token::toString() const { return mToken; } - -std::string Token::getValidToken() const { - refreshToken(); - std::ifstream aTokenFile{mFilePath}; - std::string aLine; - std::getline(aTokenFile, aLine); - const std::string kToken{aLine.substr(0, aLine.find(" "))}; - return kToken; -} - -void Token::refreshToken() const { - std::ifstream aTokenFile{mFilePath}; - std::string aLine; - std::getline(aTokenFile, aLine); - if (aLine.empty()) { - writeNewTokenToFile(); - } else { - const std::string kTimeLimitText{aLine.substr(aLine.find(" ") + 1)}; - long int aTimeLimit; - const auto kConversionStatus{ - std::from_chars(kTimeLimitText.data(), kTimeLimitText.data() + kTimeLimitText.size(), aTimeLimit)}; - if (kConversionStatus.ec == std::errc{}) { - const bool kTokenExpired{ - std::chrono::duration_cast(std::chrono::utc_clock::now().time_since_epoch()) - .count() >= aTimeLimit}; - if (kTokenExpired) { - writeNewTokenToFile(); - } - } - } -} - -void Token::writeNewTokenToFile() const { - const std::string kToken{getValidTokenWithApi()}; - if (not kToken.empty()) { - writeTokenToFile(kToken); - } -} - -void Token::writeTokenToFile(const std::string &iToken) const { - std::ofstream aTokenFile{mFilePath}; - std::chrono::seconds aExpiresAt{getCurrentTime() + std::chrono::hours(24)}; - aTokenFile << iToken << " " << aExpiresAt.count() << '\n'; -} - -std::string Token::getValidTokenWithApi() const { - CURL *aCurl{curl_easy_init()}; - std::string aTokenInfo; - if (aCurl) { - curl_easy_setopt(aCurl, CURLOPT_URL, "https://oauth.battle.net/token"); - curl_easy_setopt(aCurl, CURLOPT_SSL_VERIFYPEER, 0L); - curl_easy_setopt(aCurl, CURLOPT_SSL_VERIFYHOST, 0L); - curl_easy_setopt(aCurl, CURLOPT_WRITEFUNCTION, curlCallbackStringOutput); - curl_easy_setopt(aCurl, CURLOPT_WRITEDATA, &aTokenInfo); - curl_easy_setopt(aCurl, CURLOPT_USERPWD, std::format("{}:{}", mUsername, mPassword).data()); - curl_easy_setopt(aCurl, CURLOPT_POSTFIELDS, "grant_type=client_credentials"); - CURLcode result_code{curl_easy_perform(aCurl)}; - curl_easy_cleanup(aCurl); - if (result_code != CURLE_OK) { - std::cerr << "ERROR: token request failed" << std::endl; - std::exit(EXIT_FAILURE); - } - } - - return extractTokenWithRegex(aTokenInfo, "\"access_token\":\"(\\w+)\""); -} - -std::chrono::seconds Token::getCurrentTime() const { - return std::chrono::duration_cast(std::chrono::utc_clock::now().time_since_epoch()); -} - -std::string Token::extractTokenWithRegex(const std::string &iText, const std::string &iRegex) const { - const std::regex kRegex{iRegex}; - std::smatch aMatches; - if (std::regex_search(iText, aMatches, kRegex)) { - return aMatches[1].str(); - } - std::cerr << std::format("Unable to retrieve token with regex '{}'", iRegex); - return ""; -} - -size_t Token::curlCallbackStringOutput(void *iPtr, size_t iSize, size_t iNmemb, std::string *iUserData) { - size_t newLength{iSize * iNmemb}; - try { - iUserData->append(static_cast(iPtr), newLength); - } catch (std::bad_alloc &e) { - // handle memory problem - return 0; - } - return newLength; -} diff --git a/submodules/battleNetApi/tests/tests.cpp b/submodules/battleNetApi/tests/tests.cpp deleted file mode 100644 index 74845c5..0000000 --- a/submodules/battleNetApi/tests/tests.cpp +++ /dev/null @@ -1,65 +0,0 @@ -#include "apiUrl.hpp" -#include "hearthstoneApi.hpp" -#include -#include -#include - -class TokenMock { - public: - TokenMock() - : mTokenFilePath{"resources/token_info"}, mUsername{"2b50f1123b424d5e9c21971a110fdd04"}, - mPassword{"MrMkhVMNdOeqPL4Q4XVQAsRPR14J7Yq6"}, mToken{mTokenFilePath, mUsername, mPassword} {} - std::string toString() const { return mToken.toString(); } - Token &getToken() { return mToken; } - - private: - const std::string mTokenFilePath; - const std::string mUsername; - const std::string mPassword; - Token mToken; -}; - -class HearthstoneApiMock { - public: - HearthstoneApiMock() : mHearthstoneApi(std::move(mToken.getToken())) {}; - std::string makeApiRequest(const std::string &iUrl) { return mHearthstoneApi.makeApiRequest(iUrl); } - std::uint64_t numberOfCards(const std::string &iApiResponse) { - return mHearthstoneApi.numberOfCards(iApiResponse); - }; - - private: - TokenMock mToken; - const HearthstoneApi mHearthstoneApi; -}; - -TEST_CASE("Retrieve API Token", "[getApiToken]") { - TokenMock aToken; - const std::string kTokenContent{aToken.toString()}; - const std::string::size_type kTokenSize{kTokenContent.size()}; - REQUIRE(kTokenSize >= 30); - REQUIRE(kTokenSize <= 40); -} - -TEST_CASE("Retrieve number of cards", "[getCardsCount]") { - HearthstoneApiMock aHearthstoneApi; - const std::string kContentType{"cards"}; - const std::string kRegion{"eu"}; - ApiUrl aApiUrl(kContentType, kRegion); - aApiUrl.setLocale("fr_FR"); - aApiUrl.setGameMode("constructed"); - aApiUrl.setPageSize("1"); - std::uint64_t kNumberOfCards{aHearthstoneApi.numberOfCards(aHearthstoneApi.makeApiRequest(aApiUrl()))}; - REQUIRE(kNumberOfCards == 5991); -} - -TEST_CASE("Retrieve cards", "[retrieveCards]") { - HearthstoneApiMock aHearthstoneApi; - const std::string kContentType{"cards"}; - const std::string kRegion{"eu"}; - ApiUrl aApiUrl(kContentType, kRegion); - aApiUrl.setLocale("fr_FR"); - aApiUrl.setGameMode("constructed"); - aApiUrl.setPageSize("10"); - const std::string kApiResponse{aHearthstoneApi.makeApiRequest(aApiUrl())}; - REQUIRE(kApiResponse.size() > 300); -} -- cgit v1.2.3