PostController.cs 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331
  1. using CacheManager.Core;
  2. using Hangfire;
  3. using Masuit.LuceneEFCore.SearchEngine;
  4. using Masuit.LuceneEFCore.SearchEngine.Interfaces;
  5. using Masuit.MyBlogs.Core.Common;
  6. using Masuit.MyBlogs.Core.Configs;
  7. using Masuit.MyBlogs.Core.Extensions;
  8. using Masuit.MyBlogs.Core.Extensions.Firewall;
  9. using Masuit.MyBlogs.Core.Extensions.Hangfire;
  10. using Masuit.MyBlogs.Core.Infrastructure;
  11. using Masuit.MyBlogs.Core.Infrastructure.Repository;
  12. using Masuit.MyBlogs.Core.Infrastructure.Services.Interface;
  13. using Masuit.MyBlogs.Core.Models.Command;
  14. using Masuit.MyBlogs.Core.Models.DTO;
  15. using Masuit.MyBlogs.Core.Models.Entity;
  16. using Masuit.MyBlogs.Core.Models.Enum;
  17. using Masuit.MyBlogs.Core.Models.ViewModel;
  18. using Masuit.MyBlogs.Core.Views.Post;
  19. using Masuit.Tools;
  20. using Masuit.Tools.AspNetCore.Mime;
  21. using Masuit.Tools.AspNetCore.ModelBinder;
  22. using Masuit.Tools.AspNetCore.ResumeFileResults.Extensions;
  23. using Masuit.Tools.Core.Net;
  24. using Masuit.Tools.Core.Validator;
  25. using Masuit.Tools.Excel;
  26. using Masuit.Tools.Html;
  27. using Masuit.Tools.Linq;
  28. using Masuit.Tools.Logging;
  29. using Masuit.Tools.Models;
  30. using Masuit.Tools.Security;
  31. using Masuit.Tools.Strings;
  32. using Masuit.Tools.Systems;
  33. using Microsoft.AspNetCore.Http.Extensions;
  34. using Microsoft.AspNetCore.Mvc;
  35. using Microsoft.EntityFrameworkCore;
  36. using Microsoft.Net.Http.Headers;
  37. using System.ComponentModel.DataAnnotations;
  38. using System.Linq.Dynamic.Core;
  39. using System.Linq.Expressions;
  40. using System.Net;
  41. using System.Text;
  42. using System.Text.RegularExpressions;
  43. using Z.EntityFramework.Plus;
  44. using SameSiteMode = Microsoft.AspNetCore.Http.SameSiteMode;
  45. namespace Masuit.MyBlogs.Core.Controllers;
  46. /// <summary>
  47. /// 文章管理
  48. /// </summary>
  49. public class PostController : BaseController
  50. {
  51. public IPostService PostService { get; set; }
  52. public ICategoryService CategoryService { get; set; }
  53. public ISeminarService SeminarService { get; set; }
  54. public IPostHistoryVersionService PostHistoryVersionService { get; set; }
  55. public IWebHostEnvironment HostEnvironment { get; set; }
  56. public ISearchEngine<DataContext> SearchEngine { get; set; }
  57. public ImagebedClient ImagebedClient { get; set; }
  58. public IPostVisitRecordService PostVisitRecordService { get; set; }
  59. public ICommentService CommentService { get; set; }
  60. public IPostTagService PostTagService { get; set; }
  61. /// <summary>
  62. /// 文章详情页
  63. /// </summary>
  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, int cid, string t)
  67. {
  68. var notRobot = !Request.IsRobot();
  69. if (string.IsNullOrEmpty(t) && notRobot)
  70. {
  71. return RedirectToAction("Details", cid > 0 ? new { id, kw, cid, t = SnowFlake.NewId } : new { id, kw, t = SnowFlake.NewId });
  72. }
  73. var post = await PostService.GetQuery(p => p.Id == id && (p.Status == Status.Published || CurrentUser.IsAdmin)).Include(p => p.Seminar).AsNoTracking().FirstOrDefaultAsync() ?? throw new NotFoundException("文章未找到");
  74. CheckPermission(post);
  75. if (!string.IsNullOrEmpty(post.Redirect))
  76. {
  77. if (notRobot && string.IsNullOrEmpty(HttpContext.Session.Get<string>("post" + id)))
  78. {
  79. BackgroundJob.Enqueue<IHangfireBackJob>(job => job.RecordPostVisit(id, ClientIP, Request.Headers[HeaderNames.Referer].ToString(), Request.GetDisplayUrl()));
  80. HttpContext.Session.Set("post" + id, id.ToString());
  81. }
  82. return Redirect(post.Redirect);
  83. }
  84. post.Category = CategoryService[post.CategoryId];
  85. ViewBag.CommentsCount = CommentService.Count(c => c.PostId == id && c.ParentId == null && c.Status == Status.Published);
  86. ViewBag.HistoryCount = PostHistoryVersionService.Count(c => c.PostId == id);
  87. ViewBag.Keyword = post.Keyword + "," + post.Label;
  88. if (Request.Query.ContainsKey("share"))
  89. {
  90. ViewBag.Desc = await post.Content.GetSummary(200);
  91. }
  92. else
  93. {
  94. ViewBag.Desc = "若页面无法访问,可通过搜索引擎网页快照进行浏览。" + await post.Content.GetSummary(200);
  95. }
  96. var modifyDate = post.ModifyDate;
  97. 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);
  98. 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);
  99. ViewData[nameof(post.Author)] = post.Author;
  100. ViewData[nameof(post.PostDate)] = post.PostDate;
  101. ViewData[nameof(post.ModifyDate)] = post.ModifyDate;
  102. ViewData["cover"] = post.Content.MatchFirstImgSrc();
  103. if (!string.IsNullOrEmpty(kw))
  104. {
  105. await PostService.Highlight(post, kw);
  106. }
  107. var regex = SearchEngine.LuceneIndexSearcher.CutKeywords(string.IsNullOrWhiteSpace(post.Keyword + post.Label) ? post.Title : post.Keyword + post.Label).Select(Regex.Escape).Join("|");
  108. ViewBag.Ads = AdsService.GetByWeightedPrice(AdvertiseType.InPage, Request.Location(), post.CategoryId, regex);
  109. var related = PostService.GetQuery(PostBaseWhere().And(p => p.Id != id && Regex.IsMatch(p.Title + (p.Keyword ?? "") + (p.Label ?? ""), regex, RegexOptions.IgnoreCase)), p => p.AverageViewCount, false).Take(10).Select(p => new { p.Id, p.Title }).FromCache().ToDictionary(p => p.Id, p => p.Title);
  110. ViewBag.Related = related;
  111. post.ModifyDate = post.ModifyDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
  112. post.PostDate = post.PostDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
  113. post.Content = await ReplaceVariables(post.Content).Next(s => notRobot ? s.InjectFingerprint() : Task.FromResult(s));
  114. post.ProtectContent = await ReplaceVariables(post.ProtectContent).Next(s => notRobot ? s.InjectFingerprint() : Task.FromResult(s));
  115. if (CurrentUser.IsAdmin)
  116. {
  117. return View("Details_Admin", post);
  118. }
  119. if (notRobot && string.IsNullOrEmpty(HttpContext.Session.Get<string>("post" + id)))
  120. {
  121. BackgroundJob.Enqueue<IHangfireBackJob>(job => job.RecordPostVisit(id, ClientIP, Request.Headers[HeaderNames.Referer].ToString(), Request.GetDisplayUrl()));
  122. HttpContext.Session.Set("post" + id, id.ToString());
  123. }
  124. if (post.LimitMode == RegionLimitMode.OnlyForSearchEngine)
  125. {
  126. BackgroundJob.Enqueue<IHangfireBackJob>(job => job.RecordPostVisit(id, ClientIP, Request.Headers[HeaderNames.Referer].ToString(), Request.GetDisplayUrl()));
  127. }
  128. return View(post);
  129. }
  130. /// <summary>
  131. /// 文章历史版本
  132. /// </summary>
  133. /// <param name="id"></param>
  134. /// <param name="page"></param>
  135. /// <param name="size"></param>
  136. /// <returns></returns>
  137. [Route("{id:int}/history"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id", "page", "size" }, VaryByHeader = "Cookie")]
  138. 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)
  139. {
  140. var post = await PostService.GetAsync(p => p.Id == id && (p.Status == Status.Published || CurrentUser.IsAdmin)) ?? throw new NotFoundException("文章未找到");
  141. CheckPermission(post);
  142. ViewBag.Primary = post;
  143. var list = await PostHistoryVersionService.GetPagesAsync(page, size, v => v.PostId == id, v => v.ModifyDate, false);
  144. foreach (var item in list.Data)
  145. {
  146. item.ModifyDate = item.ModifyDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
  147. }
  148. ViewBag.Ads = AdsService.GetByWeightedPrice(AdvertiseType.InPage, Request.Location(), post.CategoryId, post.Keyword + "," + post.Label);
  149. return View(list);
  150. }
  151. /// <summary>
  152. /// 文章历史版本
  153. /// </summary>
  154. /// <param name="id"></param>
  155. /// <param name="hid"></param>
  156. /// <returns></returns>
  157. [Route("{id:int}/history/{hid:int}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id", "hid" }, VaryByHeader = "Cookie")]
  158. public async Task<ActionResult> HistoryVersion(int id, int hid)
  159. {
  160. var history = await PostHistoryVersionService.GetAsync(v => v.Id == hid && (v.Post.Status == Status.Published || CurrentUser.IsAdmin)) ?? throw new NotFoundException("文章未找到");
  161. CheckPermission(history.Post);
  162. history.Content = await ReplaceVariables(history.Content).Next(s => Request.IsRobot() ? Task.FromResult(s) : s.InjectFingerprint());
  163. history.ProtectContent = await ReplaceVariables(history.ProtectContent).Next(s => Request.IsRobot() ? Task.FromResult(s) : s.InjectFingerprint());
  164. history.ModifyDate = history.ModifyDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
  165. var next = await PostHistoryVersionService.GetAsync(p => p.PostId == id && p.ModifyDate > history.ModifyDate, p => p.ModifyDate);
  166. var prev = await PostHistoryVersionService.GetAsync(p => p.PostId == id && p.ModifyDate < history.ModifyDate, p => p.ModifyDate, false);
  167. ViewBag.Next = next;
  168. ViewBag.Prev = prev;
  169. ViewBag.Ads = AdsService.GetByWeightedPrice(AdvertiseType.InPage, Request.Location(), history.CategoryId, history.Label);
  170. ViewData[nameof(history.Post.Author)] = history.Post.Author;
  171. ViewData[nameof(history.Post.PostDate)] = history.Post.PostDate;
  172. ViewData[nameof(history.ModifyDate)] = history.ModifyDate;
  173. ViewData["cover"] = history.Content.MatchFirstImgSrc();
  174. return CurrentUser.IsAdmin ? View("HistoryVersion_Admin", history) : View(history);
  175. }
  176. /// <summary>
  177. /// 版本对比
  178. /// </summary>
  179. /// <param name="id"></param>
  180. /// <param name="v1"></param>
  181. /// <param name="v2"></param>
  182. /// <returns></returns>
  183. [Route("{id:int}/history/{v1:int}-{v2:int}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id", "v1", "v2" }, VaryByHeader = "Cookie")]
  184. public async Task<ActionResult> CompareVersion(int id, int v1, int v2)
  185. {
  186. var post = await PostService.GetAsync(p => p.Id == id && (p.Status == Status.Published || CurrentUser.IsAdmin));
  187. var main = post.Mapper<PostHistoryVersion>() ?? throw new NotFoundException("文章未找到");
  188. CheckPermission(post);
  189. var left = v1 <= 0 ? main : await PostHistoryVersionService.GetAsync(v => v.Id == v1) ?? throw new NotFoundException("文章未找到");
  190. var right = v2 <= 0 ? main : await PostHistoryVersionService.GetAsync(v => v.Id == v2) ?? throw new NotFoundException("文章未找到");
  191. main.Id = id;
  192. var diff = new HtmlDiff.HtmlDiff(right.Content, left.Content);
  193. var diffOutput = diff.Build();
  194. right.Content = await ReplaceVariables(Regex.Replace(Regex.Replace(diffOutput, "<ins.+?</ins>", string.Empty), @"<\w+></\w+>", string.Empty)).Next(s => Request.IsRobot() ? Task.FromResult(s) : s.InjectFingerprint());
  195. right.ModifyDate = right.ModifyDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
  196. left.Content = await ReplaceVariables(Regex.Replace(Regex.Replace(diffOutput, "<del.+?</del>", string.Empty), @"<\w+></\w+>", string.Empty)).Next(s => Request.IsRobot() ? Task.FromResult(s) : s.InjectFingerprint());
  197. left.ModifyDate = left.ModifyDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
  198. ViewBag.Ads = AdsService.GetsByWeightedPrice(2, AdvertiseType.InPage, Request.Location(), main.CategoryId, main.Label);
  199. ViewBag.DisableCopy = post.DisableCopy;
  200. return View(new[] { main, left, right });
  201. }
  202. /// <summary>
  203. /// 反对
  204. /// </summary>
  205. /// <param name="id"></param>
  206. /// <returns></returns>
  207. public async Task<ActionResult> VoteDown(int id)
  208. {
  209. if (HttpContext.Session.Get("post-vote" + id) != null)
  210. {
  211. return ResultData(null, false, "您刚才已经投过票了,感谢您的参与!");
  212. }
  213. var b = await PostService.GetQuery(p => p.Id == id).ExecuteUpdateAsync(s => s.SetProperty(m => m.VoteDownCount, m => m.VoteDownCount + 1)) > 0;
  214. if (b)
  215. {
  216. HttpContext.Session.Set("post-vote" + id, id.GetBytes());
  217. }
  218. return ResultData(null, b, b ? "投票成功!" : "投票失败!");
  219. }
  220. /// <summary>
  221. /// 支持
  222. /// </summary>
  223. /// <param name="id"></param>
  224. /// <returns></returns>
  225. public async Task<ActionResult> VoteUp(int id)
  226. {
  227. if (HttpContext.Session.Get("post-vote" + id) != null)
  228. {
  229. return ResultData(null, false, "您刚才已经投过票了,感谢您的参与!");
  230. }
  231. var b = await PostService.GetQuery(p => p.Id == id).ExecuteUpdateAsync(s => s.SetProperty(m => m.VoteUpCount, m => m.VoteUpCount + 1)) > 0;
  232. if (b)
  233. {
  234. HttpContext.Session.Set("post-vote" + id, id.GetBytes());
  235. }
  236. return ResultData(null, b, b ? "投票成功!" : "投票失败!");
  237. }
  238. /// <summary>
  239. /// 投稿页
  240. /// </summary>
  241. /// <returns></returns>
  242. public ActionResult Publish()
  243. {
  244. return View();
  245. }
  246. /// <summary>
  247. /// 发布投稿
  248. /// </summary>
  249. /// <param name="post"></param>
  250. /// <param name="code"></param>
  251. /// <param name="cancellationToken"></param>
  252. /// <returns></returns>
  253. [HttpPost, ValidateAntiForgeryToken]
  254. public async Task<ActionResult> Publish(PostCommand post, [Required(ErrorMessage = "验证码不能为空")] string code, CancellationToken cancellationToken)
  255. {
  256. if (RedisHelper.Get("code:" + post.Email) != code)
  257. {
  258. return ResultData(null, false, "验证码错误!");
  259. }
  260. if (PostService.Any(p => p.Status == Status.Forbidden && p.Email == post.Email))
  261. {
  262. return ResultData(null, false, "由于您曾经恶意投稿,该邮箱已经被标记为黑名单,无法进行投稿,如有疑问,请联系网站管理员进行处理。");
  263. }
  264. var match = Regex.Match(post.Title + post.Author + post.Content, CommonHelper.BanRegex);
  265. if (match.Success)
  266. {
  267. LogManager.Info($"提交内容:{post.Title}/{post.Author}/{post.Content},敏感词:{match.Value}");
  268. return ResultData(null, false, "您提交的内容包含敏感词,被禁止发表,请检查您的内容后尝试重新提交!");
  269. }
  270. if (!CategoryService.Any(c => c.Id == post.CategoryId))
  271. {
  272. return ResultData(null, message: "请选择一个分类");
  273. }
  274. post.Label = string.IsNullOrEmpty(post.Label?.Trim()) ? null : post.Label.Replace(",", ",");
  275. post.Status = Status.Pending;
  276. post.Content = await ImagebedClient.ReplaceImgSrc(await post.Content.HtmlSantinizerStandard().ClearImgAttributes(), cancellationToken);
  277. Post p = post.Mapper<Post>();
  278. p.IP = ClientIP;
  279. p.Modifier = p.Author;
  280. p.ModifierEmail = p.Email;
  281. p.DisableCopy = true;
  282. p.Rss = true;
  283. PostTagService.AddOrUpdate(t => t.Name, p.Label.AsNotNull().Split(',', StringSplitOptions.RemoveEmptyEntries).Select(s => new PostTag()
  284. {
  285. Name = s,
  286. Count = PostService.Count(t => t.Label.Contains(s))
  287. }));
  288. p = PostService.AddEntitySaved(p);
  289. if (p == null)
  290. {
  291. return ResultData(null, false, "文章发表失败!");
  292. }
  293. RedisHelper.Expire("code:" + p.Email, 1);
  294. var content = new Template(await new FileInfo(HostEnvironment.WebRootPath + "/template/publish.html").ShareReadWrite().ReadAllTextAsync(Encoding.UTF8))
  295. .Set("link", Url.Action("Details", "Post", new { id = p.Id }, Request.Scheme))
  296. .Set("time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
  297. .Set("title", p.Title).Render();
  298. BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "有访客投稿:", content, CommonHelper.SystemSettings["ReceiveEmail"], ClientIP));
  299. return ResultData(p.Mapper<PostDto>(), message: "文章发表成功,待站长审核通过以后将显示到列表中!");
  300. }
  301. /// <summary>
  302. /// 获取标签
  303. /// </summary>
  304. /// <returns></returns>
  305. [ResponseCache(Duration = 600, VaryByHeader = "Cookie")]
  306. public ActionResult GetTag()
  307. {
  308. return ResultData(PostService.GetTags().Select(x => x.Key).OrderBy(s => s));
  309. }
  310. /// <summary>
  311. /// 标签云
  312. /// </summary>
  313. /// <returns></returns>
  314. [Route("all"), ResponseCache(Duration = 600, VaryByHeader = "Cookie")]
  315. public async Task<ActionResult> All()
  316. {
  317. ViewBag.tags = new Dictionary<string, int>(PostService.GetTags().Where(x => x.Value > 1).OrderBy(x => x.Key));
  318. ViewBag.cats = await CategoryService.GetQuery(c => c.Post.Count > 0, c => c.Post.Count, false).Include(c => c.Parent).ThenInclude(c => c.Parent).AsNoTracking().ToDictionaryAsync(c => c.Id, c => c.Path()); //category
  319. ViewBag.seminars = await SeminarService.GetAll(c => c.Post.Count, false).AsNoTracking().ToDictionaryAsync(c => c.Id, c => c.Title); //seminars
  320. return View();
  321. }
  322. /// <summary>
  323. /// 检查访问密码
  324. /// </summary>
  325. /// <param name="email"></param>
  326. /// <param name="token"></param>
  327. /// <returns></returns>
  328. [HttpPost, ValidateAntiForgeryToken, AllowAccessFirewall]
  329. public ActionResult CheckViewToken(string email, string token)
  330. {
  331. if (string.IsNullOrEmpty(token))
  332. {
  333. return ResultData(null, false, "请输入访问密码!");
  334. }
  335. var s = RedisHelper.Get("token:" + email);
  336. if (token.Equals(s))
  337. {
  338. HttpContext.Session.Set("AccessViewToken", token);
  339. Response.Cookies.Append("Email", email, new CookieOptions
  340. {
  341. Expires = DateTime.Now.AddYears(1),
  342. SameSite = SameSiteMode.Lax
  343. });
  344. Response.Cookies.Append("PostAccessToken", email.MDString3(AppConfig.BaiduAK), new CookieOptions
  345. {
  346. Expires = DateTime.Now.AddYears(1),
  347. SameSite = SameSiteMode.Lax
  348. });
  349. return ResultData(null);
  350. }
  351. return ResultData(null, false, "访问密码不正确!");
  352. }
  353. /// <summary>
  354. /// 检查授权邮箱
  355. /// </summary>
  356. /// <param name="email"></param>
  357. /// <returns></returns>
  358. [HttpPost, ValidateAntiForgeryToken, AllowAccessFirewall]
  359. public ActionResult GetViewToken(string email)
  360. {
  361. var validator = new IsEmailAttribute();
  362. if (!validator.IsValid(email))
  363. {
  364. return ResultData(null, false, validator.ErrorMessage);
  365. }
  366. if (RedisHelper.Exists("get:" + email))
  367. {
  368. RedisHelper.Expire("get:" + email, 120);
  369. return ResultData(null, false, "发送频率限制,请在2分钟后重新尝试发送邮件!请检查你的邮件,若未收到,请检查你的邮箱地址或邮件垃圾箱!");
  370. }
  371. if (!UserInfoService.Any(b => b.Email.Equals(email)))
  372. {
  373. return ResultData(null, false, "您目前没有权限访问这个链接,请联系站长开通访问权限!");
  374. }
  375. var token = SnowFlake.GetInstance().GetUniqueShortId(6);
  376. RedisHelper.Set("token:" + email, token, 86400);
  377. BackgroundJob.Enqueue(() => CommonHelper.SendMail(Request.Host + "博客访问验证码", $"{Request.Host}本次验证码是:<span style='color:red'>{token}</span>,有效期为24h,请按时使用!", email, ClientIP));
  378. RedisHelper.Set("get:" + email, token, 120);
  379. return ResultData(null);
  380. }
  381. /// <summary>
  382. /// 文章合并
  383. /// </summary>
  384. /// <param name="id"></param>
  385. /// <returns></returns>
  386. [HttpGet("{id}/merge")]
  387. public async Task<ActionResult> PushMerge(int id)
  388. {
  389. var post = await PostService.GetAsync(p => p.Id == id && p.Status == Status.Published && !p.Locked) ?? throw new NotFoundException("文章未找到");
  390. CheckPermission(post);
  391. return View(post);
  392. }
  393. /// <summary>
  394. /// 文章合并
  395. /// </summary>
  396. /// <param name="id"></param>
  397. /// <param name="mid"></param>
  398. /// <returns></returns>
  399. [HttpGet("{id}/merge/{mid}")]
  400. public async Task<ActionResult> RepushMerge(int id, int mid)
  401. {
  402. var post = await PostService.GetAsync(p => p.Id == id && p.Status == Status.Published && !p.Locked) ?? throw new NotFoundException("文章未找到");
  403. CheckPermission(post);
  404. var merge = post.PostMergeRequests.FirstOrDefault(p => p.Id == mid && p.MergeState != MergeStatus.Merged) ?? throw new NotFoundException("待合并文章未找到");
  405. return View(merge);
  406. }
  407. /// <summary>
  408. /// 文章合并
  409. /// </summary>
  410. /// <param name="messageService"></param>
  411. /// <param name="postMergeRequestService"></param>
  412. /// <param name="dto"></param>
  413. /// <returns></returns>
  414. [HttpPost("{id}/pushmerge")]
  415. public async Task<ActionResult> PushMerge([FromServices] IInternalMessageService messageService, [FromServices] IPostMergeRequestService postMergeRequestService, PostMergeRequestCommand dto)
  416. {
  417. if (RedisHelper.Get("code:" + dto.ModifierEmail) != dto.Code)
  418. {
  419. return ResultData(null, false, "验证码错误!");
  420. }
  421. var post = await PostService.GetAsync(p => p.Id == dto.PostId && p.Status == Status.Published && !p.Locked) ?? throw new NotFoundException("文章未找到");
  422. if (post.Title.Equals(dto.Title) && post.Content.HammingDistance(dto.Content) <= 1)
  423. {
  424. return ResultData(null, false, "内容未被修改或修改的内容过少(无意义修改)!");
  425. }
  426. #region 合并验证
  427. if (postMergeRequestService.Any(p => p.ModifierEmail == dto.ModifierEmail && p.MergeState == MergeStatus.Block))
  428. {
  429. return ResultData(null, false, "由于您曾经多次恶意修改文章,已经被标记为黑名单,无法修改任何文章,如有疑问,请联系网站管理员进行处理。");
  430. }
  431. if (post.PostMergeRequests.Any(p => p.ModifierEmail == dto.ModifierEmail && p.MergeState == MergeStatus.Pending))
  432. {
  433. return ResultData(null, false, "您已经提交过一次修改请求正在待处理,暂不能继续提交修改请求!");
  434. }
  435. #endregion 合并验证
  436. #region 直接合并
  437. if (post.Email.Equals(dto.ModifierEmail))
  438. {
  439. var history = post.Mapper<PostHistoryVersion>();
  440. Mapper.Map(dto, post);
  441. post.PostHistoryVersion.Add(history);
  442. post.ModifyDate = DateTime.Now;
  443. return await PostService.SaveChangesAsync() > 0 ? ResultData(null, true, "你是文章原作者,无需审核,文章已自动更新并在首页展示!") : ResultData(null, false, "操作失败!");
  444. }
  445. #endregion 直接合并
  446. var merge = post.PostMergeRequests.FirstOrDefault(r => r.Id == dto.Id && r.MergeState != MergeStatus.Merged);
  447. if (merge != null)
  448. {
  449. Mapper.Map(dto, merge);
  450. merge.SubmitTime = DateTime.Now;
  451. merge.MergeState = MergeStatus.Pending;
  452. }
  453. else
  454. {
  455. merge = Mapper.Map<PostMergeRequest>(dto);
  456. merge.SubmitTime = DateTime.Now;
  457. post.PostMergeRequests.Add(merge);
  458. }
  459. merge.IP = ClientIP;
  460. var b = await PostService.SaveChangesAsync() > 0;
  461. if (!b)
  462. {
  463. return ResultData(null, false, "操作失败!");
  464. }
  465. RedisHelper.Expire("code:" + dto.ModifierEmail, 1);
  466. await messageService.AddEntitySavedAsync(new InternalMessage()
  467. {
  468. Title = $"来自【{dto.Modifier}】对文章《{post.Title}》的修改请求",
  469. Content = dto.Title,
  470. Link = "#/merge/compare?id=" + merge.Id
  471. });
  472. var htmlDiff = new HtmlDiff.HtmlDiff(post.Content.RemoveHtmlTag(), dto.Content.RemoveHtmlTag());
  473. var diff = htmlDiff.Build();
  474. var content = new Template(await new FileInfo(HostEnvironment.WebRootPath + "/template/merge-request.html").ShareReadWrite().ReadAllTextAsync(Encoding.UTF8))
  475. .Set("title", post.Title)
  476. .Set("link", Url.Action("Index", "Dashboard", new { }, Request.Scheme) + "#/merge/compare?id=" + merge.Id)
  477. .Set("diff", diff)
  478. .Set("host", "//" + Request.Host)
  479. .Set("id", merge.Id.ToString())
  480. .Render();
  481. BackgroundJob.Enqueue(() => CommonHelper.SendMail("博客文章修改请求:", content, CommonHelper.SystemSettings["ReceiveEmail"], ClientIP));
  482. return ResultData(null, true, "您的修改请求已提交,已进入审核状态,感谢您的参与!");
  483. }
  484. #region 后端管理
  485. /// <summary>
  486. /// 固顶
  487. /// </summary>
  488. /// <param name="id"></param>
  489. /// <returns></returns>
  490. [MyAuthorize]
  491. public async Task<ActionResult> Fixtop(int id)
  492. {
  493. Post post = await PostService.GetByIdAsync(id) ?? throw new NotFoundException("文章未找到");
  494. post.IsFixedTop = !post.IsFixedTop;
  495. bool b = await PostService.SaveChangesAsync() > 0;
  496. return b ? ResultData(null, true, post.IsFixedTop ? "置顶成功!" : "取消置顶成功!") : ResultData(null, false, "操作失败!");
  497. }
  498. /// <summary>
  499. /// 审核
  500. /// </summary>
  501. /// <param name="id"></param>
  502. /// <returns></returns>
  503. [MyAuthorize]
  504. public async Task<ActionResult> Pass(int id)
  505. {
  506. var post = await PostService.GetByIdAsync(id) ?? throw new NotFoundException("文章未找到");
  507. post.Status = Status.Published;
  508. post.ModifyDate = DateTime.Now;
  509. post.PostDate = DateTime.Now;
  510. var b = await PostService.SaveChangesAsync() > 0;
  511. if (!b)
  512. {
  513. return ResultData(null, false, "审核失败!");
  514. }
  515. (post.Keyword + "," + post.Label).Split(',', StringSplitOptions.RemoveEmptyEntries).ForEach(KeywordsManager.AddWords);
  516. SearchEngine.LuceneIndexer.Add(post);
  517. return ResultData(null, true, "审核通过!");
  518. }
  519. /// <summary>
  520. /// 下架文章
  521. /// </summary>
  522. /// <param name="id"></param>
  523. /// <returns></returns>
  524. [MyAuthorize]
  525. public async Task<ActionResult> Takedown(int id)
  526. {
  527. var post = await PostService.GetByIdAsync(id) ?? throw new NotFoundException("文章未找到");
  528. post.Status = Status.Takedown;
  529. bool b = await PostService.SaveChangesAsync(true) > 0;
  530. SearchEngine.LuceneIndexer.Delete(post);
  531. return ResultData(null, b, b ? $"文章《{post.Title}》已下架!" : "下架失败!");
  532. }
  533. /// <summary>
  534. /// 还原版本
  535. /// </summary>
  536. /// <param name="id"></param>
  537. /// <returns></returns>
  538. [MyAuthorize]
  539. public async Task<ActionResult> Takeup(int id)
  540. {
  541. var post = await PostService.GetByIdAsync(id) ?? throw new NotFoundException("文章未找到");
  542. post.Status = Status.Published;
  543. bool b = await PostService.SaveChangesAsync() > 0;
  544. SearchEngine.LuceneIndexer.Add(post);
  545. return ResultData(null, b, b ? "上架成功!" : "上架失败!");
  546. }
  547. /// <summary>
  548. /// 彻底删除文章
  549. /// </summary>
  550. /// <param name="id"></param>
  551. /// <returns></returns>
  552. [MyAuthorize]
  553. public ActionResult Truncate(int id)
  554. {
  555. bool b = PostService - id;
  556. return ResultData(null, b, b ? "删除成功!" : "删除失败!");
  557. }
  558. /// <summary>
  559. /// 获取文章
  560. /// </summary>
  561. /// <param name="id"></param>
  562. /// <returns></returns>
  563. [MyAuthorize]
  564. public ActionResult Get(int id)
  565. {
  566. var post = PostService.GetQuery(e => e.Id == id).Include(e => e.Seminar).FirstOrDefault() ?? throw new NotFoundException("文章未找到");
  567. var model = post.Mapper<PostDto>();
  568. model.Seminars = post.Seminar.Select(s => s.Id).Join(",");
  569. return ResultData(model);
  570. }
  571. /// <summary>
  572. /// 获取文章分页
  573. /// </summary>
  574. /// <returns></returns>
  575. [MyAuthorize]
  576. public async Task<ActionResult> GetPageData([FromServices] ICacheManager<HashSet<string>> cacheManager, int page = 1, [Range(1, 200, ErrorMessage = "页大小必须介于{1}-{2}")] int size = 10, OrderBy orderby = OrderBy.ModifyDate, string kw = "", int? cid = null)
  577. {
  578. Expression<Func<Post, bool>> where = p => true;
  579. if (cid.HasValue)
  580. {
  581. where = where.And(p => p.CategoryId == cid.Value || p.Category.ParentId == cid.Value || p.Category.Parent.ParentId == cid.Value);
  582. }
  583. if (!string.IsNullOrEmpty(kw))
  584. {
  585. kw = Regex.Escape(kw);
  586. where = where.And(p => Regex.IsMatch(p.Title + p.Author + p.Email + p.Content, kw, RegexOptions.IgnoreCase));
  587. }
  588. var list = orderby switch
  589. {
  590. OrderBy.Trending => await PostService.GetQuery(where).OrderByDescending(p => p.Status).ThenByDescending(p => p.IsFixedTop).ThenByDescending(p => p.PostVisitRecordStats.Average(t => t.Count)).ToPagedListAsync<Post, PostDataModel>(page, size, MapperConfig),
  591. _ => await PostService.GetQuery(where).OrderBy($"{nameof(Post.Status)} desc,{nameof(Post.IsFixedTop)} desc,{orderby.GetDisplay()} desc").ToPagedListAsync<Post, PostDataModel>(page, size, MapperConfig)
  592. };
  593. foreach (var item in list.Data)
  594. {
  595. item.ModifyDate = item.ModifyDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
  596. item.PostDate = item.PostDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
  597. item.Online = cacheManager.Get(nameof(PostOnline) + ":" + item.Id)?.Count ?? 0;
  598. }
  599. return Ok(list);
  600. }
  601. /// <summary>
  602. /// 获取未审核文章
  603. /// </summary>
  604. /// <param name="page"></param>
  605. /// <param name="size"></param>
  606. /// <param name="search"></param>
  607. /// <returns></returns>
  608. [MyAuthorize]
  609. 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 = "")
  610. {
  611. Expression<Func<Post, bool>> where = p => p.Status == Status.Pending;
  612. if (!string.IsNullOrEmpty(search))
  613. {
  614. where = where.And(p => p.Title.Contains(search) || p.Author.Contains(search) || p.Email.Contains(search) || p.Label.Contains(search));
  615. }
  616. var pages = await PostService.GetQuery(where).OrderByDescending(p => p.IsFixedTop).ThenByDescending(p => p.ModifyDate).ToPagedListAsync<Post, PostDataModel>(page, size, MapperConfig);
  617. foreach (var item in pages.Data)
  618. {
  619. item.ModifyDate = item.ModifyDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
  620. item.PostDate = item.PostDate.ToTimeZone(HttpContext.Session.Get<string>(SessionKey.TimeZone));
  621. }
  622. return Ok(pages);
  623. }
  624. /// <summary>
  625. /// 编辑
  626. /// </summary>
  627. /// <param name="post"></param>
  628. /// <param name="cancellationToken"></param>
  629. /// <returns></returns>
  630. [HttpPost, MyAuthorize]
  631. public async Task<ActionResult> Edit([FromBodyOrDefault] PostCommand post, CancellationToken cancellationToken = default)
  632. {
  633. post.Content = await ImagebedClient.ReplaceImgSrc(await post.Content.Trim().ClearImgAttributes(), cancellationToken);
  634. if (!ValidatePost(post, out var resultData))
  635. {
  636. return resultData;
  637. }
  638. Post p = await PostService.GetByIdAsync(post.Id);
  639. if (post.Reserve && p.Status == Status.Published)
  640. {
  641. if (p.Content.HammingDistance(post.Content) > 0)
  642. {
  643. var history = p.Mapper<PostHistoryVersion>();
  644. p.PostHistoryVersion.Add(history);
  645. }
  646. if (p.Title.HammingDistance(post.Title) > 10 && CommentService.Any(c => c.PostId == p.Id && c.ParentId == null))
  647. {
  648. p.Comment.Add(new Comment
  649. {
  650. Status = Status.Published,
  651. NickName = "系统自动评论",
  652. Email = p.Email,
  653. Content = $"<p style=\"color:red\">温馨提示:由于文章发生了重大更新,本条评论之前的所有评论仅作为原文《{p.Title}》的历史评论保留,不作为本文的最新评论参考,请知悉!了解更多信息,请查阅本文的历史修改记录。</p>",
  654. PostId = p.Id,
  655. CommentDate = DateTime.Now,
  656. IsMaster = true,
  657. IsAuthor = true,
  658. IP = "127.0.0.1",
  659. Location = "内网",
  660. GroupTag = SnowFlake.NewId,
  661. Path = SnowFlake.NewId,
  662. });
  663. }
  664. p.ModifyDate = DateTime.Now;
  665. var user = HttpContext.Session.Get<UserInfoDto>(SessionKey.UserInfo);
  666. post.Modifier = string.IsNullOrEmpty(post.Modifier) ? user.NickName : post.Modifier;
  667. post.ModifierEmail = string.IsNullOrEmpty(post.ModifierEmail) ? user.Email : post.ModifierEmail;
  668. }
  669. Mapper.Map(post, p);
  670. p.IP = ClientIP;
  671. p.Seminar.Clear();
  672. if (!string.IsNullOrEmpty(post.Seminars))
  673. {
  674. var tmp = post.Seminars.Split(',', StringSplitOptions.RemoveEmptyEntries).Distinct().Select(int.Parse).ToArray();
  675. var seminars = SeminarService.GetQuery(s => tmp.Contains(s.Id)).ToList();
  676. p.Seminar.AddRange(seminars);
  677. }
  678. (p.Keyword + "," + p.Label).Split(',', StringSplitOptions.RemoveEmptyEntries).ForEach(KeywordsManager.AddWords);
  679. PostTagService.AddOrUpdate(t => t.Name, p.Label.AsNotNull().Split(',', StringSplitOptions.RemoveEmptyEntries).Select(s => new PostTag()
  680. {
  681. Name = s,
  682. Count = PostService.Count(t => t.Label.Contains(s))
  683. }));
  684. bool b = await SearchEngine.SaveChangesAsync() > 0;
  685. if (!b)
  686. {
  687. return ResultData(null, false, "文章修改失败!");
  688. }
  689. if (p.LimitMode == RegionLimitMode.OnlyForSearchEngine)
  690. {
  691. SearchEngine.LuceneIndexer.Delete(p);
  692. }
  693. return ResultData(p.Mapper<PostDto>(), message: "文章修改成功!");
  694. }
  695. /// <summary>
  696. /// 发布
  697. /// </summary>
  698. /// <param name="post"></param>
  699. /// <param name="timespan"></param>
  700. /// <param name="schedule"></param>
  701. /// <param name="cancellationToken"></param>
  702. /// <returns></returns>
  703. [MyAuthorize, HttpPost]
  704. public async Task<ActionResult> Write([FromBodyOrDefault] PostCommand post, [FromBodyOrDefault] DateTime? timespan, [FromBodyOrDefault] bool schedule = false, CancellationToken cancellationToken = default)
  705. {
  706. post.Content = await ImagebedClient.ReplaceImgSrc(await post.Content.Trim().ClearImgAttributes(), cancellationToken);
  707. if (!ValidatePost(post, out var resultData))
  708. {
  709. return resultData;
  710. }
  711. post.Status = Status.Published;
  712. Post p = post.Mapper<Post>();
  713. p.Modifier = p.Author;
  714. p.ModifierEmail = p.Email;
  715. p.IP = ClientIP;
  716. p.Rss = p.LimitMode is null or RegionLimitMode.All;
  717. if (!string.IsNullOrEmpty(post.Seminars))
  718. {
  719. var tmp = post.Seminars.Split(',').Distinct().Select(int.Parse).ToArray();
  720. p.Seminar.AddRange(SeminarService[s => tmp.Contains(s.Id)]);
  721. }
  722. if (schedule)
  723. {
  724. if (!timespan.HasValue || timespan.Value <= DateTime.Now)
  725. {
  726. return ResultData(null, false, "如果要定时发布,请选择正确的一个将来时间点!");
  727. }
  728. p.Status = Status.Schedule;
  729. p.PostDate = timespan.Value.ToUniversalTime();
  730. p.ModifyDate = timespan.Value.ToUniversalTime();
  731. BackgroundJob.Enqueue<IHangfireBackJob>(job => job.PublishPost(p));
  732. return ResultData(p.Mapper<PostDto>(), message: $"文章于{timespan.Value:yyyy-MM-dd HH:mm:ss}将会自动发表!");
  733. }
  734. PostService.AddEntity(p);
  735. (p.Keyword + "," + p.Label).Split(',', StringSplitOptions.RemoveEmptyEntries).ForEach(KeywordsManager.AddWords);
  736. PostTagService.AddOrUpdate(t => t.Name, p.Label.AsNotNull().Split(',', StringSplitOptions.RemoveEmptyEntries).Select(s => new PostTag()
  737. {
  738. Name = s,
  739. Count = PostService.Count(t => t.Label.Contains(s))
  740. }));
  741. bool b = await SearchEngine.SaveChangesAsync() > 0;
  742. if (!b)
  743. {
  744. return ResultData(null, false, "文章发表失败!");
  745. }
  746. if (p.LimitMode == RegionLimitMode.OnlyForSearchEngine)
  747. {
  748. SearchEngine.LuceneIndexer.Delete(p);
  749. }
  750. return ResultData(null, true, "文章发表成功!");
  751. }
  752. private bool ValidatePost(PostCommand post, out ActionResult resultData)
  753. {
  754. if (!CategoryService.Any(c => c.Id == post.CategoryId && c.Status == Status.Available))
  755. {
  756. resultData = ResultData(null, false, "请选择一个分类");
  757. return false;
  758. }
  759. switch (post.LimitMode)
  760. {
  761. case RegionLimitMode.AllowRegion:
  762. case RegionLimitMode.ForbidRegion:
  763. if (string.IsNullOrEmpty(post.Regions))
  764. {
  765. resultData = ResultData(null, false, "请输入限制的地区");
  766. return false;
  767. }
  768. post.Regions = post.Regions.Replace(",", "|").Replace(",", "|");
  769. break;
  770. case RegionLimitMode.AllowRegionExceptForbidRegion:
  771. case RegionLimitMode.ForbidRegionExceptAllowRegion:
  772. if (string.IsNullOrEmpty(post.ExceptRegions))
  773. {
  774. resultData = ResultData(null, false, "请输入排除的地区");
  775. return false;
  776. }
  777. post.ExceptRegions = post.ExceptRegions.Replace(",", "|").Replace(",", "|");
  778. goto case RegionLimitMode.AllowRegion;
  779. }
  780. if (string.IsNullOrEmpty(post.Label?.Trim()) || post.Label.Equals("null"))
  781. {
  782. post.Label = null;
  783. }
  784. else if (post.Label.Trim().Length > 50)
  785. {
  786. post.Label = post.Label.Replace(",", ",");
  787. post.Label = post.Label.Trim().Substring(0, 50);
  788. }
  789. else
  790. {
  791. post.Label = post.Label.Replace(",", ",");
  792. }
  793. if (string.IsNullOrEmpty(post.ProtectContent?.RemoveHtmlTag()) || post.ProtectContent.Equals("null"))
  794. {
  795. post.ProtectContent = null;
  796. }
  797. resultData = null;
  798. return true;
  799. }
  800. /// <summary>
  801. /// 添加专题
  802. /// </summary>
  803. /// <param name="id"></param>
  804. /// <param name="sid"></param>
  805. /// <returns></returns>
  806. [MyAuthorize]
  807. public async Task<ActionResult> AddSeminar(int id, int sid)
  808. {
  809. var post = await PostService.GetByIdAsync(id) ?? throw new NotFoundException("文章未找到");
  810. Seminar seminar = await SeminarService.GetByIdAsync(sid) ?? throw new NotFoundException("专题未找到");
  811. post.Seminar.Add(seminar);
  812. bool b = await PostService.SaveChangesAsync() > 0;
  813. return ResultData(null, b, b ? $"已将文章【{post.Title}】添加到专题【{seminar.Title}】" : "添加失败");
  814. }
  815. /// <summary>
  816. /// 移除专题
  817. /// </summary>
  818. /// <param name="id"></param>
  819. /// <param name="sid"></param>
  820. /// <returns></returns>
  821. [MyAuthorize]
  822. public async Task<ActionResult> RemoveSeminar(int id, int sid)
  823. {
  824. var post = await PostService.GetByIdAsync(id) ?? throw new NotFoundException("文章未找到");
  825. Seminar seminar = await SeminarService.GetByIdAsync(sid) ?? throw new NotFoundException("专题未找到");
  826. post.Seminar.Remove(seminar);
  827. bool b = await PostService.SaveChangesAsync() > 0;
  828. return ResultData(null, b, b ? $"已将文章【{post.Title}】从【{seminar.Title}】专题移除" : "添加失败");
  829. }
  830. /// <summary>
  831. /// 删除历史版本
  832. /// </summary>
  833. /// <param name="id"></param>
  834. /// <returns></returns>
  835. [MyAuthorize]
  836. public async Task<ActionResult> DeleteHistory(int id)
  837. {
  838. bool b = await PostHistoryVersionService.DeleteByIdAsync(id) > 0;
  839. return ResultData(null, b, b ? "历史版本文章删除成功!" : "历史版本文章删除失败!");
  840. }
  841. /// <summary>
  842. /// 还原版本
  843. /// </summary>
  844. /// <param name="id"></param>
  845. /// <returns></returns>
  846. [MyAuthorize]
  847. public async Task<ActionResult> Revert(int id)
  848. {
  849. var history = await PostHistoryVersionService.GetByIdAsync(id) ?? throw new NotFoundException("版本不存在");
  850. history.Post.Category = history.Category;
  851. history.Post.CategoryId = history.CategoryId;
  852. history.Post.Content = history.Content;
  853. history.Post.Title = history.Title;
  854. history.Post.Label = history.Label;
  855. history.Post.ModifyDate = history.ModifyDate;
  856. history.Post.Seminar.Clear();
  857. foreach (var s in history.Seminar)
  858. {
  859. history.Post.Seminar.Add(s);
  860. }
  861. bool b = await SearchEngine.SaveChangesAsync() > 0;
  862. await PostHistoryVersionService.DeleteByIdAsync(id);
  863. return ResultData(null, b, b ? "回滚成功" : "回滚失败");
  864. }
  865. /// <summary>
  866. /// 禁用或开启文章评论
  867. /// </summary>
  868. /// <param name="id">文章id</param>
  869. /// <returns></returns>
  870. [MyAuthorize]
  871. [HttpPost("post/{id}/DisableComment")]
  872. public async Task<ActionResult> DisableComment(int id)
  873. {
  874. var post = await PostService.GetByIdAsync(id) ?? throw new NotFoundException("文章未找到");
  875. post.DisableComment = !post.DisableComment;
  876. return ResultData(null, await PostService.SaveChangesAsync() > 0, post.DisableComment ? $"已禁用【{post.Title}】这篇文章的评论功能!" : $"已启用【{post.Title}】这篇文章的评论功能!");
  877. }
  878. /// <summary>
  879. /// 禁用或开启文章评论
  880. /// </summary>
  881. /// <param name="id">文章id</param>
  882. /// <returns></returns>
  883. [MyAuthorize]
  884. [HttpPost("post/{id}/DisableCopy")]
  885. public async Task<ActionResult> DisableCopy(int id)
  886. {
  887. var post = await PostService.GetByIdAsync(id) ?? throw new NotFoundException("文章未找到");
  888. post.DisableCopy = !post.DisableCopy;
  889. return ResultData(null, await PostService.SaveChangesAsync() > 0, post.DisableCopy ? $"已开启【{post.Title}】这篇文章的防复制功能!" : $"已关闭【{post.Title}】这篇文章的防复制功能!");
  890. }
  891. /// <summary>
  892. /// 修改分类
  893. /// </summary>
  894. /// <param name="id"></param>
  895. /// <param name="cid"></param>
  896. /// <returns></returns>
  897. [HttpPost("post/{id}/ChangeCategory/{cid}")]
  898. public async Task<ActionResult> ChangeCategory(int id, int cid)
  899. {
  900. await PostService.GetQuery(p => p.Id == id).ExecuteUpdateAsync(s => s.SetProperty(p => p.CategoryId, cid));
  901. return Ok();
  902. }
  903. /// <summary>
  904. /// 修改专题
  905. /// </summary>
  906. /// <param name="id"></param>
  907. /// <param name="sids"></param>
  908. /// <returns></returns>
  909. [HttpPost("post/{id}/ChangeSeminar")]
  910. public async Task<ActionResult> ChangeSeminar(int id, string sids)
  911. {
  912. var post = PostService.GetQuery(e => e.Id == id).Include(e => e.Seminar).FirstOrDefault() ?? throw new NotFoundException("文章不存在");
  913. post.Seminar.Clear();
  914. if (!string.IsNullOrEmpty(sids))
  915. {
  916. var ids = sids.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
  917. post.Seminar.AddRange(SeminarService[s => ids.Contains(s.Id)]);
  918. }
  919. await PostService.SaveChangesAsync();
  920. return Ok();
  921. }
  922. /// <summary>
  923. /// 刷新文章
  924. /// </summary>
  925. /// <param name="id">文章id</param>
  926. /// <param name="cancellationToken"></param>
  927. /// <returns></returns>
  928. [MyAuthorize]
  929. public async Task<ActionResult> Refresh(int id, CancellationToken cancellationToken = default)
  930. {
  931. await PostService.GetQuery(p => p.Id == id).ExecuteUpdateAsync(s => s.SetProperty(m => m.ModifyDate, DateTime.Now), cancellationToken: cancellationToken);
  932. return RedirectToAction("Details", new { id });
  933. }
  934. /// <summary>
  935. /// 标记为恶意修改
  936. /// </summary>
  937. /// <param name="id"></param>
  938. /// <param name="cancellationToken"></param>
  939. /// <returns></returns>
  940. [MyAuthorize]
  941. [HttpPost("post/block/{id}")]
  942. public async Task<ActionResult> Block(int id, CancellationToken cancellationToken = default)
  943. {
  944. var b = await PostService.GetQuery(p => p.Id == id).ExecuteUpdateAsync(s => s.SetProperty(m => m.Status, Status.Forbidden), cancellationToken: cancellationToken) > 0;
  945. return b ? ResultData(null, true, "操作成功!") : ResultData(null, false, "操作失败!");
  946. }
  947. /// <summary>
  948. /// 切换允许rss订阅
  949. /// </summary>
  950. /// <param name="id"></param>
  951. /// <param name="cancellationToken"></param>
  952. /// <returns></returns>
  953. [MyAuthorize]
  954. [HttpPost("post/{id}/rss-switch")]
  955. public async Task<ActionResult> RssSwitch(int id, CancellationToken cancellationToken = default)
  956. {
  957. await PostService.GetQuery(p => p.Id == id).ExecuteUpdateAsync(s => s.SetProperty(m => m.Rss, p => !p.Rss), cancellationToken: cancellationToken);
  958. return ResultData(null, message: "操作成功");
  959. }
  960. /// <summary>
  961. /// 切换锁定编辑
  962. /// </summary>
  963. /// <param name="id"></param>
  964. /// <param name="cancellationToken"></param>
  965. /// <returns></returns>
  966. [MyAuthorize]
  967. [HttpPost("post/{id}/locked-switch")]
  968. public async Task<ActionResult> LockedSwitch(int id, CancellationToken cancellationToken = default)
  969. {
  970. await PostService.GetQuery(p => p.Id == id).ExecuteUpdateAsync(s => s.SetProperty(m => m.Locked, p => !p.Locked), cancellationToken: cancellationToken);
  971. return ResultData(null, message: "操作成功");
  972. }
  973. /// <summary>
  974. /// 文章统计
  975. /// </summary>
  976. /// <returns></returns>
  977. [MyAuthorize]
  978. public async Task<IActionResult> Statistic(CancellationToken cancellationToken = default)
  979. {
  980. var keys = RedisHelper.Keys(nameof(PostOnline) + ":*");
  981. var sets = keys.Select(s => (Id: s.Split(':')[1].ToInt32(), Clients: RedisHelper.HGet<HashSet<string>>(s, "value")));
  982. var ids = sets.Where(t => t.Clients?.Count > 0).OrderByDescending(t => t.Clients.Count).Take(10).Select(t => t.Id).ToArray();
  983. var mostHots = await PostService.GetQuery<PostModelBase>(p => ids.Contains(p.Id)).ToListAsync().ContinueWith(t =>
  984. {
  985. foreach (var item in t.Result)
  986. {
  987. item.ViewCount = sets.FirstOrDefault(x => x.Id == item.Id).Clients.Count;
  988. }
  989. return t.Result.OrderByDescending(p => p.ViewCount);
  990. });
  991. var postsQuery = PostService.GetQuery(p => p.Status == Status.Published);
  992. var mostView = await postsQuery.OrderByDescending(p => p.TotalViewCount).Take(10).Select(p => new PostModelBase()
  993. {
  994. Id = p.Id,
  995. Title = p.Title,
  996. ViewCount = p.TotalViewCount
  997. }).ToListAsync(cancellationToken);
  998. var mostAverage = await postsQuery.OrderByDescending(p => p.AverageViewCount).Take(10).Select(p => new PostModelBase()
  999. {
  1000. Id = p.Id,
  1001. Title = p.Title,
  1002. ViewCount = (int)p.AverageViewCount
  1003. }).ToListAsync(cancellationToken);
  1004. var yesterday = DateTime.Now.AddDays(-1);
  1005. var trending = await postsQuery.Select(p => new PostModelBase()
  1006. {
  1007. Id = p.Id,
  1008. Title = p.Title,
  1009. ViewCount = p.PostVisitRecords.Count(t => t.Time >= yesterday)
  1010. }).OrderByDescending(p => p.ViewCount).Take(10).ToListAsync(cancellationToken);
  1011. var readCount = PostVisitRecordService.Count(e => e.Time >= yesterday);
  1012. return ResultData(new
  1013. {
  1014. mostHots,
  1015. mostView,
  1016. mostAverage,
  1017. trending,
  1018. readCount
  1019. });
  1020. }
  1021. /// <summary>
  1022. /// 文章访问记录
  1023. /// </summary>
  1024. /// <param name="id"></param>
  1025. /// <param name="page"></param>
  1026. /// <param name="size"></param>
  1027. /// <returns></returns>
  1028. [HttpGet("/{id}/records"), MyAuthorize]
  1029. [ProducesResponseType(typeof(PagedList<PostVisitRecordViewModel>), (int)HttpStatusCode.OK)]
  1030. public async Task<IActionResult> PostVisitRecords(int id, int page = 1, int size = 15, string kw = "")
  1031. {
  1032. Expression<Func<PostVisitRecord, bool>> where = e => e.PostId == id;
  1033. if (!string.IsNullOrEmpty(kw))
  1034. {
  1035. kw = Regex.Escape(kw);
  1036. where = where.And(e => Regex.IsMatch(e.IP + e.Location + e.Referer + e.RequestUrl, kw, RegexOptions.IgnoreCase));
  1037. }
  1038. var pages = await PostVisitRecordService.GetPagesAsync<DateTime, PostVisitRecordViewModel>(page, size, where, e => e.Time, false);
  1039. return Ok(pages);
  1040. }
  1041. /// <summary>
  1042. /// 导出文章访问记录
  1043. /// </summary>
  1044. /// <param name="id"></param>
  1045. /// <returns></returns>
  1046. [HttpGet("/{id}/records-export"), MyAuthorize]
  1047. [ProducesResponseType(typeof(PagedList<PostVisitRecordViewModel>), (int)HttpStatusCode.OK)]
  1048. public IActionResult ExportPostVisitRecords(int id)
  1049. {
  1050. var list = PostVisitRecordService.GetQuery<DateTime, PostVisitRecordViewModel>(e => e.PostId == id, e => e.Time, false).ToList();
  1051. using var ms = list.ToExcel();
  1052. var post = PostService[id];
  1053. return this.ResumeFile(ms.ToArray(), ContentType.Xlsx, post.Title + "访问记录.xlsx");
  1054. }
  1055. /// <summary>
  1056. /// 文章访问记录图表
  1057. /// </summary>
  1058. /// <returns></returns>
  1059. [HttpGet("/{id}/records-chart"), MyAuthorize]
  1060. [ProducesResponseType((int)HttpStatusCode.OK)]
  1061. public async Task<IActionResult> PostVisitRecordChart([FromServices] IPostVisitRecordStatsService statsService, int id, bool compare, uint period, CancellationToken cancellationToken)
  1062. {
  1063. if (compare)
  1064. {
  1065. var start1 = DateTime.Today.AddDays(-period);
  1066. var list1 = await statsService.GetQuery(e => e.PostId == id && e.Date >= start1).GroupBy(t => t.Date).Select(g => new
  1067. {
  1068. Date = g.Key,
  1069. Count = g.Sum(t => t.Count),
  1070. UV = g.Sum(t => t.UV)
  1071. }).OrderBy(a => a.Date).ToListAsync(cancellationToken);
  1072. if (list1.Count == 0)
  1073. {
  1074. return Ok(Array.Empty<int>());
  1075. }
  1076. var start2 = start1.AddDays(-period - 1);
  1077. var list2 = await statsService.GetQuery(e => e.PostId == id && e.Date >= start2 && e.Date < start1).GroupBy(t => t.Date).Select(g => new
  1078. {
  1079. Date = g.Key,
  1080. Count = g.Sum(t => t.Count),
  1081. UV = g.Sum(t => t.UV)
  1082. }).OrderBy(a => a.Date).ToListAsync(cancellationToken);
  1083. // 将数据填充成连续的数据
  1084. for (var i = start1; i <= DateTime.Today; i = i.AddDays(1))
  1085. {
  1086. if (list1.All(a => a.Date != i))
  1087. {
  1088. list1.Add(new { Date = i, Count = 0, UV = 0 });
  1089. }
  1090. }
  1091. for (var i = start2; i < start1; i = i.AddDays(1))
  1092. {
  1093. if (list2.All(a => a.Date != i))
  1094. {
  1095. list2.Add(new { Date = i, Count = 0, UV = 0 });
  1096. }
  1097. }
  1098. return Ok(new[] { list1.OrderBy(a => a.Date), list2.OrderBy(a => a.Date) });
  1099. }
  1100. var list = await statsService.GetQuery(e => e.PostId == id).GroupBy(t => t.Date).Select(g => new
  1101. {
  1102. Date = g.Key,
  1103. Count = g.Sum(t => t.Count),
  1104. UV = g.Sum(t => t.UV)
  1105. }).OrderBy(a => a.Date).ToListAsync(cancellationToken);
  1106. var min = list.Min(a => a.Date);
  1107. var max = list.Max(a => a.Date);
  1108. for (var i = min; i < max; i = i.AddDays(1))
  1109. {
  1110. if (list.All(a => a.Date != i))
  1111. {
  1112. list.Add(new { Date = i, Count = 0, UV = 0 });
  1113. }
  1114. }
  1115. return Ok(new[] { list.OrderBy(a => a.Date) });
  1116. }
  1117. /// <summary>
  1118. /// 文章访问记录图表
  1119. /// </summary>
  1120. /// <returns></returns>
  1121. [HttpGet("/post/records-chart"), MyAuthorize]
  1122. [ProducesResponseType((int)HttpStatusCode.OK)]
  1123. public async Task<IActionResult> PostVisitRecordChart(bool compare, uint period, CancellationToken cancellationToken)
  1124. {
  1125. if (compare)
  1126. {
  1127. var start1 = DateTime.Today.AddDays(-period);
  1128. var list1 = await PostVisitRecordService.GetQuery(e => e.Time >= start1).Select(e => new { e.Time.Date, e.IP }).GroupBy(t => t.Date).Select(g => new
  1129. {
  1130. Date = g.Key,
  1131. Count = g.Count(),
  1132. UV = g.Select(e => e.IP).Distinct().Count()
  1133. }).OrderBy(a => a.Date).ToListAsync(cancellationToken);
  1134. if (list1.Count == 0)
  1135. {
  1136. return Ok(Array.Empty<int>());
  1137. }
  1138. var start2 = start1.AddDays(-period - 1);
  1139. var list2 = await PostVisitRecordService.GetQuery(e => e.Time >= start2 && e.Time < start1).Select(e => new { e.Time.Date, e.IP }).GroupBy(t => t.Date).Select(g => new
  1140. {
  1141. Date = g.Key,
  1142. Count = g.Count(),
  1143. UV = g.Select(e => e.IP).Distinct().Count()
  1144. }).OrderBy(a => a.Date).ToListAsync(cancellationToken);
  1145. // 将数据填充成连续的数据
  1146. for (var i = start1; i <= DateTime.Today; i = i.AddDays(1))
  1147. {
  1148. if (list1.All(a => a.Date != i))
  1149. {
  1150. list1.Add(new { Date = i, Count = 0, UV = 0 });
  1151. }
  1152. }
  1153. for (var i = start2; i < start1; i = i.AddDays(1))
  1154. {
  1155. if (list2.All(a => a.Date != i))
  1156. {
  1157. list2.Add(new { Date = i, Count = 0, UV = 0 });
  1158. }
  1159. }
  1160. return Ok(new[] { list1.OrderBy(a => a.Date), list2.OrderBy(a => a.Date) });
  1161. }
  1162. var list = await PostVisitRecordService.GetAll().Select(e => new { e.Time.Date, e.IP }).GroupBy(t => t.Date).Select(g => new
  1163. {
  1164. Date = g.Key,
  1165. Count = g.Count(),
  1166. UV = g.Select(e => e.IP).Distinct().Count()
  1167. }).OrderBy(a => a.Date).ToListAsync(cancellationToken);
  1168. var min = list.Min(a => a.Date);
  1169. var max = list.Max(a => a.Date);
  1170. for (var i = min; i < max; i = i.AddDays(1))
  1171. {
  1172. if (list.All(a => a.Date != i))
  1173. {
  1174. list.Add(new { Date = i, Count = 0, UV = 0 });
  1175. }
  1176. }
  1177. return Ok(new[] { list.OrderBy(a => a.Date) });
  1178. }
  1179. /// <summary>
  1180. /// 文章访问记录分析
  1181. /// </summary>
  1182. /// <param name="id"></param>
  1183. /// <returns></returns>
  1184. [HttpGet("/{id}/insight"), MyAuthorize]
  1185. [ProducesResponseType(typeof(PagedList<PostVisitRecordViewModel>), (int)HttpStatusCode.OK)]
  1186. public IActionResult PostVisitRecordInsight(int id)
  1187. {
  1188. return View(PostService[id]);
  1189. }
  1190. /// <summary>
  1191. /// 获取地区集
  1192. /// </summary>
  1193. /// <param name="name"></param>
  1194. /// <returns></returns>
  1195. [MyAuthorize]
  1196. [ProducesResponseType(typeof(List<string>), (int)HttpStatusCode.OK)]
  1197. public async Task<IActionResult> GetRegions(string name)
  1198. {
  1199. return ResultData(await PostService.GetAll().Select(p => EF.Property<string>(p, name)).Distinct().ToListAsync());
  1200. }
  1201. #endregion 后端管理
  1202. }