AccessKeyFetcher.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include "AccessKeyFetcher.h"
  2. #include <cstring>
  3. #include "Logger.h"
  4. #include "Utils.h"
  5. using namespace cspot;
  6. AccessKeyFetcher::AccessKeyFetcher(std::shared_ptr<cspot::Context> ctx) {
  7. this->ctx = ctx;
  8. }
  9. AccessKeyFetcher::~AccessKeyFetcher() {}
  10. bool AccessKeyFetcher::isExpired() {
  11. if (accessKey.empty()) {
  12. return true;
  13. }
  14. if (ctx->timeProvider->getSyncedTimestamp() > expiresAt) {
  15. return true;
  16. }
  17. return false;
  18. }
  19. void AccessKeyFetcher::getAccessKey(AccessKeyFetcher::Callback callback) {
  20. if (!isExpired()) {
  21. return callback(accessKey);
  22. }
  23. CSPOT_LOG(info, "Access token expired, fetching new one...");
  24. std::string url =
  25. string_format("hm://keymaster/token/authenticated?client_id=%s&scope=%s",
  26. CLIENT_ID.c_str(), SCOPES.c_str());
  27. auto timeProvider = this->ctx->timeProvider;
  28. ctx->session->execute(
  29. MercurySession::RequestType::GET, url,
  30. [this, timeProvider, callback](MercurySession::Response& res) {
  31. if (res.fail) return;
  32. char* accessKeyJson = (char*)res.parts[0].data();
  33. auto accessJSON = std::string(accessKeyJson, strrchr(accessKeyJson, '}') - accessKeyJson + 1);
  34. #ifdef BELL_ONLY_CJSON
  35. cJSON* jsonBody = cJSON_Parse(accessJSON.c_str());
  36. this->accessKey = cJSON_GetObjectItem(jsonBody, "accessToken")->valuestring;
  37. int expiresIn = cJSON_GetObjectItem(jsonBody, "expiresIn")->valueint;
  38. #else
  39. auto jsonBody = nlohmann::json::parse(accessJSON);
  40. this->accessKey = jsonBody["accessToken"];
  41. int expiresIn = jsonBody["expiresIn"];
  42. #endif
  43. expiresIn = expiresIn / 2; // Refresh token before it expires
  44. this->expiresAt =
  45. timeProvider->getSyncedTimestamp() + (expiresIn * 1000);
  46. #ifdef BELL_ONLY_CJSON
  47. callback(cJSON_GetObjectItem(jsonBody, "accessToken")->valuestring);
  48. cJSON_Delete(jsonBody);
  49. #else
  50. callback(jsonBody["accessToken"]);
  51. #endif
  52. });
  53. }