public ActionResult Put(CommentInputDto comment) { Post post = PostService.GetById(comment.PostId); if (post is null) { return(ResultData(null, false, "评论失败,文章不存在!")); } UserInfoOutputDto user = HttpContext.Session.GetByRedis <UserInfoOutputDto>(SessionKey.UserInfo); comment.Content = comment.Content.Trim().Replace("<p><br></p>", string.Empty); if (comment.Content.RemoveHtml().Trim().Equals(HttpContext.Session.GetByRedis <string>("comment" + comment.PostId))) { return(ResultData(null, false, "您刚才已经在这篇文章发表过一次评论了,换一篇文章吧,或者换一下评论内容吧!")); } if (Regex.Match(comment.Content, CommonHelper.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.Headers[HeaderNames.UserAgent]; comment.IP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(); Comment com = CommentService.AddEntitySaved(comment.Mapper <Comment>()); if (com != null) { HttpContext.Session.SetByRedis("comment" + comment.PostId, comment.Content.RemoveHtml().Trim()); var emails = new List <string>(); var email = CommonHelper.SystemSettings["ReceiveEmail"]; //站长邮箱 emails.Add(email); string content = System.IO.File.ReadAllText(_hostingEnvironment.WebRootPath + "/template/notify.html").Replace("{{title}}", 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) { MessageService.AddEntitySaved(new InternalMessage() { Title = $"来自【{com.NickName}】的新文章评论", Content = com.Content, Link = Url.Action("Details", "Post", new { id = com.PostId, cid = com.Id }, Request.Scheme) + "#comment" }); } #if !DEBUG if (com.ParentId == 0) { emails.Add(PostService.GetById(com.PostId).Email); //新评论,只通知博主和楼主 foreach (var s in emails.Distinct()) { BackgroundJob.Enqueue(() => CommonHelper.SendMail(HttpUtility.UrlDecode(Request.Headers[HeaderNames.Referer]) + "|博客文章新评论:", content.Replace("{{link}}", Url.Action("Details", "Post", new { id = com.PostId, cid = com.Id }, Request.Scheme) + "#comment"), s)); } } else { //通知博主和上层所有关联的评论访客 var pid = CommentService.GetParentCommentIdByChildId(com.Id); emails = CommentService.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.Scheme) + "#comment"; foreach (var s in emails) { BackgroundJob.Enqueue(() => CommonHelper.SendMail($"{HttpUtility.UrlDecode(Request.Headers[HeaderNames.Referer])}{CommonHelper.SystemSettings["Title"]}文章评论回复:", content.Replace("{{link}}", link), s)); } } #endif return(ResultData(null, true, "评论发表成功,服务器正在后台处理中,这会有一定的延迟,稍后将显示到评论列表中")); } foreach (var s in emails.Distinct()) { BackgroundJob.Enqueue(() => CommonHelper.SendMail(HttpUtility.UrlDecode(Request.Headers[HeaderNames.Referer]) + "|博客文章新评论(待审核):", content.Replace("{{link}}", Url.Action("Details", "Post", new { id = com.PostId, cid = com.Id }, Request.Scheme) + "#comment") + "<p style='color:red;'>(待审核)</p>", s)); } return(ResultData(null, true, "评论成功,待站长审核通过以后将显示")); } return(ResultData(null, false, "评论失败")); }
protected void SetUserSession(UserInfo user, int timeout = 20) { UserInfoOutputDto dto = user.Mapper <UserInfoOutputDto>(); System.Web.HttpContext.Current.Session.Set(QuickKeys.USER_SESSION, dto, timeout); }
public ActionResult UeditorFileUploader() { UserInfoOutputDto user = HttpContext.Session.Get <UserInfoOutputDto>(SessionKey.UserInfo) ?? new UserInfoOutputDto(); Handler action = new NotSupportedHandler(HttpContext); switch (Request.Query["action"])//通用 { case "config": action = new ConfigHandler(HttpContext); break; case "uploadimage": action = new UploadHandler(HttpContext, new UploadConfig() { AllowExtensions = UeditorConfig.GetStringList("imageAllowFiles"), PathFormat = UeditorConfig.GetString("imagePathFormat"), SizeLimit = UeditorConfig.GetInt("imageMaxSize"), UploadFieldName = UeditorConfig.GetString("imageFieldName") }); break; case "uploadscrawl": action = new UploadHandler(HttpContext, new UploadConfig() { AllowExtensions = new[] { ".png" }, PathFormat = UeditorConfig.GetString("scrawlPathFormat"), SizeLimit = UeditorConfig.GetInt("scrawlMaxSize"), UploadFieldName = UeditorConfig.GetString("scrawlFieldName"), Base64 = true, Base64Filename = "scrawl.png" }); break; case "catchimage": action = new CrawlerHandler(HttpContext); break; } if (user.IsAdmin) { switch (Request.Query["action"])//管理员用 { //case "uploadvideo": // action = new UploadHandler(context, new UploadConfig() // { // AllowExtensions = UeditorConfig.GetStringList("videoAllowFiles"), // PathFormat = UeditorConfig.GetString("videoPathFormat"), // SizeLimit = UeditorConfig.GetInt("videoMaxSize"), // UploadFieldName = UeditorConfig.GetString("videoFieldName") // }); // break; case "uploadfile": action = new UploadHandler(HttpContext, new UploadConfig() { AllowExtensions = UeditorConfig.GetStringList("fileAllowFiles"), PathFormat = UeditorConfig.GetString("filePathFormat"), SizeLimit = UeditorConfig.GetInt("fileMaxSize"), UploadFieldName = UeditorConfig.GetString("fileFieldName") }); break; //case "listimage": // action = new ListFileManager(context, UeditorConfig.GetString("imageManagerListPath"), UeditorConfig.GetStringList("imageManagerAllowFiles")); // break; //case "listfile": // action = new ListFileManager(context, UeditorConfig.GetString("fileManagerListPath"), UeditorConfig.GetStringList("fileManagerAllowFiles")); // break; } } string result = action.Process(); return(Content(result, ContentType.Json)); }
/// <summary> /// 获取页面视图模型 /// </summary> /// <param name="page"></param> /// <param name="size"></param> /// <param name="orderBy"></param> /// <param name="user"></param> /// <returns></returns> private IndexPageViewModel GetIndexPageViewModel(int page, int size, OrderBy?orderBy, UserInfoOutputDto user) { var postsQuery = PostService.GetQuery <PostOutputDto>(p => (p.Status == Status.Pended || user.IsAdmin)); //准备文章的查询 var notices = NoticeService.GetPagesFromCache <DateTime, NoticeOutputDto>(1, 5, out int _, n => (n.Status == Status.Display || user.IsAdmin), n => n.ModifyDate, false).ToList(); //加载前5条公告 var cats = CategoryService.GetQueryFromCache <string, CategoryOutputDto>(c => c.Status == Status.Available, c => c.Name).ToList(); //加载分类目录 var hotSearches = RedisHelper.Get <List <KeywordsRankOutputDto> >("SearchRank:Week").Take(10).ToList(); //热词统计 Expression <Func <PostOutputDto, double> > order = p => p.TotalViewCount; switch (new Random().Next() % 3) { case 1: order = p => p.VoteUpCount; break; case 2: order = p => p.AverageViewCount; break; } var hot6Post = postsQuery.OrderByDescending(order).Skip(0).Take(5).Cacheable().ToList(); //热门文章 var newdic = new Dictionary <string, int>(); //标签云最终结果 var tagdic = postsQuery.Where(p => !string.IsNullOrEmpty(p.Label)).Select(p => p.Label).Cacheable().AsEnumerable().SelectMany(s => s.Split(',', ',')).GroupBy(s => s).ToDictionary(g => g.Key, g => 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 = postsQuery.Where(p => !p.IsFixedTop).OrderByDescending(p => p.CommentCount).Skip(size * (page - 1)).Take(size).Cacheable().ToList(); break; case OrderBy.PostDate: posts = postsQuery.Where(p => !p.IsFixedTop).OrderByDescending(p => p.PostDate).Skip(size * (page - 1)).Take(size).Cacheable().ToList(); break; case OrderBy.ViewCount: posts = postsQuery.Where(p => !p.IsFixedTop).OrderByDescending(p => p.TotalViewCount).Skip(size * (page - 1)).Take(size).Cacheable().ToList(); break; case OrderBy.VoteCount: posts = postsQuery.Where(p => !p.IsFixedTop).OrderByDescending(p => p.VoteUpCount).Skip(size * (page - 1)).Take(size).Cacheable().ToList(); break; case OrderBy.AverageViewCount: posts = postsQuery.Where(p => !p.IsFixedTop).OrderByDescending(p => p.AverageViewCount).Skip(size * (page - 1)).Take(size).Cacheable().ToList(); break; default: posts = postsQuery.Where(p => !p.IsFixedTop).OrderByDescending(p => p.ModifyDate).Skip(size * (page - 1)).Take(size).Cacheable().ToList(); break; } if (page == 1) { posts = postsQuery.Where(p => p.IsFixedTop).OrderByDescending(p => p.ModifyDate).AsEnumerable().Union(posts).ToList(); } return(new IndexPageViewModel() { Categories = cats, HotSearch = hotSearches, Notices = notices, Posts = posts, Tags = newdic, Top6Post = hot6Post, PostsQueryable = postsQuery, SidebarAds = AdsService.GetsByWeightedPrice(2, AdvertiseType.SideBar), ListAdvertisement = AdsService.GetByWeightedPrice(AdvertiseType.PostList) }); }
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, "文章发表失败!")); }
public ActionResult Put(LeaveMessageInputDto msg) { UserInfoOutputDto user = Session.GetByRedis <UserInfoOutputDto>(SessionKey.UserInfo); msg.Content = msg.Content.Trim().Replace("<p><br></p>", string.Empty); if (Regex.Match(msg.Content, ModRegex).Length <= 0) { msg.Status = Status.Pended; } if (user != null) { msg.NickName = user.NickName; msg.QQorWechat = user.QQorWechat; msg.Email = user.Email; if (user.IsAdmin) { msg.Status = Status.Pended; msg.IsMaster = true; } } msg.PostDate = DateTime.Now; msg.Content = Regex.Replace(msg.Content.HtmlSantinizerStandard().ConvertImgSrcToRelativePath(), @"<img\s+[^>]*\s*src\s*=\s*['""]?(\S+\.\w{3,4})['""]?[^/>]*/>", "<img src=\"$1\"/>"); msg.Browser = msg.Browser ?? Request.Browser.Type; msg.IP = Request.UserHostAddress; LeaveMessage msg2 = LeaveMessageBll.AddEntitySaved(msg.Mapper <LeaveMessage>()); if (msg2 != null) { var email = GetSettings("ReceiveEmail"); string content = System.IO.File.ReadAllText(Request.MapPath("/template/notify.html")).Replace("{{time}}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).Replace("{{nickname}}", msg2.NickName).Replace("{{content}}", msg2.Content); if (msg.Status == Status.Pended) { if (!msg2.IsMaster) { MessageBll.AddEntitySaved(new InternalMessage() { Title = $"来自【{msg2.NickName}】的新留言", Content = msg2.Content, Link = Url.Action("Index", "Msg", new { cid = msg2.Id }, Request.Url.Scheme) }); } #if !DEBUG if (msg.ParentId == 0) { //新评论,只通知博主 BackgroundJob.Enqueue(() => SendMail(Request.Url.Authority + "|博客新留言:", content.Replace("{{link}}", Url.Action("Index", "Msg", new { cid = msg2.Id }, Request.Url.Scheme)), email)); } else { //通知博主和上层所有关联的评论访客 var pid = LeaveMessageBll.GetParentMessageIdByChildId(msg2.Id); var emails = LeaveMessageBll.GetSelfAndAllChildrenMessagesByParentId(pid).Select(c => c.Email).Except(new List <string>() { msg2.Email }).ToList(); emails.Add(email); string link = Url.Action("Index", "Msg", new { cid = msg2.Id }, Request.Url.Scheme); BackgroundJob.Enqueue(() => SendMail($"{Request.Url.Authority}{GetSettings("Title")} 留言回复:", content.Replace("{{link}}", link), string.Join(",", emails.Distinct()))); } #endif return(ResultData(null, true, "留言发表成功,服务器正在后台处理中,这会有一定的延迟,稍后将会显示到列表中!")); } BackgroundJob.Enqueue(() => SendMail(Request.Url.Authority + "|博客新留言(待审核):", content.Replace("{{link}}", Url.Action("Index", "Msg", new { cid = msg2.Id }, Request.Url.Scheme)) + "<p style='color:red;'>(待审核)</p>", email)); return(ResultData(null, true, "留言发表成功,待站长审核通过以后将显示到列表中!")); } return(ResultData(null, false, "留言发表失败!")); }
public ActionResult Put(LeaveMessageInputDto msg) { if (Regex.Match(msg.Content, CommonHelper.BanRegex).Length > 0) { return(ResultData(null, false, "您提交的内容包含敏感词,被禁止发表,请注意改善您的言辞!")); } UserInfoOutputDto user = HttpContext.Session.Get <UserInfoOutputDto>(SessionKey.UserInfo); msg.Content = msg.Content.Trim().Replace("<p><br></p>", string.Empty); if (msg.Content.RemoveHtmlTag().Trim().Equals(HttpContext.Session.Get <string>("msg"))) { return(ResultData(null, false, "您刚才已经发表过一次留言了!")); } if (Regex.Match(msg.Content, CommonHelper.ModRegex).Length <= 0) { msg.Status = Status.Pended; } if (user != null) { msg.NickName = user.NickName; msg.QQorWechat = user.QQorWechat; msg.Email = user.Email; if (user.IsAdmin) { msg.Status = Status.Pended; msg.IsMaster = true; } } msg.PostDate = DateTime.Now; msg.Content = msg.Content.HtmlSantinizerStandard().ClearImgAttributes(); msg.Browser = msg.Browser ?? Request.Headers[HeaderNames.UserAgent]; msg.IP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(); LeaveMessage msg2 = LeaveMessageService.AddEntitySaved(msg.Mapper <LeaveMessage>()); if (msg2 != null) { HttpContext.Session.Set("msg", msg.Content.RemoveHtmlTag().Trim()); var email = CommonHelper.SystemSettings["ReceiveEmail"]; string content = System.IO.File.ReadAllText(HostingEnvironment.WebRootPath + "/template/notify.html").Replace("{{title}}", "网站留言板").Replace("{{time}}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).Replace("{{nickname}}", msg2.NickName).Replace("{{content}}", msg2.Content); if (msg.Status == Status.Pended) { if (!msg2.IsMaster) { MessageService.AddEntitySaved(new InternalMessage() { Title = $"来自【{msg2.NickName}】的新留言", Content = msg2.Content, Link = Url.Action("Index", "Msg", new { cid = msg2.Id }, Request.Scheme) }); } #if !DEBUG if (msg.ParentId == 0) { //新评论,只通知博主 BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Domain"] + "|博客新留言:", content.Replace("{{link}}", Url.Action("Index", "Msg", new { cid = msg2.Id }, Request.Scheme)), email)); } else { //通知博主和上层所有关联的评论访客 var pid = LeaveMessageService.GetParentMessageIdByChildId(msg2.Id); var emails = LeaveMessageService.GetSelfAndAllChildrenMessagesByParentId(pid).Select(c => c.Email).ToList(); emails.Add(email); string link = Url.Action("Index", "Msg", new { cid = msg2.Id }, Request.Scheme); foreach (var s in emails.Distinct().Except(new[] { msg2.Email })) { BackgroundJob.Enqueue(() => CommonHelper.SendMail($"{CommonHelper.SystemSettings["Domain"]}{CommonHelper.SystemSettings["Title"]} 留言回复:", content.Replace("{{link}}", link), s)); } } #endif return(ResultData(null, true, "留言发表成功,服务器正在后台处理中,这会有一定的延迟,稍后将会显示到列表中!")); } BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Domain"] + "|博客新留言(待审核):", content.Replace("{{link}}", Url.Action("Index", "Msg", new { cid = msg2.Id }, Request.Scheme)) + "<p style='color:red;'>(待审核)</p>", email)); return(ResultData(null, true, "留言发表成功,待站长审核通过以后将显示到列表中!")); } return(ResultData(null, false, "留言发表失败!")); }
/// <summary> /// 获取页面视图模型 /// </summary> /// <param name="page"></param> /// <param name="size"></param> /// <param name="orderBy"></param> /// <param name="user"></param> /// <returns></returns> private IndexPageViewModel GetIndexPageViewModel(int page, int size, OrderBy orderBy, UserInfoOutputDto user) { IQueryable <PostOutputDto> postList = PostService.LoadEntities <PostOutputDto>(p => (p.Status == Status.Pended || user.IsAdmin)); //准备文章的查询 ViewBag.Total = postList.Count(); var notices = NoticeService.LoadPageEntitiesFromL2Cache <DateTime, NoticeOutputDto>(1, 5, out int _, n => (n.Status == Status.Display || user.IsAdmin), n => n.ModifyDate, false).ToList(); //加载前5条公告 var cats = CategoryService.LoadEntitiesFromL2Cache <string, CategoryOutputDto>(c => c.Status == Status.Available, c => c.Name).ToList(); //加载分类目录 var start = DateTime.Today.AddDays(-7); var hotSearches = SearchDetailsService.LoadEntitiesNoTracking(s => s.SearchTime > start, s => s.SearchTime, false).GroupBy(s => s.KeyWords).OrderByDescending(g => g.Count()).Take(10).Select(g => new KeywordsRankOutputDto() { KeyWords = g.FirstOrDefault().KeyWords, SearchCount = g.Count() }).Cacheable().ToList(); //热词统计 Expression <Func <PostOutputDto, double> > order = p => p.TotalViewCount; switch (new Random().Next() % 3) { case 1: order = p => p.VoteUpCount; break; case 2: order = p => p.AverageViewCount; break; } var hot6Post = postList.OrderByDescending(order).Skip(0).Take(5).Cacheable().ToList(); //热门文章 var topPostToday = PostService.LoadPageEntitiesFromL2Cache <int, SimplePostModel>(1, 10, out _, p => p.Status == Status.Pended, p => p.PostAccessRecord.Where(r => r.AccessTime > DateTime.Today).Sum(r => r.ClickCount), false).ToList(); //文章今日排行 var week = DateTime.Today.AddDays(-7); var topPostWeek = PostService.LoadPageEntitiesFromL2Cache <int, SimplePostModel>(1, 10, out _, p => p.Status == Status.Pended, p => p.PostAccessRecord.Where(r => r.AccessTime > week).Sum(r => r.ClickCount), false).ToList(); //文章周排行 var month = DateTime.Today.AddMonths(-1); var topPostMonth = PostService.LoadPageEntitiesFromL2Cache <int, SimplePostModel>(1, 10, out _, p => p.Status == Status.Pended, p => p.PostAccessRecord.Where(r => r.AccessTime > month).Sum(r => r.ClickCount), false).ToList(); //文章月排行 var tags = new List <string>(); //标签云 var tagdic = new Dictionary <string, int>(); var newdic = new Dictionary <string, int>(); //标签云最终结果 postList.Select(p => p.Label).Cacheable().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.Where(p => !p.IsFixedTop).OrderByDescending(p => p.CommentCount).Skip(size * (page - 1)).Take(size).Cacheable().ToList(); break; case OrderBy.PostDate: posts = postList.Where(p => !p.IsFixedTop).OrderByDescending(p => p.PostDate).Skip(size * (page - 1)).Take(size).Cacheable().ToList(); break; case OrderBy.ViewCount: posts = postList.Where(p => !p.IsFixedTop).OrderByDescending(p => p.TotalViewCount).Skip(size * (page - 1)).Take(size).Cacheable().ToList(); break; case OrderBy.VoteCount: posts = postList.Where(p => !p.IsFixedTop).OrderByDescending(p => p.VoteUpCount).Skip(size * (page - 1)).Take(size).Cacheable().ToList(); break; case OrderBy.AverageViewCount: posts = postList.Where(p => !p.IsFixedTop).OrderByDescending(p => p.AverageViewCount).Skip(size * (page - 1)).Take(size).Cacheable().ToList(); break; default: posts = postList.Where(p => !p.IsFixedTop).OrderByDescending(p => p.ModifyDate).Skip(size * (page - 1)).Take(size).Cacheable().ToList(); break; } if (page == 1) { posts = postList.Where(p => p.IsFixedTop).OrderByDescending(p => p.ModifyDate).AsEnumerable().Union(posts).ToList(); } return(new IndexPageViewModel() { Categories = cats, HotSearch = hotSearches, Notices = notices, Posts = posts, Tags = newdic, Top6Post = hot6Post, TopPostByMonth = topPostMonth, TopPostByWeek = topPostWeek, TopPostByToday = topPostToday, PostsQueryable = postList }); }
/// <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.PostDate, 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 = await postList.OrderByDescending(p => p.IsFixedTop).ThenByDescending(p => p.Comment.Count).Skip(size * (page - 1)).Take(size).Cacheable().ToListAsync(); break; case OrderBy.PostDate: posts = await postList.OrderByDescending(p => p.IsFixedTop).ThenByDescending(p => p.PostDate).Skip(size * (page - 1)).Take(size).Cacheable().ToListAsync(); break; case OrderBy.ViewCount: posts = await postList.OrderByDescending(p => p.IsFixedTop).ThenByDescending(p => p.ViewCount).Skip(size * (page - 1)).Take(size).Cacheable().ToListAsync(); break; case OrderBy.VoteCount: posts = await postList.OrderByDescending(p => p.IsFixedTop).ThenByDescending(p => p.VoteUpCount).Skip(size * (page - 1)).Take(size).Cacheable().ToListAsync(); break; default: posts = await postList.OrderByDescending(p => p.IsFixedTop).ThenByDescending(p => p.ModifyDate).Skip(size * (page - 1)).Take(size).Cacheable().ToListAsync(); 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 Publish(PostInputDto post) { 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(",", ","); 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 = 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, "文章发表失败!")); }
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("{{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 }, "http") + "#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 }, "http") + "#comment"), string.Join(",", emails.Distinct()))); } else { //通知博主和上层所有关联的评论访客 var pid = CommentBll.GetParentCommentIdByChildId(com.Id); emails = CommentBll.GetSelfAndAllChildrenCommentsByParentId(pid).Select(c => c.Email).ToList(); emails = emails.Distinct().Except(new List <string>() { com.Email }).ToList(); Parallel.ForEach(emails, e => { string link = Url.Action("Details", "Post", new { id = com.PostId, cid = com.Id, email = e }, "http") + "#comment"; BackgroundJob.Enqueue(() => SendMail($"{Request.Url.Authority}{GetSettings("Title")}文章评论回复:", content.Replace("{{link}}", link), e)); }); } #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 }, "http") + "#comment") + "<p style='color:red;'>(待审核)</p>", string.Join(",", emails.Distinct()))); return(ResultData(null, true, "评论成功,待站长审核通过以后将显示")); } return(ResultData(null, false, "评论失败")); }
public ActionResult Put(CommentInputDto comment) { if (Regex.Match(comment.Content, CommonHelper.BanRegex).Length > 0) { return(ResultData(null, false, "您提交的内容包含敏感词,被禁止发表,请注意改善您的言辞!")); } Post post = PostService.GetById(comment.PostId); if (post is null) { return(ResultData(null, false, "评论失败,文章不存在!")); } if (post.DisableComment) { return(ResultData(null, false, "本文已禁用评论功能,不允许任何人回复!")); } comment.Content = comment.Content.Trim().Replace("<p><br></p>", string.Empty); if (comment.Content.RemoveHtmlTag().Trim().Equals(HttpContext.Session.Get <string>("comment" + comment.PostId))) { return(ResultData(null, false, "您刚才已经在这篇文章发表过一次评论了,换一篇文章吧,或者换一下评论内容吧!")); } if (Regex.Match(comment.Content, CommonHelper.ModRegex).Length <= 0) { comment.Status = Status.Pended; } UserInfoOutputDto user = HttpContext.Session.Get <UserInfoOutputDto>(SessionKey.UserInfo); 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 = comment.Content.HtmlSantinizerStandard().ClearImgAttributes(); comment.CommentDate = DateTime.Now; comment.Browser = comment.Browser ?? Request.Headers[HeaderNames.UserAgent]; comment.IP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(); Comment com = CommentService.AddEntitySaved(comment.Mapper <Comment>()); if (com != null) { HttpContext.Session.Set("comment" + comment.PostId, comment.Content.RemoveHtmlTag().Trim()); var emails = new HashSet <string>(); var email = CommonHelper.SystemSettings["ReceiveEmail"]; //站长邮箱 emails.Add(email); string content = System.IO.File.ReadAllText(HostingEnvironment.WebRootPath + "/template/notify.html").Replace("{{title}}", 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) { MessageService.AddEntitySaved(new InternalMessage() { Title = $"来自【{com.NickName}】的新文章评论", Content = com.Content, Link = Url.Action("Details", "Post", new { id = com.PostId, cid = com.Id }, Request.Scheme) + "#comment" }); } #if !DEBUG if (com.ParentId == 0) { emails.Add(post.Email); emails.Add(post.ModifierEmail); //新评论,只通知博主和楼主 foreach (var s in emails) { BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Domain"] + "|博客文章新评论:", content.Replace("{{link}}", Url.Action("Details", "Post", new { id = com.PostId, cid = com.Id }, Request.Scheme) + "#comment"), s)); } } else { emails.Add(post.Email); emails.Add(post.ModifierEmail); //通知博主和上层所有关联的评论访客 var pid = CommentService.GetParentCommentIdByChildId(com.Id); CommentService.GetSelfAndAllChildrenCommentsByParentId(pid).Select(c => c.Email).ForEach(s => emails.Add(s)); emails.Remove(com.Email); string link = Url.Action("Details", "Post", new { id = com.PostId, cid = com.Id }, Request.Scheme) + "#comment"; foreach (var s in emails) { BackgroundJob.Enqueue(() => CommonHelper.SendMail($"{CommonHelper.SystemSettings["Domain"]}{CommonHelper.SystemSettings["Title"]}文章评论回复:", content.Replace("{{link}}", link), s)); } } #endif return(ResultData(null, true, "评论发表成功,服务器正在后台处理中,这会有一定的延迟,稍后将显示到评论列表中")); } foreach (var s in emails) { BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Domain"] + "|博客文章新评论(待审核):", content.Replace("{{link}}", Url.Action("Details", "Post", new { id = com.PostId, cid = com.Id }, Request.Scheme) + "#comment") + "<p style='color:red;'>(待审核)</p>", s)); } return(ResultData(null, true, "评论成功,待站长审核通过以后将显示")); } return(ResultData(null, false, "评论失败")); }
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; 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")); }