TkPoolCore.cs 20 KB

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