public async Task RefreshToken()
        {
            try
            {
                if (Account == null)
                {
                    return;
                }

                var ret = await BitbucketClient.GetRefreshToken(
                    Secrets.ClientId, Secrets.ClientSecret, Account.RefreshToken);

                if (ret == null)
                {
                    return;
                }

                Account.RefreshToken = ret.RefreshToken;
                Account.Token        = ret.AccessToken;
                _accountsService.Save(Account).ToBackground();

                Client = BitbucketClient.WithBearerAuthentication(Account.Token);
            }
            catch
            {
                // Do nothing....
            }
        }
        public async Task <object> GetRepository(string clientId, string clientPassword)
        {
            _logger.LogInformation("GetRepository");
            var client = new BitbucketClient(new BasicAuthenticationClient(clientId, clientPassword));

            return((await client.GetRepositories(RepositoryRole.Member)).Select(repo => repo.FullName));
        }
Beispiel #3
0
        private static void RegisterServerBbApi(this ContainerBuilder containerBuilder, AppConfig config)
        {
            BitbucketClient bbClient;

            switch (config.AuthType)
            {
            case AppConfig.AuthTypes.Basic:
                bbClient = new BitbucketClient(config.BaseUrl, config.Username, config.AppPassword);
                break;

            case AppConfig.AuthTypes.OAuth:
                bbClient = new BitbucketClient(config.BaseUrl, () => config.AppPassword);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            containerBuilder.RegisterInstance <CredentialsHandler>((url, fromUrl, types) =>
                                                                   new UsernamePasswordCredentials {
                Username = config.Username, Password = config.AppPassword
            });

            containerBuilder.RegisterInstance(bbClient);
        }
Beispiel #4
0
 public static async Task <Repository> BitbucketCreateRepositoryAsync(this Context context, BitbucketCreateRepositoryOptions options)
 {
     using (var client = new BitbucketClient(options))
     {
         return(await client.CreateRepositoryAsync(options.OwnerUsername, options.RepositorySlug, options.NewRepository));
     }
 }
        public async Task Login(string code)
        {
            var ret = await BitbucketClient.GetAuthorizationCode(
                Secrets.ClientId, Secrets.ClientSecret, code);

            var client = BitbucketClient.WithBearerAuthentication(ret.AccessToken);
            var user   = await client.Users.GetCurrent();

            var account = await _accountsService.Get(Domain, user.Username);

            if (account == null)
            {
                account = new Account
                {
                    Username     = user.Username,
                    AvatarUrl    = user.Links.Avatar.Href,
                    RefreshToken = ret.RefreshToken,
                    Token        = ret.AccessToken
                };

                await _accountsService.Save(account);
            }
            else
            {
                account.RefreshToken = ret.RefreshToken;
                account.Token        = ret.AccessToken;
                account.AvatarUrl    = user.Links.Avatar.Href;
                await _accountsService.Save(account);
            }

            ActivateUser(account, client);
        }
        protected async Task Startup()
        {
            var accounts = (await _accountsService.GetAccounts()).ToList();

            if (!accounts.Any())
            {
                GoToLoginCommand.ExecuteNow();
                return;
            }

            var account = await _applicationService.GetDefaultAccount();

            if (account == null)
            {
                GoToAccountsCommand.ExecuteNow();
                return;
            }

            if (string.IsNullOrEmpty(account.Token) || string.IsNullOrEmpty(account.RefreshToken))
            {
                GoToLoginCommand.ExecuteNow();
                return;
            }

            try
            {
                IsLoggingIn = true;
                Status      = "Logging in as " + account.Username;

                var ret = await BitbucketClient.GetRefreshToken(
                    Secrets.ClientId, Secrets.ClientSecret, account.RefreshToken);

                if (ret == null)
                {
                    await _alertDialogService.Alert("Error!", "Unable to refresh OAuth token. Please login again.");

                    GoToLoginCommand.ExecuteNow();
                    return;
                }

                account.RefreshToken = ret.RefreshToken;
                account.Token        = ret.AccessToken;
                await _accountsService.Save(account);
                await AttemptLogin(account);

                GoToMenuCommand.ExecuteNow();
            }
            catch (Exception e)
            {
                _alertDialogService
                .Alert("Error!", "Unable to login successfully: " + e.Message)
                .ToObservable()
                .BindCommand(GoToAccountsCommand);
            }
            finally
            {
                IsLoggingIn = false;
            }
        }
 public void ActivateUser(Account account, BitbucketClient client)
 {
     SetDefaultAccount(account);
     Account = account;
     Client  = client;
     _timer.Stop();
     _timer.Start();
 }
Beispiel #8
0
        public BitbucketClientShould()
        {
            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                                .Build();

            _client = new BitbucketClient(configuration["url"], configuration["username"], configuration["password"]);
        }
Beispiel #9
0
        public BitbucketTests(ITestOutputHelper testOutputHelper)
        {
            LogSettings.RegisterDefaultLogger <XUnitLogger>(LogLevels.Verbose, testOutputHelper);
            _bitbucketClient = BitbucketClient.Create(new Uri(BitbucketTestUri));

            if (!string.IsNullOrEmpty(_username) && !string.IsNullOrEmpty(_password))
            {
                _bitbucketClient.SetBasicAuthentication(_username, _password);
            }
        }
        public async Task <BitbucketClient> LoginAccount(Account account)
        {
            //Create the client
            var client = BitbucketClient.WithBearerAuthentication(account.Token);
            var user   = await client.Users.GetCurrent();

            account.Username  = user.Username;
            account.AvatarUrl = user.Links.Avatar.Href.Replace("/avatar/32", "/avatar/64");
            await _accountsService.Save(account);

            return(client);
        }
Beispiel #11
0
        public void ClientParsesAddress()
        {
            string expectedEndpoint = "https://api.perdu.com/2.0/repositories/comagnan/nure/default-reviewers";

            try {
                BitbucketClient bitbucketClient = new BitbucketClient(A_VALID_ADDRESS, A_USERNAME, A_PASSWORD, m_UrlClientMock.Object);
                bitbucketClient.GetDefaultReviewers();
            } catch (AggregateException e) when(e.InnerException is FlurlHttpException httpException)
            {
                string requestUri = httpException.Call.Request.RequestUri.ToString();

                Assert.Equal(expectedEndpoint, requestUri);
            }
        }
Beispiel #12
0
    public static async Task ForAllItems <T>(this BitbucketClient client, Func <BitbucketClient, Task <Collection <T> > > operation, Action <IEnumerable <T> > addAction)
    {
        var ret = await operation(client);

        addAction(ret.Values);
        var next = ret.Next;

        while (!string.IsNullOrEmpty(next))
        {
            var t = await client.Get <Collection <T> >(next);

            addAction(t.Values);
            next = t.Next;
        }
    }
Beispiel #13
0
    public static async Task <IEnumerable <T> > AllItems <T>(this BitbucketClient client, Func <BitbucketClient, Task <Collection <T> > > operation)
    {
        var ret = await operation(client);

        var items = new List <T>(ret.Values);
        var next  = ret.Next;

        while (!string.IsNullOrEmpty(next))
        {
            var t = await client.Get <Collection <T> >(next);

            items.AddRange(t.Values);
            next = t.Next;
        }

        return(items);
    }
Beispiel #14
0
        public async Task <List <PullRequest> > FetchActivePullRequests(
            string baseUrl,
            string projectName,
            string repositoryName,
            string personalAccessToken,
            string password,
            string userName
            )
        {
            var client = new BitbucketClient(
                baseUrl,
                userName,
                password ?? personalAccessToken);

            return((await client.GetPullRequestsAsync(projectName,
                                                      repositoryName)).ToList());
        }
Beispiel #15
0
 private void Auth()
 {
     if (_bitbucketClient is null)
     {
         if (!string.IsNullOrEmpty(_gitHelperData.lastGitProfile.token))
         {
             _bitbucketClient = new BitbucketClient("https://git.syneforge.com/", () => _gitHelperData.lastGitProfile.token);
             WriteLog(_bitbucketClient != null ? "Successfully authorized" : "Authorization failed");
         }
         else
         {
             WriteLog("Token is empty");
         }
     }
     else
     {
         WriteLog("Already authorized");
     }
 }
Beispiel #16
0
        public void Connect(string login = null, string pwd = null)
        {
            if (!string.IsNullOrEmpty(login))
            {
                _login = login;
            }
            if (!string.IsNullOrEmpty(pwd))
            {
                _password = pwd;
            }

            if (!string.IsNullOrEmpty(_login) && !string.IsNullOrEmpty(_password))
            {
                _client       = BitbucketClient.WithBasicAuthentication(_login, _password);
                _clientCommit = new ClientCommit(_client);
                _clientRepo   = new RepoClient(_client);
            }
            ConnectionChanged?.Invoke(null);
        }
Beispiel #17
0
        public async Task <bool> ApprovePullRequest(
            string baseUrl,
            string projectName,
            string repositoryName,
            string personalAccessToken,
            string password,
            string userName,
            long pullRequestId)
        {
            var client = new BitbucketClient(
                baseUrl,
                userName,
                password ?? personalAccessToken);
            var rez1 = await client.ApprovePullRequestAsync(projectName,
                                                            repositoryName,
                                                            pullRequestId);

            return(rez1.Approved);
        }
Beispiel #18
0
 public BbService(IConsole console, BitbucketClient bbServerClient, AppConfig appConfig)
 {
     _console        = console;
     _bbServerClient = bbServerClient;
     _appConfig      = appConfig;
 }
Beispiel #19
0
 public RepoClient(BitbucketClient client)
 {
     _client = client;
 }
 public ClientCommit(BitbucketClient client)
 {
     _client = client;
 }
Beispiel #21
0
        private static void executeBitbucket(string[] args)
        {
            var nArgs = CLIHelper.GetNamedArguments(args);

            switch (args[1]?.ToLower())
            {
            case "pull-approve":
            {
                var key         = nArgs["key"];
                var secret      = nArgs["secret"];
                var username    = nArgs["username"];
                var slug        = nArgs["slug"];
                var source      = nArgs.GetValueOrDefault("source", "develop");
                var destination = nArgs.GetValueOrDefault("destination", "master");
                var state       = nArgs.GetValueOrDefault("state", "OPEN");

                var bc          = new BitbucketClient(key, secret);
                var pullRequest = bc.GetPullRequest(username, slug, source, destination, state).Result;

                if (pullRequest == null)
                {
                    Console.WriteLine($"Warning, could not pull-approve because no pull request was found for source: {source}, destination: {destination}, state: {state} in {username}/{slug} repository.");
                }

                if (bc.PullRequestApprove(pullRequest).Result)
                {
                    Console.WriteLine($"Success, Pull request {source} => {destination} in {username}/{slug} repository was approved.");
                }

                Console.WriteLine($"Failure, Pull request {source} => {destination} in {username}/{slug} repository was NOT approved.");
            }
                ; break;

            case "pull-unapprove":
            {
                var key         = nArgs["key"];
                var secret      = nArgs["secret"];
                var username    = nArgs["username"];
                var slug        = nArgs["slug"];
                var source      = nArgs.GetValueOrDefault("source", "develop");
                var destination = nArgs.GetValueOrDefault("destination", "master");
                var state       = nArgs.GetValueOrDefault("state", "OPEN");

                var bc          = new BitbucketClient(key, secret);
                var pullRequest = bc.GetPullRequest(username, slug, source, destination, state).Result;

                if (pullRequest == null)
                {
                    Console.WriteLine($"Warning, could not pull-unapprove because no pull request was found for source: {source}, destination: {destination}, state: {state} in {username}/{slug} repository.");
                }

                if (bc.PullRequestUnApprove(pullRequest).Result)
                {
                    Console.WriteLine($"Success, Pull request {source} => {destination} in {username}/{slug} repository was unpproved.");
                    return;
                }

                Console.WriteLine($"Failure, Pull request {source} => {destination} in {username}/{slug} repository was NOT unapproved.");
            }
                ; break;

            case "pull-comment":
            {
                var key         = nArgs["key"];
                var secret      = nArgs["secret"];
                var username    = nArgs["username"];
                var slug        = nArgs["slug"];
                var source      = nArgs.GetValueOrDefault("source", "develop");
                var destination = nArgs.GetValueOrDefault("destination", "master");
                var state       = nArgs.GetValueOrDefault("state", "OPEN");
                var content     = nArgs["content"];

                var bc          = new BitbucketClient(key, secret);
                var pullRequest = bc.GetPullRequest(username, slug, source, destination, state).Result;

                if (pullRequest == null)
                {
                    Console.WriteLine($"Warning, could not comment because no pull request was found for source: {source}, destination: {destination}, state: {state} in {username}/{slug} repository.");
                }

                bc.PullRequestComment(pullRequest, content).Await();
                Console.WriteLine($"Success, Commented Pull request {source} => {destination} in {username}/{slug} repository with text: '{content}'.");
            }
                ; break;

            case "help":
            case "--help":
            case "-help":
            case "-h":
            case "h":
                HelpPrinter($"{args[0]}", "Bitbucket API Control",
                            ("pull-approve", "Accepts params: key, secret, username, slug, source (default: develop), destination (default: master), state (default: OPEN)"),
                            ("pull-unapprove", "Accepts params: key, secret, username, slug, source (default: develop), destination (default: master), state (default: OPEN)"),
                            ("pull-comment", "Accepts params: key, secret, username, slug, source (default: develop), destination (default: master), state (default: OPEN), content"));
                break;

            default:
            {
                Console.WriteLine($"Try '{args[0]} help' to find out list of available commands.");
                throw new Exception($"Unknown AES command: '{args[0]} {args[1]}'");
            }
            }
        }