/// <summary>
 /// 评论管理
 /// </summary>
 /// <param name="commentService"></param>
 /// <param name="postService"></param>
 /// <param name="messageService"></param>
 /// <param name="hostingEnvironment"></param>
 public CommentController(ICommentService commentService, IPostService postService, IInternalMessageService messageService, IHostingEnvironment hostingEnvironment)
 {
     CommentService      = commentService;
     PostService         = postService;
     MessageService      = messageService;
     _hostingEnvironment = hostingEnvironment;
 }
Beispiel #2
0
 public InternalMessagesController(
     IInternalMessageService internalMessageService,
     IMapper mapper)
 {
     _internalMessageService = internalMessageService;
     _mapper = mapper;
 }
Beispiel #3
0
        public async Task <ActionResult> PushMerge([FromServices] IInternalMessageService messageService, [FromServices] IPostMergeRequestService postMergeRequestService, PostMergeRequestCommand dto)
        {
            if (await RedisHelper.GetAsync("code:" + dto.ModifierEmail) != dto.Code)
            {
                return(ResultData(null, false, "验证码错误!"));
            }

            var post = await PostService.GetByIdAsync(dto.PostId) ?? throw new NotFoundException("文章未找到");

            var htmlDiff = new HtmlDiff.HtmlDiff(post.Content.RemoveHtmlTag(), dto.Content.RemoveHtmlTag());
            var diff     = htmlDiff.Build();

            if (post.Title.Equals(dto.Title) && !diff.Contains(new[] { "diffmod", "diffdel", "diffins" }))
            {
                return(ResultData(null, false, "内容未被修改!"));
            }

            #region 合并验证

            if (postMergeRequestService.Any(p => p.ModifierEmail == dto.ModifierEmail && p.MergeState == MergeStatus.Block))
            {
                return(ResultData(null, false, "由于您曾经多次恶意修改文章,已经被标记为黑名单,无法修改任何文章,如有疑问,请联系网站管理员进行处理。"));
            }

            if (post.PostMergeRequests.Any(p => p.ModifierEmail == dto.ModifierEmail && p.MergeState == MergeStatus.Pending))
            {
                return(ResultData(null, false, "您已经提交过一次修改请求正在待处理,暂不能继续提交修改请求!"));
            }

            #endregion

            #region 直接合并

            if (post.Email.Equals(dto.ModifierEmail))
            {
                var history = post.Mapper <PostHistoryVersion>();
                Mapper.Map(dto, post);
                post.PostHistoryVersion.Add(history);
                post.ModifyDate = DateTime.Now;
                return(await PostService.SaveChangesAsync() > 0 ? ResultData(null, true, "你是文章原作者,无需审核,文章已自动更新并在首页展示!") : ResultData(null, false, "操作失败!"));
            }

            #endregion

            var merge = post.PostMergeRequests.FirstOrDefault(r => r.Id == dto.Id && r.MergeState != MergeStatus.Merged);
            if (merge != null)
            {
                Mapper.Map(dto, merge);
                merge.SubmitTime = DateTime.Now;
                merge.MergeState = MergeStatus.Pending;
            }
            else
            {
                merge            = Mapper.Map <PostMergeRequest>(dto);
                merge.SubmitTime = DateTime.Now;
                post.PostMergeRequests.Add(merge);
            }

            var b = await PostService.SaveChangesAsync() > 0;

            if (!b)
            {
                return(ResultData(null, false, "操作失败!"));
            }

            await RedisHelper.ExpireAsync("code:" + dto.ModifierEmail, 1);

            await messageService.AddEntitySavedAsync(new InternalMessage()
            {
                Title   = $"来自【{dto.Modifier}】对文章《{post.Title}》的修改请求",
                Content = dto.Title,
                Link    = "#/merge/compare?id=" + merge.Id
            });

            var content = new Template(await System.IO.File.ReadAllTextAsync(HostEnvironment.WebRootPath + "/template/merge-request.html"))
                          .Set("title", post.Title)
                          .Set("link", Url.Action("Index", "Dashboard", new { }, Request.Scheme) + "#/merge/compare?id=" + merge.Id)
                          .Set("diff", diff)
                          .Set("host", "//" + Request.Host)
                          .Set("id", merge.Id.ToString())
                          .Render();
            BackgroundJob.Enqueue(() => CommonHelper.SendMail("博客文章修改请求:", content, CommonHelper.SystemSettings["ReceiveEmail"], ClientIP));
            return(ResultData(null, true, "您的修改请求已提交,已进入审核状态,感谢您的参与!"));
        }
        public async Task <ActionResult> Submit([FromServices] IInternalMessageService messageService, [FromServices] IMailSender mailSender, CommentCommand dto)
        {
            var match = Regex.Match(dto.NickName + dto.Content.RemoveHtmlTag(), CommonHelper.BanRegex);

            if (match.Success)
            {
                LogManager.Info($"提交内容:{dto.NickName}/{dto.Content},敏感词:{match.Value}");
                return(ResultData(null, false, "您提交的内容包含敏感词,被禁止发表,请检查您的内容后尝试重新提交!"));
            }
            var error = await ValidateEmailCode(mailSender, dto.Email, dto.Code);

            if (!string.IsNullOrEmpty(error))
            {
                return(ResultData(null, false, error));
            }

            Post post = await PostService.GetByIdAsync(dto.PostId) ?? throw new NotFoundException("评论失败,文章未找到");

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

            dto.Content = dto.Content.Trim().Replace("<p><br></p>", string.Empty);
            if (CommentFeq.GetOrAdd("Comments:" + ClientIP, 1) > 2)
            {
                CommentFeq.Expire("Comments:" + ClientIP, TimeSpan.FromMinutes(1));
                return(ResultData(null, false, "您的发言频率过快,请稍后再发表吧!"));
            }

            var comment = dto.Mapper <Comment>();

            if (Regex.Match(dto.NickName + dto.Content, CommonHelper.ModRegex).Length <= 0)
            {
                comment.Status = Status.Published;
            }

            comment.CommentDate = DateTime.Now;
            var user = HttpContext.Session.Get <UserInfoDto>(SessionKey.UserInfo);

            if (user != null)
            {
                comment.NickName = user.NickName;
                comment.Email    = user.Email;
                if (user.IsAdmin)
                {
                    comment.Status   = Status.Published;
                    comment.IsMaster = true;
                }
            }
            comment.Content = await dto.Content.HtmlSantinizerStandard().ClearImgAttributes();

            comment.Browser  = dto.Browser ?? Request.Headers[HeaderNames.UserAgent];
            comment.IP       = ClientIP;
            comment.Location = Request.Location();
            comment          = CommentService.AddEntitySaved(comment);
            if (comment == null)
            {
                return(ResultData(null, false, "评论失败"));
            }

            Response.Cookies.Append("NickName", comment.NickName, new CookieOptions()
            {
                Expires  = DateTimeOffset.Now.AddYears(1),
                SameSite = SameSiteMode.Lax
            });
            WriteEmailKeyCookie(dto.Email);
            CommentFeq.AddOrUpdate("Comments:" + ClientIP, 1, i => i + 1, 5);
            CommentFeq.Expire("Comments:" + ClientIP, TimeSpan.FromMinutes(1));
            var emails = new HashSet <string>();
            var email  = CommonHelper.SystemSettings["ReceiveEmail"]; //站长邮箱

            emails.Add(email);
            var content = new Template(await System.IO.File.ReadAllTextAsync(HostEnvironment.WebRootPath + "/template/notify.html"))
                          .Set("title", post.Title)
                          .Set("time", DateTime.Now.ToTimeZoneF(HttpContext.Session.Get <string>(SessionKey.TimeZone)))
                          .Set("nickname", comment.NickName)
                          .Set("content", comment.Content);

            if (comment.Status == Status.Published)
            {
                if (!comment.IsMaster)
                {
                    await messageService.AddEntitySavedAsync(new InternalMessage()
                    {
                        Title   = $"来自【{comment.NickName}】在文章《{post.Title}》的新评论",
                        Content = comment.Content,
                        Link    = Url.Action("Details", "Post", new { id = comment.PostId, cid = comment.Id }) + "#comment"
                    });
                }
                if (comment.ParentId == 0)
                {
                    emails.Add(post.Email);
                    emails.Add(post.ModifierEmail);
                    //新评论,只通知博主和楼主
                    foreach (var s in emails)
                    {
                        BackgroundJob.Enqueue(() => CommonHelper.SendMail(Request.Host + "|博客文章新评论:", content.Set("link", Url.Action("Details", "Post", new { id = comment.PostId, cid = comment.Id }, Request.Scheme) + "#comment").Render(false), s, ClientIP));
                    }
                }
                else
                {
                    //通知博主和上层所有关联的评论访客
                    var parent = await CommentService.GetByIdAsync(comment.ParentId);

                    emails.AddRange(parent.Root().Flatten().Select(c => c.Email).ToArray());
                    emails.AddRange(post.Email, post.ModifierEmail);
                    emails.Remove(comment.Email);
                    string link = Url.Action("Details", "Post", new { id = comment.PostId, cid = comment.Id }, Request.Scheme) + "#comment";
                    foreach (var s in emails)
                    {
                        BackgroundJob.Enqueue(() => CommonHelper.SendMail($"{Request.Host}{CommonHelper.SystemSettings["Title"]}文章评论回复:", content.Set("link", link).Render(false), s, ClientIP));
                    }
                }
                return(ResultData(null, true, "评论发表成功,服务器正在后台处理中,这会有一定的延迟,稍后将显示到评论列表中"));
            }

            foreach (var s in emails)
            {
                BackgroundJob.Enqueue(() => CommonHelper.SendMail(Request.Host + "|博客文章新评论(待审核):", content.Set("link", Url.Action("Details", "Post", new { id = comment.PostId, cid = comment.Id }, Request.Scheme) + "#comment").Render(false) + "<p style='color:red;'>(待审核)</p>", s, ClientIP));
            }

            return(ResultData(null, true, "评论成功,待站长审核通过以后将显示"));
        }
 /// <summary>
 /// 留言板和站内信
 /// </summary>
 /// <param name="leaveMessageService"></param>
 /// <param name="messageService"></param>
 /// <param name="hostingEnvironment"></param>
 public MsgController(ILeaveMessageService leaveMessageService, IInternalMessageService messageService, IHostingEnvironment hostingEnvironment)
 {
     LeaveMessageService = leaveMessageService;
     MessageService      = messageService;
     _hostingEnvironment = hostingEnvironment;
 }