TkPoolCore.cs 18 KB

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