SearchController.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. using Common;
  2. using Masuit.LuceneEFCore.SearchEngine.Interfaces;
  3. using Masuit.MyBlogs.Core.Extensions;
  4. using Masuit.MyBlogs.Core.Infrastructure.Application;
  5. using Masuit.MyBlogs.Core.Infrastructure.Services.Interface;
  6. using Masuit.MyBlogs.Core.Models.DTO;
  7. using Masuit.MyBlogs.Core.Models.Entity;
  8. using Masuit.Tools;
  9. using Masuit.Tools.Core.Net;
  10. using Masuit.Tools.NoSQL;
  11. using Microsoft.AspNetCore.Mvc;
  12. using Microsoft.Net.Http.Headers;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Linq;
  16. using System.Linq.Expressions;
  17. using System.Text.RegularExpressions;
  18. namespace Masuit.MyBlogs.Core.Controllers
  19. {
  20. /// <summary>
  21. /// 站内搜索
  22. /// </summary>
  23. public class SearchController : BaseController
  24. {
  25. /// <summary>
  26. ///
  27. /// </summary>
  28. public ISearchDetailsService SearchDetailsService { get; set; }
  29. private readonly IPostService _postService;
  30. private readonly ISearchEngine<DataContext> _searchEngine;
  31. /// <summary>
  32. /// 站内搜索
  33. /// </summary>
  34. /// <param name="searchDetailsService"></param>
  35. /// <param name="postService"></param>
  36. /// <param name="searchEngine"></param>
  37. public SearchController(ISearchDetailsService searchDetailsService, IPostService postService, ISearchEngine<DataContext> searchEngine)
  38. {
  39. SearchDetailsService = searchDetailsService;
  40. _postService = postService;
  41. _searchEngine = searchEngine;
  42. }
  43. /// <summary>
  44. /// 搜索页
  45. /// </summary>
  46. /// <param name="wd"></param>
  47. /// <param name="page"></param>
  48. /// <param name="size"></param>
  49. /// <returns></returns>
  50. [Route("s/{wd?}/{page:int?}/{size:int?}"), ResponseCache(VaryByQueryKeys = new[] { "wd", "page", "size" }, VaryByHeader = HeaderNames.Cookie, Duration = 600)]
  51. public ActionResult Search(string wd = "", int page = 1, int size = 10)
  52. {
  53. var nul = new List<PostOutputDto>();
  54. ViewBag.Elapsed = 0;
  55. ViewBag.Total = 0;
  56. ViewBag.Keyword = wd;
  57. if (Regex.Match(wd ?? "", CommonHelper.BanRegex + "|" + CommonHelper.ModRegex).Length > 0)
  58. {
  59. return RedirectToAction("Search");
  60. }
  61. var start = DateTime.Today.AddDays(-7);
  62. using (RedisHelper redisHelper = RedisHelper.GetInstance())
  63. {
  64. string key = HttpContext.Connection.Id;
  65. if (redisHelper.KeyExists(key) && !redisHelper.GetString(key).Equals(wd))
  66. {
  67. var hotSearches = SearchDetailsService.LoadEntitiesFromL2CacheNoTracking(s => s.SearchTime > start, s => s.SearchTime, false).GroupBy(s => s.KeyWords.ToLower()).OrderByDescending(g => g.Count()).Take(7).Select(g => new KeywordsRankOutputDto()
  68. {
  69. KeyWords = g.First().KeyWords,
  70. SearchCount = g.Count()
  71. }).ToList();
  72. ViewBag.hotSearches = hotSearches;
  73. ViewBag.ErrorMsg = "10秒内只能搜索1次!";
  74. return View(nul);
  75. }
  76. wd = wd.Trim().Replace("+", " ");
  77. if (!string.IsNullOrWhiteSpace(wd) && !wd.Contains("锟斤拷"))
  78. {
  79. if (!HttpContext.Session.TryGetValue("search:" + wd, out _) && !HttpContext.Request.IsRobot())
  80. {
  81. SearchDetailsService.AddEntity(new SearchDetails
  82. {
  83. KeyWords = wd,
  84. SearchTime = DateTime.Now,
  85. IP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString()
  86. });
  87. HttpContext.Session.Set("search:" + wd, wd);
  88. }
  89. var posts = _postService.SearchPage(page, size, wd);
  90. ViewBag.Elapsed = posts.Elapsed;
  91. ViewBag.Total = posts.Total;
  92. SearchDetailsService.SaveChanges();
  93. if (posts.Total > 1)
  94. {
  95. redisHelper.SetString(key, wd, TimeSpan.FromSeconds(10));
  96. }
  97. ViewBag.hotSearches = new List<KeywordsRankOutputDto>();
  98. return View(posts.Results);
  99. }
  100. ViewBag.hotSearches = SearchDetailsService.LoadEntitiesFromL2CacheNoTracking(s => s.SearchTime > start, s => s.SearchTime, false).GroupBy(s => s.KeyWords.ToLower()).OrderByDescending(g => g.Count()).Take(7).Select(g => new KeywordsRankOutputDto()
  101. {
  102. KeyWords = g.FirstOrDefault().KeyWords,
  103. SearchCount = g.Count()
  104. }).ToList();
  105. return View(nul);
  106. }
  107. }
  108. /// <summary>
  109. /// 关键词推荐
  110. /// </summary>
  111. /// <param name="page"></param>
  112. /// <param name="size"></param>
  113. /// <param name="search"></param>
  114. /// <returns></returns>
  115. [Authority, HttpPost, ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "page", "size", "search" }, VaryByHeader = HeaderNames.Cookie)]
  116. public ActionResult SearchList(int page = 1, int size = 10, string search = "")
  117. {
  118. if (page <= 0)
  119. {
  120. page = 1;
  121. }
  122. var where = string.IsNullOrEmpty(search) ? (Expression<Func<SearchDetails, bool>>)(s => true) : s => s.KeyWords.Contains(search);
  123. var list = SearchDetailsService.LoadPageEntities<DateTime, SearchDetailsOutputDto>(page, size, out int total, where, s => s.SearchTime, false).ToList();
  124. var pageCount = Math.Ceiling(total * 1.0 / size).ToInt32();
  125. return PageResult(list, pageCount, total);
  126. }
  127. /// <summary>
  128. /// 热词
  129. /// </summary>
  130. /// <returns></returns>
  131. [Authority, HttpPost, ResponseCache(Duration = 600, VaryByHeader = HeaderNames.Cookie)]
  132. public ActionResult HotKey()
  133. {
  134. var start = DateTime.Today.AddMonths(-1);
  135. var temp = SearchDetailsService.LoadEntitiesNoTracking(s => s.SearchTime > start, s => s.SearchTime, false).ToList();
  136. var month = temp.GroupBy(s => s.KeyWords.ToLower()).OrderByDescending(g => g.Count()).Take(30).Select(g => new
  137. {
  138. Keywords = g.FirstOrDefault().KeyWords,
  139. Count = g.Count()
  140. }).ToList();
  141. var week = temp.Where(s => s.SearchTime > DateTime.Today.AddDays(-7)).GroupBy(s => s.KeyWords.ToLower()).OrderByDescending(g => g.Count()).Take(30).Select(g => new
  142. {
  143. Keywords = g.FirstOrDefault().KeyWords,
  144. Count = g.Count()
  145. }).ToList();
  146. var today = temp.Where(s => s.SearchTime > DateTime.Today).GroupBy(s => s.KeyWords.ToLower()).OrderByDescending(g => g.Count()).Take(30).Select(g => new
  147. {
  148. Keywords = g.FirstOrDefault().KeyWords,
  149. Count = g.Count()
  150. }).ToList();
  151. return ResultData(new
  152. {
  153. month,
  154. week,
  155. today
  156. });
  157. }
  158. /// <summary>
  159. /// 删除搜索记录
  160. /// </summary>
  161. /// <param name="id"></param>
  162. /// <returns></returns>
  163. [HttpPost, Authority]
  164. public ActionResult Delete(int id)
  165. {
  166. bool b = SearchDetailsService.DeleteByIdSaved(id);
  167. return ResultData(null, b, b ? "删除成功!" : "删除失败!");
  168. }
  169. }
  170. }