TkPoolCore.cs 17 KB

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