public async Task <List <SimplePlaylist> > RefreshPlaylists() { Playlists.Clear(); Paging <SimplePlaylist> response = await Spotify.Playlists.GetUsers(Profile.Id); var all = await Spotify.PaginateAll(response); foreach (var item in all) { Playlists.Add(item); } return(Playlists); }
public static async Task <System.Collections.Generic.IList <SpotifyAPI.Web.SimplePlaylist> > getAllPlayerList() { var json = await File.ReadAllTextAsync(CredentialsPath); var token = JsonConvert.DeserializeObject <PKCETokenResponse>(json); var authenticator = new PKCEAuthenticator(clientId !, token); authenticator.TokenRefreshed += (sender, token) => File.WriteAllText(CredentialsPath, JsonConvert.SerializeObject(token)); var config = SpotifyClientConfig.CreateDefault() .WithAuthenticator(authenticator); var spotify = new SpotifyClient(config); var me = await spotify.UserProfile.Current(); var playlists = await spotify.PaginateAll(await spotify.Playlists.CurrentUsers().ConfigureAwait(false)); _server.Dispose(); return(playlists); // Environment.Exit(0); }
public static async Task <SimplePlaylist> getPlayListById(string id) { var json = await File.ReadAllTextAsync(CredentialsPath); var token = JsonConvert.DeserializeObject <PKCETokenResponse>(json); var authenticator = new PKCEAuthenticator(clientId !, token); authenticator.TokenRefreshed += (sender, token) => File.WriteAllText(CredentialsPath, JsonConvert.SerializeObject(token)); var config = SpotifyClientConfig.CreateDefault() .WithAuthenticator(authenticator); var spotify = new SpotifyClient(config); var me = await spotify.UserProfile.Current(); var playlists = await spotify.PaginateAll(await spotify.Playlists.CurrentUsers().ConfigureAwait(false)); SimplePlaylist item = null; foreach (SimplePlaylist list_item in playlists) { if (list_item.Id == id) { item = list_item; break; } } _server.Dispose(); return(item); }
private static async Task Start() { var json = await File.ReadAllTextAsync(CredentialsPath); var token = JsonConvert.DeserializeObject <PKCETokenResponse>(json); var authenticator = new PKCEAuthenticator(clientId !, token); authenticator.TokenRefreshed += (sender, token) => File.WriteAllText(CredentialsPath, JsonConvert.SerializeObject(token)); var config = SpotifyClientConfig.CreateDefault() .WithAuthenticator(authenticator); var spotify = new SpotifyClient(config); var me = await spotify.UserProfile.Current(); Console.WriteLine($"Welcome {me.DisplayName} ({me.Id}), you're authenticated!"); var playlists = await spotify.PaginateAll(await spotify.Playlists.CurrentUsers().ConfigureAwait(false)); Console.WriteLine($"Total Playlists in your Account: {playlists.Count}"); _server.Dispose(); Environment.Exit(0); }
public void initClient(string accessToken) { try { var request = new FollowOfCurrentUserRequest { Limit = 50 }; client = new SpotifyClient(accessToken); var followedArtists = client.Follow.OfCurrentUser().Result; List <FullArtist> follows = (List <FullArtist>)client.PaginateAll(followedArtists.Artists, next => next.Artists).Result; getPlaylists(); releases = new List <Release>(); foreach (var follow in follows) { var latestRelease = getLatestRelease(follow.Id); Release release = new Release(); release.artist = follow.Name; release.album = latestRelease.Name; release.date = latestRelease.ReleaseDate; release.link = "https://open.spotify.com/" + latestRelease.Uri.Replace("spotify:", "").Replace(':', '/'); release.oneliner = $"{release.artist} - {release.album}"; release.youtubeLink = $"https://music.youtube.com/search?q={release.oneliner}"; release.uri = latestRelease.Uri; release.id = latestRelease.Id; release.tracks = client.Albums.GetTracks(latestRelease.Id).Result; releases.Add(release); } releases.Sort(CompareReleases); // sort all releases (show newest songs on top) notifyIfNeeded(releases); listView.Invoke(new Action(() => { foreach (Release release in releases) { listView.Items.Add(release.artist); var i = listView.Items.Count - 1; listView.Items[i].SubItems.Add(release.album); listView.Items[i].SubItems.Add(release.date); } listView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); })); ready = true; } catch (Exception e) { Debug.WriteLine(e.Message); ready = false; } }
private async Task StartPlaylistGeneration() { const int tracksPerPlaylist = 9900; var paginator = new SimplePaginatorWithDelay(100); var authenticator = this.spotifyAuthorization.GetAuthenticator(); var spotifyClient = new SpotifyClient(SpotifyClientConfig.CreateDefault().WithAuthenticator(authenticator)); var profile = await spotifyClient.UserProfile.Current(); var albums = this.GetAlbums().OrderBy(a => a.Artist).ThenBy(a => a.Album).ToList(); var cachedAlbums = this.GetCachedAlbums(); List <string> trackUris = new List <string>(); int counter = 0; var cachedAlbumsInLibrary = cachedAlbums.Where(ca => albums.Select(a => a.Id).Contains(ca.Id)); trackUris.AddRange(cachedAlbumsInLibrary.SelectMany(ca => ca.TrackUris)); var albumsNotInCache = albums.Where(a => !cachedAlbums.Any(ca => ca.Id == a.Id)).ToList(); foreach (var album in albumsNotInCache) { Console.WriteLine($"Processing {++counter}/{albumsNotInCache.Count}: {album.Artist} - {album.Album}"); var albumTrackUris = (await spotifyClient.PaginateAll(await spotifyClient.Albums.GetTracks(album.Id).ConfigureAwait(false), paginator)).Select(at => at.Uri).ToList(); trackUris.AddRange(albumTrackUris); cachedAlbums.Add(new AlbumWithTracks { Id = album.Id, TrackUris = albumTrackUris }); Thread.Sleep(100); } this.SaveCachedAlbums(cachedAlbums); int playlistCounter = 1; var blacklistHelper = new TrackBlacklistHelper(); trackUris = trackUris.Except(blacklistHelper.GetBlacklist()).ToList(); while (trackUris.Any()) { string playlistId = await GetPlaylistId(string.Format(Constants.PlaylistName, playlistCounter++), paginator, spotifyClient, profile).ConfigureAwait(false); await AddTracksToPlaylist(spotifyClient, playlistId, trackUris.Take(tracksPerPlaylist).ToList()); trackUris.RemoveRange(0, Math.Min(tracksPerPlaylist, trackUris.Count)); } }
/* * Gets the tracks from the user's saved tracks library */ public IList <string> GetSavedTracks() { IList <string> uris = new List <string>(); try { var task = spotify.Library.GetTracks(); task.Wait(); var pages = task.Result; var task2 = spotify.PaginateAll(pages); task2.Wait(); var tracks = task2.Result; foreach (var track in tracks) { uris.Add(track.Track.Uri); } } catch (AggregateException ex) { Logger.Log("Failed to retrieve user's saved tracks: " + ex.InnerException.Message); } return(uris); }
private async Task StartUpdate() { var authenticator = this.spotifyAuthorization.GetAuthenticator(); var spotifyClient = new SpotifyClient(SpotifyClientConfig.CreateDefault().WithAuthenticator(authenticator)); var paginator = new SimplePaginatorWithDelay(100); var albumsFromSpotify = await spotifyClient.PaginateAll(await spotifyClient.Library.GetAlbums().ConfigureAwait(false), paginator); var savableAlbums = albumsFromSpotify.Select(a => new SavableAlbum { Artist = a.Album.Artists.FirstOrDefault()?.Name, Album = a.Album.Name, Id = a.Album.Id }).ToArray(); File.WriteAllText(Constants.AlbumListFileName, JsonConvert.SerializeObject(savableAlbums)); }
private static async Task <string> GetPlaylistId(string playlistName, SimplePaginatorWithDelay paginator, SpotifyClient spotifyClient, PrivateUser profile) { var playlists = await spotifyClient.PaginateAll(await spotifyClient.Playlists.GetUsers(profile.Id).ConfigureAwait(false), paginator); var playlist = playlists.FirstOrDefault(pl => pl.Name == playlistName); FullPlaylist createdPlaylist = null; if (playlist == null) { createdPlaylist = await spotifyClient.Playlists.Create(profile.Id, new PlaylistCreateRequest(playlistName)); } string playlistId = playlist?.Id ?? createdPlaylist?.Id; return(playlistId); }
public async Task <List <SimplePlaylist> > GetPlaylists(string s) { var featuredPlaylists = _spotifyClient.Browse.GetFeaturedPlaylists().Result.Playlists.Items; var userPlaylistsPage = await _spotifyClient.Playlists.CurrentUsers(); var userPlaylists = await _spotifyClient.PaginateAll(userPlaylistsPage); List <SimplePlaylist> returnedPlaylists = new List <SimplePlaylist>(); //Add User playlists that contain the query returnedPlaylists = returnedPlaylists.Concat( userPlaylists.Where( playlist => playlist.Name.ToLower().Contains(s.ToLower())).ToList()).ToList(); //Add Featured playlists that contain the query returnedPlaylists = returnedPlaylists.Concat( featuredPlaylists.ToList <SimplePlaylist>().Where( playlist => playlist.Name.ToLower().Contains(s.ToLower())).ToList()).ToList(); return(returnedPlaylists); }
// Function for 'search' button after click // Uses Spotify Search API to find the root song protected async void Button1_Submit_Click(object sender, EventArgs e) { // Get input from user via TextBox string song = Convert.ToString(TextBox1.Text); // Get input from user via TextBox string artist = Convert.ToString(TextBox2.Text); string searchSong = ""; if (song.Length > 0 && artist.Length > 0) { searchSong = song + " " + artist; } // else if (song.Length == 0) //no song input { // display an error message } else if (artist.Length > 0) { searchSong = song; } Label1.Text = "Searching for " + song; string CLIENTID = Environment.GetEnvironmentVariable("SPOTIFY_CLIENT_ID"); string CLIENTSECRET = Environment.GetEnvironmentVariable("SPOTIFY_CLIENT_SECRET"); var config = SpotifyClientConfig.CreateDefault(); var request = new ClientCredentialsRequest(CLIENTID, CLIENTSECRET); var response = await new OAuthClient(config).RequestToken(request); spotify = new SpotifyClient(config.WithToken(response.AccessToken)); // [placeholder] catch Spotify connection errors //perform search. CAN REPLACE WITH USER INPUTTED REQUEST HERE var search = await spotify.Search.Item(new SearchRequest(SearchRequest.Types.Track, searchSong)); //Get tracks from search result var trackResults = spotify.PaginateAll(search.Tracks, (s) => s.Tracks); //add the first 5 results into a list. This shouldn't be needed with paginate all /* List<FullTrack> trackList = new List<FullTrack>(); * for (int i = 0; i <= 5; i++) * { * trackList.Add(enumerator.Current); * await enumerator.MoveNextAsync(); * }*/ string temp = ""; //print list of first 5 items that appear in search result for (int i = 0; i < 5; i++) { if (trackResults.Result[i] != null) { //at this point we want user to input a number //Console.Write("Option " + i + ": \"" + trackList[i].Name + "\" by \"" + trackList[i].Artists[0].Name + "\""); //Console.WriteLine(" From the album \"" + trackList[i].Album.Name + "\""); temp = i + ": \"" + trackResults.Result[i].Name + "\" by \"" + trackResults.Result[i].Artists[0].Name + "\"" + " From the album \"" + trackResults.Result[i].Album.Name + "\""; } } // Each generated option is displayed as an option // User must choose one option Option1.Text = trackResults.Result[0].Name + "\" by \"" + trackResults.Result[0].Artists[0].Name + "\"" + " From the album \"" + trackResults.Result[0].Album.Name; Option2.Text = trackResults.Result[1].Name + "\" by \"" + trackResults.Result[1].Artists[0].Name + "\"" + " From the album \"" + trackResults.Result[1].Album.Name; Option3.Text = trackResults.Result[2].Name + "\" by \"" + trackResults.Result[2].Artists[0].Name + "\"" + " From the album \"" + trackResults.Result[2].Album.Name; Option4.Text = trackResults.Result[3].Name + "\" by \"" + trackResults.Result[3].Artists[0].Name + "\"" + " From the album \"" + trackResults.Result[3].Album.Name; Option5.Text = trackResults.Result[4].Name + "\" by \"" + trackResults.Result[4].Artists[0].Name + "\"" + " From the album \"" + trackResults.Result[4].Album.Name; // Matches the choice from the list // choice = input from default.aspx int choice = 1; string trackID = trackResults.Result[choice].Id; string artistID = trackResults.Result[choice].Artists[0].Id; //get the genres of the artist by searching for the exact artist name based on choice from user List <string> artistGenres = new List <string>(); search = await spotify.Search.Item(new SearchRequest(SearchRequest.Types.Artist, trackResults.Result[choice].Artists[0].Name)); var artistResults = spotify.PaginateAll(search.Artists, (s) => s.Artists); //go through every artist until we find a matching artist ID. //This may be problematic if we run into a weird case where we get the ID but when searching by name the artist doesnt show up //I set i to 50 because I wasn't sure how to iterate through the whole ilist, 80% sure we will have a 99% chance we find the artist for (int i = 0; i < 50; i++) { if (artistResults.Result[i] == null) { //if we ran out of results to look for? break; } //to ensure we have the right artis if (artistResults.Result[i].Id == artistID) { artistGenres = artistResults.Result[i].Genres; break; } } // information for generating the reccomendations RecommendationsRequest recFinder = new RecommendationsRequest(); recFinder.SeedTracks.Add(trackID); recFinder.SeedGenres.Add(artistGenres[0]); recFinder.SeedArtists.Add(artistID); //WE CAN CHANGE AMOUNT OF SONGS WE WANT TO GENERATE HERE recFinder.Limit = 20; //performt he recommendation search var recList = spotify.Browse.GetRecommendations(recFinder); Console.WriteLine("\nReccomendations found: "); string recommendations = ""; for (int i = 0; i < recList.Result.Tracks.Count; i++) { string tmp = ("Song " + (i + 1) + ": \"" + recList.Result.Tracks[i].Name + "\" by " + recList.Result.Tracks[i].Artists[0].Name); recommendations.Concat(tmp); //maybe print the URL for a track here idk how to find it I'm happy with what is done so far. } RecLabel.Text = "Reccomendations found: " + recommendations; }