TkPoolCore.cs 18 KB

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