PostController.cs 42 KB

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