Esempio n. 1
0
        public async Task <PostCommentResult> PostCommentAsync(IFormCollection form)
        {
            if (form is null)
            {
                throw new ArgumentNullException(nameof(form));
            }

            // Make sure the site posting the comment is the correct site.
            var allowedSite = _config.Website;
            var postedSite  = form[FormFields.CommentSite];

            if (!string.IsNullOrWhiteSpace(allowedSite) && !AreSameSites(allowedSite, postedSite))
            {
                return(new PostCommentResult(
                           HttpStatusCode.BadRequest,
                           string.Format(
                               CultureInfo.InvariantCulture,
                               CommentResources.AreNotSameSitesErrorMessage,
                               postedSite.ToString() ?? "null")));
            }

            var commentResult = await _commentFactory.CreateFromFormAsync(form).ConfigureAwait(false);

            if (commentResult.HasErrors)
            {
                return(new PostCommentResult(
                           HttpStatusCode.BadRequest,
                           $"Creating comment from form failed: {string.Join("\n", commentResult.Errors)}",
                           commentResult.Exception));
            }

            var pullRequestResult = await _pullRequestService.TryCreatePullRequestAsync(commentResult.Comment)
                                    .ConfigureAwait(false);

            if (pullRequestResult.HasError)
            {
                return(new PostCommentResult(
                           HttpStatusCode.BadRequest,
                           $"Creating pull request failed: {pullRequestResult.Error}",
                           pullRequestResult.Exception));
            }

            if (!Uri.TryCreate(form[FormFields.Redirect], UriKind.Absolute, out var redirectUri))
            {
                return(new PostCommentResult(HttpStatusCode.OK));
            }
            else
            {
                return(new PostCommentResult(HttpStatusCode.Redirect, redirectUri));
            }
        }