From 3ae0c756663c403b380ea233ebc684abb17d2f08 Mon Sep 17 00:00:00 2001 From: Hamid Reza Mohammadi Date: Sun, 18 Jul 2021 20:22:06 +0430 Subject: [PATCH] #114 basic codes for spotify direct api call (not working codes only copies) --- GanjooRazor/Pages/Spotify.cshtml.cs | 86 +++++++++++++++++++++++++++-- GanjooRazor/appsettings.json | 8 ++- 2 files changed, 89 insertions(+), 5 deletions(-) diff --git a/GanjooRazor/Pages/Spotify.cshtml.cs b/GanjooRazor/Pages/Spotify.cshtml.cs index 38091ddf..de4d27f7 100644 --- a/GanjooRazor/Pages/Spotify.cshtml.cs +++ b/GanjooRazor/Pages/Spotify.cshtml.cs @@ -4,9 +4,13 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.ViewFeatures; +using Microsoft.Extensions.Configuration; using Newtonsoft.Json; +using Newtonsoft.Json.Linq; using RMuseum.Models.Ganjoor; using RMuseum.Models.Ganjoor.ViewModels; +using System; +using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Text; @@ -23,14 +27,20 @@ namespace GanjooRazor.Pages /// private readonly HttpClient _httpClient; + /// + /// configuration + /// + private readonly IConfiguration _configuration; + /// /// constructor /// /// - /// - public SpotifyModel(HttpClient httpClient) + /// + public SpotifyModel(HttpClient httpClient, IConfiguration configuration) { _httpClient = httpClient; + _configuration = configuration; } /// @@ -146,9 +156,52 @@ namespace GanjooRazor.Pages /// search by artists name /// /// + /// /// - public async Task OnPostSearchByArtistNameAsync(string search) + public async Task OnPostSearchByArtistNameAsync(string search, bool secondtime = false) { + string spotifyToken = _configuration.GetSection("Spofify")["AccessToken"];//we need to store these values in another place + var request = new HttpRequestMessage(HttpMethod.Get, + $"https://api.spotify.com/v1/search?q={search}&type=artist"); + request.Headers.Add("Authorization", spotifyToken); + var response = await _httpClient.SendAsync(request); + List artists = new List(); + if (response.IsSuccessStatusCode) + { + string json = await response.Content.ReadAsStringAsync(); + var parsed = JObject.Parse(json); + + foreach (JToken artist in parsed.SelectTokens("artists.items[*]")) + { + string imageUrl = ""; + foreach (JToken image in artist.SelectTokens("images[*].url")) + { + imageUrl = image.Value(); + break; + } + artists.Add( + new NameIdUrlImage() + { + Name = artist.SelectToken("name").Value(), + Id = artist.SelectToken("id").Value(), + Url = artist.SelectToken("external_urls.spotify").Value(), + Image = imageUrl + } + ); + } + + } + else + { + if (!secondtime) + { + await RefreshToken(); + return await OnPostSearchByArtistNameAsync(search, true); + } + return BadRequest(response.ToString()); + } + + /* //Warning: This is a private wrapper around the spotify API, created only for this project and incapable of // responding large number of requests (both server and Spotify user limitations), // so please do not use this proxy in other projects because you will cause this proxy to become unavailable for me @@ -161,6 +214,7 @@ namespace GanjooRazor.Pages { artists = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); } + */ return new PartialViewResult() @@ -170,12 +224,36 @@ namespace GanjooRazor.Pages { Model = new _SpotifySearchPartialModel() { - Artists = artists + Artists = artists.ToArray() } } }; } + private async Task RefreshToken() + { + string refresh_token = _configuration.GetSection("Spofify")["RefreshToken"];//we need to store these values in another place + var nvc = new List>(); + nvc.Add(new KeyValuePair("grant_type", "refresh_token")); + nvc.Add(new KeyValuePair("refresh_token", refresh_token)); + var formContent = new FormUrlEncodedContent(nvc); + var request = new HttpRequestMessage(HttpMethod.Post, + "https://accounts.spotify.com/api/token"); + request.Content = formContent; + string authValue = Convert.ToBase64String(new ASCIIEncoding().GetBytes($"{_configuration.GetSection("Spofify")["ClientID"]}:{_configuration.GetSection("Spofify")["ClientSecret"]}")); + request.Headers.Add("Authorization", $"Basic {authValue}"); + var response = await _httpClient.SendAsync(request); + if (response.IsSuccessStatusCode) + { + string json = await response.Content.ReadAsStringAsync(); + var parsed = JObject.Parse(json); + string access_token = parsed.SelectToken("access_token").Value(); + + + _configuration.GetSection("Spofify")["AccessToken"] = access_token; + } + } + /// /// fill artist albums /// diff --git a/GanjooRazor/appsettings.json b/GanjooRazor/appsettings.json index 24839963..ee1528e5 100644 --- a/GanjooRazor/appsettings.json +++ b/GanjooRazor/appsettings.json @@ -9,5 +9,11 @@ "AllowedHosts": "*", "GoogleAnalyticsCode": "", "APIRoot": "http://localhost:3439", - "GlobalAPIRoot": "http://localhost:3439" + "GlobalAPIRoot": "http://localhost:3439", + "Spofify": { + "ClientID": "", + "ClientSecret": "", + "AccessToken": "", + "RefreshToken": "" + } }