コード例 #1
0
        public async Task ReturnsExistsForResponseWithCorrectHeadersRegardlessOfResponse(HttpStatusCode httpStatusCode)
        {
            var headers = new Dictionary <string, string>()
            {
                { "Server", "REVERSE-PROXY" },
                { "X-GitHub-Request-Id", Guid.NewGuid().ToString() }
            };
            var response = CreateResponse(httpStatusCode, headers);

            var productHeader = new ProductHeaderValue("GHfW", "99");
            var httpClient    = Substitute.For <IHttpClient>();

            httpClient.Send(Args.Request, CancellationToken.None).Returns(Task.FromResult(response));
            var enterpriseProbe = new EnterpriseProbe(productHeader, httpClient);

            var result = await enterpriseProbe.Probe(new Uri("https://example.com/"));

            Assert.Equal(EnterpriseProbeResult.Ok, result);
            httpClient.Received(1).Send(Arg.Is <Request>(r =>
                                                         r.BaseAddress == new Uri("https://example.com") &&
                                                         r.Endpoint == new Uri("/site/sha", UriKind.Relative) &&
                                                         r.Method == HttpMethod.Get &&
                                                         r.Timeout == TimeSpan.FromSeconds(3) &&
                                                         r.Headers["User-Agent"] == "GHfW/99"
                                                         ), CancellationToken.None);
        }
コード例 #2
0
        public async Task ThrowsArgumentExceptionForGitHubDotComDomain()
        {
            var httpClient = Substitute.For <IHttpClient>();

            httpClient.Send(Args.Request, CancellationToken.None).ThrowsAsync(new InvalidOperationException());
            var productHeader   = new ProductHeaderValue("GHfW", "99");
            var enterpriseProbe = new EnterpriseProbe(productHeader, httpClient);

            var result = await Assert.ThrowsAsync <ArgumentException>(async() => await enterpriseProbe.Probe(new Uri("https://github.com/")));

            Assert.Equal("enterpriseBaseUrl", result.ParamName);
        }
コード例 #3
0
        public async Task ReturnsDefinitelyNotEnterpriseExistsForUnknownException()
        {
            var httpClient = Substitute.For <IHttpClient>();

            httpClient.Send(Args.Request, CancellationToken.None).ThrowsAsync(new InvalidOperationException());
            var productHeader   = new ProductHeaderValue("GHfW", "99");
            var enterpriseProbe = new EnterpriseProbe(productHeader, httpClient);

            var result = await enterpriseProbe.Probe(new Uri("https://example.com/"));

            Assert.Equal(EnterpriseProbeResult.Failed, result);
        }
コード例 #4
0
        public async Task ReturnsExistsForApiExceptionWithCorrectHeaders()
        {
            var httpClient = Substitute.For <IHttpClient>();
            var response   = Substitute.For <IResponse>();

            response.Headers["Server"].Returns("GitHub.com");
            response.Headers.ContainsKey("X-GitHub-Request-Id").Returns(true);
            var apiException = new ApiException(response);

            httpClient.Send(Args.Request, CancellationToken.None).ThrowsAsync(apiException);
            var productHeader   = new ProductHeaderValue("GHfW", "99");
            var enterpriseProbe = new EnterpriseProbe(productHeader, httpClient);

            var result = await enterpriseProbe.Probe(new Uri("https://example.com/"));

            Assert.Equal(EnterpriseProbeResult.Ok, result);
        }
コード例 #5
0
        public async Task ReturnsExistsForApiExceptionWithCorrectHeaders()
        {
            var headers = new Dictionary <string, string>()
            {
                { "Server", "GitHub.com" },
                { "X-GitHub-Request-Id", Guid.NewGuid().ToString() }
            };

            var apiException = new ApiException(CreateResponse(HttpStatusCode.OK, headers));

            var httpClient = Substitute.For <IHttpClient>();

            httpClient.Send(Args.Request, CancellationToken.None).ThrowsAsync(apiException);

            var productHeader   = new ProductHeaderValue("GHfW", "99");
            var enterpriseProbe = new EnterpriseProbe(productHeader, httpClient);

            var result = await enterpriseProbe.Probe(new Uri("https://example.com/"));

            Assert.Equal(EnterpriseProbeResult.Ok, result);
        }
コード例 #6
0
        /// <summary>
        /// GitHubへのアクセス情報を登録する。
        /// </summary>
        private async void Register()
        {
            isRegistering = true;
            bool hasError = false;

            RegisterCommand.RaiseCanExecuteChanged();
            ((App)App.Current).notificationService.Stop();

            ProductHeaderValue phv = new ProductHeaderValue("GitHubNotifier");
            Uri         uri        = new Uri(StrRootUrl);
            Credentials tokenAuth  = new Credentials(StrToken);

            // URLが有効かチェック
            if (!uri.Host.Equals("github.com", StringComparison.OrdinalIgnoreCase) &&
                !uri.Host.Equals("api.github.com", StringComparison.OrdinalIgnoreCase))
            {
                Properties.Settings.Default.IsEnterprise = true;
                EnterpriseProbe       probe  = new EnterpriseProbe(phv);
                EnterpriseProbeResult result = await probe.Probe(uri);

                switch (result)
                {
                case EnterpriseProbeResult.Failed:
                    StrError = Properties.Resources.NetworkErrorText;
                    hasError = true;
                    break;

                case EnterpriseProbeResult.NotFound:
                    StrError = Properties.Resources.ServerErrorText;
                    hasError = true;
                    break;
                }
            }
            else
            {
                Properties.Settings.Default.IsEnterprise = false;
            }

            if (!hasError)
            {
                // 通知を取得する
                GitHubClient client = new GitHubClient(phv, uri)
                {
                    Credentials = tokenAuth
                };
                try
                {
                    IReadOnlyList <Notification> notifications = await client.Activity.Notifications.GetAllForCurrent();
                }
                catch (AuthorizationException)
                {
                    StrError = Properties.Resources.TokenErrorText;
                    hasError = true;
                }
                catch (ForbiddenException)
                {
                    StrError = Properties.Resources.PermissionErrorText;
                    hasError = true;
                }
            }

            if (hasError)
            {
                Properties.Settings.Default.IsValidated = false;
            }
            else
            {
                // 入力値を保存する
                Properties.Settings.Default.RootURL     = StrRootUrl;
                Properties.Settings.Default.Token       = StrToken;
                Properties.Settings.Default.IsValidated = true;
                Properties.Settings.Default.Save();
                // NotificationServiceを開始する
                ((App)App.Current).notificationService.Run();
                // ウィンドウを閉じる
                App.Current.MainWindow.Close();
            }

            isRegistering = false;
            RegisterCommand.RaiseCanExecuteChanged();
        }
コード例 #7
0
        private async Task <bool> CreateIssue(Event <LogEventData> evt)
        {
            if (evt == null)
            {
                return(false);
            }

            if ((LogEventLevelList?.Count ?? 0) > 0 && !LogEventLevelList.Contains(evt.Data.Level))
            {
                return(false);
            }

            if (!(GitHubRepoName ?? "").HasValue() ||
                !(GitHubRepoOwnerName ?? "").HasValue() ||
                !(GitHubUsername ?? "").HasValue()
                )
            {
                return(false);
            }

            Uri entUri = null;

            if ((GitHubEntUrl ?? "").HasValue() && !Uri.TryCreate(GitHubEntUrl, UriKind.RelativeOrAbsolute, out entUri))
            {
                return(false);
            }


            var phv = new ProductHeaderValue("SeqApp.GitHub");

            if (entUri != null)
            {
                _step = $"Will probe GitHub enterprise {entUri}";
                var probe  = new EnterpriseProbe(phv);
                var result = await probe.Probe(entUri);

                _step = $"DONE probe GitHub enterprise {entUri}";
                if (result != EnterpriseProbeResult.Ok)
                {
                    Log.Error("Probe enterprise GitHub failed with result {result}", result);
                    return(false);
                }
            }


            object repoNamePropValue = null;

            evt?.Data?.Properties?.TryGetValue(GitHubRepoName, out repoNamePropValue);
            var repoName = repoNamePropValue?.ToString() ?? GitHubRepoName;

            if (!(repoName ?? "").HasValue())
            {
                return(false);
            }

            object repoOwnerNamePropValue = null;

            evt?.Data?.Properties?.TryGetValue(GitHubRepoOwnerName, out repoOwnerNamePropValue);
            var repoOwnerName = repoOwnerNamePropValue?.ToString() ?? GitHubRepoOwnerName;

            if (!(repoOwnerName ?? "").HasValue())
            {
                return(false);
            }

            var creds = (GitHubPassword ?? "").HasValue()
                ? new Credentials(GitHubUsername, GitHubPassword)
                : new Credentials(GitHubUsername);

            var client = entUri == null ? new GitHubClient(phv) : new GitHubClient(phv, entUri);

            client.Credentials = creds;

            var renderedMessage   = (evt?.Data?.RenderedMessage ?? "");
            var summary           = renderedMessage.CleanCRLF().TruncateWithEllipsis(255);
            var seqUrl            = SeqUrl.NormalizeHostOrFQDN();
            var eventUrl          = $"{seqUrl}#/events?filter=@Id%20%3D%20'{evt.Id}'";
            var propValuesInTitle = BuildPropertyValuesString(evt, TitlePropertiesList);

            StringBuilder sb = new StringBuilder();

            // Attach the rendered message
            if (renderedMessage.HasValue())
            {
                sb.AppendLine($"**Message** [View Event]({eventUrl})");
                sb.AppendLine("```");
                sb.AppendLine(renderedMessage);
                sb.AppendLine("```");
                sb.AppendLine("");
            }

            // If event has exception attach that Exception
            if (AttachException && (evt?.Data?.Exception ?? "").HasValue())
            {
                sb.AppendLine("**Exception**");
                sb.AppendLine("```");
                sb.AppendLine(evt?.Data?.Exception);
                sb.AppendLine("```");
                sb.AppendLine("");
            }


            // Attach structured properties
            if (AttachProperties && (evt?.Data?.Properties?.Count ?? 0) > 0)
            {
                sb.AppendLine("**Properties**");

                var allProps         = evt.Data.Properties;
                var additionPropList = AdditionalPropertiesList;
                sb.AppendLine("```");
                foreach (var kvp in allProps)
                {
                    if (additionPropList?.Count > 0 && !additionPropList.Contains(kvp.Key))
                    {
                        continue;
                    }

                    sb.AppendLine($"* {kvp.Key} : {(kvp.Value != null ? JsonConvert.SerializeObject(kvp.Value) : "")}");;
                }
                sb.AppendLine("```");
                sb.AppendLine("");
            }


            // Create the issue
            var title = $"{(propValuesInTitle.HasValue() ? propValuesInTitle + " : " : "")}{summary}";

            var newIssue = new NewIssue(title)
            {
                Body = sb.ToString(),
            };
            var labels = GetPropertyValuesAsList(evt, LabelPropertiesList, ",", (AddLogLevelAsLabel ? new string[1] {
                evt.Data.Level.ToString()
            } : null));

            if (labels?.Count > 0)
            {
                labels.ForEach(lb => newIssue.Labels.Add(lb));
            }

            _step = $"Will create issue for {GitHubRepoOwnerName}/{GitHubRepoName}";

            var createdIssue = await client.Issue.Create(GitHubRepoOwnerName, GitHubRepoName, newIssue).ConfigureAwait(false);

            _step = $"DONE create issue for {GitHubRepoOwnerName}/{GitHubRepoName}";
            return(true);
        }