/// Add a song to playlist public static async Task AddSongToPlaylist(SpotifyDetails sDetails) { var playlistID = sDetails.MonthlyPlaylistId; httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", sDetails.AccessToken); // Get current song Josh is listening to string uri = "https://api.spotify.com/v1/me/player/currently-playing"; HttpResponseMessage res = await httpClient.GetAsync(uri); if (!res.StatusCode.Equals(System.Net.HttpStatusCode.OK)) { log.LogError($"[-] Error Getting current playing song ({res.StatusCode})"); } string songID = JObject.Parse(await res.Content.ReadAsStringAsync()).SelectToken("item.uri").Value <string>(); log.LogInformation($"[+] songID={songID}"); string username = GetEnvironmentVariable("SPOT_USERNAME"); //Post song to playlist. uri = $"https://api.spotify.com/v1/users/{username}/playlists/{playlistID}/tracks?uris={songID}"; res = await httpClient.PostAsync(uri, new MultipartContent()); if (!res.StatusCode.Equals(System.Net.HttpStatusCode.Created)) { log.LogError($"[-] Error posting song to playlit ({res.StatusCode})"); } log.LogInformation($"[+] Posting song to playlist: {res.StatusCode}"); }
/// Update the monthly playlist public static async Task UpdateMonthlyPlaylist(CloudTable cTable, string playlistId, SpotifyDetails sDetails) { SpotifyDetails sCreds = new SpotifyDetails() { PartitionKey = "1", RowKey = "1", MonthlyPlaylistId = playlistId, ExpiresAt = sDetails.ExpiresAt }; await cTable.ExecuteAsync(TableOperation.InsertOrMerge(sCreds)); }
/// Update the Token public static async Task <string> RefreshTokenAndUpdate(CloudTable cTable, SpotifyDetails sDetails) { // Refresh our access token. var clientIdClientSecret = GetEnvironmentVariable("CLIENTIDCLIENTSECRET"); var refresh_token = $"{sDetails.RefreshTokenLeft}{sDetails.RefreshTokenRight}"; httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", clientIdClientSecret); var uri = "https://accounts.spotify.com/api/token"; var res = await httpClient.PostAsync(uri, new FormUrlEncodedContent(new Dictionary <string, string>() { { "grant_type", "refresh_token" }, { "refresh_token", refresh_token } })); log.LogInformation($"[+] Refreshed Token: {res.StatusCode}"); // Parse out returned access token. var newAccessToken = ""; if (JObject.Parse(await res.Content.ReadAsStringAsync()).TryGetValue("access_token", out var token)) { newAccessToken = token.Value <string>() ?? ""; } SpotifyDetails sCreds = new SpotifyDetails() { PartitionKey = "1", RowKey = "1", AccessToken = newAccessToken, ExpiresAt = DateTime.Now.AddMinutes(55) }; await cTable.ExecuteAsync(TableOperation.InsertOrMerge(sCreds)); return(newAccessToken); }