diff --git a/NowPlayingKiosk/MainWindow.xaml.cs b/NowPlayingKiosk/MainWindow.xaml.cs index c5b46e4..2ffb5e2 100644 --- a/NowPlayingKiosk/MainWindow.xaml.cs +++ b/NowPlayingKiosk/MainWindow.xaml.cs @@ -140,6 +140,7 @@ public partial class MainWindow : Window { private bool _inStateChange; private TrackInfoPoller poller; + private SpotifyWebAPI webApi; public MainWindow() { @@ -218,19 +219,19 @@ private async void LoggedInSuccessfully(object sender, AuthorizationCode payload Dispatcher.Invoke(DispatcherPriority.Render, new Action(() => GoToMainPage())); Token token = await auth.ExchangeCode(payload.Code); - SpotifyWebAPI api = new SpotifyWebAPI + webApi = new SpotifyWebAPI { AccessToken = token.AccessToken, TokenType = token.TokenType }; - StartPoller(api); + StartPoller(auth, token); } - private void StartPoller(SpotifyWebAPI api) + private void StartPoller(AuthorizationCodeAuth auth, Token token) { CoverManager coverManager = new CoverManager(); - NowPlayingTrackInfoProvider trackInfoProvider = new SpotifyNowPlayingTrackInfoProvider(api); + NowPlayingTrackInfoProvider trackInfoProvider = new SpotifyNowPlayingTrackInfoProvider(webApi, auth, token); poller = new TrackInfoPoller(trackInfoProvider, coverManager, this); Thread pollerThread = new Thread(new ThreadStart(poller.PollAndUpdate)); pollerThread.Start(); diff --git a/NowPlayingKiosk/SpotifyNowPlayingTrackInfoProvider.cs b/NowPlayingKiosk/SpotifyNowPlayingTrackInfoProvider.cs index 34d0b81..825fbbc 100644 --- a/NowPlayingKiosk/SpotifyNowPlayingTrackInfoProvider.cs +++ b/NowPlayingKiosk/SpotifyNowPlayingTrackInfoProvider.cs @@ -1,4 +1,5 @@ using SpotifyAPI.Web; +using SpotifyAPI.Web.Auth; using SpotifyAPI.Web.Enums; using SpotifyAPI.Web.Models; using System; @@ -7,16 +8,29 @@ namespace NowPlayingKiosk { public class SpotifyNowPlayingTrackInfoProvider : NowPlayingTrackInfoProvider { - private readonly SpotifyWebAPI clientApi; + private readonly SpotifyWebAPI webApi; + private readonly AuthorizationCodeAuth authorization; + private Token accessToken; + private Token refreshToken; - public SpotifyNowPlayingTrackInfoProvider(SpotifyWebAPI api) + public SpotifyNowPlayingTrackInfoProvider(SpotifyWebAPI api, AuthorizationCodeAuth auth, Token token) { - clientApi = api; + webApi = api; + authorization = auth; + accessToken = token; + refreshToken = token; } public TrackInfo WhatIsNowPlaying() { - PlaybackContext context = clientApi.GetPlayingTrack(); + DateTime expireDate = accessToken.CreateDate.AddSeconds(accessToken.ExpiresIn); + if (DateTime.Compare(DateTime.Now, expireDate.AddMinutes(-1)) > 0) + { + accessToken = authorization.RefreshToken(refreshToken.RefreshToken).Result; + webApi.AccessToken = accessToken.AccessToken; + } + + PlaybackContext context = webApi.GetPlayingTrack(); if (context.IsPlaying && !TrackType.Ad.Equals(context.CurrentlyPlayingType)) {