Skip to content

api no longer updates after certain ammount of time #635

Description

@halal-beef

when i leave my program for around 10-15 minutes the api dissconnects and will no longer update not even the music progress :(

ill share code i dont know what i did wrong

`using SpotifyAPI.Web;
using SpotifyAPI.Web.Models;
using System;
using System.Diagnostics;
using System.Threading;
using System.Timers;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Threading;

namespace minify
{

public partial class MainWindow : Window
{

    string _songID;
    int progress = 0;
    SpotifyAPI spotAPI;
    SpotifyWebAPI _spotify;
    bool _pauseAPI = false;
    byte r = 255, g = 0, b = 0;
    private TimeSpan duration { get; set; } = TimeSpan.FromSeconds(1);
    private IEasingFunction ease { get; set; } = new QuarticEase { EasingMode = EasingMode.EaseInOut };

    public MainWindow()
    {
        InitializeComponent();
        if (Properties.Settings.Default.firstLaunch)
        {
            Left = SystemParameters.WorkArea.Width - Width;
            Top = SystemParameters.WorkArea.Height - Height;

            Properties.Settings.Default.mainLeft = Left;
            Properties.Settings.Default.mainTop = Top;

            Properties.Settings.Default.firstLaunch = false;
            Properties.Settings.Default.Save();
        }
        else
        {
            ;
            
            
        }

        
        App.Current.Properties["userPause"] = false;
        spotAPI = new SpotifyAPI(Properties.Resources.SpotID, Properties.Resources.SpotSecret);

        
        Thread.Sleep(1000);
        _spotify = new SpotifyWebAPI()
        {
            AccessToken = (string)Application.Current.Properties["AccessToken"],
            TokenType = (string)Application.Current.Properties["TokenType"]
        };

        
        System.Timers.Timer timer = new System.Timers.Timer(350);
        timer.Elapsed += Timer_Elapsed;
        timer.Start();

        
        System.Timers.Timer accesser = new System.Timers.Timer(3500000);
        accesser.Elapsed += Access_Elapsed;
        accesser.Start();

        
        Debug.WriteLine(IsActive);
        IsEnabled = true;
        

        var desktopWorkingArea = System.Windows.SystemParameters.WorkArea;
        this.Left = desktopWorkingArea.Right - this.Width;
        this.Top = desktopWorkingArea.Bottom - this.Height;

    }

    private void Timer_Tick(object sender, EventArgs e)
    {
        durat.Foreground = new SolidColorBrush(Color.FromRgb(r, g, b));
        if (r > 0 && b == 0)
        {
            r--;
            g++;
        }
        if (g > 0 && r == 0)
        {
            g--;
            b++;
        }
        if (b > 0 && g == 0)
        {
            b--;
            r++;
        }
    }

    public void FadeIn(DependencyObject element)
    {
        DoubleAnimation fadeAnimation = new DoubleAnimation()
        {
            From = 0,
            To = 1,
            Duration = duration,
            EasingFunction = ease
        };

        Storyboard.SetTarget(fadeAnimation, element);
        Storyboard.SetTargetProperty(fadeAnimation, new PropertyPath(OpacityProperty));

        Storyboard storyboard = new Storyboard();
        storyboard.Children.Add(fadeAnimation);
        
        storyboard.Begin();
    }

    public void FadeOut(DependencyObject element)
    {
        DoubleAnimation fadeAnimation = new DoubleAnimation()
        {
            From = 1,
            To = 0,
            Duration = duration,
            EasingFunction = ease
        };

        Storyboard.SetTarget(fadeAnimation, element);
        Storyboard.SetTargetProperty(fadeAnimation, new PropertyPath(OpacityProperty));

        Storyboard storyboard = new Storyboard();
        storyboard.Children.Add(fadeAnimation);
        
        storyboard.Begin();
    }


    private void Timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        
        if (_pauseAPI) { return; }

        try
        {
            PlaybackContext context = _spotify.GetPlayingTrack();
            
            Dispatcher.Invoke(() =>
            {
                if (context.Error == null && context.Item != null)
                {
                    if (context.Item.Error == null)
                    {
                        musicsong.Text = context.Item.Name;
                        artist.Text = context.Item.Artists[0].Name;

                        
                        if ((context.Item.Album.Images[0].Url != thing.ImageSource.ToString()) && (context.Item.Album.Images[0].Url != null))
                        {
                            BitmapImage albumArt = new BitmapImage();
                            albumArt.BeginInit();
                            albumArt.UriSource = new Uri(context.Item.Album.Images[0].Url);
                            albumArt.EndInit();
                            thing.ImageSource = albumArt;

                            
                            _songID = context.Item.Id;
                            
                            if(context.IsPlaying)
                            {
                                playpause.Content = "";
                            }

                            
                            progress = context.Item.DurationMs;
                        }

                        
                        durat.Value = ((double)(context.ProgressMs) / (double)(progress)) * 100;
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Inside- " + context.Error.Message);
                    }
                }
                else if (context.Error != null)
                {
                    System.Diagnostics.Debug.WriteLine("Outside- " + context.Error.Message);

                    
                    if (context.Error.Message == "Only valid bearer authentication supported")
                    {
                        _spotify = new SpotifyWebAPI()
                        {
                            AccessToken = (string)Application.Current.Properties["AccessToken"],
                            TokenType = (string)Application.Current.Properties["TokenType"]
                        };
                    }
                    else if (context.Error.Message == "The access token expired")
                    {
                        Debug.WriteLine("Attempting to refresh token due to expiration");
                        spotAPI.Authenticate();
                        _spotify = new SpotifyWebAPI()
                        {
                            AccessToken = (string)Application.Current.Properties["AccessToken"],
                            TokenType = (string)Application.Current.Properties["TokenType"]
                        };
                    }
                }
            });
        }
        catch (Exception err)
        {
            System.Diagnostics.Debug.WriteLine("Error main timer- " + err.Message);
        }
    }

    private void Access_Elapsed(object sender, ElapsedEventArgs e)
    {
        spotAPI.Authenticate();
        _spotify = new SpotifyWebAPI()
        {
            AccessToken = (string)Application.Current.Properties["AccessToken"],
            TokenType = (string)Application.Current.Properties["TokenType"]
        };
    }

    private  void Playpause_Click(object sender, RoutedEventArgs e)
    {
         if ((string)playpause.Content == "")
         {
            Spotify.PausePlaySong();
             playpause.Content = "";
         }
         else
         {
            Spotify.PausePlaySong();
            playpause.Content = "";
         }
        
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        Topmost = true;
        DispatcherTimer timer1 = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1), IsEnabled = true };
        timer1.Tick += Timer_Tick;
        timer1.Start();
    }

    private void Window_Deactivated(object sender, EventArgs e)
    {
        Activate();
    }

    private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
    {
        if(e.Key == System.Windows.Input.Key.NumLock)
        {
            if(this.Opacity == 0)
            {
                FadeIn(this);
            }
            else
            {
                FadeOut(this);
            }
        }
        e.Handled = true;
    }

    private void Skipright_Click(object sender, RoutedEventArgs e)
    {
        Spotify.NextSong();
        playpause.Content = "";
    }

    private void Skipleft_Click(object sender, RoutedEventArgs e)
    {
        Spotify.PreviousSong();
        playpause.Content = "";

    }
}

}
`

`using SpotifyAPI.Web;
using SpotifyAPI.Web.Models;
using System;
using System.Collections.Generic;

namespace minify
{
class Spotify
{
public static void UserTrackSuggestion()
{
try
{
var _spotify = new SpotifyWebAPI
{
AccessToken = (string)App.Current.Properties["AccessToken"],
TokenType = (string)App.Current.Properties["TokenType"]
};

            PlaybackContext context = _spotify.GetPlayingTrack();
            PlaybackContext playbackContext = _spotify.GetPlayback();

            Random random = new Random();
            
            Paging<FullTrack> tracks = _spotify.GetUsersTopTracks();
            List<string> favTracks = new List<string>();
            
            tracks.Items.ForEach(item => favTracks.Add(item.Id));
            
            List<string> recTracks = new List<string>();
            foreach (string track in favTracks)
            {
                recTracks.Add(_spotify.GetRecommendations(trackSeed: new List<string> { track }, limit: 5).Tracks[random.Next(2)].Uri);
            }
            
            ErrorResponse err = _spotify.ResumePlayback(uris: recTracks, offset: "");

        }
        catch
        {
            System.Diagnostics.Debug.WriteLine("Failed at Spotify/UserTrackSuggestion");
        }
    }

    public static void ResumePlayback()
    {
        try
        {
            SpotifyWebAPI _spotify = new SpotifyWebAPI
            {
                AccessToken = (string)App.Current.Properties["AccessToken"],
                TokenType = (string)App.Current.Properties["TokenType"]
            };

            ErrorResponse err = _spotify.ResumePlayback(contextUri: (string)App.Current.Properties["playlistID"], offset: "");
        }
        catch
        {
            System.Diagnostics.Debug.WriteLine("Failed at Spotify/resumePlayback");
        }
    }

    public static void LoveSong(string ID)
    {
        try
        {
            SpotifyWebAPI _spotify = new SpotifyWebAPI
            {
                AccessToken = (string)App.Current.Properties["AccessToken"],
                TokenType = (string)App.Current.Properties["TokenType"]
            };

            PlaybackContext context = _spotify.GetPlayingTrack();
            ErrorResponse response = _spotify.SaveTrack(ID);

        }
        catch
        {
            System.Diagnostics.Debug.WriteLine("Failed at Spotify/LoveSong");
        }
    }

    public static void UnLoveSong(string ID)
    {
        try
        {
            SpotifyWebAPI _spotify = new SpotifyWebAPI()
            {
                AccessToken = (string)App.Current.Properties["AccessToken"],
                TokenType = (string)App.Current.Properties["TokenType"]
            };

            PlaybackContext context = _spotify.GetPlayingTrack();
            ErrorResponse response = _spotify.RemoveSavedTracks(new List<string> { ID });

        }
        catch
        {
            System.Diagnostics.Debug.WriteLine("Failed at Spotify/LoveSong");
        }
    }

    public static void NextSong()
    {
        try
        {
            SpotifyWebAPI _spotify = new SpotifyWebAPI()
            {
                AccessToken = (string)App.Current.Properties["AccessToken"],
                TokenType = (string)App.Current.Properties["TokenType"]
            };

            ErrorResponse error = _spotify.SkipPlaybackToNext();

        }
        catch
        {
            System.Diagnostics.Debug.WriteLine("Failed at Spotify/NextSong");
        }
    }

    public static void PreviousSong()
    {
        try
        {
            SpotifyWebAPI _spotify = new SpotifyWebAPI()
            {
                AccessToken = (string)App.Current.Properties["AccessToken"],
                TokenType = (string)App.Current.Properties["TokenType"]
            };

            ErrorResponse error = _spotify.SkipPlaybackToPrevious();

        }
        catch
        {
            System.Diagnostics.Debug.WriteLine("Failed at Spotify/PreviousSong");
        }
    }

    public static void SeekPlayback(int position)
    {
        try
        {
            SpotifyWebAPI _spotify = new SpotifyWebAPI()
            {
                AccessToken = (string)App.Current.Properties["AccessToken"],
                TokenType = (string)App.Current.Properties["TokenType"]
            };
            PlaybackContext context = _spotify.GetPlayingTrack();
            ErrorResponse error = _spotify.SeekPlayback((int)((position / 100.0) * context.Item.DurationMs));
        }
        catch
        {
            System.Diagnostics.Debug.WriteLine("Failed at Spotify/PreviousSong");
        }
    }

    public static void PausePlaySong()
    {
        try
        {
            SpotifyWebAPI _spotify = new SpotifyWebAPI()
            {
                AccessToken = (string)App.Current.Properties["AccessToken"],
                TokenType = (string)App.Current.Properties["TokenType"]
            };
            PlaybackContext context = _spotify.GetPlayback();
            if (context.IsPlaying)
            {
                ErrorResponse error = _spotify.PausePlayback();
                App.Current.Properties["userPause"] = true;
            }
            else
            {
                ErrorResponse error = _spotify.ResumePlayback(offset: "");
                App.Current.Properties["userPause"] = false;
            }
        }
        catch
        {
            System.Diagnostics.Debug.WriteLine("Failed at Spotify/PausePlaySong");
        }
    }

    public static int GetSetVolume(int volume = 255)
    {
        try
        {
            SpotifyWebAPI _spotify = new SpotifyWebAPI()
            {
                AccessToken = (string)App.Current.Properties["AccessToken"],
                TokenType = (string)App.Current.Properties["TokenType"]
            };
            
            PlaybackContext context = _spotify.GetPlayback();
            if (volume == 255)
            {
                return context.Device.VolumePercent;
            }
            else
            {
                ErrorResponse _ = _spotify.SetVolume(volume);
                return 1;
            }
        }
        catch
        {
            System.Diagnostics.Debug.WriteLine("Failed at Spotify/GetSetVolume");
            return -1;
        }
    }
}

}
`

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions