CommonHelper.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. using AutoMapper;
  2. using HtmlAgilityPack;
  3. using IP2Region;
  4. using Masuit.Tools;
  5. using Masuit.Tools.Media;
  6. using Microsoft.AspNetCore.Http;
  7. using Microsoft.EntityFrameworkCore.Internal;
  8. using Microsoft.Extensions.DependencyInjection;
  9. using Microsoft.Net.Http.Headers;
  10. using System;
  11. using System.Collections.Concurrent;
  12. using System.Collections.Generic;
  13. using System.Drawing;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Net;
  17. using System.Text;
  18. using System.Threading;
  19. #if !DEBUG
  20. #endif
  21. namespace Masuit.MyBlogs.Core.Common
  22. {
  23. /// <summary>
  24. /// 公共类库
  25. /// </summary>
  26. public static class CommonHelper
  27. {
  28. static CommonHelper()
  29. {
  30. ThreadPool.QueueUserWorkItem(s =>
  31. {
  32. while (true)
  33. {
  34. BanRegex = File.ReadAllText(Path.Combine(AppContext.BaseDirectory + "App_Data", "ban.txt"), Encoding.UTF8);
  35. ModRegex = File.ReadAllText(Path.Combine(AppContext.BaseDirectory + "App_Data", "mod.txt"), Encoding.UTF8);
  36. DenyIP = File.ReadAllText(Path.Combine(AppContext.BaseDirectory + "App_Data", "denyip.txt"), Encoding.UTF8);
  37. string[] lines = File.ReadAllLines(Path.Combine(AppContext.BaseDirectory + "App_Data", "DenyIPRange.txt"), Encoding.UTF8);
  38. DenyIPRange = new Dictionary<string, string>();
  39. foreach (string line in lines)
  40. {
  41. try
  42. {
  43. var strs = line.Split(' ');
  44. DenyIPRange[strs[0]] = strs[1];
  45. }
  46. catch (IndexOutOfRangeException)
  47. {
  48. }
  49. }
  50. IPWhiteList = File.ReadAllText(Path.Combine(AppContext.BaseDirectory + "App_Data", "whitelist.txt")).Split(',', ',').ToList();
  51. Console.WriteLine("刷新公共数据...");
  52. Thread.Sleep(TimeSpan.FromMinutes(10));
  53. }
  54. });
  55. }
  56. /// <summary>
  57. /// 敏感词
  58. /// </summary>
  59. public static string BanRegex { get; set; }
  60. /// <summary>
  61. /// 审核词
  62. /// </summary>
  63. public static string ModRegex { get; set; }
  64. /// <summary>
  65. /// 全局禁止IP
  66. /// </summary>
  67. public static string DenyIP { get; set; }
  68. /// <summary>
  69. /// ip白名单
  70. /// </summary>
  71. public static List<string> IPWhiteList { get; set; }
  72. /// <summary>
  73. /// 每IP错误的次数统计
  74. /// </summary>
  75. public static ConcurrentDictionary<string, int> IPErrorTimes { get; set; } = new ConcurrentDictionary<string, int>();
  76. /// <summary>
  77. /// 系统设定
  78. /// </summary>
  79. public static ConcurrentDictionary<string, string> SystemSettings { get; set; } = new ConcurrentDictionary<string, string>();
  80. /// <summary>
  81. /// 访问量
  82. /// </summary>
  83. public static double InterviewCount
  84. {
  85. get
  86. {
  87. try
  88. {
  89. return RedisHelper.Get<double>("Interview:ViewCount");
  90. }
  91. catch
  92. {
  93. return 1;
  94. }
  95. }
  96. set => RedisHelper.IncrBy("Interview:ViewCount");
  97. }
  98. /// <summary>
  99. /// 平均访问量
  100. /// </summary>
  101. public static double AverageCount
  102. {
  103. get
  104. {
  105. try
  106. {
  107. return RedisHelper.Get<double>("Interview:ViewCount") / RedisHelper.Get<double>("Interview:RunningDays");
  108. }
  109. catch
  110. {
  111. return 1;
  112. }
  113. }
  114. }
  115. /// <summary>
  116. /// 网站启动时间
  117. /// </summary>
  118. public static DateTime StartupTime { get; set; } = DateTime.Now;
  119. /// <summary>
  120. /// IP黑名单地址段
  121. /// </summary>
  122. public static Dictionary<string, string> DenyIPRange { get; set; }
  123. /// <summary>
  124. /// 判断IP地址是否被黑名单
  125. /// </summary>
  126. /// <param name="ip"></param>
  127. /// <returns></returns>
  128. public static bool IsDenyIpAddress(this string ip)
  129. {
  130. if (IPWhiteList.Contains(ip))
  131. {
  132. return false;
  133. }
  134. return DenyIP.Contains(ip) || DenyIPRange.AsParallel().Any(kv => kv.Key.StartsWith(ip.Split('.')[0]) && ip.IpAddressInRange(kv.Key, kv.Value));
  135. }
  136. /// <summary>
  137. /// 是否是禁区
  138. /// </summary>
  139. /// <param name="ips"></param>
  140. /// <returns></returns>
  141. public static bool IsInDenyArea(this string ips)
  142. {
  143. var denyAreas = SystemSettings.GetOrAdd("DenyArea", "").Split(new[] { ',', ',' }, StringSplitOptions.RemoveEmptyEntries);
  144. if (denyAreas.Any())
  145. {
  146. foreach (var item in ips.Split(','))
  147. {
  148. var pos = GetIPLocation(item);
  149. return pos.Contains(denyAreas) || denyAreas.Intersect(pos.Split("|")).Any();
  150. }
  151. }
  152. return false;
  153. }
  154. private static readonly DbSearcher Searcher = new DbSearcher(Path.Combine(AppContext.BaseDirectory + "App_Data", "ip2region.db"));
  155. public static string GetIPLocation(this IPAddress ip) => GetIPLocation(ip.MapToIPv4().ToString());
  156. public static string GetIPLocation(this string ips)
  157. {
  158. return ips.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(s => Searcher.MemorySearch(s.Trim())?.Region).Join(" , ");
  159. }
  160. /// <summary>
  161. /// 类型映射
  162. /// </summary>
  163. /// <typeparam name="T"></typeparam>
  164. /// <param name="source"></param>
  165. /// <returns></returns>
  166. public static T Mapper<T>(this object source) where T : class => Startup.ServiceProvider.GetRequiredService<IMapper>().Map<T>(source);
  167. /// <summary>
  168. /// 发送邮件
  169. /// </summary>
  170. /// <param name="title">标题</param>
  171. /// <param name="content">内容</param>
  172. /// <param name="tos">收件人</param>
  173. public static void SendMail(string title, string content, string tos)
  174. {
  175. #if !DEBUG
  176. new Email()
  177. {
  178. EnableSsl = bool.Parse(SystemSettings.GetOrAdd("EnableSsl", "true")),
  179. Body = content,
  180. SmtpServer = SystemSettings["SMTP"],
  181. Username = SystemSettings["EmailFrom"],
  182. Password = SystemSettings["EmailPwd"],
  183. SmtpPort = SystemSettings["SmtpPort"].ToInt32(),
  184. Subject = title,
  185. Tos = tos
  186. }.Send();
  187. #endif
  188. }
  189. /// <summary>
  190. /// 是否是机器人访问
  191. /// </summary>
  192. /// <param name="req"></param>
  193. /// <returns></returns>
  194. public static bool IsRobot(this HttpRequest req)
  195. {
  196. return req.Headers[HeaderNames.UserAgent].ToString().Contains(new[]
  197. {
  198. "DNSPod",
  199. "Baidu",
  200. "spider",
  201. "Python",
  202. "bot"
  203. });
  204. }
  205. /// <summary>
  206. /// 清理html的img标签的除src之外的其他属性
  207. /// </summary>
  208. /// <param name="html"></param>
  209. /// <returns></returns>
  210. public static string ClearImgAttributes(this string html)
  211. {
  212. var doc = new HtmlDocument();
  213. doc.LoadHtml(html);
  214. var nodes = doc.DocumentNode.Descendants("img");
  215. foreach (var node in nodes)
  216. {
  217. node.Attributes.RemoveWhere(a => !new[] { "src", "data-original", "width", "style", "class" }.Contains(a.Name));
  218. }
  219. return doc.DocumentNode.OuterHtml;
  220. }
  221. /// <summary>
  222. /// 将html的img标签的src属性名替换成data-original
  223. /// </summary>
  224. /// <param name="html"></param>
  225. /// <param name="title"></param>
  226. /// <returns></returns>
  227. public static string ReplaceImgAttribute(this string html, string title)
  228. {
  229. var doc = new HtmlDocument();
  230. doc.LoadHtml(html);
  231. var nodes = doc.DocumentNode.Descendants("img");
  232. foreach (var node in nodes)
  233. {
  234. if (node.Attributes.Contains("src"))
  235. {
  236. string src = node.Attributes["src"].Value;
  237. node.Attributes.Remove("src");
  238. node.Attributes.Add("data-original", src);
  239. node.Attributes.Add("alt", SystemSettings["Title"]);
  240. node.Attributes.Add("title", title);
  241. }
  242. }
  243. return doc.DocumentNode.OuterHtml;
  244. }
  245. /// <summary>
  246. /// 获取文章摘要
  247. /// </summary>
  248. /// <param name="html"></param>
  249. /// <param name="length">截取长度</param>
  250. /// <param name="min">摘要最少字数</param>
  251. /// <returns></returns>
  252. public static string GetSummary(this string html, int length = 150, int min = 10)
  253. {
  254. var doc = new HtmlDocument();
  255. doc.LoadHtml(html);
  256. var summary = doc.DocumentNode.Descendants("p").FirstOrDefault(n => n.InnerText.Length > min)?.InnerText ?? "没有摘要";
  257. if (summary.Length > length)
  258. {
  259. return summary.Substring(0, length) + "...";
  260. }
  261. return summary;
  262. }
  263. public static string TrimQuery(this string path)
  264. {
  265. return path.Split('&').Where(s => s.Split('=', StringSplitOptions.RemoveEmptyEntries).Length == 2).Join("&");
  266. }
  267. /// <summary>
  268. /// 添加水印
  269. /// </summary>
  270. /// <param name="stream"></param>
  271. /// <returns></returns>
  272. public static Stream AddWatermark(this Stream stream)
  273. {
  274. if (!string.IsNullOrEmpty(SystemSettings.GetOrAdd("Watermark", string.Empty)))
  275. {
  276. try
  277. {
  278. var watermarker = new ImageWatermarker(stream)
  279. {
  280. SkipWatermarkForSmallImages = true,
  281. SmallImagePixelsThreshold = 40000
  282. };
  283. return watermarker.AddWatermark(SystemSettings["Watermark"], Color.LightGray, WatermarkPosition.BottomRight, 30);
  284. }
  285. catch
  286. {
  287. //
  288. }
  289. }
  290. return stream;
  291. }
  292. }
  293. }