OverrideRuleCore.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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, out _);
  113. if (is_ignore) continue;
  114. is_ignore = AlimamaPlus.FlowControlIgnoreRequest(request, out _);
  115. if (is_ignore) continue;
  116. }
  117. string output_text = item.output_text;
  118. if (output_text.Contains("{url:query_text}")) output_text = output_text.Replace("{url:query_text}", HttpUtility.UrlEncode(original_text));
  119. if (output_text.Contains("{url2:query_text}")) output_text = output_text.Replace("{url2:query_text}", HttpUtility.UrlEncode(HttpUtility.UrlEncode(original_text)));
  120. if (output_text.Contains("{url3:query_text}")) output_text = output_text.Replace("{url3:query_text}", HttpUtility.UrlEncode(HttpUtility.UrlEncode(HttpUtility.UrlEncode(original_text))));
  121. if (output_text.Contains("{query_text}")) output_text = output_text.Replace("{query_text}", original_text);
  122. // 返回副本,避免占位符替换结果写回缓存中的规则
  123. var matched = item.Clone();
  124. matched.output_text = output_text;
  125. var now = DateTime.Now;
  126. if (!await TryRecordRewriteAsync(item, now)) continue;
  127. // 日、小时重写次数已经与限额一起原子更新,这里只记录其他历史统计。
  128. await SaveKeywordStatisticsAsync(item.id, item.platform, original_text, now);
  129. return matched;
  130. }
  131. return null;
  132. }
  133. /// <summary>
  134. /// 保存关键词统计数据到Redis,用于长期数据分析
  135. /// 缓存周期:6个月
  136. /// </summary>
  137. private static async Task SaveKeywordStatisticsAsync(int ruleId, string platform, string keyword, DateTime now)
  138. {
  139. try
  140. {
  141. // 6个月的秒数
  142. const int sixMonthsInSeconds = 180 * 86400;
  143. // 关键词总请求次数统计 - 按月份
  144. string monthlyKey = $":keyword_stats:{platform}:{ruleId}:{now:yyyyMM}";
  145. await RedisKit.IncrByAsync(monthlyKey);
  146. await RedisKit.ExpireAsync(monthlyKey, sixMonthsInSeconds);
  147. // 平台维度统计
  148. string platformMonthlyKey = $":keyword_stats:platform:{platform}:{now:yyyyMM}";
  149. await RedisKit.IncrByAsync(platformMonthlyKey);
  150. await RedisKit.ExpireAsync(platformMonthlyKey, sixMonthsInSeconds);
  151. // 全局统计
  152. string globalMonthlyKey = $":keyword_stats:global:{now:yyyyMM}";
  153. await RedisKit.IncrByAsync(globalMonthlyKey);
  154. await RedisKit.ExpireAsync(globalMonthlyKey, sixMonthsInSeconds);
  155. // 记录关键词集合(用于后续查询有哪些关键词)
  156. string keywordSetKey = $":keyword_stats:set:{platform}:{now:yyyyMM}";
  157. await RedisKit.SAddAsync(keywordSetKey, keyword);
  158. await RedisKit.ExpireAsync(keywordSetKey, sixMonthsInSeconds);
  159. }
  160. catch (Exception ex)
  161. {
  162. // Redis错误时记录日志但不阻塞业务
  163. _ = new LoggerLibrary("OverrideRule", "KeywordStats").Info($"Keyword statistics save failed: {ex.Message}", ex.StackTrace).SaveAsync();
  164. }
  165. }
  166. public static void Refresh()
  167. {
  168. _cached = null;
  169. _ = ListAsync(true);
  170. }
  171. public static int Update(OverrideRuleDTO data, IDbConnection conn)
  172. {
  173. var result = (int)conn.Update<OverrideRuleDTO>(data, new { data.id });
  174. _ = ListAsync(true);
  175. #if DEBUG
  176. #else
  177. EndPointCore.NotifyReload();
  178. #endif
  179. return result;
  180. }
  181. public static int Create(OverrideRuleDTO data, IDbConnection conn)
  182. {
  183. var result = (int)conn.Insert(data);
  184. _ = ListAsync(true);
  185. #if DEBUG
  186. #else
  187. EndPointCore.NotifyReload();
  188. #endif
  189. return result;
  190. }
  191. }
  192. }