From de1da2391d06971d670fd2ecacf1f6f0b9c88720 Mon Sep 17 00:00:00 2001 From: Liam Date: Sat, 6 Jul 2024 00:31:48 +0100 Subject: [PATCH] add currently playing cache to spotify --- .../fascinated/bat/service/SpotifyService.java | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/main/java/cc/fascinated/bat/service/SpotifyService.java b/src/main/java/cc/fascinated/bat/service/SpotifyService.java index 1b09e41..21a957c 100644 --- a/src/main/java/cc/fascinated/bat/service/SpotifyService.java +++ b/src/main/java/cc/fascinated/bat/service/SpotifyService.java @@ -36,6 +36,13 @@ public class SpotifyService { .expiration(30, TimeUnit.MINUTES) .build(); + /** + * A cache of the currently playing track for each user. + */ + private final Map currentlyPlayingCache = ExpiringMap.builder() + .expiration(30, TimeUnit.SECONDS) + .build(); + /** * The client ID. */ @@ -98,7 +105,12 @@ public class SpotifyService { */ @SneakyThrows public CurrentlyPlaying getCurrentlyPlayingTrack(BatUser user) { - return getSpotifyApi(user).getUsersCurrentlyPlayingTrack().build().execute(); + if (currentlyPlayingCache.containsKey(user)) { + return currentlyPlayingCache.get(user); + } + CurrentlyPlaying currentlyPlaying = getSpotifyApi(user).getUsersCurrentlyPlayingTrack().build().execute(); + currentlyPlayingCache.put(user, currentlyPlaying); + return currentlyPlaying; } /** @@ -191,7 +203,7 @@ public class SpotifyService { AuthorizationCodeCredentials credentials = api.authorizationCodeRefresh().build().execute(); profile.setAccessToken(credentials.getAccessToken()); profile.setExpiresAt(System.currentTimeMillis() + (credentials.getExpiresIn() * 1000)); - log.info("Refreshed Spotify token for user {}", user.getName()); + log.info("Refreshed Spotify token for user \"{}\"", user.getName()); } catch (SpotifyWebApiException ex) { log.error("Failed to refresh Spotify token", ex); }