PostController.cs 43 KB

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