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; private String refreshToken;
/**
* When the access token expires
*/
private Long expiresAt;
public SpotifyProfile() { public SpotifyProfile() {
super("spotify"); super("spotify");
} }

@ -91,6 +91,7 @@ public class SpotifyService {
try { try {
return getSpotifyApi(user).getUsersCurrentlyPlayingTrack().build().execute(); return getSpotifyApi(user).getUsersCurrentlyPlayingTrack().build().execute();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace();
return null; return null;
} }
} }
@ -178,11 +179,26 @@ public class SpotifyService {
* *
* @return the Spotify API * @return the Spotify API
*/ */
@SneakyThrows
public SpotifyApi getSpotifyApi(BatUser user) { public SpotifyApi getSpotifyApi(BatUser user) {
SpotifyProfile profile = user.getProfile(SpotifyProfile.class); SpotifyProfile profile = user.getProfile(SpotifyProfile.class);
return new SpotifyApi.Builder() SpotifyApi api = new SpotifyApi.Builder()
.setAccessToken(profile.getAccessToken()) .setClientId(clientId)
.setClientSecret(clientSecret) .setClientSecret(clientSecret)
.setAccessToken(profile.getAccessToken())
.setRefreshToken(profile.getRefreshToken())
.build(); .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;
} }
} }