TkPoolCore.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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. /// <summary>
  165. /// 归还分配账号时占用的 QPS 名额(转链未提交到 endpoint 时调用)
  166. /// </summary>
  167. public static void ReleaseQps(TkPoolDTO account, long acquiredSinceTicks)
  168. {
  169. if (account == null || account.qps_limit <= 0) return;
  170. SpecialBusinessRateLimiter.Release(
  171. $"tk_pool_qps:{account.id}",
  172. TimeSpan.FromSeconds(1),
  173. acquiredSinceTicks);
  174. }
  175. private static async Task<bool> FilterNodesAsync(TkPoolDTO item, TkAction action)
  176. {
  177. if (!PassesFastAccountChecks(item, action)) return false;
  178. if (item.daily_calls_limit > 0)
  179. {
  180. int daily_num = RiskControlCore.GetCalls(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMdd"));
  181. if (daily_num >= item.daily_calls_limit) return false;
  182. }
  183. if (item.hourly_calls_limit > 0)
  184. {
  185. int hourly_num = RiskControlCore.GetCalls(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMddHH"));
  186. if (hourly_num >= item.hourly_calls_limit) return false;
  187. }
  188. var endpointCheck = await TkEndpointManager.HasAvailableEndpointAsync(item.id).ConfigureAwait(false);
  189. if (!endpointCheck) return false;
  190. switch (action)
  191. {
  192. case TkAction.parse:
  193. if (!item.enable_parse) return false;
  194. break;
  195. case TkAction.promotionQuery:
  196. if (!item.enable_promotionQuery) return false;
  197. break;
  198. case TkAction.coupon:
  199. case TkAction.activity:
  200. if (!item.enable_coupon) return false;
  201. break;
  202. }
  203. if (item.daily_income_limit == 0) return true;
  204. decimal income_amt = RiskControlCore.GetIncomeAmt(TkChannelEnum.tb, $"{item.id}");
  205. return income_amt < item.daily_income_limit;
  206. }
  207. private static IEnumerable<TkPoolDTO> FilterByAction(IEnumerable<TkPoolDTO> accounts, TkAction action)
  208. {
  209. return action switch
  210. {
  211. TkAction.parse => accounts.Where(item => item.enable_parse),
  212. TkAction.promotionQuery => accounts.Where(item => item.enable_promotionQuery),
  213. TkAction.coupon => accounts.Where(item => item.enable_coupon),
  214. TkAction.activity => accounts.Where(item => item.enable_coupon),
  215. _ => accounts
  216. };
  217. }
  218. private static bool PassesFastAccountChecks(TkPoolDTO item, TkAction action)
  219. {
  220. if (!string.IsNullOrEmpty(item.suspended_endpoint) && item.suspended_endpoint.Contains($"{_end_point}|")) return false;
  221. if (!string.IsNullOrEmpty(_end_point) && !string.IsNullOrEmpty(item.end_point) && item.end_point != _end_point)
  222. return false;
  223. if (!new WorkSchedule(item.time_range).IsWorkHour()) return false;
  224. return action switch
  225. {
  226. TkAction.parse => item.enable_parse,
  227. TkAction.promotionQuery => item.enable_promotionQuery,
  228. TkAction.coupon => item.enable_coupon,
  229. TkAction.activity => item.enable_coupon,
  230. _ => true
  231. };
  232. }
  233. private static Dictionary<int, TkPoolDTO> BuildOwnerByRelatedAccountId(IEnumerable<TkPoolDTO> allAccounts)
  234. {
  235. var result = new Dictionary<int, TkPoolDTO>();
  236. foreach (var account in allAccounts)
  237. {
  238. if (string.IsNullOrWhiteSpace(account.related_account_ids)) continue;
  239. foreach (var idStr in account.related_account_ids.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
  240. {
  241. if (!int.TryParse(idStr, out var relatedId)) continue;
  242. result.TryAdd(relatedId, account);
  243. }
  244. }
  245. return result;
  246. }
  247. public static async Task<IEnumerable<TkPoolDTO>> AllListAsync(bool force = false)
  248. {
  249. if (!force && _all_cached != default) return _all_cached;
  250. try
  251. {
  252. await _semaphore.WaitAsync();
  253. string cache_key = $"cache:all_tk_pool";
  254. var list = await RedisKit.GetAsync<IEnumerable<TkPoolDTO>>(cache_key);
  255. if (force || list == default)
  256. {
  257. list = new DBContext.Table("tk_pool").Select<TkPoolDTO>();
  258. if (list == null) return default;
  259. // 等待 Redis 写入完成
  260. await RedisKit.SetAsync(cache_key, list, 30 * 86400);
  261. }
  262. _all_cached = list;
  263. return list;
  264. }
  265. catch (Exception)
  266. {
  267. // 发生异常时返回上一次的缓存,如果没有则返回默认值
  268. return _all_cached ?? default;
  269. }
  270. finally
  271. {
  272. _semaphore.Release();
  273. }
  274. }
  275. public static async Task<IEnumerable<TkPoolDTO>> ListAsync(bool force = false)
  276. {
  277. // 内存缓存检查
  278. if (!force && _cached != null) return _cached;
  279. string cache_key = "cache:tk_pool";
  280. if (!force)
  281. {
  282. var cachedList = await RedisHelper.GetAsync<IEnumerable<TkPoolDTO>>(cache_key);
  283. if (cachedList != null)
  284. {
  285. _cached = cachedList;
  286. return cachedList;
  287. }
  288. }
  289. // 获取新数据
  290. await _semaphore.WaitAsync();
  291. try
  292. {
  293. // 双重检查,防止并发情况下重复加载
  294. if (!force)
  295. {
  296. var cachedList = await RedisHelper.GetAsync<IEnumerable<TkPoolDTO>>(cache_key);
  297. if (cachedList != null)
  298. {
  299. _cached = cachedList;
  300. return cachedList;
  301. }
  302. }
  303. // 从数据库加载数据
  304. var list = new DBContext.Table("tk_pool")
  305. .Where("status=@status", new { status = 1 })
  306. .Select<TkPoolDTO>();
  307. if (list == null) return default;
  308. // 更新调用次数
  309. foreach (var item in list)
  310. {
  311. _ = RiskControlCore.SetCallsAsync(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMddHH"), item.current_hourly_calls);
  312. _ = RiskControlCore.SetCallsAsync(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMdd"), item.current_daily_calls);
  313. }
  314. // 更新缓存
  315. await RedisHelper.SetAsync(cache_key, list, 30 * 86400);
  316. _cached = list;
  317. return list;
  318. }
  319. finally
  320. {
  321. _semaphore.Release();
  322. }
  323. }
  324. public static void Refresh()
  325. {
  326. _ = ListAsync(true);
  327. _ = AllListAsync(true);
  328. TkEndpointCore.Refresh();
  329. TkEndpointManager.Refresh();
  330. }
  331. public static void UpdateDrawBalance(string name, decimal amout)
  332. {
  333. new DBContext.Table("tk_pool")
  334. .Add("draw_balance", amout)
  335. .Where("name=@name", new { name })
  336. .Update();
  337. _ = ListAsync(true);
  338. }
  339. public static void Suspend(string endpoint, int accountId, string name, string content)
  340. {
  341. string cache_key = $"cache:tk_pool:{accountId}:suspend";
  342. long count = RedisHelper.IncrBy(cache_key);
  343. RedisHelper.Expire(cache_key, 10);
  344. if (count > 1) return;
  345. var update = new DBContext.Table("tk_pool").Add("suspended_endpoint:", $"CONCAT(suspended_endpoint, '{endpoint},')");
  346. if (accountId > 0)
  347. {
  348. update.Where("id=@accountId", new { accountId }).Update();
  349. }
  350. else
  351. {
  352. update.Where("name=@name", new { name }).Update();
  353. }
  354. _ = ListAsync(true);
  355. NotifyCore.Notify(new NifyMessage
  356. {
  357. message = $"【淘客{accountId}:{name}】{endpoint} 暂停",
  358. priority = NifyMessagePriority.high,
  359. tags = ["red_circle"]
  360. });
  361. _ = EndPointCore.NotifyReload(true);
  362. }
  363. public static void Disabled(int accountId, string name, string content, bool is_hide)
  364. {
  365. #if DEBUG
  366. #else
  367. #endif
  368. string cache_key = $"cache:tk_pool:{accountId}:disabled";
  369. long count = RedisHelper.IncrBy(cache_key);
  370. RedisHelper.Expire(cache_key, 10);
  371. if (count > 1) return;
  372. var update = new DBContext.Table("tk_pool").Add("status", 0);
  373. if (accountId > 0)
  374. {
  375. update.Where("id=@accountId", new { accountId }).Update();
  376. }
  377. else
  378. {
  379. update.Where("name=@name", new { name }).Update();
  380. }
  381. _ = ListAsync(true);
  382. _ = AllListAsync(true);
  383. NotifyCore.Notify(new NifyMessage
  384. {
  385. message = $"【淘客{accountId}:{name}】cookie 掉线\n\n{content}",
  386. priority = NifyMessagePriority.high,
  387. tags = ["red_circle"]
  388. });
  389. if (!is_hide)
  390. {
  391. _ = NotifyCore.QYWeixinPushNotifyAsync("掉线", $"【淘客{accountId}:{name}】cookie 掉线");
  392. }
  393. _ = EndPointCore.NotifyReload(true);
  394. }
  395. public static async Task<int> UpdateCookies(string cookies, string user_agent)
  396. {
  397. if (string.IsNullOrEmpty(cookies)) return 0;
  398. cookies += ";";
  399. string dnk = cookies.GetContentPart("dnk=", ";");
  400. string company = dnk;
  401. int accountId = 0;
  402. string tb_token = cookies.GetContentPart("_tb_token_=", ";");
  403. if (string.IsNullOrEmpty(dnk) || string.IsNullOrEmpty(tb_token)) return 0;
  404. var exist = new DBContext.Table("tk_pool").Fields("id, name, company, refpid, status").Get<dynamic>("name=@dnk", new { dnk });
  405. if (exist != null)
  406. {
  407. int status = exist.status;
  408. string refpid = exist.refpid;
  409. company = exist.company;
  410. accountId = exist.id;
  411. if (!string.IsNullOrEmpty(refpid)) status = 1;
  412. new DBContext.Table("tk_pool")
  413. .Add("name", dnk)
  414. .Add("tb_token", tb_token)
  415. .Add("cookies", cookies)
  416. .Add("user_agent", user_agent)
  417. .Add("status", status)
  418. .Add("suspended_endpoint", string.Empty)
  419. .Add("last_time", DateTime.Now)
  420. .Add("login_time", DateTime.Now)
  421. .Where("id=@id", new { exist.id })
  422. .Update();
  423. RiskControlCore.SetRiskCookie($"tb:{exist.id}", "");
  424. if (status == 1) _ = ListAsync(true);
  425. }
  426. else
  427. {
  428. accountId = new DBContext.Table("tk_pool")
  429. .Add("name", dnk)
  430. .Add("description", "由cookies上报创建此记录")
  431. .Add("tb_token", tb_token)
  432. .Add("refpid", string.Empty)
  433. .Add("cookies", cookies)
  434. .Add("user_agent", user_agent)
  435. .Add("create_time", DateTime.Now)
  436. .Add("last_time", DateTime.Now)
  437. .Add("login_time", DateTime.Now)
  438. .Add("status", 0)
  439. .Create();
  440. RiskControlCore.SetRiskCookie($"tb:{accountId}", "");
  441. }
  442. NotifyCore.Notify(new NifyMessage
  443. {
  444. message = $"【淘客{accountId}:{company}】cookie 上线",
  445. tags = ["green_circle"]
  446. });
  447. _ = EndPointCore.NotifyReload(true);
  448. //NotifyCore.QYWeixinPushNotifyAsync("上线", $"【淘宝联盟:{dnk}】cookie 上报更新");
  449. return accountId;
  450. }
  451. internal static void AccountExhausted()
  452. {
  453. string cache_key = $"cache:tk_pool:account:exhausted";
  454. long count = RedisHelper.IncrBy(cache_key);
  455. if (count > 1) return;
  456. RedisHelper.Expire(cache_key, 3600);
  457. NotifyCore.Notify(new NifyMessage
  458. {
  459. message = $"【淘客】没有匹配账号",
  460. priority = NifyMessagePriority.high,
  461. tags = ["red_circle"]
  462. });
  463. _ = NotifyCore.QYWeixinPushNotifyAsync("没账号", $"【淘客】没有匹配账号");
  464. }
  465. }
  466. }