PostController.cs 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. using AutoMapper;
  2. using Common;
  3. using EFSecondLevelCache.Core;
  4. using Hangfire;
  5. using Masuit.LuceneEFCore.SearchEngine.Interfaces;
  6. using Masuit.MyBlogs.Core.Common;
  7. using Masuit.MyBlogs.Core.Configs;
  8. using Masuit.MyBlogs.Core.Extensions;
  9. using Masuit.MyBlogs.Core.Extensions.Hangfire;
  10. using Masuit.MyBlogs.Core.Infrastructure;
  11. using Masuit.MyBlogs.Core.Infrastructure.Services.Interface;
  12. using Masuit.MyBlogs.Core.Models.DTO;
  13. using Masuit.MyBlogs.Core.Models.Entity;
  14. using Masuit.MyBlogs.Core.Models.Enum;
  15. using Masuit.MyBlogs.Core.Models.ViewModel;
  16. using Masuit.Tools;
  17. using Masuit.Tools.Core.Net;
  18. using Masuit.Tools.DateTimeExt;
  19. using Masuit.Tools.Html;
  20. using Masuit.Tools.Security;
  21. using Masuit.Tools.Systems;
  22. using Microsoft.AspNetCore.Hosting;
  23. using Microsoft.AspNetCore.Http;
  24. using Microsoft.AspNetCore.Mvc;
  25. using Microsoft.AspNetCore.Mvc.Rendering;
  26. using Microsoft.Net.Http.Headers;
  27. using System;
  28. using System.Collections.Generic;
  29. using System.IO;
  30. using System.Linq;
  31. using System.Text.RegularExpressions;
  32. namespace Masuit.MyBlogs.Core.Controllers
  33. {
  34. /// <summary>
  35. /// 文章管理
  36. /// </summary>
  37. public class PostController : BaseController
  38. {
  39. private IPostService PostService { get; set; }
  40. private ICategoryService CategoryService { get; set; }
  41. private IBroadcastService BroadcastService { get; set; }
  42. private ISeminarService SeminarService { get; set; }
  43. private readonly IHostingEnvironment _hostingEnvironment;
  44. private readonly ISearchEngine<DataContext> _searchEngine;
  45. /// <summary>
  46. ///
  47. /// </summary>
  48. public IPostHistoryVersionService PostHistoryVersionService { get; set; }
  49. /// <summary>
  50. /// 文章管理
  51. /// </summary>
  52. /// <param name="postService"></param>
  53. /// <param name="categoryService"></param>
  54. /// <param name="broadcastService"></param>
  55. /// <param name="seminarService"></param>
  56. /// <param name="postHistoryVersionService"></param>
  57. /// <param name="hostingEnvironment"></param>
  58. /// <param name="searchEngine"></param>
  59. public PostController(IPostService postService, ICategoryService categoryService, IBroadcastService broadcastService, ISeminarService seminarService, IPostHistoryVersionService postHistoryVersionService, IHostingEnvironment hostingEnvironment, ISearchEngine<DataContext> searchEngine)
  60. {
  61. PostService = postService;
  62. CategoryService = categoryService;
  63. BroadcastService = broadcastService;
  64. SeminarService = seminarService;
  65. PostHistoryVersionService = postHistoryVersionService;
  66. _hostingEnvironment = hostingEnvironment;
  67. _searchEngine = searchEngine;
  68. }
  69. /// <summary>
  70. /// 文章详情页
  71. /// </summary>
  72. /// <param name="id"></param>
  73. /// <param name="kw"></param>
  74. /// <returns></returns>
  75. [Route("{id:int}/{kw}"), Route("{id:int}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id", "kw" }, VaryByHeader = HeaderNames.Cookie)]
  76. public ActionResult Details(int id, string kw)
  77. {
  78. Post post = PostService.GetById(id);
  79. if (post != null)
  80. {
  81. ViewBag.Keyword = post.Keyword + "," + post.Label;
  82. UserInfoOutputDto user = HttpContext.Session.Get<UserInfoOutputDto>(SessionKey.UserInfo) ?? new UserInfoOutputDto();
  83. DateTime modifyDate = post.ModifyDate;
  84. ViewBag.Next = PostService.GetFirstEntityNoTracking(p => p.ModifyDate > modifyDate && (p.Status == Status.Pended || user.IsAdmin), p => p.ModifyDate);
  85. ViewBag.Prev = PostService.GetFirstEntityNoTracking(p => p.ModifyDate < modifyDate && (p.Status == Status.Pended || user.IsAdmin), p => p.ModifyDate, false);
  86. if (!string.IsNullOrEmpty(kw))
  87. {
  88. ViewData["keywords"] = post.Content.Contains(kw) ? $"['{kw}']" : _searchEngine.LuceneIndexSearcher.CutKeywords(kw).ToJsonString();
  89. }
  90. if (user.IsAdmin)
  91. {
  92. return View("Details_Admin", post);
  93. }
  94. if (post.Status != Status.Pended)
  95. {
  96. return RedirectToAction("Post", "Home");
  97. }
  98. if (!HttpContext.Request.IsRobot() && string.IsNullOrEmpty(HttpContext.Session.Get<string>("post" + id)))
  99. {
  100. HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.RecordPostVisit), args: id);
  101. HttpContext.Session.Set("post" + id, id.ToString());
  102. }
  103. return View(post);
  104. }
  105. return RedirectToAction("Index", "Error");
  106. }
  107. /// <summary>
  108. /// 文章历史版本
  109. /// </summary>
  110. /// <param name="id"></param>
  111. /// <param name="page"></param>
  112. /// <param name="size"></param>
  113. /// <returns></returns>
  114. [Route("{id:int}/history"), Route("{id:int}/history/{page:int}/{size:int}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id", "page", "size" }, VaryByHeader = HeaderNames.Cookie)]
  115. public ActionResult History(int id, int page = 1, int size = 20)
  116. {
  117. var p = PostService.GetById(id).Mapper<PostOutputDto>();
  118. if (p != null)
  119. {
  120. ViewBag.Primary = p;
  121. var list = PostHistoryVersionService.LoadPageEntitiesNoTracking(page, size, out int total, v => v.PostId == id, v => v.ModifyDate, false).Select(v => new PostHistoryVersion()
  122. {
  123. PostId = id,
  124. Category = v.Category,
  125. ModifyDate = v.ModifyDate,
  126. Title = v.Title,
  127. Id = v.Id,
  128. CategoryId = v.CategoryId
  129. }).Cacheable().ToList();
  130. ViewBag.Total = total;
  131. ViewBag.PageCount = Math.Ceiling(total * 1.0 / size).ToInt32();
  132. return View(list);
  133. }
  134. return RedirectToAction("Details", "Post", new { id });
  135. }
  136. /// <summary>
  137. /// 文章历史版本
  138. /// </summary>
  139. /// <param name="id"></param>
  140. /// <param name="hid"></param>
  141. /// <returns></returns>
  142. [Route("{id:int}/history/{hid:int}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id", "hid" }, VaryByHeader = HeaderNames.Cookie)]
  143. public ActionResult HistoryVersion(int id, int hid)
  144. {
  145. UserInfoOutputDto user = HttpContext.Session.Get<UserInfoOutputDto>(SessionKey.UserInfo) ?? new UserInfoOutputDto();
  146. var post = PostHistoryVersionService.GetById(hid);
  147. if (post is null)
  148. {
  149. return RedirectToAction("History", new
  150. {
  151. id
  152. });
  153. }
  154. ViewBag.Next = PostHistoryVersionService.GetFirstEntityNoTracking(p => p.PostId == id && p.ModifyDate > post.ModifyDate, p => p.ModifyDate);
  155. ViewBag.Prev = PostHistoryVersionService.GetFirstEntityNoTracking(p => p.PostId == id && p.ModifyDate < post.ModifyDate, p => p.ModifyDate, false);
  156. if (user.IsAdmin)
  157. {
  158. return View("HistoryVersion_Admin", post);
  159. }
  160. return View(post);
  161. }
  162. /// <summary>
  163. /// 版本对比
  164. /// </summary>
  165. /// <param name="id"></param>
  166. /// <param name="v1"></param>
  167. /// <param name="v2"></param>
  168. /// <returns></returns>
  169. [Route("{id:int}/history/{v1:int}-{v2:int}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id", "v1", "v2" }, VaryByHeader = HeaderNames.Cookie)]
  170. public ActionResult CompareVersion(int id, int v1, int v2)
  171. {
  172. var main = PostService.GetById(id).Mapper<PostHistoryVersion>();
  173. var left = v1 <= 0 ? main : PostHistoryVersionService.GetById(v1);
  174. var right = v2 <= 0 ? main : PostHistoryVersionService.GetById(v2);
  175. if (left is null || right is null)
  176. {
  177. return RedirectToAction("History", "Post", new { id });
  178. }
  179. HtmlDiff.HtmlDiff diffHelper = new HtmlDiff.HtmlDiff(right.Content, left.Content);
  180. string diffOutput = diffHelper.Build();
  181. right.Content = Regex.Replace(Regex.Replace(diffOutput, "<ins.+?</ins>", string.Empty), @"<\w+></\w+>", string.Empty);
  182. left.Content = Regex.Replace(Regex.Replace(diffOutput, "<del.+?</del>", string.Empty), @"<\w+></\w+>", string.Empty);
  183. return View(new[]
  184. {
  185. main,
  186. left,
  187. right
  188. });
  189. }
  190. /// <summary>
  191. /// 反对
  192. /// </summary>
  193. /// <param name="id"></param>
  194. /// <returns></returns>
  195. public ActionResult VoteDown(int id)
  196. {
  197. Post post = PostService.GetById(id);
  198. if (HttpContext.Session.Get("post-vote" + id) != null)
  199. {
  200. return ResultData(null, false, "您刚才已经投过票了,感谢您的参与!");
  201. }
  202. if (post != null)
  203. {
  204. HttpContext.Session.Set("post-vote" + id, id.GetBytes());
  205. ++post.VoteDownCount;
  206. PostService.UpdateEntity(post);
  207. var b = PostService.SaveChanges() > 0;
  208. return ResultData(null, b, b ? "投票成功!" : "投票失败!");
  209. }
  210. return ResultData(null, false, "非法操作");
  211. }
  212. /// <summary>
  213. /// 支持
  214. /// </summary>
  215. /// <param name="id"></param>
  216. /// <returns></returns>
  217. public ActionResult VoteUp(int id)
  218. {
  219. Post post = PostService.GetById(id);
  220. if (HttpContext.Session.Get("post-vote" + id) != null)
  221. {
  222. return ResultData(null, false, "您刚才已经投过票了,感谢您的参与!");
  223. }
  224. if (post != null)
  225. {
  226. HttpContext.Session.Set("post-vote" + id, id.GetBytes());
  227. ++post.VoteUpCount;
  228. PostService.UpdateEntity(post);
  229. var b = PostService.SaveChanges() > 0;
  230. return ResultData(null, b, b ? "投票成功!" : "投票失败!");
  231. }
  232. return ResultData(null, false, "非法操作");
  233. }
  234. /// <summary>
  235. /// 投稿页
  236. /// </summary>
  237. /// <returns></returns>
  238. public ActionResult Publish()
  239. {
  240. List<string> list = PostService.GetAll().Select(p => p.Label).ToList();
  241. List<string> result = new List<string>();
  242. list.ForEach(s =>
  243. {
  244. if (!string.IsNullOrEmpty(s))
  245. {
  246. result.AddRange(s.Split(',', ','));
  247. }
  248. });
  249. ViewBag.Category = CategoryService.LoadEntitiesNoTracking(c => c.Status == Status.Available).ToList();
  250. UserInfoOutputDto user = HttpContext.Session.Get<UserInfoOutputDto>(SessionKey.UserInfo);
  251. if (user != null)
  252. {
  253. return View("Publish_Admin", result.Distinct().OrderBy(s => s));
  254. }
  255. return View(result.Distinct().OrderBy(s => s));
  256. }
  257. /// <summary>
  258. /// 发布投稿
  259. /// </summary>
  260. /// <param name="post"></param>
  261. /// <returns></returns>
  262. [HttpPost, ValidateAntiForgeryToken]
  263. public ActionResult Publish(PostInputDto post)
  264. {
  265. if (Regex.Match(post.Content, CommonHelper.BanRegex).Length > 0)
  266. {
  267. return ResultData(null, false, "您提交的内容包含敏感词,被禁止发表,请注意改善您的言辞!");
  268. }
  269. UserInfoOutputDto user = HttpContext.Session.Get<UserInfoOutputDto>(SessionKey.UserInfo);
  270. if (!CategoryService.Any(c => c.Id == post.CategoryId && c.Status == Status.Available))
  271. {
  272. return ResultData(null, message: "请选择一个分类");
  273. }
  274. if (string.IsNullOrEmpty(post.Label?.Trim()))
  275. {
  276. post.Label = null;
  277. }
  278. else if (post.Label.Trim().Length > 50)
  279. {
  280. post.Label = post.Label.Replace(",", ",").Trim().Substring(0, 50);
  281. }
  282. else
  283. {
  284. post.Label = post.Label.Replace(",", ",");
  285. }
  286. post.Status = Status.Pending;
  287. post.PostDate = DateTime.Now;
  288. post.ModifyDate = DateTime.Now;
  289. if (user != null && user.IsAdmin)
  290. {
  291. post.Status = Status.Pended;
  292. }
  293. else
  294. {
  295. post.Content = CommonHelper.ReplaceImgSrc(Regex.Replace(post.Content.HtmlSantinizerStandard(), @"<img\s+[^>]*\s*src\s*=\s*['""]?(\S+\.\w{3,4})['""]?[^/>]*/>", "<img src=\"$1\"/>")).Replace("/thumb150/", "/large/");
  296. }
  297. ViewBag.CategoryId = new SelectList(CategoryService.LoadEntitiesNoTracking(c => c.Status == Status.Available), "Id", "Name", post.CategoryId);
  298. Post p = post.Mapper<Post>();
  299. p.IP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
  300. p.PostAccessRecord.Add(new PostAccessRecord()
  301. {
  302. AccessTime = DateTime.Today,
  303. ClickCount = 0
  304. });
  305. p = PostService.AddEntitySaved(p);
  306. if (p != null)
  307. {
  308. if (p.Status == Status.Pending)
  309. {
  310. var email = CommonHelper.SystemSettings["ReceiveEmail"];
  311. string link = Url.Action("Details", "Post", new
  312. {
  313. id = p.Id
  314. }, Request.Scheme);
  315. string content = System.IO.File.ReadAllText(_hostingEnvironment.WebRootPath + "/template/publish.html").Replace("{{link}}", link).Replace("{{time}}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).Replace("{{title}}", p.Title);
  316. BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "有访客投稿:", content, email));
  317. return ResultData(p.Mapper<PostOutputDto>(), message: "文章发表成功,待站长审核通过以后将显示到列表中!");
  318. }
  319. return ResultData(p.Mapper<PostOutputDto>(), message: "文章发表成功!");
  320. }
  321. return ResultData(null, false, "文章发表失败!");
  322. }
  323. /// <summary>
  324. /// 获取标签
  325. /// </summary>
  326. /// <returns></returns>
  327. [ResponseCache(Duration = 600, VaryByHeader = HeaderNames.Cookie)]
  328. public ActionResult GetTag()
  329. {
  330. List<string> list = PostService.GetAll().Select(p => p.Label).ToList();
  331. List<string> result = new List<string>();
  332. list.ForEach(s =>
  333. {
  334. if (!string.IsNullOrEmpty(s))
  335. {
  336. result.AddRange(s.Split(',', ','));
  337. }
  338. });
  339. return ResultData(result.Distinct().OrderBy(s => s));
  340. }
  341. /// <summary>
  342. /// 标签云
  343. /// </summary>
  344. /// <returns></returns>
  345. [Route("all"), ResponseCache(Duration = 600, VaryByHeader = HeaderNames.Cookie)]
  346. public ActionResult All()
  347. {
  348. UserInfoOutputDto user = HttpContext.Session.Get<UserInfoOutputDto>(SessionKey.UserInfo) ?? new UserInfoOutputDto();
  349. List<string> tags = PostService.GetAll().Select(p => p.Label).ToList(); //tag
  350. List<string> result = new List<string>();
  351. tags.ForEach(s =>
  352. {
  353. if (!string.IsNullOrEmpty(s))
  354. {
  355. result.AddRange(s.Split(',', ','));
  356. }
  357. });
  358. ViewBag.tags = result.GroupBy(t => t).OrderByDescending(g => g.Count()).ThenBy(g => g.Key);
  359. ViewBag.cats = CategoryService.GetAll(c => c.Post.Count, false).Select(c => new TagCloudViewModel()
  360. {
  361. Id = c.Id,
  362. Name = c.Name,
  363. Count = c.Post.Count(p => p.Status == Status.Pended || user.IsAdmin)
  364. }).ToList(); //category
  365. ViewBag.seminars = SeminarService.GetAll(c => c.Post.Count, false).Select(c => new TagCloudViewModel
  366. {
  367. Id = c.Id,
  368. Name = c.Title,
  369. Count = c.Post.Count(p => p.Post.Status == Status.Pended || user.IsAdmin)
  370. }).ToList(); //seminars
  371. return View();
  372. }
  373. /// <summary>
  374. /// 检查访问密码
  375. /// </summary>
  376. /// <param name="token"></param>
  377. /// <returns></returns>
  378. [HttpPost, ValidateAntiForgeryToken]
  379. public ActionResult CheckViewToken(string token)
  380. {
  381. if (string.IsNullOrEmpty(token))
  382. {
  383. return ResultData(null, false, "请输入文章访问密码!");
  384. }
  385. var s = RedisHelper.Get("ArticleViewToken");
  386. if (token.Equals(s))
  387. {
  388. HttpContext.Session.Set("ArticleViewToken", token);
  389. return ResultData(null);
  390. }
  391. return ResultData(null, false, "文章访问密码不正确!");
  392. }
  393. /// <summary>
  394. /// 检查授权邮箱
  395. /// </summary>
  396. /// <param name="email"></param>
  397. /// <returns></returns>
  398. [HttpPost, ValidateAntiForgeryToken, ResponseCache(Duration = 120, VaryByQueryKeys = new[] { "email" })]
  399. public ActionResult GetViewToken(string email)
  400. {
  401. if (string.IsNullOrEmpty(email) && !email.MatchEmail())
  402. {
  403. return ResultData(null, false, "请输入正确的邮箱!");
  404. }
  405. if (RedisHelper.Exists("code:" + email))
  406. {
  407. RedisHelper.Expire("code:" + email, 120);
  408. return ResultData(null, false, "发送频率限制,请在2分钟后重新尝试发送邮件!请检查你的邮件,若未收到,请检查你的邮箱地址或邮件垃圾箱!");
  409. }
  410. if (BroadcastService.Any(b => b.Email.Equals(email) && b.SubscribeType == SubscribeType.ArticleToken))
  411. {
  412. var s = RedisHelper.Get("ArticleViewToken");
  413. CommonHelper.SendMail(CommonHelper.SystemSettings["Domain"] + "博客文章验证码", $"{CommonHelper.SystemSettings["Domain"]}博客文章验证码是:<span style='color:red'>{s}</span>,有效期为24h,请按时使用!", email);
  414. RedisHelper.Set("code:" + email, s, 120);
  415. return ResultData(null);
  416. }
  417. return ResultData(null, false, "您目前没有权限访问这篇文章的加密部分,请联系站长开通这篇文章的访问权限!");
  418. }
  419. #region 后端管理
  420. /// <summary>
  421. /// 固顶
  422. /// </summary>
  423. /// <param name="id"></param>
  424. /// <returns></returns>
  425. [Authority]
  426. public ActionResult Fixtop(int id)
  427. {
  428. Post post = PostService.GetById(id);
  429. post.IsFixedTop = !post.IsFixedTop;
  430. bool b = PostService.UpdateEntitySaved(post);
  431. if (b)
  432. {
  433. return ResultData(null, true, post.IsFixedTop ? "置顶成功!" : "取消置顶成功!");
  434. }
  435. return ResultData(null, false, "操作失败!");
  436. }
  437. /// <summary>
  438. /// 审核
  439. /// </summary>
  440. /// <param name="id"></param>
  441. /// <returns></returns>
  442. [Authority]
  443. public ActionResult Pass(int id)
  444. {
  445. Post post = PostService.GetById(id);
  446. post.Status = Status.Pended;
  447. post.ModifyDate = DateTime.Now;
  448. post.PostDate = DateTime.Now;
  449. bool b = PostService.UpdateEntitySaved(post);
  450. if (!b)
  451. {
  452. return ResultData(null, false, "审核失败!");
  453. }
  454. if ("false" == CommonHelper.SystemSettings["DisabledEmailBroadcast"])
  455. {
  456. var cast = BroadcastService.LoadEntities(c => c.Status == Status.Subscribed).ToList();
  457. string link = Request.Scheme + "://" + Request.Host + "/" + id;
  458. cast.ForEach(c =>
  459. {
  460. var ts = DateTime.Now.GetTotalMilliseconds();
  461. string content = System.IO.File.ReadAllText(_hostingEnvironment.WebRootPath + "/template/broadcast.html").Replace("{{link}}", link + "?email=" + c.Email).Replace("{{time}}", post.ModifyDate.ToString("yyyy-MM-dd HH:mm:ss")).Replace("{{title}}", post.Title).Replace("{{author}}", post.Author).Replace("{{content}}", post.Content.RemoveHtmlTag(150)).Replace("{{cancel}}", Url.Action("Subscribe", "Subscribe", new
  462. {
  463. c.Email,
  464. act = "cancel",
  465. validate = c.ValidateCode,
  466. timespan = ts,
  467. hash = (c.Email + "cancel" + c.ValidateCode + ts).AESEncrypt(AppConfig.BaiduAK)
  468. }, Request.Scheme));
  469. BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "博客有新文章发布了", content, c.Email));
  470. });
  471. }
  472. return ResultData(null, true, "审核通过!");
  473. }
  474. /// <summary>
  475. /// 删除
  476. /// </summary>
  477. /// <param name="id"></param>
  478. /// <returns></returns>
  479. [Authority]
  480. public ActionResult Delete(int id)
  481. {
  482. var post = PostService.GetById(id);
  483. post.Status = Status.Deleted;
  484. bool b = PostService.UpdateEntitySaved(post);
  485. _searchEngine.LuceneIndexer.Delete(post);
  486. return ResultData(null, b, b ? "删除成功!" : "删除失败!");
  487. }
  488. /// <summary>
  489. /// 还原版本
  490. /// </summary>
  491. /// <param name="id"></param>
  492. /// <returns></returns>
  493. [Authority]
  494. public ActionResult Restore(int id)
  495. {
  496. var post = PostService.GetById(id);
  497. post.Status = Status.Pended;
  498. bool b = PostService.UpdateEntitySaved(post);
  499. return ResultData(null, b, b ? "恢复成功!" : "恢复失败!");
  500. }
  501. /// <summary>
  502. /// 彻底删除文章
  503. /// </summary>
  504. /// <param name="id"></param>
  505. /// <returns></returns>
  506. [Authority]
  507. public ActionResult Truncate(int id)
  508. {
  509. var post = PostService.GetById(id);
  510. if (post is null)
  511. {
  512. return ResultData(null, false, "文章已经被删除!");
  513. }
  514. if (post.IsWordDocument)
  515. {
  516. try
  517. {
  518. System.IO.File.Delete(Path.Combine(_hostingEnvironment.WebRootPath + "/upload", post.ResourceName));
  519. Directory.Delete(Path.Combine(_hostingEnvironment.WebRootPath + "/upload", Path.GetFileNameWithoutExtension(post.ResourceName)), true);
  520. }
  521. catch (IOException)
  522. {
  523. }
  524. }
  525. var srcs = post.Content.MatchImgSrcs();
  526. foreach (var path in srcs)
  527. {
  528. if (path.StartsWith("/"))
  529. {
  530. try
  531. {
  532. System.IO.File.Delete(_hostingEnvironment.WebRootPath + path);
  533. }
  534. catch (IOException)
  535. {
  536. }
  537. }
  538. }
  539. bool b = PostService.DeleteByIdSaved(id);
  540. return ResultData(null, b, b ? "删除成功!" : "删除失败!");
  541. }
  542. /// <summary>
  543. /// 获取文章
  544. /// </summary>
  545. /// <param name="id"></param>
  546. /// <returns></returns>
  547. [Authority]
  548. public ActionResult Get(int id)
  549. {
  550. Post post = PostService.GetById(id);
  551. PostOutputDto model = post.Mapper<PostOutputDto>();
  552. model.Seminars = string.Join(",", post.Seminar.Select(s => s.Seminar.Title));
  553. return ResultData(model);
  554. }
  555. /// <summary>
  556. /// 文章详情
  557. /// </summary>
  558. /// <param name="id"></param>
  559. /// <returns></returns>
  560. [Authority]
  561. public ActionResult Read(int id) => ResultData(PostService.GetById(id).Mapper<PostOutputDto>());
  562. /// <summary>
  563. /// 获取所有文章
  564. /// </summary>
  565. /// <returns></returns>
  566. public ActionResult GetAllData()
  567. {
  568. var plist = PostService.LoadEntitiesNoTracking(p => p.Status != Status.Deleted).OrderBy(p => p.Status).ThenByDescending(p => p.IsFixedTop).ThenByDescending(p => p.ModifyDate).Select(p => new
  569. {
  570. p.Id,
  571. p.Author,
  572. CategoryName = p.Category.Name,
  573. p.Email,
  574. p.IsFixedTop,
  575. p.Label,
  576. md = p.ModifyDate,
  577. pd = p.PostDate,
  578. p.Title,
  579. ViewCount = p.TotalViewCount,
  580. p.VoteDownCount,
  581. p.VoteUpCount,
  582. stat = p.Status
  583. }).ToList();
  584. var list = new List<PostDataModel>();
  585. plist.ForEach(item =>
  586. {
  587. PostDataModel model = item.MapTo<PostDataModel>();
  588. model.PostDate = item.pd.ToString("yyyy-MM-dd HH:mm");
  589. model.ModifyDate = item.md.ToString("yyyy-MM-dd HH:mm");
  590. model.Status = item.stat.GetDisplay();
  591. list.Add(model);
  592. });
  593. return ResultData(list);
  594. }
  595. /// <summary>
  596. /// 获取文章分页
  597. /// </summary>
  598. /// <returns></returns>
  599. public ActionResult GetPageData(int page = 1, int size = 10, OrderBy orderby = OrderBy.ModifyDate, string kw = "")
  600. {
  601. if (page < 1)
  602. {
  603. page = 1;
  604. }
  605. if (size < 1)
  606. {
  607. page = 10;
  608. }
  609. var list = new List<PostDataModel>();
  610. IOrderedQueryable<Post> temp;
  611. var query = string.IsNullOrEmpty(kw) ? PostService.GetAllNoTracking() : PostService.LoadEntitiesNoTracking(p => p.Title.Contains(kw) || p.Author.Contains(kw) || p.Email.Contains(kw) || p.Label.Contains(kw) || p.Content.Contains(kw));
  612. var total = query.Count();
  613. var order = query.OrderByDescending(p => p.Status).ThenByDescending(p => p.IsFixedTop);
  614. switch (orderby)
  615. {
  616. case OrderBy.CommentCount:
  617. temp = order.ThenByDescending(p => p.Comment.Count);
  618. break;
  619. case OrderBy.PostDate:
  620. temp = order.ThenByDescending(p => p.PostDate);
  621. break;
  622. case OrderBy.ViewCount:
  623. temp = order.ThenByDescending(p => p.TotalViewCount);
  624. break;
  625. case OrderBy.VoteCount:
  626. temp = order.ThenByDescending(p => p.VoteUpCount);
  627. break;
  628. case OrderBy.AverageViewCount:
  629. temp = order.ThenByDescending(p => p.AverageViewCount);
  630. break;
  631. default:
  632. temp = order.ThenByDescending(p => p.ModifyDate);
  633. break;
  634. }
  635. var plist = temp.Skip((page - 1) * size).Take(size).Select(p => new
  636. {
  637. p.Id,
  638. p.Author,
  639. CategoryName = p.Category.Name,
  640. p.Email,
  641. p.IsFixedTop,
  642. p.Label,
  643. md = p.ModifyDate,
  644. pd = p.PostDate,
  645. p.Title,
  646. ViewCount = p.TotalViewCount,
  647. p.VoteDownCount,
  648. p.VoteUpCount,
  649. stat = p.Status,
  650. ModifyCount = p.PostHistoryVersion.Count
  651. }).ToList();
  652. plist.ForEach(item =>
  653. {
  654. PostDataModel model = item.MapTo<PostDataModel>();
  655. model.PostDate = item.pd.ToString("yyyy-MM-dd HH:mm");
  656. model.ModifyDate = item.md.ToString("yyyy-MM-dd HH:mm");
  657. model.Status = item.stat.GetDisplay();
  658. model.ModifyCount = item.ModifyCount;
  659. list.Add(model);
  660. });
  661. var pageCount = Math.Ceiling(total * 1.0 / size).ToInt32();
  662. return PageResult(list, pageCount, total);
  663. }
  664. /// <summary>
  665. /// 获取未审核文章
  666. /// </summary>
  667. /// <param name="page"></param>
  668. /// <param name="size"></param>
  669. /// <param name="search"></param>
  670. /// <returns></returns>
  671. [Authority]
  672. public ActionResult GetPending(int page = 1, int size = 10, string search = "")
  673. {
  674. int total;
  675. IQueryable<Post> temp;
  676. if (string.IsNullOrEmpty(search))
  677. {
  678. temp = PostService.LoadPageEntitiesNoTracking(page, size, out total, p => p.Status == Status.Pending, p => p.Id);
  679. }
  680. else
  681. {
  682. temp = PostService.LoadPageEntitiesNoTracking(page, size, out total, p => p.Status == Status.Pending && (p.Title.Contains(search) || p.Author.Contains(search) || p.Email.Contains(search) || p.Label.Contains(search)), p => p.Id);
  683. }
  684. var plist = temp.OrderByDescending(p => p.IsFixedTop).ThenByDescending(p => p.ModifyDate).Select(p => new
  685. {
  686. p.Id,
  687. p.Author,
  688. CategoryName = p.Category.Name,
  689. p.Email,
  690. p.IsFixedTop,
  691. p.Label,
  692. md = p.ModifyDate,
  693. pd = p.PostDate,
  694. p.Title,
  695. ViewCount = p.TotalViewCount,
  696. p.VoteDownCount,
  697. p.VoteUpCount,
  698. stat = p.Status
  699. }).ToList();
  700. var list = new List<PostDataModel>();
  701. plist.ForEach(item =>
  702. {
  703. PostDataModel model = item.MapTo<PostDataModel>();
  704. model.PostDate = item.pd.ToString("yyyy-MM-dd HH:mm");
  705. model.ModifyDate = item.md.ToString("yyyy-MM-dd HH:mm");
  706. model.Status = item.stat.GetDisplay();
  707. list.Add(model);
  708. });
  709. var pageCount = Math.Ceiling(total * 1.0 / size).ToInt32();
  710. return PageResult(list, pageCount, total);
  711. }
  712. /// <summary>
  713. /// 编辑
  714. /// </summary>
  715. /// <param name="post"></param>
  716. /// <param name="notify"></param>
  717. /// <param name="reserve"></param>
  718. /// <returns></returns>
  719. [HttpPost, Authority]
  720. public ActionResult Edit(PostInputDto post, bool notify = true, bool reserve = true)
  721. {
  722. post.Content = CommonHelper.ReplaceImgSrc(Regex.Replace(post.Content.Trim(), @"<img\s+[^>]*\s*src\s*=\s*['""]?(\S+\.\w{3,4})['""]?[^/>]*/>", "<img src=\"$1\"/>")).Replace("/thumb150/", "/large/");
  723. if (!CategoryService.Any(c => c.Id == post.CategoryId && c.Status == Status.Available))
  724. {
  725. return ResultData(null, message: "请选择一个分类");
  726. }
  727. if (string.IsNullOrEmpty(post.Label?.Trim()) || post.Label.Equals("null"))
  728. {
  729. post.Label = null;
  730. }
  731. else if (post.Label.Trim().Length > 50)
  732. {
  733. post.Label = post.Label.Replace(",", ",");
  734. post.Label = post.Label.Trim().Substring(0, 50);
  735. }
  736. else
  737. {
  738. post.Label = post.Label.Replace(",", ",");
  739. }
  740. if (!post.IsWordDocument)
  741. {
  742. post.ResourceName = null;
  743. }
  744. if (string.IsNullOrEmpty(post.ProtectContent) || post.ProtectContent.Equals("null", StringComparison.InvariantCultureIgnoreCase))
  745. {
  746. post.ProtectContent = null;
  747. }
  748. Post p = PostService.GetById(post.Id);
  749. if (reserve)
  750. {
  751. post.ModifyDate = DateTime.Now;
  752. var history = p.Mapper<PostHistoryVersion>();
  753. history.Id = 0;
  754. p.PostHistoryVersion.Add(history);
  755. }
  756. p.IP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
  757. Mapper.Map(post, p);
  758. if (!string.IsNullOrEmpty(post.Seminars))
  759. {
  760. var tmp = post.Seminars.Split(',').Distinct();
  761. p.Seminar.Clear();
  762. tmp.ForEach(s =>
  763. {
  764. Seminar seminar = SeminarService.GetFirstEntity(e => e.Title.Equals(s));
  765. p.Seminar.Add(new SeminarPost()
  766. {
  767. Post = p,
  768. Seminar = seminar,
  769. PostId = p.Id,
  770. SeminarId = seminar.Id
  771. });
  772. });
  773. }
  774. bool b = PostService.UpdateEntitySaved(p);
  775. if (b)
  776. {
  777. #if !DEBUG
  778. if (notify && "false" == CommonHelper.SystemSettings["DisabledEmailBroadcast"])
  779. {
  780. var cast = BroadcastService.LoadEntities(c => c.Status == Status.Subscribed).ToList();
  781. string link = Request.Scheme + "://" + Request.Host + "/" + p.Id;
  782. cast.ForEach(c =>
  783. {
  784. var ts = DateTime.Now.GetTotalMilliseconds();
  785. string content = System.IO.File.ReadAllText(Path.Combine(_hostingEnvironment.WebRootPath, "template", "broadcast.html"))
  786. .Replace("{{link}}", link + "?email=" + c.Email)
  787. .Replace("{{time}}", post.ModifyDate.ToString("yyyy-MM-dd HH:mm:ss"))
  788. .Replace("{{title}}", post.Title)
  789. .Replace("{{author}}", post.Author)
  790. .Replace("{{content}}", post.Content.RemoveHtmlTag(150))
  791. .Replace("{{cancel}}", Url.Action("Subscribe", "Subscribe", new
  792. {
  793. c.Email,
  794. act = "cancel",
  795. validate = c.ValidateCode,
  796. timespan = ts,
  797. hash = (c.Email + "cancel" + c.ValidateCode + ts).AESEncrypt(AppConfig.BaiduAK)
  798. }, Request.Scheme));
  799. BackgroundJob.Schedule(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "博客有新文章发布了", content, c.Email), (p.ModifyDate - DateTime.Now));
  800. });
  801. }
  802. #endif
  803. return ResultData(p.Mapper<PostOutputDto>(), message: "文章修改成功!");
  804. }
  805. return ResultData(null, false, "文章修改失败!");
  806. }
  807. /// <summary>
  808. /// 发布
  809. /// </summary>
  810. /// <param name="post"></param>
  811. /// <param name="timespan"></param>
  812. /// <param name="schedule"></param>
  813. /// <returns></returns>
  814. [Authority, HttpPost]
  815. public ActionResult Write(PostInputDto post, DateTime? timespan, bool schedule = false)
  816. {
  817. post.Content = CommonHelper.ReplaceImgSrc(Regex.Replace(post.Content.Trim(), @"<img\s+[^>]*\s*src\s*=\s*['""]?(\S+\.\w{3,4})['""]?[^/>]*/>", "<img src=\"$1\"/>")).Replace("/thumb150/", "/large/"); //提取img标签,提取src属性并重新创建个只包含src属性的img标签
  818. if (!CategoryService.Any(c => c.Id == post.CategoryId && c.Status == Status.Available))
  819. {
  820. return ResultData(null, message: "请选择一个分类");
  821. }
  822. if (string.IsNullOrEmpty(post.Label?.Trim()) || post.Label.Equals("null"))
  823. {
  824. post.Label = null;
  825. }
  826. else if (post.Label.Trim().Length > 50)
  827. {
  828. post.Label = post.Label.Replace(",", ",");
  829. post.Label = post.Label.Trim().Substring(0, 50);
  830. }
  831. else
  832. {
  833. post.Label = post.Label.Replace(",", ",");
  834. }
  835. if (!post.IsWordDocument)
  836. {
  837. post.ResourceName = null;
  838. }
  839. if (string.IsNullOrEmpty(post.ProtectContent) || post.ProtectContent.Equals("null", StringComparison.InvariantCultureIgnoreCase))
  840. {
  841. post.ProtectContent = null;
  842. }
  843. post.Status = Status.Pended;
  844. post.PostDate = DateTime.Now;
  845. post.ModifyDate = DateTime.Now;
  846. Post p = post.Mapper<Post>();
  847. p.IP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
  848. if (!string.IsNullOrEmpty(post.Seminars))
  849. {
  850. var tmp = post.Seminars.Split(',').Distinct();
  851. tmp.ForEach(s =>
  852. {
  853. var id = s.ToInt32();
  854. Seminar seminar = SeminarService.GetById(id);
  855. p.Seminar.Add(new SeminarPost()
  856. {
  857. Post = p,
  858. PostId = p.Id,
  859. Seminar = seminar,
  860. SeminarId = seminar.Id
  861. });
  862. });
  863. }
  864. p.PostAccessRecord.Add(new PostAccessRecord()
  865. {
  866. AccessTime = DateTime.Today,
  867. ClickCount = 0
  868. });
  869. if (schedule)
  870. {
  871. if (timespan.HasValue && timespan.Value > DateTime.Now)
  872. {
  873. p.Status = Status.Schedule;
  874. p.PostDate = timespan.Value;
  875. p.ModifyDate = timespan.Value;
  876. HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.PublishPost), args: p);
  877. return ResultData(p.Mapper<PostOutputDto>(), message: schedule ? $"文章于{timespan.Value:yyyy-MM-dd HH:mm:ss}将会自动发表!" : "文章发表成功!");
  878. }
  879. return ResultData(null, false, "如果要定时发布,请选择正确的一个将来时间点!");
  880. }
  881. bool b = PostService.AddEntitySaved(p) != null;
  882. if (b)
  883. {
  884. if ("false" == CommonHelper.SystemSettings["DisabledEmailBroadcast"])
  885. {
  886. var cast = BroadcastService.LoadEntities(c => c.Status == Status.Subscribed).ToList();
  887. string link = Request.Scheme + "://" + Request.Host + "/" + p.Id;
  888. cast.ForEach(c =>
  889. {
  890. var ts = DateTime.Now.GetTotalMilliseconds();
  891. string content = System.IO.File.ReadAllText(_hostingEnvironment.WebRootPath + "/template/broadcast.html").Replace("{{link}}", link + "?email=" + c.Email).Replace("{{time}}", post.ModifyDate.ToString("yyyy-MM-dd HH:mm:ss")).Replace("{{title}}", post.Title).Replace("{{author}}", post.Author).Replace("{{content}}", post.Content.RemoveHtmlTag(150)).Replace("{{cancel}}", Url.Action("Subscribe", "Subscribe", new
  892. {
  893. c.Email,
  894. act = "cancel",
  895. validate = c.ValidateCode,
  896. timespan = ts,
  897. hash = (c.Email + "cancel" + c.ValidateCode + ts).AESEncrypt(AppConfig.BaiduAK)
  898. }, Request.Scheme));
  899. BackgroundJob.Schedule(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "博客有新文章发布了", content, c.Email), (p.ModifyDate - DateTime.Now));
  900. });
  901. }
  902. return ResultData(null, true, "文章发表成功!");
  903. }
  904. return ResultData(null, false, "文章发表失败!");
  905. }
  906. /// <summary>
  907. /// 添加专题
  908. /// </summary>
  909. /// <param name="id"></param>
  910. /// <param name="sid"></param>
  911. /// <returns></returns>
  912. [Authority]
  913. public ActionResult AddSeminar(int id, int sid)
  914. {
  915. var post = PostService.GetById(id);
  916. Seminar seminar = SeminarService.GetById(sid);
  917. post.Seminar.Add(new SeminarPost()
  918. {
  919. Post = post,
  920. Seminar = seminar,
  921. SeminarId = seminar.Id,
  922. PostId = post.Id
  923. });
  924. bool b = PostService.UpdateEntitySaved(post);
  925. return ResultData(null, b, b ? $"已将文章【{post.Title}】添加到专题【{seminar.Title}】" : "添加失败");
  926. }
  927. /// <summary>
  928. /// 移除专题
  929. /// </summary>
  930. /// <param name="id"></param>
  931. /// <param name="sid"></param>
  932. /// <returns></returns>
  933. [Authority]
  934. public ActionResult RemoveSeminar(int id, int sid)
  935. {
  936. var post = PostService.GetById(id);
  937. Seminar seminar = SeminarService.GetById(sid);
  938. post.Seminar.Remove(new SeminarPost()
  939. {
  940. Post = post,
  941. Seminar = seminar,
  942. SeminarId = seminar.Id,
  943. PostId = post.Id
  944. });
  945. bool b = PostService.UpdateEntitySaved(post);
  946. return ResultData(null, b, b ? $"已将文章【{post.Title}】从【{seminar.Title}】专题移除" : "添加失败");
  947. }
  948. /// <summary>
  949. /// 删除历史版本
  950. /// </summary>
  951. /// <param name="id"></param>
  952. /// <returns></returns>
  953. [Authority]
  954. public ActionResult DeleteHistory(int id)
  955. {
  956. bool b = PostHistoryVersionService.DeleteByIdSaved(id);
  957. return ResultData(null, b, b ? "历史版本文章删除成功!" : "历史版本文章删除失败!");
  958. }
  959. /// <summary>
  960. /// 获取文章访问密码
  961. /// </summary>
  962. /// <returns></returns>
  963. [Authority, HttpPost]
  964. public ActionResult ViewToken()
  965. {
  966. if (!RedisHelper.Exists("ArticleViewToken"))
  967. {
  968. RedisHelper.Set("ArticleViewToken", SnowFlake.GetInstance().GetUniqueShortId(6));
  969. }
  970. var token = RedisHelper.Get("ArticleViewToken");
  971. return ResultData(token);
  972. }
  973. /// <summary>
  974. /// 还原版本
  975. /// </summary>
  976. /// <param name="id"></param>
  977. /// <returns></returns>
  978. public ActionResult Revert(int id)
  979. {
  980. var history = PostHistoryVersionService.GetById(id);
  981. if (history != null)
  982. {
  983. //var version = history.Post.Mapper<PostHistoryVersion>();
  984. //version.Id = 0;
  985. //PostHistoryVersionService.AddEntity(version);
  986. history.Post.Category = history.Category;
  987. history.Post.CategoryId = history.CategoryId;
  988. history.Post.Content = history.Content;
  989. history.Post.Title = history.Title;
  990. history.Post.Label = history.Label;
  991. history.Post.Seminar.Clear();
  992. foreach (var s in history.Seminar)
  993. {
  994. history.Post.Seminar.Add(new SeminarPost()
  995. {
  996. Post = history.Post,
  997. PostId = history.PostId,
  998. Seminar = s.Seminar,
  999. SeminarId = s.SeminarId
  1000. });
  1001. }
  1002. history.Post.ModifyDate = history.ModifyDate;
  1003. bool b = PostHistoryVersionService.UpdateEntitySaved(history);
  1004. PostHistoryVersionService.DeleteByIdSaved(id);
  1005. return ResultData(null, b, b ? "回滚成功" : "回滚失败");
  1006. }
  1007. return ResultData(null, false, "版本不存在");
  1008. }
  1009. /// <summary>
  1010. /// 文章分析
  1011. /// </summary>
  1012. /// <param name="id"></param>
  1013. /// <returns></returns>
  1014. [HttpPost]
  1015. public ActionResult Analyse(int id)
  1016. {
  1017. var list = PostService.GetById(id).PostAccessRecord.OrderBy(r => r.AccessTime).GroupBy(r => r.AccessTime.Date).Select(r => new[]
  1018. {
  1019. r.Key.GetTotalMilliseconds(),
  1020. r.Sum(p => p.ClickCount)
  1021. }).ToList();
  1022. var high = list.OrderByDescending(n => n[1]).FirstOrDefault();
  1023. var average = list.Average(d => d[1]);
  1024. return ResultData(new
  1025. {
  1026. list,
  1027. aver = average,
  1028. high = high[1],
  1029. highDate = DateTime.Parse("1970-01-01").AddMilliseconds(high[0])
  1030. });
  1031. }
  1032. #endregion
  1033. }
  1034. }