OverrideRuleCore.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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(string platform, string content, string ip, string oaid, string riskStrategy, int launchScene, int special_text)
  80. {
  81. if (string.IsNullOrEmpty(platform)) return null;
  82. var list = await ListAsync();
  83. if (list == default) return null;
  84. foreach (var item in list)
  85. {
  86. if (!platform.Equals(item.platform)) continue;
  87. if (string.IsNullOrEmpty(item.original_text)) continue;
  88. switch (item.rule)
  89. {
  90. case "regex":
  91. Match match = Regex.Match(content, item.original_text);
  92. if (!match.Success) continue;
  93. break;
  94. case "text":
  95. if (!content.Equals(item.original_text)) continue;
  96. break;
  97. default:
  98. if (!content.Contains(item.original_text)) continue;
  99. break;
  100. }
  101. if (item.use_risk_control)
  102. {
  103. bool is_ignore = AlimamaPlus.ShouldIgnoreRequest(ip, oaid, riskStrategy, launchScene, out _);
  104. if (is_ignore) continue;
  105. }
  106. if (item.use_special_text == 1 && special_text != 1) continue;
  107. // 每小时调用次数限制
  108. if (item.hourly_calls_limit > 0)
  109. {
  110. string hourlyKey = $":override_rule_calls:{item.id}:{DateTime.Now:yyyyMMddHH}";
  111. try
  112. {
  113. long currentHourlyCalls = await RedisKit.IncrByAsync(hourlyKey);
  114. // 如果是第一次调用,设置过期时间为2小时
  115. if (currentHourlyCalls < 10)
  116. {
  117. await RedisKit.ExpireAsync(hourlyKey, 7200); // 2小时
  118. }
  119. // 如果超过每小时限制,跳过该规则
  120. if (currentHourlyCalls > item.hourly_calls_limit) continue;
  121. }
  122. catch (Exception ex)
  123. {
  124. // Redis错误时记录日志但不阻塞业务
  125. _ = new LoggerLibrary("OverrideRule", "Redis").Info($"Hourly limit check failed: {ex.Message}", ex.StackTrace).SaveAsync();
  126. }
  127. }
  128. // 每日调用次数限制
  129. if (item.daily_calls_limit > 0)
  130. {
  131. string dailyKey = $":override_rule_calls:{item.id}:{DateTime.Now:yyyyMMdd}";
  132. try
  133. {
  134. long currentDailyCalls = await RedisKit.IncrByAsync(dailyKey);
  135. if (currentDailyCalls < 10)
  136. {
  137. await RedisKit.ExpireAsync(dailyKey, 259200); // 3天
  138. }
  139. if (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. }
  147. return item;
  148. }
  149. return null;
  150. }
  151. public static void Refresh()
  152. {
  153. _cached = null;
  154. _ = ListAsync(true);
  155. }
  156. public static int Update(OverrideRuleDTO data, IDbConnection conn)
  157. {
  158. var result = (int)conn.Update<OverrideRuleDTO>(data, new { data.id });
  159. _ = ListAsync(true);
  160. #if DEBUG
  161. #else
  162. EndPointCore.NotifyReload();
  163. #endif
  164. return result;
  165. }
  166. public static int Create(OverrideRuleDTO data, IDbConnection conn)
  167. {
  168. var result = (int)conn.Insert(data);
  169. _ = ListAsync(true);
  170. #if DEBUG
  171. #else
  172. EndPointCore.NotifyReload();
  173. #endif
  174. return result;
  175. }
  176. }
  177. }