TkPoolCore.cs 19 KB

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