TkPoolCore.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. using Microsoft.AspNetCore.Http;
  2. using Microsoft.AspNetCore.Mvc.Controllers;
  3. using Microsoft.AspNetCore.Mvc.Filters;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using dodohold.core;
  9. using Spire.Pdf.Exporting.XPS.Schema;
  10. using System.Xml.Linq;
  11. using System.Net;
  12. using TencentCloud.Mrs.V20200910.Models;
  13. using YunhuiKit;
  14. namespace molilian.core
  15. {
  16. public partial class TkPoolCore
  17. {
  18. public enum TkAction
  19. {
  20. all,
  21. parse,
  22. coupon,
  23. promotionQuery
  24. }
  25. private static string _end_point;
  26. static TkPoolCore()
  27. {
  28. _end_point = Environment.GetEnvironmentVariable("EndPoint");
  29. }
  30. private static SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
  31. private static IEnumerable<TkPoolDTO> _cached;
  32. private static IEnumerable<TkPoolDTO> _all_cached;
  33. public static async Task<TkPoolDTO> GetOneAsync(TkAction action)
  34. {
  35. var list = await ListAsync();
  36. if (!list.Any()) return null;
  37. return list.Where(e => FilterNodes(e, action)).OrderBy(l => Guid.NewGuid()).FirstOrDefault();
  38. }
  39. public static async Task<TkPoolDTO> GetOneAsync(int id)
  40. {
  41. var list = await ListAsync();
  42. if (!list.Any()) return null;
  43. return list.Where(e => e.id == id).FirstOrDefault();
  44. }
  45. private static bool FilterNodes(TkPoolDTO item, TkAction action)
  46. {
  47. if (!string.IsNullOrEmpty(item.suspended_endpoint) && item.suspended_endpoint.Contains($"{_end_point}|")) return false;
  48. if (!string.IsNullOrEmpty(_end_point) && !string.IsNullOrEmpty(item.end_point))
  49. {
  50. if (item.end_point != _end_point) return false;
  51. }
  52. // 使用初始化参数创建工作时间表
  53. if (!new WorkSchedule(item.time_range).IsWorkHour()) return false;
  54. if (item.daily_calls_limit > 0)
  55. {
  56. int daily_num = RiskControlCore.GetCalls(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMdd"));
  57. if (daily_num >= item.daily_calls_limit) return false;
  58. }
  59. if (item.hourly_calls_limit > 0)
  60. {
  61. int hourly_num = RiskControlCore.GetCalls(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMddHH"));
  62. if (hourly_num >= item.hourly_calls_limit) return false;
  63. }
  64. switch (action)
  65. {
  66. case TkAction.parse:
  67. if (!item.enable_parse) return false;
  68. break;
  69. case TkAction.promotionQuery:
  70. if (!item.enable_promotionQuery) return false;
  71. break;
  72. case TkAction.coupon:
  73. if (!item.enable_coupon) return false;
  74. break;
  75. }
  76. if (item.daily_income_limit == 0) return true;
  77. decimal income_amt = RiskControlCore.GetIncomeAmt(TkChannelEnum.tb, $"{item.id}");
  78. return income_amt < item.daily_income_limit;
  79. }
  80. public static async Task<IEnumerable<TkPoolDTO>> AllListAsync(bool force = false)
  81. {
  82. if (!force && _all_cached != default) return _all_cached;
  83. try
  84. {
  85. await _semaphore.WaitAsync();
  86. string cache_key = $"cache:all_tk_pool";
  87. var list = await RedisKit.GetAsync<IEnumerable<TkPoolDTO>>(cache_key);
  88. if (force || list == default)
  89. {
  90. list = new DBContext.Table("tk_pool").Select<TkPoolDTO>();
  91. if (list == null) return default;
  92. // 等待 Redis 写入完成
  93. await RedisKit.SetAsync(cache_key, list, 30 * 86400);
  94. }
  95. _all_cached = list;
  96. return list;
  97. }
  98. catch (Exception)
  99. {
  100. // 发生异常时返回上一次的缓存,如果没有则返回默认值
  101. return _all_cached ?? default;
  102. }
  103. finally
  104. {
  105. _semaphore.Release();
  106. }
  107. }
  108. public static async Task<IEnumerable<TkPoolDTO>> ListAsync(bool force = false)
  109. {
  110. // 内存缓存检查
  111. if (!force && _cached != null) return _cached;
  112. string cache_key = "cache:tk_pool";
  113. if (!force)
  114. {
  115. var cachedList = await RedisHelper.GetAsync<IEnumerable<TkPoolDTO>>(cache_key);
  116. if (cachedList != null)
  117. {
  118. _cached = cachedList;
  119. return cachedList;
  120. }
  121. }
  122. // 获取新数据
  123. await _semaphore.WaitAsync();
  124. try
  125. {
  126. // 双重检查,防止并发情况下重复加载
  127. if (!force)
  128. {
  129. var cachedList = await RedisHelper.GetAsync<IEnumerable<TkPoolDTO>>(cache_key);
  130. if (cachedList != null)
  131. {
  132. _cached = cachedList;
  133. return cachedList;
  134. }
  135. }
  136. // 从数据库加载数据
  137. var list = new DBContext.Table("tk_pool")
  138. .Where("status=@status", new { status = 1 })
  139. .Select<TkPoolDTO>();
  140. if (list == null) return default;
  141. // 更新调用次数
  142. foreach (var item in list)
  143. {
  144. _ = RiskControlCore.SetCallsAsync(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMddHH"), item.current_hourly_calls);
  145. _ = RiskControlCore.SetCallsAsync(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMdd"), item.current_daily_calls);
  146. }
  147. // 更新缓存
  148. await RedisHelper.SetAsync(cache_key, list, 30 * 86400);
  149. _cached = list;
  150. return list;
  151. }
  152. finally
  153. {
  154. _semaphore.Release();
  155. }
  156. }
  157. public static void Refresh()
  158. {
  159. _ = AllListAsync(true);
  160. _ = ListAsync(true);
  161. }
  162. public static void UpdateDrawBalance(string name, decimal amout)
  163. {
  164. new DBContext.Table("tk_pool")
  165. .Add("draw_balance", amout)
  166. .Where("name=@name", new { name })
  167. .Update();
  168. _ = ListAsync(true);
  169. }
  170. public static void Suspend(string endpoint, int accountId, string name, string content)
  171. {
  172. string cache_key = $"cache:tk_pool:{accountId}:suspend";
  173. long count = RedisHelper.IncrBy(cache_key);
  174. RedisHelper.Expire(cache_key, 10);
  175. if (count > 1) return;
  176. var update = new DBContext.Table("tk_pool").Add("suspended_endpoint:", $"CONCAT(suspended_endpoint, '{endpoint},')");
  177. if (accountId > 0)
  178. {
  179. update.Where("id=@accountId", new { accountId }).Update();
  180. }
  181. else
  182. {
  183. update.Where("name=@name", new { name }).Update();
  184. }
  185. _ = ListAsync(true);
  186. NotifyCore.Notify(new NifyMessage
  187. {
  188. message = $"【淘客{accountId}:{name}】{endpoint} 暂停",
  189. priority = NifyMessagePriority.high,
  190. tags = ["red_circle"]
  191. });
  192. NotifyCore.AnPushNotify("暂停", $"【淘客{accountId}:{name}】{endpoint} 暂停");
  193. EndPointCore.NotifyReload(true);
  194. }
  195. public static bool IsNeedSwitchBackup(int accountId)
  196. {
  197. string cache_key = $"cache:tk_pool:{accountId}:switchBackup";
  198. long count = RedisHelper.Get<int>(cache_key);
  199. return count != 0;
  200. }
  201. public static void SwitchBackup(string endpoint, int accountId, string name, string content)
  202. {
  203. string cache_key = $"cache:tk_pool:{accountId}:switchBackup";
  204. long count = RedisHelper.IncrBy(cache_key);
  205. RedisHelper.Expire(cache_key, 3600 * 4);
  206. if (count > 1) return;
  207. //_ = ListAsync(true);
  208. NotifyCore.Notify(new NifyMessage
  209. {
  210. message = $"【淘客{accountId}:{name}】{endpoint} 风控,切换备用接口",
  211. priority = NifyMessagePriority.high,
  212. tags = ["red_circle"]
  213. });
  214. NotifyCore.AnPushNotify("切换接口", $"【淘客{accountId}:{name}】{endpoint} 切换备用接口");
  215. EndPointCore.NotifyReload(true);
  216. }
  217. public static void Disabled(int accountId, string name, string content)
  218. {
  219. #if DEBUG
  220. #else
  221. #endif
  222. string cache_key = $"cache:tk_pool:{accountId}:disabled";
  223. long count = RedisHelper.IncrBy(cache_key);
  224. RedisHelper.Expire(cache_key, 10);
  225. if (count > 1) return;
  226. var update = new DBContext.Table("tk_pool").Add("status", 0);
  227. if (accountId > 0)
  228. {
  229. update.Where("id=@accountId", new { accountId }).Update();
  230. }
  231. else
  232. {
  233. update.Where("name=@name", new { name }).Update();
  234. }
  235. _ = ListAsync(true);
  236. NotifyCore.Notify(new NifyMessage
  237. {
  238. message = $"【淘客{accountId}:{name}】cookie 掉线\n\n{content}",
  239. priority = NifyMessagePriority.high,
  240. tags = ["red_circle"]
  241. });
  242. NotifyCore.AnPushNotify("掉线", $"【淘客{accountId}:{name}】cookie 掉线");
  243. EndPointCore.NotifyReload(true);
  244. }
  245. public static int UpdateCookies(string cookies, string user_agent)
  246. {
  247. if (string.IsNullOrEmpty(cookies)) return 0;
  248. cookies += ";";
  249. string dnk = cookies.GetContentPart("dnk=", ";");
  250. string company = dnk;
  251. int accountId = 0;
  252. string tb_token = cookies.GetContentPart("_tb_token_=", ";");
  253. if (string.IsNullOrEmpty(dnk) || string.IsNullOrEmpty(tb_token)) return 0;
  254. var exist = new DBContext.Table("tk_pool").Fields("id, name, company, refpid, status").Get<dynamic>("name=@dnk", new { dnk });
  255. if (exist != null)
  256. {
  257. int status = exist.status;
  258. string refpid = exist.refpid;
  259. company = exist.company;
  260. accountId = exist.id;
  261. if (!string.IsNullOrEmpty(refpid)) status = 1;
  262. new DBContext.Table("tk_pool")
  263. .Add("name", dnk)
  264. .Add("tb_token", tb_token)
  265. .Add("cookies", cookies)
  266. .Add("user_agent", user_agent)
  267. .Add("status", status)
  268. .Add("suspended_endpoint", string.Empty)
  269. .Add("last_time", DateTime.Now)
  270. .Add("login_time", DateTime.Now)
  271. .Where("id=@id", new { exist.id })
  272. .Update();
  273. if (status == 1) _ = ListAsync(true);
  274. }
  275. else
  276. {
  277. accountId = new DBContext.Table("tk_pool")
  278. .Add("name", dnk)
  279. .Add("description", "由cookies上报创建此记录")
  280. .Add("tb_token", tb_token)
  281. .Add("refpid", string.Empty)
  282. .Add("cookies", cookies)
  283. .Add("user_agent", user_agent)
  284. .Add("create_time", DateTime.Now)
  285. .Add("last_time", DateTime.Now)
  286. .Add("login_time", DateTime.Now)
  287. .Add("status", 0)
  288. .Create();
  289. }
  290. NotifyCore.Notify(new NifyMessage
  291. {
  292. message = $"【淘客{accountId}:{company}】cookie 上线",
  293. tags = ["green_circle"]
  294. });
  295. EndPointCore.NotifyReload(true);
  296. //NotifyCore.AnPushNotify("上线", $"【淘宝联盟:{dnk}】cookie 上报更新");
  297. return accountId;
  298. }
  299. internal static void AccountExhausted()
  300. {
  301. string cache_key = $"cache:tk_pool:account:exhausted";
  302. long count = RedisHelper.IncrBy(cache_key);
  303. if (count > 1) return;
  304. RedisHelper.Expire(cache_key, 3600);
  305. NotifyCore.Notify(new NifyMessage
  306. {
  307. message = $"【淘客】没有匹配账号",
  308. priority = NifyMessagePriority.high,
  309. tags = ["red_circle"]
  310. });
  311. NotifyCore.AnPushNotify("没账号", $"【淘客】没有匹配账号");
  312. }
  313. }
  314. }