OverrideRuleCore.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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 YunhuiKit;
  7. namespace molilian.core
  8. {
  9. public partial class OverrideRuleCore
  10. {
  11. private static IEnumerable<OverrideRuleDTO> _cached;
  12. private static readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
  13. public static async Task<IEnumerable<OverrideRuleDTO>> ListAsync(bool force = false)
  14. {
  15. #if DEBUG
  16. return new DBContext.Table("tk_override_rules")
  17. .Where("status=@status", new { status = 1 })
  18. .Order("sort DESC, id DESC")
  19. .Select<OverrideRuleDTO>();
  20. #endif
  21. if (!force && _cached != null) return _cached;
  22. try
  23. {
  24. await _semaphore.WaitAsync();
  25. // 如果缓存存在且未强制刷新,直接返回
  26. if (!force && _cached != null) return _cached;
  27. string cache_key = $"cache:tk_override_rules";
  28. IEnumerable<OverrideRuleDTO>? list = null;
  29. // 尝试从Redis获取数据
  30. try
  31. {
  32. list = await RedisKit.GetAsync<IEnumerable<OverrideRuleDTO>>(cache_key);
  33. }
  34. catch (Exception ex)
  35. {
  36. // 记录Redis错误
  37. _ = new LoggerLibrary("OverrideRule", "Redis").Info(ex.Message, ex.StackTrace).SaveAsync();
  38. }
  39. // 如果Redis获取失败或需要强制刷新
  40. if (force || list == null)
  41. {
  42. try
  43. {
  44. list = new DBContext.Table("tk_override_rules")
  45. .Where("status=@status", new { status = 1 })
  46. .Order("sort DESC, id DESC")
  47. .Select<OverrideRuleDTO>();
  48. if (list != null && list.Any())
  49. {
  50. // 尝试更新Redis缓存
  51. try
  52. {
  53. await RedisKit.SetAsync(cache_key, list, 30 * 86400);
  54. }
  55. catch (Exception ex)
  56. {
  57. // 记录Redis更新错误
  58. _ = new LoggerLibrary("OverrideRule", "Redis").Info(ex.Message, ex.StackTrace).SaveAsync();
  59. }
  60. }
  61. }
  62. catch (Exception ex)
  63. {
  64. // 记录数据库查询错误
  65. _ = new LoggerLibrary("OverrideRule", "Database").Info(ex.Message, ex.StackTrace).SaveAsync();
  66. // 如果数据库查询失败但缓存还在,继续使用缓存
  67. if (_cached != null) return _cached;
  68. throw; // 如果没有任何可用数据,则抛出异常
  69. }
  70. }
  71. _cached = list;
  72. return list ?? [];
  73. }
  74. finally
  75. {
  76. _semaphore.Release();
  77. }
  78. }
  79. public static async Task<OverrideRuleDTO> ProcessAsync(UnionParseRequest request)
  80. {
  81. if (string.IsNullOrEmpty(request.Channel)) return null;
  82. var list = await ListAsync();
  83. if (list == default) return null;
  84. string content = request.Content;
  85. if (request.SpecialText == 1) content = request.QueryText;
  86. if (string.IsNullOrEmpty(content)) return null;
  87. foreach (var item in list)
  88. {
  89. if (!request.Channel.Equals(item.platform)) continue;
  90. if (string.IsNullOrEmpty(item.original_text)) continue;
  91. if (item.use_special_text == 1 && request.SpecialText != 1) continue;
  92. switch (item.rule)
  93. {
  94. case "regex":
  95. Match match = Regex.Match(content, item.original_text);
  96. if (!match.Success) continue;
  97. break;
  98. case "text":
  99. if (!content.Equals(item.original_text)) continue;
  100. break;
  101. default:
  102. if (!content.Contains(item.original_text)) continue;
  103. break;
  104. }
  105. if (item.use_risk_control)
  106. {
  107. bool is_ignore = AlimamaPlus.ShouldIgnoreRequest(request.Ip, request.Oaid, request.RiskStrategy, request.LaunchScene, out _);
  108. if (is_ignore) continue;
  109. }
  110. if (item.use_special_text == 1 && request.SpecialText != 1) continue;
  111. // 每小时调用次数统计(无论是否设置限制都要记录)
  112. string hourlyKey = $":override_rule_calls:{item.id}:{DateTime.Now:yyyyMMddHH}";
  113. try
  114. {
  115. long currentHourlyCalls = await RedisKit.IncrByAsync(hourlyKey);
  116. // 如果是第一次调用,设置过期时间为2小时
  117. if (currentHourlyCalls < 10)
  118. {
  119. await RedisKit.ExpireAsync(hourlyKey, 7200); // 2小时
  120. }
  121. // 如果设置了每小时限制且超过限制,跳过该规则
  122. if (item.hourly_calls_limit > 0 && currentHourlyCalls > item.hourly_calls_limit) continue;
  123. }
  124. catch (Exception ex)
  125. {
  126. // Redis错误时记录日志但不阻塞业务
  127. _ = new LoggerLibrary("OverrideRule", "Redis").Info($"Hourly limit check failed: {ex.Message}", ex.StackTrace).SaveAsync();
  128. }
  129. // 每日调用次数统计(无论是否设置限制都要记录)
  130. string dailyKey = $":override_rule_calls:{item.id}:{DateTime.Now:yyyyMMdd}";
  131. try
  132. {
  133. long currentDailyCalls = await RedisKit.IncrByAsync(dailyKey);
  134. if (currentDailyCalls < 10)
  135. {
  136. await RedisKit.ExpireAsync(dailyKey, 259200); // 3天
  137. }
  138. // 如果设置了每日限制且超过限制,跳过该规则
  139. if (item.daily_calls_limit > 0 && currentDailyCalls >= item.daily_calls_limit) continue;
  140. }
  141. catch (Exception ex)
  142. {
  143. // Redis错误时记录日志但不阻塞业务
  144. _ = new LoggerLibrary("OverrideRule", "Redis").Info($"Daily limit check failed: {ex.Message}", ex.StackTrace).SaveAsync();
  145. }
  146. return item;
  147. }
  148. return null;
  149. }
  150. public static void Refresh()
  151. {
  152. _cached = null;
  153. _ = ListAsync(true);
  154. }
  155. public static int Update(OverrideRuleDTO data, IDbConnection conn)
  156. {
  157. var result = (int)conn.Update<OverrideRuleDTO>(data, new { data.id });
  158. _ = ListAsync(true);
  159. #if DEBUG
  160. #else
  161. EndPointCore.NotifyReload();
  162. #endif
  163. return result;
  164. }
  165. public static int Create(OverrideRuleDTO data, IDbConnection conn)
  166. {
  167. var result = (int)conn.Insert(data);
  168. _ = ListAsync(true);
  169. #if DEBUG
  170. #else
  171. EndPointCore.NotifyReload();
  172. #endif
  173. return result;
  174. }
  175. }
  176. }