public ActionResult Pass(int id)
        {
            Comment comment = CommentBll.GetById(id);

            comment.Status = Status.Pended;
            Post post = PostBll.GetById(comment.PostId);
            bool b    = CommentBll.UpdateEntitySaved(comment);
            var  pid  = comment.ParentId == 0 ? comment.Id : CommentBll.GetParentCommentIdByChildId(id);

#if !DEBUG
            string content = System.IO.File.ReadAllText(Request.MapPath("/template/notify.html")).Replace("{{title}}", post.Title).Replace("{{time}}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).Replace("{{nickname}}", comment.NickName).Replace("{{content}}", comment.Content);
            var    emails  = CommentBll.GetSelfAndAllChildrenCommentsByParentId(pid).Select(c => c.Email).Distinct().Except(new List <string>()
            {
                comment.Email,
                GetSettings("ReceiveEmail")
            }).ToList();
            string link = Url.Action("Details", "Post", new
            {
                id  = comment.PostId,
                cid = pid
            }, Request.Url.Scheme) + "#comment";
            foreach (var email in emails)
            {
                BackgroundJob.Enqueue(() => SendMail($"{Request.Url.Authority}{GetSettings("Title")}文章评论回复:", content.Replace("{{link}}", link), email));
            }
#endif
            return(ResultData(null, b, b ? "审核通过!" : "审核失败!"));
        }
Esempio n. 2
0
        /// <summary>
        /// 后台评论分布视图
        /// </summary>
        /// <returns></returns>
        public ActionResult BackCommentPartial(int?pageindex, int?SelectType)
        {
            int index = SelectType ?? 0;
            List <CommentTable> list = new List <CommentTable>();

            if (index == 0)
            {
                list = CommentBll.SelectAllComment().OrderByDescending(p => p.IsTop).ToList();
            }
            else if (index == 5)
            {
                //查询违规评论
                list = CommentBll.SelectAllComment().Where(p => p.Reportingnums > 0).OrderByDescending(p => p.IsTop).OrderByDescending(p => p.Reportingnums).ToList();
            }
            else
            {
                //查询第一大类的商品评论
                list = CommentBll.SelectByTidComment(index).OrderByDescending(p => p.IsTop).ToList();
                //增加userinfo对象,防止报错
                list.ForEach(p => p.UserInfo = UserInfoBll.SelectUser(p.UserID ?? 1));
            }
            if (list != null && list.Count() > 0)
            {
                Session["plcount"] = list.Count();
            }
            else
            {
                Session["plcount"] = 0;
            }
            ViewBag.SelectType     = index;
            ViewBag.pageindex      = pageindex ?? 1;
            Session["plpagecount"] = Math.Ceiling(list.Count() / 10.0);
            Session["allpl"]       = list.Skip(((pageindex ?? 1) - 1) * 10).Take(10).ToList();
            return(PartialView("BackCommentPartial"));
        }
        public ActionResult GetPageComments(int page = 1, int size = 5, int cid = 0)
        {
            UserInfoOutputDto user = Session.GetByRedis <UserInfoOutputDto>(SessionKey.UserInfo) ?? new UserInfoOutputDto();
            int total; //总条数,用于前台分页

            if (cid != 0)
            {
                int            pid    = CommentBll.GetParentCommentIdByChildId(cid);
                List <Comment> single = CommentBll.GetSelfAndAllChildrenCommentsByParentId(pid).ToList();
                if (single.Any())
                {
                    total = 1;
                    return(ResultData(new { total, parentTotal = total, page, size, rows = single.Mapper <IList <CommentViewModel> >() }));
                }
            }
            IList <Comment> parent = CommentBll.LoadPageEntities(page, size, out total, c => c.ParentId == 0 && (c.Status == Status.Pended || user.IsAdmin), c => c.CommentDate, false).ToList();

            if (!parent.Any())
            {
                return(ResultData(null, false, "没有评论"));
            }
            var list = new List <Comment>();

            parent.ForEach(c => CommentBll.GetSelfAndAllChildrenCommentsByParentId(c.Id).ForEach(result => list.Add(result)));
            var qlist = list.Where(c => (c.Status == Status.Pended || user.IsAdmin));

            if (total > 0)
            {
                return(ResultData(new { total, parentTotal = total, page, size, rows = qlist.Mapper <IList <CommentViewModel> >() }));
            }
            return(ResultData(null, false, "没有评论"));
        }
Esempio n. 4
0
        //[HttpPost]
        public ActionResult PostComment(int id, string id2)
        {
            if (Session["userId"] == null)
            {
                throw new Exception("uiuiui");
            }
            //return new ContentResult() { Content = "Not Logged in" };

            string usernameString = Session["userId"].ToString();
            //String text = comment.comment;
            int    discriminator = int.Parse(usernameString.Split('-')[0]);
            string username      = usernameString.Split('-')[1];

            //int id = comment.video;

            CommentBll commentBll = new CommentBll();
            int        CommentId  = commentBll.CreateComment(id, usernameString, id2);
            List <MVCPAP.Models.Comment> comments = commentBll.GetCommentsByVideoId(id);

            VideoBll videoBll = new VideoBll();

            //return View("Video", videoBll.GetVideoDataById(id));
            return(new ContentResult()
            {
                Content = CommentId.ToString()
            });
        }
        private void GetCommentList(HttpContext CurrentContext)
        {
            CommentBll bll    = new CommentBll();
            int        NewsID = Convert.ToInt32(CurrentContext.Request["nid"]);

            if (NewsID == 0)
            {
                CurrentContext.Response.Write(GetJsonResult(false, "参数错误!"));
                return;
            }

            DataTable dt = bll.GetList(AppType.News, NewsID);

            StringBuilder result = new StringBuilder();
            StringWriter  sw     = new StringWriter(result);
            JsonWriter    writer = new JsonWriter(sw);

            writer.Formatting = Formatting.Indented;
            writer.WriteStartArray();
            foreach (DataRow row in dt.Rows)
            {
                writer.WriteStartObject();

                WriteJsonKeyValue(writer, "userid", row["userid"].ToString());
                WriteJsonKeyValue(writer, "content", row["content"].ToString());
                WriteJsonKeyValue(writer, "createtime", Convert.ToDateTime(row["createtime"]).ToString("yyyy-MM-dd HH:mm:ss"));

                writer.WriteEndObject();
            }
            writer.WriteEndArray();
            writer.Close();

            CurrentContext.Response.Write("(" + result.ToString() + ")");
        }
        public ActionResult GetPendingComments(int page = 1, int size = 10)
        {
            List <CommentOutputDto> list = CommentBll.LoadPageEntities <DateTime, CommentOutputDto>(page, size, out int total, c => c.Status == Status.Pending, c => c.CommentDate, false).ToList();
            var pageCount = Math.Ceiling(total * 1.0 / size).ToInt32();

            return(PageResult(list, pageCount, total));
        }
Esempio n. 7
0
        private bool IsValidComment(CommentBll gameToValidate)
        {
            var errors = new Dictionary <string, string>();

            if (gameToValidate == null)
            {
                errors.Add("", "Empty game");
            }
            else
            {
                if (gameToValidate.GameId == 0)
                {
                    errors.Add("Name", "GameId is required.");
                }
                if (string.IsNullOrEmpty(gameToValidate.Name))
                {
                    errors.Add("Name", "Name is required.");
                }
            }
            if (errors.Count != 0)
            {
                throw new ValidationException("The game is not valid");
            }

            return(true);
        }
Esempio n. 8
0
 /// <summary>
 /// 修改评论是否置顶
 /// </summary>
 /// <param name="CommentID">评论id</param>
 /// <param name="IsTop">是否置顶</param>
 /// <returns></returns>
 public JsonResult UpdateTop(string CommentID, string IsTop)
 {
     if (CommentBll.UpdateIsTop(Convert.ToInt32(CommentID), IsTop))
     {
         return(Json(1, JsonRequestBehavior.AllowGet));
     }
     return(Json(0, JsonRequestBehavior.AllowGet));
 }
 /// <summary>
 /// 评论举报
 /// </summary>
 /// <param name="CommentID">评论id</param>
 /// <returns></returns>
 public JsonResult AddReport(string CommentID)
 {
     if (CommentBll.AddReport(Convert.ToInt32(CommentID)))
     {
         return(Json(1, JsonRequestBehavior.AllowGet));
     }
     return(Json(0, JsonRequestBehavior.AllowGet));
 }
Esempio n. 10
0
 /// <summary>
 /// 管理员删除用户评论
 /// </summary>
 /// <param name="CommentID">评论id</param>
 /// <returns></returns>
 public JsonResult DelComment(string CommentID)
 {
     if (CommentBll.CommentDelAdmin(Convert.ToInt32(CommentID)))
     {
         return(Json(1, JsonRequestBehavior.AllowGet));
     }
     return(Json(0, JsonRequestBehavior.AllowGet));
 }
Esempio n. 11
0
 /// <summary>
 /// 删除评价
 /// </summary>
 /// <param name="CommentID"></param>
 /// <returns></returns>
 public JsonResult CommentDel(int CommentID)
 {
     //调用方法删除
     if (CommentBll.DeleteUserComment(CommentID))
     {
         return(Json(1, JsonRequestBehavior.AllowGet));
     }
     return(Json(0, JsonRequestBehavior.AllowGet));
 }
Esempio n. 12
0
        /// <summary>
        /// 用户提交评论
        /// </summary>
        /// <param name="OrderId">订单id</param>
        /// <param name="GoodId">商品id</param>
        /// <param name="StarRating">星级</param>
        /// <param name="Content">评论内容</param>
        /// <returns></returns>
        public JsonResult IsComment(string OrderId, string GoodId, string StarRating, string Content)
        {
            int userid = Convert.ToInt32(Session["userid"]);

            //如果都为true
            if (CommentBll.AddUserComment(userid, Convert.ToInt32(GoodId), Content, Convert.ToInt32(StarRating)) && OrderBll.IsComment(Convert.ToInt32(OrderId)))
            {
                return(Json(1, JsonRequestBehavior.AllowGet));
            }
            return(Json(0, JsonRequestBehavior.AllowGet));
        }
Esempio n. 13
0
        public ActionResult EditComment(int id, string id2)
        {
            CommentBll commentBll = new CommentBll();

            if (Session["userId"] == null)
            {
                return new ContentResult()
                       {
                           Content = "false"
                       }
            }
            ;

            Models.Comment comment = commentBll.GetCommentById(id);

            if (comment == null)
            {
                return new ContentResult()
                       {
                           Content = "false"
                       }
            }
            ;

            string usernameString = Session["userId"].ToString();

            int    discriminator = int.Parse(usernameString.Split('-')[0]);
            string username      = usernameString.Split('-')[1];

            if (comment.username != username || comment.discriminator != discriminator)
            {
                return new ContentResult()
                       {
                           Content = "false"
                       }
            }
            ;

            commentBll.EditCommentById(id, id2);

            return(new ContentResult()
            {
                Content = "true"
            });
        }
Esempio n. 14
0
        public ActionResult DeleteComment(int id)
        {
            if (Session["userId"] == null)
            {
                //return new ContentResult() { Content = "Not Logged in" };
                throw new Exception("Not loged in");
            }

            CommentBll commentBll = new CommentBll();

            //List<Models.Comment> comments = commentBll.GetCommentsByVideoId(id2);

            //Models.Comment comment = comments.Where(x => x.id == id).FirstOrDefault();

            Models.Comment comment = commentBll.GetCommentById(id);

            if (comment == null)
            {
                //return new ContentResult() { Content = "Comment not found" };
                throw new Exception("Comment does not exist");
            }

            string usernameString = Session["userId"].ToString();
            //String text = Request.QueryString.Get("text");

            int    discriminator = int.Parse(usernameString.Split('-')[0]);
            string username      = usernameString.Split('-')[1];

            if (comment.user.username != username || comment.user.discriminator != discriminator)
            {
                //return new ContentResult() { Content = "User does not has permission" };
                throw new Exception("Not your comment");
            }

            commentBll.DeleteCommentById(id);

            //comments.Remove(comment);

            return(new ContentResult()
            {
                Content = "Done"
            });
            //return PartialView("CommentSection", comments);
            //return RedirectToAction("Video", "Home", id);
        }
        public ActionResult CommentVote(int id)
        {
            Comment cm = CommentBll.GetFirstEntity(c => c.Id == id && c.Status == Status.Pended);

            if (Session["cm" + id] != null)
            {
                return(ResultData(null, false, "您刚才已经投过票了,感谢您的参与!"));
            }
            if (cm != null)
            {
                cm.VoteCount++;
                CommentBll.UpdateEntity(cm);
                Session["cm" + id] = id;
                bool b = CommentBll.SaveChanges() > 0;
                return(ResultData(null, b, b ? "投票成功" : "投票失败"));
            }
            return(ResultData(null, false, "非法操作"));
        }
Esempio n. 16
0
        public async Task UpdateAsync(CommentBll entity)
        {
            if (!IsValidComment(entity))
            {
                return;
            }

            var comment = MapperBll.Map <Comment>(entity);

            try
            {
                _commentRepository.Add(comment);
                await Database.CommitAsync();
            }
            catch (Exception ex)
            {
                throw new AccessException($"Can not add comment {entity.Name} to database", "", ex);
            }
        }
Esempio n. 17
0
        /// <summary>
        /// 后台评论界面
        /// </summary>
        /// <returns></returns>
        public ActionResult BackCommentIndex()
        {
            Session["li_1"] = 5;
            Session["li_2"] = 0;
            //查询所有评论
            List <CommentTable> list = CommentBll.SelectAllComment().OrderByDescending(p => p.IsTop).ToList();

            if (list != null && list.Count() > 0)
            {
                Session["plcount"] = list.Count();
            }
            else
            {
                Session["plcount"] = 0;
            }
            ViewBag.SelectType     = 0;
            Session["plpagecount"] = Math.Ceiling(list.Count() / 10.0);
            Session["allpl"]       = list.Take(10).ToList();
            //商品图片
            Session["GoodsPhoto"] = GoodsPhotoBll.SelectAllGoodsPhoto();
            return(View());
        }
        public ActionResult GoodsComment(int num, int goodsid)
        {
            List <CommentTable> list = CommentBll.SelectGoodsComment(goodsid);

            //好评
            if (num == 0)
            {
                list = list.Where(p => p.CommentStarRating >= 4).ToList();
            }
            else if (num == 1)
            {
                //中评
                list = list.Where(p => p.CommentStarRating == 3).ToList();
            }
            else if (num == 2)
            {
                //差评
                list = list.Where(p => p.CommentStarRating <= 2).ToList();
            }
            ViewBag.num             = num;
            Session["GoodsComment"] = list;
            return(PartialView("GoodsComment"));
        }
        /// <summary>
        /// 商品详情
        /// </summary>
        /// <param name="goodsid">商品id</param>
        /// <returns></returns>
        public ActionResult GoodsDesc(int goodsid)
        {
            //商品图片
            ViewBag.GoodsPhoto = GoodsPhotoBll.SelectAllGoodsPhoto().Where(p => p.GoodsID == goodsid).ToList();
            //商品的所有评价(置顶排序)
            List <CommentTable> list = CommentBll.SelectGoodsComment(goodsid).OrderByDescending(p => p.IsTop).ToList();

            Session["GoodsComment"] = list;
            //用户是否收藏商品
            ViewBag.iscollection = CollectionBll.SelectOneCollection(Convert.ToInt32(Session["userid"]), goodsid);
            //加载或更新用户购物车数量
            if (Session["userid"] != null)
            {
                Session["carcount"] = ShopingCarBll.SelectAllShopCar(Convert.ToInt32(Session["userid"])).Count();
            }
            //获取到的该商品的信息
            GoodsTable good = GoodsBll.SelectGoodsIdGoods(goodsid);

            //相关商品的推荐(3条)
            ViewBag.GetGoods      = GoodsBll.SelectGetGoods(good.TID ?? 0).Where(p => p.GoodsID != good.GoodsID).OrderBy(p => Guid.NewGuid()).Take(3).ToList();
            Session["GoodsPhoto"] = GoodsPhotoBll.SelectAllGoodsPhoto();
            return(View(good));
        }
        public ActionResult Delete(int id)
        {
            var b = CommentBll.DeleteEntitiesSaved(CommentBll.GetSelfAndAllChildrenCommentsByParentId(id).ToList());

            return(ResultData(null, b, b ? "删除成功!" : "删除失败!"));
        }
Esempio n. 21
0
 public CommentController()
 {
     this._CommentBll = new CommentBll();
 }
Esempio n. 22
0
        public void AddComment(HttpContext CurrentContext, int AppCode, int TargetID, string Content, string ValidateCode)
        {
            string AppName = String.Empty;

            switch (AppCode)
            {
            case 1:
                AppName = AppType.Member;
                break;

            case 2:
                AppName = AppType.News;
                break;

            case 3:
                AppName = AppType.Order;
                break;

            case 4:
                AppName = AppType.Address;
                break;

            case 5:
                AppName = AppType.Product;
                break;

            case 6:
                AppName = AppType.MagicWorld;
                break;

            default:
                break;
            }

            if (CurrentUser == null)
            {
                CurrentContext.Response.Write(FormatResult(false, "请登录后评论!"));
                return;
            }
            if (new ValidateHelper().Validate(ValidateCode, true))
            {
                CommentBll bll = new CommentBll();


                CommentModel Comment = new CommentModel();

                Comment.CommentID  = CommDataHelper.GetNewSerialNum(AppName);
                Comment.AppType    = AppName;
                Comment.Content    = StringUtility.RemoveHtmlTags(Content);
                Comment.CreateTime = DateTime.Now;
                Comment.TargetID   = TargetID;
                Comment.UserID     = GetUserID();

                bll.Add(Comment);

                CurrentContext.Response.Write(FormatResult(true, "添加成功"));
            }
            else
            {
                CurrentContext.Response.Write(FormatResult(false, "添加失败,验证码错误"));
            }
        }
Esempio n. 23
0
 /// <summary>
 /// 我的评价分布视图
 /// </summary>
 /// <returns></returns>
 public ActionResult MyComment()
 {
     return(PartialView("MyComment", CommentBll.SelectUserComment(Convert.ToInt32(Session["userid"]))));
 }
Esempio n. 24
0
        /// <summary>
        /// 获取页面视图模型
        /// </summary>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <param name="orderBy"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        private async Task <IndexPageViewModel> GetIndexPageViewModelAsync(int page, int size, OrderBy orderBy, UserInfoOutputDto user)
        {
            IQueryable <PostOutputDto> postList = PostBll.LoadEntitiesNoTracking <PostOutputDto>(p => (p.Status == Status.Pended || user.IsAdmin));                                                                                                  //准备文章的查询
            var notices = NoticeBll.LoadPageEntitiesFromL2CacheNoTracking <DateTime, NoticeOutputDto>(1, 5, out int _, n => (n.Status == Status.Display || user.IsAdmin), n => n.ModifyDate, false).ToList();                                        //加载前5条公告
            var cats    = await CategoryBll.LoadEntitiesFromL2CacheNoTrackingAsync <string, CategoryOutputDto>(c => c.Status == Status.Available, c => c.Name).ConfigureAwait(true);                                                                 //加载分类目录

            var comments    = CommentBll.LoadPageEntitiesFromL2CacheNoTracking <DateTime, CommentOutputDto>(1, 10, out int _, c => c.Status == Status.Pended && c.Post.Status == Status.Pended || user.IsAdmin, c => c.CommentDate, false).ToList(); //加在新评论
            var start       = DateTime.Today.AddDays(-7);
            var hotSearches = await SearchDetailsBll.LoadEntitiesNoTracking(s => s.SearchTime > start, s => s.SearchTime, false).GroupBy(s => s.KeyWords.ToLower()).OrderByDescending(g => g.Count()).Take(10).Select(g => new KeywordsRankOutputDto()
            {
                KeyWords    = g.FirstOrDefault().KeyWords,
                SearchCount = g.Count()
            }).ToListAsync();                                                                                                                                                                                                                                                        //热词统计

            var hot6Post    = await(new Random().Next() % 2 == 0 ? postList.OrderByDescending(p => p.ViewCount) : postList.OrderByDescending(p => p.VoteUpCount)).Skip(0).Take(5).Cacheable().ToListAsync();                                                                         //热门文章
            var topPostWeek = await PostBll.SqlQuery <SimplePostModel>("SELECT [Id],[Title] from Post WHERE Id in (SELECT top 10 PostId FROM [dbo].[PostAccessRecord] where DATEDIFF(week,AccessTime,getdate())<=1 GROUP BY PostId ORDER BY sum(ClickCount) desc)").ToListAsync();   //文章周排行

            var topPostMonth = await PostBll.SqlQuery <SimplePostModel>("SELECT [Id],[Title] from Post WHERE Id in (SELECT top 10 PostId FROM [dbo].[PostAccessRecord] where DATEDIFF(month,AccessTime,getdate())<=1 GROUP BY PostId ORDER BY sum(ClickCount) desc)").ToListAsync(); //文章月排行

            var topPostYear = await PostBll.SqlQuery <SimplePostModel>("SELECT [Id],[Title] from Post WHERE Id in (SELECT top 10 PostId FROM [dbo].[PostAccessRecord] where DATEDIFF(year,AccessTime,getdate())<=1 GROUP BY PostId ORDER BY sum(ClickCount) desc)").ToListAsync();   //文章年度排行

            var tags   = new List <string>();                                                                                                                                                                                                                                        //标签云
            var tagdic = new Dictionary <string, int>();
            var newdic = new Dictionary <string, int>();                                                                                                                                                                                                                             //标签云最终结果

            postList.Select(p => p.Label).ToList().ForEach(m =>
            {
                if (!string.IsNullOrEmpty(m))
                {
                    tags.AddRange(m.Split(',', ','));
                }
            });//统计标签
            tags.GroupBy(s => s).ForEach(g =>
            {
                tagdic.Add(g.Key, g.Count());
            });  //将标签分组
            if (tagdic.Any())
            {
                int min = tagdic.Values.Min();
                tagdic.ForEach(kv =>
                {
                    var fontsize = (int)Math.Floor(kv.Value * 1.0 / (min * 1.0) + 12.0);
                    newdic.Add(kv.Key, fontsize >= 36 ? 36 : fontsize);
                });
            }
            IList <PostOutputDto> posts;

            switch (orderBy)//文章排序
            {
            case OrderBy.CommentCount:
                posts = postList.OrderByDescending(p => p.IsFixedTop).ThenByDescending(p => p.Comment.Count).Skip(size * (page - 1)).Take(size).ToList();
                break;

            case OrderBy.PostDate:
                posts = postList.OrderByDescending(p => p.IsFixedTop).ThenByDescending(p => p.PostDate).Skip(size * (page - 1)).Take(size).ToList();
                break;

            case OrderBy.ViewCount:
                posts = postList.OrderByDescending(p => p.IsFixedTop).ThenByDescending(p => p.ViewCount).Skip(size * (page - 1)).Take(size).ToList();
                break;

            case OrderBy.VoteCount:
                posts = postList.OrderByDescending(p => p.IsFixedTop).ThenByDescending(p => p.VoteUpCount).Skip(size * (page - 1)).Take(size).ToList();
                break;

            default:
                posts = postList.OrderByDescending(p => p.IsFixedTop).ThenByDescending(p => p.ModifyDate).Skip(size * (page - 1)).Take(size).ToList();
                break;
            }
            return(new IndexPageViewModel()
            {
                Categories = cats.ToList(),
                Comments = comments,
                HotSearch = hotSearches,
                Notices = notices,
                Posts = posts,
                Tags = newdic,
                Top6Post = hot6Post,
                TopPostByMonth = topPostMonth,
                TopPostByWeek = topPostWeek,
                TopPostByYear = topPostYear,
                PostsQueryable = postList
            });
        }
        public ActionResult Details(int id, string kw)
        {
            List <string> list = new List <string>();

            if (!string.IsNullOrEmpty(kw))
            {
                list = LuceneHelper.CutKeywords(kw);
                if (Regex.Match(kw, BanRegex).Length > 0 || Regex.Match(kw, ModRegex).Length > 0)
                {
                    ViewBag.Keyword = "";
                    return(RedirectToAction("Details", "Post", new { id }));
                }
            }
            Post post = PostBll.GetById(id);

            if (post != null)
            {
                ViewBag.Keyword = post.Keyword + "," + post.Label;
                string email = Request["email"];
                if (!string.IsNullOrEmpty(email))
                {
                    ViewBag.Email = email;
                    var com = CommentBll.GetFirstEntityFromL2CacheNoTracking(c => c.Email.Equals(email));
                    if (com != null)
                    {
                        ViewBag.NickName   = com.NickName;
                        ViewBag.QQorWechat = com.QQorWechat;
                    }
                }
                UserInfoOutputDto user       = Session.GetByRedis <UserInfoOutputDto>(SessionKey.UserInfo) ?? new UserInfoOutputDto();
                DateTime          modifyDate = post.ModifyDate;
                ViewBag.Next = PostBll.GetFirstEntityFromL2CacheNoTracking(p => p.ModifyDate > modifyDate && (p.Status == Status.Pended || user.IsAdmin), p => p.ModifyDate);
                ViewBag.Prev = PostBll.GetFirstEntityFromL2CacheNoTracking(p => p.ModifyDate < modifyDate && (p.Status == Status.Pended || user.IsAdmin), p => p.ModifyDate, false);
                if (user.IsAdmin)
                {
                    return(View("Details_Admin", post));
                }
                if (post.Status != Status.Pended)
                {
                    return(RedirectToAction("Post", "Home"));
                }
                if (string.IsNullOrEmpty(Session.GetByRedis <string>("post" + id)))
                {
                    //post.ViewCount++;
                    var record = post.PostAccessRecord.FirstOrDefault(r => r.AccessTime == DateTime.Today);
                    if (record != null)
                    {
                        record.ClickCount += 1;
                    }
                    else
                    {
                        post.PostAccessRecord.Add(new PostAccessRecord
                        {
                            ClickCount = 1,
                            AccessTime = DateTime.Today
                        });
                    }
                    PostBll.UpdateEntitySaved(post);
                    Session.SetByRedis("post" + id, id.ToString());
                }
                foreach (var s in list)
                {
                    if (s.Contains(new[] { @"\?", @"\*", @"\+", @"\-", @"\[", @"\]", @"\{", @"\}", @"\(", @"\)", "�" }))
                    {
                        continue;
                    }
                    post.Content = Regex.IsMatch(s, @"^\p{P}.*") ? post.Content.Replace(s, $"<span style='color:red;background-color:yellow;font-size: 1.1em;font-weight:700;'>{s}</span>") : Regex.Replace(post.Content, s, $"<span style='color:red;background-color:yellow;font-size: 1.1em;font-weight:700;'>{s}</span>", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Multiline);
                }
                return(View(post));
            }
            return(RedirectToAction("Index", "Error"));
        }
Esempio n. 26
0
 /// <summary>
 /// 文章详情前10条评价
 /// </summary>
 /// <param name="articleId"></param>
 /// <returns></returns>
 public static async Task <Tuple <List <Comment>, int> > SelectCommentsTop10(int articleId) => await GetFromCacheAsync($"DetailCommentsTopNumById/{articleId}", () => CommentBll.SelectCommentsTopNum(articleId, 10), CacheTimeEnum.Short);
        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, "评论失败"));
        }
        public DataTable GetNewsComments(int NewsID)
        {
            CommentBll bll = new CommentBll();

            return(bll.GetList(AppType.News, NewsID));
        }