TkPoolCore.cs 15 KB

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