spotify debug
All checks were successful
Deploy to Dokku / docker (ubuntu-latest) (push) Successful in 36s

This commit is contained in:
Lee 2024-06-28 03:50:38 +01:00
parent 53b84a884c
commit eccd673db8
2 changed files with 23 additions and 2 deletions

@ -19,6 +19,11 @@ public class SpotifyProfile extends Profile {
*/
private String refreshToken;
/**
* When the access token expires
*/
private Long expiresAt;
public SpotifyProfile() {
super("spotify");
}

@ -91,6 +91,7 @@ public class SpotifyService {
try {
return getSpotifyApi(user).getUsersCurrentlyPlayingTrack().build().execute();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@ -178,11 +179,26 @@ public class SpotifyService {
*
* @return the Spotify API
*/
@SneakyThrows
public SpotifyApi getSpotifyApi(BatUser user) {
SpotifyProfile profile = user.getProfile(SpotifyProfile.class);
return new SpotifyApi.Builder()
.setAccessToken(profile.getAccessToken())
SpotifyApi api = new SpotifyApi.Builder()
.setClientId(clientId)
.setClientSecret(clientSecret)
.setAccessToken(profile.getAccessToken())
.setRefreshToken(profile.getRefreshToken())
.build();
// Refresh the access token if it's expired
if (profile.getExpiresAt() == null || profile.getExpiresAt() < System.currentTimeMillis()) {
AuthorizationCodeCredentials credentials = api.authorizationCodeRefresh().build().execute();
profile.setAccessToken(credentials.getAccessToken());
profile.setRefreshToken(credentials.getRefreshToken());
profile.setExpiresAt(System.currentTimeMillis() + (credentials.getExpiresIn() * 1000));
api.setAccessToken(credentials.getAccessToken());
api.setRefreshToken(credentials.getRefreshToken());
userService.saveUser(user);
}
return api;
}
}