Beispiel #1
0
        public TrackInfo WhatIsNowPlaying()
        {
            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;
                if (accessToken.RefreshToken != null)
                {
                    refreshToken = accessToken;
                }
            }

            try
            {
                PlaybackContext context = webApi.GetPlayingTrack();
                if (context.IsPlaying && !TrackType.Ad.Equals(context.CurrentlyPlayingType))
                {
                    FullTrack track = context.Item;
                    return(new TrackInfo(track.Artists[0].Name, track.Name, track.Album.Images[0].Url));
                }
            }
            catch (AggregateException)
            { }
            return(null);
        }
Beispiel #2
0
    public async void refreshtoken(string codeToken, bool tellPeople, Action <bool, bool, string, string> callback = null)
    {
        initialized = false;
        if (_spotify == null)
        {
            _spotify = new SpotifyWebAPI();
        }
        AuthorizationCodeAuth auth = getAuth();
        Token token = await auth.RefreshToken(codeToken);

        _spotify.AccessToken = token.AccessToken;
        _spotify.TokenType   = token.TokenType;

        if (!token.HasError())
        {
            initialized = true;
        }
        else
        {
            Console.WriteLine(token.Error + " - " + token.ErrorDescription);
        }

        if (callback != null)
        {
            callback(initialized, tellPeople, token.AccessToken, token.RefreshToken);
        }
    }
Beispiel #3
0
        /// <summary>
        /// <see cref="BaseMeasure.Update"/>
        /// </summary>
        /// <returns><see cref="BaseMeasure.Update"/></returns>
        internal override double Update()
        {
            if (_accessToken == null || _accessToken.IsExpired())
            {
                var auth    = new AuthorizationCodeAuth(_clientId, _clientSecret, string.Empty, string.Empty);
                var refresh = auth.RefreshToken(_refreshToken);

                if (!refresh.Wait(10000))
                {
                    _log(LogType.Error, "Timeout when refreshing token");
                    return(0);
                }

                _accessToken = refresh.Result;
            }

            var api = new SpotifyWebAPI
            {
                AccessToken = _accessToken.AccessToken,
                UseAuth     = true,
                TokenType   = _accessToken.TokenType,
            };

            Playback = api.GetPlayback();

            return(base.Update());
        }
Beispiel #4
0
        public CustomToken RefreshToken(string refreshToken, string clientSecret)
        {
            AuthorizationCodeAuth auth = new AuthorizationCodeAuth(
                Settings.ClientId,
                Settings.ClientSecret,
                Settings.RedirectUri,
                Settings.RedirectUri,
                Scope.None,
                Settings.StateKey
                );

            Token       response;
            CustomToken result = null;

            try
            {
                response = auth.RefreshToken(refreshToken).Result;

                result = response.ToCustomToken();

                if (result != null)
                {
                    result.RefreshToken = refreshToken;
                }
            }
            catch (Exception)
            {
            }

            return(result);
        }
        public async Task ConnectWebApi(bool keepRefreshToken = true)
        {
            _securityStore = SecurityStore.Load(pluginDirectory);

            AuthorizationCodeAuth auth = new AuthorizationCodeAuth(_securityStore.ClientId, _securityStore.ClientSecret, "http://localhost:4002", "http://localhost:4002",
                                                                   Scope.PlaylistReadPrivate | Scope.PlaylistReadCollaborative | Scope.UserReadCurrentlyPlaying | Scope.UserReadPlaybackState | Scope.UserModifyPlaybackState | Scope.Streaming | Scope.UserFollowModify);


            if (_securityStore.HasRefreshToken && keepRefreshToken)
            {
                Token token = await auth.RefreshToken(_securityStore.RefreshToken);

                _spotifyApi = new SpotifyWebAPI()
                {
                    TokenType = token.TokenType, AccessToken = token.AccessToken
                };
            }
            else
            {
                auth.AuthReceived += async(sender, payload) =>
                {
                    auth.Stop();
                    Token token = await auth.ExchangeCode(payload.Code);

                    _securityStore.RefreshToken = token.RefreshToken;
                    _securityStore.Save(pluginDirectory);
                    _spotifyApi = new SpotifyWebAPI()
                    {
                        TokenType = token.TokenType, AccessToken = token.AccessToken
                    };
                };
                auth.Start();
                auth.OpenBrowser();
            }
        }
Beispiel #6
0
        private async Task RefreshTokenAsync()
        {
            if (!_settings.Token.HasExpired())
            {
                return;
            }

            UpdateToken(await _authentication.RefreshToken(_settings.Token.RefreshToken));
        }
Beispiel #7
0
        public void Authenticate()
        {
            Token newToken = auth.RefreshToken(token.RefreshToken).Result;

            api.TokenType   = newToken.TokenType;
            api.AccessToken = newToken.AccessToken;
            App.Current.Properties["TokenType"]   = api.TokenType;
            App.Current.Properties["AccessToken"] = api.AccessToken;
        }
Beispiel #8
0
        public void RefrescarToken()
        {
            Log.Instance.ImprimirMensaje("Refrescando Token...", TipoMensaje.Info);
            Token newToken = auth.RefreshToken(CodigoRefresco).Result;

            _spotify.AccessToken = newToken.AccessToken;
            _spotify.TokenType   = newToken.TokenType;
            tokenActual          = newToken;
            Log.Instance.ImprimirMensaje("Token refrescado!", TipoMensaje.Correcto);
        }
        internal SpotifyAuthentication()
        {
            bool initialized = false;
            var  client_id   = "7b2f38e47869431caeda389929a1908e";
            var  secret_id   = "c3a86330ef844c16be6cb46d5e285a45";

            _authenFactory = new AuthorizationCodeAuth(
                client_id,
                secret_id,
                "http://localhost:8800",
                "http://localhost:8800",
                Scope.UserReadCurrentlyPlaying |
                Scope.UserModifyPlaybackState |
                Scope.AppRemoteControl |
                Scope.UserReadPlaybackState
                );
            _authenFactory.AuthReceived += async(s, p) =>
            {
                var ath = (AuthorizationCodeAuth)s;
                ath.Stop();

                var token = await ath.ExchangeCode(p.Code);

                _refreshToken = token.RefreshToken;
                if (_client == null)
                {
                    _client = new SpotifyWebAPI()
                    {
                        AccessToken = token.AccessToken,
                        TokenType   = "Bearer"
                    };
                }
                else
                {
                    _client.AccessToken = token.AccessToken;
                }
                if (!initialized)
                {
                    ClientReady?.Invoke(this, _client);
                }
                initialized = true;
            };
            _authenFactory.Start();
            _authenFactory.OpenBrowser();
            _refreshTokenWorker          = new Timer();
            _refreshTokenWorker.Interval = 30 * (1000 * 60);
            _refreshTokenWorker.Elapsed += async(s, e) =>
            {
                var token = await _authenFactory.RefreshToken(_refreshToken);

                _client.AccessToken = token.AccessToken;
            };
            _refreshTokenWorker.Start();
        }
        SpotifyConfiguration()
        {
            bool initialized = false;
            var  client_id   = "7b2f38e47869431caeda389929a1908e";
            var  secret_id   = "c3a86330ef844c16be6cb46d5e285a45";

            AuthenFactory = new AuthorizationCodeAuth(
                client_id,
                secret_id,
                "http://localhost:8888",
                "http://localhost:8888",
                SpotifyAPI.Web.Enums.Scope.AppRemoteControl
                );
            AuthenFactory.AuthReceived += async(s, p) =>
            {
                var ath = (AuthorizationCodeAuth)s;
                ath.Stop();

                var token = await ath.ExchangeCode(p.Code);

                initialized  = true;
                RefreshToken = token.RefreshToken;
                if (Client == null)
                {
                    Client = new SpotifyWebAPI()
                    {
                        AccessToken = token.AccessToken,
                        TokenType   = "Bearer"
                    };
                }
                else
                {
                    Client.AccessToken = token.AccessToken;
                }
                IsAvailable = true;
            };
            AuthenFactory.Start();
            AuthenFactory.OpenBrowser();
            while (!initialized)
            {
                System.Threading.Thread.Sleep(1000);
            }
            AuthenFactory.Stop();
            _refreshTokenWorker          = new Timer();
            _refreshTokenWorker.Interval = 30 * (1000 * 60);
            _refreshTokenWorker.Elapsed += async(s, e) =>
            {
                var token = await AuthenFactory.RefreshToken(RefreshToken);

                Client.AccessToken = token.AccessToken;
            };
            _refreshTokenWorker.Start();
        }
Beispiel #11
0
    static async Task RefreshToken(bool isSilent = false)
    {
        if (!isSilent)
        {
            Console.WriteLine(String.Format("\r{0,-80}", "Refreshing access token..."));
        }
        Token newToken = await auth.RefreshToken(token.RefreshToken);

        if (!newToken.HasError())
        {
            spotifyAPI.AccessToken = newToken.AccessToken;
            spotifyAPI.TokenType   = newToken.TokenType;

            token.AccessToken = newToken.AccessToken;
            token.ExpiresIn   = newToken.ExpiresIn;
            token.CreateDate  = newToken.CreateDate;

            if (!isSilent)
            {
                Console.WriteLine("New '" + token.TokenType + "' access token acquired at " + DateTime.Now);
            }

            SaveTokenToFile(isSilent);
            if (!isSilent)
            {
                Console.WriteLine("");
            }
        }
        else
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("TOKEN ERROR");
            Console.WriteLine("Error:\t\t" + newToken.Error);
            Console.WriteLine("Description:\t" + newToken.ErrorDescription);
            Console.ForegroundColor = ConsoleColor.Gray;
            if (newToken.ErrorDescription == "Refresh token revoked")
            {
                File.WriteAllText("AccessToken.json", "");
                if (!isAuthServerOn)
                {
                    await CreateSpotifyAPI();
                }
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Shutting down...");
                Console.ForegroundColor = ConsoleColor.Gray;
                Environment.Exit(0);
            }
        }
    }
Beispiel #12
0
        private async void spotifyDataLoop()
        {
            connected = true;
            bool playbackState = false;

            while (true)
            {
                if (token.IsExpired())
                {
                    token = await auth.RefreshToken(token.RefreshToken);

                    api.AccessToken = token.AccessToken;
                    api.TokenType   = token.TokenType;
                }
                var playback = api.GetPlayingTrack();
                if (playback.HasError())
                {
                    Console.WriteLine(playback.Error.Message);
                }
                else if (playback.Item == null)
                {
                    if (currentlyPlaying != "")
                    {
                        currentlyPlaying = "";
                        OnAudioChange(this, new AudioChangeArgs(playback));
                        //picture.Image = Properties.Resources.NoSong;
                        //playingLabel.Text = currentlyPlaying;
                    }
                }
                else if (currentlyPlaying != playback.Item.Id)
                {
                    Console.WriteLine(playback.Item.Name + " " + playback.Item.PreviewUrl);
                    currentlyPlaying = playback.Item.Id;
                    OnAudioChange(this, new AudioChangeArgs(playback));
                }
                if (playback.IsPlaying != playbackState)
                {
                    if (playback.IsPlaying)
                    {
                        ArduinoInterface.sendPlay(playback.ProgressMs, playback.Item.DurationMs);
                    }
                    else
                    {
                        ArduinoInterface.sendPause(playback.ProgressMs, playback.Item.DurationMs);
                    }
                }


                playbackState = playback.IsPlaying;
                Thread.Sleep(1000);
            }
        }
Beispiel #13
0
        private Token RefreshToken(string refreshToken)
        {
            AuthorizationCodeAuth auth = new AuthorizationCodeAuth(
                Settings.ClientId,
                Settings.ClientSecret,
                Settings.RedirectUri,
                Settings.RedirectUri,
                Scope.None,
                Settings.StateKey
                );

            return(auth.RefreshToken(refreshToken).Result);
        }
Beispiel #14
0
        private static async Task <string> GetAccessToken(ILogger log, string client_id, string client_secret, string redirect_url, string refreshToken)
        {
            if (!memoryCache.TryGetValue("AccessToken", out string cacheAccessToken))
            {
                AuthorizationCodeAuth auth = new AuthorizationCodeAuth(client_id, client_secret, redirect_url, redirect_url,
                                                                       Scope.PlaylistReadPrivate | Scope.PlaylistReadCollaborative | Scope.UserModifyPlaybackState | Scope.UserReadPlaybackState);

                var token = await auth.RefreshToken(refreshToken);

                cacheAccessToken = token.AccessToken;
                memoryCache.Set("AccessToken", cacheAccessToken, TimeSpan.FromMinutes(50));
                log.LogInformation($"AccessToken updated in cache");
            }
            return(cacheAccessToken);
        }
Beispiel #15
0
        private async Task <T> GetAsync <T>(Func <Task <T> > func) where T : BasicModel
        {
            T result = await func();

            if (result.HasError() && _accessTokenErrorStatusCodes.Contains(result.Error.Status))
            {
                AuthorizationCodeAuth auth = new AuthorizationCodeAuth(_credentials.SpotifyClientId, _credentials.SpotifyClientSecret, _credentials.SpotifyRedirectUri, "");
                Token token = await auth.RefreshToken(_credentials.SpotifyRefreshToken);

                _spotify.AccessToken = token.AccessToken;
                _spotify.TokenType   = token.TokenType;
            }

            return(await func());
        }
Beispiel #16
0
        public Token RefreshToken()
        {
            this.spotifyToken = this.GetTokenFromFile();
            AuthorizationCodeAuth auth = this.CreateAuthorization();
            Token refreshedToken       = auth.RefreshToken(this.spotifyToken.RefreshToken).Result;

            refreshedToken.RefreshToken = this.spotifyToken.RefreshToken;

            this.SpotifyWebApi = this.CreateSpotifyWebApi(this.spotifyToken);

            this.CreateTokenFile(refreshedToken);
            this.spotifyToken = refreshedToken;

            return(refreshedToken);
        }
Beispiel #17
0
        async void refreshToken()
        {
            try
            {
                Token newToken = await auth.RefreshToken(token.RefreshToken);

                oAuthToken = newToken.AccessToken;
                txt_accessToken.Invoke((MethodInvoker) delegate
                {
                    txt_accessToken.Text = oAuthToken;
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        //saves the playlist to th users account and sends you back to the home page
        public async Task <ActionResult> Save(string playlistName, bool isPublic = false)
        {
            string name = playlistName;

            if (name == "")
            {
                name = ((IndexViewModel)TempData["ViewModel"]).title;
            }

            Token token = (Token)TempData["Token"];
            AuthorizationCodeAuth auth     = (AuthorizationCodeAuth)TempData["Auth"];
            SpotifyWebAPI         api      = (SpotifyWebAPI)TempData["Api"];
            Playlist       currentPlaylist = (Playlist)TempData["Playlist"];
            IndexViewModel viewModel       = (IndexViewModel)TempData["ViewModel"];

            viewModel.PlaylistURIs = (List <string>)TempData["PlaylistURIs"];
            if (token.IsExpired())
            {
                Token newToken = await auth.RefreshToken(token.RefreshToken);

                api.AccessToken = newToken.AccessToken;
                api.TokenType   = newToken.TokenType;
            }

            string userId = api.GetPrivateProfile().Id;

            FullPlaylist playlist = api.CreatePlaylist(userId, name, isPublic);

            ErrorResponse response = new ErrorResponse();

            response = api.AddPlaylistTracks(playlist.Id, viewModel.PlaylistURIs);

            TempData["FlashMessage"] = name + " was successfully created and saved to your Spotify account!";
            TempData["isError"]      = false;

            //checks for error from laylist save and changes the flass message appropriately.
            if (response.HasError())
            {
                TempData["FlashMessage"] = "Something went wrong while saving the playlist.";
                TempData["isError"]      = true;
            }



            return(RedirectToAction("Index", "Home"));
        }
Beispiel #19
0
        private async Task <SpotifyWebAPI> GetSpotifyWebAPI()
        {
            if (_token == null)
            {
                return(null);
            }

            if (DateTimeOffset.UtcNow >= _nextTokenRenewal)
            {
                _token = await _authorizationCodeAuth.RefreshToken(_token.RefreshToken);
            }

            return(new SpotifyWebAPI
            {
                AccessToken = _token.AccessToken,
                TokenType = _token.TokenType
            });
        }
Beispiel #20
0
        private async Task RefreshTokenAndConfigure(AuthorizationCodeAuth auth, string refreshToken)
        {
            SAPIModels.Token token = await auth.RefreshToken(refreshToken);

            // Inject RefreshToken back into after each re-auth
            token.RefreshToken = m_refreshToken;

            if (token != null && token.Error == null)
            {
                m_refreshTokenRoutine = null;
                Analysis.Log($"Obtained a new authorization token at '{token.CreateDate}'", Analysis.LogLevel.Vital);
                Configure(token, auth);
            }
            else
            {
                string errorMsg = token != null ? $"Error - {token.Error}" : "Token is null";
                Analysis.LogError($"Unable to refresh authorization token - {errorMsg}", Analysis.LogLevel.Vital);
            }
        }
Beispiel #21
0
        //callback method used if login from "playlist/create"
        public async Task <ActionResult> CallbackFromCreate(string code)
        {
            AuthorizationCodeAuth auth = new AuthorizationCodeAuth(
                _clientId,
                _secretId,
                _redirectURLFromCreate,
                _serverURI,
                Scope.PlaylistReadPrivate | Scope.PlaylistReadCollaborative
                );


            Token token = await auth.ExchangeCode(code);

            SpotifyWebAPI api = new SpotifyWebAPI()
            {
                TokenType   = token.TokenType,
                AccessToken = token.AccessToken
            };

            if (token.IsExpired())
            {
                Token newToken = await auth.RefreshToken(token.RefreshToken);

                api.AccessToken = newToken.AccessToken;
                api.TokenType   = newToken.TokenType;
            }
            PrivateProfile profile = await api.GetPrivateProfileAsync();

            IndexViewModel viewModel = (IndexViewModel)TempData["ViewModel"];

            viewModel.Playlist = (Playlist)TempData["Playlist"];
            viewModel.profile  = profile;


            TempData["Api"]       = api;
            TempData["User"]      = viewModel.profile;
            TempData["Token"]     = token;
            TempData["Auth"]      = auth;
            TempData["ViewModel"] = viewModel;
            TempData["Playlist"]  = (Playlist)TempData["Playlist"];
            return(RedirectToAction("Create", "Playlist"));
        }
Beispiel #22
0
        private async Task GetSpotifyWebAPI()
        {
            if (_token == null)
            {
                OpenAuthenticationDialog();
                return;
            }

            if (_token.IsExpired())
            {
                try
                {
                    if (_api != null)
                    {
                        _api.Dispose();
                    }
                    _api   = null;
                    _token = await _authorizationCodeAuth.RefreshToken(_token.RefreshToken ?? _refreshToken);
                }
                catch
                {
                    // ignored
                }
            }

            if (_api == null)
            {
                try
                {
                    _api = new SpotifyWebAPI
                    {
                        AccessToken = _token.AccessToken,
                        TokenType   = _token.TokenType
                    };
                }
                catch (Exception)
                {
                    _api = null;
                    _authorizationCodeAuth.Stop();
                }
            }
        }
Beispiel #23
0
        private async Task RefreshAccessToken()
        {
            try
            {
                var token = await auth.RefreshToken(refreshToken);

                if (token.HasError())
                {
                    refreshToken = null;
                    System.Diagnostics.Debug.Write("Bad token\r\n");
                    Authorize();
                    return;
                }
                UpdateAccessToken(token);
            }
            catch (Exception e)
            {
                initExcpt = e;
            }
        }
        private static async Task RefreshSpotifyToken()
        {
            var token = await s_SpotifyAuth.RefreshToken(s_SpotifyToken.RefreshToken);

            if (!string.IsNullOrEmpty(token.Error))
            {
                Log.Error(token.Error);
                Log.Error(token.ErrorDescription);
            }

            if (string.IsNullOrEmpty(token.RefreshToken))
            {
                Log.Debug("Token refresh is null");
                token.RefreshToken = s_SpotifyToken.RefreshToken;
            }

            s_SpotifyAPI.AccessToken  = token.AccessToken;
            s_SpotifyAPI.TokenType    = token.TokenType;
            s_SpotifyToken.CreateDate = DateTime.Now;
            s_SpotifyToken            = token;
        }
        //returns you to the create playlist view
        public async Task <ActionResult> Create()
        {
            if ((Playlist)TempData["Playlist"] == null)
            {
                return(RedirectToAction("NoItemSelected", "Error"));
            }

            IndexViewModel        viewModel = (IndexViewModel)TempData["ViewModel"];
            Token                 userToken = (Token)TempData["Token"];
            AuthorizationCodeAuth userAuth  = (AuthorizationCodeAuth)TempData["Auth"];

            viewModel.profile      = (PrivateProfile)TempData["User"];
            viewModel.api          = (SpotifyWebAPI)TempData["Api"];
            viewModel.Playlist     = (Playlist)TempData["Playlist"];
            viewModel.PlaylistURIs = (List <string>)TempData["PlaylistURIs"];

            Console.WriteLine(viewModel.PlaylistURIs);

            if (viewModel.profile != null)
            {
                if (userToken.IsExpired())
                {
                    Token newToken = await userAuth.RefreshToken(userToken.RefreshToken);

                    viewModel.api.AccessToken = newToken.AccessToken;
                    viewModel.api.TokenType   = newToken.TokenType;
                }
            }

            TempData["PlaylistURIs"] = (List <string>)TempData["PlaylistURIs"];
            TempData["Api"]          = viewModel.api;
            TempData["User"]         = viewModel.profile;
            TempData["Token"]        = userToken;
            TempData["Auth"]         = userAuth;
            TempData["ViewModel"]    = viewModel;
            TempData["Playlist"]     = viewModel.Playlist;
            TempData["isFromIndex"]  = false;
            return(View(viewModel));
        }
Beispiel #26
0
    public async Task _refreshtoken(string codeToken)
    {
        initialized = false;
        if (_spotify == null)
        {
            _spotify = new SpotifyWebAPI();
        }
        AuthorizationCodeAuth auth = getAuth();
        Token token = await auth.RefreshToken(codeToken);

        _spotify.AccessToken = token.AccessToken;
        _spotify.TokenType   = token.TokenType;

        if (token.HasError())
        {
            Console.WriteLine(token.Error + " - " + token.ErrorDescription);
        }
        else
        {
            initialized = true;
        }
    }
Beispiel #27
0
        /// <summary>
        /// Fetch the current playback status from the Spotify Web API.
        /// Writes out the playback status to a flat keyvale representations as FieldName=FieldValue\r\n
        /// so it can be easily parsed
        /// </summary>
        /// <param name="opts_">CLI arguments</param>
        /// <returns>1 for errors, 0 otherwise</returns>
        static int RunStatus(Status opts_)
        {
            SysConsole.WriteLine("Fetching current playback status");

            var auth    = new AuthorizationCodeAuth(opts_.ClientId, opts_.ClientSecret, string.Empty, string.Empty);
            var refresh = auth.RefreshToken(opts_.RefreshToken);

            if (!refresh.Wait(10000))
            {
                SysConsole.WriteLine("Timeout when refreshing token");
                return(1);
            }

            var token = refresh.Result;
            var api   = new SpotifyWebAPI
            {
                AccessToken = token.AccessToken,
                TokenType   = token.TokenType,
            };

            Dump(api.GetPlayback());

            return(0);
        }
        public async Task <ActionResult> CreatePlaylist(string inputId, bool isTrack, int range, int numberOfTracks)
        {
            IndexViewModel viewModel = new IndexViewModel();

            viewModel.profile = (PrivateProfile)TempData["User"];
            viewModel.api     = (SpotifyWebAPI)TempData["Api"];
            Token userToken = (Token)TempData["Token"];
            AuthorizationCodeAuth userAuth = (AuthorizationCodeAuth)TempData["Auth"];

            if (userToken != null)
            {
                if (userToken.IsExpired())
                {
                    Token newToken = await userAuth.RefreshToken(userToken.RefreshToken);

                    viewModel.api.AccessToken = newToken.AccessToken;
                    viewModel.api.TokenType   = newToken.TokenType;
                }
            }

            viewModel.isTrack = isTrack;

            Token token = await auth.GetToken();

            _spotify = new SpotifyWebAPI()
            {
                AccessToken = token.AccessToken,
                TokenType   = token.TokenType
            };

            string         artistId       = inputId;
            List <string>  trackArtistIds = new List <string>();
            SeveralArtists relatedArtists = new SeveralArtists();

            List <SeveralArtists> relatedArtistsLists = new List <SeveralArtists>();

            //if the search item was a track
            //get all the artists from that track
            //then get all the related artists for those artists
            //then create the playlsit
            if (isTrack)
            {
                viewModel.searchedTrack = _spotify.GetTrack(inputId);
                artistId               = viewModel.searchedTrack.Artists[0].Id;
                viewModel.title        = viewModel.searchedTrack.Name + " Playlist";
                viewModel.trackArtists = displayArtistsNames(viewModel.searchedTrack);
                viewModel.imageUrl     = viewModel.searchedTrack.Album.Images[1].Url;

                relatedArtists.Artists = new List <FullArtist>();
                int i = 0;
                foreach (var artist in viewModel.searchedTrack.Artists)
                {
                    relatedArtistsLists.Add(_spotify.GetRelatedArtists(artist.Id));
                    relatedArtistsLists[i].Artists.Insert(0, _spotify.GetArtist(artist.Id));
                    i++;
                }

                viewModel.Playlist     = getPlaylistFromTrack(relatedArtistsLists, numberOfTracks, range, viewModel.searchedTrack.Id);
                viewModel.trackLengths = (Dictionary <string, string>)TempData["TrackLengths"];
            }
            //if the search item was an artist, get the related artists, and create a playlist
            else
            {
                viewModel.searchedArtist = _spotify.GetArtist(artistId);
                viewModel.title          = viewModel.searchedArtist.Name + " Playlist";
                viewModel.imageUrl       = viewModel.searchedArtist.Images[1].Url;

                relatedArtists = _spotify.GetRelatedArtists(artistId);
                relatedArtists.Artists.Insert(0, (_spotify.GetArtist(artistId)));
                viewModel.Playlist     = getPlaylistFromArtist(relatedArtists, numberOfTracks, range);
                viewModel.trackLengths = (Dictionary <string, string>)TempData["TrackLengths"];
            }

            TempData["PlaylistURIs"] = (List <string>)TempData["PlaylistURIs"];

            TempData["Playlist"]  = viewModel.Playlist;
            TempData["Token"]     = userToken;
            TempData["Auth"]      = userAuth;
            TempData["ViewModel"] = viewModel;
            return(RedirectToAction("Create"));
        }
        public async Task <ActionResult> Index(IndexViewModel viewModel)
        {
            TempData["Playlist"]  = null;
            viewModel.isFromIndex = true;
            viewModel.profile     = (PrivateProfile)TempData["User"];
            viewModel.api         = (SpotifyWebAPI)TempData["Api"];
            Token token = (Token)TempData["Token"];
            AuthorizationCodeAuth auth = (AuthorizationCodeAuth)TempData["Auth"];

            if (token != null)
            {
                if (token.IsExpired())
                {
                    Token newToken = await auth.RefreshToken(token.RefreshToken);

                    viewModel.api.AccessToken = newToken.AccessToken;
                    viewModel.api.TokenType   = newToken.TokenType;
                }

                CursorPaging <PlayHistory> histories = viewModel.api.GetUsersRecentlyPlayedTracks(20);
                Paging <FullArtist>        artists   = viewModel.api.GetUsersTopArtists(TimeRangeType.ShortTerm, 20);

                //creates a random list from 0 to the number of recent tracks and 0 to recent artists
                //then shuffled to be used to display random recent artists and tracks
                //did the same thing for both for the case that there are not 20 recent artists or tracks to get
                //the lists might then be different sizes and could throw an index out of bounds error
                Random     rand            = new Random();
                List <int> randArtistNumbs = new List <int>();
                List <int> randTrackNumbs  = new List <int>();

                for (int i = 0; i < artists.Items.Count; i++)
                {
                    randArtistNumbs.Add(i);
                }
                for (int i = 0; i < histories.Items.Count; i++)
                {
                    randTrackNumbs.Add(i);
                }

                //shuffles the list of artist numbers
                int n = randArtistNumbs.Count;
                while (n > 1)
                {
                    n--;
                    int k    = rand.Next(n + 1);
                    int temp = randTrackNumbs[k];
                    randTrackNumbs[k] = randTrackNumbs[n];
                    randTrackNumbs[n] = temp;
                }

                //shuffle list of track numbers
                int m = randTrackNumbs.Count;
                while (m > 1)
                {
                    m--;
                    int k    = rand.Next(m + 1);
                    int temp = randTrackNumbs[k];
                    randTrackNumbs[k] = randTrackNumbs[m];
                    randTrackNumbs[m] = temp;
                }

                //adds up to 5 recent artists to the top artists view property
                for (int i = 0; i < 5; i++)
                {
                    if (artists.Items[randArtistNumbs[i]] != null)
                    {
                        viewModel.topArtists.Add(artists.Items[randArtistNumbs[i]]);
                    }
                }
                //adds non duplicate tracks to the recent tracks property
                viewModel.recentTracks = new Playlist();
                int count = 0;
                while (viewModel.recentTracks.TrackList.Count < 5 && count < randTrackNumbs.Count)
                {
                    string trackId = histories.Items[randTrackNumbs[count]].Track.Id;
                    if (!viewModel.recentTracks.hasTrack(trackId))
                    {
                        viewModel.recentTracks.TrackList.Add(viewModel.api.GetTrack(trackId));
                    }
                    count++;
                }
            }

            ViewBag.FlashMessage = (string)TempData["FlashMessage"];

            if (TempData["isError"] != null)
            {
                ViewBag.isError = (bool)TempData["isError"];
            }

            TempData["User"]        = viewModel.profile;
            TempData["Api"]         = viewModel.api;
            TempData["Token"]       = token;
            TempData["Auth"]        = auth;
            TempData["isFromIndex"] = true;
            TempData["ViewModel"]   = viewModel;
            return(View(viewModel));
        }