public async Task PopulateSongWithSpotifyData(WikipediaSong song) { HttpRequestMessage requestMessage = await CreateSpotifyRequestMessage( method : HttpMethod.Get, url : $"https://api.spotify.com/v1/search?q={song.GetArtistAndSongForSpotifyAPISearch()}&type=track&limit=1"); string answer = await GetResponseContent(requestMessage); JObject jo = JObject.Parse(answer); bool songHasBeenFound = ((JArray)(jo["tracks"]["items"])).Count() > 0; if (!songHasBeenFound) { return; } JObject joSong = (JObject)jo["tracks"]["items"][0]; song.SpotifyId = (string)joSong["id"]; song.SpotifySong = (string)joSong["name"]; song.SpotifyAlbum = (string)joSong["album"]["name"]; JArray artists = (JArray)joSong["artists"]; string artistString = ""; foreach (JToken artist in artists) { if (!artistString.IsNullOrEmpty()) { artistString += ", "; } artistString += artist["name"]; } song.SpotifyArtist = artistString; }
public async Task AddSongsToPlaylist(List <WikipediaSong> songs, string playlistId) { List <WikipediaSong> songsFiltered = new(); HashSet <WikipediaSong> addedSongs = new(); foreach (WikipediaSong song in songs) { if (song.SpotifyId.IsNullOrEmpty()) { continue; } if (!addedSongs.Contains(song)) { songsFiltered.Add(song); addedSongs.Add(song); } if (songsFiltered.Count >= 10000) { break; } } List <List <WikipediaSong> > listOf100SongLists = new List <List <WikipediaSong> >(); int indexCounter = 0; listOf100SongLists.Add(new List <WikipediaSong>()); for (int i = 0; i < songsFiltered.Count; i++) { WikipediaSong song = songsFiltered[i]; listOf100SongLists[indexCounter].Add(song); if (listOf100SongLists[indexCounter].Count < 100) { continue; } indexCounter++; listOf100SongLists.Add(new List <WikipediaSong>()); } foreach (List <WikipediaSong> songList in listOf100SongLists) { StringBuilder songUris = new StringBuilder("["); foreach (WikipediaSong song in songList) { if (songUris.Length > 1) { songUris.Append(","); } songUris.Append($"\"spotify:track:{song.SpotifyId}\""); } songUris.Append("]"); HttpRequestMessage request = await CreateSpotifyRequestMessage( method : HttpMethod.Post, url : $"https://api.spotify.com/v1/playlists/{playlistId}/tracks"); AddJsonAsBodyDataToRequest(songUris.ToString(), request); string result = await GetResponseContent(request); } }