//[ValidateAntiForgeryToken] public IActionResult OidcClientGrant([FromBody] ClientCredentialsRequest req, [FromServices] IConfiguration cfg) { try { var oidcConf = cfg.GetSection(nameof(IdSrvConfig)).Get <IdSrvConfig>() ?? new IdSrvConfig(); if (string.IsNullOrEmpty(oidcConf.Authority)) { throw new Exception("OidcServerAuthority is missed."); } string access_token = string.Empty; using (var web = new WebClient()) { web.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); var rawToken = web.UploadString($"{oidcConf.Authority}/connect/token", $"grant_type=client_credentials&scope={req.Scope}&client_id={req.ClientId}&client_secret={req.ClientSecret}"); var token = Newtonsoft.Json.JsonConvert.DeserializeObject <BearerToken>(rawToken); access_token = token.access_token; } return(Ok(access_token)); } catch (Exception ex) { _logger.LogError(ex, "error OidcClientGrant AuthController"); return(InternalServerError(ex)); } }
public async Task <List <FullArtist> > GetArtists() { //TODO: Apply SOLID to this function var config = SpotifyClientConfig.CreateDefault(); var request = new ClientCredentialsRequest(Secrets.ClientId, Secrets.ClientSecret); var response = await new OAuthClient(config).RequestToken(request); var spotify = new SpotifyClient(config.WithToken(response.AccessToken)); var artists = new List <FullArtist>(); var rand = new Random(); int artistId1, artistId2, numArtists = ArtistIds.Ids.Count; do { artistId1 = rand.Next(0, numArtists); artistId2 = rand.Next(0, numArtists); } while (ArtistValidation(spotify, artistId1, artistId2) == false); artists.Add(spotify.Artists.Get(ArtistIds.Ids[artistId1]).Result); artists.Add(spotify.Artists.Get(ArtistIds.Ids[artistId2]).Result); return(artists); }
public SpotifyService() { var request = new ClientCredentialsRequest(CLIENTID, CLIENTSECRET); var response = new OAuthClient(_defaultConfig).RequestToken(request).Result; _spotify = new SpotifyClient(_defaultConfig.WithToken(response.AccessToken)); }
//private method to request a connection to the API private static async Task RequestConnection() { var Config = SpotifyClientConfig.CreateDefault(); var Request = new ClientCredentialsRequest(CLIENT_ID, CLIENT_SECRET); var Response = await new OAuthClient(Config).RequestToken(Request); Spotify = new SpotifyClient(Config.WithToken(Response.AccessToken)); }
private static async Task <SpotifyClient> GetSpotifyClient() { var config = SpotifyClientConfig.CreateDefault(); var request = new ClientCredentialsRequest(MemoryLaneConfig.Spotify.ClientId, MemoryLaneConfig.Spotify.ClientSecret); var response = await new OAuthClient(config).RequestToken(request); return(new SpotifyClient(config.WithToken(response.AccessToken))); }
public string GetAccessToken() { var clientId = ConfigurationManager.AppSettings["CLIENT_ID"]; var clientSecret = ConfigurationManager.AppSettings["CLIENT_SECRET"]; var config = SpotifyClientConfig.CreateDefault(); var request = new ClientCredentialsRequest(clientId, clientSecret); return(new OAuthClient(config).RequestToken(request).Result.AccessToken); }
public async Task <string> ObterToken() { var config = SpotifyClientConfig.CreateDefault(); var request = new ClientCredentialsRequest(_spotifyConfig.ClientId, _spotifyConfig.Secret); var response = await new OAuthClient(config).RequestToken(request); return(response.AccessToken); }
public static async Task <SpotifyClient> GetAuth() { var config = SpotifyClientConfig.CreateDefault(); var request = new ClientCredentialsRequest(Custom.Config.userConfig.clientId, Custom.Config.userConfig.clientSecret); var response = await new OAuthClient(config).RequestToken(request); var spotify = new SpotifyClient(config.WithToken(response.AccessToken)); return(spotify); }
/// <summary> /// /// </summary> /// <param name="_"></param> /// <returns></returns> public async Task InitializeAsync(CancellationToken _ = default) { IsInitialized = true; var config = SpotifyClientConfig.CreateDefault(); var request = new ClientCredentialsRequest(Username, Password); var authClient = new OAuthClient(config); var response = await authClient.RequestToken(request) .ConfigureAwait(false); Client ??= new SpotifyClient(config.WithToken(response.AccessToken)); }
private static async Task <SpotifyClient> AccessSpotify() { SpotifyClientConfig config = SpotifyClientConfig.CreateDefault(); var request = new ClientCredentialsRequest( Environment.GetEnvironmentVariable("Token_Spotify_ClientID"), Environment.GetEnvironmentVariable("Token_Spotify_ClientSecret") ); CredentialsTokenResponse response = await new OAuthClient(config).RequestToken(request); return(new SpotifyClient(config.WithToken(response.AccessToken))); }
public SpotifyService( ISpotifyTrackRepository spotifyTrackRepository, IOAuthClient oauthClient, IArtistService artistService, Func <SpotifyClientConfig, ISpotifyClient> spotifyClientProvider, Func <ClientCredentialsRequest> clientCredentialsRequestProvider) { this.spotifyTrackRepository = spotifyTrackRepository; this.oauthClient = oauthClient; this.artistService = artistService; this.spotifyClientProvider = spotifyClientProvider; semaphore = new SemaphoreSlim(1, 1); credentialsRequest = clientCredentialsRequestProvider(); }
public static async Task <SpotifyClient> GetAsync() { if (_spotifyClient == null || _tokenResponse == null || _tokenResponse.IsExpired) { if (_CLIENT_ID == "CHANGEME" || _CLIENT_SECRET == "CHANGEME") { throw new Exception("You need to override _CLIENT_ID and _CLIENT_SECRET with the values from your Spotify dev account"); } var request = new ClientCredentialsRequest(_CLIENT_ID, _CLIENT_SECRET); _tokenResponse = await new OAuthClient(_spotifyClientConfig).RequestToken(request); _spotifyClient = new SpotifyClient(_spotifyClientConfig.WithToken(_tokenResponse.AccessToken)); } return(_spotifyClient); }
public async void GetSpotifyRecommandation(Object obj) { if (!string.IsNullOrEmpty(SpotifyId)) { List <string> nameList = new List <string>(); var config = SpotifyClientConfig.CreateDefault(); var request = new ClientCredentialsRequest("349e633cba5b499183d80b075c90da6c", "a19042332bd5470f9fc9d2fca33c7b23"); var response = await new OAuthClient(config).RequestToken(request); var spotify = new SpotifyClient(config.WithToken(response.AccessToken)); var related = await spotify.Artists.GetRelatedArtists(SpotifyId); foreach (var name in related.Artists) { nameList.Add(name.Name.ToString()); } UpdateRelatedList(nameList); } }
public static async Task <EmbedBuilder> Search(string requestString) { string song_name; string album_name; int popuarity; string artistname; string genres_string = ""; EmbedBuilder embedBuilder = new EmbedBuilder(); //Getting tokens from our json. GetSpotifyTokens(); //Connection of Bot client var config = SpotifyClientConfig.CreateDefault(); var request = new ClientCredentialsRequest(Bot_id, Bot_ids); var response = await new OAuthClient(config).RequestToken(request); var spotify = new SpotifyClient(config.WithToken(response.AccessToken)); // --- try { SearchRequest searchRequest = new SearchRequest(SearchRequest.Types.All, requestString); searchRequest.Limit = 5; var result = await spotify.Search.Item(searchRequest); //Sending search request and obtaining data obj EmbedBuilder embed = EmbedCreator(result, spotify); if (embed == null) { throw new ArgumentException(""); } return(embed); } catch (Exception e) { throw new ArgumentException($"No matches found for \"{requestString}\"."); } }
/// <summary> /// This method is created for command !listen. /// Returns string with genres of songs artist and popularity score. /// </summary> /// <param name="songName"></param> /// <returns></returns> /// <exception cref="ArgumentException"></exception> public static async Task <Tuple <int, string> > Listen(string songName) { GetSpotifyTokens(); //Connection of Bot client var config = SpotifyClientConfig.CreateDefault(); var request = new ClientCredentialsRequest(Bot_id, Bot_ids); var response = await new OAuthClient(config).RequestToken(request); var spotify = new SpotifyClient(config.WithToken(response.AccessToken)); // --- try { var result = await spotify.Search.Item(new SearchRequest(SearchRequest.Types.All, songName)); //Sending search request and creating json string data_json = result.Tracks.ToJson(); dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(data_json); var popularity = data.Items[0].Popularity; //популярність треку //GenreSearch string artistid = data.Items[0].Album.Artists[0].Id.ToString(); var artist = await spotify.Artists.Get(artistid); var artistname = data.Items[0].Artists[0].Name.ToString(); string genres_string = ""; foreach (var genre in artist.Genres.ToArray()) { genres_string = genres_string + "+" + genre; } return(Tuple.Create((int)popularity, genres_string)); } catch (Exception e) { throw new ArgumentException($"Song \"{songName}\" was not found."); } }
private static void Main(string[] args) { var appReg = new TokenTools.Microsoft.ApplicationRegistration() { ClientId = "c5b373fb-7e75-4620-81e9-161c8704b838", ClientSecret = "fdPKI740^lpmosPDLD51@[:" }; var tokenRequest = new ClientCredentialsRequest(appReg); var tokenResponse = tokenRequest.RequestToken().Result; Console.WriteLine("Token Response:"); Console.WriteLine(JsonConvert.SerializeObject(tokenResponse, Formatting.Indented)); Console.WriteLine(); Console.WriteLine("Access Token Claims:"); var accessTokenClaims = tokenResponse.DecodeAccessToken(); Console.WriteLine(JsonConvert.SerializeObject(accessTokenClaims, Formatting.Indented)); Console.ReadKey(); }
async Task GetAlbumsAsync() { if (IsBusy) { return; } try { IsBusy = true; var config = SpotifyClientConfig.CreateDefault(); var request = new ClientCredentialsRequest(clientId, clientSecret); var response = await new OAuthClient(config).RequestToken(request); var spotify = new SpotifyClient(config.WithToken(response.AccessToken)); var albumsRaw = await spotify.Artists.GetAlbums(Authors[AuthorSelected]); var albums = albumsRaw.Items; Albums.Clear(); foreach (var album in albums) { var songsRaw = await spotify.Albums.GetTracks(album.Id); var songs = songsRaw.Items; Albums.Add(Album.FromSimpleAlbum(album, songs)); } } catch (Exception ex) { Debug.WriteLine($"Error to get albums: {ex.Message}"); await Application.Current.MainPage.DisplayAlert("Error with albums! ", ex.Message, "Dobrá"); } finally { IsBusy = false; } }
/// <summary> /// For Spotify API calls that only require client authorization, not tied to a specific user /// See: https://developer.spotify.com/documentation/general/guides/authorization-guide/#client-credentials-flow /// </summary> private async Task <GetSpotifyApiOutput> GetApiWithClientCredentials() { string clientId = _configuration.GetValue <string>(AppSettingKeys.Spotify.ClientId); string clientSecret = _configuration.GetValue <string>(AppSettingKeys.Spotify.ClientSecret); var config = SpotifyClientConfig.CreateDefault(); try { var request = new ClientCredentialsRequest(clientId, clientSecret); var response = await new OAuthClient(config).RequestToken(request); return(new GetSpotifyApiOutput { Api = new SpotifyClient(response.AccessToken, response.TokenType), TokenResponse = response }); } catch (Exception ex) { Logger.LogError("ClientId: {0}, Message: {1}", clientId, ex.Message); throw new Exception("Error requesting Spotify access token: " + ex.Message); } }
// 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; }
public AudioHelper(LavaNode lavanode, EmbedHelper eh) { Node = lavanode; embedHelper = eh; // TODO: Make SpotifyClient own class if (Program.BotConfig.SpotifyClientId != "" && Program.BotConfig.SpotifySecret != "") { var config = SpotifyClientConfig.CreateDefault(); var request = new ClientCredentialsRequest(Program.BotConfig.SpotifyClientId, Program.BotConfig.SpotifySecret); var response = new OAuthClient(config).RequestToken(request); var spotify = new SpotifyClient(config.WithToken(response.Result.AccessToken)); Spotify = spotify; _disconnectTokens = new ConcurrentDictionary <ulong, CancellationTokenSource>(); SpotifyLogin = true; } // Handler for when a LavaTrack is started // args: TrackStartEventArgs Node.OnTrackStarted += async(args) => { var player = args.Player; var queue = await GetNewEmbedQueueString(player); var embed = await embedHelper.BuildMusicEmbed(player, Color.DarkTeal); //If for some reason Volume is set to 0 (100%) it will set to default volume if (player.Volume == 0) { await player.UpdateVolumeAsync(Program.BotConfig.Volume); } var content = queue switch { "" => NoSongsInQueue, _ => string.Format(QueueMayHaveSongs, queue) }; await Program.BotConfig.BotEmbedMessage.ModifyAsync(x => { x.Embed = embed; x.Content = content; }); if (!_disconnectTokens.TryGetValue(args.Player.VoiceChannel.Id, out var value)) { return; } if (value.IsCancellationRequested) { return; } value.Cancel(true); }; // Handler for when a LavaTrack is ended, stopped, or skipped // args: TrackEndedEventArgs Node.OnTrackEnded += async(args) => { var player = args.Player; if (RepeatFlag) { await player.PlayAsync(RepeatTrack); return; } RepeatFlag = false; if (!args.Reason.ShouldPlayNext()) { return; } if (!player.Queue.TryDequeue(out var track) && player.Queue.Count == 0) { var embed = await EmbedHelper.BuildDefaultEmbed(); await Program.BotConfig.BotEmbedMessage.ModifyAsync(x => { x.Content = NoSongsInQueue; x.Embed = embed; }); if (!StayFlag) { _ = InitiateDisconnectAsync(args.Player, TimeSpan.FromMinutes(15)); } return; } await args.Player.PlayAsync(track); }; // Handler for when a LavaTrack throws an exception // args: TrackExceptionEventArgs Node.OnTrackException += async(args) => { var player = args.Player; var errorMessage = args.ErrorMessage switch { "This video cannot be viewed anonymously." => "This video most likely hasn't premiered yet.", "Received unexpected response from YouTube." => "YouTube is most likely down.", _ => "Video might still be processing, try again later." }; var msg = await embedHelper.BuildTrackErrorEmbed($"[{player.Track.Title}]({player.Track.Url})\n{errorMessage}"); await player.TextChannel.SendAndRemove(embed : msg); if (player.Queue.Count == 0) { //If no songs in queue it will stop playback to reset the embed await player.StopAsync(); return; } //If queue has any songs it will skip to the next track await player.SkipAsync(); return; }; // Handler for when a LavaTrack gets stuck // args: TrackStuckEventArgs Node.OnTrackStuck += async(args) => { var player = args.Player; var msg = await embedHelper.BuildTrackErrorEmbed($"[{player.Track.Title}]({player.Track.Url})\nTrack got stuck, moving on..."); await player.TextChannel.SendAndRemove(embed : msg); if (player.Queue.Count == 0) { //If no songs in queue it will stop playback to reset the embed await player.StopAsync(); return; } //If queue has any songs it will skip to the next track await player.SkipAsync(); return; }; } /// <summary> /// Initiates a disconnect from the voice channel /// </summary> /// <param name="player">Instance of LavaPlayer for the guild</param> /// <param name="timeSpan">TimeSpan for length before disconnecting</param> /// <returns></returns> private async Task InitiateDisconnectAsync(LavaPlayer player, TimeSpan timeSpan) { if (!_disconnectTokens.TryGetValue(player.VoiceChannel.Id, out var value)) { value = new CancellationTokenSource(); _disconnectTokens.TryAdd(player.VoiceChannel.Id, value); } else if (value.IsCancellationRequested) { _disconnectTokens.TryUpdate(player.VoiceChannel.Id, new CancellationTokenSource(), value); value = _disconnectTokens[player.VoiceChannel.Id]; } var isCancelled = SpinWait.SpinUntil(() => value.IsCancellationRequested, timeSpan); if (isCancelled) { return; } await Node.LeaveAsync(player.VoiceChannel); var msg = await embedHelper.BuildMessageEmbed("Muse has disconnected due to inactivity."); await player.TextChannel.SendAndRemove(embed : msg); }