public async void ShouldSortItemsDescending() { // Arrange var accessToken = "BQAqqcamWRPmlTQIXjJdU434qvufZ3FOp6yrgNTW38ug6YRz9PkI8b3RWT8oZREU2HNZDjUJGtBNs4t4omxa2oPWJteF9jvVVXoARVUkJKIj90zulM1qWeP8zxMd9ZSkJN9lSoxmbeO7U0eXbKcsKDodAXqyzaFGvdMgsHW3PbnWk34nBqzYlvMjlRTNmSY0jFJ_8jOEIPHh_rkMdmZDyZNqDlei_32nlyV93ZXwEyUIyMkM928mBBLpfIivnuE2Jx-2UXMQIMRpbs_rOq3p"; var playlistId = "5qwobGpX8XWmsT9sdbX8ms"; var userService = new Mock <ICurrentUserService>(); var tokenService = new Mock <IUserTokenService>(); var spotifyConfig = SpotifyClientConfig.CreateDefault(); var spotifyClient = new SpotifyClient(spotifyConfig.WithToken(accessToken)); var spotifyService = new SpotifyService(userService.Object, spotifyConfig, tokenService.Object); var beforePlaylist = await spotifyClient.Playlists.Get(playlistId); beforePlaylist.Tracks.Items.OrderByDescending(x => x.AddedAt); // Act await spotifyService.SortPlaylistAsync(playlistId, Domain.Enums.SortDirection.Descending, CancellationToken.None); var assertPlaylist = await spotifyClient.Playlists.Get(playlistId); // Assert // AddedDate should be the same assertPlaylist.Tracks.Items[0].AddedAt.Should().Be(beforePlaylist.Tracks.Items[0].AddedAt); }
public async void Start() { try { _authenticator = new PKCEAuthenticator(_clientId !, TokenResponse); var config = SpotifyClientConfig.CreateDefault() .WithAuthenticator(_authenticator); _spotifyClient = new SpotifyClient(config); var user = await _spotifyClient.UserProfile.Current(); //var playlists = await _spotifyClient.Playlists.GetUsers(user.Id); _user = user; //UserPlaylists = playlists; if (user.Product == "premium") { IsPremiumUser = true; } OnLoggedIn?.Invoke(_user, TokenResponse); _stateThread = new Thread(StateUpdateTimer); _stateThread.Start(); } catch (Exception e) { //We will just ignore for now, this should be handled better though } }
public static void Run() { var config = SpotifyClientConfig .CreateDefault() .WithAuthenticator(new ClientCredentialsAuthenticator("1b5ad373ad7449228cf8a7c26ae969af", "1563b6253ba04c55bd6e2092adee5fb2")); _spotifyClient = new SpotifyClient(config); var counts = new int[10]; AddCounts(counts, "6RxsseYlyxrkJOOmAOLQTM").Wait(); // Rolling stone 500 AddCounts(counts, "0xIhTsBJm7fpW2Q4cicDrX").Wait(); // Top Wszechczasów AddCounts(counts, "3RFC2ZoAqj2utRUNQxrTzb").Wait(); // Polski top Wszechczasów AddCounts(counts, "0WEvguGJN7UslUZN5Wpm8B").Wait(); // Don's Tunes AddCounts(counts, "4Op1LnZYmLtnrR8ffxHyIv").Wait(); // Best bass guitar riffs AddCounts(counts, "37i9dQZF1DWSf2RDTDayIx").Wait(); // Happy Beats AddCounts(counts, "37i9dQZF1DWWEJlAGA9gs0").Wait(); // Classical Essentials AddCounts(counts, "37i9dQZF1DWWn6teJIIcfG").Wait(); // Creative Focus AddCounts(counts, "37i9dQZF1DX0BcQWzuB7ZO").Wait(); // Dance Hits AddCounts(counts, "37i9dQZF1DX2TRYkJECvfC").Wait(); // Deep House Relax AddCounts(counts, "37i9dQZF1DWZeKCadgRdKQ").Wait(); // Deep Focus AddCounts(counts, "37i9dQZF1DWWQRwui0ExPn").Wait(); // Lo-Fi Beats AddCounts(counts, "37i9dQZF1DX4sWSpwq3LiO").Wait(); // Peaceful Piano AddCounts(counts, "37i9dQZF1DWV7EzJMK2FUI").Wait(); // Jazz in the background AddCounts(counts, "2YMRuaTDBC5X4jsfUBlD3i").Wait(); //Northern Echoes int number = 1; counts.Skip(1).ToList().ForEach(x => { //Console.WriteLine($"{number++} - {x}"); Console.WriteLine(x); }); }
public static async Task Desmute() { var json = await File.ReadAllTextAsync(CredentialsPath); var token = JsonConvert.DeserializeObject <PKCETokenResponse>(json); var authenticator = new PKCEAuthenticator(clientId !, token); authenticator.TokenRefreshed += (sender, token) => File.WriteAllText(CredentialsPath, JsonConvert.SerializeObject(token)); var config = SpotifyClientConfig.CreateDefault() .WithAuthenticator(authenticator); var spotify = new SpotifyClient(config); var me = await spotify.UserProfile.Current(); // Debug.WriteLine($"Welcome {me.DisplayName} ({me.Id}), you're authenticated!"); PlayerVolumeRequest playvolumecontext = new PlayerVolumeRequest(volumeBefore); await spotify.Player.SetVolume(playvolumecontext); Mute = false; _server.Dispose(); }
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); }
private async Task RefreshTokenAsync(string refreshToken) { try { // await File.WriteAllTextAsync("code.txt", code); var response = await new OAuthClient().RequestToken( new AuthorizationCodeRefreshRequest(spotifyConfig.ClientId, spotifyConfig.ClientSecret, refreshToken) ); var config = SpotifyClientConfig .CreateDefault() .WithAuthenticator(new AuthorizationCodeAuthenticator(spotifyConfig.ClientId, spotifyConfig.ClientSecret, new AuthorizationCodeTokenResponse() { AccessToken = response.AccessToken, ExpiresIn = response.ExpiresIn, RefreshToken = refreshToken, CreatedAt = response.CreatedAt, Scope = response.Scope, TokenType = response.TokenType })); spotifyClient = new SpotifyClient(config); IsAuthed = true; } catch (Exception ex) { // TODO: figure out what might lead here return; } }
private void RegisterServices(IServiceCollection services) { services.AddHttpContextAccessor(); services.AddSingleton(SpotifyClientConfig.CreateDefault()); services.AddScoped <IAccountService, AccountService>(); }
public async Task <bool> SwapCodeForTokenAsync(string code) { try { // await File.WriteAllTextAsync("code.txt", code); var response = await new OAuthClient().RequestToken( new AuthorizationCodeTokenRequest(spotifyConfig.ClientId, spotifyConfig.ClientSecret, code, new Uri("https://localhost:5001/callback")) ); await File.WriteAllTextAsync("refresh.txt", response.RefreshToken); var config = SpotifyClientConfig .CreateDefault() .WithAuthenticator(new AuthorizationCodeAuthenticator(spotifyConfig.ClientId, spotifyConfig.ClientSecret, response)); spotifyClient = new SpotifyClient(config); IsAuthed = true; return(true); } catch (Exception ex) { // TODO: figure out what might lead here return(false); } }
public static async Task PlayPlaylist(SimplePlaylist playlist) { var json = await File.ReadAllTextAsync(CredentialsPath); var token = JsonConvert.DeserializeObject <PKCETokenResponse>(json); var authenticator = new PKCEAuthenticator(clientId !, token); authenticator.TokenRefreshed += (sender, token) => File.WriteAllText(CredentialsPath, JsonConvert.SerializeObject(token)); var config = SpotifyClientConfig.CreateDefault() .WithAuthenticator(authenticator); var spotify = new SpotifyClient(config); var me = await spotify.UserProfile.Current(); PlayerResumePlaybackRequest teste = new PlayerResumePlaybackRequest(); teste.ContextUri = playlist.Uri; await spotify.Player.ResumePlayback(teste); _server.Dispose(); // Environment.Exit(0); }
private async Task <string?> GetSpotifyTrack(string link) { var spotifyConfig = SpotifyClientConfig .CreateDefault() .WithAuthenticator( new ClientCredentialsAuthenticator(config["SpotifyId"], config["SpotifySecret"])); var spotify = new SpotifyClient(spotifyConfig); var id = link.Split("/").LastOrDefault(); var idWithoutQueryString = id?.Split("?").FirstOrDefault(); if (idWithoutQueryString != null) { id = idWithoutQueryString; } var track = await spotify.Tracks.Get(id ?? ""); string?result = null; if (track != null) { result = ""; foreach (var artist in track.Artists) { result += artist.Name + " "; } result += " " + track.Name; } return(result); }
public static async Task <System.Collections.Generic.IList <SpotifyAPI.Web.SimplePlaylist> > getAllPlayerList() { var json = await File.ReadAllTextAsync(CredentialsPath); var token = JsonConvert.DeserializeObject <PKCETokenResponse>(json); var authenticator = new PKCEAuthenticator(clientId !, token); authenticator.TokenRefreshed += (sender, token) => File.WriteAllText(CredentialsPath, JsonConvert.SerializeObject(token)); var config = SpotifyClientConfig.CreateDefault() .WithAuthenticator(authenticator); var spotify = new SpotifyClient(config); var me = await spotify.UserProfile.Current(); var playlists = await spotify.PaginateAll(await spotify.Playlists.CurrentUsers().ConfigureAwait(false)); _server.Dispose(); return(playlists); // Environment.Exit(0); }
public static async Task <SimplePlaylist> getPlayListById(string id) { var json = await File.ReadAllTextAsync(CredentialsPath); var token = JsonConvert.DeserializeObject <PKCETokenResponse>(json); var authenticator = new PKCEAuthenticator(clientId !, token); authenticator.TokenRefreshed += (sender, token) => File.WriteAllText(CredentialsPath, JsonConvert.SerializeObject(token)); var config = SpotifyClientConfig.CreateDefault() .WithAuthenticator(authenticator); var spotify = new SpotifyClient(config); var me = await spotify.UserProfile.Current(); var playlists = await spotify.PaginateAll(await spotify.Playlists.CurrentUsers().ConfigureAwait(false)); SimplePlaylist item = null; foreach (SimplePlaylist list_item in playlists) { if (list_item.Id == id) { item = list_item; break; } } _server.Dispose(); return(item); }
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration, bool useInMemoryDatabase) { var configSection = configuration.GetSection(ConfigurationSection); if (!configSection.Exists()) { throw new ConfigurationSectionMissingException(ConfigurationSection); } var databaseConfig = configSection.Get <SqlDatabaseConfiugration>(); if (useInMemoryDatabase) { services.AddDbContext <IDatabaseContext, DatabaseContext>(options => options.UseInMemoryDatabase("CleanArchitectureDb")); } else { services.AddDbContext <IDatabaseContext, DatabaseContext>( options => options.UseSqlServer(databaseConfig.ConnectionString, builder => builder.MigrationsAssembly(typeof(DatabaseContext).Assembly.FullName))); } var serviceBusConfiguration = configuration.GetSection("ServiceBus").Get <QueueClientConfiguration>(); services.AddSingleton <QueueClientConfiguration>(serviceBusConfiguration); services.AddScoped <IQueueClient, ServiceBusQueueClient>(); services.AddScoped <IUserTokenService, UserTokenService>(); services.AddSingleton <SpotifyClientConfig>((c) => SpotifyClientConfig.CreateDefault()); services.AddScoped <IStreamingService, SpotifyService>(); services.AddScoped <IDomainEventService, DomainEventService>(); return(services); }
private void Start() { Log.Instance.PrintMessage("Trying to connect to Spotify...", MessageType.Info, "Spotify.Start()"); User = null; Stopwatch crono = Stopwatch.StartNew(); Kernel.InternetAvaliable(false); try { SpotifyConfig = SpotifyClientConfig.CreateDefault().WithAuthenticator(new ClientCredentialsAuthenticator(PublicKey, PrivateKey)); SpotifyClient = new SpotifyClient(SpotifyConfig); crono.Stop(); if (SpotifyConfig is not null) //?? { Kernel.InternetAvaliable(true); Log.Instance.PrintMessage("Connected!", MessageType.Correct, crono, TimeType.Milliseconds); } else //yo creoque esto nunca se ejecuta... { Kernel.InternetAvaliable(false); Log.Instance.PrintMessage("Token is null", MessageType.Error, crono, TimeType.Milliseconds); } } catch (APIException ex) { Kernel.InternetAvaliable(false); Log.Instance.PrintMessage(ex.Message, MessageType.Error); MessageBox.Show(Kernel.LocalTexts.GetString("error_internet")); } }
public SpotifyService(ApplicationConfig appConfig, IConsole console) { _appConfig = appConfig; _console = console; if (!string.IsNullOrEmpty(appConfig.SpotifyToken.RefreshToken)) { // We're logged in as a user _config = CreateForUser(); _spotify = new SpotifyClient(_config); } else if ( !string.IsNullOrEmpty(appConfig.SpotifyApp.ClientId) && !string.IsNullOrEmpty(appConfig.SpotifyApp.ClientSecret) ) { _config = CreateForCredentials(); _spotify = new SpotifyClient(_config); } else { _config = SpotifyClientConfig.CreateDefault(); } _oauth = new OAuthClient(_config); }
public async UniTaskVoid FromAuthorizationCode(string authorizationCode) { try { string clientId = SpotifyConfiguration.ClientConfiguration.ClientID; string clientSecret = SpotifyConfiguration.ClientConfiguration.ClientSecret; Uri redirectUri = SpotifyConfiguration.ServerConfiguration.Uri; var response = await new OAuthClient().RequestToken( new AuthorizationCodeTokenRequest(clientId, clientSecret, authorizationCode, redirectUri) ); var config = SpotifyClientConfig .CreateDefault() .WithAuthenticator(new AuthorizationCodeAuthenticator(clientId, clientSecret, response)); Value = new SpotifyAPI.Web.SpotifyClient(config); Debug.Log("Login and client configuration successful."); OnAuthenticationCompleted.Raise(); } catch (Exception e) { Debug.LogException(e); } }
public ISpotifyClient GetSpotifyClient() { var clientInfo = new SpotifyClientInfo( EnvHelpers.GetEnvOrDefault("SPOTPG_SPOTIFY_CLIENT_ID", this.configuration.ClientId), EnvHelpers.GetEnvOrDefault("SPOTPG_SPOTIFY_CLIENT_SECRET", this.configuration.ClientSecret)); if (this.client != null && this.currentInfo == clientInfo) { return(this.client); } this.serviceLogger.LogInfo("Recreation Spotify client..."); var authResponse = new AuthorizationCodeTokenResponse { AccessToken = this.configuration.AccessToken, RefreshToken = this.configuration.RefreshToken }; var auth = new AuthorizationCodeAuthenticator(clientInfo.Id, clientInfo.Secret, authResponse); var config = SpotifyClientConfig.CreateDefault() .WithDefaultPaginator(new SimplePaginator()) .WithRetryHandler(new SimpleRetryHandler()) .WithAuthenticator(auth); this.client = new SpotifyClient(config); this.currentInfo = clientInfo; this.serviceLogger.LogInfo("New Spotify client was created successfully"); return(this.client); }
public static async Task setVolume(int volume) { if (Mute) { await Desmute(); } var json = await File.ReadAllTextAsync(CredentialsPath); var token = JsonConvert.DeserializeObject <PKCETokenResponse>(json); var authenticator = new PKCEAuthenticator(clientId !, token); authenticator.TokenRefreshed += (sender, token) => File.WriteAllText(CredentialsPath, JsonConvert.SerializeObject(token)); var config = SpotifyClientConfig.CreateDefault() .WithAuthenticator(authenticator); var spotify = new SpotifyClient(config); var me = await spotify.UserProfile.Current(); // Debug.WriteLine($"Welcome {me.DisplayName} ({me.Id}), you're authenticated!"); int atualpercent = spotify.Player.GetCurrentPlayback().Result.Device.VolumePercent.GetValueOrDefault(); int result = atualpercent + volume; PlayerVolumeRequest playvolumecontext = new PlayerVolumeRequest(result); await spotify.Player.SetVolume(playvolumecontext); _server.Dispose(); // Environment.Exit(0); }
public async Task <ISpotifyClient> GetClientAsync(string mbUserId) { var token = await GetTokenAsync(mbUserId); if (token == null) { return(null); } var authenticator = new AuthorizationCodeAuthenticator(config.SpotifyClientId, config.SpotifyClientSecret, token); authenticator.TokenRefreshed += delegate(object o, AuthorizationCodeTokenResponse token) { // TODO: Logging via constructor - this value of log is currently null // log.LogInformation("Refreshing spotify token for user {user}", user); Task.Run(async() => { await SaveTokenAsync(mbUserId, token); }).Wait(); }; var spotifyConfig = SpotifyClientConfig .CreateDefault() .WithAuthenticator(authenticator); return(new SpotifyClient(spotifyConfig)); }
/// <summary> /// Checks if user is authenticated /// </summary> /// <returns> /// Null if failed, Profile if successful /// </returns> public static async Task <PrivateUser> IsAuthenticated() { //check if file with token exists, if it does not exist, login will be shown if (!File.Exists(CredentialsPath)) { return(null); } var json = await File.ReadAllTextAsync(CredentialsPath); var token = JsonConvert.DeserializeObject <AuthorizationCodeTokenResponse>(json); CheckCliendSecretId(); if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(clientSecret)) { return(null); } var authenticator = new AuthorizationCodeAuthenticator(clientId, clientSecret, token); authenticator.TokenRefreshed += (sender, tokenx) => File.WriteAllText(CredentialsPath, JsonConvert.SerializeObject(tokenx)); //might throw an error if user revoked access to their spotify account var config = SpotifyClientConfig.CreateDefault() .WithAuthenticator(authenticator); SpotifyClient = new SpotifyClient(config); //try and get user profile return(await SpotifyClient.UserProfile.Current()); }
public SpotifyService(ICurrentUserService userService, SpotifyClientConfig spotifyClientConfig, IUserTokenService tokenService) { _UserService = userService; _ClientConfig = spotifyClientConfig; _TokenService = tokenService; _TokenRefreshPolicy = CreateRetryPolicy(); }
static void Connect() { var response = new AuthorizationCodeTokenResponse { AccessToken = Environment.GetEnvironmentVariable("SPOTIFY_ACCESS_TOKEN"), TokenType = "Bearer", ExpiresIn = 0, RefreshToken = Environment.GetEnvironmentVariable("SPOTIFY_REFRESH_TOKEN"), Scope = "playlist-read-private playlist-read-collaborative user-follow-modify user-library-read user-library-modify user-follow-read playlist-modify-private playlist-modify-public user-read-birthdate user-read-email user-read-private" }; var config = SpotifyClientConfig .CreateDefault() .WithAuthenticator(new AuthorizationCodeAuthenticator( Environment.GetEnvironmentVariable("SPOTIFY_CLIENT_ID"), Environment.GetEnvironmentVariable("SPOTIFY_CLIENT_SECRET"), response )); var spotify = new SpotifyClient(config); var looper = new SpotifyStatusLooper(telegram, spotify); looper.Loop().Wait(); }
public SpotifyClientService() { var config = SpotifyClientConfig.CreateDefault() .WithAuthenticator(new ClientCredentialsAuthenticator(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET)); _spotify = new SpotifyClient(config); }
private static async Task Start() { var json = await File.ReadAllTextAsync(CredentialsPath); var token = JsonConvert.DeserializeObject <PKCETokenResponse>(json); var authenticator = new PKCEAuthenticator(clientId !, token); authenticator.TokenRefreshed += (sender, token) => File.WriteAllText(CredentialsPath, JsonConvert.SerializeObject(token)); var config = SpotifyClientConfig.CreateDefault() .WithAuthenticator(authenticator); var spotify = new SpotifyClient(config); var me = await spotify.UserProfile.Current(); Console.WriteLine($"Welcome {me.DisplayName} ({me.Id}), you're authenticated!"); var playlists = await spotify.PaginateAll(await spotify.Playlists.CurrentUsers().ConfigureAwait(false)); Console.WriteLine($"Total Playlists in your Account: {playlists.Count}"); _server.Dispose(); Environment.Exit(0); }
public async Task <SpotifyClient> BuildClient() { var config = SpotifyClientConfig .CreateDefault() .WithAuthenticator(new ClientCredentialsAuthenticator(Configuration["SpotifySettings:ClientID"], Configuration["SpotifySettings:ClientSecret"])); return(new SpotifyClient(config)); }
/// <summary> /// Returns an authorized client via clientID and secretID. /// This is an analog of constructor which is using <see cref="SpotifyClientConfig" /> /// </summary> /// <param name="clientId">ClientID which you can get from your SpotifyApp</param> /// <param name="secretId">SecretID which you can get from your SpotifyApp</param> /// <returns>Instance of <see cref="SpotifySearchEngine{TIn}" /></returns> public static SpotifyClient GetAuthorizedByIds(string clientId, string secretId) { Guarantee.IsStringNotNullOrEmpty(clientId, nameof(clientId)); Guarantee.IsStringNotNullOrEmpty(secretId, nameof(secretId)); return(new SpotifyClient(SpotifyClientConfig.CreateDefault() .WithAuthenticator(new ClientCredentialsAuthenticator(clientId, secretId)))); }
public static SpotifyClient CreateSpotifyClient(SpotifyAPICredentials spotifyAPICredentials) { var config = SpotifyClientConfig .CreateDefault() .WithAuthenticator(new ClientCredentialsAuthenticator(spotifyAPICredentials.ClientId, spotifyAPICredentials.ClientSecret)); return(new SpotifyClient(config)); }
public void Initialize() { var config = SpotifyClientConfig .CreateDefault() .WithAuthenticator(new ClientCredentialsAuthenticator(_config["SpotifyClientID"], _config["SpotifyClientSecret"])); _spotifyClient = new SpotifyClient(config); }
public static async Task <SpotifyClient> Authenticate() { CheckCliendSecretId(); if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(clientSecret)) { return(null); } var request = new LoginRequest(_server.BaseUri, clientId, LoginRequest.ResponseType.Code) { Scope = new List <string> { UserReadPrivate, PlaylistReadPrivate, UserModifyPlaybackState, UserLibraryModify, UserLibraryRead, PlaylistModifyPrivate, PlaylistModifyPublic, UgcImageUpload } }; Uri uri = request.ToUri(); Uri StartUri = uri; Uri EndUri = new Uri("http://localhost:5000/callback"); WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync( WebAuthenticationOptions.None, StartUri, EndUri); if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success) { var index = WebAuthenticationResult.ResponseData.IndexOf("code="); string code = WebAuthenticationResult.ResponseData.Substring(index + 5); var config = SpotifyClientConfig.CreateDefault(); var tokenResponse = await new OAuthClient(config).RequestToken( new AuthorizationCodeTokenRequest( clientId, clientSecret, code, EndUri)); SpotifyClient = new SpotifyClient(tokenResponse.AccessToken); try { if (!File.Exists(CredentialsPath)) { await ApplicationData.Current.LocalFolder.CreateFileAsync("credentials.json"); } await File.WriteAllTextAsync(CredentialsPath, JsonConvert.SerializeObject(tokenResponse)); } catch (Exception) { } return(SpotifyClient); } else { return(null); } }
public SpotifyService() { var config = SpotifyClientConfig.CreateDefault() .WithAuthenticator(new ClientCredentialsAuthenticator( Config.Data.SpotifyId, Config.Data.SpotifySecret)); client = new SpotifyClient(config); }