Example #1
0
        public async Task <OperationResult <GetPlaylistsQuery, GetPlaylistsResponse> > HandleAsync(GetPlaylistsQuery query)
        {
            OperationResult <GetPlaylistsQuery, GetPlaylistsResponse> result;

            try
            {
                if (query?.AccessToken == null)
                {
                    throw new APIUnauthorizedException();
                }

                var config = SpotifyClientConfig
                             .CreateDefault(query.AccessToken)
                             .WithRetryHandler(new SimpleRetryHandler()
                {
                    RetryTimes = 30, RetryAfter = TimeSpan.FromSeconds(1), TooManyRequestsConsumesARetry = false
                });

                spotify = new SpotifyClient(config);

                var playlistsTuple = await GetUserPlaylists(query.Index, query.OwnerId);

                var response = new GetPlaylistsResponse
                {
                    Playlists  = playlistsTuple.Item1,
                    IsFinished = playlistsTuple.Item2,
                    Index      = playlistsTuple.Item3
                };

                result = OperationResult <GetPlaylistsQuery, GetPlaylistsResponse> .Success(response);

                return(await Task.FromResult(result));
            }
            catch (APIUnauthorizedException)
            {
                result = OperationResult <GetPlaylistsQuery, GetPlaylistsResponse> .Failure(StatusCodes.Unauthorized, ErrorMessages.SessionExpired);

                return(await Task.FromResult(result));
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "An unexpected error occurred.");
                result = OperationResult <GetPlaylistsQuery, GetPlaylistsResponse> .Failure(StatusCodes.InternalServerError, ErrorMessages.UnexpectedError);

                return(await Task.FromResult(result));
            }
        }
        //HashSet<Edge> Edges = new HashSet<Edge>();

        public ArtistsConnectionsForm()
        {
            InitializeComponent();
            var config = SpotifyClientConfig.CreateDefault().WithAuthenticator(new ClientCredentialsAuthenticator("e6bf2e305d98443190c472ee318fd511", "96bad35ecf9c41f581a761eb3a85348b"));

            Spotify = new SpotifyClient(config);
            ArtistsToCheck.Enqueue("4JxdBEK730fH7tgcyG3vuv", 0);
            int n = 0;

            while (ArtistsToCheck.Count > 0 && ArtistsToCheck.GetPriority(ArtistsToCheck.First) <= 2)
            {
                string first    = ArtistsToCheck.First;
                float  priority = ArtistsToCheck.GetPriority(first);
                ArtistsToCheck.Dequeue();
                Task <List <string> > artistsTask = FindAllConnectedArtists(first, priority);
                artistsTask.Wait();
                n++;
            }
            List <string> edges = new List <string>();

            foreach (Edge edge in ArtistsGraph.Edges)
            {
                string sourceName;
                string targetName;
                ArtistIdToName.TryGetValue(edge.Source, out sourceName);
                ArtistIdToName.TryGetValue(edge.Source, out targetName);
                edges.Add(sourceName + " - " + edge.LabelText + " - " + targetName);
            }
            ListBox1.DataSource = edges;
            while (ArtistsToCheck.Count > 0)
            {
                string name;
                ArtistIdToName.TryGetValue(ArtistsToCheck.First, out name);
                float priority = ArtistsToCheck.GetPriority(ArtistsToCheck.First);
                ArtistsToCheck.Dequeue();
                ListBox3.Items.Add(name + " - " + priority);
            }
            foreach (string id in CheckedArtists)
            {
                string name;
                ArtistIdToName.TryGetValue(id, out name);
                ListBox2.Items.Add(name);
            }
            label1.Text = ListBox1.Items.Count.ToString();
            label2.Text = ListBox2.Items.Count.ToString();
            label3.Text = ListBox3.Items.Count.ToString();
        }
Example #3
0
        public async Task <ISpotifyClient> CreateSpotifyClientAsync()
        {
            PKCETokenResponse tokenResponse = _config.Tokens;

            if (String.IsNullOrEmpty(tokenResponse.AccessToken) || String.IsNullOrEmpty(tokenResponse.RefreshToken))
            {
                tokenResponse = await UseNewTokens();
            }
            else if (tokenResponse.HasExpired())
            {
                tokenResponse = await RefreshTokens();
            }

            var config = SpotifyClientConfig.CreateDefault().WithAuthenticator(new PKCEAuthenticator(_config.ClientId, tokenResponse));

            return(new SpotifyClient(config));
        }
Example #4
0
        private async Task <string?> SearchSpotify(string details)
        {
            var spotifyConfig = SpotifyClientConfig
                                .CreateDefault()
                                .WithAuthenticator(
                new ClientCredentialsAuthenticator(config["SpotifyId"], config["SpotifySecret"]));

            var spotify = new SpotifyClient(spotifyConfig);

            var searchResult = await spotify.Search.Item(new SearchRequest(SearchRequest.Types.Track, details));

            var track = searchResult.Tracks?.Items?.FirstOrDefault();

            var result = track?.ExternalUrls["spotify"];

            return(result);
        }
Example #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpContextAccessor();
            services.AddSingleton(SpotifyClientConfig.CreateDefault());
            services.AddScoped <SpotifyClientBuilder>();

            services.AddDbContext <MatchMusicContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("Default"));
            });


            services.AddAuthorization(options =>
            {
                options.AddPolicy("Spotify", policy =>
                {
                    policy.AuthenticationSchemes.Add("Spotify");
                    policy.RequireAuthenticatedUser();
                });
            });

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(options =>
            {
                options.ExpireTimeSpan = TimeSpan.FromMinutes(50);
            })
            .AddSpotify(options =>
            {
                options.ClientId     = Configuration["**"];
                options.ClientSecret = Configuration["**"];
                options.SaveTokens   = true;

                var scopes = new List <string>
                {
                    UserReadEmail, UserReadPrivate, PlaylistReadPrivate, PlaylistReadCollaborative, UserTopRead
                };
                options.Scope.Add(string.Join(",", scopes));
            })
            .Services.Configure <SpotifyAuthenticationOptions>("Spotify", Configuration.GetSection("Authentication:Spotify"));

            services.AddControllersWithViews();
        }
Example #6
0
        private async Task OnAuthorizationCodeReceivedAsync(object sender, AuthorizationCodeResponse response)
        {
            await Server.Stop();

            Server.Dispose();

            var config        = SpotifyClientConfig.CreateDefault();
            var tokenResponse = await new OAuthClient(config).RequestToken(new AuthorizationCodeTokenRequest(CLIENT_ID, CLIENT_SECRET, response.Code, new Uri("http://localhost:5000/callback")));

            SClient  = new SpotifyClient(tokenResponse.AccessToken);
            SToken   = tokenResponse.AccessToken;
            SRefresh = tokenResponse.RefreshToken;
            SReady   = true;
            SExpiry  = DateTime.Now.AddSeconds(tokenResponse.ExpiresIn);

            Console.Clear();
            await Util.LoggerAsync(new LogMessage(LogSeverity.Info, "Spotify", "Spotify Connected. You can now start queueing songs."));
        }
        public async Task NextPageForIPaginatable()
        {
            var api     = new Mock <IAPIConnector>();
            var config  = SpotifyClientConfig.CreateDefault("FakeToken").WithAPIConnector(api.Object);
            var spotify = new SpotifyClient(config);

            var response = new SearchResponse
            {
                Albums = new Paging <SimpleAlbum, SearchResponse>
                {
                    Next = "https://next-url",
                }
            };

            await spotify.NextPage(response.Albums);

            api.Verify(a => a.Get <SearchResponse>(new System.Uri("https://next-url")), Times.Once);
        }
Example #8
0
        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);

                _stateTaskCancellationTokenSource = new CancellationTokenSource();
                var token = _stateTaskCancellationTokenSource.Token;
                var task  = new Task(async(token) =>
                {
                    while (!((CancellationToken)token !).IsCancellationRequested)
                    {
                        var delayTask = Task.Delay(_playerRefreshTime); //Run timer every _playerRefreshTime
                        await CheckPlayerState();
                        await delayTask;
                    }
                }, _stateTaskCancellationTokenSource.Token);
                task.Start();
            }
            catch (Exception e)
            {
                //We will just ignore for now, this should be handled better though
            }
        }
Example #9
0
        public void RenewToken(int seconds)
        {
            var renewThread = Task.Run(async() =>
            {
                await Task.Delay(1000 * (seconds - 120));
                SReady = false;
                await Util.LoggerAsync(new LogMessage(LogSeverity.Info, "Spotify", "Spotify token refreshing."));

                var config        = SpotifyClientConfig.CreateDefault();
                var tokenResponse = await new OAuthClient(config).RequestToken(new AuthorizationCodeRefreshRequest(CLIENT_ID, CLIENT_SECRET, SRefresh));

                SClient = new SpotifyClient(tokenResponse.AccessToken);
                SToken  = tokenResponse.AccessToken;
                SReady  = true;
                SExpiry = DateTime.Now.AddSeconds(tokenResponse.ExpiresIn);

                await Util.LoggerAsync(new LogMessage(LogSeverity.Info, "Spotify", "Spotify token refreshed."));
            });
        }
        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);
            }
        }
Example #11
0
        private static async Task <SpotifyClient> GetSpotifyClient(string spotifyToken)
        {
            var config = SpotifyClientConfig.CreateDefault()
                         .WithToken(spotifyToken)
                         .WithRetryHandler(new SimpleRetryHandler {
                RetryAfter = TimeSpan.FromSeconds(1), RetryTimes = 1
            });

            var spotify = new SpotifyClient(config);

            var me = await spotify.UserProfile.Current().ConfigureAwait(false);

            if (string.IsNullOrWhiteSpace(me.Id))
            {
                throw new Exception("Authorization with Spotify failed.");
            }

            return(spotify);
        }
        public static bool StartCached(Action <SpotifyClient> onComplete)
        {
            if (!File.Exists(m_TokenPath))
            {
                return(false);
            }

            string            json  = File.ReadAllText(m_TokenPath);
            PKCETokenResponse token = JsonConvert.DeserializeObject <PKCETokenResponse>(json);

            PKCEAuthenticator authenticator = new PKCEAuthenticator(m_ClientId, token);

            authenticator.TokenRefreshed += (sender, refreshedToken) => File.WriteAllText(m_TokenPath, JsonConvert.SerializeObject(refreshedToken));

            SpotifyClientConfig config = SpotifyClientConfig.CreateDefault().WithAuthenticator(authenticator);
            SpotifyClient       client = new SpotifyClient(config);

            onComplete(client);
            return(true);
        }
        public async void SkipRemovalIfLimitIsNotExceeded()
        {
            //Arrange
            var userService = new Mock<ICurrentUserService>();
            userService.SetupGet(x => x.UserId).Returns("eimerreis");
            var userTokenService = new Mock<IUserTokenService>();

            var spotifyClientMock = new Mock<SpotifyClient>();
            spotifyClientMock.Setup(x => x.Playlists.Get(It.IsAny<string>()))
                .ReturnsAsync(JsonConvert.DeserializeObject<FullPlaylist>(""));

            var spotifyConfig = SpotifyClientConfig.CreateDefault();
            var spotifyService = new SpotifyService(userService.Object, spotifyConfig.WithToken(""), userTokenService.Object);

            //Act
            await spotifyService.RemoveOrArchiveTracksAsync("", 60, "");

            //Assert
            spotifyClientMock.Verify(x => x.Playlists.RemoveItems(It.IsAny<string>(), It.IsAny<PlaylistRemoveItemsRequest>()), Times.Never);
        }
Example #14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpContextAccessor();
            services.AddSingleton(SpotifyClientConfig.CreateDefault());
            services.AddScoped <SpotifyClientBuilder>();

            services.AddAuthorization(options =>
            {
                options.AddPolicy("Spotify", policy =>
                {
                    policy.AuthenticationSchemes.Add("Spotify");
                    policy.RequireAuthenticatedUser();
                });
            });
            services
            .AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(options =>
            {
                options.ExpireTimeSpan = TimeSpan.FromMinutes(50);
            })
            .AddSpotify(options =>
            {
                options.ClientId     = Configuration["SPOTIFY_CLIENT_ID"];
                options.ClientSecret = Configuration["SPOTIFY_CLIENT_SECRET"];
                options.CallbackPath = "/Auth/callback";
                options.SaveTokens   = true;

                var scopes = new List <string> {
                    UserReadEmail, UserReadPrivate, PlaylistReadPrivate, PlaylistReadCollaborative
                };
                options.Scope.Add(string.Join(",", scopes));
            });
            services.AddRazorPages()
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.AuthorizeFolder("/", "Spotify");
            });
        }
Example #15
0
        private async Task StartLoginSpotify(Stopwatch crono)
        {
            Log.Instance.PrintMessage("Logging to Spotify", MessageType.Info);
            var json = await File.ReadAllTextAsync(AuthPath);

            var token = JsonConvert.DeserializeObject <PKCETokenResponse>(json);
            var auth  = new PKCEAuthenticator(PublicKey, token);

            auth.TokenRefreshed += (sender, token) => File.WriteAllText(AuthPath, JsonConvert.SerializeObject(token));
            SpotifyConfig        = SpotifyClientConfig.CreateDefault().WithAuthenticator(auth);
            SpotifyClient        = new SpotifyClient(SpotifyConfig);
            AccountReady         = true;
            User = SpotifyClient.UserProfile.Current().Result;
            Log.Instance.PrintMessage("Connected as " + User.Email, MessageType.Correct, crono, TimeType.Seconds);
            Config.LinkedWithSpotify = true;
            AccountLinked            = true;
            Kernel.ActivarReproduccionSpotify();
            Kernel.InternetAvaliable(true);
            Kernel.BringMainFormFront();
            crono.Stop();
        }
Example #16
0
        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}\".");
            }
        }
Example #17
0
/// <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.");
            }
        }
Example #18
0
        public async void ShouldRemoveItems()
        {
            // Arrange
            var accessToken   = "BQAqqcamWRPmlTQIXjJdU434qvufZ3FOp6yrgNTW38ug6YRz9PkI8b3RWT8oZREU2HNZDjUJGtBNs4t4omxa2oPWJteF9jvVVXoARVUkJKIj90zulM1qWeP8zxMd9ZSkJN9lSoxmbeO7U0eXbKcsKDodAXqyzaFGvdMgsHW3PbnWk34nBqzYlvMjlRTNmSY0jFJ_8jOEIPHh_rkMdmZDyZNqDlei_32nlyV93ZXwEyUIyMkM928mBBLpfIivnuE2Jx-2UXMQIMRpbs_rOq3p";
            var playlistId    = "5qwobGpX8XWmsT9sdbX8ms";
            var archiveListId = "0nhkQH0NluA1M8sfXJKP8n";
            var maximumTracks = 5;

            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);

            // Act
            await spotifyService.RemoveOrArchiveTracksAsync(playlistId, maximumTracks, archiveListId);

            var assertPlaylist = await spotifyClient.Playlists.Get(playlistId);

            // Assert
            assertPlaylist.Tracks.Items.Count.Should().Be(maximumTracks);
        }
        static Clients( )
        {
            Log.Information("Connecting to Spotify...");

            SpotifyClientConfig spotify_config = SpotifyClientConfig.CreateDefault( )
                                                 .WithAuthenticator(
                new ClientCredentialsAuthenticator(
                    Config.SotifyClientID,
                    Config.SotifyClientSecret));

            _spotify_client = new SpotifyClient(spotify_config);

            Log.Information("Connection to Spotify successful");

            Log.Information("Connecting to Yandex Music...");

            _yAusthStorage       = new AuthStorage(  );
            _yandex_music_client = new YandexMusicApi( );
            _yandex_music_client.User.Authorize(_yAusthStorage, Config.YMLogin, Config.YMPassword);

            Log.Information("Connection to Yandex Music successful");
        }
Example #20
0
        public static async Task SkipPrevius()
        {
            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();


            await spotify.Player.SkipPrevious();

            _server.Dispose();
        }
Example #21
0
        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>
        /// Create a client to do calls to the spotify api with.
        /// </summary>
        /// <returns>A SpotifyClient, or null of no accessToken could be found.</returns>
        public async Task <ISpotifyClient> Create(long userId)
        {
            var token = await _authorizationTokenRepository.Get(userId);

            if (token == null)
            {
                return(null);
            }

            // Map the token to a model the Spotify library can work with.
            var tokenResponse = _mapper.Map <AuthorizationCodeTokenResponse>(token);

            // TODO: inject singleton httpclient from startup.
            var config = SpotifyClientConfig
                         .CreateDefault()
                         .WithAuthenticator(new AuthorizationCodeAuthenticator(_spotifyOptions.ClientId, _spotifyOptions.Secret, tokenResponse))
                         .WithRetryHandler(new SimpleRetryHandler()
            {
                RetryAfter = TimeSpan.FromSeconds(1), TooManyRequestsConsumesARetry = true
            });

            return(new SpotifyClient(config));
        }
        /// <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);
            }
        }
Example #24
0
        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();


            var playlists = await spotify.PaginateAll(await spotify.Playlists.CurrentUsers().ConfigureAwait(false));


            _server.Dispose();
            //  Environment.Exit(0);
        }
Example #25
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureServices((hostContext, services) =>
        {
            Services.ConfigurationProvider configProvider = new Services.ConfigurationProvider(hostContext.Configuration);
            services.AddTransient <ISpotifyClient>(s =>
            {
                SpotifyClientConfig config = SpotifyClientConfig
                                             .CreateDefault()
                                             .WithAuthenticator(new ClientCredentialsAuthenticator(
                                                                    configProvider.SpotifyClientId,
                                                                    configProvider.SpotifyClientSectret));

                return(new SpotifyClient(config));
            });
            services.AddTransient(s =>
            {
                CosmosClientOptions options = new CosmosClientOptions()
                {
                    SerializerOptions = new CosmosSerializationOptions()
                    {
                        PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase
                    }
                };
                return(new CosmosClient(configProvider.CosmosConnectionString, options));
            });
            services.AddTransient <ISpotifyDataLayer, SpotifyDataLayer>();
            services.AddSingleton <IConfigurationProvider>(configProvider);
            services.AddTransient <IMusicInfoService, MusicInfoService>();
            services.AddTransient <ICosmosDataLayer, CosmosDataLayer>();
            services.AddTransient <ISubscriptionService, SubscriptionService>();
            services.AddTransient <INewMusicBotService, NewMusicBotService>();
            services.AddSingleton <IDiscordClientWrapper, DiscordClientWrapper>();
            services.AddHostedService <Worker>();
            services.AddHostedService <NewMusicChecker>();
        });
Example #26
0
        /// <summary>
        /// Start the authroization code flow or request for an access token if a refresh token is present and the scopes match.
        /// </summary>
        /// <param name="cancel">A <see cref="CancellationToken"/> to cancel the wait for users to authorize on their browsers</param>
        /// <exception cref="OperationCanceledException">Thrown if the wait is canceled</exception>
        public override async Task Authorize(CancellationToken cancel = default)
        {
            AuthorizationCodeTokenResponse tokenResponse;

            if (RefreshToken.IsNullOrEmpty() || !requiredScopes.IsSubsetOf(AuthorizedScopes))
            {
                var taskCompletionSource = new TaskCompletionSource <AuthorizationCodeResponse>();

                EmbedIOAuthServer _server = new EmbedIOAuthServer(new Uri("http://localhost:5000/callback"), 5000);
                await _server.Start();

                _server.AuthorizationCodeReceived += (_, response) =>
                {
                    taskCompletionSource.SetResult(response);
                    return(Task.CompletedTask);
                };

                var request = new SpotifyAPI.Web.LoginRequest(_server.BaseUri, ClientId, SpotifyAPI.Web.LoginRequest.ResponseType.Code)
                {
                    Scope = requiredScopes
                };
                Helper.OpenUri(request.ToUri());

                while (!taskCompletionSource.Task.IsCompleted)
                {
                    cancel.ThrowIfCancellationRequested();
                    await Task.Delay(500);
                }

                await _server.Stop();

                var response = taskCompletionSource.Task.Result;
                tokenResponse = await new OAuthClient().RequestToken(
                    new AuthorizationCodeTokenRequest(
                        ClientId, ClientSecret, response.Code, new Uri("http://localhost:5000/callback")
                        )
                    );
                RefreshToken = tokenResponse.RefreshToken;
            }
            else
            {
                var response = await new OAuthClient().RequestToken(new AuthorizationCodeRefreshRequest(ClientId, ClientSecret, RefreshToken));
                tokenResponse = new AuthorizationCodeTokenResponse()
                {
                    RefreshToken = RefreshToken,
                    AccessToken  = response.AccessToken,
                    CreatedAt    = response.CreatedAt,
                    ExpiresIn    = response.ExpiresIn,
                    Scope        = response.Scope,
                    TokenType    = response.TokenType
                };
            }
            AccessToken      = tokenResponse.AccessToken;
            AuthorizedScopes = tokenResponse.Scope.Split(' ').ToList();
            var config = SpotifyClientConfig
                         .CreateDefault()
                         .WithAuthenticator(new AuthorizationCodeAuthenticator(ClientId, ClientSecret, tokenResponse));

            spotify = new SpotifyClient(tokenResponse.AccessToken);
            RaiseConfigUpdated(EventArgs.Empty);
        }
Example #27
0
        // 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;
        }
Example #28
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            _secrets = new string[]
            {
                Configuration["DatabaseSettings:ConnectionString"],
                Configuration["DatabaseSettings:DatabaseName"],
                Configuration["Microsoft:Id"],
                Configuration["Microsoft:Secret"],
                Configuration["SpotifySettings:ClientID"],
                Configuration["SpotifySettings:ClientSecret"],
            };
            services.AddHttpContextAccessor();
            services.AddSingleton(SpotifyClientConfig.CreateDefault());
            services.AddScoped <SpotifyBuilder>();

            services.AddServerSideBlazor();

            services.AddMudServices();

            services.AddAuthorization(options =>
            {
                options.AddPolicy("Spotify", policy =>
                {
                    policy.AuthenticationSchemes.Add("Spotify");
                    policy.RequireAuthenticatedUser();
                });
            });

            services.AddAuthentication(opt => {
                opt.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(opt =>
            {
                opt.ExpireTimeSpan = TimeSpan.FromMinutes(50);
                //opt.Cookie.Name = "AuthCookie";
            })
            .AddSpotify(opt =>
            {
                opt.ClientId     = Configuration["SpotifySettings:ClientID"];
                opt.ClientSecret = Configuration["SpotifySettings:ClientSecret"];
                opt.CallbackPath = "/Auth/callback";
                opt.SaveTokens   = true;

                var scopes = new List <string> {
                    UserReadEmail, UserReadPrivate, PlaylistReadPrivate, PlaylistReadCollaborative, UserLibraryRead, UserFollowRead, UserTopRead
                };
                opt.Scope.Add(string.Join(",", scopes));
            })
            .AddMicrosoftAccount(opt =>
            {
                opt.SignInScheme = "Cookies";
                opt.ClientId     = Configuration["Microsoft:Id"];
                opt.ClientSecret = Configuration["Microsoft:Secret"];
            });
            services.AddRazorPages(options => {
                options.Conventions.AuthorizeFolder("/", "Spotify");
            });

            services.AddScoped <HttpClient>();
            services.AddScoped <DialogService>();
            services.AddControllers();
            services.AddSingleton <TrackDataAccess>();

            services.Configure <DatabaseSettings>(Configuration.GetSection(nameof(DatabaseSettings)));
            services.AddSingleton <IDatabaseSettings>(x => x.GetRequiredService <IOptions <DatabaseSettings> >().Value);

            services.Configure <SpotifySettings>(Configuration.GetSection(nameof(SpotifySettings)));
            services.AddSingleton <ISpotifySettings>(x => x.GetRequiredService <IOptions <SpotifySettings> >().Value);
        }
Example #29
0
        public async Task NowPlayingSpotify()
        {
            using var typing = Context.Channel.EnterTypingState();

            var userId = Context.User.Id;

            string?token = null;

            using (var connection = new SqliteConnection("Data Source=data.db"))
            {
                await connection.OpenAsync();

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM users WHERE id=$id";
                    command.Parameters.AddWithValue("$id", userId);

                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var isNull = await reader.IsDBNullAsync(2);

                            token = isNull == true ? null : reader.GetString(2);
                        }
                    }
                }
            }

            if (token != null)
            {
                try
                {
                    string?trackUri      = null;
                    string?trackDetails  = null;
                    var    spotifyConfig = SpotifyClientConfig
                                           .CreateDefault()
                                           .WithAuthenticator(
                        new ClientCredentialsAuthenticator(config["SpotifyId"], config["SpotifySecret"]));

                    var spotify = new SpotifyClient(token);

                    var currentlyPlaying =
                        await spotify.Player.GetCurrentlyPlaying(new PlayerCurrentlyPlayingRequest(PlayerCurrentlyPlayingRequest.AdditionalTypes.Track));

                    if (currentlyPlaying.Item is FullTrack fullTrack)
                    {
                        trackUri     = fullTrack.ExternalUrls["spotify"];
                        trackDetails = string.Empty;

                        foreach (var artist in fullTrack.Artists)
                        {
                            trackDetails += artist.Name + " ";
                        }

                        trackDetails += " - " + fullTrack.Name;
                    }

                    await ReplyAsync(trackUri ?? "No Spotify match found.");

                    if (string.IsNullOrEmpty(trackDetails) == false)
                    {
                        var youTubeResult = await SearchYouTube(trackDetails);
                        await ReplyAsync(youTubeResult ?? "No YouTube match found");
                    }
                }
                catch (APIUnauthorizedException)
                {
                    await ReplyAsync("Your Spotify API token has expired.");

                    return;
                }
            }
            else
            {
                await ReplyAsync("Spotify token invalid. Use !npsetspotify <token> in a private message to TuneBot to set your Spotify token.");
                await ReplyAsync("Do not send this token in a public chanel.");
            }
        }
Example #30
0
        private static async Task Start()
        {
            // find the lights
            //var findBulbs = Task.Run(() => YeelightHelper.FindDevices());
            //findBulbs.Wait();

            // connect to the lights
            //Task.Run(() => YeelightHelper.ConnectToBulbs());
            //YeelightHelper.ConnectToBulbs();

            await YeelightHelper.InitializeYeelights();

            // do all that cool Spotify authentication shit
            var json = await File.ReadAllTextAsync(CredentialsPath);

            var token = JsonConvert.DeserializeObject <AuthorizationCodeTokenResponse>(json);

            var authenticator = new AuthorizationCodeAuthenticator(clientId !, clientSecret !, token);

            authenticator.TokenRefreshed += (sender, token) => File.WriteAllText(CredentialsPath, JsonConvert.SerializeObject(token));

            var config = SpotifyClientConfig.CreateDefault()
                         .WithAuthenticator(authenticator);

            // build spotify client
            var spotify = new SpotifyClient(config);

            // get user account data
            var me = await spotify.UserProfile.Current();

            Console.WriteLine($"[Spotify] Authenticated as {me.DisplayName} ({me.Id}).");

            // flash the lights green & back to default to show we're alive
            // YeelightHelper.bulbs.SetRGBColor(0, 255, 0, 250);
            await Task.Delay(1000);

            //YeelightHelper.bulbs.SetColorTemperature(2700, 250);


            string oldTrackId = "";   // used to track if we're playing a different track than last loop
            int    loopDelay  = 2000; // don't set below 1000ms.

            while (true)
            {
                // for measuring api times
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                // get info on playback status
                var currentTrack = await spotify.Player.GetCurrentPlayback(new PlayerCurrentPlaybackRequest());

                // check if we're playing something, or if we pulled null data somehow (API failure?)
                if (currentTrack == null || currentTrack.Item == null || currentTrack.IsPlaying == false)
                {
                    await Task.Delay(loopDelay);

                    continue;
                }

                // grab the track details
                var currentTrackDetails = (FullTrack)currentTrack.Item;

                // check if it's different from what we saw last loop - if so, wait and try the loop again
                if (currentTrackDetails.Id == oldTrackId)
                {
                    await Task.Delay(loopDelay);

                    continue;
                }

                // download the album art to memory
                var         albumArtUrl    = currentTrackDetails.Album.Images[0].Url;
                WebRequest  request        = WebRequest.Create(albumArtUrl);
                WebResponse response       = request.GetResponse();
                Stream      responseStream = response.GetResponseStream();

                // convert album art to color - color should be average color of image after some adjustments
                Color albumColor = new Color();
                using (MagickImage image = new MagickImage(responseStream, MagickFormat.Jpg))
                {
                    // debug - output image before doing anything at all
                    var debugOutputPreProcessing = new FileInfo("debug-output-album-pre-processing.jpg");
                    image.Write(debugOutputPreProcessing);

                    // set white & black to transparent, to make sure they don't mess with the vibrancy of the image
                    image.ColorFuzz = (Percentage)15;  // shades within 15% of pure white/black will count as pure
                    image.Opaque(new MagickColor(MagickColors.White), new MagickColor(MagickColors.Transparent));
                    image.Opaque(new MagickColor(MagickColors.Black), new MagickColor(MagickColors.Transparent));

                    // flatten image down to a few colors
                    image.Quantize(new QuantizeSettings {
                        Colors = 5
                    });

                    // debug - output image after quantizing
                    var debugOutputQuantized = new FileInfo("debug-output-album-quantized.jpg");
                    image.Write(debugOutputQuantized);

                    // massively boost saturation so the lights actually have color to them
                    image.Modulate((Percentage)100, (Percentage)1000, (Percentage)100);

                    // resize to 1px, as the built-in converter will average out all the remaining colors into one
                    image.Resize(1, 1);

                    // get color rgb values and set to albumColor
                    var colorKey = image.Histogram().FirstOrDefault().Key;
                    albumColor = Color.FromArgb(255, colorKey.R, colorKey.G, colorKey.B);

                    // debug - output after all post processing. should return a 100x100px image of one solid color.
                    image.Resize(100, 100);
                    var debugOutputDone = new FileInfo("debug-output-done.jpg");
                    image.Write(debugOutputDone);

                    // get rid of any junk we don't need anymore
                    image.Dispose();
                    responseStream.Dispose();
                }

                // set the light color to the album art's average color
                YeelightHelper.bulbs.SetRGBColor(albumColor.R, albumColor.G, albumColor.B, 250);


                stopwatch.Stop();
                oldTrackId = currentTrackDetails.Id;

                Console.WriteLine($"[Spotify] {currentTrackDetails.Artists[0].Name} - {currentTrackDetails.Name}" +
                                  $" | {albumColor.R} {albumColor.G} {albumColor.B}" +
                                  $" | performed in {stopwatch.ElapsedMilliseconds}ms");

                await Task.Delay(loopDelay);
            }
        }