Example #1
0
        public Task <string?> WaitForLogin(Uri address, int port, TimeSpan timeout, string state)
        {
            var tcs = new TaskCompletionSource <string?>();

            var server = new EmbedIOAuthServer(address, port);

            server.AuthorizationCodeReceived += async(sender, response) =>
            {
                await server.Stop();

                if (response.State != state)
                {
                    tcs.SetResult("Given state parameter was not correct.");
                    return;
                }

                var tokenResponse = await _spotifyService.OAuth.RequestToken(
                    new AuthorizationCodeTokenRequest(
                        _appConfig.SpotifyApp.ClientId !,
                        _appConfig.SpotifyApp.ClientSecret !,
                        response.Code,
                        server.BaseUri
                        )
                    );

                _appConfig.SpotifyToken.AccessToken  = tokenResponse.AccessToken;
                _appConfig.SpotifyToken.RefreshToken = tokenResponse.RefreshToken;
                _appConfig.SpotifyToken.CreatedAt    = tokenResponse.CreatedAt;
                _appConfig.SpotifyToken.ExpiresIn    = tokenResponse.ExpiresIn;
                _appConfig.SpotifyToken.TokenType    = tokenResponse.TokenType;

                // Create a temporary spotify with access token to fetch user
                var spotify = new SpotifyClient(_spotifyService.Config.WithToken(tokenResponse.AccessToken));
                var me      = await spotify.UserProfile.Current();

                _appConfig.Account.Id          = me.Id;
                _appConfig.Account.DisplayName = me.DisplayName;
                _appConfig.Account.Uri         = me.Uri;

                await _appConfig.Save();

                server.Dispose();
                tcs.SetResult(null);
            };

            var ct = new CancellationTokenSource(timeout);

            ct.Token.Register(() =>
            {
                server.Stop();
                server.Dispose();
                tcs.TrySetCanceled();
            }, useSynchronizationContext: false);

            server.Start();

            return(tcs.Task);
        }
Example #2
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();

            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);
        }
Example #3
0
        private async UniTaskVoid StartServer()
        {
            try
            {
                Uri baseUri = SpotifyConfiguration.ServerConfiguration.Uri;
                int port    = SpotifyConfiguration.ServerConfiguration.Port;

                EmbedIOAuthServer server = new EmbedIOAuthServer(baseUri, port);
                await server.Start();

                server.AuthorizationCodeReceived += (sender, response) =>
                {
                    server.Stop();
                    server.Dispose();
                    responseCode = response.Code;
                    return(null);
                };

                OnServerInitialized.Raise();

                await UniTask.WaitUntil(() => !string.IsNullOrEmpty(responseCode));

                Client.FromAuthorizationCode(responseCode).Forget();
                Destroy(gameObject);
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
        }
Example #4
0
        /// <summary>
        /// Encapsulate the login flow with <see cref="EmbedIOAuthServer"/>, useful for console application.
        /// </summary>
        public async Task Login()
        {
            var server = new EmbedIOAuthServer(new Uri(_config.CallbackUrl), _config.CallbackPort);
            await server.Start();

            var auth = new TaskCompletionSource();

            server.AuthorizationCodeReceived += async(_, response) =>
            {
                await CompleteLogin(response.Code);

                auth.SetResult();
            };

            var result = await TryLogin();

            await result.IfSomeAsync(async url =>
            {
                BrowserUtil.Open(new Uri(url));
                await auth.Task;
            });

            await server.Stop();

            server.Dispose();
        }
Example #5
0
    public void DeauthorizeUser()
    {
        // Dispose server
        if (_server != null)
        {
            _server.Dispose();
        }

        _pkceToken = null;
    }
Example #6
0
    public void DeauthorizeUser()
    {
        if (_server != null)
        {
            _server.Dispose();
        }

        if (_lastAuthToken != null)
        {
            _lastAuthToken = null;
        }
    }
Example #7
0
        private void Start()
        {
            var json  = File.ReadAllText(CredentialsPath);
            var token = JsonConvert.DeserializeObject <PKCETokenResponse>(json);

            var authenticator = new PKCEAuthenticator(clientId, token);

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

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

            spotify = new SpotifyClient(config);

            _server.Dispose();
        }
Example #8
0
        private static async Task OnAuthorizationCodeReceived(object sender, AuthorizationCodeResponse response)
        {
            await _server.Stop();

            AuthorizationCodeTokenResponse token = await new OAuthClient().RequestToken(
                new AuthorizationCodeTokenRequest(clientId !, clientSecret !, response.Code, _server.BaseUri)
                );

            await File.WriteAllTextAsync(CredentialsPath, JsonConvert.SerializeObject(token));

            // get rid of the web server
            _server.Dispose();

            await Start();
        }
Example #9
0
        private async Task StartStreamMode()
        {
            try
            {
                Log.Instance.PrintMessage("Trying to connect Spotify account", MessageType.Info, "Spotify.StartStreamMode()");
                Kernel.InternetAvaliable(false);
                Stopwatch crono = Stopwatch.StartNew();
                if (!File.Exists(AuthPath))
                {
                    var(verifier, challenge) = PKCEUtil.GenerateCodes();
                    var server = new EmbedIOAuthServer(new Uri("http://localhost:4002/callback"), 4002);
                    await server.Start();

                    server.AuthorizationCodeReceived += async(sender, response) =>
                    {
                        await server.Stop();

                        PKCETokenResponse token = await new OAuthClient().RequestToken(new PKCETokenRequest(PublicKey, response.Code, server.BaseUri, verifier));
                        await File.WriteAllTextAsync(AuthPath, JsonConvert.SerializeObject(token));
                        await StartLoginSpotify(crono);

                        server.Dispose();
                    };
                    var login = new LoginRequest(server.BaseUri, PublicKey, LoginRequest.ResponseType.Code)
                    {
                        CodeChallenge       = challenge,
                        CodeChallengeMethod = "S256",
                        Scope = new List <string> {
                            Scopes.UserReadEmail, Scopes.UserReadPrivate, Scopes.Streaming, Scopes.PlaylistReadPrivate, Scopes.UserReadPlaybackState, Scopes.UserLibraryRead
                        }
                    };
                    BrowserUtil.Open(login.ToUri());
                }
                else
                {
                    await StartLoginSpotify(crono);
                }
            }
            catch (APIException e)
            {
                Kernel.InternetAvaliable(false);
                Log.Instance.PrintMessage(e.Message, MessageType.Error);
                System.Windows.Forms.MessageBox.Show(Kernel.LocalTexts.GetString("error_internet"));
            }
        }
Example #10
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."));
        }
Example #11
0
        private static async Task Start(string _accessToken)
        {
            var spotify = new SpotifyClient(_accessToken);

            SearchRequest  sReq;
            SearchResponse sRes;

            LibrarySaveAlbumsRequest librarySaveAlbumsRequest;
            FollowRequest            followRequest;

            List <string>    IDList      = new List <string>();
            HashSet <string> ArtistIDSet = new HashSet <string>();

            List <string> notAddedMusicList = new List <string>();
            List <string> addedMusicList    = new List <string>();

            SimpleAlbum album;

            for (int i = 1; i <= _artistAlbumPairs.Count; ++i)
            {
                sReq = new SearchRequest(SearchRequest.Types.Album, _artistAlbumPairs[i - 1].Key + " " + _artistAlbumPairs[i - 1].Value);
                sRes = spotify.Search.Item(sReq).Result; // maybe need await?

                if (sRes.Albums.Items.Count != 0)
                {
                    var FoundAlbums = sRes.Albums;

                    album = FoundAlbums.Items[0];

                    ArtistIDSet.Add(album.Artists[0].Id);

                    IDList.Add(album.Id);

                    Console.WriteLine("Added to library: " + album.Artists[0].Name + " - " + album.Name);

                    addedMusicList.Add(album.Artists[0].Name + " - " + album.Name);
                }
                else
                {
                    _notAddedArtistAlbumPairs.Add(_artistAlbumPairs[i - 1]);
                }

                if (i % 50 == 0)
                {
                    librarySaveAlbumsRequest = new LibrarySaveAlbumsRequest(IDList);
                    followRequest            = new FollowRequest(FollowRequest.Type.Artist, new List <string>(ArtistIDSet));

                    await spotify.Library.SaveAlbums(librarySaveAlbumsRequest);

                    await spotify.Follow.Follow(followRequest);

                    IDList      = new List <string>();
                    ArtistIDSet = new HashSet <string>();

                    System.Threading.Thread.Sleep(500);
                }

                if (i == _artistAlbumPairs.Count)
                {
                    if (IDList.Count != 0)
                    {
                        librarySaveAlbumsRequest = new LibrarySaveAlbumsRequest(IDList);
                        followRequest            = new FollowRequest(FollowRequest.Type.Artist, new List <string>(ArtistIDSet));

                        await spotify.Library.SaveAlbums(librarySaveAlbumsRequest);

                        await spotify.Follow.Follow(followRequest);

                        break;
                    }

                    break;
                }
            }

            if (_notAddedArtistAlbumPairs != null && _notAddedArtistAlbumPairs.Count != 0)
            {
                foreach (var pair in _notAddedArtistAlbumPairs)
                {
                    Console.WriteLine("Not added to library: " + pair.Key + " - " + pair.Value);
                }

                foreach (var pair in _notAddedArtistAlbumPairs)
                {
                    notAddedMusicList.Add(pair.Key + " - " + pair.Value);
                }
            }

            WriteListToFile(notAddedMusicList, "not_added.txt");
            WriteListToFile(addedMusicList, "added.txt");

            _server.Dispose();
            Environment.Exit(0);
        }