OverrideRuleCore.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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. string hourlyKey = $":override_rule_calls:{item.id}:{DateTime.Now:yyyyMMddHH}";
  109. try
  110. {
  111. long currentHourlyCalls = await RedisKit.IncrByAsync(hourlyKey);
  112. // 如果是第一次调用,设置过期时间为2小时
  113. if (currentHourlyCalls < 10)
  114. {
  115. await RedisKit.ExpireAsync(hourlyKey, 7200); // 2小时
  116. }
  117. // 如果设置了每小时限制且超过限制,跳过该规则
  118. if (item.hourly_calls_limit > 0 && currentHourlyCalls > item.hourly_calls_limit) continue;
  119. }
  120. catch (Exception ex)
  121. {
  122. // Redis错误时记录日志但不阻塞业务
  123. _ = new LoggerLibrary("OverrideRule", "Redis").Info($"Hourly limit check failed: {ex.Message}", ex.StackTrace).SaveAsync();
  124. }
  125. // 每日调用次数统计(无论是否设置限制都要记录)
  126. string dailyKey = $":override_rule_calls:{item.id}:{DateTime.Now:yyyyMMdd}";
  127. try
  128. {
  129. long currentDailyCalls = await RedisKit.IncrByAsync(dailyKey);
  130. if (currentDailyCalls < 10)
  131. {
  132. await RedisKit.ExpireAsync(dailyKey, 259200); // 3天
  133. }
  134. // 如果设置了每日限制且超过限制,跳过该规则
  135. if (item.daily_calls_limit > 0 && currentDailyCalls >= item.daily_calls_limit) continue;
  136. }
  137. catch (Exception ex)
  138. {
  139. // Redis错误时记录日志但不阻塞业务
  140. _ = new LoggerLibrary("OverrideRule", "Redis").Info($"Daily limit check failed: {ex.Message}", ex.StackTrace).SaveAsync();
  141. }
  142. return item;
  143. }
  144. return null;
  145. }
  146. public static void Refresh()
  147. {
  148. _cached = null;
  149. _ = ListAsync(true);
  150. }
  151. public static int Update(OverrideRuleDTO data, IDbConnection conn)
  152. {
  153. var result = (int)conn.Update<OverrideRuleDTO>(data, new { data.id });
  154. _ = ListAsync(true);
  155. #if DEBUG
  156. #else
  157. EndPointCore.NotifyReload();
  158. #endif
  159. return result;
  160. }
  161. public static int Create(OverrideRuleDTO data, IDbConnection conn)
  162. {
  163. var result = (int)conn.Insert(data);
  164. _ = ListAsync(true);
  165. #if DEBUG
  166. #else
  167. EndPointCore.NotifyReload();
  168. #endif
  169. return result;
  170. }
  171. }
  172. }