22
22
using ToastifyAPI . Model . Interfaces ;
23
23
using ToastifyAPI . Native ;
24
24
using Settings = Toastify . Model . Settings ;
25
+ using Timer = System . Threading . Timer ;
25
26
26
27
namespace Toastify . Core
27
28
{
@@ -41,10 +42,15 @@ public static Spotify Instance
41
42
#endregion
42
43
43
44
private readonly string spotifyPath ;
45
+ private readonly TimeSpan songChangeBuffer = TimeSpan . FromMilliseconds ( 1500 ) ;
44
46
45
47
private SpotifyWindow spotifyWindow ;
46
48
private Process spotifyProcess ;
47
49
50
+ private Timer apiTrackDelayedUpdateTimer ;
51
+ private DateTime lastSongChange = DateTime . Now ;
52
+ private int songChangesInTimespan ;
53
+
48
54
#region Public Properties
49
55
50
56
[ PropertyDependency ]
@@ -853,8 +859,25 @@ private async void SpotifyWindowTitleWatcher_TitleChanged(object sender, WindowT
853
859
if ( logger . IsDebugEnabled )
854
860
logger . Debug ( $ "Spotify's window title changed: \" { e . NewTitle } \" . Fetching song info...") ;
855
861
856
- if ( ! ( Settings . Current . EnableSpotifyWebApi && this . IsWebApiRunning &&
857
- await this . UpdateTrackInfoUsingWebApi ( ) . ConfigureAwait ( false ) ) )
862
+ bool shouldUpdateUsingWindowTitle = ! ( Settings . Current . EnableSpotifyWebApi && this . IsWebApiRunning ) ;
863
+
864
+ this . apiTrackDelayedUpdateTimer ? . Dispose ( ) ;
865
+ bool tooFast = this . songChangesInTimespan >= 3 ;
866
+ if ( ! shouldUpdateUsingWindowTitle && tooFast )
867
+ {
868
+ logger . Debug ( $ "Songs are being changed too fast ({ this . songChangesInTimespan } times in { this . songChangeBuffer . TotalMilliseconds } ms)!") ;
869
+ this . apiTrackDelayedUpdateTimer = new Timer ( async state =>
870
+ {
871
+ logger . Debug ( $ "Executing delayed track update using WebAPI (\" { state } \" )") ;
872
+ await this . UpdateTrackInfoUsingWebApi ( ) . ConfigureAwait ( false ) ;
873
+ } , e . NewTitle , this . songChangeBuffer , TimeSpan . FromMilliseconds ( - 1 ) ) ;
874
+ shouldUpdateUsingWindowTitle = true ;
875
+ }
876
+
877
+ if ( ! shouldUpdateUsingWindowTitle )
878
+ shouldUpdateUsingWindowTitle = ! await this . UpdateTrackInfoUsingWebApi ( ) . ConfigureAwait ( false ) ;
879
+
880
+ if ( shouldUpdateUsingWindowTitle )
858
881
{
859
882
// If the WebAPIs are disabled or they weren't able to retrieve the song info, fallback to
860
883
// the old method based on the title of Spotify's window.
@@ -882,6 +905,11 @@ await this.UpdateTrackInfoUsingWebApi().ConfigureAwait(false)))
882
905
}
883
906
}
884
907
}
908
+
909
+ this . songChangesInTimespan ++ ;
910
+ if ( DateTime . Now - this . lastSongChange > this . songChangeBuffer )
911
+ this . songChangesInTimespan = 0 ;
912
+ this . lastSongChange = DateTime . Now ;
885
913
}
886
914
catch ( Exception exception )
887
915
{
0 commit comments