示例#1
0
        private static SpotifyWebAPI GetWebClient(SpotifyUser oSpotifyUser)
        {
            AutorizationCodeAuth oAuth = new AutorizationCodeAuth()
            {
                ClientId    = _ClientPublic,
                RedirectUri = _RedirectUrl,
                Scope       = Scope.UserReadPrivate | Scope.UserReadPrivate | Scope.PlaylistReadPrivate | Scope.UserLibraryRead | Scope.UserReadPrivate | Scope.UserFollowRead
            };

            //oAuth.StartHttpServer();//Not sure if this is needed or not but what the hell why not!

            if (oSpotifyUser.AccessToken.AccessExpired)//The user has authorized us and was tokenized but the temp access token has expired
            {
                Token oToken = oAuth.RefreshToken(oSpotifyUser.RefreshToken.Code, _ClientPrivate);
                if (oToken.Error == null)
                {
                    oSpotifyUser.UpdateUserWithToken(oToken);
                }
            }



            //oAuth.StopHttpServer();
            SpotifyWebAPI oWebClient = new SpotifyWebAPI()
            {
                AccessToken = oSpotifyUser.AccessToken.Code,
                TokenType   = oSpotifyUser.AccessToken.TokenType,
                UseAuth     = true
            };

            return(oWebClient);
        }
        /// <summary>
        /// fait l authentification pour Spotify, retourne True si l operation reussi
        /// et false sinon
        /// </summary>
        /// <returns>Task<bool></returns>
        public async Task <bool> RunAuthentication()
        {
            WebAPIFactory webApiFactory = new WebAPIFactory(
                "http://localhost",
                7000,
                "8554a963221c499fa356f8b4a95e79f8",
                Scope.UserReadPrivate | Scope.UserReadEmail | Scope.PlaylistReadPrivate | Scope.UserLibraryRead |
                Scope.UserReadPrivate | Scope.UserFollowRead | Scope.UserReadBirthdate | Scope.UserTopRead | Scope.PlaylistReadCollaborative |
                Scope.UserReadRecentlyPlayed | Scope.UserReadPlaybackState | Scope.UserModifyPlaybackState);

            try
            {
                m_spotifyWebAPI = await webApiFactory.GetWebApi();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            if (m_spotifyWebAPI == null)
            {
                return(false);
            }
            return(true);
        }
示例#3
0
        /// <summary>
        /// This method for initialize spotify class.
        /// </summary>
        public static void Init()
        {
            var request = (HttpWebRequest)WebRequest.Create(Const.TokenUrl);
            var body    = "grant_type=client_credentials";
            var data    = Encoding.ASCII.GetBytes(body);

            request.Method        = "POST";
            request.ContentType   = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            request.Headers.Add("Authorization", Const.AuthHeader);

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            var tokenResponse = JsonConvert.DeserializeObject <TokenResponse>(responseString);

            _api = new SpotifyWebAPI
            {
                AccessToken = tokenResponse.access_token,
                TokenType   = tokenResponse.token_type
            };
        }
示例#4
0
        public async Task <IActionResult> GetSpotifyAlt(string title, string artist)
        {
            AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
            var keyVaultClient = new KeyVaultClient(
                new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback)
                );
            var spotifyID = await keyVaultClient.GetSecretAsync("https://wakeyvault.vault.azure.net/secrets/appSettings--connectionSettings--spotifyId/69cdf003254f4b2e81a5ce90dffe80ab").ConfigureAwait(false);

            Console.Write(spotifyID);
            var spotifySecret = await keyVaultClient.GetSecretAsync("https://wakeyvault.vault.azure.net/secrets/appSettings--connectionStrings--spotifySecret/49de24c1d0a44edcb4c7e9379b49d1a4").ConfigureAwait(false);

            CredentialsAuth auth  = new CredentialsAuth(spotifyID.Value, spotifySecret.Value);
            Token           token = await auth.GetToken();

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

            SearchItem searchItem = api.SearchItems(title, SearchType.Track);


            return(Ok(searchItem.Tracks.Items[1]));
        }
        public Task AuthorizeAsync()
        {
            var tcs = new TaskCompletionSource <bool>();

            var auth = new ImplicitGrantAuth(ClientId, "http://localhost:4002", "http://localhost:4002", Scope.UserReadPrivate | Scope.PlaylistReadPrivate | Scope.UserLibraryRead |
                                             Scope.PlaylistModifyPrivate | Scope.PlaylistModifyPublic | Scope.PlaylistReadCollaborative);

            auth.AuthReceived += async(_, payload) =>
            {
                auth.Stop();

                spotify = new SpotifyWebAPI()
                {
                    TokenType   = payload.TokenType,
                    AccessToken = payload.AccessToken
                };

                IsAuthorized = true;
                var profile = await spotify.GetPrivateProfileAsync();

                Profile = new Profile
                {
                    Id       = profile.Id,
                    Username = profile.DisplayName
                };

                tcs.SetResult(true);
            };

            auth.Start();
            auth.OpenBrowser();

            return(tcs.Task);
        }
示例#6
0
        public async Task <ActionResult> GenerateTokens()
        {
            CredentialsAuth cred = new CredentialsAuth(Private.Private.Spotify_clientId, Private.Private.Spotify_clientSecret);

            Token token = await cred.GetToken();


            string artistId = "5tWbDIXx7HTHSwBZNJrRgQ";

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

            var result = api.GetArtist(artistId);

            var result2 = api.GetArtistsTopTracks(artistId, "US");

            int popularity = result2.Tracks[1].Popularity;

            foreach (var song in result2.Tracks)
            {
            }



            return(RedirectToAction("About"));
        }
示例#7
0
        public List <Disk> GetTop50ByGenre()
        {
            var auth  = new CredentialsAuth(CLIENTID, SECRET);
            var token = auth.GetToken().Result;
            var api   = new SpotifyWebAPI()
            {
                TokenType = token.TokenType, AccessToken = token.AccessToken
            };
            var         genres = Enum.GetValues(typeof(EDiskGenre));
            List <Disk> disks  = new List <Disk>();


            //search the top 50 albums by genre and add in the disk list
            foreach (var g in genres)
            {
                SearchItem search = api.SearchItems(g.ToString(), SearchType.Album, 50);

                foreach (var sDisk in search.Albums.Items)
                {
                    decimal value       = Convert.ToDecimal(string.Format("{0:0.##}", new Random().NextDouble() * 10));
                    var     description = $"Released Date: {sDisk.ReleaseDate} | URI: {sDisk.Uri} | Album Type: {sDisk.AlbumType}  | Artists: {string.Join<string>(",", sDisk.Artists.Select(x=> x.Name).ToArray())}";
                    disks.Add(new Disk(sDisk.Name, description, value, (EDiskGenre)g, sDisk.Images.FirstOrDefault().Url));
                }
            }

            return(disks);
        }
示例#8
0
        public async Task <SpotifyWebAPI> ConnectToSpotifyAsync(SpotifyWebAPI _spotify)
        {
            WebAPIFactory webApiFactory = new WebAPIFactory(
                "http://localhost",
                44333,
                SPOTIFY_API_KEY,
                Scope.PlaylistModifyPrivate | Scope.PlaylistModifyPublic | Scope.Streaming | Scope.UserFollowModify |
                Scope.UserFollowRead | Scope.UserLibraryRead | Scope.UserReadPrivate | Scope.UserTopRead,
                TimeSpan.FromSeconds(20));

            try
            {
                //This will open the user's browser and returns once
                //the user is authorized.
                _spotify = await webApiFactory.GetWebApi();
            }
            catch (Exception ex)
            {
                ViewBag.AuthError = ex.Message;
            }

            if (_spotify == null)
            {
                throw new NullReferenceException();
            }

            return(await Task.FromResult <SpotifyWebAPI>(_spotify));
        }
示例#9
0
        public AuthUtils()
        {
            _httpClient = new HttpClient();
            _auth       = new TokenSwapAuth("http://40.68.75.212:80/spotify/index.php", "http://40.68.75.212:80/",
                                            Scope.PlaylistReadPrivate | Scope.UserReadRecentlyPlayed | Scope.UserReadPrivate | Scope.AppRemoteControl |
                                            Scope.UserReadCurrentlyPlaying | Scope.UserReadPlaybackState | Scope.Streaming | Scope.UserModifyPlaybackState)
            {
                ShowDialog = !Preferences.Get("AutoLogin", false)
            };


            _auth.AuthReceived += async(sender, response) =>
            {
                _lastToken = await _auth.ExchangeCodeAsync(response.Code);

                _api = new SpotifyWebAPI()
                {
                    TokenType   = _lastToken.TokenType,
                    AccessToken = _lastToken.AccessToken
                };
            };
            _auth.OnAccessTokenExpired += async(sender, e) =>
                                          _api.AccessToken = (await _auth.RefreshAuthAsync(_lastToken.RefreshToken)).AccessToken;



            ServerUri = _auth.GetUri();
            _auth.Start();
        }
        public async void Init()
        {
            var webApiFactory = new WebAPIFactory(
                "http://localhost",
                8000,
                ConfigurationManager.AppSettings["SpotifyClientID"],
                Scope.UserReadPrivate,
                TimeSpan.FromSeconds(20)
                );

            try
            {
                //This will open the user's browser and returns once
                //the user is authorized.
                _spotify = await webApiFactory.GetWebApi();

                _user            = _spotify.GetPrivateProfile();
                tracksToDownload = new List <string>();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            if (_spotify == null)
            {
                return;
            }
        }
示例#11
0
 public SpotifyRunConfig(LavaRestClient lavaRest, SpotifyWebAPI api, SpotifyConfig config, SpotifyTrackConverter trackConverter)
 {
     this.LavaRest       = lavaRest;
     this.Api            = api;
     this.Config         = config;
     this.TrackConverter = trackConverter;
 }
        public async Task <string> Songs(string query)
        {
            var auth = new ClientCredentialsAuth
            {
                ClientId     = "9d8c56fb47664994958f336728af9a6d",
                ClientSecret = "5da8736095c44009802957350d0aae62",
                Scope        = Scope.UserModifyPlaybackState
            };
            var token = await auth.DoAuthAsync();

            var client = new SpotifyWebAPI
            {
                TokenType   = token.TokenType,
                AccessToken = token.AccessToken,
                UseAuth     = true
            };

            var results = await client.SearchItemsAsync(query, SearchType.Track);

            var str = string.Empty;

            foreach (var track in results.Tracks.Items)
            {
                str += " " + track.Name;
            }

            return(str);
        }
示例#13
0
        private async void RunAuthentication()
        {
            WebAPIFactory webApiFactory = new WebAPIFactory(
                "http://localhost",
                8000,
                "26d287105e31491889f3cd293d85bfea",
                Scope.UserReadPrivate | Scope.UserReadEmail | Scope.PlaylistReadPrivate | Scope.UserLibraryRead |
                Scope.UserReadPrivate | Scope.UserFollowRead | Scope.UserReadBirthdate | Scope.UserTopRead | Scope.PlaylistReadCollaborative);

            try
            {
                _spotify = await webApiFactory.GetWebApi();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            if (_spotify == null)
            {
                return;
            }


            InitialSetup();
        }
        public void AllLibraryToPlaylist(SpotifyWebAPI spotify)
        {
            //saves all track ids to list

            var tracksUri = HelperFunctions.GetSavedTracksUris(spotify);

            Console.WriteLine($"Number of tracks: {tracksUri.Count}");


            // gets user id
            PrivateProfile user = spotify.GetPrivateProfile();

            if (user.HasError())
            {
                Console.WriteLine("\n\nProfileID not read properly. Cannot create playlist.\n\n");
            }
            var userId = user.Id;

            //creates new empty playlist
            FullPlaylist playlist = spotify.CreatePlaylist(userId, "Library to Playlist");

            //error notification
            Console.WriteLine(playlist.HasError()
                ? "/n/nError while creating playlist.\n\n"
                : "Playlist created and named \"Library to Playlist\"");


            //inserts playlist tracks to playlist
            HelperFunctions.InsertTracks(spotify, tracksUri, playlist.Id);

            Console.WriteLine("\nWarning: there may be less songs added to playlist than are present in library, because they might be not available");
            Console.WriteLine("\nTask ended. Press any key to exit. . .");
        }
        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();
            }
        }
        public static async Task <ServiceResult <string> > CurrentPlayingsong(SpotifyWebAPI api)
        {
            SimpleCurrentsong currentsong = await api.GetUserCurrentSong();

            var songInfo = "";

            if (currentsong.Item == null)
            {
                return(ServiceResult <string> .Failed("no playing song found"));
            }


            //If the ad was playing we will do nothing
            if (currentsong.currently_playing_type == "ad")
            {
                return(ServiceResult <string> .Failed(songInfo));
            }


            //for finding lyrics the first Artist is enough
            songInfo += currentsong.Item.Artists.First().Name;


            //if song has something like 'Remasterd' or anything else at the end of it names the lyrics api can not find the actual Lyrics so we eliminate that part
            songInfo += $"- {currentsong.Item.Name.Split('-')[0].Trim()}";
            return(ServiceResult <string> .Success(songInfo));
        }
示例#17
0
        public SearchItem GetSongBySearch(string search, string accessToken)
        {
            SpotifyWebAPI _spotify = GetSpotifyResponseWithAccessToken(accessToken);
            SearchItem    result   = _spotify.SearchItems(search, SearchType.Track);

            return(result);
        }
        public static void InsertTracks(SpotifyWebAPI spotify, List <string> tracksUri, string playlistId)
        {
            Console.WriteLine("Adding tracks to playlist...");
            var position         = 0;
            var howMany          = tracksUri.Count;
            var iterationCounter = 1;

            if (howMany > 100)
            {
                howMany = 100;
            }
            while (true)
            {
                if (howMany * iterationCounter > tracksUri.Count)
                {
                    howMany = tracksUri.Count - 100 * iterationCounter + 100;
                }
                if (position >= tracksUri.Count)
                {
                    break;
                }
                var addTracks = spotify.AddPlaylistTracks(playlistId, tracksUri.GetRange(position, howMany), position);
                if (addTracks.HasError())
                {
                    Console.WriteLine("Error while processing. Breaking.");
                    Console.WriteLine(addTracks.Error.Message);
                    break;
                }
                position += howMany;
                iterationCounter++;
            }
            Console.WriteLine("Tracks added successfully.");
        }
示例#19
0
        //Authenticate the program
        public async Task Authenticate()
        {
            //The server side php code came from here: https://github.com/rollersteaam/spotify-token-swap-php
            webApiFactory = new TokenSwapWebAPIFactory("http://mrhumagames.com/MrhumasMusicOverlay/index.php")
            {
                Scope         = Scope.UserReadCurrentlyPlaying,
                AutoRefresh   = true,
                HostServerUri = "http://localhost:4002/auth",
                Timeout       = 30
            };

            //If the user denied the request
            webApiFactory.OnAuthFailure += (sender, e) =>
            {
                //Let the user know they must accept in order to use the program with Spotify
                MessageBox.Show("You must accept the authentication request in order to use this program with Spotify.");
                authorized = false;
            };

            //If the user accepted the request
            webApiFactory.OnAuthSuccess += (sender, e) =>
            {
                authorized = true;
            };

            try
            {
                api = await webApiFactory.GetWebApiAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Spotify failed to load: " + ex.Message);
            }
        }
        public static PlaylistStatus PlaylistPresenceCheck(SpotifyWebAPI spotify)   //returns ID of playlist named "Library to Playlist"
        {
            Console.WriteLine("Checking playlist \"Library to Playlist\" presence...");
            var playlistStatus = new PlaylistStatus();
            var userId         = spotify.GetPrivateProfile().Id;
            var offset         = 0;

            while (true)
            {
                var userPlaylists = spotify.GetUserPlaylists(userId, 50, offset);
                userPlaylists.Items.ForEach(playlist =>
                {
                    if (playlist.Name == "Library to Playlist" && playlist.Owner.Id == userId)
                    {
                        playlistStatus.PlaylistId = playlist.Id;
                        playlistStatus.IsPresent  = true;
                    }
                });
                if (!userPlaylists.HasNextPage())
                {
                    break;
                }
            }
            return(playlistStatus);
        }
示例#21
0
        public async Task <SpotifyWebAPI> GetApi(string absoultUrl)
        {
            _code = GetBetween(absoultUrl, "?", "&");

            if (_code.Contains("code="))
            {
                if (!passed)
                {
                    passed = true;
                    _token = await SetToken(_code);
                }



                if (_token != null)
                {
                    _api = new SpotifyWebAPI()
                    {
                        TokenType   = _token.TokenType,
                        AccessToken = _token.AccessToken,
                    };
                    return(_api);

                    //CAUSAVA NULL POINTER INIZIALE
                    //if (_api.AccessToken.Length > 1)
                    //{
                    //    return _api;
                    //}
                }
            }

            return(default);
        private static List <string> TracksUriList(SpotifyWebAPI spotify, string playlistId)
        {
            Console.WriteLine("Generating list of playlist tracks uris...");
            var offset    = 0;
            var tracksUri = new List <string>();

            while (true)
            {
                var playlistTracks = spotify.GetPlaylistTracks(playlistId, "next,items(track(uri))", 100, offset);
                if (!playlistTracks.HasError())
                {
                    playlistTracks.Items.ForEach(track =>
                    {
                        tracksUri.Add(track.Track.Uri);
                    });
                    offset += 100;
                    if (!playlistTracks.HasNextPage())
                    {
                        break;
                    }
                }
                else
                {
                    Console.WriteLine(playlistTracks.Error.Status);
                    Console.WriteLine(playlistTracks.Error.Message);
                    break;
                }
            }
            Console.WriteLine("Tracks uris generated successfully.");
            return(tracksUri);
        }
    void Start()
    {
        Debug.Log("Testing SpotifyWebAPI Client...");

        _spotify = new SpotifyWebAPI()
        {
            AccessToken = "BQCbA3-36RXsmkIW9OHVoCjRHrYyCIqTxIQR9E_If3NPw_McHQaFykPSOOEdDa5wjX-9dKIrdZ6SFwD3PDg",
            TokenType   = "Bearer"
        };
        Debug.Log("SpotifyWebInstance() successfully created and connected!");

        AudioAnalysis analysis = _spotify.GetAudioAnalysis("3Hvu1pq89D4R0lyPBoujSv");

        if (analysis == null || analysis.Bars == null)
        {
            Debug.Log("NO AnalysisResults RETURNED!");
            return;
        }
        Debug.Log("AnalysisResults succesfully loaded!");

        Debug.Log("Bars: " + analysis.Bars.Count.ToString());   //Yeay! We just printed a tracks name.
        Debug.Log("Beats: " + analysis.Beats.Count.ToString()); //Yeay! We just printed a tracks name.

        Debug.Log("Prueba Concluida con Exito!!");
    }
示例#24
0
        public Spotify()
        {
            this._api = new SpotifyWebAPI();
            var url    = "http://localhost:4002";
            var scopes = Scope.PlaylistReadPrivate |
                         Scope.PlaylistReadCollaborative |
                         Scope.UserReadPlaybackState |
                         Scope.AppRemoteControl |
                         Scope.UserModifyPlaybackState;

            this._auth = new AuthorizationCodeAuth(
                Encoding.Unicode.GetString(Convert.FromBase64String("MQAwADcAMgA4AGMAZgA0ADEAZgBhADEANAA3ADMAZgA4AGYANAA3AGMAOAAxADcAZABlAGUAZAAzAGMANQBhAA==")),
                Encoding.Unicode.GetString(Convert.FromBase64String("OQA4ADIANAAxAGUANABiADYAMwAxAGIANAAyAGEANABhADQAMgA2ADMAYwAwADQAMAAzAGQANwA4ADgAMABiAA==")),
                url, url, scopes);

            this._auth.AuthReceived += async(sender, payload) =>
            {
                this._auth.Stop();
                if (this._token.IsExpired())
                {
                    this._token = await this._auth.RefreshToken(this._token.RefreshToken);
                }
                this._token = await this._auth.ExchangeCode(payload.Code);

                this._api = new SpotifyWebAPI()
                {
                    TokenType   = this._token.TokenType,
                    AccessToken = this._token.AccessToken
                };
            };

            this._auth.Start();
            this._auth.OpenBrowser();
        }
示例#25
0
        public async Task <bool> Login()
        {
            try
            {
                var url       = ConfigurationManager.AppSettings[@"Url"];
                var porta     = Convert.ToInt32(ConfigurationManager.AppSettings[@"Porta"]);
                var clienteId = ConfigurationManager.AppSettings[@"ClienteIdSpotify"];

                var webApiFactory = new WebAPIFactory(
                    url,
                    porta,
                    clienteId,
                    Scope.UserReadPrivate | Scope.UserReadEmail | Scope.PlaylistReadPrivate | Scope.UserLibraryRead |
                    Scope.UserFollowRead | Scope.UserReadBirthdate | Scope.UserTopRead | Scope.PlaylistReadCollaborative |
                    Scope.UserReadRecentlyPlayed | Scope.UserReadPlaybackState
                    );

                spotifyWebApi = await webApiFactory.GetWebApi();
            }
            catch (Exception ex)
            {
                return(false);
            }

            return(spotifyWebApi != null);
        }
示例#26
0
        private static async void TryConnect()
        {
            try
            {
                _spotify = await _spotifyApiFactory.GetWebApi(true);

                _watcher = new SpotifyWatcher(_spotify);

                //_watcher.PlayStateChanged += SpotifyLocalOnOnPlayStateChange;
                //_watcher.TrackChanged += SpotifyLocalOnOnTrackChange;
                //_watcher.TrackTimeChanged += SpotifyLocalOnOnTrackTimeChange;
                //_watcher.VolumeChanged += SpotifyLocalOnOnVolumeChange;

                _watcher.Tick += SpotifyLocalOnTick;
            }
            catch (Exception ex)
            {
                MessageBox.Show(@"Error authenticating to Spotify API");
                throw;
            }

            if (_spotify == null)
            {
                return;
            }
        }
示例#27
0
        public IList <SpotifyImportListItemInfo> Fetch(SpotifyWebAPI api, string playlistId)
        {
            var result = new List <SpotifyImportListItemInfo>();

            _logger.Trace($"Processing playlist {playlistId}");

            var playlistTracks = _spotifyProxy.GetPlaylistTracks(this, api, playlistId, "next, items(track(name, artists(id, name), album(id, name, release_date, release_date_precision, artists(id, name))))");

            while (true)
            {
                if (playlistTracks?.Items == null)
                {
                    return(result);
                }

                foreach (var playlistTrack in playlistTracks.Items)
                {
                    result.AddIfNotNull(ParsePlaylistTrack(playlistTrack));
                }

                if (!playlistTracks.HasNextPage())
                {
                    break;
                }

                playlistTracks = _spotifyProxy.GetNextPage(this, api, playlistTracks);
            }

            return(result);
        }
示例#28
0
 public SpotifyService()
 {
     _spotify = new SpotifyWebAPI()
     {
         UseAuth = false, // This will disable Authentication
     };
 }
示例#29
0
        public async Task <bool> SearchAlbums(string searchString)
        {
            SpotifyWebAPI api = new SpotifyWebAPI
            {
                AccessToken = BearerToken,
                TokenType   = "Bearer"
            };

            var searchResult = await api.SearchItemsAsync(searchString, SpotifyAPI.Web.Enums.SearchType.Album);

            Albums.Clear();

            if (null != searchResult.Albums)
            {
                if (searchResult.Albums.Items.Count > 0)
                {
                    foreach (var album in searchResult.Albums.Items)
                    {
                        if (album.Images.Count > 0)
                        {
                            if (album.Images[0] is Image)
                            {
                                Console.WriteLine(album.Images[0].Url);
                                var addedAlbum = new MyAlbum {
                                    Url = album.Images[0].Url, Name = album.Name, ID = album.Id
                                };
                                Albums.Add(addedAlbum);
                            }
                        }
                    }
                }
            }

            return(true);
        }
示例#30
0
        public static IEnumerable <SpotifyPlaylist> GetUsersFollowedPlaylists(SpotifyUser oSpotifyUser)
        {
            List <SpotifyPlaylist> Playlists = new List <SpotifyPlaylist>();

            using (SpotifyWebAPI oWebCLient = GetWebClient(oSpotifyUser))
            {
                Paging <SimplePlaylist> oPaging = oWebCLient.GetUserPlaylists(oSpotifyUser.Name);

                foreach (SimplePlaylist oSimplePlaylist in oPaging.Items)
                {
                    if (!oSimplePlaylist.Owner.Id.Equals(oSpotifyUser.Name))
                    {
                        Dictionary <int, SpotifyTrack> oTracks = GetTracksForPlaylist(oWebCLient, oSimplePlaylist, oSpotifyUser);
                        Playlists.Add(new SpotifyPlaylist(oSimplePlaylist, oTracks));
                    }
                }
                while (oPaging.Next != null)
                {
                    oPaging = oWebCLient.DownloadData <Paging <SimplePlaylist> >(oPaging.Next);
                    foreach (SimplePlaylist oSimplePlaylist in oPaging.Items)
                    {
                        if (!oSimplePlaylist.Owner.Id.Equals(oSpotifyUser.Name))
                        {
                            Dictionary <int, SpotifyTrack> oTracks = GetTracksForPlaylist(oWebCLient, oSimplePlaylist, oSpotifyUser);
                            Playlists.Add(new SpotifyPlaylist(oSimplePlaylist, oTracks));
                        }
                    }
                }
            }
            return(Playlists);
        }
示例#31
0
        public SpotifyApi(string pluginDir = null)
        {
            var pluginDirectory = pluginDir ?? Directory.GetCurrentDirectory();
            CacheFolder = Path.Combine(pluginDirectory, "Cache");

            // Create the cache folder, if it doesn't already exist
            if (!Directory.Exists(CacheFolder))
                Directory.CreateDirectory(CacheFolder);

            _localSpotify = new SpotifyLocalAPI();
            _localSpotify.OnTrackChange += (o, e) => CurrentTrack = e.NewTrack;
            _localSpotify.OnPlayStateChange += (o, e) => IsPlaying = e.Playing;
            ConnectToSpotify();

            _spotifyApi = new SpotifyWebAPI
            {
                UseAuth = false
            };
        }
示例#32
0
        void _auth_OnResponseReceivedEvent(Token token, string state)
        {
            _auth.StopHttpServer();

            if (state != "XSS")
            {
                MessageBox.Show("Wrong state received.", "SpotifyWeb API Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (token.Error != null)
            {
                MessageBox.Show("Error: " + token.Error, "SpotifyWeb API Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            _spotify = new SpotifyWebAPI
            {
                UseAuth = true,
                AccessToken = token.AccessToken,
                TokenType = token.TokenType
            };
            InitialSetup();
        }
示例#33
0
        private SpotifyWebAPI HandleSpotifyResponse(string state, Token token)
        {
            if (state != _xss)
                throw new SpotifyWebApiException($"Wrong state '{state}' received.");

            if (token.Error != null)
                throw new SpotifyWebApiException($"Error: {token.Error}");

            var spotifyWebApi = new SpotifyWebAPI
            {
                UseAuth = true,
                AccessToken = token.AccessToken,
                TokenType = token.TokenType
            };

            return spotifyWebApi;
        }
示例#34
0
 private void InitSpotifyWebAPI()
 {
     _spotify = new SpotifyWebAPI
     {
         UseAuth = true,
         AccessToken = Settings.Default.Token,
         TokenType = Settings.Default.TokenType,
     };
 }
        private void authenticate(Token token)
        {
            _spotifyWeb = new SpotifyWebAPI
            {
                UseAuth = true,
                AccessToken = token.AccessToken,
                TokenType = token.TokenType
            };

            ConnectedWeb = true;
        }
        private static SpotifyWebAPI GetWebClient(SpotifyUser oSpotifyUser)
        {
            AutorizationCodeAuth oAuth = new AutorizationCodeAuth()
            {
                ClientId = _ClientPublic,
                RedirectUri= _RedirectUrl,
                Scope = Scope.UserReadPrivate | Scope.UserReadPrivate | Scope.PlaylistReadPrivate | Scope.UserLibraryRead |  Scope.UserReadPrivate | Scope.UserFollowRead
            };

            //oAuth.StartHttpServer();//Not sure if this is needed or not but what the hell why not!

            if (oSpotifyUser.AccessToken.AccessExpired)//The user has authorized us and was tokenized but the temp access token has expired
            {
                Token oToken = oAuth.RefreshToken(oSpotifyUser.RefreshToken.Code, _ClientPrivate);
                if (oToken.Error == null)
                {
                    oSpotifyUser.UpdateUserWithToken(oToken);
                }
            }

            //oAuth.StopHttpServer();
            SpotifyWebAPI oWebClient = new SpotifyWebAPI()
            {
                AccessToken = oSpotifyUser.AccessToken.Code,
                TokenType = oSpotifyUser.AccessToken.TokenType,
                UseAuth = true
            };

            return oWebClient;
        }
        private static Dictionary<int, SpotifyTrack> GetTracksForPlaylist(SpotifyWebAPI oWebCLient, SimplePlaylist oSimplePlaylist, SpotifyUser oSpotifyUser)
        {
            Dictionary<int, SpotifyTrack> oTracks = new Dictionary<int, SpotifyTrack>();
            Paging<PlaylistTrack> oPagingPlaylistTracks = oWebCLient.GetPlaylistTracks(oSimplePlaylist.Owner.Id, oSimplePlaylist.Id, market:"");
            int iPos = 0;
            foreach (PlaylistTrack oPlaylistTrack in oPagingPlaylistTracks.Items)
            {
                List<SpotifyArtist> oArtists = new List<SpotifyArtist>();
                oArtists.AddRange(GetArtistsForTrack(oPlaylistTrack));
                if (oPlaylistTrack.Track.Id == null)
                {
                    if (oPlaylistTrack.Track.Name != null && oPlaylistTrack.Track.Type != null)
                    {//Issues with some tracks having null id properties and the only way to deal with that is to try to hash an id myself
                        oPlaylistTrack.Track.Id = HashSlingingSlasher.HashString(oSimplePlaylist.Name + oSimplePlaylist.Type);
                    }

                }
                oTracks.Add(iPos, new SpotifyTrack(oPlaylistTrack, oArtists));
                iPos++;
            }
            while (oPagingPlaylistTracks.Next != null)
            {
                oPagingPlaylistTracks = oWebCLient.DownloadData<Paging<PlaylistTrack>>(oPagingPlaylistTracks.Next);
                foreach (PlaylistTrack oPlaylistTrack in oPagingPlaylistTracks.Items)
                {
                    List<SpotifyArtist> oArtists = new List<SpotifyArtist>();
                    oArtists.AddRange(GetArtistsForTrack(oPlaylistTrack));
                    if (oPlaylistTrack.Track.Id == null)
                    {
                        if (oPlaylistTrack.Track.Name != null && oPlaylistTrack.Track.Type != null)
                        {//Issues with some tracks having null id properties and the only way to deal with that is to try to hash an id myself
                            oPlaylistTrack.Track.Id = HashSlingingSlasher.HashString(oSimplePlaylist.Name + oSimplePlaylist.Type);
                        }

                    }
                    oTracks.Add(iPos, new SpotifyTrack(oPlaylistTrack, oArtists));
                    iPos++;
                }
            }

            return oTracks;
        }
示例#38
0
		public ActionResult Result(string Artist)
		{
			/* Most of this uses the Spotify-API */
			var result = new Search();

			// new authorization so we can search without restrictions
			var auth = new ClientCredentialsAuth()
			{
				//Your client Id
				ClientId = "c99b06725565434cab71dae37925376c",
				ClientSecret = "ccb0bc68f03647749a970bb8987b29b0",
				Scope = Scope.UserReadPrivate
			};

			// get a token for the spotifywebapi object
			Token token = auth.DoAuth();

			// create the new spotify web api object
			var spotify = new SpotifyWebAPI()
			{
				TokenType = token.TokenType,
				AccessToken = token.AccessToken,
				UseAuth = false
			};

			// search for the artist specified by the user and get the results
			var artistResult = spotify.SearchItems(Artist, SearchType.Artist);

			string albumID;
			FullAlbum albumResult;

			// create a new empty sorted list
			result.sortedList = new System.Collections.Generic.SortedList<FullAlbum, int>(new AlbumPopularityComparer());

			// make sure search returned results
			if (artistResult.Artists.Items.Count > 0)
			{
				// get the first artist returned
				var artistObj = artistResult.Artists.Items[0];
				
				// search for the albums of that artist
				var albums = spotify.GetArtistsAlbums(artistObj.Id, limit: 300);
				bool albumInList = false;
				// since the album search only returns a simple album with no
				// popularity variable, we must search for the album by ID. This
				// gives us a FullAlbum object with the popularity variable.
				for (int i = 0; i < albums.Items.Count; ++i)
				{
					albumID = albums.Items[i].Id;
					albumResult = spotify.GetAlbum(albumID);

					// if list empty, go ahead and add the first album
					if(result.sortedList.Count > 0)
					{
						// check to see if the album is already in the list
						for (int j = 0; j < result.sortedList.Count; ++j)
						{
							// if it IS in the list
							if (albumResult.Name == result.sortedList.ElementAt(j).Key.Name)
							{
								// set to true
								albumInList = true;
							}
						}

						// now that we know if the album is in the list already or not
						// we can decide if we need to add the album
						if (albumInList != true)
						{
							// The code above was not perfect and this helps
							// double check that the album object is not already in the list
							if (result.sortedList.ContainsKey(albumResult) != true)
							{
								result.sortedList.Add(albumResult, albumResult.Popularity);
							}
						}

						// reset to false
						albumInList = false;
					} // if
					else
					{	// add the first album
						result.sortedList.Add(albumResult, albumResult.Popularity);
					}
				} // for

				// set the artist object in the model to the artist object
				// from the search
				result.Artist = artistObj;
			} // if
			else
			{
				// no result found, go to error page
				return RedirectToAction("errorPage");
			}

			return View(result);
			//return View();
		}
示例#39
0
        public RedirectResult Authorized(string code, string error, string state)
        {
            if (error != null)
            {
                throw new Exception(error);
            }
            AutorizationCodeAuth oAutorizationCodeAuth = new AutorizationCodeAuth()
            {
                //Your client Id
                ClientId = this._oSCCManager.SCC_PUBLIC_ID,
                //Set this to localhost if you want to use the built-in HTTP Server
                RedirectUri = this._oSCCManager.RedirectUrl,
                //How many permissions we need?
                Scope = Scope.UserReadPrivate | Scope.UserReadPrivate | Scope.PlaylistReadPrivate | Scope.UserLibraryRead | Scope.UserReadPrivate | Scope.UserFollowRead
            };

            Token oToken;
            oToken = oAutorizationCodeAuth.ExchangeAuthCode(code, this._oSCCManager.SCC_PRIVATE_ID);
            //oToken = oAutorizationCodeAuth.RefreshToken(response.Code, SCC_PRIVATE_ID);

            SpotifyWebAPI oSpotifyWebApi = new SpotifyWebAPI()
            {
                AccessToken = oToken.AccessToken,
                TokenType = oToken.TokenType,
                UseAuth = true
            };

            PrivateProfile oPrivateProfile = oSpotifyWebApi.GetPrivateProfile();

            SpotifyUser oSpotifyUser = this._oSCCManager.AddSpotifyUser(oPrivateProfile, code, oToken);
            // ViewBag.RedirectUrl = string.Format("/SpotifyChangeControl/Change/Index?UserGuid={0}&SessionGuid={1}", oSpotifyUser.UserGuid, oSpotifyUser.SessionGuid);

            if (!this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("UserGuid"))
            {
                HttpCookie hcUserGuid = new HttpCookie("UserGuid");
                hcUserGuid.Value = oSpotifyUser.UserGuid;
                this.ControllerContext.HttpContext.Response.Cookies.Add(hcUserGuid);
                this.ControllerContext.HttpContext.Response.Cookies.Add(hcUserGuid);
            }
            else
            {
                this.ControllerContext.HttpContext.Request.Cookies.Get("UserGuid").Value = oSpotifyUser.UserGuid;
            }

            if (!this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("SessionGuid"))
            {
                HttpCookie hcSessionGuid = new HttpCookie("SessionGuid");
                hcSessionGuid.Value = oSpotifyUser.SessionGuid;
                this.ControllerContext.HttpContext.Response.Cookies.Add(hcSessionGuid);

            }
            else
            {
                this.ControllerContext.HttpContext.Request.Cookies.Get("SessionGuid").Value = oSpotifyUser.SessionGuid;
            }

            return new RedirectResult(string.Format("/SpotifyChangeControl/Change/Index", oSpotifyUser.UserGuid, oSpotifyUser.SessionGuid));
        }
示例#40
0
        private async void RunAuthentication()
        {
            WebAPIFactory webApiFactory = new WebAPIFactory(
                "http://localhost",
                8000,
                "26d287105e31491889f3cd293d85bfea",
                Scope.UserReadPrivate | Scope.UserReadEmail | Scope.PlaylistReadPrivate | Scope.UserLibraryRead |
                Scope.UserReadPrivate | Scope.UserFollowRead | Scope.UserReadBirthdate | Scope.UserTopRead | Scope.PlaylistReadCollaborative);

            try
            {
                _spotify = await webApiFactory.GetWebApi();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            if (_spotify == null)
                return;

            InitialSetup();
        }