public void RemovePlaylistTrack(Int64 trackInfoId) { TrackInfo trackToRemove = PlaylistTracks.First(t => t.Id == trackInfoId); PlaylistTracks.Remove(trackToRemove); this.StateHasChanged(); }
private async Task SavePlaylist() { string idList = string.Join("|", PlaylistTracks.Select(p => p.Id)); Wrap.Cookie playlistCookie = new Wrap.Cookie("playlist", JsRuntime); await playlistCookie.Set(idList); }
public async Task GetPlaylist(string playlistId) { //sets selected playlist string playlistJson = await Globals.Requester.GetAsync($"https://api.spotify.com/v1/playlists/{playlistId}?limit=999"); Playlist playlist = JsonConvert.DeserializeObject <Playlist>(playlistJson); SelectedPlaylist = playlist; //gets playlist items string playlistTracksJson = await Globals.Requester.GetAsync($"https://api.spotify.com/v1/playlists/{playlistId}/tracks?limit=99"); PlaylistTracks playlistTracks = JsonConvert.DeserializeObject <PlaylistTracks>(playlistTracksJson); if (playlistTracks.total > 99) { int numLoops = (int)Math.Ceiling(Convert.ToDouble(playlistTracks.total) / 99.0); for (int i = 1; i < numLoops; i++) { playlistTracksJson = await Globals.Requester.GetAsync($"https://api.spotify.com/v1/playlists/{playlistId}/tracks?limit=99&offset={99*i}"); PlaylistList playlistTracksOffset = JsonConvert.DeserializeObject <PlaylistList>(playlistTracksJson); playlistTracks.items.AddRange(playlistTracksOffset.items.ToArray()); } } SelectedPlaylistTracks = playlistTracks; }
public void DoubleclickPlaylistRow(TrackInfo track) { if (PlaylistTracks.Any(t => t.Id == track.Id)) { return; } PlaylistTracks.Add(track); }
public void SetCurrentTrackNext() { if (PlaylistTracks.Count <= 1) { return; } Data.CurrentTrack = PlaylistTracks[(PlaylistTracks.IndexOf(Data.CurrentTrack) + 1) % PlaylistTracks.Count]; }
private void OnEnded() { if (PlaylistTracks.Count <= 1) { return; } Data.CurrentTrack = PlaylistTracks[(PlaylistTracks.IndexOf(Data.CurrentTrack) + 1) % PlaylistTracks.Count]; }
protected void PlaylistRowClick(Int64 id) { if (Data.CurrentTrack != null && Data.CurrentTrack.Id == id || !PlaylistTracks.Any(t => t.Id == id)) { return; } Data.CurrentTrack = PlaylistTracks.First(t => t.Id == id); this.StateHasChanged(); }
private async void lnkGenerateObscure_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { int firstPlaylistCount = Globals.DataStore.SelectedPlaylist.tracks.total; NewPlaylistForm newPlaylistForm = new NewPlaylistForm(firstPlaylistCount); newPlaylistForm.ShowDialog(); string playlistName = newPlaylistForm.Name_; string playlistDescription = newPlaylistForm.Description; //int numTracks = newPlaylistForm.NumTracks; PlaylistTracks playlistTracks = Globals.DataStore.SelectedPlaylistTracks; List <string> seedTrackIDs = GetPlaylistTrackIDs(); List <string> newTrackUris = new List <string>(); for (int i = 0; i < firstPlaylistCount; i += 5) { string recomUrl = $"https://api.spotify.com/v1/recommendations?limit=5&seed_tracks="; for (int ii = 0; ii < 5; ii += 1) { if (seedTrackIDs.Count > i + ii) { recomUrl += $"{seedTrackIDs[i + ii]},"; } } if (recomUrl.Contains(',')) { recomUrl = recomUrl.Remove(recomUrl.LastIndexOf(',')); } recomUrl += "&target_popularity=0"; string recommendationJson = await Globals.Requester.GetAsync(recomUrl); Recommendation recommendation = JsonConvert.DeserializeObject <Recommendation>(recommendationJson); foreach (Track t in recommendation.tracks) { newTrackUris.Add(t.uri); } } string uriPostContent = GetUriListJson(newTrackUris); Playlist newPlaylist = await CreateNewPlaylist(playlistName, playlistDescription); await PopulatePlaylistTracks(newPlaylist.id, uriPostContent); newPlaylistForm.Dispose(); }
public async Task <TracksSearchResponse> GetPlaylistTracksAsync(string playlistID) { PlaylistTracks pt = await GetSpotifyResponseObject <PlaylistTracks>("playlists/" + playlistID + "/tracks?offset=" + OffsetSelector.GetRandomOffset()); TracksSearchResponse tsr = new TracksSearchResponse { Tracks = pt.Tracks.Select(x => x.Track).ToList() }; return(tsr); }
/// <summary> /// Rebind the playlist to the view after it's been randified /// </summary> /// <returns></returns> public async Task BindPlaylistAfterSort(List <PlaylistTrack> playlistTracks) { PlaylistTracks.Clear(); PlaylistTracks.AddRange(playlistTracks); NumberOfLoadedTracks = PlaylistTracks.Count(); IsPlaylistLoading = false; Stopwatch.Stop(); StateHasChanged(); }
protected void PlaylistRowRemoveClick(Int64 id) { if (!PlaylistTracks.Any(t => t.Id == id)) { return; } if (Data.CurrentTrack != null && Data.CurrentTrack.Id == id) { SetCurrentTrackNext(); } RemovePlaylistTrack(id); }
protected void PreviousTrackClick() { if (PlaylistTracks.Count <= 1) { return; } if (PlaylistTracks.IndexOf(Data.CurrentTrack) == 0) { Data.CurrentTrack = PlaylistTracks[PlaylistTracks.Count - 1]; } else { Data.CurrentTrack = PlaylistTracks[(PlaylistTracks.ToList().IndexOf(Data.CurrentTrack) - 1) % PlaylistTracks.Count]; } }
protected void PlaylistRowDoubleClick(Int64 id) { if (Data.IsPlaying) { return; } Data.IsPlaying = true; if (Data.CurrentTrack.Id == id || !PlaylistTracks.Any(t => t.Id == id)) { this.StateHasChanged(); return; } Data.CurrentTrack = PlaylistTracks.First(t => t.Id == id); this.StateHasChanged(); }
public static PlaylistTracks GetPlaylistTracks(string AccessToken, string UserId, string PlaylistId) { var client = new RestClient("https://api.spotify.com/v1"); var request = new RestRequest("users/{userid}/playlists/{playlistid}/tracks", Method.GET); request.AddUrlSegment("userid", UserId); request.AddUrlSegment("playlistid", PlaylistId); request.AddHeader("Authorization", string.Format("Bearer {0}", AccessToken)); // execute api call and deserialize the results into the object IRestResponse response = client.Execute(request); PlaylistTracks tracks = new PlaylistTracks(); tracks = JsonConvert.DeserializeObject <PlaylistTracks>(response.Content); return(tracks); }
private async Task LoadPlaylist() { Wrap.Cookie playlistCookie = new Wrap.Cookie("playlist", JsRuntime); string sidList = await playlistCookie.Get(); if (sidList != null) { (await Data.GetTracks(sidList)).ForEach(t => { if (!PlaylistTracks.Any(p => p.Id == t.Id)) { PlaylistTracks.Add(t); } }); } if (PlaylistTracks.Count > 0) { this.StateHasChanged(); } }
public void LoadPlaylist() { //playlist: Playlist playlist = Globals.DataStore.SelectedPlaylist; lblPlaylistName.Text = playlist.name; //lblCreatedOn.Text = $"Created on: "; lblPlaylistFollowers.Text = $"{playlist.followers.total.ToString()} followers"; lblAuthor.Text = $"By: {playlist.owner.display_name.ToString()}"; if (playlist.collaborative) { ckbCollab.Checked = true; } else { ckbCollab.Checked = false; } if (playlist.@public) { ckbPublic.Checked = true; } else { ckbPublic.Checked = false; } //playlist tracks: PlaylistTracks playlistTracks = Globals.DataStore.SelectedPlaylistTracks; foreach (Item item in playlistTracks.items) { dgvPlaylist.Rows.Add(item.track.name, item.added_at, item.added_by.id, item.track.id, item.added_by.id); } }
public Playlist(int ownerid, BindingList <BassTrack> tracks, string playlistName) { this.PlaylistTracks = new List <int>() { }; this.PlaylistTracksSerialized = new BindingList <BassTrack>() { }; this.OwnerId = ownerid; foreach (BassTrack track in tracks) { this.PlaylistTracks.Add(track.TrackId); } foreach (BassTrack track in tracks) { this.PlaylistTracksSerialized.Add(track); } this.PlaylistName = playlistName; this.PlaylistId = PlaylistName.GetHashCode() + PlaylistTracks.GetHashCode(); }
private async Task <PlaylistTracks> GetTracks(string token, string playlistid) { var request = new HttpRequestMessage(HttpMethod.Get, $"https://api.spotify.com/v1/browse/categories/{playlistid}/playlists"); request.Headers.Add("Authorization", $"Bearer {token}"); var client = ClientFactory.CreateClient(); var response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { var json = await response.Content.ReadAsStringAsync(); var playlists = Playlists.FromJson(json); var firstList = playlists.PlaylistsPlaylists.Items.FirstOrDefault(); if (firstList != null) { request = new HttpRequestMessage(HttpMethod.Get, firstList.Tracks.Href); request.Headers.Add("Authorization", $"Bearer {token}"); response = await client.SendAsync(request); json = await response.Content.ReadAsStringAsync(); return(PlaylistTracks.FromJson(json)); } return(null); } else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { throw new SpotifyTokenExpiredException(); } else { throw new ApplicationException(response.StatusCode.ToString()); } }
public JsonResult CraftPlaylistFromGenres(string AccessToken, string NameString, string[] GenreStringList) { List <string> NameList = NameString.Trim().Trim(',').Split(',').ToList(); double TotalDancability = 0.0; int DancabilityCount = 0; double TotalEnergy = 0.0; int EnergyCount = 0; double TotalSpeechiness = 0.0; int SpeechinessCount = 0; //SortedDictionary<string, int> Genres = new SortedDictionary<string, int>(); List <string> ArtistIds = new List <string>(); foreach (string name in NameList) { UserPlaylists playlists = APICalls.GetUsersPlaylists(AccessToken, name, 10); List <string> TrackIds = new List <string>(); Random rand = new Random(); playlists.Playlists = playlists.Playlists.OrderBy(x => rand.Next()).Take(3).ToList(); foreach (Item pl in playlists.Playlists) { PlaylistTracks tracks = APICalls.GetPlaylistTracks(AccessToken, name, pl.id); if (tracks.Songs != null) { foreach (PlaylistItem pli in tracks.Songs) { if (pli.track.id != null) { TrackIds.Add(pli.track.id); } if (pli.track.artists[0].id != null) { if (!ArtistIds.Contains(pli.track.artists[0].id)) { ArtistIds.Add(pli.track.artists[0].id); } } } } } MultipleSongFeatures features = APICalls.GetMultipleSongFeatures(AccessToken, TrackIds); foreach (AudioFeature af in features.features) { TotalDancability += af.danceability; DancabilityCount++; TotalEnergy += af.energy; EnergyCount++; TotalSpeechiness += af.speechiness; SpeechinessCount++; } } //var sortedDict = Genres.OrderByDescending(x => x.Value).Take(5).ToDictionary(x => x.Key, x => x.Value); string GenreString = ""; foreach (string o in GenreStringList) { GenreString += o + ","; } GenreString = GenreString.Trim(','); double AvgDancability = TotalDancability / DancabilityCount; double AvgEnergy = TotalEnergy / EnergyCount; double AvgSpeechiness = TotalSpeechiness / SpeechinessCount; TracksBasedOnSeed SeededTracks = APICalls.GetPlaylistTracksByVariable(AccessToken, 40, AvgDancability, AvgEnergy, AvgSpeechiness, GenreString); return(Json(new { Tracks = SeededTracks, AvgDancability = AvgDancability, AvgEnergy = AvgEnergy, AvgSpeechiness = AvgSpeechiness, Genres = GenreString.Replace(",", ", ") })); }
void OnClick(int position) { if (UseChannel) { MainActivity.instance.SupportFragmentManager.BeginTransaction().Replace(Resource.Id.contentView, ChannelDetails.NewInstance(channels[position])).AddToBackStack("Channel Details").Commit(); } else { MainActivity.instance.SupportFragmentManager.BeginTransaction().Replace(Resource.Id.contentView, PlaylistTracks.NewInstance(playlists[position])).AddToBackStack("Playlist Track").Commit(); } }
/* * public async Task<Recommendation> GetRecommendations() * { * * } */ private async void lnkGenerateSimilar_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { int firstPlaylistCount = Globals.DataStore.SelectedPlaylist.tracks.total; NewPlaylistForm newPlaylistForm = new NewPlaylistForm(firstPlaylistCount); newPlaylistForm.ShowDialog(); string playlistName = newPlaylistForm.Name_; string playlistDescription = newPlaylistForm.Description; //int numTracks = newPlaylistForm.NumTracks; PlaylistTracks playlistTracks = Globals.DataStore.SelectedPlaylistTracks; List <string> seedTrackIDs = GetPlaylistTrackIDs(); List <string> newTrackUris = new List <string>(); for (int i = 0; i < firstPlaylistCount; i += 5) { //TODO: only seeding w/ first 5 tracks for now string recomUrl = $"https://api.spotify.com/v1/recommendations?limit=5&seed_tracks="; for (int ii = 0; ii < 5; ii += 1) { if (seedTrackIDs.Count > i + ii) { recomUrl += $"{seedTrackIDs[i + ii]},"; } } if (recomUrl.Contains(',')) { recomUrl = recomUrl.Remove(recomUrl.LastIndexOf(',')); } string recommendationJson = await Globals.Requester.GetAsync(recomUrl); Recommendation recommendation = JsonConvert.DeserializeObject <Recommendation>(recommendationJson); foreach (Track t in recommendation.tracks) { newTrackUris.Add(t.uri); } } string uriPostContent = GetUriListJson(newTrackUris); Playlist newPlaylist = await CreateNewPlaylist(playlistName, playlistDescription); await PopulatePlaylistTracks(newPlaylist.id, uriPostContent); /* * //this is working * //maybe lets put this in a method with parameters so it can be used for the other generation methods * //if that won't work or is too time-consuming it can be easily done in each event also */ newPlaylistForm.Dispose(); }
public void Add_TrackToPlaylist(string playlistname, string username, int trackid) { using (var context = new ChinookContext()) { //does the playlist already exist Playlist exists = (from x in context.Playlists where x.UserName.Equals(username) && x.Name.Equals(playlistname) select x).FirstOrDefault(); int tracknumber = 0; PlaylistTracks newtrack = null; if (exists == null) { //create the new Playlist exists = new Playlist(); exists.Name = playlistname; exists.UserName = username; exists = context.Playlists.Add(exists); tracknumber = 1; } else { //the playlist already exists //and the query has given as the instance of that playlist from the DB //generate the next tracknumber tracknumber = exists.PlaylistTracks.Count(); //on our sample, playlist tracks for a playlist //are unique newtrack = exists.PlaylistTracks.SingleOrDefault(x => x.TrackId == trackid); if (newtrack != null) { throw new Exception("Playlist already has a requested track."); } } //this is a boom test //remove after testing //if (playlistname.Equals("Boom")) //{ // throw new Exception("forced abort, check DB for Boom playlist"); //} //you have a playlist //you know the track will be unique //create the new track newtrack = new PlaylistTracks(); newtrack.TrackId = trackid; newtrack.TrackNumber = tracknumber; //since i am using the navigation property of the //playlist to get to playlisttrack //the savechanges will fill the playlistID //from either the hashset or from the existing instance exists.PlaylistTracks.Add(newtrack); context.SaveChanges(); } }
public override void OnBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { if (items[position].contentType == SectionType.SinglePlaylist) { LineSongHolder holder = (LineSongHolder)viewHolder; items[position].recycler = holder.recycler; holder.recycler.SetLayoutManager(new LinearLayoutManager(MainActivity.instance, LinearLayoutManager.Horizontal, false)); if (items[position].SectionTitle == "Queue") { holder.title.Text = MainActivity.instance.GetString(Resource.String.queue); LineAdapter adapter = new LineAdapter(holder.recycler); Home.instance.QueueAdapter = adapter; holder.recycler.SetAdapter(adapter); holder.more.Click += (sender, e) => { MainActivity.instance.ShowPlayer(); Player.instance.ShowQueue(); }; if (MusicPlayer.CurrentID() != -1 && MusicPlayer.CurrentID() <= MusicPlayer.queue.Count) { holder.recycler.ScrollToPosition(MusicPlayer.CurrentID()); } } else if (items[position].SectionTitle == "Fav") { holder.title.Text = MainActivity.instance.GetString(Resource.String.favorite); holder.recycler.SetAdapter(new LineAdapter(true, items[position].contentValue.GetRange(0, items[position].contentValue.Count > 20 ? 20 : items[position].contentValue.Count), holder.recycler)); holder.more.Click += (sender, e) => { position = holder.AdapterPosition; MainActivity.instance.SupportFragmentManager.BeginTransaction().Replace(Resource.Id.contentView, PlaylistTracks.NewInstance(items[position].contentValue, items[position].SectionTitle)).AddToBackStack(null).Commit(); }; } else if (items[position].SectionTitle == null) { //The playlist is loading holder.recycler.SetAdapter(new LineAdapter(new List <Song>(), holder.recycler)); } else { holder.title.Text = items[position].SectionTitle; holder.recycler.SetAdapter(new LineAdapter(items[position].contentValue.GetRange(0, items[position].contentValue.Count > 20 ? 20 : items[position].contentValue.Count), holder.recycler)); holder.more.Click += (sender, e) => { position = holder.AdapterPosition; if (items[position].playlist == null) { MainActivity.instance.SupportFragmentManager.BeginTransaction().Replace(Resource.Id.contentView, PlaylistTracks.NewInstance(items[position].contentValue, items[position].SectionTitle)).AddToBackStack(null).Commit(); } else { MainActivity.instance.SupportFragmentManager.BeginTransaction().Replace(Resource.Id.contentView, PlaylistTracks.NewInstance(items[position].playlist)).AddToBackStack(null).Commit(); } }; } } else if (items[position].contentType == SectionType.ChannelList) { LineSongHolder holder = (LineSongHolder)viewHolder; items[position].recycler = holder.recycler; holder.title.Text = items[position].SectionTitle; holder.recycler.SetLayoutManager(new LinearLayoutManager(MainActivity.instance, LinearLayoutManager.Vertical, false)); if (items[position].channelContent != null) { holder.recycler.SetAdapter(new VerticalSectionAdapter(items[position].channelContent.GetRange(0, items[position].channelContent.Count > 4 ? 4 : items[position].channelContent.Count), holder.recycler)); if (items[position].channelContent.Count > 4) { holder.more.Visibility = ViewStates.Visible; ((GradientDrawable)holder.more.Background).SetStroke(5, Android.Content.Res.ColorStateList.ValueOf(Color.Argb(255, 21, 183, 237))); holder.more.SetTextColor(Color.Argb(255, 21, 183, 237)); holder.more.Text = ((VerticalSectionAdapter)holder.recycler.GetAdapter()).channels.Count > 4 ? MainActivity.instance.GetString(Resource.String.view_less) : MainActivity.instance.GetString(Resource.String.view_more); holder.more.Click += (sender, e) => { VerticalSectionAdapter adapter = (VerticalSectionAdapter)holder.recycler.GetAdapter(); if (adapter.ItemCount == 4) { adapter.channels.AddRange(items[position].channelContent.GetRange(4, items[position].channelContent.Count - 4)); adapter.NotifyItemRangeInserted(4, items[position].channelContent.Count - 4); holder.more.Text = MainActivity.instance.GetString(Resource.String.view_less); } else { int count = adapter.channels.Count - 4; adapter.channels.RemoveRange(4, count); adapter.NotifyItemRangeRemoved(4, count); holder.more.Text = MainActivity.instance.GetString(Resource.String.view_more); } }; } else { holder.more.Visibility = ViewStates.Gone; } } else { holder.recycler.SetAdapter(new VerticalSectionAdapter(false, holder.recycler)); } } else if (items[position].contentType == SectionType.PlaylistList) { LineSongHolder holder = (LineSongHolder)viewHolder; items[position].recycler = holder.recycler; holder.title.Text = items[position].SectionTitle; holder.recycler.SetLayoutManager(new LinearLayoutManager(MainActivity.instance, LinearLayoutManager.Vertical, false)); if (items[position].playlistContent != null) { holder.recycler.SetAdapter(new VerticalSectionAdapter(items[position].playlistContent.GetRange(0, items[position].playlistContent.Count > 4 ? 4 : items[position].playlistContent.Count), holder.recycler)); if (ChannelDetails.instance != null) { if (items[position].playlistContent.Count > 4) { holder.more.Visibility = ViewStates.Visible; ((GradientDrawable)holder.more.Background).SetStroke(5, Android.Content.Res.ColorStateList.ValueOf(Color.Argb(255, 21, 183, 237))); holder.more.SetTextColor(Color.Argb(255, 21, 183, 237)); holder.more.Text = ((VerticalSectionAdapter)holder.recycler.GetAdapter()).playlists.Count > 4 ? MainActivity.instance.GetString(Resource.String.view_less) : MainActivity.instance.GetString(Resource.String.view_more); holder.more.Click += (sender, e) => { VerticalSectionAdapter adapter = (VerticalSectionAdapter)holder.recycler.GetAdapter(); if (adapter.ItemCount == 4) { adapter.playlists.AddRange(items[position].playlistContent.GetRange(4, items[position].playlistContent.Count - 4)); adapter.NotifyItemRangeInserted(4, items[position].playlistContent.Count - 4); holder.more.Text = MainActivity.instance.GetString(Resource.String.view_less); } else { int count = adapter.playlists.Count - 4; adapter.playlists.RemoveRange(4, count); adapter.NotifyItemRangeRemoved(4, count); holder.more.Text = MainActivity.instance.GetString(Resource.String.view_more); } }; } else { holder.more.Visibility = ViewStates.Gone; } } else { holder.more.Click += (sender, e) => { MainActivity.instance.FindViewById <BottomNavigationView>(Resource.Id.bottomView).SelectedItemId = Resource.Id.playlistLayout; }; holder.more.Visibility = ViewStates.Visible; } } else { holder.recycler.SetAdapter(new VerticalSectionAdapter(true, holder.recycler)); holder.more.Visibility = ViewStates.Gone; } } }
/// <summary> /// Drop down list changed event to bind the playlist to the view /// </summary> /// <returns></returns> public async Task BindPlaylist(ChangeEventArgs e) { if (IsRandifying || IsPlaylistLoading) { return; } var playlistId = e.Value.ToString(); try { IsPlaylistLoading = true; Seconds = 0; NumberOfLoadedTracks = 0; Stopwatch = new Stopwatch(); Stopwatch.Start(); PlaylistTracks.Clear(); try { var tracks = new List <PlaylistTrack>(); CurrentPlaylist = Playlists.FirstOrDefault(o => o.Id == playlistId); var page = await SpotifyService.GetPlaylistTracks(AuthenticationService.User, AuthenticationService.AuthenticationToken, CurrentPlaylist); do { foreach (var playlistTrack in page.Items) { tracks.Add(playlistTrack); } Seconds = Stopwatch.Elapsed.Seconds; NumberOfLoadedTracks = tracks.Count(); StateHasChanged(); if (page.HasNextPage) { page = await SpotifyService.GetNextPage(page, AuthenticationService.AuthenticationToken); } else { page = null; } }while (page != null); PlaylistTracks = tracks; } catch (Exception ex) { PageException = ex; } NumberOfLoadedTracks = PlaylistTracks.Count(); IsPlaylistLoading = false; Stopwatch.Stop(); StateHasChanged(); } catch (Exception ex) { PageException = ex; } }
/// <summary> /// Randomize the currently playlist, remove all of the tracks from the playlist, add all of the tracks back in a random order /// </summary> /// <returns></returns> public async Task Randify() { if (IsRandifying || IsPlaylistLoading) { return; } IsRandifying = true; var currentPlaylist = CurrentPlaylist; var randomTracks = PlaylistTracks.ToList(); var listOfSkippedTracks = new List <PlaylistTrack>(); var tracks = new List <Track>(); // it looks overcomplicated and you're right, but the spotify endpoint has a limit of 100 songs try { for (int i = 0; i < randomTracks.Count; i++) { if (!string.IsNullOrEmpty(randomTracks[i].Track.Id) && !string.IsNullOrWhiteSpace(randomTracks[i].Track.Id)) { tracks.Add(randomTracks[i].Track); } else { listOfSkippedTracks.Add(randomTracks[i]); } if (i % 100 == 0) { await SpotifyService.RemoveTracksFromPlaylist(AuthenticationService.User, AuthenticationService.AuthenticationToken, currentPlaylist, tracks); tracks.Clear(); } } await SpotifyService.RemoveTracksFromPlaylist(AuthenticationService.User, AuthenticationService.AuthenticationToken, currentPlaylist, tracks); } catch (Exception ex) { PageException = ex; } tracks.Clear(); randomTracks = randomTracks .OrderBy(o => Guid.NewGuid()) .ToList(); // it looks overcomplicated and you're right, but the spotify endpoint has a limit of 100 songs try { for (int i = 0; i < randomTracks.Count; i++) { if (!string.IsNullOrEmpty(randomTracks[i].Track.Id) && !string.IsNullOrWhiteSpace(randomTracks[i].Track.Id)) { tracks.Add(randomTracks[i].Track); } if (i % 100 == 0) { await SpotifyService.AddTracksToPlaylist(AuthenticationService.User, AuthenticationService.AuthenticationToken, currentPlaylist, tracks); tracks.Clear(); } } await SpotifyService.AddTracksToPlaylist(AuthenticationService.User, AuthenticationService.AuthenticationToken, currentPlaylist, tracks); } catch (Exception ex) { PageException = ex; } foreach (var skippedTrack in listOfSkippedTracks) { randomTracks.Remove(skippedTrack); } listOfSkippedTracks.Reverse(); foreach (var skippedTrack in listOfSkippedTracks) { randomTracks.Insert(0, skippedTrack); } IsRandifying = false; await BindPlaylistAfterSort(randomTracks); }
public JsonResult CraftPlaylist(string AccessToken, string NameString) { List <string> NameList = NameString.Trim().Trim(',').Split(',').ToList(); double TotalDancability = 0.0; int DancabilityCount = 0; double TotalEnergy = 0.0; int EnergyCount = 0; double TotalSpeechiness = 0.0; int SpeechinessCount = 0; SortedDictionary <string, int> Genres = new SortedDictionary <string, int>(); List <string> ArtistIds = new List <string>(); foreach (string name in NameList) { UserPlaylists playlists = APICalls.GetUsersPlaylists(AccessToken, name, 10); List <string> TrackIds = new List <string>(); Random rand = new Random(); playlists.Playlists = playlists.Playlists.OrderBy(x => rand.Next()).Take(3).ToList(); foreach (Item pl in playlists.Playlists) { PlaylistTracks tracks = APICalls.GetPlaylistTracks(AccessToken, name, pl.id); if (tracks.Songs != null) { foreach (PlaylistItem pli in tracks.Songs) { if (pli.track.id != null) { TrackIds.Add(pli.track.id); } if (pli.track.artists[0].id != null) { if (!ArtistIds.Contains(pli.track.artists[0].id)) { ArtistIds.Add(pli.track.artists[0].id); } } } } } for (int i = 0; i <= ArtistIds.Count / 20; i++) { ArtistList artists = APICalls.GetArtistList(AccessToken, ArtistIds.Take(20).ToList()); if (artists.artists == null || artists.artists.Count == 0) { break; } foreach (FullArtist fa in artists.artists) { foreach (object o in fa.genres) { if (Genres.ContainsKey(o.ToString())) { Genres[o.ToString()]++; } else { Genres.Add(o.ToString(), 1); } } } try { for (int z = 1; z <= 20; z++) { ArtistIds.RemoveAt(0); } } catch (Exception e) { } } MultipleSongFeatures features = APICalls.GetMultipleSongFeatures(AccessToken, TrackIds); foreach (AudioFeature af in features.features) { TotalDancability += af.danceability; DancabilityCount++; TotalEnergy += af.energy; EnergyCount++; TotalSpeechiness += af.speechiness; SpeechinessCount++; } } var sortedDict = Genres.OrderByDescending(x => x.Value).Take(5).ToDictionary(x => x.Key, x => x.Value); string GenreString = ""; foreach (KeyValuePair <string, int> o in sortedDict) { GenreString += o.Key + ","; } GenreString = GenreString.Trim(','); double AvgDancability = TotalDancability / DancabilityCount; double AvgEnergy = TotalEnergy / EnergyCount; double AvgSpeechiness = TotalSpeechiness / SpeechinessCount; TracksBasedOnSeed SeededTracks = APICalls.GetPlaylistTracksByVariable(AccessToken, 40, AvgDancability, AvgEnergy, AvgSpeechiness, GenreString); return(Json(new { Tracks = SeededTracks, AvgDancability = AvgDancability, AvgEnergy = AvgEnergy, AvgSpeechiness = AvgSpeechiness, Genres = GenreString.Replace(",", ", ") })); }