OverrideRuleCore.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. using dodohold.core;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Security.Cryptography;
  5. using System.Text.RegularExpressions;
  6. using System.Web;
  7. using YunhuiKit;
  8. namespace molilian.core
  9. {
  10. public partial class OverrideRuleCore
  11. {
  12. private static IEnumerable<OverrideRuleDTO> _cached;
  13. private static readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
  14. public static async Task<IEnumerable<OverrideRuleDTO>> ListAsync(bool force = false)
  15. {
  16. #if DEBUG
  17. return new DBContext.Table("tk_override_rules")
  18. .Where("status=@status", new { status = 1 })
  19. .Order("sort DESC, id DESC")
  20. .Select<OverrideRuleDTO>();
  21. #endif
  22. if (!force && _cached != null) return _cached;
  23. try
  24. {
  25. await _semaphore.WaitAsync();
  26. // 如果缓存存在且未强制刷新,直接返回
  27. if (!force && _cached != null) return _cached;
  28. string cache_key = $"cache:tk_override_rules";
  29. IEnumerable<OverrideRuleDTO>? list = null;
  30. // 尝试从Redis获取数据
  31. try
  32. {
  33. list = await RedisKit.GetAsync<IEnumerable<OverrideRuleDTO>>(cache_key);
  34. }
  35. catch (Exception ex)
  36. {
  37. // 记录Redis错误
  38. _ = new LoggerLibrary("OverrideRule", "Redis").Info(ex.Message, ex.StackTrace).SaveAsync();
  39. }
  40. // 如果Redis获取失败或需要强制刷新
  41. if (force || list == null)
  42. {
  43. try
  44. {
  45. list = new DBContext.Table("tk_override_rules")
  46. .Where("status=@status", new { status = 1 })
  47. .Order("sort DESC, id DESC")
  48. .Select<OverrideRuleDTO>();
  49. if (list != null && list.Any())
  50. {
  51. // 尝试更新Redis缓存
  52. try
  53. {
  54. await RedisKit.SetAsync(cache_key, list, 30 * 86400);
  55. }
  56. catch (Exception ex)
  57. {
  58. // 记录Redis更新错误
  59. _ = new LoggerLibrary("OverrideRule", "Redis").Info(ex.Message, ex.StackTrace).SaveAsync();
  60. }
  61. }
  62. }
  63. catch (Exception ex)
  64. {
  65. // 记录数据库查询错误
  66. _ = new LoggerLibrary("OverrideRule", "Database").Info(ex.Message, ex.StackTrace).SaveAsync();
  67. // 如果数据库查询失败但缓存还在,继续使用缓存
  68. if (_cached != null) return _cached;
  69. throw; // 如果没有任何可用数据,则抛出异常
  70. }
  71. }
  72. _cached = list;
  73. return list ?? [];
  74. }
  75. finally
  76. {
  77. _semaphore.Release();
  78. }
  79. }
  80. public static async Task<OverrideRuleDTO> ProcessAsync(UnionParseRequest request)
  81. {
  82. if (string.IsNullOrEmpty(request.Channel)) return null;
  83. var list = await ListAsync();
  84. if (list == default) return null;
  85. string content = request.Content;
  86. if (request.SpecialText == 1) content = request.QueryText;
  87. if (string.IsNullOrEmpty(content)) return null;
  88. foreach (var item in list)
  89. {
  90. //
  91. if (!request.Channel.Equals(item.platform)) continue;
  92. if (item.use_special_text == 1 && request.SpecialText != 1) continue;
  93. string original_text = item.original_text;
  94. if (item.use_special_text == 1) original_text = request.QueryText;
  95. if (string.IsNullOrEmpty(original_text)) continue;
  96. switch (item.rule)
  97. {
  98. case "regex":
  99. Match match = Regex.Match(content, original_text);
  100. if (!match.Success) continue;
  101. break;
  102. case "text":
  103. if (!content.Equals(original_text)) continue;
  104. break;
  105. default:
  106. if (!content.Contains(original_text)) continue;
  107. break;
  108. }
  109. if (item.use_special_text == 1 && request.SpecialText != 1) continue;
  110. if (item.use_risk_control)
  111. {
  112. bool is_ignore = AlimamaPlus.ShouldIgnoreRequest(request.Ip, request.Oaid, request.RiskStrategy, request.LaunchScene, out _);
  113. if (is_ignore) continue;
  114. }
  115. // 每小时调用次数统计(无论是否设置限制都要记录)
  116. string hourlyKey = $":override_rule_calls:{item.id}:{DateTime.Now:yyyyMMddHH}";
  117. try
  118. {
  119. long currentHourlyCalls = await RedisKit.IncrByAsync(hourlyKey);
  120. // 如果是第一次调用,设置过期时间为2小时
  121. if (currentHourlyCalls < 10)
  122. {
  123. await RedisKit.ExpireAsync(hourlyKey, 7200); // 2小时
  124. }
  125. // 如果设置了每小时限制且超过限制,跳过该规则
  126. if (item.hourly_calls_limit > 0 && currentHourlyCalls > item.hourly_calls_limit) continue;
  127. }
  128. catch (Exception ex)
  129. {
  130. // Redis错误时记录日志但不阻塞业务
  131. _ = new LoggerLibrary("OverrideRule", "Redis").Info($"Hourly limit check failed: {ex.Message}", ex.StackTrace).SaveAsync();
  132. }
  133. // 每日调用次数统计(无论是否设置限制都要记录)
  134. string dailyKey = $":override_rule_calls:{item.id}:{DateTime.Now:yyyyMMdd}";
  135. try
  136. {
  137. long currentDailyCalls = await RedisKit.IncrByAsync(dailyKey);
  138. if (currentDailyCalls < 10)
  139. {
  140. await RedisKit.ExpireAsync(dailyKey, 259200); // 3天
  141. }
  142. // 如果设置了每日限制且超过限制,跳过该规则
  143. if (item.daily_calls_limit > 0 && currentDailyCalls >= item.daily_calls_limit) continue;
  144. }
  145. catch (Exception ex)
  146. {
  147. // Redis错误时记录日志但不阻塞业务
  148. _ = new LoggerLibrary("OverrideRule", "Redis").Info($"Daily limit check failed: {ex.Message}", ex.StackTrace).SaveAsync();
  149. }
  150. // 关键词统计 - 长期缓存(6个月)用于历史数据分析
  151. await SaveKeywordStatisticsAsync(item.id, item.platform, original_text);
  152. string output_text = item.output_text;
  153. if (output_text.Contains("{url:query_text}")) output_text = output_text.Replace("{url:query_text}", HttpUtility.UrlEncode(original_text));
  154. if (output_text.Contains("{url2:query_text}")) output_text = output_text.Replace("{url2:query_text}", HttpUtility.UrlEncode(HttpUtility.UrlEncode(original_text)));
  155. if (output_text.Contains("{url3:query_text}")) output_text = output_text.Replace("{url3:query_text}", HttpUtility.UrlEncode(HttpUtility.UrlEncode(HttpUtility.UrlEncode(original_text))));
  156. if (output_text.Contains("{query_text}")) output_text = output_text.Replace("{query_text}", original_text);
  157. item.output_text = output_text;
  158. return item;
  159. }
  160. return null;
  161. }
  162. /// <summary>
  163. /// 保存关键词统计数据到Redis,用于长期数据分析
  164. /// 缓存周期:6个月
  165. /// </summary>
  166. private static async Task SaveKeywordStatisticsAsync(int ruleId, string platform, string keyword)
  167. {
  168. try
  169. {
  170. // 6个月的秒数
  171. const int sixMonthsInSeconds = 180 * 86400;
  172. // 关键词总请求次数统计 - 按月份
  173. string monthlyKey = $":keyword_stats:{platform}:{ruleId}:{DateTime.Now:yyyyMM}";
  174. await RedisKit.IncrByAsync(monthlyKey);
  175. await RedisKit.ExpireAsync(monthlyKey, sixMonthsInSeconds);
  176. // 关键词总请求次数统计 - 按日
  177. string dailyKey = $":keyword_stats:{platform}:{ruleId}:{DateTime.Now:yyyyMMdd}";
  178. await RedisKit.IncrByAsync(dailyKey);
  179. await RedisKit.ExpireAsync(dailyKey, sixMonthsInSeconds);
  180. // 关键词总请求次数统计 - 按小时
  181. string hourlyKey = $":keyword_stats:{platform}:{ruleId}:{DateTime.Now:yyyyMMddHH}";
  182. await RedisKit.IncrByAsync(hourlyKey);
  183. await RedisKit.ExpireAsync(hourlyKey, sixMonthsInSeconds);
  184. // 平台维度统计
  185. string platformMonthlyKey = $":keyword_stats:platform:{platform}:{DateTime.Now:yyyyMM}";
  186. await RedisKit.IncrByAsync(platformMonthlyKey);
  187. await RedisKit.ExpireAsync(platformMonthlyKey, sixMonthsInSeconds);
  188. // 全局统计
  189. string globalMonthlyKey = $":keyword_stats:global:{DateTime.Now:yyyyMM}";
  190. await RedisKit.IncrByAsync(globalMonthlyKey);
  191. await RedisKit.ExpireAsync(globalMonthlyKey, sixMonthsInSeconds);
  192. // 记录关键词集合(用于后续查询有哪些关键词)
  193. string keywordSetKey = $":keyword_stats:set:{platform}:{DateTime.Now:yyyyMM}";
  194. await RedisKit.SAddAsync(keywordSetKey, keyword);
  195. await RedisKit.ExpireAsync(keywordSetKey, sixMonthsInSeconds);
  196. }
  197. catch (Exception ex)
  198. {
  199. // Redis错误时记录日志但不阻塞业务
  200. _ = new LoggerLibrary("OverrideRule", "KeywordStats").Info($"Keyword statistics save failed: {ex.Message}", ex.StackTrace).SaveAsync();
  201. }
  202. }
  203. public static void Refresh()
  204. {
  205. _cached = null;
  206. _ = ListAsync(true);
  207. }
  208. public static int Update(OverrideRuleDTO data, IDbConnection conn)
  209. {
  210. var result = (int)conn.Update<OverrideRuleDTO>(data, new { data.id });
  211. _ = ListAsync(true);
  212. #if DEBUG
  213. #else
  214. EndPointCore.NotifyReload();
  215. #endif
  216. return result;
  217. }
  218. public static int Create(OverrideRuleDTO data, IDbConnection conn)
  219. {
  220. var result = (int)conn.Insert(data);
  221. _ = ListAsync(true);
  222. #if DEBUG
  223. #else
  224. EndPointCore.NotifyReload();
  225. #endif
  226. return result;
  227. }
  228. }
  229. }