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); }