diff options
Diffstat (limited to 'battleNetApi/src')
| -rw-r--r-- | battleNetApi/src/apiUrl.cpp | 18 | ||||
| -rw-r--r-- | battleNetApi/src/hearthstoneApi.cpp | 42 | ||||
| -rw-r--r-- | battleNetApi/src/main.cpp | 16 | ||||
| -rw-r--r-- | battleNetApi/src/token.cpp | 48 | ||||
| -rw-r--r-- | battleNetApi/src/tokenBuilder.cpp | 14 | ||||
| -rw-r--r-- | battleNetApi/src/tokenPool.cpp | 4 |
6 files changed, 101 insertions, 41 deletions
diff --git a/battleNetApi/src/apiUrl.cpp b/battleNetApi/src/apiUrl.cpp index 1f11add..fa07372 100644 --- a/battleNetApi/src/apiUrl.cpp +++ b/battleNetApi/src/apiUrl.cpp @@ -19,7 +19,8 @@ void ApiUrl::setLocale(const std::string &iLocale) { void ApiUrl::setGameMode(const std::string &iGameMode) { if (not iGameMode.empty()) { //!< A recognized game mode, e.g. "constructed" - //!< @see https://community.developer.battle.net/documentation/hearthstone/guides/game-modes + //!< @see + //!< https://community.developer.battle.net/documentation/hearthstone/guides/game-modes setValue(kGAME_MODE_KEY, iGameMode); } } @@ -36,13 +37,19 @@ void ApiUrl::setPageSize(const std::string &iPageSize) { setValue(kPAGE_SIZE_KEY, iPageSize); } } -void ApiUrl::setPageSize(uint64_t iPageSize) { return setPageSize(std::to_string(iPageSize)); } +void ApiUrl::setPageSize(uint64_t iPageSize) { + return setPageSize(std::to_string(iPageSize)); +} bool ApiUrl::hasLocale() const { return hasValue(kLOCALE_KEY); } bool ApiUrl::hasGameMode() const { return hasValue(kGAME_MODE_KEY); } bool ApiUrl::hasPage() const { return hasValue(kPAGE_KEY); } bool ApiUrl::hasPageSize() const { return hasValue(kPAGE_SIZE_KEY); } -void ApiUrl::setValue(const std::string &iKey, const std::string &iValue) { aParameters[iKey] = iValue; } -bool ApiUrl::hasValue(const std::string &iKey) const { return aParameters.count(iKey) > 0; } +void ApiUrl::setValue(const std::string &iKey, const std::string &iValue) { + aParameters[iKey] = iValue; +} +bool ApiUrl::hasValue(const std::string &iKey) const { + return aParameters.count(iKey) > 0; +} std::string ApiUrl::text() const { std::string aFormattedParameters; for (const auto &[key, value] : aParameters) { @@ -52,6 +59,7 @@ std::string ApiUrl::text() const { aFormattedParameters[0] = '?'; } aFormattedParameters = - std::format("https://{}.api.blizzard.com/hearthstone/{}/{}", mRegion, mContentType, 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 index 133f38d..1341f74 100644 --- a/battleNetApi/src/hearthstoneApi.cpp +++ b/battleNetApi/src/hearthstoneApi.cpp @@ -10,7 +10,9 @@ std::string HearthstoneApi::authorizationHeader(const std::string &iTokenText) { return std::format("Authorization: Bearer {}", iTokenText); } -size_t HearthstoneApi::curlCallbackStringOutput(void *iContent, size_t iSize, size_t iNmemb, std::string *iS) { +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); @@ -21,7 +23,8 @@ size_t HearthstoneApi::curlCallbackStringOutput(void *iContent, size_t iSize, si return kNewLength; } -json HearthstoneApi::makeApiRequest(const ApiUrl &iApiUrl, const std::string &iTokenText) { +json HearthstoneApi::makeApiRequest(const ApiUrl &iApiUrl, + const std::string &iTokenText) { CURL *curl = curl_easy_init(); std::string aRequestOutput; if (curl) { @@ -31,7 +34,8 @@ json HearthstoneApi::makeApiRequest(const ApiUrl &iApiUrl, const std::string &iT curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlCallbackStringOutput); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &aRequestOutput); struct curl_slist *chunk = nullptr; - chunk = curl_slist_append(chunk, authorizationHeader(iTokenText).c_str()); + chunk = + curl_slist_append(chunk, authorizationHeader(iTokenText).c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk); curl_easy_perform(curl); curl_easy_cleanup(curl); @@ -40,25 +44,34 @@ json HearthstoneApi::makeApiRequest(const ApiUrl &iApiUrl, const std::string &iT return aOutputJson; } -std::vector<json> HearthstoneApi::makeApiRequest(const std::vector<ApiUrl> &iApiUrls, const std::string &iTokenText) { +std::vector<json> +HearthstoneApi::makeApiRequest(const std::vector<ApiUrl> &iApiUrls, + const std::string &iTokenText) { std::vector<std::string> aApiUrls(iApiUrls.size()); - std::ranges::transform(iApiUrls, aApiUrls.begin(), [](const ApiUrl &iApiUrl) { return iApiUrl.text(); }); + std::ranges::transform( + iApiUrls, aApiUrls.begin(), + [](const ApiUrl &iApiUrl) { return iApiUrl.text(); }); return makeApiRequest(aApiUrls, iTokenText); } -std::vector<json> HearthstoneApi::makeApiRequest(const std::vector<std::string> &iUrls, const std::string &iTokenText) { +std::vector<json> +HearthstoneApi::makeApiRequest(const std::vector<std::string> &iUrls, + const std::string &iTokenText) { std::vector<std::string> aResponses(iUrls.size()); CURLM *curlm = curl_multi_init(); if (curlm) { - for (std::vector<std::string>::size_type i{0}; i < aResponses.size(); ++i) { + for (std::vector<std::string>::size_type i{0}; i < aResponses.size(); + ++i) { CURL *curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, iUrls[i].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_WRITEFUNCTION, + curlCallbackStringOutput); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &(aResponses[i])); struct curl_slist *chunk = nullptr; - chunk = curl_slist_append(chunk, authorizationHeader(iTokenText).c_str()); + chunk = curl_slist_append(chunk, + authorizationHeader(iTokenText).c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk); curl_multi_add_handle(curlm, curl); } @@ -69,7 +82,8 @@ std::vector<json> HearthstoneApi::makeApiRequest(const std::vector<std::string> int numfds = 0; int res = curl_multi_wait(curlm, NULL, 0, kMaxWaitMs, &numfds); if (res != CURLM_OK) { - std::cerr << std::format("error: curl_multi_wait() returned {}\n", res); + std::cerr << std::format( + "error: curl_multi_wait() returned {}\n", res); } curl_multi_perform(curlm, &aStillRunning); } while (aStillRunning); @@ -84,15 +98,17 @@ std::vector<json> HearthstoneApi::makeApiRequest(const std::vector<std::string> aHandle = aMessage->easy_handle; aReturnCode = aMessage->data.result; if (aReturnCode != CURLE_OK) { - fprintf(stderr, "CURL error code: %d\n", aMessage->data.result); + fprintf(stderr, "CURL error code: %d\n", + aMessage->data.result); continue; } curl_multi_remove_handle(curlm, aHandle); curl_easy_cleanup(aHandle); aHandle = nullptr; } else { - std::cerr << std::format("error: after curl_multi_info_read(), CURLMsg={}\n", - static_cast<int>(aMessage->msg)); + std::cerr << std::format( + "error: after curl_multi_info_read(), CURLMsg={}\n", + static_cast<int>(aMessage->msg)); } } curl_multi_cleanup(curlm); diff --git a/battleNetApi/src/main.cpp b/battleNetApi/src/main.cpp index 2b6596a..ccab84c 100644 --- a/battleNetApi/src/main.cpp +++ b/battleNetApi/src/main.cpp @@ -23,7 +23,7 @@ class DefaultDownloadMethod : public DownloadMethod { aApiUrl.setPageSize("100"); std::optional<Token> aToken{TokenPool::availableToken()}; if (aToken.has_value()) { - HearthstoneApi::downloadCards(aApiUrl, aToken.value()); + return HearthstoneApi::downloadCards(aApiUrl, aToken.value()); } return json({}); }; @@ -32,8 +32,11 @@ class DefaultDownloadMethod : public DownloadMethod { class DownloaderContext { public: DownloaderContext() = default; - DownloaderContext(std::unique_ptr<DownloadMethod> iDownloader) : mDownloader(std::move(iDownloader)) {}; - void setDownloadMethod(std::unique_ptr<DownloadMethod> iDownloader) { mDownloader = std::move(iDownloader); } + DownloaderContext(std::unique_ptr<DownloadMethod> iDownloader) + : mDownloader(std::move(iDownloader)) {}; + void setDownloadMethod(std::unique_ptr<DownloadMethod> iDownloader) { + mDownloader = std::move(iDownloader); + } json download() { if (mDownloader) { return mDownloader->download(); @@ -50,13 +53,16 @@ class DownloaderContext { int main(int argc, char *argv[]) { DownloaderContext aDownloaderContext; std::string aOutputJsonPath; - if (argc < 4) { + if (argc < 3) { TokenPool::feedTokenSource("tests/resources/credentials.json"); - aDownloaderContext.setDownloadMethod(std::make_unique<DefaultDownloadMethod>()); + aDownloaderContext.setDownloadMethod( + std::make_unique<DefaultDownloadMethod>()); aOutputJsonPath = "tests/output/list_of_cards.json"; } else { std::string aCredentialsFilePath{argv[1]}; TokenPool::feedTokenSource(aCredentialsFilePath); + aDownloaderContext.setDownloadMethod( + std::make_unique<DefaultDownloadMethod>()); aOutputJsonPath = argv[2]; } std::ofstream aOutputJsonFile(aOutputJsonPath); diff --git a/battleNetApi/src/token.cpp b/battleNetApi/src/token.cpp index 21717cb..1f952ff 100644 --- a/battleNetApi/src/token.cpp +++ b/battleNetApi/src/token.cpp @@ -10,23 +10,28 @@ using json = nlohmann::json; -Token::Token(const std::string &iTokenFilePath) : mFilePath{iTokenFilePath}, mToken{generateToken()} {} +Token::Token(const std::string &iTokenFilePath) + : mFilePath{iTokenFilePath}, mToken{generateToken()} {} std::string Token::text() const { return mToken; } const bool Token::hasExpired() const { std::ifstream aTokenFile{mFilePath}; json aCredentialsFile = json::parse(aTokenFile); - if (not aCredentialsFile.contains("Token") or not aCredentialsFile["Token"].contains("ExpirationTime") or + if (not aCredentialsFile.contains("Token") or + not aCredentialsFile["Token"].contains("ExpirationTime") or not aCredentialsFile["Token"].contains("Content")) { return true; } - if (aCredentialsFile["Token"]["Content"].dump().length() < kTokenContentMinLength) { + if (aCredentialsFile["Token"]["Content"].dump().length() < + kTokenContentMinLength) { return true; } - const std::uint64_t kExpirationTime{aCredentialsFile["Token"]["ExpirationTime"]}; + const std::uint64_t kExpirationTime{ + aCredentialsFile["Token"]["ExpirationTime"]}; const std::uint64_t kCurrentTime{static_cast<std::uint64_t>( - std::chrono::duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now().time_since_epoch()) + std::chrono::duration_cast<std::chrono::seconds>( + std::chrono::high_resolution_clock::now().time_since_epoch()) .count())}; if (kCurrentTime >= kExpirationTime) { return true; @@ -34,8 +39,6 @@ const bool Token::hasExpired() const { return false; } -void Token::updateToken() { mToken = generateToken(); } - std::string Token::getTokenFromLocalFile() const { std::ifstream aTokenFile{mFilePath}; return json::parse(aTokenFile)["Token"]["Content"]; @@ -43,18 +46,21 @@ std::string Token::getTokenFromLocalFile() const { std::string Token::generateToken() { if (hasExpired()) { - const std::pair<std::string, std::uint64_t> kTokenContent{getTokenWithApi()}; + const std::pair<std::string, std::uint64_t> kTokenContent{ + getTokenWithApi()}; writeTokenToLocalFile(kTokenContent); } return getTokenFromLocalFile(); } -void Token::writeTokenToLocalFile(const std::pair<std::string, std::uint64_t> &iToken) const { +void Token::writeTokenToLocalFile( + const std::pair<std::string, std::uint64_t> &iToken) const { std::ifstream aTokenFileInput{mFilePath}; json aCredentialsFile = json::parse(aTokenFileInput); aCredentialsFile["Token"]["Content"] = iToken.first; aCredentialsFile["Token"]["ExpirationTime"] = - std::chrono::duration_cast<std::chrono::seconds>(getCurrentTime() + std::chrono::seconds(iToken.second)) + std::chrono::duration_cast<std::chrono::seconds>( + getCurrentTime() + std::chrono::seconds(iToken.second)) .count(); std::ofstream aTokenFileOutput{mFilePath}; @@ -64,9 +70,11 @@ void Token::writeTokenToLocalFile(const std::pair<std::string, std::uint64_t> &i std::pair<std::string, std::uint64_t> Token::getTokenWithApi() const { std::ifstream aCredentialsFile{mFilePath}; json aCredentials = json::parse(aCredentialsFile); - if (not aCredentials.contains("Agent") or not aCredentials["Agent"].contains("Username") or + if (not aCredentials.contains("Agent") or + not aCredentials["Agent"].contains("Username") or not aCredentials["Agent"].contains("Password")) { - std::cerr << "Please define Agent/Username and Agent/Password in the JSON credentials file\n"; + std::cerr << "Please define Agent/Username and Agent/Password in the " + "JSON credentials file\n"; std::exit(EXIT_FAILURE); } const std::string kAgentUsername{aCredentials["Agent"]["Username"]}; @@ -77,10 +85,14 @@ std::pair<std::string, std::uint64_t> Token::getTokenWithApi() const { 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_WRITEFUNCTION, + curlCallbackStringOutput); curl_easy_setopt(aCurl, CURLOPT_WRITEDATA, &aTokenInfo); - curl_easy_setopt(aCurl, CURLOPT_USERPWD, std::format("{}:{}", kAgentUsername, kAgentPassword).data()); - curl_easy_setopt(aCurl, CURLOPT_POSTFIELDS, "grant_type=client_credentials"); + curl_easy_setopt( + aCurl, CURLOPT_USERPWD, + std::format("{}:{}", kAgentUsername, kAgentPassword).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) { @@ -93,10 +105,12 @@ std::pair<std::string, std::uint64_t> Token::getTokenWithApi() const { } std::chrono::seconds Token::getCurrentTime() const { - return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::utc_clock::now().time_since_epoch()); + return std::chrono::duration_cast<std::chrono::seconds>( + std::chrono::utc_clock::now().time_since_epoch()); } -size_t Token::curlCallbackStringOutput(void *iPtr, size_t iSize, size_t iNmemb, std::string *iUserData) { +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<char *>(iPtr), newLength); diff --git a/battleNetApi/src/tokenBuilder.cpp b/battleNetApi/src/tokenBuilder.cpp new file mode 100644 index 0000000..733f5c1 --- /dev/null +++ b/battleNetApi/src/tokenBuilder.cpp @@ -0,0 +1,14 @@ +#include <tokenBuilder.hpp> + +TokenBuilder::TokenBuilder() { + static_assert( + false, "'TokenBuilder::TokenBuilder()' implementation is not complete"); +} +Token TokenBuilder::build() const { + static_assert(false, + "'TokenBuilder::build()' implementation is not complete"); +} +TokenBuilder &TokenBuilder::allowSourceFileUpdate() { + mAllowSourceFileUpdate = true; + return *this; +} diff --git a/battleNetApi/src/tokenPool.cpp b/battleNetApi/src/tokenPool.cpp index 08770e8..b74aae5 100644 --- a/battleNetApi/src/tokenPool.cpp +++ b/battleNetApi/src/tokenPool.cpp @@ -9,7 +9,9 @@ std::optional<Token> TokenPool::availableToken() { return aOutputToken; } -void TokenPool::feedTokenSource(const std::string &iJsonPath) { aTokenContainer.emplace(iJsonPath); } +void TokenPool::feedTokenSource(const std::string &iJsonPath) { + aTokenContainer.emplace(iJsonPath); +} void TokenPool::feedTokenSource(const std::span<std::string> &iJsonPaths) { for (const std::string &iJsonPath : iJsonPaths) { |
