TkPoolCore.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. using dodohold.core;
  2. using Org.BouncyCastle.Bcpg.OpenPgp;
  3. using YunhuiKit;
  4. namespace molilian.core
  5. {
  6. public partial class TkPoolCore
  7. {
  8. public enum TkAction
  9. {
  10. all,
  11. parse,
  12. coupon,
  13. promotionQuery,
  14. activity
  15. }
  16. private static string _end_point;
  17. static TkPoolCore()
  18. {
  19. _end_point = Environment.GetEnvironmentVariable("EndPoint");
  20. }
  21. private static SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
  22. private static IEnumerable<TkPoolDTO> _cached;
  23. private static IEnumerable<TkPoolDTO> _all_cached;
  24. public static IEnumerable<TkPoolDTO> GetCachedAccounts()
  25. {
  26. return _all_cached ?? _cached ?? Enumerable.Empty<TkPoolDTO>();
  27. }
  28. public static async Task<TkPoolDTO> GetOneAsync(int id)
  29. {
  30. var list = await ListAsync();
  31. if (!list.Any()) return null;
  32. return list.Where(e => e.id == id).FirstOrDefault();
  33. }
  34. public static async Task<TkPoolDTO> ALLGetOneAsync(int id)
  35. {
  36. var list = await AllListAsync();
  37. if (!list.Any()) return null;
  38. return list.Where(e => e.id == id).FirstOrDefault();
  39. }
  40. public static async Task<TkPoolDTO> GetOneAsync2(TkAction action)
  41. {
  42. var list = await ListAsync().ConfigureAwait(false);
  43. if (!list.Any()) return null;
  44. // 线程安全的随机排序
  45. var random = new Random(Guid.NewGuid().GetHashCode());
  46. var shuffled = list.OrderBy(_ => random.Next()).ToList();
  47. foreach (var item in shuffled)
  48. {
  49. if (await FilterNodesAsync(item, action).ConfigureAwait(false))
  50. return item;
  51. }
  52. return null;
  53. }
  54. public static async Task<TkPoolDTO> GetOneAsync(TkAction action, bool isTaobaoUrl, string riskStrategy, int launchScene, string parse_type = "", string strategy_id = "")
  55. {
  56. var list = await ListAsync().ConfigureAwait(false);
  57. if (!list.Any())
  58. return null;
  59. // 获取所有账号(包括离线账号)
  60. var allAccounts = await AllListAsync().ConfigureAwait(false);
  61. if (allAccounts == null)
  62. return null;
  63. if (!string.IsNullOrEmpty(strategy_id))
  64. {
  65. list = list.Where(item => strategy_id.Equals(item.strategy_id)).ToList();
  66. }
  67. else
  68. {
  69. list = list.Where(item => string.IsNullOrEmpty(item.strategy_id)).ToList();
  70. }
  71. if (!list.Any()) return null;
  72. if ("dp".Equals(parse_type))
  73. {
  74. list = list.Where(item => "dp".Equals(item.parse_type)).ToList();
  75. if (!list.Any()) return null;
  76. }
  77. else if ("ym".Equals(parse_type))
  78. {
  79. list = list.Where(item => "ym".Equals(item.parse_type)).ToList();
  80. if (!list.Any()) return null;
  81. }
  82. else
  83. {
  84. list = list.Where(item => string.IsNullOrEmpty(item.parse_type)).ToList();
  85. }
  86. if (!list.Any()) return null;
  87. if (!string.IsNullOrEmpty(riskStrategy) && !"os".Equals(riskStrategy) && launchScene != -1)
  88. {
  89. list = list.Where(item => riskStrategy.Equals(item.riskStrategy) && item.launchScene == launchScene).ToList();
  90. }
  91. else
  92. {
  93. list = list.Where(item => string.IsNullOrEmpty(item.riskStrategy)).ToList();
  94. }
  95. if (!list.Any()) return null;
  96. list = FilterByAction(list, action).ToList();
  97. if (!list.Any()) return null;
  98. list = list.Where(item => PassesFastAccountChecks(item, action)).ToList();
  99. if (!list.Any()) return null;
  100. var ownerByRelatedId = BuildOwnerByRelatedAccountId(allAccounts);
  101. var onlineAccountIds = list.Select(a => a.id).ToHashSet();
  102. var filteredList = list
  103. .Where(item =>
  104. !ownerByRelatedId.TryGetValue(item.id, out var ownerAccount) ||
  105. onlineAccountIds.Contains(ownerAccount.id) ||
  106. !ownerAccount.enable_fake_click)
  107. .ToList();
  108. if (filteredList.Count == 0) return null;
  109. // 1. 筛选出有可用端点的账号池,并计算权重
  110. var weightedAccounts = new List<(TkPoolDTO account, int weight)>();
  111. var random = new Random(Guid.NewGuid().GetHashCode()); // 避免重复种子问题
  112. foreach (var item in filteredList)
  113. {
  114. // 获取账号关联的所有端点配置
  115. var endpoints = await TkEndpointCore.GetEndpointsByAccountReadonlyAsync(item.id, isTaobaoUrl, item.parseEndpoint).ConfigureAwait(false);
  116. if (endpoints == null || endpoints.Count == 0)
  117. continue;
  118. // 过滤可用端点(状态正常且未达限制)
  119. var availableEndpoints = endpoints
  120. .Where(e => e.status)
  121. .Where(e => e.hourly_calls_limit <= 0 || e.current_hourly_calls < e.hourly_calls_limit)
  122. .Where(e => e.daily_calls_limit <= 0 || e.current_daily_calls < e.daily_calls_limit)
  123. .Where(e => !TkEndpointManager.IsEndpointSuspended(item.id, e.endpoint)) // 直接检查端点对象
  124. .ToList();
  125. if (availableEndpoints.Count == 0) continue;
  126. // 计算账号权重(基于剩余调用量)
  127. int weight = availableEndpoints.Sum(e =>
  128. e.hourly_calls_limit <= 0 ? 3600 : e.hourly_calls_limit - e.current_hourly_calls);
  129. weightedAccounts.Add((item, weight));
  130. }
  131. if (weightedAccounts.Count == 0) return null;
  132. // 2. 保留原有加权随机选择,选中账号超出 QPS 时继续尝试其他账号
  133. int totalWeight = weightedAccounts.Sum(x => x.weight);
  134. int randomNumber = random.Next(0, totalWeight);
  135. foreach (var (account, weight) in weightedAccounts)
  136. {
  137. if (randomNumber < weight)
  138. {
  139. if (await FilterNodesAsync(account, action).ConfigureAwait(false) && TryAcquireQps(account))
  140. return account;
  141. break;
  142. }
  143. randomNumber -= weight;
  144. }
  145. // 3. 选中账号不可用或超过 QPS 时,回退尝试其他候选账号
  146. var fallbackCandidates = weightedAccounts
  147. .OrderBy(_ => random.Next())
  148. .Select(x => x.account);
  149. foreach (var account in fallbackCandidates)
  150. {
  151. if (await FilterNodesAsync(account, action).ConfigureAwait(false) && TryAcquireQps(account))
  152. return account;
  153. }
  154. return null;
  155. }
  156. private static bool TryAcquireQps(TkPoolDTO account)
  157. {
  158. if (account == null) return false;
  159. return SpecialBusinessRateLimiter.TryAcquire(
  160. $"tk_pool_qps:{account.id}",
  161. account.qps_limit,
  162. TimeSpan.FromSeconds(1));
  163. }
  164. private static async Task<bool> FilterNodesAsync(TkPoolDTO item, TkAction action)
  165. {
  166. if (!PassesFastAccountChecks(item, action)) return false;
  167. if (item.daily_calls_limit > 0)
  168. {
  169. int daily_num = RiskControlCore.GetCalls(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMdd"));
  170. if (daily_num >= item.daily_calls_limit) return false;
  171. }
  172. if (item.hourly_calls_limit > 0)
  173. {
  174. int hourly_num = RiskControlCore.GetCalls(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMddHH"));
  175. if (hourly_num >= item.hourly_calls_limit) return false;
  176. }
  177. var endpointCheck = await TkEndpointManager.HasAvailableEndpointAsync(item.id).ConfigureAwait(false);
  178. if (!endpointCheck) return false;
  179. switch (action)
  180. {
  181. case TkAction.parse:
  182. if (!item.enable_parse) return false;
  183. break;
  184. case TkAction.promotionQuery:
  185. if (!item.enable_promotionQuery) return false;
  186. break;
  187. case TkAction.coupon:
  188. case TkAction.activity:
  189. if (!item.enable_coupon) return false;
  190. break;
  191. }
  192. if (item.daily_income_limit == 0) return true;
  193. decimal income_amt = RiskControlCore.GetIncomeAmt(TkChannelEnum.tb, $"{item.id}");
  194. return income_amt < item.daily_income_limit;
  195. }
  196. private static IEnumerable<TkPoolDTO> FilterByAction(IEnumerable<TkPoolDTO> accounts, TkAction action)
  197. {
  198. return action switch
  199. {
  200. TkAction.parse => accounts.Where(item => item.enable_parse),
  201. TkAction.promotionQuery => accounts.Where(item => item.enable_promotionQuery),
  202. TkAction.coupon => accounts.Where(item => item.enable_coupon),
  203. TkAction.activity => accounts.Where(item => item.enable_coupon),
  204. _ => accounts
  205. };
  206. }
  207. private static bool PassesFastAccountChecks(TkPoolDTO item, TkAction action)
  208. {
  209. if (!string.IsNullOrEmpty(item.suspended_endpoint) && item.suspended_endpoint.Contains($"{_end_point}|")) return false;
  210. if (!string.IsNullOrEmpty(_end_point) && !string.IsNullOrEmpty(item.end_point) && item.end_point != _end_point)
  211. return false;
  212. if (!new WorkSchedule(item.time_range).IsWorkHour()) return false;
  213. return action switch
  214. {
  215. TkAction.parse => item.enable_parse,
  216. TkAction.promotionQuery => item.enable_promotionQuery,
  217. TkAction.coupon => item.enable_coupon,
  218. TkAction.activity => item.enable_coupon,
  219. _ => true
  220. };
  221. }
  222. private static Dictionary<int, TkPoolDTO> BuildOwnerByRelatedAccountId(IEnumerable<TkPoolDTO> allAccounts)
  223. {
  224. var result = new Dictionary<int, TkPoolDTO>();
  225. foreach (var account in allAccounts)
  226. {
  227. if (string.IsNullOrWhiteSpace(account.related_account_ids)) continue;
  228. foreach (var idStr in account.related_account_ids.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
  229. {
  230. if (!int.TryParse(idStr, out var relatedId)) continue;
  231. result.TryAdd(relatedId, account);
  232. }
  233. }
  234. return result;
  235. }
  236. public static async Task<IEnumerable<TkPoolDTO>> AllListAsync(bool force = false)
  237. {
  238. if (!force && _all_cached != default) return _all_cached;
  239. try
  240. {
  241. await _semaphore.WaitAsync();
  242. string cache_key = $"cache:all_tk_pool";
  243. var list = await RedisKit.GetAsync<IEnumerable<TkPoolDTO>>(cache_key);
  244. if (force || list == default)
  245. {
  246. list = new DBContext.Table("tk_pool").Select<TkPoolDTO>();
  247. if (list == null) return default;
  248. // 等待 Redis 写入完成
  249. await RedisKit.SetAsync(cache_key, list, 30 * 86400);
  250. }
  251. _all_cached = list;
  252. return list;
  253. }
  254. catch (Exception)
  255. {
  256. // 发生异常时返回上一次的缓存,如果没有则返回默认值
  257. return _all_cached ?? default;
  258. }
  259. finally
  260. {
  261. _semaphore.Release();
  262. }
  263. }
  264. public static async Task<IEnumerable<TkPoolDTO>> ListAsync(bool force = false)
  265. {
  266. // 内存缓存检查
  267. if (!force && _cached != null) return _cached;
  268. string cache_key = "cache:tk_pool";
  269. if (!force)
  270. {
  271. var cachedList = await RedisHelper.GetAsync<IEnumerable<TkPoolDTO>>(cache_key);
  272. if (cachedList != null)
  273. {
  274. _cached = cachedList;
  275. return cachedList;
  276. }
  277. }
  278. // 获取新数据
  279. await _semaphore.WaitAsync();
  280. try
  281. {
  282. // 双重检查,防止并发情况下重复加载
  283. if (!force)
  284. {
  285. var cachedList = await RedisHelper.GetAsync<IEnumerable<TkPoolDTO>>(cache_key);
  286. if (cachedList != null)
  287. {
  288. _cached = cachedList;
  289. return cachedList;
  290. }
  291. }
  292. // 从数据库加载数据
  293. var list = new DBContext.Table("tk_pool")
  294. .Where("status=@status", new { status = 1 })
  295. .Select<TkPoolDTO>();
  296. if (list == null) return default;
  297. // 更新调用次数
  298. foreach (var item in list)
  299. {
  300. _ = RiskControlCore.SetCallsAsync(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMddHH"), item.current_hourly_calls);
  301. _ = RiskControlCore.SetCallsAsync(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMdd"), item.current_daily_calls);
  302. }
  303. // 更新缓存
  304. await RedisHelper.SetAsync(cache_key, list, 30 * 86400);
  305. _cached = list;
  306. return list;
  307. }
  308. finally
  309. {
  310. _semaphore.Release();
  311. }
  312. }
  313. public static void Refresh()
  314. {
  315. _ = ListAsync(true);
  316. _ = AllListAsync(true);
  317. TkEndpointCore.Refresh();
  318. TkEndpointManager.Refresh();
  319. }
  320. public static void UpdateDrawBalance(string name, decimal amout)
  321. {
  322. new DBContext.Table("tk_pool")
  323. .Add("draw_balance", amout)
  324. .Where("name=@name", new { name })
  325. .Update();
  326. _ = ListAsync(true);
  327. }
  328. public static void Suspend(string endpoint, int accountId, string name, string content)
  329. {
  330. string cache_key = $"cache:tk_pool:{accountId}:suspend";
  331. long count = RedisHelper.IncrBy(cache_key);
  332. RedisHelper.Expire(cache_key, 10);
  333. if (count > 1) return;
  334. var update = new DBContext.Table("tk_pool").Add("suspended_endpoint:", $"CONCAT(suspended_endpoint, '{endpoint},')");
  335. if (accountId > 0)
  336. {
  337. update.Where("id=@accountId", new { accountId }).Update();
  338. }
  339. else
  340. {
  341. update.Where("name=@name", new { name }).Update();
  342. }
  343. _ = ListAsync(true);
  344. NotifyCore.Notify(new NifyMessage
  345. {
  346. message = $"【淘客{accountId}:{name}】{endpoint} 暂停",
  347. priority = NifyMessagePriority.high,
  348. tags = ["red_circle"]
  349. });
  350. _ = EndPointCore.NotifyReload(true);
  351. }
  352. public static void Disabled(int accountId, string name, string content, bool is_hide)
  353. {
  354. #if DEBUG
  355. #else
  356. #endif
  357. string cache_key = $"cache:tk_pool:{accountId}:disabled";
  358. long count = RedisHelper.IncrBy(cache_key);
  359. RedisHelper.Expire(cache_key, 10);
  360. if (count > 1) return;
  361. var update = new DBContext.Table("tk_pool").Add("status", 0);
  362. if (accountId > 0)
  363. {
  364. update.Where("id=@accountId", new { accountId }).Update();
  365. }
  366. else
  367. {
  368. update.Where("name=@name", new { name }).Update();
  369. }
  370. _ = ListAsync(true);
  371. _ = AllListAsync(true);
  372. NotifyCore.Notify(new NifyMessage
  373. {
  374. message = $"【淘客{accountId}:{name}】cookie 掉线\n\n{content}",
  375. priority = NifyMessagePriority.high,
  376. tags = ["red_circle"]
  377. });
  378. if (!is_hide)
  379. {
  380. _ = NotifyCore.QYWeixinPushNotifyAsync("掉线", $"【淘客{accountId}:{name}】cookie 掉线");
  381. }
  382. _ = EndPointCore.NotifyReload(true);
  383. }
  384. public static async Task<int> UpdateCookies(string cookies, string user_agent)
  385. {
  386. if (string.IsNullOrEmpty(cookies)) return 0;
  387. cookies += ";";
  388. string dnk = cookies.GetContentPart("dnk=", ";");
  389. string company = dnk;
  390. int accountId = 0;
  391. string tb_token = cookies.GetContentPart("_tb_token_=", ";");
  392. if (string.IsNullOrEmpty(dnk) || string.IsNullOrEmpty(tb_token)) return 0;
  393. var exist = new DBContext.Table("tk_pool").Fields("id, name, company, refpid, status").Get<dynamic>("name=@dnk", new { dnk });
  394. if (exist != null)
  395. {
  396. int status = exist.status;
  397. string refpid = exist.refpid;
  398. company = exist.company;
  399. accountId = exist.id;
  400. if (!string.IsNullOrEmpty(refpid)) status = 1;
  401. new DBContext.Table("tk_pool")
  402. .Add("name", dnk)
  403. .Add("tb_token", tb_token)
  404. .Add("cookies", cookies)
  405. .Add("user_agent", user_agent)
  406. .Add("status", status)
  407. .Add("suspended_endpoint", string.Empty)
  408. .Add("last_time", DateTime.Now)
  409. .Add("login_time", DateTime.Now)
  410. .Where("id=@id", new { exist.id })
  411. .Update();
  412. RiskControlCore.SetRiskCookie($"tb:{exist.id}", "");
  413. if (status == 1) _ = ListAsync(true);
  414. }
  415. else
  416. {
  417. accountId = new DBContext.Table("tk_pool")
  418. .Add("name", dnk)
  419. .Add("description", "由cookies上报创建此记录")
  420. .Add("tb_token", tb_token)
  421. .Add("refpid", string.Empty)
  422. .Add("cookies", cookies)
  423. .Add("user_agent", user_agent)
  424. .Add("create_time", DateTime.Now)
  425. .Add("last_time", DateTime.Now)
  426. .Add("login_time", DateTime.Now)
  427. .Add("status", 0)
  428. .Create();
  429. RiskControlCore.SetRiskCookie($"tb:{accountId}", "");
  430. }
  431. NotifyCore.Notify(new NifyMessage
  432. {
  433. message = $"【淘客{accountId}:{company}】cookie 上线",
  434. tags = ["green_circle"]
  435. });
  436. _ = EndPointCore.NotifyReload(true);
  437. //NotifyCore.QYWeixinPushNotifyAsync("上线", $"【淘宝联盟:{dnk}】cookie 上报更新");
  438. return accountId;
  439. }
  440. internal static void AccountExhausted()
  441. {
  442. string cache_key = $"cache:tk_pool:account:exhausted";
  443. long count = RedisHelper.IncrBy(cache_key);
  444. if (count > 1) return;
  445. RedisHelper.Expire(cache_key, 3600);
  446. NotifyCore.Notify(new NifyMessage
  447. {
  448. message = $"【淘客】没有匹配账号",
  449. priority = NifyMessagePriority.high,
  450. tags = ["red_circle"]
  451. });
  452. _ = NotifyCore.QYWeixinPushNotifyAsync("没账号", $"【淘客】没有匹配账号");
  453. }
  454. }
  455. }