Example #1
0
        public async Task <ActionResult> Create(BlogEdit blog, [FromServices] HtmlSanitizerService sanitizerService)
        {
            ViewBag.CategoryList = _catUtil.GetCategoryDropdown();
            ViewBag.UserHanGroup = GetUserHanGroup();
            string        content    = blog.Content;
            bool          isLocalimg = false;
            Blog          newblog;
            List <string> imglist = null;

            try
            {
                if (!ModelState.IsValid)
                {
                    throw new BlogException();
                }
                if (content == null || string.IsNullOrWhiteSpace(BlogHelper.removeAllTags(content)))
                {
                    ModelState.AddModelError("", "内容不能为空或纯图片");
                    throw new BlogException();
                }
                if (NolinkCategories == null || !NolinkCategories.Contains(blog.CategoryID))
                {
                    if (blog.BlogLinks == null)
                    {
                        ModelState.AddModelError("", "链接地址不能为空");
                        throw new BlogException();
                    }
                    else
                    {
                        blog.BlogLinks = blog.BlogLinks.Where(b => !string.IsNullOrWhiteSpace(b.url)).ToArray();
                        if (!BlogHelper.checkBlogLinks(blog.BlogLinks))
                        {
                            ModelState.AddModelError("", "链接地址不能为空,且不得包含javascript");
                            throw new BlogException();
                        }
                    }
                }
                if (!_blogUtil.CheckAdmin())
                {
                    content = sanitizerService.Sanitize(content);
                }
                if (blog.HanGroupID.HasValue && !_db.HanGroupMembers.Any(h => h.Username == User.Identity.Name && h.HanGroupID == blog.HanGroupID))
                {
                    ModelState.AddModelError("", "汉化组ID无效,请刷新重试。");
                    throw new BlogException();
                }
                List <IFormFile> BlogImages = new List <IFormFile>();
                if (Request.Form.Files.Count > 0)
                {
                    for (int i = 0; i < Request.Form.Files.Count; i++)
                    {
                        var file = Request.Form.Files[i];
                        if (file.Length > 0)
                        {
                            if (!file.ContentType.Contains("image"))
                            {
                                ModelState.AddModelError("", "不接受的文件类型");
                                throw new BlogException();
                            }
                            else if (file.Length > 1048576 * 4)
                            {
                                ModelState.AddModelError("", "文件不得超过4MB");
                                throw new BlogException();
                            }
                            isLocalimg = true;
                            BlogImages.Add(file);
                        }
                        else
                        {
                            content = BlogHelper.removeImgPlaceholder(content, i);
                        }
                    }
                }
                if (!isLocalimg)
                {
                    var imgname = BlogHelper.getFirstImg(content);
                    if (imgname == null || imgname.Length < 5)
                    {
                        ModelState.AddModelError("", "请添加预览图!(上传或在文中外链图片)");
                        throw new BlogException();
                    }
                    imglist = new List <string>()
                    {
                        imgname
                    };
                }
                else
                {
                    try
                    {
                        imglist = await _uploadUtil.SaveImagesAsync(BlogImages);
                    }
                    catch (Exception e)
                    {
                        ModelState.AddModelError("", "保存图片时发生异常:(" + e.Message + ")。如多次出错,请汇报给管理员。");
                        throw new BlogException(e.Message, e);
                    }
                    if (imglist.Count < 1)
                    {
                        ModelState.AddModelError("", "图片服务器上传出错,请稍后再试。如多次出错,请汇报给管理员。");
                        throw new BlogException();
                    }
                }
                string imgpath = string.Empty;
                if (imglist != null)
                {
                    imgpath = string.Join(";", imglist);
                }
                bool approve = User.IsInRole("Administrator") || User.IsInRole("Writers") || User.IsInRole("Moderator");
                // Replace 【】() with []()
                blog.BlogTitle = blog.BlogTitle.ToSingleByteCharacterString();
                blog.ImagePath = imgpath;
                content        = BlogHelper.RemoveComments(content);
                newblog        = _blogUtil.AddBlog(blog.BlogTitle, content,
                                                   blog.CategoryID, imgpath, User.Identity.Name, approve, isLocalimg, blog.BlogLinks);
                var taglist = new List <Tag>();
                if (!string.IsNullOrEmpty(blog.BlogTags))
                {
                    string[] tags = TagUtil.SplitTags(blog.BlogTags);
                    taglist = _tagUtil.AddTagsForBlog(newblog.BlogID, tags, newblog.Author);
                }
                var save = false;
                if (BlogHelper.BlogIsHarmony(_db, newblog, HarmonySettings))
                {
                    newblog.isHarmony = true;
                    save = true;
                }
                if (blog.HanGroupID.HasValue)
                {
                    _db.HanGroupBlogs.Add(new HanGroupBlog {
                        BlogID = newblog.BlogID, HanGroupID = blog.HanGroupID.Value
                    });
                    save = true;
                }
                if (blog.Option != null && !blog.Option.IsDefault())
                {
                    newblog.option = blog.Option.OverrideOption(_blogUtil);
                    if (newblog.option.NoApprove)
                    {
                        newblog.isApproved = false;
                    }
                    save = true;
                }
                if (save)
                {
                    _db.SaveChanges();
                }
                TriggerNewBlog(newblog, taglist);
            }
            catch (BlogException e)
            {
                if (Request.IsAjaxRequest())
                {
                    return(Json(new
                    {
                        err = e.Message + string.Join(";", ModelState.Values.SelectMany(m => m.Errors)
                                                      .Select(err => err.ErrorMessage)
                                                      .ToList())
                    }));
                }
                return(View(blog));
            }
            catch
            {
                if (isLocalimg && imglist != null)
                {
                    await _uploadUtil.DeleteFilesAsync(imglist.Concat(new[] { blog.ImagePath.Split(';')[0].Replace("/upload/", "/thumbs/") }));
                }
                throw;
            }
            if (Request.IsAjaxRequest())
            {
                return(Json(new { id = newblog.BlogID, src = BlogHelper.firstImgPath(newblog, true) }));
            }
            return(RedirectToAction("Details", new { id = newblog.BlogID }));
        }