示例#1
0
        public IActionResult UpdatePost(Guid authorId, Guid postId, PostInputDto updatedPost,
                                        [FromHeader(Name = "Content-Type")] string mediaType)
        {
            if (IsUserIdNotEqualTo(authorId))
            {
                return(Unauthorized());
            }

            var idsSet       = new PostIdsSet(authorId, postId);
            var postFromRepo = blogRepository.GetPostForAuthor(authorId, postId);

            if (postFromRepo is null)
            {
                return(AddPost(idsSet, updatedPost, IncludeLinks(mediaType)));
            }

            mapper.Map(updatedPost, postFromRepo);
            blogRepository.SaveChanges();

            if (IncludeLinks(mediaType))
            {
                var mappedPost = mapper.Map <PostOutputDto>(postFromRepo);
                return(Ok(ShapeAndLinkSinglePost(mappedPost, idsSet)));
            }

            return(NoContent());
        }
        public async Task <Post> AddNewPost(PostInputDto postInputDto)
        {
            try
            {
                // Yeni bir Post ekliyoruz (Insert işlemi)
                // _mapper AutoMapper yardımı ile gelen (PostInputDto postInputDto) nesnesi Post tipine mapliyoruz
                var CreatedPostInfo = _postService.Insert(_mapper.Map <Post>(postInputDto));
                // PostTag tablosuna PostId ve TagId (birden çok olabilir) parametreleri ile kayıt atıyoruz
                PostTagAdded(postInputDto, CreatedPostInfo.PostId);

                /* Indexleme işleminde önerme (Suggest) işlemi için keywordler oluşturuyoruz
                 * Burada keyword olarak CategoryName, ve eklenen TagName (birden çok olabilir) bilgilerini alıyoruz isterseniz Post'un başlık alanınıda ekleyebiliriz.
                 * Önerme (Suggest) işlemlerinde hangi keywordlerden yararlanmak istiyorsak ekleyebiliriz.    */
                var suggestList = GetPostElasticSuggetItems(CreatedPostInfo);
                // Indexleme işleminde TagNameValues alanı olarak TagName degerlerini bir List<string> liste olarak alıyoruz.
                var tagNameValues = GetPostTagListForPost(CreatedPostInfo);
                // Indexleme işlemi için son olarak elde ettiğimiz tüm veriler ile Index atılacak nesnemizi (PostElasticIndexDto) oluşturuyoruz.
                var indexCreateItem = GetElasticIndexItem(CreatedPostInfo, tagNameValues, postInputDto.PostTagIds, suggestList);
                // Index ekleme işlemi için yazılan metot
                PostAddOrUpdateElasticIndex(indexCreateItem);
                // Geriye, oluşturulan nesnemizi (PostElasticIndexDto) dönüyoruz.
                return(await Task.FromResult(CreatedPostInfo));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message, ex);
                return(await Task.FromException <Post>(ex));
            }
        }
示例#3
0
        public async Task <ActionResult <PostViewDto> > CreatePost([FromBody] PostInputDto postInputDto)
        {
            if (postInputDto == null)
            {
                return(BadRequest());
            }

            //model state validation is not required due to the [ApiController] attribute automatically returning UnprocessableEntity (see startup.cs)
            //when model binding fails

            //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 postToAdd = _mapper.Map <Post>(postInputDto); //map PostInputDto to Post

            postToAdd.UserId = user.Id;                       //set the user id as otherwise navigation property will be null
            _postRepository.AddPost(postToAdd);

            if (!await _postRepository.SaveChangesAsync())
            {
                throw new Exception($"Error saving Post {postToAdd.Id} to the database");
            }

            var postToReturn = _mapper.Map <PostViewDto>(postToAdd);

            return(CreatedAtRoute("GetPost", new { id = postToAdd.Id }, postToReturn));
        }
示例#4
0
 public bool SetPost(PostInputDto postInput)
 {
     try
     {
         DateTime date = DateTime.Now;
         Posts    post = new Posts
         {
             PostTitle       = postInput.PostTitle,
             PostIcon        = "https://bbs.3dmgame.com/static/image/common/folder_new.gif",
             PostTypeId      = postInput.PostTypeId,
             PostType        = postInput.PostType,
             PostContent     = postInput.Content,
             CreateTime      = date,
             CreateUserId    = postInput.UserId,
             EditTime        = date,
             EditUserId      = postInput.UserId,
             LastReplyTime   = date,
             LastReplyUserId = postInput.UserId,
             Clicks          = 1,
             Replys          = 0,
         };
         _postsService.InsertPost(post);
         return(true);
     }
     catch (System.Exception ex)
     {
         throw;
     }
 }
示例#5
0
        public ActionResult Publish(PostInputDto post)
        {
            UserInfoOutputDto user = Session.GetByRedis <UserInfoOutputDto>(SessionKey.UserInfo);

            if (!CategoryBll.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(",", ",");
                post.Label = post.Label.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 = 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(CategoryBll.LoadEntitiesNoTracking(c => c.Status == Status.Available), "Id", "Name", post.CategoryId);
            Post p = post.Mapper <Post>();

            p.PostAccessRecord.Add(new PostAccessRecord()
            {
                AccessTime = DateTime.Today,
                ClickCount = 0
            });
            p = PostBll.AddEntitySaved(p);
            if (p != null)
            {
                if (p.Status == Status.Pending)
                {
                    var    email = GetSettings("ReceiveEmail");
                    string link  = Url.Action("Details", "Post", new
                    {
                        id = p.Id
                    }, Request.Url?.Scheme ?? "http");
                    string content = System.IO.File.ReadAllText(Request.MapPath("/template/publish.html")).Replace("{{link}}", link).Replace("{{time}}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).Replace("{{title}}", p.Title);
                    BackgroundJob.Enqueue(() => SendMail(GetSettings("Title") + "有访客投稿:", content, email));
                    return(ResultData(p.Mapper <PostOutputDto>(), message: "文章发表成功,待站长审核通过以后将显示到列表中!"));
                }
                return(ResultData(p.Mapper <PostOutputDto>(), message: "文章发表成功!"));
            }
            return(ResultData(null, false, "文章发表失败!"));
        }
 private void PostTagAdded(PostInputDto postInputDto, int postId)
 {
     foreach (var itemTag in postInputDto.PostTagIds)
     {
         _PostTagService.Insert(new PostTag {
             PostId = postId, TagId = itemTag
         });
     }
 }
示例#7
0
        public async Task Add_InvalidPost_Returns_BadRequest()
        {
            //Arrange
            PostInputDto x = null;

            //Act
            var result = await postsController.CreatePost(x);

            //Assert
            Assert.IsType <BadRequestResult>(result.Result);
        }
示例#8
0
        public IActionResult AddPost(Guid authorId, PostInputDto newPost,
                                     [FromHeader(Name = "Content-Type")] string mediaType)
        {
            if (IsUserIdNotEqualTo(authorId))
            {
                return(Unauthorized());
            }

            var idsSet = new PostIdsSet(authorId);

            return(AddPost(idsSet, newPost, IncludeLinks(mediaType)));
        }
示例#9
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: "文章发表成功,待站长审核通过以后将显示到列表中!"));
        }
示例#10
0
        public void PostsProfileTest()
        {
            // Arrange
            var mapperConfiguration = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new PostsProfile());
                cfg.AddProfile(new AuthorsProfile());
                cfg.AddProfile(new CommentsProfile());
            });

            var target = new Mapper(mapperConfiguration);

            var postInput = new PostInputDto()
            {
                Contents = "Contents",
                Tags     = new string[] { "tag1", "tag2", "tag3" }
            };

            var post = new Post()
            {
                Tags = new Tags("tag1", "tag2", "tag3")
            };

            // Act
            var testDelegate = new TestDelegate(mapperConfiguration.AssertConfigurationIsValid);
            var inputResult  = target.Map <Post>(postInput);
            var outputResult = target.Map <PostOutputDto>(post);

            // Assert
            Assert.DoesNotThrow(testDelegate);

            var expectedInputTags = "<tag1><tag2><tag3>";

            Assert.AreEqual(expectedInputTags, inputResult.Tags.Raw);
            Assert.AreEqual(postInput.Contents, inputResult.Contents);

            var expectedOutputTags = new string[] { "tag1", "tag2", "tag3" };

            Assert.AreEqual(expectedOutputTags, outputResult.Tags);
        }
示例#11
0
        private IActionResult AddPost(PostIdsSet idsSet, PostInputDto newPost, bool includeLinks)
        {
            if (validator.DontMatchRules(newPost as IPostInputDto, ModelState))
            {
                return(ValidationProblem(ModelState));
            }

            if (blogRepository.AuthorNotExist(idsSet.authorId))
            {
                return(NotFound());
            }

            var postToAdd = mapper.Map <Post>(newPost);

            postToAdd.AuthorId = idsSet.authorId;
            InsertAuthorsInto(postToAdd);

            if (idsSet.postId != Guid.Empty)
            {
                postToAdd.Id = idsSet.postId;
            }

            blogRepository.AddPostForAuthor(idsSet.authorId, postToAdd);
            blogRepository.SaveChanges();

            var mappedPost = mapper.Map <PostOutputDto>(postToAdd);

            idsSet.postId = mappedPost.Id;

            dynamic toReturn = mappedPost;

            if (includeLinks)
            {
                toReturn = ShapeAndLinkSinglePost(mappedPost, idsSet);
            }

            return(CreatedAtRoute("GetPost",
                                  new { idsSet.authorId, idsSet.postId }, toReturn));
        }
 public async Task <Post> Update(PostInputDto postInputDto)
 {
     //using (TransactionScope scope = new TransactionScope())
     //{
     try
     {
         var updatedPostInfo = _postService.Update(_mapper.Map <Post>(postInputDto));
         PostTagsRemove(updatedPostInfo.PostId);
         PostTagAdded(postInputDto, updatedPostInfo.PostId);
         var suggestList     = GetPostElasticSuggetItems(updatedPostInfo);
         var tagNameValues   = GetPostTagListForPost(updatedPostInfo);
         var indexCreateItem = GetElasticIndexItem(updatedPostInfo, tagNameValues, postInputDto.PostTagIds, suggestList);
         PostAddOrUpdateElasticIndex(indexCreateItem);
         // scope.Complete();
         return(await Task.FromResult(updatedPostInfo));
     }
     catch (Exception ex)
     {
         // scope.Dispose();
         _logger.LogError(ex.Message, ex);
         return(await Task.FromException <Post>(ex));
     }
     //}
 }
示例#13
0
        public async Task <ActionResult> Write(PostInputDto post, DateTime?timespan, bool schedule = false)
        {
            post.Content = await ImagebedClient.ReplaceImgSrc(post.Content.Trim().ClearImgAttributes());

            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.Modifier      = p.Author;
            p.ModifierEmail = p.Email;
            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
                    });
                });
            }

            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: $"文章于{timespan.Value:yyyy-MM-dd HH:mm:ss}将会自动发表!"));
                }

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

            PostService.AddEntity(p);
            bool b = SearchEngine.SaveChanges() > 0;

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

            if ("true" == CommonHelper.SystemSettings["DisabledEmailBroadcast"])
            {
                return(ResultData(null, true, "文章发表成功!"));
            }
            var    cast = BroadcastService.GetQuery(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(HostEnvironment.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, "文章发表成功!"));
        }
示例#14
0
        public async Task <ActionResult> Edit(PostInputDto post, bool notify = true, bool reserve = true)
        {
            post.Content = await ImagebedClient.ReplaceImgSrc(post.Content.Trim().ClearImgAttributes());

            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 p = PostService.GetById(post.Id);

            if (reserve)
            {
                var history = p.Mapper <PostHistoryVersion>();
                p.PostHistoryVersion.Add(history);
                post.ModifyDate = DateTime.Now;
                var user = HttpContext.Session.Get <UserInfoOutputDto>(SessionKey.UserInfo);
                p.Modifier      = user.NickName;
                p.ModifierEmail = user.Email;
            }

            p.IP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
            Mapper.Map(post, p);
            if (!string.IsNullOrEmpty(post.Seminars))
            {
                var tmp = post.Seminars.Split(',').Distinct();
                p.Seminar.Clear();
                tmp.ForEach(s =>
                {
                    var seminar = SeminarService.Get(e => e.Title.Equals(s));
                    if (seminar != null)
                    {
                        p.Seminar.Add(new SeminarPost()
                        {
                            Post      = p,
                            Seminar   = seminar,
                            PostId    = p.Id,
                            SeminarId = seminar.Id
                        });
                    }
                });
            }

            bool b = SearchEngine.SaveChanges() > 0;

            if (!b)
            {
                return(ResultData(null, false, "文章修改失败!"));
            }

#if !DEBUG
            if (notify && "false" == CommonHelper.SystemSettings["DisabledEmailBroadcast"])
            {
                var    cast = BroadcastService.GetQuery(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(Path.Combine(HostEnvironment.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));
                });
            }
#endif
            return(ResultData(p.Mapper <PostOutputDto>(), message: "文章修改成功!"));
        }
示例#15
0
        public ActionResult Write(PostInputDto post, string Seminars, DateTime?timespan, bool schedule = false)
        {
            post.Content = 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 (!CategoryBll.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>();

            if (!string.IsNullOrEmpty(Seminars))
            {
                var tmp = Seminars.Split(',').Distinct();
                tmp.ForEach(s =>
                {
                    var id = s.ToInt32();
                    p.Seminar.Add(SeminarBll.GetById(id));
                });
            }
            p.PostAccessRecord.Add(new PostAccessRecord()
            {
                AccessTime = DateTime.Today,
                ClickCount = 0
            });
            if (schedule)
            {
                if (timespan.HasValue && timespan.Value > DateTime.Now)
                {
                    p.Status = Status.Schedule;
                    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, "如果要定时发布,请选择正确的一个将来时间点!"));
            }
            p = PostBll.AddEntitySaved(p);
            if (p != null)
            {
                var    cast = BroadcastBll.LoadEntities(c => c.Status == Status.Subscribed).ToList();
                string link = Request.Url?.Scheme + "://" + Request.Url?.Authority + "/" + p.Id;
                cast.ForEach(c =>
                {
                    var ts         = DateTime.Now.GetTotalMilliseconds();
                    string content = System.IO.File.ReadAllText(Request.MapPath("/template/broadcast.html")).Replace("{{link}}", link + "?email=" + c.Email).Replace("{{time}}", post.PostDate.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(ConfigurationManager.AppSettings["BaiduAK"]) }, Request.Url.Scheme));
                    BackgroundJob.Schedule(() => SendMail(GetSettings("Title") + "博客有新文章发布了", content, c.Email), (p.PostDate - DateTime.Now));
                });
                HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.UpdateLucene));
                return(ResultData(null, true, "文章发表成功!"));
            }
            return(ResultData(null, false, "文章发表失败!"));
        }
示例#16
0
        public ActionResult Edit(PostInputDto post, string Seminars, bool notify = true)
        {
            post.Content = ReplaceImgSrc(Regex.Replace(post.Content.Trim(), @"<img\s+[^>]*\s*src\s*=\s*['""]?(\S+\.\w{3,4})['""]?[^/>]*/>", "<img src=\"$1\"/>")).Replace("/thumb150/", "/large/");
            if (!CategoryBll.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.ModifyDate = DateTime.Now;
            Post p       = PostBll.GetById(post.Id);
            var  history = p.Mapper <PostHistoryVersion>();

            p.PostHistoryVersion.Add(history);
            Mapper.Map(post, p);
            if (!string.IsNullOrEmpty(Seminars))
            {
                var tmp = Seminars.Split(',').Distinct();
                p.Seminar.Clear();
                tmp.ForEach(s =>
                {
                    p.Seminar.Add(SeminarBll.GetFirstEntity(e => e.Title.Equals(s)));
                });
            }

            bool b = PostBll.UpdateEntitySaved(p);

            if (b)
            {
#if !DEBUG
                if (notify)
                {
                    var    cast = BroadcastBll.LoadEntities(c => c.Status == Status.Subscribed).ToList();
                    string link = Request.Url?.Scheme + "://" + Request.Url?.Authority + "/" + p.Id;
                    cast.ForEach(c =>
                    {
                        var ts         = DateTime.Now.GetTotalMilliseconds();
                        string content = System.IO.File.ReadAllText(Request.MapPath("/template/broadcast.html")).Replace("{{link}}", link + "?email=" + c.Email).Replace("{{time}}", post.PostDate.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(ConfigurationManager.AppSettings["BaiduAK"]) }, Request.Url.Scheme));
                        BackgroundJob.Schedule(() => SendMail(GetSettings("Title") + "博客有新文章发布了", content, c.Email), (p.PostDate - DateTime.Now));
                    });
                }
#endif
                HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.UpdateLucene));
                return(ResultData(p.Mapper <PostOutputDto>(), message: "文章修改成功!"));
            }
            return(ResultData(null, false, "文章修改失败!"));
        }
示例#17
0
        public async Task <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 = await _imagebedClient.ReplaceImgSrc(post.Content.HtmlSantinizerStandard().ClearImgAttributes());
            }

            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    = 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, "文章发表失败!"));
        }