CommonHelper.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. using AutoMapper;
  2. using Hangfire;
  3. using HtmlAgilityPack;
  4. using IP2Region;
  5. using Masuit.MyBlogs.Core.Common.Mails;
  6. using Masuit.Tools;
  7. using Masuit.Tools.Media;
  8. using MaxMind.GeoIP2;
  9. using MaxMind.GeoIP2.Exceptions;
  10. using MaxMind.GeoIP2.Responses;
  11. using Microsoft.Extensions.DependencyInjection;
  12. using Polly;
  13. using System;
  14. using System.Collections.Concurrent;
  15. using System.Collections.Generic;
  16. using System.Drawing;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Net;
  20. using System.Net.Sockets;
  21. using System.Text;
  22. using System.Threading;
  23. using TimeZoneConverter;
  24. namespace Masuit.MyBlogs.Core.Common
  25. {
  26. /// <summary>
  27. /// 公共类库
  28. /// </summary>
  29. public static class CommonHelper
  30. {
  31. static CommonHelper()
  32. {
  33. ThreadPool.QueueUserWorkItem(_ =>
  34. {
  35. while (true)
  36. {
  37. BanRegex = File.ReadAllText(Path.Combine(AppContext.BaseDirectory + "App_Data", "ban.txt"), Encoding.UTF8);
  38. ModRegex = File.ReadAllText(Path.Combine(AppContext.BaseDirectory + "App_Data", "mod.txt"), Encoding.UTF8);
  39. DenyIP = File.ReadAllText(Path.Combine(AppContext.BaseDirectory + "App_Data", "denyip.txt"), Encoding.UTF8);
  40. string[] lines = File.ReadAllLines(Path.Combine(AppContext.BaseDirectory + "App_Data", "DenyIPRange.txt"), Encoding.UTF8);
  41. DenyIPRange = new Dictionary<string, string>();
  42. foreach (string line in lines)
  43. {
  44. try
  45. {
  46. var strs = line.Split(' ');
  47. DenyIPRange[strs[0]] = strs[1];
  48. }
  49. catch (IndexOutOfRangeException)
  50. {
  51. }
  52. }
  53. IPWhiteList = File.ReadAllText(Path.Combine(AppContext.BaseDirectory + "App_Data", "whitelist.txt")).Split(',', ',').ToList();
  54. Console.WriteLine("刷新公共数据...");
  55. Thread.Sleep(TimeSpan.FromMinutes(10));
  56. }
  57. });
  58. }
  59. /// <summary>
  60. /// 敏感词
  61. /// </summary>
  62. public static string BanRegex { get; set; }
  63. /// <summary>
  64. /// 审核词
  65. /// </summary>
  66. public static string ModRegex { get; set; }
  67. /// <summary>
  68. /// 全局禁止IP
  69. /// </summary>
  70. public static string DenyIP { get; set; }
  71. /// <summary>
  72. /// ip白名单
  73. /// </summary>
  74. public static List<string> IPWhiteList { get; set; }
  75. /// <summary>
  76. /// 每IP错误的次数统计
  77. /// </summary>
  78. public static ConcurrentDictionary<string, int> IPErrorTimes { get; set; } = new();
  79. /// <summary>
  80. /// 系统设定
  81. /// </summary>
  82. public static ConcurrentDictionary<string, string> SystemSettings { get; set; } = new();
  83. /// <summary>
  84. /// 网站启动时间
  85. /// </summary>
  86. public static DateTime StartupTime { get; set; } = DateTime.Now;
  87. /// <summary>
  88. /// IP黑名单地址段
  89. /// </summary>
  90. public static Dictionary<string, string> DenyIPRange { get; set; }
  91. /// <summary>
  92. /// 判断IP地址是否被黑名单
  93. /// </summary>
  94. /// <param name="ip"></param>
  95. /// <returns></returns>
  96. public static bool IsDenyIpAddress(this string ip)
  97. {
  98. if (IPWhiteList.Contains(ip))
  99. {
  100. return false;
  101. }
  102. return DenyIP.Contains(ip) ||
  103. DenyIPRange.AsParallel().Any(kv => kv.Key.StartsWith(ip.Split('.')[0]) && ip.IpAddressInRange(kv.Key, kv.Value));
  104. }
  105. /// <summary>
  106. /// 是否是禁区
  107. /// </summary>
  108. /// <param name="ips"></param>
  109. /// <returns></returns>
  110. public static bool IsInDenyArea(this string ips)
  111. {
  112. var denyAreas = SystemSettings.GetOrAdd("DenyArea", "").Split(new[] { ',', ',' }, StringSplitOptions.RemoveEmptyEntries);
  113. if (denyAreas.Any())
  114. {
  115. foreach (var item in ips.Split(','))
  116. {
  117. var pos = GetIPLocation(item);
  118. return pos.Contains(denyAreas) || denyAreas.Intersect(pos.Split("|")).Any();
  119. }
  120. }
  121. return false;
  122. }
  123. private static readonly DbSearcher IPSearcher = new(Path.Combine(AppContext.BaseDirectory + "App_Data", "ip2region.db"));
  124. public static readonly DatabaseReader MaxmindReader = new(Path.Combine(AppContext.BaseDirectory + "App_Data", "GeoLite2-City.mmdb"));
  125. private static readonly DatabaseReader MaxmindAsnReader = new(Path.Combine(AppContext.BaseDirectory + "App_Data", "GeoLite2-ASN.mmdb"));
  126. public static AsnResponse GetIPAsn(this string ip)
  127. {
  128. if (ip.IsPrivateIP())
  129. {
  130. return new AsnResponse();
  131. }
  132. return Policy<AsnResponse>.Handle<AddressNotFoundException>().Fallback(new AsnResponse()).Execute(() => MaxmindAsnReader.Asn(ip));
  133. }
  134. public static AsnResponse GetIPAsn(this IPAddress ip)
  135. {
  136. return Policy<AsnResponse>.Handle<AddressNotFoundException>().Fallback(new AsnResponse()).Execute(() => MaxmindAsnReader.Asn(ip));
  137. }
  138. public static string GetIPLocation(this string ips)
  139. {
  140. var (location, network) = GetIPLocation(IPAddress.Parse(ips));
  141. return location + "|" + network;
  142. }
  143. public static (string location, string network) GetIPLocation(this IPAddress ip)
  144. {
  145. switch (ip.AddressFamily)
  146. {
  147. case AddressFamily.InterNetwork when ip.IsPrivateIP():
  148. case AddressFamily.InterNetworkV6 when ip.IsPrivateIP():
  149. return ("内网", "内网IP");
  150. case AddressFamily.InterNetworkV6 when ip.IsIPv4MappedToIPv6:
  151. ip = ip.MapToIPv4();
  152. goto case AddressFamily.InterNetwork;
  153. case AddressFamily.InterNetwork:
  154. var parts = IPSearcher.MemorySearch(ip.ToString())?.Region.Split('|');
  155. if (parts != null)
  156. {
  157. var asn = GetIPAsn(ip);
  158. var network = parts[^1] == "0" ? asn.AutonomousSystemOrganization : parts[^1];
  159. var location = parts[..^1].Where(s => s != "0").Distinct().Join("");
  160. return (location, network + $"(AS{asn.AutonomousSystemNumber})");
  161. }
  162. goto default;
  163. default:
  164. var cityResp = Policy<CityResponse>.Handle<AddressNotFoundException>().Fallback(new CityResponse()).Execute(() => MaxmindReader.City(ip));
  165. var asnResp = GetIPAsn(ip);
  166. return (cityResp.Country.Names.GetValueOrDefault("zh-CN") + cityResp.City.Names.GetValueOrDefault("zh-CN"), asnResp.AutonomousSystemOrganization + $"(AS{asnResp.AutonomousSystemNumber})");
  167. }
  168. }
  169. /// <summary>
  170. /// 获取ip所在时区
  171. /// </summary>
  172. /// <param name="ip"></param>
  173. /// <returns></returns>
  174. public static string GetClientTimeZone(this IPAddress ip)
  175. {
  176. switch (ip.AddressFamily)
  177. {
  178. case AddressFamily.InterNetwork when ip.IsPrivateIP():
  179. case AddressFamily.InterNetworkV6 when ip.IsPrivateIP():
  180. return "Asia/Shanghai";
  181. default:
  182. var resp = Policy<CityResponse>.Handle<AddressNotFoundException>().Fallback(new CityResponse()).Execute(() => MaxmindReader.City(ip));
  183. return resp.Location.TimeZone ?? "Asia/Shanghai";
  184. }
  185. }
  186. /// <summary>
  187. /// 类型映射
  188. /// </summary>
  189. /// <typeparam name="T"></typeparam>
  190. /// <param name="source"></param>
  191. /// <returns></returns>
  192. public static T Mapper<T>(this object source) where T : class => Startup.ServiceProvider.GetRequiredService<IMapper>().Map<T>(source);
  193. /// <summary>
  194. /// 发送邮件
  195. /// </summary>
  196. /// <param name="title">标题</param>
  197. /// <param name="content">内容</param>
  198. /// <param name="tos">收件人</param>
  199. /// <param name="clientip"></param>
  200. [AutomaticRetry(Attempts = 1, OnAttemptsExceeded = AttemptsExceededAction.Delete)]
  201. public static void SendMail(string title, string content, string tos, string clientip)
  202. {
  203. Startup.ServiceProvider.GetRequiredService<IMailSender>().Send(title, content, tos);
  204. RedisHelper.SAdd($"Email:{DateTime.Now:yyyyMMdd}", new { title, content, tos, time = DateTime.Now, clientip });
  205. RedisHelper.Expire($"Email:{DateTime.Now:yyyyMMdd}", 86400);
  206. }
  207. /// <summary>
  208. /// 清理html的img标签的除src之外的其他属性
  209. /// </summary>
  210. /// <param name="html"></param>
  211. /// <returns></returns>
  212. public static string ClearImgAttributes(this string html)
  213. {
  214. var doc = new HtmlDocument();
  215. doc.LoadHtml(html);
  216. var nodes = doc.DocumentNode.Descendants("img");
  217. foreach (var node in nodes)
  218. {
  219. node.Attributes.RemoveWhere(a => !new[] { "src", "data-original", "width", "style", "class" }.Contains(a.Name));
  220. }
  221. return doc.DocumentNode.OuterHtml;
  222. }
  223. /// <summary>
  224. /// 将html的img标签的src属性名替换成data-original
  225. /// </summary>
  226. /// <param name="html"></param>
  227. /// <param name="title"></param>
  228. /// <returns></returns>
  229. public static string ReplaceImgAttribute(this string html, string title)
  230. {
  231. var doc = new HtmlDocument();
  232. doc.LoadHtml(html);
  233. var nodes = doc.DocumentNode.Descendants("img");
  234. foreach (var node in nodes)
  235. {
  236. if (node.Attributes.Contains("src"))
  237. {
  238. string src = node.Attributes["src"].Value;
  239. node.Attributes.Remove("src");
  240. node.Attributes.Add("data-original", src);
  241. node.Attributes.Add("alt", SystemSettings["Title"]);
  242. node.Attributes.Add("title", title);
  243. }
  244. }
  245. return doc.DocumentNode.OuterHtml;
  246. }
  247. /// <summary>
  248. /// 获取文章摘要
  249. /// </summary>
  250. /// <param name="html"></param>
  251. /// <param name="length">截取长度</param>
  252. /// <param name="min">摘要最少字数</param>
  253. /// <returns></returns>
  254. public static string GetSummary(this string html, int length = 150, int min = 10)
  255. {
  256. var doc = new HtmlDocument();
  257. doc.LoadHtml(html);
  258. var summary = doc.DocumentNode.Descendants("p").FirstOrDefault(n => n.InnerText.Length > min)?.InnerText ?? "没有摘要";
  259. if (summary.Length > length)
  260. {
  261. return summary.Substring(0, length) + "...";
  262. }
  263. return summary;
  264. }
  265. public static string TrimQuery(this string path)
  266. {
  267. return path.Split('&').Where(s => s.Split('=', StringSplitOptions.RemoveEmptyEntries).Length == 2).Join("&");
  268. }
  269. /// <summary>
  270. /// 添加水印
  271. /// </summary>
  272. /// <param name="stream"></param>
  273. /// <returns></returns>
  274. public static Stream AddWatermark(this Stream stream)
  275. {
  276. if (!string.IsNullOrEmpty(SystemSettings.GetOrAdd("Watermark", string.Empty)))
  277. {
  278. try
  279. {
  280. var watermarker = new ImageWatermarker(stream)
  281. {
  282. SkipWatermarkForSmallImages = true,
  283. SmallImagePixelsThreshold = 90000
  284. };
  285. return watermarker.AddWatermark(SystemSettings["Watermark"], Color.LightGray, WatermarkPosition.BottomRight, 30);
  286. }
  287. catch
  288. {
  289. //
  290. }
  291. }
  292. return stream;
  293. }
  294. /// <summary>
  295. /// 转换时区
  296. /// </summary>
  297. /// <param name="time">UTC时间</param>
  298. /// <param name="zone">时区id</param>
  299. /// <returns></returns>
  300. public static DateTime ToTimeZone(this in DateTime time, string zone)
  301. {
  302. return TimeZoneInfo.ConvertTime(time, TZConvert.GetTimeZoneInfo(zone));
  303. }
  304. /// <summary>
  305. /// 转换时区
  306. /// </summary>
  307. /// <param name="time">UTC时间</param>
  308. /// <param name="zone">时区id</param>
  309. /// <param name="format">时间格式字符串</param>
  310. /// <returns></returns>
  311. public static string ToTimeZoneF(this in DateTime time, string zone, string format = "yyyy-MM-dd HH:mm:ss")
  312. {
  313. return ToTimeZone(time, zone).ToString(format);
  314. }
  315. }
  316. }