コード例 #1
0
ファイル: PostController.cs プロジェクト: ldqk/Masuit.MyBlogs
        public async Task <ActionResult> Publish(PostCommand post, [Required(ErrorMessage = "验证码不能为空")] string code, CancellationToken cancellationToken)
        {
            if (await RedisHelper.GetAsync("code:" + post.Email) != code)
            {
                return(ResultData(null, false, "验证码错误!"));
            }

            if (PostService.Any(p => p.Status == Status.Forbidden && p.Email == post.Email))
            {
                return(ResultData(null, false, "由于您曾经恶意投稿,该邮箱已经被标记为黑名单,无法进行投稿,如有疑问,请联系网站管理员进行处理。"));
            }

            var match = Regex.Match(post.Title + post.Author + post.Content, CommonHelper.BanRegex);

            if (match.Success)
            {
                LogManager.Info($"提交内容:{post.Title}/{post.Author}/{post.Content},敏感词:{match.Value}");
                return(ResultData(null, false, "您提交的内容包含敏感词,被禁止发表,请检查您的内容后尝试重新提交!"));
            }

            if (!CategoryService.Any(c => c.Id == post.CategoryId))
            {
                return(ResultData(null, message: "请选择一个分类"));
            }

            post.Label   = string.IsNullOrEmpty(post.Label?.Trim()) ? null : post.Label.Replace(",", ",");
            post.Status  = Status.Pending;
            post.Content = await ImagebedClient.ReplaceImgSrc(await post.Content.HtmlSantinizerStandard().ClearImgAttributes(), cancellationToken);

            Post p = post.Mapper <Post>();

            p.IP            = ClientIP;
            p.Modifier      = p.Author;
            p.ModifierEmail = p.Email;
            p.DisableCopy   = true;
            p.Rss           = true;
            p = PostService.AddEntitySaved(p);
            if (p == null)
            {
                return(ResultData(null, false, "文章发表失败!"));
            }

            await RedisHelper.ExpireAsync("code:" + p.Email, 1);

            var content = new Template(await new FileInfo(HostEnvironment.WebRootPath + "/template/publish.html").ShareReadWrite().ReadAllTextAsync(Encoding.UTF8))
                          .Set("link", Url.Action("Details", "Post", new { id = p.Id }, Request.Scheme))
                          .Set("time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
                          .Set("title", p.Title).Render();

            BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "有访客投稿:", content, CommonHelper.SystemSettings["ReceiveEmail"], ClientIP));
            return(ResultData(p.Mapper <PostDto>(), message: "文章发表成功,待站长审核通过以后将显示到列表中!"));
        }
コード例 #2
0
        public async Task <ActionResult> Publish(PostInputDto post, string code)
        {
            if (RedisHelper.Get("code:" + post.Email) != code)
            {
                return(ResultData(null, false, "验证码错误!"));
            }

            if (Regex.Match(post.Content, CommonHelper.BanRegex).Length > 0)
            {
                return(ResultData(null, false, "您提交的内容包含敏感词,被禁止发表,请注意改善您的言辞!"));
            }

            if (!CategoryService.Any(c => c.Id == post.CategoryId))
            {
                return(ResultData(null, message: "请选择一个分类"));
            }

            post.Label      = string.IsNullOrEmpty(post.Label?.Trim()) ? null : post.Label.Replace(",", ",");
            post.Status     = Status.Pending;
            post.PostDate   = DateTime.Now;
            post.ModifyDate = DateTime.Now;
            post.Content    = await ImagebedClient.ReplaceImgSrc(post.Content.HtmlSantinizerStandard().ClearImgAttributes());

            ViewBag.CategoryId = new SelectList(CategoryService.GetQueryNoTracking(c => c.Status == Status.Available), "Id", "Name", post.CategoryId);
            Post p = post.Mapper <Post>();

            p.IP            = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
            p.Modifier      = p.Author;
            p.ModifierEmail = p.Email;
            p = PostService.AddEntitySaved(p);
            if (p == null)
            {
                return(ResultData(null, false, "文章发表失败!"));
            }

            RedisHelper.Expire("code:" + p.Email, 1);
            var content = System.IO.File.ReadAllText(HostEnvironment.WebRootPath + "/template/publish.html")
                          .Replace("{{link}}", Url.Action("Details", "Post", new { id = p.Id }, Request.Scheme))
                          .Replace("{{time}}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
                          .Replace("{{title}}", p.Title);

            BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "有访客投稿:", content, CommonHelper.SystemSettings["ReceiveEmail"]));
            return(ResultData(p.Mapper <PostOutputDto>(), message: "文章发表成功,待站长审核通过以后将显示到列表中!"));
        }
コード例 #3
0
        public async Task <ActionResult> Publish(PostCommand post, [Required(ErrorMessage = "验证码不能为空")] string code)
        {
            if (await RedisHelper.GetAsync("code:" + post.Email) != code)
            {
                return(ResultData(null, false, "验证码错误!"));
            }

            if (Regex.Match(post.Title + post.Author + post.Content, CommonHelper.BanRegex).Length > 0)
            {
                return(ResultData(null, false, "您提交的内容包含敏感词,被禁止发表,请检查您的内容后尝试重新提交!"));
            }

            if (!CategoryService.Any(c => c.Id == post.CategoryId))
            {
                return(ResultData(null, message: "请选择一个分类"));
            }

            post.Label   = string.IsNullOrEmpty(post.Label?.Trim()) ? null : post.Label.Replace(",", ",");
            post.Status  = Status.Pending;
            post.Content = await ImagebedClient.ReplaceImgSrc(post.Content.HtmlSantinizerStandard().ClearImgAttributes());

            //ViewBag.CategoryId = new SelectList(CategoryService.GetQueryNoTracking(c => c.Status == Status.Available), "Id", "Name", post.CategoryId);
            Post p = post.Mapper <Post>();

            p.IP            = ClientIP;
            p.Modifier      = p.Author;
            p.ModifierEmail = p.Email;
            p.DisableCopy   = true;
            p = PostService.AddEntitySaved(p);
            if (p == null)
            {
                return(ResultData(null, false, "文章发表失败!"));
            }

            await RedisHelper.ExpireAsync("code:" + p.Email, 1);

            var content = new Template(await System.IO.File.ReadAllTextAsync(HostEnvironment.WebRootPath + "/template/publish.html"))
                          .Set("link", Url.Action("Details", "Post", new { id = p.Id }, Request.Scheme))
                          .Set("time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
                          .Set("title", p.Title).Render();

            BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "有访客投稿:", content, CommonHelper.SystemSettings["ReceiveEmail"]));
            return(ResultData(p.Mapper <PostDto>(), message: "文章发表成功,待站长审核通过以后将显示到列表中!"));
        }
コード例 #4
0
        public ActionResult Write(PostInputDto post, DateTime?timespan, bool schedule = false)
        {
            post.Content = CommonHelper.ReplaceImgSrc(Regex.Replace(post.Content.Trim(), @"<img\s+[^>]*\s*src\s*=\s*['""]?(\S+\.\w{3,4})['""]?[^/>]*/>", "<img src=\"$1\"/>")).Replace("/thumb150/", "/large/"); //提取img标签,提取src属性并重新创建个只包含src属性的img标签
            if (!CategoryService.Any(c => c.Id == post.CategoryId && c.Status == Status.Available))
            {
                return(ResultData(null, message: "请选择一个分类"));
            }

            if (string.IsNullOrEmpty(post.Label?.Trim()) || post.Label.Equals("null"))
            {
                post.Label = null;
            }
            else if (post.Label.Trim().Length > 50)
            {
                post.Label = post.Label.Replace(",", ",");
                post.Label = post.Label.Trim().Substring(0, 50);
            }
            else
            {
                post.Label = post.Label.Replace(",", ",");
            }

            if (!post.IsWordDocument)
            {
                post.ResourceName = null;
            }

            if (string.IsNullOrEmpty(post.ProtectContent) || post.ProtectContent.Equals("null", StringComparison.InvariantCultureIgnoreCase))
            {
                post.ProtectContent = null;
            }

            post.Status     = Status.Pended;
            post.PostDate   = DateTime.Now;
            post.ModifyDate = DateTime.Now;
            Post p = post.Mapper <Post>();

            p.IP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
            if (!string.IsNullOrEmpty(post.Seminars))
            {
                var tmp = post.Seminars.Split(',').Distinct();
                tmp.ForEach(s =>
                {
                    var id          = s.ToInt32();
                    Seminar seminar = SeminarService.GetById(id);
                    p.Seminar.Add(new SeminarPost()
                    {
                        Post      = p,
                        PostId    = p.Id,
                        Seminar   = seminar,
                        SeminarId = seminar.Id
                    });
                });
            }

            p.PostAccessRecord.Add(new PostAccessRecord()
            {
                AccessTime = DateTime.Today,
                ClickCount = 0
            });
            if (schedule)
            {
                if (timespan.HasValue && timespan.Value > DateTime.Now)
                {
                    p.Status     = Status.Schedule;
                    p.PostDate   = timespan.Value;
                    p.ModifyDate = timespan.Value;
                    HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.PublishPost), args: p);
                    return(ResultData(p.Mapper <PostOutputDto>(), message: schedule ? $"文章于{timespan.Value:yyyy-MM-dd HH:mm:ss}将会自动发表!" : "文章发表成功!"));
                }

                return(ResultData(null, false, "如果要定时发布,请选择正确的一个将来时间点!"));
            }

            bool b = PostService.AddEntitySaved(p) != null;

            if (b)
            {
                if ("false" == CommonHelper.SystemSettings["DisabledEmailBroadcast"])
                {
                    var    cast = BroadcastService.LoadEntities(c => c.Status == Status.Subscribed).ToList();
                    string link = Request.Scheme + "://" + Request.Host + "/" + p.Id;
                    cast.ForEach(c =>
                    {
                        var ts         = DateTime.Now.GetTotalMilliseconds();
                        string content = System.IO.File.ReadAllText(_hostingEnvironment.WebRootPath + "/template/broadcast.html")
                                         .Replace("{{link}}", link + "?email=" + c.Email)
                                         .Replace("{{time}}", post.ModifyDate.ToString("yyyy-MM-dd HH:mm:ss"))
                                         .Replace("{{title}}", post.Title).Replace("{{author}}", post.Author)
                                         .Replace("{{content}}", post.Content.RemoveHtmlTag(150))
                                         .Replace("{{cancel}}", Url.Action("Subscribe", "Subscribe", new
                        {
                            c.Email,
                            act      = "cancel",
                            validate = c.ValidateCode,
                            timespan = ts,
                            hash     = (c.Email + "cancel" + c.ValidateCode + ts).AESEncrypt(AppConfig.BaiduAK)
                        }, Request.Scheme));
                        BackgroundJob.Schedule(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "博客有新文章发布了", content, c.Email), (p.ModifyDate - DateTime.Now));
                    });
                }

                return(ResultData(null, true, "文章发表成功!"));
            }

            return(ResultData(null, false, "文章发表失败!"));
        }
コード例 #5
0
        public ActionResult Publish(PostInputDto post)
        {
            if (Regex.Match(post.Content, CommonHelper.BanRegex).Length > 0)
            {
                return(ResultData(null, false, "您提交的内容包含敏感词,被禁止发表,请注意改善您的言辞!"));
            }

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

            if (!CategoryService.Any(c => c.Id == post.CategoryId && c.Status == Status.Available))
            {
                return(ResultData(null, message: "请选择一个分类"));
            }

            if (string.IsNullOrEmpty(post.Label?.Trim()))
            {
                post.Label = null;
            }
            else if (post.Label.Trim().Length > 50)
            {
                post.Label = post.Label.Replace(",", ",").Trim().Substring(0, 50);
            }
            else
            {
                post.Label = post.Label.Replace(",", ",");
            }

            post.Status     = Status.Pending;
            post.PostDate   = DateTime.Now;
            post.ModifyDate = DateTime.Now;
            if (user != null && user.IsAdmin)
            {
                post.Status = Status.Pended;
            }
            else
            {
                post.Content = CommonHelper.ReplaceImgSrc(Regex.Replace(post.Content.HtmlSantinizerStandard(), @"<img\s+[^>]*\s*src\s*=\s*['""]?(\S+\.\w{3,4})['""]?[^/>]*/>", "<img src=\"$1\"/>")).Replace("/thumb150/", "/large/");
            }

            ViewBag.CategoryId = new SelectList(CategoryService.LoadEntitiesNoTracking(c => c.Status == Status.Available), "Id", "Name", post.CategoryId);
            Post p = post.Mapper <Post>();

            p.IP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
            p.PostAccessRecord.Add(new PostAccessRecord()
            {
                AccessTime = DateTime.Today,
                ClickCount = 0
            });
            p = PostService.AddEntitySaved(p);
            if (p != null)
            {
                if (p.Status == Status.Pending)
                {
                    var    email = CommonHelper.SystemSettings["ReceiveEmail"];
                    string link  = Url.Action("Details", "Post", new
                    {
                        id = p.Id
                    }, Request.Scheme);
                    string content = System.IO.File.ReadAllText(_hostingEnvironment.WebRootPath + "/template/publish.html").Replace("{{link}}", link).Replace("{{time}}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).Replace("{{title}}", p.Title);
                    BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "有访客投稿:", content, email));
                    return(ResultData(p.Mapper <PostOutputDto>(), message: "文章发表成功,待站长审核通过以后将显示到列表中!"));
                }

                return(ResultData(p.Mapper <PostOutputDto>(), message: "文章发表成功!"));
            }

            return(ResultData(null, false, "文章发表失败!"));
        }