PostController.cs 42 KB

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