TkPoolCore.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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. var filteredList = new List<TkPoolDTO>();
  97. foreach (var item in list)
  98. {
  99. // 在所有账号中检查是否有账号关联了当前账号
  100. var ownerAccount = allAccounts.FirstOrDefault(other =>
  101. other.id != item.id &&
  102. !string.IsNullOrEmpty(other.related_account_ids) &&
  103. other.related_account_ids.Split(',').Contains(item.id.ToString()));
  104. // 如果没有账号关联它,或者关联它的账号在线,或者主账号不需要补点击,则可以使用
  105. if (ownerAccount == null || list.Any(a => a.id == ownerAccount.id) || !ownerAccount.enable_fake_click)
  106. {
  107. filteredList.Add(item);
  108. }
  109. }
  110. foreach (var item in list)
  111. {
  112. // 在所有账号中检查是否有账号关联了当前账号
  113. var ownerAccount = allAccounts.FirstOrDefault(other =>
  114. other.id != item.id &&
  115. !string.IsNullOrEmpty(other.related_account_ids) &&
  116. other.related_account_ids.Split(',').Contains(item.id.ToString()));
  117. // 如果没有账号关联它,或者关联它的账号在线,或者主账号不需要补点击,则可以使用
  118. if (ownerAccount == null || list.Any(a => a.id == ownerAccount.id) || !ownerAccount.enable_fake_click)
  119. {
  120. filteredList.Add(item);
  121. }
  122. }
  123. if (filteredList.Count == 0) return null;
  124. // 1. 筛选出有可用端点的账号池,并计算权重
  125. var weightedAccounts = new List<(TkPoolDTO account, int weight)>();
  126. var random = new Random(Guid.NewGuid().GetHashCode()); // 避免重复种子问题
  127. foreach (var item in filteredList)
  128. {
  129. // 获取账号关联的所有端点配置
  130. var endpoints = await TkEndpointCore.GetEndpointsByAccountAsync(item.id, isTaobaoUrl, item.parseEndpoint);
  131. if (endpoints == null || endpoints.Count == 0)
  132. continue;
  133. // 过滤可用端点(状态正常且未达限制)
  134. var availableEndpoints = endpoints
  135. .Where(e => e.status)
  136. .Where(e => e.hourly_calls_limit <= 0 || e.current_hourly_calls < e.hourly_calls_limit)
  137. .Where(e => e.daily_calls_limit <= 0 || e.current_daily_calls < e.daily_calls_limit)
  138. .Where(e => !TkEndpointManager.IsEndpointSuspended(item.id, e.endpoint)) // 直接检查端点对象
  139. .ToList();
  140. if (availableEndpoints.Count == 0) continue;
  141. // 计算账号权重(基于剩余调用量)
  142. int weight = availableEndpoints.Sum(e =>
  143. e.hourly_calls_limit <= 0 ? 3600 : e.hourly_calls_limit - e.current_hourly_calls);
  144. weightedAccounts.Add((item, weight));
  145. }
  146. if (weightedAccounts.Count == 0) return null;
  147. // 2. 加权随机选择
  148. int totalWeight = weightedAccounts.Sum(x => x.weight);
  149. int randomNumber = random.Next(0, totalWeight);
  150. foreach (var (account, weight) in weightedAccounts)
  151. {
  152. if (randomNumber < weight)
  153. {
  154. if (await FilterNodesAsync(account, action).ConfigureAwait(false))
  155. return account;
  156. break; // 如果过滤失败,跳出当前循环
  157. }
  158. randomNumber -= weight;
  159. }
  160. // 3. 如果加权选择失败,回退到简单随机选择
  161. var fallbackCandidates = weightedAccounts
  162. .OrderBy(_ => random.Next())
  163. .Select(x => x.account);
  164. foreach (var account in fallbackCandidates)
  165. {
  166. if (await FilterNodesAsync(account, action).ConfigureAwait(false))
  167. return account;
  168. }
  169. return null;
  170. }
  171. private static async Task<bool> FilterNodesAsync(TkPoolDTO item, TkAction action)
  172. {
  173. if (!string.IsNullOrEmpty(item.suspended_endpoint) && item.suspended_endpoint.Contains($"{_end_point}|")) return false;
  174. if (!string.IsNullOrEmpty(_end_point) && !string.IsNullOrEmpty(item.end_point))
  175. {
  176. if (item.end_point != _end_point) return false;
  177. }
  178. // 使用初始化参数创建工作时间表
  179. if (!new WorkSchedule(item.time_range).IsWorkHour()) return false;
  180. if (item.daily_calls_limit > 0)
  181. {
  182. int daily_num = RiskControlCore.GetCalls(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMdd"));
  183. if (daily_num >= item.daily_calls_limit) return false;
  184. }
  185. if (item.hourly_calls_limit > 0)
  186. {
  187. int hourly_num = RiskControlCore.GetCalls(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMddHH"));
  188. if (hourly_num >= item.hourly_calls_limit) return false;
  189. }
  190. var endpointCheck = await TkEndpointManager.HasAvailableEndpointAsync(item.id).ConfigureAwait(false);
  191. if (!endpointCheck) return false;
  192. switch (action)
  193. {
  194. case TkAction.parse:
  195. if (!item.enable_parse) return false;
  196. break;
  197. case TkAction.promotionQuery:
  198. if (!item.enable_promotionQuery) return false;
  199. break;
  200. case TkAction.coupon:
  201. case TkAction.activity:
  202. if (!item.enable_coupon) return false;
  203. break;
  204. }
  205. if (item.daily_income_limit == 0) return true;
  206. decimal income_amt = RiskControlCore.GetIncomeAmt(TkChannelEnum.tb, $"{item.id}");
  207. return income_amt < item.daily_income_limit;
  208. }
  209. public static async Task<IEnumerable<TkPoolDTO>> AllListAsync(bool force = false)
  210. {
  211. if (!force && _all_cached != default) return _all_cached;
  212. try
  213. {
  214. await _semaphore.WaitAsync();
  215. string cache_key = $"cache:all_tk_pool";
  216. var list = await RedisKit.GetAsync<IEnumerable<TkPoolDTO>>(cache_key);
  217. if (force || list == default)
  218. {
  219. list = new DBContext.Table("tk_pool").Select<TkPoolDTO>();
  220. if (list == null) return default;
  221. // 等待 Redis 写入完成
  222. await RedisKit.SetAsync(cache_key, list, 30 * 86400);
  223. }
  224. _all_cached = list;
  225. return list;
  226. }
  227. catch (Exception)
  228. {
  229. // 发生异常时返回上一次的缓存,如果没有则返回默认值
  230. return _all_cached ?? default;
  231. }
  232. finally
  233. {
  234. _semaphore.Release();
  235. }
  236. }
  237. public static async Task<IEnumerable<TkPoolDTO>> ListAsync(bool force = false)
  238. {
  239. // 内存缓存检查
  240. if (!force && _cached != null) return _cached;
  241. string cache_key = "cache:tk_pool";
  242. if (!force)
  243. {
  244. var cachedList = await RedisHelper.GetAsync<IEnumerable<TkPoolDTO>>(cache_key);
  245. if (cachedList != null)
  246. {
  247. _cached = cachedList;
  248. return cachedList;
  249. }
  250. }
  251. // 获取新数据
  252. await _semaphore.WaitAsync();
  253. try
  254. {
  255. // 双重检查,防止并发情况下重复加载
  256. if (!force)
  257. {
  258. var cachedList = await RedisHelper.GetAsync<IEnumerable<TkPoolDTO>>(cache_key);
  259. if (cachedList != null)
  260. {
  261. _cached = cachedList;
  262. return cachedList;
  263. }
  264. }
  265. // 从数据库加载数据
  266. var list = new DBContext.Table("tk_pool")
  267. .Where("status=@status", new { status = 1 })
  268. .Select<TkPoolDTO>();
  269. if (list == null) return default;
  270. // 更新调用次数
  271. foreach (var item in list)
  272. {
  273. _ = RiskControlCore.SetCallsAsync(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMddHH"), item.current_hourly_calls);
  274. _ = RiskControlCore.SetCallsAsync(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMdd"), item.current_daily_calls);
  275. }
  276. // 更新缓存
  277. await RedisHelper.SetAsync(cache_key, list, 30 * 86400);
  278. _cached = list;
  279. return list;
  280. }
  281. finally
  282. {
  283. _semaphore.Release();
  284. }
  285. }
  286. public static void Refresh()
  287. {
  288. _ = ListAsync(true);
  289. _ = AllListAsync(true);
  290. TkEndpointCore.Refresh();
  291. TkEndpointManager.Refresh();
  292. }
  293. public static void UpdateDrawBalance(string name, decimal amout)
  294. {
  295. new DBContext.Table("tk_pool")
  296. .Add("draw_balance", amout)
  297. .Where("name=@name", new { name })
  298. .Update();
  299. _ = ListAsync(true);
  300. }
  301. public static void Suspend(string endpoint, int accountId, string name, string content)
  302. {
  303. string cache_key = $"cache:tk_pool:{accountId}:suspend";
  304. long count = RedisHelper.IncrBy(cache_key);
  305. RedisHelper.Expire(cache_key, 10);
  306. if (count > 1) return;
  307. var update = new DBContext.Table("tk_pool").Add("suspended_endpoint:", $"CONCAT(suspended_endpoint, '{endpoint},')");
  308. if (accountId > 0)
  309. {
  310. update.Where("id=@accountId", new { accountId }).Update();
  311. }
  312. else
  313. {
  314. update.Where("name=@name", new { name }).Update();
  315. }
  316. _ = ListAsync(true);
  317. NotifyCore.Notify(new NifyMessage
  318. {
  319. message = $"【淘客{accountId}:{name}】{endpoint} 暂停",
  320. priority = NifyMessagePriority.high,
  321. tags = ["red_circle"]
  322. });
  323. _ = EndPointCore.NotifyReload(true);
  324. }
  325. public static void Disabled(int accountId, string name, string content, bool is_hide)
  326. {
  327. #if DEBUG
  328. #else
  329. #endif
  330. string cache_key = $"cache:tk_pool:{accountId}:disabled";
  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("status", 0);
  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. _ = AllListAsync(true);
  345. NotifyCore.Notify(new NifyMessage
  346. {
  347. message = $"【淘客{accountId}:{name}】cookie 掉线\n\n{content}",
  348. priority = NifyMessagePriority.high,
  349. tags = ["red_circle"]
  350. });
  351. if (!is_hide)
  352. {
  353. _ = NotifyCore.QYWeixinPushNotifyAsync("掉线", $"【淘客{accountId}:{name}】cookie 掉线");
  354. }
  355. _ = EndPointCore.NotifyReload(true);
  356. }
  357. public static async Task<int> UpdateCookies(string cookies, string user_agent)
  358. {
  359. if (string.IsNullOrEmpty(cookies)) return 0;
  360. cookies += ";";
  361. string dnk = cookies.GetContentPart("dnk=", ";");
  362. string company = dnk;
  363. int accountId = 0;
  364. string tb_token = cookies.GetContentPart("_tb_token_=", ";");
  365. if (string.IsNullOrEmpty(dnk) || string.IsNullOrEmpty(tb_token)) return 0;
  366. var exist = new DBContext.Table("tk_pool").Fields("id, name, company, refpid, status").Get<dynamic>("name=@dnk", new { dnk });
  367. if (exist != null)
  368. {
  369. int status = exist.status;
  370. string refpid = exist.refpid;
  371. company = exist.company;
  372. accountId = exist.id;
  373. if (!string.IsNullOrEmpty(refpid)) status = 1;
  374. new DBContext.Table("tk_pool")
  375. .Add("name", dnk)
  376. .Add("tb_token", tb_token)
  377. .Add("cookies", cookies)
  378. .Add("user_agent", user_agent)
  379. .Add("status", status)
  380. .Add("suspended_endpoint", string.Empty)
  381. .Add("last_time", DateTime.Now)
  382. .Add("login_time", DateTime.Now)
  383. .Where("id=@id", new { exist.id })
  384. .Update();
  385. RiskControlCore.SetRiskCookie($"tb:{exist.id}", "");
  386. if (status == 1) _ = ListAsync(true);
  387. }
  388. else
  389. {
  390. accountId = new DBContext.Table("tk_pool")
  391. .Add("name", dnk)
  392. .Add("description", "由cookies上报创建此记录")
  393. .Add("tb_token", tb_token)
  394. .Add("refpid", string.Empty)
  395. .Add("cookies", cookies)
  396. .Add("user_agent", user_agent)
  397. .Add("create_time", DateTime.Now)
  398. .Add("last_time", DateTime.Now)
  399. .Add("login_time", DateTime.Now)
  400. .Add("status", 0)
  401. .Create();
  402. RiskControlCore.SetRiskCookie($"tb:{accountId}", "");
  403. }
  404. NotifyCore.Notify(new NifyMessage
  405. {
  406. message = $"【淘客{accountId}:{company}】cookie 上线",
  407. tags = ["green_circle"]
  408. });
  409. _ = EndPointCore.NotifyReload(true);
  410. //NotifyCore.QYWeixinPushNotifyAsync("上线", $"【淘宝联盟:{dnk}】cookie 上报更新");
  411. return accountId;
  412. }
  413. internal static void AccountExhausted()
  414. {
  415. string cache_key = $"cache:tk_pool:account:exhausted";
  416. long count = RedisHelper.IncrBy(cache_key);
  417. if (count > 1) return;
  418. RedisHelper.Expire(cache_key, 3600);
  419. NotifyCore.Notify(new NifyMessage
  420. {
  421. message = $"【淘客】没有匹配账号",
  422. priority = NifyMessagePriority.high,
  423. tags = ["red_circle"]
  424. });
  425. _ = NotifyCore.QYWeixinPushNotifyAsync("没账号", $"【淘客】没有匹配账号");
  426. }
  427. }
  428. }