CommonHelper.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. using AutoMapper;
  2. using HtmlAgilityPack;
  3. using IP2Region;
  4. using Masuit.Tools;
  5. using Microsoft.AspNetCore.Http;
  6. using Microsoft.Extensions.DependencyInjection;
  7. using Microsoft.Net.Http.Headers;
  8. using System;
  9. using System.Collections.Concurrent;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Net;
  14. using System.Text;
  15. using System.Threading;
  16. #if !DEBUG
  17. using Masuit.MyBlogs.Core.Models.ViewModel;
  18. using Masuit.Tools.Models;
  19. #endif
  20. namespace Masuit.MyBlogs.Core.Common
  21. {
  22. /// <summary>
  23. /// 公共类库
  24. /// </summary>
  25. public static class CommonHelper
  26. {
  27. static CommonHelper()
  28. {
  29. ThreadPool.QueueUserWorkItem(s =>
  30. {
  31. while (true)
  32. {
  33. BanRegex = File.ReadAllText(Path.Combine(AppContext.BaseDirectory + "App_Data", "ban.txt"), Encoding.UTF8);
  34. ModRegex = File.ReadAllText(Path.Combine(AppContext.BaseDirectory + "App_Data", "mod.txt"), Encoding.UTF8);
  35. DenyIP = File.ReadAllText(Path.Combine(AppContext.BaseDirectory + "App_Data", "denyip.txt"), Encoding.UTF8);
  36. string[] lines = File.ReadAllLines(Path.Combine(AppContext.BaseDirectory + "App_Data", "DenyIPRange.txt"), Encoding.UTF8);
  37. DenyIPRange = new Dictionary<string, string>();
  38. foreach (string line in lines)
  39. {
  40. try
  41. {
  42. var strs = line.Split(' ');
  43. DenyIPRange[strs[0]] = strs[1];
  44. }
  45. catch (IndexOutOfRangeException)
  46. {
  47. }
  48. }
  49. IPWhiteList = File.ReadAllText(Path.Combine(AppContext.BaseDirectory + "App_Data", "whitelist.txt")).Split(',', ',').ToList();
  50. Console.WriteLine("刷新公共数据...");
  51. Thread.Sleep(TimeSpan.FromMinutes(10));
  52. }
  53. });
  54. }
  55. /// <summary>
  56. /// 敏感词
  57. /// </summary>
  58. public static string BanRegex { get; set; }
  59. /// <summary>
  60. /// 审核词
  61. /// </summary>
  62. public static string ModRegex { get; set; }
  63. /// <summary>
  64. /// 全局禁止IP
  65. /// </summary>
  66. public static string DenyIP { get; set; }
  67. /// <summary>
  68. /// ip白名单
  69. /// </summary>
  70. public static List<string> IPWhiteList { get; set; }
  71. /// <summary>
  72. /// 每IP错误的次数统计
  73. /// </summary>
  74. public static ConcurrentDictionary<string, int> IPErrorTimes { get; set; } = new ConcurrentDictionary<string, int>();
  75. /// <summary>
  76. /// 系统设定
  77. /// </summary>
  78. public static ConcurrentDictionary<string, string> SystemSettings { get; set; } = new ConcurrentDictionary<string, string>();
  79. /// <summary>
  80. /// 访问量
  81. /// </summary>
  82. public static double InterviewCount
  83. {
  84. get
  85. {
  86. try
  87. {
  88. return RedisHelper.Get<double>("Interview:ViewCount");
  89. }
  90. catch
  91. {
  92. return 1;
  93. }
  94. }
  95. set => RedisHelper.IncrBy("Interview:ViewCount");
  96. }
  97. /// <summary>
  98. /// 平均访问量
  99. /// </summary>
  100. public static double AverageCount
  101. {
  102. get
  103. {
  104. try
  105. {
  106. return RedisHelper.Get<double>("Interview:ViewCount") / RedisHelper.Get<double>("Interview:RunningDays");
  107. }
  108. catch
  109. {
  110. return 1;
  111. }
  112. }
  113. }
  114. /// <summary>
  115. /// 网站启动时间
  116. /// </summary>
  117. public static DateTime StartupTime { get; set; } = DateTime.Now;
  118. /// <summary>
  119. /// IP黑名单地址段
  120. /// </summary>
  121. public static Dictionary<string, string> DenyIPRange { get; set; }
  122. /// <summary>
  123. /// 判断IP地址是否被黑名单
  124. /// </summary>
  125. /// <param name="ip"></param>
  126. /// <returns></returns>
  127. public static bool IsDenyIpAddress(this string ip)
  128. {
  129. if (IPWhiteList.Contains(ip))
  130. {
  131. return false;
  132. }
  133. var denyed = DenyIP.Contains(ip) || DenyIPRange.AsParallel().Any(kv => kv.Key.StartsWith(ip.Split('.')[0]) && ip.IpAddressInRange(kv.Key, kv.Value));
  134. if (SystemSettings.GetOrAdd("EnableDenyArea", "false") == "false")
  135. {
  136. return denyed;
  137. }
  138. var pos = GetIPLocation(ip);
  139. var denyAreas = SystemSettings.GetOrAdd("DenyArea", "").Split(',', ',');
  140. return denyed || pos.Contains(denyAreas) || denyAreas.Intersect(pos.Split("|")).Any();
  141. }
  142. public static string GetIPLocation(this IPAddress ip) => GetIPLocation(ip.MapToIPv4().ToString());
  143. public static string GetIPLocation(this string ip)
  144. {
  145. using var searcher = new DbSearcher(Path.Combine(AppContext.BaseDirectory + "App_Data", "ip2region.db"));
  146. return searcher.MemorySearch(ip).Region;
  147. }
  148. /// <summary>
  149. /// 类型映射
  150. /// </summary>
  151. /// <typeparam name="T"></typeparam>
  152. /// <param name="source"></param>
  153. /// <returns></returns>
  154. public static T Mapper<T>(this object source) where T : class => Startup.ServiceProvider.GetRequiredService<IMapper>().Map<T>(source);
  155. /// <summary>
  156. /// 发送邮件
  157. /// </summary>
  158. /// <param name="title">标题</param>
  159. /// <param name="content">内容</param>
  160. /// <param name="tos">收件人</param>
  161. public static void SendMail(string title, string content, string tos)
  162. {
  163. #if !DEBUG
  164. new Email()
  165. {
  166. EnableSsl = true,
  167. Body = content,
  168. SmtpServer = EmailConfig.Smtp,
  169. Username = EmailConfig.SendFrom,
  170. Password = EmailConfig.EmailPwd,
  171. SmtpPort = SystemSettings["SmtpPort"].ToInt32(),
  172. Subject = title,
  173. Tos = tos
  174. }.Send();
  175. #endif
  176. }
  177. /// <summary>
  178. /// 是否是机器人访问
  179. /// </summary>
  180. /// <param name="req"></param>
  181. /// <returns></returns>
  182. public static bool IsRobot(this HttpRequest req)
  183. {
  184. return req.Headers[HeaderNames.UserAgent].ToString().Contains(new[]
  185. {
  186. "DNSPod",
  187. "Baidu",
  188. "spider",
  189. "Python",
  190. "bot"
  191. });
  192. }
  193. /// <summary>
  194. /// 清理html的img标签的除src之外的其他属性
  195. /// </summary>
  196. /// <param name="html"></param>
  197. /// <returns></returns>
  198. public static string ClearImgAttributes(this string html)
  199. {
  200. var doc = new HtmlDocument();
  201. doc.LoadHtml(html);
  202. var nodes = doc.DocumentNode.Descendants("img");
  203. foreach (var node in nodes)
  204. {
  205. string src = "";
  206. if (node.Attributes.Contains("data-original"))
  207. {
  208. src = node.Attributes["data-original"].Value;
  209. }
  210. if (node.Attributes.Contains("src"))
  211. {
  212. src = node.Attributes["src"].Value;
  213. }
  214. node.Attributes.RemoveAll();
  215. node.Attributes.Add("src", src);
  216. }
  217. return doc.DocumentNode.OuterHtml;
  218. }
  219. /// <summary>
  220. /// 将html的img标签的src属性名替换成data-original
  221. /// </summary>
  222. /// <param name="html"></param>
  223. /// <returns></returns>
  224. public static string ReplaceImgAttribute(this string html)
  225. {
  226. var doc = new HtmlDocument();
  227. doc.LoadHtml(html);
  228. var nodes = doc.DocumentNode.Descendants("img");
  229. foreach (var node in nodes)
  230. {
  231. if (node.Attributes.Contains("src"))
  232. {
  233. string src = node.Attributes["src"].Value;
  234. node.Attributes.Remove("src");
  235. node.Attributes.Add("data-original", src);
  236. }
  237. }
  238. return doc.DocumentNode.OuterHtml;
  239. }
  240. }
  241. }