Esempio n. 1
0
        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 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);
    }
Esempio n. 3
0
        private async Task SaveTokenAsync(string mbUserId, AuthorizationCodeTokenResponse response)
        {
            var secret = new KeyVaultSecret(
                name: GetUserTokenKey(mbUserId),
                value: JsonConvert.SerializeObject(response));

            secret.Properties.ContentType = "application/json";
            secret.Properties.NotBefore   = response.CreatedAt.ToUniversalTime();
            secret.Properties.ExpiresOn   = response.CreatedAt.AddSeconds(response.ExpiresIn).ToUniversalTime();
            await secretClient.SetSecretAsync(secret);
        }
Esempio n. 4
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));

            await Start();
        }
Esempio n. 5
0
        public async Task SaveAccessTokenAsync(string userId, string accessToken)
        {
            User user = await _userRepo.GetByIdAsync(userId)
                        ?? throw new KeyNotFoundException($"Could not find user with id '{userId}'!");

            AuthorizationCodeTokenResponse response = await new OAuthClient().RequestToken(
                new AuthorizationCodeTokenRequest(_externalAuthSettings.ClientId, _externalAuthSettings.ClientSecret, accessToken, new Uri(_externalAuthSettings.CallbackUrl)));

            user.RefreshToken = response.RefreshToken;

            await _userRepo.SaveAsync(user);
        }
Esempio n. 6
0
        private async Task OnAuthorizationCodeReceived(object sender, AuthorizationCodeResponse response)
        {
            await this.server.Stop();

            this.server.AuthorizationCodeReceived -= this.OnAuthorizationCodeReceived;

            AuthorizationCodeTokenResponse tokenResponse = await new OAuthClient().RequestToken(
                new AuthorizationCodeTokenRequest(this.clientId, this.clientSecret, response.Code, this.server.BaseUri)
                );

            File.WriteAllText(Constants.CredentialsFileName, JsonConvert.SerializeObject(tokenResponse));

            this.IsAuthorizationFinished = true;
        }
Esempio n. 7
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)
                );

            var config  = SpotifyClientConfig.CreateDefault().WithToken(token.AccessToken, token.TokenType);
            var spotify = new SpotifyClient(config);

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

            Console.WriteLine($"Your E-Mail: {me.Email}");
            Environment.Exit(0);
        }
Esempio n. 8
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);
        }
        public static async Task GetNewAuthTokens(string username, string code)
        {
            AuthorizationCodeTokenResponse response = await new OAuthClient().RequestToken(new AuthorizationCodeTokenRequest(Resources.SpotifyClientID, Resources.SpotifyClientSecret, code, new Uri("https://www.example.com/callback")));

            DataBase.AddNewToken(username, response.AccessToken, response.RefreshToken);
        }
        public async Task ConnectWebClient(bool keepRefreshToken = true)
        {
            _securityStore = SecurityStore.Load(pluginDirectory);

            EmbedIOAuthServer _server = new EmbedIOAuthServer(new Uri("http://localhost:4002/callback"), 4002);

            if (_securityStore.HasRefreshToken && keepRefreshToken)
            {
                var refreshRequest = new AuthorizationCodeRefreshRequest(_securityStore.ClientId,
                                                                         _securityStore.ClientSecret,
                                                                         _securityStore.RefreshToken);
                var refreshResponse = await new OAuthClient().RequestToken(refreshRequest);
                lock (_lock)
                {
                    _spotifyClient = new SpotifyClient(refreshResponse.AccessToken);
                }
            }
            else
            {
                await _server.Start();

                _server.AuthorizationCodeReceived += async(object sender, AuthorizationCodeResponse response) =>
                {
                    await _server.Stop();

                    AuthorizationCodeTokenResponse token = await new OAuthClient().RequestToken(
                        new AuthorizationCodeTokenRequest(_securityStore.ClientId,
                                                          _securityStore.ClientSecret,
                                                          response.Code,
                                                          _server.BaseUri));
                    lock (_lock)
                    {
                        _securityStore.RefreshToken = token.RefreshToken;
                        _securityStore.Save(pluginDirectory);
                        _spotifyClient = new SpotifyClient(token.AccessToken);
                    }
                };

                _server.ErrorReceived += async(object sender, string error, string state) =>
                {
                    Console.WriteLine($"Aborting authorization, error received: {error}");
                    await _server.Stop();
                };

                var request = new LoginRequest(_server.BaseUri, _securityStore.ClientId, LoginRequest.ResponseType.Code)
                {
                    Scope = new List <string> {
                        UserLibraryRead,
                        UserReadEmail,
                        UserReadPrivate,
                        UserReadPlaybackPosition,
                        UserReadCurrentlyPlaying,
                        UserReadPlaybackState,
                        UserModifyPlaybackState,
                        AppRemoteControl,
                        PlaylistReadPrivate
                    }
                };

                Uri uri = request.ToUri();
                try {
                    BrowserUtil.Open(uri);
                } catch (Exception) {
                    Console.WriteLine("Unable to open URL, manually open: {0}", uri);
                };
            };
        }
Esempio n. 11
0
    public static async Task GetNewAuthTokens(string username, string code)
    {
        AuthorizationCodeTokenResponse response = await new OAuthClient().RequestToken(new AuthorizationCodeTokenRequest(AppSettings.Spotify.ClientId, AppSettings.Spotify.ClientSecret, code, new("https://example.com/callback")));

        DbController.AddNewToken(username, response.AccessToken, response.RefreshToken);
    }