PostController.cs 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  1. using AngleSharp;
  2. using CacheManager.Core;
  3. using EFCoreSecondLevelCacheInterceptor;
  4. using Hangfire;
  5. using JiebaNet.Segmenter;
  6. using Masuit.LuceneEFCore.SearchEngine.Interfaces;
  7. using Masuit.MyBlogs.Core.Common;
  8. using Masuit.MyBlogs.Core.Configs;
  9. using Masuit.MyBlogs.Core.Extensions;
  10. using Masuit.MyBlogs.Core.Extensions.Firewall;
  11. using Masuit.MyBlogs.Core.Extensions.Hangfire;
  12. using Masuit.MyBlogs.Core.Infrastructure;
  13. using Masuit.MyBlogs.Core.Infrastructure.Repository;
  14. using Masuit.MyBlogs.Core.Infrastructure.Services.Interface;
  15. using Masuit.MyBlogs.Core.Models.Command;
  16. using Masuit.MyBlogs.Core.Models.DTO;
  17. using Masuit.MyBlogs.Core.Models.Entity;
  18. using Masuit.MyBlogs.Core.Models.Enum;
  19. using Masuit.MyBlogs.Core.Models.ViewModel;
  20. using Masuit.MyBlogs.Core.Views.Post;
  21. using Masuit.Tools;
  22. using Masuit.Tools.Core.Net;
  23. using Masuit.Tools.Html;
  24. using Masuit.Tools.Linq;
  25. using Masuit.Tools.Logging;
  26. using Masuit.Tools.Security;
  27. using Masuit.Tools.Strings;
  28. using Masuit.Tools.Systems;
  29. using Microsoft.AspNetCore.Hosting;
  30. using Microsoft.AspNetCore.Http;
  31. using Microsoft.AspNetCore.Mvc;
  32. using Microsoft.EntityFrameworkCore;
  33. using Microsoft.Net.Http.Headers;
  34. using System;
  35. using System.Collections.Generic;
  36. using System.Collections.Immutable;
  37. using System.ComponentModel.DataAnnotations;
  38. using System.Linq;
  39. using System.Linq.Dynamic.Core;
  40. using System.Linq.Expressions;
  41. using System.Text.RegularExpressions;
  42. using System.Threading;
  43. using System.Threading.Tasks;
  44. using SameSiteMode = Microsoft.AspNetCore.Http.SameSiteMode;
  45. namespace Masuit.MyBlogs.Core.Controllers
  46. {
  47. /// <summary>
  48. /// 文章管理
  49. /// </summary>
  50. public class PostController : BaseController
  51. {
  52. public IPostService PostService { get; set; }
  53. public ICategoryService CategoryService { get; set; }
  54. public ISeminarService SeminarService { get; set; }
  55. public IPostHistoryVersionService PostHistoryVersionService { get; set; }
  56. public IWebHostEnvironment HostEnvironment { get; set; }
  57. public ISearchEngine<DataContext> SearchEngine { get; set; }
  58. public ImagebedClient ImagebedClient { get; set; }
  59. /// <summary>
  60. /// 文章详情页
  61. /// </summary>
  62. /// <param name="id"></param>
  63. /// <param name="kw"></param>
  64. /// <returns></returns>
  65. [Route("{id:int}"), Route("{id:int}/comments/{cid:int}"), ResponseCache(Duration = 600, VaryByHeader = "Cookie")]
  66. public async Task<ActionResult> Details(int id, string kw)
  67. {
  68. var post = await PostService.GetAsync(p => p.Id == id && (p.Status == Status.Published || CurrentUser.IsAdmin)) ?? throw new NotFoundException("文章未找到");
  69. CheckPermission(post);
  70. ViewBag.Keyword = post.Keyword + "," + post.Label;
  71. ViewBag.Desc = await post.Content.GetSummary(200);
  72. var modifyDate = post.ModifyDate;
  73. ViewBag.Next = await PostService.GetFromCacheAsync<DateTime, PostModelBase>(p => p.ModifyDate > modifyDate && (p.LimitMode ?? 0) == RegionLimitMode.All && (p.Status == Status.Published || CurrentUser.IsAdmin), p => p.ModifyDate);
  74. ViewBag.Prev = await PostService.GetFromCacheAsync<DateTime, PostModelBase>(p => p.ModifyDate < modifyDate && (p.LimitMode ?? 0) == RegionLimitMode.All && (p.Status == Status.Published || CurrentUser.IsAdmin), p => p.ModifyDate, false);
  75. if (!string.IsNullOrEmpty(kw))
  76. {
  77. ViewData["keywords"] = post.Content.Contains(kw) ? $"['{kw}']" : SearchEngine.LuceneIndexSearcher.CutKeywords(kw).ToJsonString();
  78. }
  79. ViewBag.Ads = AdsService.GetByWeightedPrice(AdvertiseType.InPage, Request.Location(), post.CategoryId);
  80. var regex = SearchEngine.LuceneIndexSearcher.CutKeywords(string.IsNullOrWhiteSpace(post.Keyword + post.Label) ? post.Title : post.Keyword + post.Label).Join("|");
  81. var related = await PostService.GetQuery(p => p.Id != id && (p.LimitMode ?? 0) == RegionLimitMode.All && Regex.IsMatch(p.Title + (p.Keyword ?? "") + (p.Label ?? ""), regex), p => p.AverageViewCount, false).Take(10).Select(p => new { p.Id, p.Title }).Cacheable().ToDictionaryAsync(p => p.Id, p => p.Title);
  82. ViewBag.Related = related;
  83. post.ModifyDate = post.ModifyDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
  84. post.PostDate = post.PostDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
  85. post.Content = ReplaceVariables(post.Content);
  86. post.ProtectContent = ReplaceVariables(post.ProtectContent);
  87. if (CurrentUser.IsAdmin)
  88. {
  89. return View("Details_Admin", post);
  90. }
  91. if (!HttpContext.Request.IsRobot() && string.IsNullOrEmpty(HttpContext.Session.Get<string>("post" + id)))
  92. {
  93. HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.RecordPostVisit), args: id);
  94. HttpContext.Session.Set("post" + id, id.ToString());
  95. }
  96. return View(post);
  97. }
  98. private void CheckPermission(Post post)
  99. {
  100. var location = Request.Location() + "|" + Request.Headers[HeaderNames.UserAgent];
  101. switch (post.LimitMode)
  102. {
  103. case RegionLimitMode.AllowRegion:
  104. if (!location.Contains(post.Regions.Split(',', StringSplitOptions.RemoveEmptyEntries)) && !CurrentUser.IsAdmin && !VisitorTokenValid && !Request.IsRobot())
  105. {
  106. Disallow(post);
  107. }
  108. break;
  109. case RegionLimitMode.ForbidRegion:
  110. if (location.Contains(post.Regions.Split(',', StringSplitOptions.RemoveEmptyEntries)) && !CurrentUser.IsAdmin && !VisitorTokenValid && !Request.IsRobot())
  111. {
  112. Disallow(post);
  113. }
  114. break;
  115. case RegionLimitMode.AllowRegionExceptForbidRegion:
  116. if (location.Contains(post.ExceptRegions.Split(',', StringSplitOptions.RemoveEmptyEntries)) && !CurrentUser.IsAdmin && !VisitorTokenValid)
  117. {
  118. Disallow(post);
  119. }
  120. goto case RegionLimitMode.AllowRegion;
  121. case RegionLimitMode.ForbidRegionExceptAllowRegion:
  122. if (location.Contains(post.ExceptRegions.Split(',', StringSplitOptions.RemoveEmptyEntries)) && !CurrentUser.IsAdmin && !VisitorTokenValid)
  123. {
  124. break;
  125. }
  126. goto case RegionLimitMode.ForbidRegion;
  127. }
  128. }
  129. private void Disallow(Post post)
  130. {
  131. RedisHelper.IncrBy("interceptCount");
  132. RedisHelper.LPush("intercept", new IpIntercepter()
  133. {
  134. IP = ClientIP,
  135. RequestUrl = $"//{Request.Host}/{post.Id}",
  136. Referer = Request.Headers[HeaderNames.Referer],
  137. Time = DateTime.Now,
  138. UserAgent = Request.Headers[HeaderNames.UserAgent],
  139. Remark = "无权限查看该文章",
  140. Address = Request.Location()
  141. });
  142. throw new NotFoundException("文章未找到");
  143. }
  144. /// <summary>
  145. /// 文章历史版本
  146. /// </summary>
  147. /// <param name="id"></param>
  148. /// <param name="page"></param>
  149. /// <param name="size"></param>
  150. /// <returns></returns>
  151. [Route("{id:int}/history"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id", "page", "size" }, VaryByHeader = "Cookie")]
  152. public async Task<ActionResult> History(int id, [Range(1, int.MaxValue, ErrorMessage = "页码必须大于0")] int page = 1, [Range(1, 50, ErrorMessage = "页大小必须在0到50之间")] int size = 20)
  153. {
  154. var post = await PostService.GetAsync(p => p.Id == id && (p.Status == Status.Published || CurrentUser.IsAdmin)) ?? throw new NotFoundException("文章未找到");
  155. CheckPermission(post);
  156. ViewBag.Primary = post;
  157. var list = await PostHistoryVersionService.GetPagesAsync(page, size, v => v.PostId == id, v => v.ModifyDate, false);
  158. foreach (var item in list.Data)
  159. {
  160. item.ModifyDate = item.ModifyDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
  161. }
  162. ViewBag.Ads = AdsService.GetByWeightedPrice(AdvertiseType.InPage, Request.Location(), post.CategoryId);
  163. return View(list);
  164. }
  165. /// <summary>
  166. /// 文章历史版本
  167. /// </summary>
  168. /// <param name="id"></param>
  169. /// <param name="hid"></param>
  170. /// <returns></returns>
  171. [Route("{id:int}/history/{hid:int}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id", "hid" }, VaryByHeader = "Cookie")]
  172. public async Task<ActionResult> HistoryVersion(int id, int hid)
  173. {
  174. var post = await PostHistoryVersionService.GetAsync(v => v.Id == hid && (v.Post.Status == Status.Published || CurrentUser.IsAdmin)) ?? throw new NotFoundException("文章未找到");
  175. CheckPermission(post.Post);
  176. post.Content = ReplaceVariables(post.Content);
  177. post.ProtectContent = ReplaceVariables(post.ProtectContent);
  178. var next = await PostHistoryVersionService.GetAsync(p => p.PostId == id && p.ModifyDate > post.ModifyDate, p => p.ModifyDate);
  179. var prev = await PostHistoryVersionService.GetAsync(p => p.PostId == id && p.ModifyDate < post.ModifyDate, p => p.ModifyDate, false);
  180. ViewBag.Next = next;
  181. ViewBag.Prev = prev;
  182. ViewBag.Ads = AdsService.GetByWeightedPrice(AdvertiseType.InPage, Request.Location(), post.CategoryId);
  183. return CurrentUser.IsAdmin ? View("HistoryVersion_Admin", post) : View(post);
  184. }
  185. /// <summary>
  186. /// 版本对比
  187. /// </summary>
  188. /// <param name="id"></param>
  189. /// <param name="v1"></param>
  190. /// <param name="v2"></param>
  191. /// <returns></returns>
  192. [Route("{id:int}/history/{v1:int}-{v2:int}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id", "v1", "v2" }, VaryByHeader = "Cookie")]
  193. public async Task<ActionResult> CompareVersion(int id, int v1, int v2)
  194. {
  195. var post = await PostService.GetAsync(p => p.Id == id && (p.Status == Status.Published || CurrentUser.IsAdmin));
  196. var main = post.Mapper<PostHistoryVersion>() ?? throw new NotFoundException("文章未找到");
  197. CheckPermission(post);
  198. var left = v1 <= 0 ? main : await PostHistoryVersionService.GetAsync(v => v.Id == v1) ?? throw new NotFoundException("文章未找到");
  199. var right = v2 <= 0 ? main : await PostHistoryVersionService.GetAsync(v => v.Id == v2) ?? throw new NotFoundException("文章未找到");
  200. main.Id = id;
  201. var diff = new HtmlDiff.HtmlDiff(right.Content, left.Content);
  202. var diffOutput = diff.Build();
  203. right.Content = ReplaceVariables(Regex.Replace(Regex.Replace(diffOutput, "<ins.+?</ins>", string.Empty), @"<\w+></\w+>", string.Empty));
  204. left.Content = ReplaceVariables(Regex.Replace(Regex.Replace(diffOutput, "<del.+?</del>", string.Empty), @"<\w+></\w+>", string.Empty));
  205. ViewBag.Ads = AdsService.GetsByWeightedPrice(2, AdvertiseType.InPage, Request.Location(), main.CategoryId);
  206. ViewBag.DisableCopy = post.DisableCopy;
  207. return View(new[] { main, left, right });
  208. }
  209. /// <summary>
  210. /// 反对
  211. /// </summary>
  212. /// <param name="id"></param>
  213. /// <returns></returns>
  214. public async Task<ActionResult> VoteDown(int id)
  215. {
  216. if (HttpContext.Session.Get("post-vote" + id) != null)
  217. {
  218. return ResultData(null, false, "您刚才已经投过票了,感谢您的参与!");
  219. }
  220. var b = await PostService.GetQuery(p => p.Id == id).UpdateFromQueryAsync(p => new Post()
  221. {
  222. VoteDownCount = p.VoteDownCount + 1
  223. }) > 0;
  224. if (b)
  225. {
  226. HttpContext.Session.Set("post-vote" + id, id.GetBytes());
  227. }
  228. return ResultData(null, b, b ? "投票成功!" : "投票失败!");
  229. }
  230. /// <summary>
  231. /// 支持
  232. /// </summary>
  233. /// <param name="id"></param>
  234. /// <returns></returns>
  235. public async Task<ActionResult> VoteUp(int id)
  236. {
  237. if (HttpContext.Session.Get("post-vote" + id) != null)
  238. {
  239. return ResultData(null, false, "您刚才已经投过票了,感谢您的参与!");
  240. }
  241. var b = await PostService.GetQuery(p => p.Id == id).UpdateFromQueryAsync(p => new Post()
  242. {
  243. VoteUpCount = p.VoteUpCount + 1
  244. }) > 0;
  245. if (b)
  246. {
  247. HttpContext.Session.Set("post-vote" + id, id.GetBytes());
  248. }
  249. return ResultData(null, b, b ? "投票成功!" : "投票失败!");
  250. }
  251. /// <summary>
  252. /// 投稿页
  253. /// </summary>
  254. /// <returns></returns>
  255. public async Task<ActionResult> Publish()
  256. {
  257. var list = await CategoryService.GetQueryFromCacheAsync(c => c.Status == Status.Available);
  258. return View(list);
  259. }
  260. /// <summary>
  261. /// 发布投稿
  262. /// </summary>
  263. /// <param name="post"></param>
  264. /// <param name="code"></param>
  265. /// <param name="cancellationToken"></param>
  266. /// <returns></returns>
  267. [HttpPost, ValidateAntiForgeryToken]
  268. public async Task<ActionResult> Publish(PostCommand post, [Required(ErrorMessage = "验证码不能为空")] string code, CancellationToken cancellationToken)
  269. {
  270. if (await RedisHelper.GetAsync("code:" + post.Email) != code)
  271. {
  272. return ResultData(null, false, "验证码错误!");
  273. }
  274. if (PostService.Any(p => p.Status == Status.Forbidden && p.Email == post.Email))
  275. {
  276. return ResultData(null, false, "由于您曾经恶意投稿,该邮箱已经被标记为黑名单,无法进行投稿,如有疑问,请联系网站管理员进行处理。");
  277. }
  278. var match = Regex.Match(post.Title + post.Author + post.Content, CommonHelper.BanRegex);
  279. if (match.Success)
  280. {
  281. LogManager.Info($"提交内容:{post.Title}/{post.Author}/{post.Content},敏感词:{match.Value}");
  282. return ResultData(null, false, "您提交的内容包含敏感词,被禁止发表,请检查您的内容后尝试重新提交!");
  283. }
  284. if (!CategoryService.Any(c => c.Id == post.CategoryId))
  285. {
  286. return ResultData(null, message: "请选择一个分类");
  287. }
  288. post.Label = string.IsNullOrEmpty(post.Label?.Trim()) ? null : post.Label.Replace(",", ",");
  289. post.Status = Status.Pending;
  290. post.Content = await ImagebedClient.ReplaceImgSrc(await post.Content.HtmlSantinizerStandard().ClearImgAttributes(), cancellationToken);
  291. Post p = post.Mapper<Post>();
  292. p.IP = ClientIP;
  293. p.Modifier = p.Author;
  294. p.ModifierEmail = p.Email;
  295. p.DisableCopy = true;
  296. p = PostService.AddEntitySaved(p);
  297. if (p == null)
  298. {
  299. return ResultData(null, false, "文章发表失败!");
  300. }
  301. await RedisHelper.ExpireAsync("code:" + p.Email, 1);
  302. var content = new Template(await System.IO.File.ReadAllTextAsync(HostEnvironment.WebRootPath + "/template/publish.html"))
  303. .Set("link", Url.Action("Details", "Post", new { id = p.Id }, Request.Scheme))
  304. .Set("time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
  305. .Set("title", p.Title).Render();
  306. BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "有访客投稿:", content, CommonHelper.SystemSettings["ReceiveEmail"], ClientIP));
  307. return ResultData(p.Mapper<PostDto>(), message: "文章发表成功,待站长审核通过以后将显示到列表中!");
  308. }
  309. /// <summary>
  310. /// 获取标签
  311. /// </summary>
  312. /// <returns></returns>
  313. [ResponseCache(Duration = 600, VaryByHeader = "Cookie")]
  314. public ActionResult GetTag()
  315. {
  316. return ResultData(PostService.GetTags().Where(p => p.Value > 1).Select(x => x.Key).OrderBy(s => s));
  317. }
  318. /// <summary>
  319. /// 标签云
  320. /// </summary>
  321. /// <returns></returns>
  322. [Route("all"), ResponseCache(Duration = 600, VaryByHeader = "Cookie")]
  323. public async Task<ActionResult> All()
  324. {
  325. ViewBag.tags = new Dictionary<string, int>(PostService.GetTags().Where(x => x.Value > 1).OrderBy(x => x.Key));
  326. ViewBag.cats = await CategoryService.GetAll(c => c.Post.Count, false).ToDictionaryAsync(c => c.Id, c => c.Name); //category
  327. ViewBag.seminars = await SeminarService.GetAll(c => c.Post.Count, false).ToDictionaryAsync(c => c.Id, c => c.Title); //seminars
  328. return View();
  329. }
  330. /// <summary>
  331. /// 检查访问密码
  332. /// </summary>
  333. /// <param name="email"></param>
  334. /// <param name="token"></param>
  335. /// <returns></returns>
  336. [HttpPost, ValidateAntiForgeryToken, AllowAccessFirewall]
  337. public ActionResult CheckViewToken(string email, string token)
  338. {
  339. if (string.IsNullOrEmpty(token))
  340. {
  341. return ResultData(null, false, "请输入访问密码!");
  342. }
  343. var s = RedisHelper.Get("token:" + email);
  344. if (token.Equals(s))
  345. {
  346. HttpContext.Session.Set("AccessViewToken", token);
  347. Response.Cookies.Append("Email", email, new CookieOptions
  348. {
  349. Expires = DateTime.Now.AddYears(1),
  350. SameSite = SameSiteMode.Lax
  351. });
  352. Response.Cookies.Append("PostAccessToken", email.MDString3(AppConfig.BaiduAK), new CookieOptions
  353. {
  354. Expires = DateTime.Now.AddYears(1),
  355. SameSite = SameSiteMode.Lax
  356. });
  357. return ResultData(null);
  358. }
  359. return ResultData(null, false, "访问密码不正确!");
  360. }
  361. /// <summary>
  362. /// 检查授权邮箱
  363. /// </summary>
  364. /// <param name="email"></param>
  365. /// <returns></returns>
  366. [HttpPost, ValidateAntiForgeryToken, AllowAccessFirewall]
  367. public ActionResult GetViewToken(string email)
  368. {
  369. if (string.IsNullOrEmpty(email) || !email.MatchEmail().isMatch)
  370. {
  371. return ResultData(null, false, "请输入正确的邮箱!");
  372. }
  373. if (RedisHelper.Exists("get:" + email))
  374. {
  375. RedisHelper.Expire("get:" + email, 120);
  376. return ResultData(null, false, "发送频率限制,请在2分钟后重新尝试发送邮件!请检查你的邮件,若未收到,请检查你的邮箱地址或邮件垃圾箱!");
  377. }
  378. if (!UserInfoService.Any(b => b.Email.Equals(email)))
  379. {
  380. return ResultData(null, false, "您目前没有权限访问这个链接,请联系站长开通访问权限!");
  381. }
  382. var token = SnowFlake.GetInstance().GetUniqueShortId(6);
  383. RedisHelper.Set("token:" + email, token, 86400);
  384. BackgroundJob.Enqueue(() => CommonHelper.SendMail(Request.Host + "博客访问验证码", $"{Request.Host}本次验证码是:<span style='color:red'>{token}</span>,有效期为24h,请按时使用!", email, ClientIP));
  385. RedisHelper.Set("get:" + email, token, 120);
  386. return ResultData(null);
  387. }
  388. /// <summary>
  389. /// 文章合并
  390. /// </summary>
  391. /// <param name="id"></param>
  392. /// <returns></returns>
  393. [HttpGet("{id}/merge")]
  394. public async Task<ActionResult> PushMerge(int id)
  395. {
  396. var post = await PostService.GetByIdAsync(id) ?? throw new NotFoundException("文章未找到");
  397. CheckPermission(post);
  398. return View(post);
  399. }
  400. /// <summary>
  401. /// 文章合并
  402. /// </summary>
  403. /// <param name="id"></param>
  404. /// <param name="mid"></param>
  405. /// <returns></returns>
  406. [HttpGet("{id}/merge/{mid}")]
  407. public async Task<ActionResult> RepushMerge(int id, int mid)
  408. {
  409. var post = await PostService.GetByIdAsync(id) ?? throw new NotFoundException("文章未找到");
  410. CheckPermission(post);
  411. var merge = post.PostMergeRequests.FirstOrDefault(p => p.Id == mid && p.MergeState != MergeStatus.Merged) ?? throw new NotFoundException("待合并文章未找到");
  412. return View(merge);
  413. }
  414. /// <summary>
  415. /// 文章合并
  416. /// </summary>
  417. /// <param name="messageService"></param>
  418. /// <param name="postMergeRequestService"></param>
  419. /// <param name="dto"></param>
  420. /// <returns></returns>
  421. [HttpPost("{id}/pushmerge")]
  422. public async Task<ActionResult> PushMerge([FromServices] IInternalMessageService messageService, [FromServices] IPostMergeRequestService postMergeRequestService, PostMergeRequestCommand dto)
  423. {
  424. if (await RedisHelper.GetAsync("code:" + dto.ModifierEmail) != dto.Code)
  425. {
  426. return ResultData(null, false, "验证码错误!");
  427. }
  428. var post = await PostService.GetByIdAsync(dto.PostId) ?? throw new NotFoundException("文章未找到");
  429. var htmlDiff = new HtmlDiff.HtmlDiff(post.Content.RemoveHtmlTag(), dto.Content.RemoveHtmlTag());
  430. var diff = htmlDiff.Build();
  431. if (post.Title.Equals(dto.Title) && !diff.Contains(new[] { "diffmod", "diffdel", "diffins" }))
  432. {
  433. return ResultData(null, false, "内容未被修改!");
  434. }
  435. #region 合并验证
  436. if (postMergeRequestService.Any(p => p.ModifierEmail == dto.ModifierEmail && p.MergeState == MergeStatus.Block))
  437. {
  438. return ResultData(null, false, "由于您曾经多次恶意修改文章,已经被标记为黑名单,无法修改任何文章,如有疑问,请联系网站管理员进行处理。");
  439. }
  440. if (post.PostMergeRequests.Any(p => p.ModifierEmail == dto.ModifierEmail && p.MergeState == MergeStatus.Pending))
  441. {
  442. return ResultData(null, false, "您已经提交过一次修改请求正在待处理,暂不能继续提交修改请求!");
  443. }
  444. #endregion
  445. #region 直接合并
  446. if (post.Email.Equals(dto.ModifierEmail))
  447. {
  448. var history = post.Mapper<PostHistoryVersion>();
  449. Mapper.Map(dto, post);
  450. post.PostHistoryVersion.Add(history);
  451. post.ModifyDate = DateTime.Now;
  452. return await PostService.SaveChangesAsync() > 0 ? ResultData(null, true, "你是文章原作者,无需审核,文章已自动更新并在首页展示!") : ResultData(null, false, "操作失败!");
  453. }
  454. #endregion
  455. var merge = post.PostMergeRequests.FirstOrDefault(r => r.Id == dto.Id && r.MergeState != MergeStatus.Merged);
  456. if (merge != null)
  457. {
  458. Mapper.Map(dto, merge);
  459. merge.SubmitTime = DateTime.Now;
  460. merge.MergeState = MergeStatus.Pending;
  461. }
  462. else
  463. {
  464. merge = Mapper.Map<PostMergeRequest>(dto);
  465. merge.SubmitTime = DateTime.Now;
  466. post.PostMergeRequests.Add(merge);
  467. }
  468. var b = await PostService.SaveChangesAsync() > 0;
  469. if (!b)
  470. {
  471. return ResultData(null, false, "操作失败!");
  472. }
  473. await RedisHelper.ExpireAsync("code:" + dto.ModifierEmail, 1);
  474. await messageService.AddEntitySavedAsync(new InternalMessage()
  475. {
  476. Title = $"来自【{dto.Modifier}】对文章《{post.Title}》的修改请求",
  477. Content = dto.Title,
  478. Link = "#/merge/compare?id=" + merge.Id
  479. });
  480. var content = new Template(await System.IO.File.ReadAllTextAsync(HostEnvironment.WebRootPath + "/template/merge-request.html"))
  481. .Set("title", post.Title)
  482. .Set("link", Url.Action("Index", "Dashboard", new { }, Request.Scheme) + "#/merge/compare?id=" + merge.Id)
  483. .Set("diff", diff)
  484. .Set("host", "//" + Request.Host)
  485. .Set("id", merge.Id.ToString())
  486. .Render();
  487. BackgroundJob.Enqueue(() => CommonHelper.SendMail("博客文章修改请求:", content, CommonHelper.SystemSettings["ReceiveEmail"], ClientIP));
  488. return ResultData(null, true, "您的修改请求已提交,已进入审核状态,感谢您的参与!");
  489. }
  490. #region 后端管理
  491. /// <summary>
  492. /// 固顶
  493. /// </summary>
  494. /// <param name="id"></param>
  495. /// <returns></returns>
  496. [MyAuthorize]
  497. public async Task<ActionResult> Fixtop(int id)
  498. {
  499. Post post = await PostService.GetByIdAsync(id) ?? throw new NotFoundException("文章未找到");
  500. post.IsFixedTop = !post.IsFixedTop;
  501. bool b = await PostService.SaveChangesAsync() > 0;
  502. return b ? ResultData(null, true, post.IsFixedTop ? "置顶成功!" : "取消置顶成功!") : ResultData(null, false, "操作失败!");
  503. }
  504. /// <summary>
  505. /// 审核
  506. /// </summary>
  507. /// <param name="id"></param>
  508. /// <returns></returns>
  509. [MyAuthorize]
  510. public async Task<ActionResult> Pass(int id)
  511. {
  512. var post = await PostService.GetByIdAsync(id) ?? throw new NotFoundException("文章未找到");
  513. post.Status = Status.Published;
  514. post.ModifyDate = DateTime.Now;
  515. post.PostDate = DateTime.Now;
  516. var b = await PostService.SaveChangesAsync() > 0;
  517. if (!b)
  518. {
  519. return ResultData(null, false, "审核失败!");
  520. }
  521. var js = new JiebaSegmenter();
  522. (post.Keyword + "," + post.Label).Split(',', StringSplitOptions.RemoveEmptyEntries).ForEach(s => js.AddWord(s));
  523. SearchEngine.LuceneIndexer.Add(post);
  524. return ResultData(null, true, "审核通过!");
  525. }
  526. /// <summary>
  527. /// 删除
  528. /// </summary>
  529. /// <param name="id"></param>
  530. /// <returns></returns>
  531. [MyAuthorize]
  532. public async Task<ActionResult> Delete(int id)
  533. {
  534. var post = await PostService.GetByIdAsync(id) ?? throw new NotFoundException("文章未找到");
  535. post.Status = Status.Deleted;
  536. bool b = await PostService.SaveChangesAsync(true) > 0;
  537. SearchEngine.LuceneIndexer.Delete(post);
  538. return ResultData(null, b, b ? "删除成功!" : "删除失败!");
  539. }
  540. /// <summary>
  541. /// 还原版本
  542. /// </summary>
  543. /// <param name="id"></param>
  544. /// <returns></returns>
  545. [MyAuthorize]
  546. public async Task<ActionResult> Restore(int id)
  547. {
  548. var post = await PostService.GetByIdAsync(id) ?? throw new NotFoundException("文章未找到");
  549. post.Status = Status.Published;
  550. bool b = await PostService.SaveChangesAsync() > 0;
  551. SearchEngine.LuceneIndexer.Add(post);
  552. return ResultData(null, b, b ? "恢复成功!" : "恢复失败!");
  553. }
  554. /// <summary>
  555. /// 彻底删除文章
  556. /// </summary>
  557. /// <param name="id"></param>
  558. /// <returns></returns>
  559. [MyAuthorize]
  560. public ActionResult Truncate(int id)
  561. {
  562. bool b = PostService - id;
  563. return ResultData(null, b, b ? "删除成功!" : "删除失败!");
  564. }
  565. /// <summary>
  566. /// 获取文章
  567. /// </summary>
  568. /// <param name="id"></param>
  569. /// <returns></returns>
  570. [MyAuthorize]
  571. public ActionResult Get(int id)
  572. {
  573. Post post = PostService[id] ?? throw new NotFoundException("文章未找到");
  574. PostDto model = post.Mapper<PostDto>();
  575. model.Seminars = post.Seminar.Select(s => s.Title).Join(",");
  576. return ResultData(model);
  577. }
  578. /// <summary>
  579. /// 获取文章分页
  580. /// </summary>
  581. /// <returns></returns>
  582. [MyAuthorize]
  583. public ActionResult GetPageData([FromServices] ICacheManager<HashSet<string>> cacheManager, [Range(1, int.MaxValue, ErrorMessage = "页数必须大于0")] int page = 1, [Range(1, int.MaxValue, ErrorMessage = "页大小必须大于0")] int size = 10, OrderBy orderby = OrderBy.ModifyDate, string kw = "", int? cid = null)
  584. {
  585. Expression<Func<Post, bool>> where = p => true;
  586. if (cid.HasValue)
  587. {
  588. where = where.And(p => p.CategoryId == cid.Value);
  589. }
  590. if (!string.IsNullOrEmpty(kw))
  591. {
  592. kw = Regex.Escape(kw);
  593. where = where.And(p => Regex.IsMatch(p.Title + p.Author + p.Email + p.Content, kw));
  594. }
  595. var list = PostService.GetQuery(where).OrderBy($"{nameof(Post.Status)} desc,{nameof(Post.IsFixedTop)} desc,{orderby.GetDisplay()} desc").ToPagedList<Post, PostDataModel>(page, size, MapperConfig);
  596. foreach (var item in list.Data)
  597. {
  598. item.ModifyDate = item.ModifyDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
  599. item.PostDate = item.PostDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
  600. item.Online = cacheManager.Get(nameof(PostOnline) + ":" + item.Id)?.Count ?? 0;
  601. }
  602. return Ok(list);
  603. }
  604. /// <summary>
  605. /// 获取未审核文章
  606. /// </summary>
  607. /// <param name="page"></param>
  608. /// <param name="size"></param>
  609. /// <param name="search"></param>
  610. /// <returns></returns>
  611. [MyAuthorize]
  612. public async Task<ActionResult> GetPending([Range(1, int.MaxValue, ErrorMessage = "页码必须大于0")] int page = 1, [Range(1, 50, ErrorMessage = "页大小必须在0到50之间")] int size = 15, string search = "")
  613. {
  614. Expression<Func<Post, bool>> where = p => p.Status == Status.Pending;
  615. if (!string.IsNullOrEmpty(search))
  616. {
  617. where = where.And(p => p.Title.Contains(search) || p.Author.Contains(search) || p.Email.Contains(search) || p.Label.Contains(search));
  618. }
  619. var pages = await PostService.GetQuery(where).OrderByDescending(p => p.IsFixedTop).ThenByDescending(p => p.ModifyDate).ToCachedPagedListAsync<Post, PostDataModel>(page, size, MapperConfig);
  620. foreach (var item in pages.Data)
  621. {
  622. item.ModifyDate = item.ModifyDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
  623. item.PostDate = item.PostDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
  624. }
  625. return Ok(pages);
  626. }
  627. /// <summary>
  628. /// 编辑
  629. /// </summary>
  630. /// <param name="post"></param>
  631. /// <param name="reserve">是否保留历史版本</param>
  632. /// <param name="cancellationToken"></param>
  633. /// <returns></returns>
  634. [HttpPost, MyAuthorize]
  635. public async Task<ActionResult> Edit(PostCommand post, bool reserve = true, CancellationToken cancellationToken = default)
  636. {
  637. post.Content = await ImagebedClient.ReplaceImgSrc(await post.Content.Trim().ClearImgAttributes(), cancellationToken);
  638. if (!ValidatePost(post, out var resultData))
  639. {
  640. return resultData;
  641. }
  642. Post p = await PostService.GetByIdAsync(post.Id);
  643. if (reserve && p.Status == Status.Published)
  644. {
  645. var context = BrowsingContext.New(Configuration.Default);
  646. var doc1 = await context.OpenAsync(req => req.Content(p.Content), cancellationToken);
  647. var doc2 = await context.OpenAsync(req => req.Content(post.Content), cancellationToken);
  648. if (doc1.Body.TextContent != doc2.Body.TextContent)
  649. {
  650. var history = p.Mapper<PostHistoryVersion>();
  651. p.PostHistoryVersion.Add(history);
  652. }
  653. p.ModifyDate = DateTime.Now;
  654. var user = HttpContext.Session.Get<UserInfoDto>(SessionKey.UserInfo);
  655. post.Modifier = string.IsNullOrEmpty(post.Modifier) ? user.NickName : post.Modifier;
  656. post.ModifierEmail = string.IsNullOrEmpty(post.ModifierEmail) ? user.Email : post.ModifierEmail;
  657. }
  658. Mapper.Map(post, p);
  659. p.IP = ClientIP;
  660. if (!string.IsNullOrEmpty(post.Seminars))
  661. {
  662. var tmp = post.Seminars.Split(',').Distinct();
  663. p.Seminar.Clear();
  664. foreach (var s in tmp)
  665. {
  666. var seminar = await SeminarService.GetAsync(e => e.Title.Equals(s));
  667. if (seminar != null)
  668. {
  669. p.Seminar.Add(seminar);
  670. }
  671. }
  672. }
  673. var js = new JiebaSegmenter();
  674. (p.Keyword + "," + p.Label).Split(',', StringSplitOptions.RemoveEmptyEntries).ForEach(s => js.AddWord(s));
  675. bool b = await SearchEngine.SaveChangesAsync() > 0;
  676. if (!b)
  677. {
  678. return ResultData(null, false, "文章修改失败!");
  679. }
  680. return ResultData(p.Mapper<PostDto>(), message: "文章修改成功!");
  681. }
  682. /// <summary>
  683. /// 发布
  684. /// </summary>
  685. /// <param name="post"></param>
  686. /// <param name="timespan"></param>
  687. /// <param name="schedule"></param>
  688. /// <returns></returns>
  689. [MyAuthorize, HttpPost]
  690. public async Task<ActionResult> Write(PostCommand post, DateTime? timespan, bool schedule = false, CancellationToken cancellationToken = default)
  691. {
  692. post.Content = await ImagebedClient.ReplaceImgSrc(await post.Content.Trim().ClearImgAttributes(), cancellationToken);
  693. if (!ValidatePost(post, out var resultData))
  694. {
  695. return resultData;
  696. }
  697. post.Status = Status.Published;
  698. Post p = post.Mapper<Post>();
  699. p.Rss = true;
  700. p.Modifier = p.Author;
  701. p.ModifierEmail = p.Email;
  702. p.IP = ClientIP;
  703. if (!string.IsNullOrEmpty(post.Seminars))
  704. {
  705. var tmp = post.Seminars.Split(',').Distinct();
  706. foreach (var s in tmp)
  707. {
  708. var id = s.ToInt32();
  709. Seminar seminar = await SeminarService.GetByIdAsync(id);
  710. p.Seminar.Add(seminar);
  711. }
  712. }
  713. if (schedule)
  714. {
  715. if (!timespan.HasValue || timespan.Value <= DateTime.Now)
  716. {
  717. return ResultData(null, false, "如果要定时发布,请选择正确的一个将来时间点!");
  718. }
  719. p.Status = Status.Schedule;
  720. p.PostDate = timespan.Value.ToUniversalTime();
  721. p.ModifyDate = timespan.Value.ToUniversalTime();
  722. HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.PublishPost), args: p);
  723. return ResultData(p.Mapper<PostDto>(), message: $"文章于{timespan.Value:yyyy-MM-dd HH:mm:ss}将会自动发表!");
  724. }
  725. PostService.AddEntity(p);
  726. var js = new JiebaSegmenter();
  727. (p.Keyword + "," + p.Label).Split(',', StringSplitOptions.RemoveEmptyEntries).ForEach(s => js.AddWord(s));
  728. bool b = await SearchEngine.SaveChangesAsync() > 0;
  729. if (!b)
  730. {
  731. return ResultData(null, false, "文章发表失败!");
  732. }
  733. return ResultData(null, true, "文章发表成功!");
  734. }
  735. private bool ValidatePost(PostCommand post, out ActionResult resultData)
  736. {
  737. if (!CategoryService.Any(c => c.Id == post.CategoryId && c.Status == Status.Available))
  738. {
  739. resultData = ResultData(null, false, "请选择一个分类");
  740. return false;
  741. }
  742. switch (post.LimitMode)
  743. {
  744. case RegionLimitMode.AllowRegion:
  745. case RegionLimitMode.ForbidRegion:
  746. if (string.IsNullOrEmpty(post.Regions))
  747. {
  748. resultData = ResultData(null, false, "请输入限制的地区");
  749. return false;
  750. }
  751. break;
  752. case RegionLimitMode.AllowRegionExceptForbidRegion:
  753. case RegionLimitMode.ForbidRegionExceptAllowRegion:
  754. if (string.IsNullOrEmpty(post.ExceptRegions))
  755. {
  756. resultData = ResultData(null, false, "请输入排除的地区");
  757. return false;
  758. }
  759. goto case RegionLimitMode.AllowRegion;
  760. }
  761. if (string.IsNullOrEmpty(post.Label?.Trim()) || post.Label.Equals("null"))
  762. {
  763. post.Label = null;
  764. }
  765. else if (post.Label.Trim().Length > 50)
  766. {
  767. post.Label = post.Label.Replace(",", ",");
  768. post.Label = post.Label.Trim().Substring(0, 50);
  769. }
  770. else
  771. {
  772. post.Label = post.Label.Replace(",", ",");
  773. }
  774. if (string.IsNullOrEmpty(post.ProtectContent?.RemoveHtmlTag()) || post.ProtectContent.Equals("null"))
  775. {
  776. post.ProtectContent = null;
  777. }
  778. resultData = null;
  779. return true;
  780. }
  781. /// <summary>
  782. /// 添加专题
  783. /// </summary>
  784. /// <param name="id"></param>
  785. /// <param name="sid"></param>
  786. /// <returns></returns>
  787. [MyAuthorize]
  788. public async Task<ActionResult> AddSeminar(int id, int sid)
  789. {
  790. var post = await PostService.GetByIdAsync(id) ?? throw new NotFoundException("文章未找到");
  791. Seminar seminar = await SeminarService.GetByIdAsync(sid) ?? throw new NotFoundException("专题未找到");
  792. post.Seminar.Add(seminar);
  793. bool b = await PostService.SaveChangesAsync() > 0;
  794. return ResultData(null, b, b ? $"已将文章【{post.Title}】添加到专题【{seminar.Title}】" : "添加失败");
  795. }
  796. /// <summary>
  797. /// 移除专题
  798. /// </summary>
  799. /// <param name="id"></param>
  800. /// <param name="sid"></param>
  801. /// <returns></returns>
  802. [MyAuthorize]
  803. public async Task<ActionResult> RemoveSeminar(int id, int sid)
  804. {
  805. var post = await PostService.GetByIdAsync(id) ?? throw new NotFoundException("文章未找到");
  806. Seminar seminar = await SeminarService.GetByIdAsync(sid) ?? throw new NotFoundException("专题未找到");
  807. post.Seminar.Remove(seminar);
  808. bool b = await PostService.SaveChangesAsync() > 0;
  809. return ResultData(null, b, b ? $"已将文章【{post.Title}】从【{seminar.Title}】专题移除" : "添加失败");
  810. }
  811. /// <summary>
  812. /// 删除历史版本
  813. /// </summary>
  814. /// <param name="id"></param>
  815. /// <returns></returns>
  816. [MyAuthorize]
  817. public async Task<ActionResult> DeleteHistory(int id)
  818. {
  819. bool b = await PostHistoryVersionService.DeleteByIdAsync(id) > 0;
  820. return ResultData(null, b, b ? "历史版本文章删除成功!" : "历史版本文章删除失败!");
  821. }
  822. /// <summary>
  823. /// 还原版本
  824. /// </summary>
  825. /// <param name="id"></param>
  826. /// <returns></returns>
  827. [MyAuthorize]
  828. public async Task<ActionResult> Revert(int id)
  829. {
  830. var history = await PostHistoryVersionService.GetByIdAsync(id) ?? throw new NotFoundException("版本不存在");
  831. history.Post.Category = history.Category;
  832. history.Post.CategoryId = history.CategoryId;
  833. history.Post.Content = history.Content;
  834. history.Post.Title = history.Title;
  835. history.Post.Label = history.Label;
  836. history.Post.ModifyDate = history.ModifyDate;
  837. history.Post.Seminar.Clear();
  838. foreach (var s in history.Seminar)
  839. {
  840. history.Post.Seminar.Add(s);
  841. }
  842. bool b = await SearchEngine.SaveChangesAsync() > 0;
  843. await PostHistoryVersionService.DeleteByIdAsync(id);
  844. return ResultData(null, b, b ? "回滚成功" : "回滚失败");
  845. }
  846. /// <summary>
  847. /// 禁用或开启文章评论
  848. /// </summary>
  849. /// <param name="id">文章id</param>
  850. /// <returns></returns>
  851. [MyAuthorize]
  852. public async Task<ActionResult> DisableComment(int id)
  853. {
  854. var post = await PostService.GetByIdAsync(id) ?? throw new NotFoundException("文章未找到");
  855. post.DisableComment = !post.DisableComment;
  856. return ResultData(null, await PostService.SaveChangesAsync() > 0, post.DisableComment ? $"已禁用【{post.Title}】这篇文章的评论功能!" : $"已启用【{post.Title}】这篇文章的评论功能!");
  857. }
  858. /// <summary>
  859. /// 禁用或开启文章评论
  860. /// </summary>
  861. /// <param name="id">文章id</param>
  862. /// <returns></returns>
  863. [MyAuthorize]
  864. public async Task<ActionResult> DisableCopy(int id)
  865. {
  866. var post = await PostService.GetByIdAsync(id) ?? throw new NotFoundException("文章未找到");
  867. post.DisableCopy = !post.DisableCopy;
  868. return ResultData(null, await PostService.SaveChangesAsync() > 0, post.DisableCopy ? $"已开启【{post.Title}】这篇文章的防复制功能!" : $"已关闭【{post.Title}】这篇文章的防复制功能!");
  869. }
  870. /// <summary>
  871. /// 刷新文章
  872. /// </summary>
  873. /// <param name="id">文章id</param>
  874. /// <returns></returns>
  875. [MyAuthorize]
  876. public async Task<ActionResult> Refresh(int id)
  877. {
  878. await PostService.GetQuery(p => p.Id == id).UpdateFromQueryAsync(p => new Post()
  879. {
  880. ModifyDate = DateTime.Now
  881. });
  882. return RedirectToAction("Details", new { id });
  883. }
  884. /// <summary>
  885. /// 标记为恶意修改
  886. /// </summary>
  887. /// <param name="id"></param>
  888. /// <returns></returns>
  889. [MyAuthorize]
  890. [HttpPost("post/block/{id}")]
  891. public async Task<ActionResult> Block(int id)
  892. {
  893. var b = await PostService.GetQuery(p => p.Id == id).UpdateFromQueryAsync(p => new Post()
  894. {
  895. Status = Status.Forbidden
  896. }) > 0;
  897. return b ? ResultData(null, true, "操作成功!") : ResultData(null, false, "操作失败!");
  898. }
  899. /// <summary>
  900. /// 切换允许rss订阅
  901. /// </summary>
  902. /// <param name="id"></param>
  903. /// <returns></returns>
  904. [MyAuthorize]
  905. [HttpPost("post/{id}/rss-switch")]
  906. public async Task<ActionResult> RssSwitch(int id)
  907. {
  908. await PostService.GetQuery(p => p.Id == id).UpdateFromQueryAsync(p => new Post()
  909. {
  910. Rss = !p.Rss
  911. });
  912. return ResultData(null, message: "操作成功");
  913. }
  914. /// <summary>
  915. /// 文章统计
  916. /// </summary>
  917. /// <returns></returns>
  918. [MyAuthorize]
  919. public async Task<IActionResult> Statistic()
  920. {
  921. var keys = await RedisHelper.KeysAsync(nameof(PostOnline) + ":*");
  922. var sets = await keys.SelectAsync(async s => (Id: s.Split(':')[1].ToInt32(), Clients: await RedisHelper.HGetAsync<HashSet<string>>(s, "value")));
  923. var ids = sets.Where(t => t.Clients?.Count > 0).OrderByDescending(t => t.Clients.Count).Take(10).Select(t => t.Id).ToArray();
  924. var mostHots = await PostService.GetQuery<PostModelBase>(p => ids.Contains(p.Id)).ToListAsync().ContinueWith(t =>
  925. {
  926. foreach (var item in t.Result)
  927. {
  928. item.ViewCount = sets.FirstOrDefault(x => x.Id == item.Id).Clients.Count;
  929. }
  930. return t.Result.OrderByDescending(p => p.ViewCount);
  931. });
  932. var postsQuery = PostService.GetQuery(p => p.Status == Status.Published);
  933. var mostView = await postsQuery.OrderByDescending(p => p.TotalViewCount).Take(10).Select(p => new PostModelBase()
  934. {
  935. Id = p.Id,
  936. Title = p.Title,
  937. ViewCount = p.TotalViewCount
  938. }).Cacheable().ToListAsync();
  939. var mostAverage = await postsQuery.OrderByDescending(p => p.AverageViewCount).Take(10).Select(p => new PostModelBase()
  940. {
  941. Id = p.Id,
  942. Title = p.Title,
  943. ViewCount = (int)p.AverageViewCount
  944. }).Cacheable().ToListAsync();
  945. return ResultData(new
  946. {
  947. mostHots,
  948. mostView,
  949. mostAverage
  950. });
  951. }
  952. #endregion
  953. }
  954. }