Ejemplo n.º 1
0
        public IActionResult CreateComment(Guid postAuthorId, Guid postId,
                                           CommentInputDto newComment, [FromHeader(Name = "Content-Type")] string mediaType)
        {
            var idsSet = new CommentIdsSet(postAuthorId, postId);

            newComment.AuthorId = GetUserId();
            return(AddComment(idsSet, newComment, IncludeLinks(mediaType)));
        }
Ejemplo n.º 2
0
        public ResultModel CreateComment(CommentInputDto model)
        {
            var          httpContext = _httpContextAccessor.HttpContext;
            string       userid      = httpContext?.User.Claims.Where(s => s.Type == "userid").FirstOrDefault()?.Value;
            CommentDatas comment     = new CommentDatas(model.RelationObjectID, (int)CY_Classify.创意回复, new Guid(userid), model.ReplyContent, model.ReplyToUserObjectID, model.ParentID);

            return(new ResultModel(0, comment));
        }
Ejemplo n.º 3
0
        public BaseResponse <CommentOutputDto> Create(CommentInputDto commentInputDto, Guid id)
        {
            var comment = Create(Mapper.Map <Comment>(commentInputDto), out var isSaved);

            if (!isSaved)
            {
                throw new InternalServerErrorException("Could not create Comment");
            }

            return(new SuccessResponse <CommentOutputDto>(Mapper.Map <CommentOutputDto>(comment)));
        }
Ejemplo n.º 4
0
        public BaseResponse <bool> Update(Guid id, CommentInputDto commentInputDto)
        {
            var comment = First(x => x.Id == id);

            comment.Content = commentInputDto.Content;

            var isSaved = Update(comment);

            if (!isSaved)
            {
                throw new InternalServerErrorException("Could not update Comment");
            }

            return(new SuccessResponse <bool>(true));
        }
Ejemplo n.º 5
0
        private IActionResult AddComment(CommentIdsSet idsSet,
                                         CommentInputDto newComment, bool includeLinks = false)
        {
            if (validator.DontMatchRules(newComment as ICommentInputDto, ModelState))
            {
                return(ValidationProblem(ModelState));
            }

            if (AuthorOrPostNotExist(idsSet.postAuthorId, idsSet.postId))
            {
                return(NotFound());
            }

            var commentToAdd = mapper.Map <Comment>(newComment);

            InsertAuthorsInto(commentToAdd);

            if (idsSet.commentId != Guid.Empty)
            {
                commentToAdd.Id = idsSet.commentId;
            }

            blogRepository.AddCommentForPost(idsSet.postId, commentToAdd);
            blogRepository.SaveChanges();

            var mappedComment = mapper.Map <CommentOutputDto>(commentToAdd);

            idsSet.commentId = mappedComment.Id;

            dynamic toReturn = mappedComment;

            if (includeLinks)
            {
                toReturn = ShapeAndLinkSingleComment(mappedComment, idsSet);
            }

            return(CreatedAtRoute("GetComment",
                                  new { idsSet.postAuthorId, idsSet.postId, commentId = mappedComment.Id }, toReturn));
        }
Ejemplo n.º 6
0
        public IActionResult UpdateComment(Guid postAuthorId, Guid postId, Guid commentId,
                                           CommentInputDto updatedComment, [FromHeader(Name = "Content-Type")] string mediaType)
        {
            var idsSet          = new CommentIdsSet(postAuthorId, postId, commentId);
            var commentFromRepo = blogRepository.GetCommentForPost(postId, commentId);

            if (commentFromRepo is null)
            {
                return(AddComment(idsSet, updatedComment, IncludeLinks(mediaType)));
            }

            mapper.Map(updatedComment, commentFromRepo);
            blogRepository.SaveChanges();

            if (IncludeLinks(mediaType))
            {
                var mappedComment = mapper.Map <CommentOutputDto>(commentFromRepo);
                return(Ok(ShapeAndLinkSingleComment(mappedComment, idsSet)));
            }

            return(NoContent());
        }
Ejemplo n.º 7
0
        public ActionResult Put(CommentInputDto comment)
        {
            UserInfoOutputDto user = Session.GetByRedis <UserInfoOutputDto>(SessionKey.UserInfo);

            comment.Content = comment.Content.Trim().Replace("<p><br></p>", string.Empty);

            if (Regex.Match(comment.Content, ModRegex).Length <= 0)
            {
                comment.Status = Status.Pended;
            }
            if (user != null)
            {
                comment.NickName   = user.NickName;
                comment.QQorWechat = user.QQorWechat;
                comment.Email      = user.Email;
                if (user.IsAdmin)
                {
                    comment.Status   = Status.Pended;
                    comment.IsMaster = true;
                }
            }
            comment.Content     = Regex.Replace(comment.Content.HtmlSantinizerStandard().ConvertImgSrcToRelativePath(), @"<img\s+[^>]*\s*src\s*=\s*['""]?(\S+\.\w{3,4})['""]?[^/>]*/>", "<img src=\"$1\"/>");
            comment.CommentDate = DateTime.Now;
            comment.Browser     = comment.Browser ?? Request.Browser.Type;
            comment.IP          = Request.UserHostAddress;
            Comment com = CommentBll.AddEntitySaved(comment.Mapper <Comment>());

            if (com != null)
            {
                var emails = new List <string>();
                var email  = GetSettings("ReceiveEmail"); //站长邮箱
                emails.Add(email);
                string content = System.IO.File.ReadAllText(Request.MapPath("/template/notify.html")).Replace("{{title}}", com.Post.Title).Replace("{{time}}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).Replace("{{nickname}}", com.NickName).Replace("{{content}}", com.Content);
                if (comment.Status == Status.Pended)
                {
                    if (!com.IsMaster)
                    {
                        MessageBll.AddEntitySaved(new InternalMessage()
                        {
                            Title   = $"来自【{com.NickName}】的新文章评论",
                            Content = com.Content,
                            Link    = Url.Action("Details", "Post", new
                            {
                                id  = com.PostId,
                                cid = com.Id
                            }, Request.Url.Scheme) + "#comment"
                        });
                    }
#if !DEBUG
                    if (com.ParentId == 0)
                    {
                        emails.Add(PostBll.GetById(com.PostId).Email);
                        //新评论,只通知博主和楼主
                        BackgroundJob.Enqueue(() => SendMail(Request.Url.Authority + "|博客文章新评论:", content.Replace("{{link}}", Url.Action("Details", "Post", new
                        {
                            id  = com.PostId,
                            cid = com.Id
                        }, Request.Url.Scheme) + "#comment"), string.Join(",", emails.Distinct())));
                    }
                    else
                    {
                        //通知博主和上层所有关联的评论访客
                        var pid = CommentBll.GetParentCommentIdByChildId(com.Id);
                        emails = CommentBll.GetSelfAndAllChildrenCommentsByParentId(pid).Select(c => c.Email).Except(new List <string>()
                        {
                            com.Email
                        }).Distinct().ToList();
                        string link = Url.Action("Details", "Post", new
                        {
                            id  = com.PostId,
                            cid = com.Id
                        }, Request.Url.Scheme) + "#comment";
                        BackgroundJob.Enqueue(() => SendMail($"{Request.Url.Authority}{GetSettings("Title")}文章评论回复:", content.Replace("{{link}}", link), string.Join(",", emails)));
                    }
#endif
                    return(ResultData(null, true, "评论发表成功,服务器正在后台处理中,这会有一定的延迟,稍后将显示到评论列表中"));
                }
                BackgroundJob.Enqueue(() => SendMail(Request.Url.Authority + "|博客文章新评论(待审核):", content.Replace("{{link}}", Url.Action("Details", "Post", new
                {
                    id  = com.PostId,
                    cid = com.Id
                }, Request.Url.Scheme) + "#comment") + "<p style='color:red;'>(待审核)</p>", string.Join(",", emails)));
                return(ResultData(null, true, "评论成功,待站长审核通过以后将显示"));
            }
            return(ResultData(null, false, "评论失败"));
        }
Ejemplo n.º 8
0
        public ActionResult Put(CommentInputDto comment)
        {
            if (Regex.Match(comment.Content, CommonHelper.BanRegex).Length > 0)
            {
                return(ResultData(null, false, "您提交的内容包含敏感词,被禁止发表,请注意改善您的言辞!"));
            }

            Post post = PostService.GetById(comment.PostId);

            if (post is null)
            {
                return(ResultData(null, false, "评论失败,文章不存在!"));
            }

            if (post.DisableComment)
            {
                return(ResultData(null, false, "本文已禁用评论功能,不允许任何人回复!"));
            }

            comment.Content = comment.Content.Trim().Replace("<p><br></p>", string.Empty);
            if (comment.Content.RemoveHtmlTag().Trim().Equals(HttpContext.Session.Get <string>("comment" + comment.PostId)))
            {
                return(ResultData(null, false, "您刚才已经在这篇文章发表过一次评论了,换一篇文章吧,或者换一下评论内容吧!"));
            }

            if (Regex.Match(comment.Content, CommonHelper.ModRegex).Length <= 0)
            {
                comment.Status = Status.Pended;
            }

            UserInfoOutputDto user = HttpContext.Session.Get <UserInfoOutputDto>(SessionKey.UserInfo);

            if (user != null)
            {
                comment.NickName   = user.NickName;
                comment.QQorWechat = user.QQorWechat;
                comment.Email      = user.Email;
                if (user.IsAdmin)
                {
                    comment.Status   = Status.Pended;
                    comment.IsMaster = true;
                }
            }
            comment.Content     = comment.Content.HtmlSantinizerStandard().ClearImgAttributes();
            comment.CommentDate = DateTime.Now;
            comment.Browser     = comment.Browser ?? Request.Headers[HeaderNames.UserAgent];
            comment.IP          = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
            Comment com = CommentService.AddEntitySaved(comment.Mapper <Comment>());

            if (com != null)
            {
                HttpContext.Session.Set("comment" + comment.PostId, comment.Content.RemoveHtmlTag().Trim());
                var emails = new List <string>();
                var email  = CommonHelper.SystemSettings["ReceiveEmail"]; //站长邮箱
                emails.Add(email);
                string content = System.IO.File.ReadAllText(_hostingEnvironment.WebRootPath + "/template/notify.html").Replace("{{title}}", post.Title).Replace("{{time}}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).Replace("{{nickname}}", com.NickName).Replace("{{content}}", com.Content);
                if (comment.Status == Status.Pended)
                {
                    if (!com.IsMaster)
                    {
                        MessageService.AddEntitySaved(new InternalMessage()
                        {
                            Title   = $"来自【{com.NickName}】的新文章评论",
                            Content = com.Content,
                            Link    = Url.Action("Details", "Post", new { id = com.PostId, cid = com.Id }, Request.Scheme) + "#comment"
                        });
                    }
#if !DEBUG
                    if (com.ParentId == 0)
                    {
                        emails.Add(PostService.GetById(com.PostId).Email);
                        //新评论,只通知博主和楼主
                        foreach (var s in emails.Distinct())
                        {
                            BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Domain"] + "|博客文章新评论:", content.Replace("{{link}}", Url.Action("Details", "Post", new { id = com.PostId, cid = com.Id }, Request.Scheme) + "#comment"), s));
                        }
                    }
                    else
                    {
                        //通知博主和上层所有关联的评论访客
                        var pid = CommentService.GetParentCommentIdByChildId(com.Id);
                        emails = CommentService.GetSelfAndAllChildrenCommentsByParentId(pid).Select(c => c.Email).Except(new List <string> {
                            com.Email
                        }).Distinct().ToList();
                        string link = Url.Action("Details", "Post", new { id = com.PostId, cid = com.Id }, Request.Scheme) + "#comment";
                        foreach (var s in emails)
                        {
                            BackgroundJob.Enqueue(() => CommonHelper.SendMail($"{CommonHelper.SystemSettings["Domain"]}{CommonHelper.SystemSettings["Title"]}文章评论回复:", content.Replace("{{link}}", link), s));
                        }
                    }
#endif
                    return(ResultData(null, true, "评论发表成功,服务器正在后台处理中,这会有一定的延迟,稍后将显示到评论列表中"));
                }
                foreach (var s in emails.Distinct())
                {
                    BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Domain"] + "|博客文章新评论(待审核):", content.Replace("{{link}}", Url.Action("Details", "Post", new { id = com.PostId, cid = com.Id }, Request.Scheme) + "#comment") + "<p style='color:red;'>(待审核)</p>", s));
                }
                return(ResultData(null, true, "评论成功,待站长审核通过以后将显示"));
            }
            return(ResultData(null, false, "评论失败"));
        }
Ejemplo n.º 9
0
        public async Task<ActionResult<CommentViewDto>> CreateCommentForPost([FromRoute] Guid postId, [FromBody] CommentInputDto commentInputDto)
        {
            //model state validation is not required due to the [ApiController] attribute automatically returning UnprocessableEntity (see startup.cs)
            //when model binding fails

            if (commentInputDto == null)
            {
                return BadRequest();
            }

            if (!await _postRepository.PostExistsAsync(postId))
            {
                return NotFound();
            }

            //fetch the user id from the JWT via HttpContext. Then get the user from the repository. This is to ensure that an authorized user
            //is calling the API with a valid user id
            var user = await _userRepository.GetUserAsync(User.GetUserId());

            if (user == null)
            {
                return BadRequest(new { Error = "The user was not found in the system. Please try again with an authorized and valid user." });
            }

            var commentToAdd = _mapper.Map<Comment>(commentInputDto); //map CommentInputDto to Comment
            commentToAdd.UserId = user.Id; //set the user id as otherwise navigation property will be null
            await _commentRepository.AddCommentAsync(postId, commentToAdd);

            if (!await _commentRepository.SaveChangesAsync())
            {
                throw new Exception($"Error saving Comment {commentToAdd.Id} to the database");
            }

            var commentToReturn = _mapper.Map<CommentViewDto>(commentToAdd);

            return CreatedAtRoute("GetComment", new { id = commentToAdd.Id }, commentToReturn);
        }
 public BaseResponse <bool> Update(Guid id, [FromBody] CommentInputDto commentInputDto)
 {
     return(_commentService.Update(id, commentInputDto));
 }
        public BaseResponse <CommentOutputDto> Create([FromBody] CommentInputDto commentInputDto)
        {
            var userId = User.GetUserId();

            return(_commentService.Create(commentInputDto, userId));
        }