TkPoolCore.cs 16 KB

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