From eccd673db8c9f03ed317ea610eb9b239f61e0e18 Mon Sep 17 00:00:00 2001 From: Liam Date: Fri, 28 Jun 2024 03:50:38 +0100 Subject: [PATCH] spotify debug --- .../spotify/profile/SpotifyProfile.java | 5 +++++ .../bat/service/SpotifyService.java | 20 +++++++++++++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/main/java/cc/fascinated/bat/features/spotify/profile/SpotifyProfile.java b/src/main/java/cc/fascinated/bat/features/spotify/profile/SpotifyProfile.java index 03e3e0f..eebb3d8 100644 --- a/src/main/java/cc/fascinated/bat/features/spotify/profile/SpotifyProfile.java +++ b/src/main/java/cc/fascinated/bat/features/spotify/profile/SpotifyProfile.java @@ -19,6 +19,11 @@ public class SpotifyProfile extends Profile { */ private String refreshToken; + /** + * When the access token expires + */ + private Long expiresAt; + public SpotifyProfile() { super("spotify"); } diff --git a/src/main/java/cc/fascinated/bat/service/SpotifyService.java b/src/main/java/cc/fascinated/bat/service/SpotifyService.java index 0d0bfbd..9998263 100644 --- a/src/main/java/cc/fascinated/bat/service/SpotifyService.java +++ b/src/main/java/cc/fascinated/bat/service/SpotifyService.java @@ -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; } }