PostController.cs 41 KB

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