TkPoolCore.cs 16 KB

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