TkPoolCore.cs 17 KB

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