TkPoolCore.cs 18 KB

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