mirror of
https://github.com/sle118/squeezelite-esp32.git
synced 2025-12-12 06:27:12 +03:00
move to new cspot
This commit is contained in:
53
components/spotify/cspot/src/AccessKeyFetcher.cpp
Normal file
53
components/spotify/cspot/src/AccessKeyFetcher.cpp
Normal file
@@ -0,0 +1,53 @@
|
||||
#include "AccessKeyFetcher.h"
|
||||
#include <cstring>
|
||||
#include "Logger.h"
|
||||
#include "Utils.h"
|
||||
|
||||
using namespace cspot;
|
||||
|
||||
AccessKeyFetcher::AccessKeyFetcher(std::shared_ptr<cspot::Context> ctx) {
|
||||
this->ctx = ctx;
|
||||
}
|
||||
|
||||
AccessKeyFetcher::~AccessKeyFetcher() {}
|
||||
|
||||
bool AccessKeyFetcher::isExpired() {
|
||||
if (accessKey.empty()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (ctx->timeProvider->getSyncedTimestamp() > expiresAt) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void AccessKeyFetcher::getAccessKey(AccessKeyFetcher::Callback callback) {
|
||||
if (!isExpired()) {
|
||||
return callback(accessKey);
|
||||
}
|
||||
|
||||
CSPOT_LOG(info, "Access token expired, fetching new one...");
|
||||
|
||||
std::string url =
|
||||
string_format("hm://keymaster/token/authenticated?client_id=%s&scope=%s",
|
||||
CLIENT_ID.c_str(), SCOPES.c_str());
|
||||
auto timeProvider = this->ctx->timeProvider;
|
||||
|
||||
ctx->session->execute(
|
||||
MercurySession::RequestType::GET, url,
|
||||
[this, timeProvider, callback](MercurySession::Response& res) {
|
||||
if (res.fail) return;
|
||||
char* accessKeyJson = (char*)res.parts[0].data();
|
||||
auto accessJSON = std::string(accessKeyJson, strrchr(accessKeyJson, '}') - accessKeyJson + 1);
|
||||
auto jsonBody = nlohmann::json::parse(accessJSON);
|
||||
this->accessKey = jsonBody["accessToken"];
|
||||
int expiresIn = jsonBody["expiresIn"];
|
||||
expiresIn = expiresIn / 2; // Refresh token before it expires
|
||||
|
||||
this->expiresAt =
|
||||
timeProvider->getSyncedTimestamp() + (expiresIn * 1000);
|
||||
callback(jsonBody["accessToken"]);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user