PddPoolCore.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  1. using Microsoft.AspNetCore.Http;
  2. using Microsoft.AspNetCore.Mvc.Controllers;
  3. using Microsoft.AspNetCore.Mvc.Filters;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using dodohold.core;
  9. using Dataoke;
  10. using Google.Protobuf.WellKnownTypes;
  11. using System.Diagnostics;
  12. using System.Text.Json;
  13. using TencentCloud.Tcm.V20210413.Models;
  14. using System.Security.Cryptography;
  15. using System.Collections.Concurrent;
  16. using YunhuiKit;
  17. using System.Xml.Linq;
  18. namespace molilian.core
  19. {
  20. public partial class PddPoolCore
  21. {
  22. private static readonly object _lockObj = new();
  23. private static IEnumerable<PddPoolDTO> _cached;
  24. private static IEnumerable<PddPoolDTO> _all_cached;
  25. private static string _end_point;
  26. private static Dictionary<string, decimal> _incomeAmt = new();
  27. private static ConcurrentDictionary<int, DateTime> _suspend = new();
  28. // 移除本地内存统计,改用 Redis 存储
  29. private static SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
  30. static PddPoolCore()
  31. {
  32. _end_point = Environment.GetEnvironmentVariable("EndPoint");
  33. }
  34. /// <summary>
  35. /// 获取一个账号用于处理请求
  36. /// 使用平滑加权轮询算法(Smooth Weighted Round-Robin)实现流量均衡分配
  37. /// </summary>
  38. public static PddPoolDTO? GetOne(PddUnionWorkMode mode, int accountid = 0, string parse_type = "")
  39. {
  40. return GetOne(mode, new UnionParseRequest
  41. {
  42. AccountId = accountid
  43. }, parse_type);
  44. }
  45. /// <summary>
  46. /// 按 id 取账号(含下线账号),供 aid 调试强制使用,不做选号检查
  47. /// </summary>
  48. public static async Task<PddPoolDTO?> ALLGetOneAsync(int id)
  49. {
  50. var list = await AllListAsync();
  51. return list?.FirstOrDefault(e => e.id == id);
  52. }
  53. public static PddPoolDTO? GetOne(PddUnionWorkMode mode, UnionParseRequest request, string parse_type = "")
  54. {
  55. var list = List();
  56. if (!list.Any()) return null;
  57. // 按 parse_type 过滤
  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. list = list.Where(item => string.IsNullOrEmpty(item.parse_type)).ToList();
  66. if (!list.Any()) return null;
  67. }
  68. if (!string.IsNullOrEmpty(request.RiskStrategy) && !"os".Equals(request.RiskStrategy) && request.LaunchScene != -1)
  69. {
  70. list = list.Where(item => request.RiskStrategy.Equals(item.riskStrategy) && item.launchScene == request.LaunchScene).ToList();
  71. if (!list.Any()) return null;
  72. }
  73. else
  74. {
  75. list = list.Where(item => string.IsNullOrEmpty(item.riskStrategy)).ToList();
  76. if (!list.Any()) return null;
  77. }
  78. // 过滤出符合条件的候选账号
  79. var candidates = list.Where(e => IsMatch(e, mode, request.AccountId)).ToList();
  80. if (!candidates.Any()) return null;
  81. // 使用平滑加权轮询算法选择账号
  82. return SmoothWeightedRoundRobin(candidates, parse_type);
  83. }
  84. /// <summary>
  85. /// 基于最后使用时间的调度策略(并发安全版本)
  86. /// 选择"距离上次使用时间最长"且"超过cis_limit间隔"的账号
  87. ///
  88. /// 优势:
  89. /// 1. 不区分新老账号,一视同仁(无历史记录的账号返回DateTime.MinValue,自然会被优先选中)
  90. /// 2. 自然满足cis_limit要求(距离时间 < limit 会被跳过)
  91. /// 3. 优先选择"休息最久"的账号,最大化每个账号的休息时间
  92. /// 4. 简单直观,易于调试和理解
  93. /// 5. 并发安全:使用Redis原子操作预留账号,避免多个请求竞争同一账号
  94. /// </summary>
  95. private static PddPoolDTO? SmoothWeightedRoundRobin(List<PddPoolDTO> candidates, string parse_type)
  96. {
  97. if (!candidates.Any()) return null;
  98. #if DEBUG
  99. var single = candidates[0];
  100. return single;
  101. #else
  102. if (candidates.Count == 1)
  103. {
  104. var single = candidates[0];
  105. // 尝试预留账号(并发安全)
  106. if (TryReserveAccount(single.id, parse_type, single.cis_limit))
  107. {
  108. return single;
  109. }
  110. return null; // 预留失败,说明账号已被其他请求占用
  111. }
  112. #endif
  113. try
  114. {
  115. string groupKey = string.IsNullOrEmpty(parse_type) ? "default" : parse_type;
  116. var now = DateTime.Now;
  117. // 候选账号列表:记录每个账号的空闲时长
  118. var accountsWithIdleTime = new List<(PddPoolDTO account, long idleMs)>();
  119. foreach (var account in candidates)
  120. {
  121. // 获取账号最后使用时间
  122. var lastUsedTime = GetAccountLastUsedTime(account.id, groupKey);
  123. // 计算距离现在的时间差(毫秒)
  124. long idleMs = (long)(now - lastUsedTime).TotalMilliseconds;
  125. // 如果设置了 cis_limit,必须满足间隔要求
  126. if (account.cis_limit > 0 && idleMs < account.cis_limit)
  127. {
  128. continue; // 跳过未满足间隔要求的账号
  129. }
  130. accountsWithIdleTime.Add((account, idleMs));
  131. }
  132. // 如果没有满足条件的账号,返回null
  133. if (!accountsWithIdleTime.Any()) return null;
  134. // 按照空闲时间降序排序,优先尝试"休息最久"的账号
  135. var sortedAccounts = accountsWithIdleTime
  136. .OrderByDescending(x => x.idleMs)
  137. .ToList();
  138. // 依次尝试预留账号(从空闲时间最长的开始)
  139. foreach (var (account, idleMs) in sortedAccounts)
  140. {
  141. // 尝试原子预留此账号
  142. if (TryReserveAccount(account.id, groupKey, account.cis_limit))
  143. {
  144. // 预留成功,更新最后使用时间
  145. SetAccountLastUsedTime(account.id, groupKey, now);
  146. Console.WriteLine($"[PDD] Selected account {account.id} ({account.name}), idle time: {Math.Round(idleMs / 1000.0, 2)}s");
  147. return account;
  148. }
  149. else
  150. {
  151. // 预留失败,说明此账号已被其他并发请求占用,尝试下一个
  152. Console.WriteLine($"[PDD] Account {account.id} ({account.name}) is reserved by another request, trying next...");
  153. }
  154. }
  155. // 所有满足条件的账号都已被占用
  156. Console.WriteLine($"[PDD] All available accounts are reserved, no account available");
  157. return null;
  158. }
  159. catch (Exception ex)
  160. {
  161. Console.WriteLine($"Idle time selection failed: {ex.Message}, fallback to simple strategy");
  162. // 降级策略:使用原有的最少使用次数算法
  163. return candidates
  164. .OrderBy(account => GetCurrentDayUsageFromRedis(account.id))
  165. .ThenBy(account => Guid.NewGuid())
  166. .FirstOrDefault();
  167. }
  168. }
  169. /// <summary>
  170. /// 尝试原子预留账号(并发安全)
  171. /// 使用 Redis SET NX EX 实现原子操作,避免多个请求竞争同一账号
  172. /// </summary>
  173. /// <param name="accountId">账号ID</param>
  174. /// <param name="groupKey">分组键</param>
  175. /// <param name="cisLimit">请求间隔限制(毫秒),0表示无限制</param>
  176. /// <returns>true=预留成功,false=账号已被占用</returns>
  177. private static bool TryReserveAccount(int accountId, string groupKey, int cisLimit)
  178. {
  179. try
  180. {
  181. string reserveKey = $"pdd_account_reserved:{groupKey}:{accountId}";
  182. // 如果没有设置 cis_limit,使用默认100ms的预留时间(防止极端并发)
  183. int expireSeconds = cisLimit > 0 ? (int)Math.Ceiling(cisLimit / 1000.0) : 1;
  184. // 使用 Redis SET NX EX 原子操作(一次性完成设置和过期时间)
  185. // 等价于 Redis 命令: SET key value NX EX seconds
  186. // 如果 key 不存在则设置成功(返回true),如果已存在则失败(返回false)
  187. // 注意:必须使用原子操作,SetNx + Expire 两步操作会有竞态条件!
  188. bool reserved = RedisHelper.Set(reserveKey, 1, expireSeconds, CSRedis.RedisExistence.Nx);
  189. return reserved;
  190. }
  191. catch (Exception ex)
  192. {
  193. Console.WriteLine($"Failed to reserve account {accountId}: {ex.Message}");
  194. // 预留失败时保守处理:假设账号不可用
  195. return false;
  196. }
  197. }
  198. /// <summary>
  199. /// 获取账号最后使用时间
  200. /// </summary>
  201. private static DateTime GetAccountLastUsedTime(int accountId, string groupKey)
  202. {
  203. try
  204. {
  205. string key = $"pdd_last_used_time:{groupKey}:{accountId}";
  206. var timestamp = RedisHelper.Get<long>(key);
  207. if (timestamp > 0)
  208. {
  209. return DateTimeOffset.FromUnixTimeMilliseconds(timestamp).LocalDateTime;
  210. }
  211. // 如果没有记录,返回很久以前的时间(确保新账号和长期未使用的账号能被优先选中)
  212. return DateTime.MinValue;
  213. }
  214. catch
  215. {
  216. return DateTime.MinValue;
  217. }
  218. }
  219. /// <summary>
  220. /// 设置账号最后使用时间
  221. /// </summary>
  222. private static void SetAccountLastUsedTime(int accountId, string groupKey, DateTime time)
  223. {
  224. try
  225. {
  226. string key = $"pdd_last_used_time:{groupKey}:{accountId}";
  227. long timestamp = new DateTimeOffset(time).ToUnixTimeMilliseconds();
  228. // 设置过期时间为24小时,避免数据积累
  229. RedisHelper.Set(key, timestamp, 86400);
  230. }
  231. catch (Exception ex)
  232. {
  233. Console.WriteLine($"Failed to set last used time for {accountId}: {ex.Message}");
  234. }
  235. }
  236. /// <summary>
  237. /// 获取账号的静态权重
  238. /// 可以根据账号的 daily_calls_limit 或其他因素动态计算
  239. /// </summary>
  240. private static int GetAccountStaticWeight(int accountId)
  241. {
  242. try
  243. {
  244. string key = $"pdd_account_weight:{accountId}";
  245. int weight = RedisHelper.Get<int>(key);
  246. // 如果没有设置,返回默认权重100
  247. if (weight <= 0)
  248. {
  249. // 可以基于账号的限额动态计算默认权重
  250. var account = List()?.FirstOrDefault(a => a.id == accountId);
  251. if (account != null && account.daily_calls_limit > 0)
  252. {
  253. // 将日限额映射到权重:每1000次调用对应权重10
  254. weight = Math.Max(10, Math.Min(1000, account.daily_calls_limit / 100));
  255. }
  256. else
  257. {
  258. weight = 100; // 默认权重
  259. }
  260. }
  261. return weight;
  262. }
  263. catch
  264. {
  265. return 100; // 异常时返回默认权重
  266. }
  267. }
  268. /// <summary>
  269. /// 设置账号的静态权重
  270. /// </summary>
  271. public static void SetAccountStaticWeight(int accountId, int weight)
  272. {
  273. try
  274. {
  275. if (weight < 1) weight = 1;
  276. if (weight > 1000) weight = 1000;
  277. string key = $"pdd_account_weight:{accountId}";
  278. RedisHelper.Set(key, weight, 30 * 86400); // 30天过期
  279. }
  280. catch (Exception ex)
  281. {
  282. Console.WriteLine($"Failed to set account weight for {accountId}: {ex.Message}");
  283. }
  284. }
  285. /// <summary>
  286. /// 获取账号的当前动态权重
  287. /// </summary>
  288. private static int GetAccountCurrentWeight(int accountId, string groupKey)
  289. {
  290. try
  291. {
  292. string key = $"pdd_current_weight:{groupKey}:{accountId}";
  293. return RedisHelper.Get<int>(key);
  294. }
  295. catch
  296. {
  297. return 0;
  298. }
  299. }
  300. /// <summary>
  301. /// 设置账号的当前动态权重
  302. /// </summary>
  303. private static void SetAccountCurrentWeight(int accountId, string groupKey, int weight)
  304. {
  305. try
  306. {
  307. string key = $"pdd_current_weight:{groupKey}:{accountId}";
  308. RedisHelper.Set(key, weight, 3600); // 1小时过期,自动重置
  309. }
  310. catch (Exception ex)
  311. {
  312. Console.WriteLine($"Failed to set current weight for {accountId}: {ex.Message}");
  313. }
  314. }
  315. /// <summary>
  316. /// 重置所有账号的动态权重(用于调试或重新初始化)
  317. /// </summary>
  318. public static void ResetAllWeights(string groupKey = "default")
  319. {
  320. try
  321. {
  322. var accounts = List()?.Where(a => a.status && a.enable_parse).ToList();
  323. if (accounts == null || !accounts.Any()) return;
  324. foreach (var account in accounts)
  325. {
  326. string key = $"pdd_current_weight:{groupKey}:{account.id}";
  327. RedisHelper.Del(key);
  328. }
  329. Console.WriteLine($"Reset weights for {accounts.Count} accounts in group '{groupKey}'");
  330. }
  331. catch (Exception ex)
  332. {
  333. Console.WriteLine($"Failed to reset weights: {ex.Message}");
  334. }
  335. }
  336. private static int GetCurrentDayUsageFromRedis(int accountId)
  337. {
  338. try
  339. {
  340. var today = DateTime.Now.ToString("yyyyMMdd");
  341. string key = $"pdd_daily_usage:{accountId}:{today}";
  342. return RedisHelper.Get<int>(key);
  343. }
  344. catch (Exception)
  345. {
  346. return 0;
  347. }
  348. }
  349. internal static void UpdateAccountUsage(int accountId)
  350. {
  351. try
  352. {
  353. var today = DateTime.Now.ToString("yyyyMMdd");
  354. string key = $"pdd_daily_usage:{accountId}:{today}";
  355. // 递增计数并设置24小时过期时间
  356. RedisHelper.IncrBy(key);
  357. RedisHelper.Expire(key, 86400); // 24小时后自动过期
  358. }
  359. catch (Exception ex)
  360. {
  361. // 记录错误但不影响主流程
  362. Console.WriteLine($"Failed to update account usage for {accountId}: {ex.Message}");
  363. }
  364. }
  365. /// <summary>
  366. /// 获取当前所有账号的平均使用次数
  367. /// </summary>
  368. private static int GetAverageUsageCount()
  369. {
  370. try
  371. {
  372. var activeAccounts = List()?.Where(a => a.enable_parse).ToList();
  373. if (activeAccounts == null || !activeAccounts.Any()) return 0;
  374. var today = DateTime.Now.ToString("yyyyMMdd");
  375. var totalUsage = 0;
  376. var validCount = 0;
  377. foreach (var account in activeAccounts)
  378. {
  379. var usage = GetCurrentDayUsageFromRedis(account.id);
  380. totalUsage += usage;
  381. validCount++;
  382. }
  383. return validCount > 0 ? totalUsage / validCount : 0;
  384. }
  385. catch (Exception ex)
  386. {
  387. Console.WriteLine($"Failed to get average usage count: {ex.Message}");
  388. return 0;
  389. }
  390. }
  391. /// <summary>
  392. /// 重置所有在线账号的当日调用次数Redis计数器
  393. /// 随机排序账号后,每个账号间隔1递增value
  394. /// </summary>
  395. public static int RechargeAllOnlineAccountUsage()
  396. {
  397. try
  398. {
  399. var onlineAccounts = List()?.Where(a => a.status && a.enable_parse).ToList();
  400. if (onlineAccounts == null || !onlineAccounts.Any())
  401. {
  402. return 0;
  403. }
  404. var today = DateTime.Now.ToString("yyyyMMdd");
  405. // 随机排序账号
  406. var random = new Random();
  407. var shuffledAccounts = onlineAccounts.OrderBy(x => random.Next()).ToList();
  408. int incrementValue = 1;
  409. int rechargedCount = 0;
  410. foreach (var account in shuffledAccounts)
  411. {
  412. string key = $"pdd_daily_usage:{account.id}:{today}";
  413. // 设置递增的value并设置24小时过期时间
  414. RedisHelper.Set(key, incrementValue, 86400);
  415. RedisHelper.Set(key, 0, 86400);
  416. incrementValue++;
  417. rechargedCount++;
  418. }
  419. return rechargedCount;
  420. }
  421. catch (Exception ex)
  422. {
  423. }
  424. return 0;
  425. }
  426. /// <summary>
  427. /// 为新上线的账号设置平均使用次数(仅用于降级策略的统计)
  428. /// 注意:基于时间间隔的调度策略不需要初始化权重,因为无历史记录的账号会自动返回DateTime.MinValue
  429. /// </summary>
  430. public static void InitializeNewAccountUsage(int accountId, string groupKey = "default")
  431. {
  432. try
  433. {
  434. var today = DateTime.Now.ToString("yyyyMMdd");
  435. string usageKey = $"pdd_daily_usage:{accountId}:{today}";
  436. // 检查该账号今天是否已有使用记录
  437. var currentUsage = RedisHelper.Get<int>(usageKey);
  438. if (currentUsage > 0)
  439. {
  440. Console.WriteLine($"Account {accountId} already has usage record: {currentUsage}, skip initialization");
  441. return; // 已有记录,不需要初始化
  442. }
  443. // 获取所有在线账号的平均值(仅用于降级策略)
  444. var activeAccounts = List()?.Where(a => a.status && a.enable_parse && a.id != accountId).ToList();
  445. if (activeAccounts == null || !activeAccounts.Any())
  446. {
  447. Console.WriteLine($"No other active accounts found, account {accountId} will use default value");
  448. return; // 没有其他账号,使用默认值0即可
  449. }
  450. // 初始化 daily_usage(用于降级策略的统计)
  451. var totalUsage = 0;
  452. foreach (var account in activeAccounts)
  453. {
  454. totalUsage += GetCurrentDayUsageFromRedis(account.id);
  455. }
  456. var averageUsage = totalUsage / activeAccounts.Count;
  457. if (averageUsage > 0)
  458. {
  459. RedisHelper.Set(usageKey, averageUsage, 86400);
  460. Console.WriteLine($"Initialized account {accountId} daily_usage with average: {averageUsage}");
  461. }
  462. Console.WriteLine($"Account {accountId} initialization complete. Time-based scheduling will use DateTime.MinValue for idle time calculation.");
  463. }
  464. catch (Exception ex)
  465. {
  466. Console.WriteLine($"Failed to initialize new account for {accountId}: {ex.Message}");
  467. }
  468. }
  469. /// <summary>
  470. /// 获取当前统计信息(用于监控和调试)- 改为从Redis获取
  471. /// </summary>
  472. internal static Dictionary<string, int> GetCurrentUsageSnapshot()
  473. {
  474. try
  475. {
  476. var result = new Dictionary<string, int>();
  477. var accounts = List()?.Where(a => a.status && a.enable_parse).ToList();
  478. if (accounts == null || !accounts.Any()) return result;
  479. var today = DateTime.Now.ToString("yyyyMMdd");
  480. foreach (var account in accounts)
  481. {
  482. string key = $"pdd_daily_usage:{account.id}:{today}";
  483. int usage = RedisHelper.Get<int>(key);
  484. result[$"Account_{account.id}_{account.name}"] = usage;
  485. }
  486. return result;
  487. }
  488. catch (Exception)
  489. {
  490. return new Dictionary<string, int>();
  491. }
  492. }
  493. /// <summary>
  494. /// 获取账号调度时间间隔信息(用于监控和调试)
  495. /// </summary>
  496. public static Dictionary<string, object> GetScheduleWeightSnapshot(string groupKey = "default")
  497. {
  498. try
  499. {
  500. var result = new Dictionary<string, object>();
  501. var accounts = List()?.Where(a => a.status && a.enable_parse).ToList();
  502. if (accounts == null || !accounts.Any()) return result;
  503. var now = DateTime.Now;
  504. var accountInfos = new List<Dictionary<string, object>>();
  505. foreach (var account in accounts)
  506. {
  507. var lastUsedTime = GetAccountLastUsedTime(account.id, groupKey);
  508. long idleMs = (long)(now - lastUsedTime).TotalMilliseconds;
  509. bool canUse = account.cis_limit <= 0 || idleMs >= account.cis_limit;
  510. var info = new Dictionary<string, object>
  511. {
  512. ["account_id"] = account.id,
  513. ["account_name"] = account.name,
  514. ["cis_limit_ms"] = account.cis_limit,
  515. ["last_used_time"] = lastUsedTime == DateTime.MinValue ? "从未使用" : lastUsedTime.ToString("yyyy-MM-dd HH:mm:ss.fff"),
  516. ["idle_time_ms"] = idleMs,
  517. ["idle_time_seconds"] = Math.Round(idleMs / 1000.0, 2),
  518. ["can_use"] = canUse,
  519. ["daily_usage"] = GetCurrentDayUsageFromRedis(account.id),
  520. ["daily_limit"] = account.daily_calls_limit
  521. };
  522. accountInfos.Add(info);
  523. }
  524. // 按照空闲时间降序排序(与选择逻辑一致)
  525. accountInfos = accountInfos.OrderByDescending(x => (long)x["idle_time_ms"]).ToList();
  526. result["accounts"] = accountInfos;
  527. result["group_key"] = groupKey;
  528. result["timestamp"] = now.ToString("yyyy-MM-dd HH:mm:ss.fff");
  529. result["total_accounts"] = accountInfos.Count;
  530. result["available_accounts"] = accountInfos.Count(x => (bool)x["can_use"]);
  531. return result;
  532. }
  533. catch (Exception ex)
  534. {
  535. return new Dictionary<string, object> { ["error"] = ex.Message };
  536. }
  537. }
  538. /// <summary>
  539. /// 强制清理统计数据(仅用于测试或紧急情况)- Redis版本
  540. /// </summary>
  541. internal static void ForceClearStats()
  542. {
  543. try
  544. {
  545. var today = DateTime.Now.ToString("yyyyMMdd");
  546. var pattern = $"pdd_daily_usage:*:{today}";
  547. // TODO: 实现Redis批量删除相关keys
  548. // 生产环境中需要谨慎使用
  549. Console.WriteLine("Force clear stats - Redis keys will auto-expire in 24h");
  550. }
  551. catch (Exception ex)
  552. {
  553. Console.WriteLine($"Failed to force clear stats: {ex.Message}");
  554. }
  555. }
  556. internal static void TempSuspend(int accountId)
  557. {
  558. _suspend.AddOrUpdate(accountId, DateTime.Now, (key, oldValue) => DateTime.Now);
  559. }
  560. private static bool IsMatch(PddPoolDTO item, PddUnionWorkMode mode, int accountid)
  561. {
  562. if (accountid != 0 && accountid != item.id) return false;
  563. if (!item.enable_parse) return false;
  564. if (mode != PddUnionWorkMode.All && mode != item.work_mode) return false;
  565. if (item.work_mode == PddUnionWorkMode.Crawler && !item.cookie_status) return false;
  566. if (!string.IsNullOrEmpty(_end_point) && !string.IsNullOrEmpty(item.end_point))
  567. {
  568. if (item.end_point != _end_point) return false;
  569. }
  570. // 使用初始化参数创建工作时间表
  571. if (!new WorkSchedule(item.time_range).IsWorkHour()) return false;
  572. if (_suspend.TryGetValue(accountid, out DateTime suspendTime))
  573. {
  574. var ts = DateTime.Now - suspendTime;
  575. if (ts.TotalSeconds < 70) return false;
  576. }
  577. // cis_limit 检查已移至 SmoothWeightedRoundRobin 方法中基于时间间隔判断
  578. // 这里不再需要检查 Redis 锁
  579. #if DEBUG
  580. #else
  581. if (item.rpm_limit > 0)
  582. {
  583. int rpm_num = RiskControlCore.GetCalls(TkChannelEnum.pdd, item.id, DateTime.Now.ToString("yyyyMMddHHmm"));
  584. if (rpm_num >= item.rpm_limit) return false;
  585. }
  586. if (item.daily_calls_limit > 0)
  587. {
  588. int daily_num = RiskControlCore.GetCalls(TkChannelEnum.pdd, item.id, DateTime.Now.ToString("yyyyMMdd"));
  589. if (daily_num >= item.daily_calls_limit) return false;
  590. }
  591. if (item.hourly_calls_limit > 0)
  592. {
  593. int hourly_num = RiskControlCore.GetCalls(TkChannelEnum.pdd, item.id, DateTime.Now.ToString("yyyyMMddHH"));
  594. if (hourly_num >= item.hourly_calls_limit) return false;
  595. }
  596. #endif
  597. return true;
  598. }
  599. public static async Task<IEnumerable<PddPoolDTO>> AllListAsync(bool force = false)
  600. {
  601. if (!force && _all_cached != default) return _all_cached;
  602. try
  603. {
  604. await _semaphore.WaitAsync();
  605. string cache_key = $"cache:all_pdd_pool";
  606. var list = await RedisKit.GetAsync<IEnumerable<PddPoolDTO>>(cache_key);
  607. if (force || list == default)
  608. {
  609. list = new DBContext.Table("pdd_pool").Select<PddPoolDTO>();
  610. if (list == null) return default;
  611. // 等待 Redis 写入完成
  612. await RedisKit.SetAsync(cache_key, list, 30 * 86400);
  613. }
  614. _all_cached = list;
  615. return list;
  616. }
  617. catch (Exception)
  618. {
  619. // 发生异常时返回上一次的缓存,如果没有则返回默认值
  620. return _all_cached ?? default;
  621. }
  622. finally
  623. {
  624. _semaphore.Release();
  625. }
  626. }
  627. public static IEnumerable<PddPoolDTO> List(bool force = false)
  628. {
  629. if (!force && _cached != null) return _cached;
  630. string cache_key = $"cache:pdd_pool";
  631. var list = RedisHelper.Get<IEnumerable<PddPoolDTO>>(cache_key);
  632. if (force || list == null)
  633. {
  634. lock (_lockObj)
  635. {
  636. list = new DBContext.Table("pdd_pool")
  637. .Where("status=@status", new { status = 1 })
  638. .Select<PddPoolDTO>();
  639. if (list == null) return default;
  640. foreach (var item in list)
  641. {
  642. RiskControlCore.SetCallsAsync(TkChannelEnum.pdd, item.id, DateTime.Now.ToString("yyyyMMddHH"), item.current_hourly_calls);
  643. RiskControlCore.SetCallsAsync(TkChannelEnum.pdd, item.id, DateTime.Now.ToString("yyyyMMdd"), item.current_daily_calls);
  644. }
  645. RedisHelper.Set(cache_key, list, 30 * 86400);
  646. }
  647. }
  648. _cached = list;
  649. return list;
  650. }
  651. public static void Refresh()
  652. {
  653. _cached = null;
  654. _all_cached = null;
  655. _ = List(true);
  656. _ = AllListAsync(true);
  657. }
  658. public static void Disabled(string name)
  659. {
  660. string cache_key = $"cache:pdd_pool:{name}:disabled";
  661. long count = RedisHelper.IncrBy(cache_key);
  662. RedisHelper.Expire(cache_key, 10);
  663. if (count > 1) return;
  664. new DBContext.Table("pdd_pool")
  665. .Add("status", 0)
  666. .Where("name=@name", new { name })
  667. .Update();
  668. _ = List(true);
  669. NotifyCore.Notify(new NifyMessage
  670. {
  671. message = $"【多多:{name}】调用异常",
  672. priority = NifyMessagePriority.high,
  673. tags = ["red_circle"]
  674. });
  675. }
  676. public static void Disabled(int accountId, string name, string content)
  677. {
  678. string cache_key = $"cache:pdd_pool:{name}:disabled";
  679. long count = RedisHelper.IncrBy(cache_key);
  680. RedisHelper.Expire(cache_key, 10);
  681. if (count > 1) return;
  682. var update = new DBContext.Table("pdd_pool").Add("status", 0);
  683. if (accountId > 0)
  684. {
  685. update.Where("id=@accountId", new { accountId }).Update();
  686. }
  687. else
  688. {
  689. update.Where("name=@name", new { name }).Update();
  690. }
  691. _ = List(true);
  692. NotifyCore.Notify(new NifyMessage
  693. {
  694. message = $"【多多{accountId}:{name}】cookie 掉线\n\n{content}",
  695. priority = NifyMessagePriority.high,
  696. tags = ["red_circle"]
  697. });
  698. //NotifyCore.QYWeixinPushNotifyAsync("掉线", $"【多多{accountId}:{name}】cookie 掉线");
  699. EndPointCore.NotifyReload(true);
  700. }
  701. internal static void AccountExhausted()
  702. {
  703. string cache_key = $"cache:pdd_pool:account:exhausted";
  704. long count = RedisHelper.IncrBy(cache_key);
  705. if (count > 1) return;
  706. RedisHelper.Expire(cache_key, 3600);
  707. NotifyCore.Notify(new NifyMessage
  708. {
  709. message = $"【多多】没有匹配账号",
  710. priority = NifyMessagePriority.high,
  711. tags = ["red_circle"]
  712. });
  713. //_ = NotifyCore.QYWeixinPushNotifyAsync("没账号", $"【多多】没有匹配账号");
  714. }
  715. internal static async Task<JsonElement> GetUserInfo(string cookies)
  716. {
  717. JsonElement result = default;
  718. try
  719. {
  720. string url = "https://jinbao.pinduoduo.com/network/api/account/userInfo";
  721. WebClientUtility client = new WebClientUtility();
  722. client.Post("{}");
  723. client.SetCookies(cookies);
  724. client.SetContentType("application/json");
  725. var response = await client.RequestAsync(url, "POST");
  726. var body = response.Body();
  727. result = body.Convert2JsonElement();
  728. }
  729. catch (Exception ex)
  730. {
  731. }
  732. return result;
  733. }
  734. public static async Task<int> UpdateCookies(string cookies, string user_agent, int id = 0)
  735. {
  736. if (string.IsNullOrEmpty(cookies)) return 0;
  737. var userinfo = await GetUserInfo(cookies);
  738. if (userinfo.ValueKind != JsonValueKind.Object) return 0;
  739. int duoId = userinfo.PathRead<int>("result.duoId", 0);
  740. string company = userinfo.PathRead<string>("result.mobile", string.Empty);
  741. string lastPid = userinfo.PathRead<string>("result.lastPid", string.Empty);
  742. int accountId = 0;
  743. if (duoId == 0 && id == 0) return 0;
  744. string filter = id != 0 ? "id=@id" : "duoId=@duoId";
  745. var exist = new DBContext.Table("pdd_pool").Get<PddPoolDTO>(filter, new { id, duoId });
  746. if (exist != null)
  747. {
  748. var status = exist.status;
  749. var work_mode = exist.work_mode;
  750. accountId = exist.id;
  751. if (work_mode == PddUnionWorkMode.Crawler) status = true;
  752. new DBContext.Table("pdd_pool")
  753. .Add("cookies", cookies)
  754. .Add("user_agent", user_agent)
  755. .Add("status", status)
  756. .Add("cookie_status", 1)
  757. .Add("last_time", DateTime.Now)
  758. .Add("login_time", DateTime.Now)
  759. .Where("id=@id", new { exist.id })
  760. .Update();
  761. if (status)
  762. {
  763. _ = List(true);
  764. // 为重新上线的账号初始化使用次数和权重(针对所有分组)
  765. InitializeNewAccountUsage(exist.id, "default");
  766. InitializeNewAccountUsage(exist.id, "dp");
  767. }
  768. }
  769. else
  770. {
  771. accountId = new DBContext.Table("pdd_pool")
  772. .Add("duoId", duoId)
  773. .Add("name", company)
  774. .Add("company", company)
  775. .Add("description", "由cookies上报创建此记录")
  776. .Add("cookies", cookies)
  777. .Add("user_agent", user_agent)
  778. .Add("pid", lastPid)
  779. .Add("cookie_status", 1)
  780. .Add("create_time", DateTime.Now)
  781. .Add("last_time", DateTime.Now)
  782. .Add("login_time", DateTime.Now)
  783. .Add("status", 0)
  784. .Create();
  785. // 为新创建的账号初始化使用次数(如果将来会启用的话)
  786. // InitializeNewAccountUsage(accountId); // 暂不调用,因为新创建的账号status=0
  787. }
  788. NotifyCore.Notify(new NifyMessage
  789. {
  790. message = $"【拼多多{accountId}:{company}】cookie 上线",
  791. tags = ["green_circle"]
  792. });
  793. EndPointCore.NotifyReload(true);
  794. //NotifyCore.QYWeixinPushNotifyAsync("上线", $"【淘宝联盟:{dnk}】cookie 上报更新");
  795. return accountId;
  796. }
  797. public static int CookieDisabled(int id)
  798. {
  799. return new DBContext.Table("pdd_pool")
  800. .Add("cookie_status", 0)
  801. .Add("last_time", DateTime.Now)
  802. .Where("id=@id", new { id })
  803. .Update();
  804. }
  805. public static int Update(PddPoolDTO account)
  806. {
  807. return new DBContext.Table("pdd_pool")
  808. .Add("current_hourly_calls", account.current_hourly_calls)
  809. .Add("current_daily_calls", account.current_daily_calls)
  810. //.Add("today_clickNum", account.today_clickNum)
  811. //.Add("today_cosFee", account.today_cosFee)
  812. //.Add("today_cosPrice", account.today_cosPrice)
  813. //.Add("today_finishCosFee", account.today_finishCosFee)
  814. //.Add("today_finishCosPrice", account.today_finishCosPrice)
  815. //.Add("today_finishOrderNum", account.today_finishOrderNum)
  816. //.Add("today_orderNum", account.today_orderNum)
  817. .Add("last_time", DateTime.Now)
  818. .Where("id=@id", new { account.id })
  819. .Update();
  820. }
  821. public static void AccountRisk(PddPoolDTO account)
  822. {
  823. string cache_key = $"cache:pdd_pool:{account.name}:disabled";
  824. long count = RedisHelper.IncrBy(cache_key);
  825. RedisHelper.Expire(cache_key, 10);
  826. if (count > 1) return;
  827. // 发送通知
  828. string message = $"【PDD风控】【{account.id}:{account.name}】出现30007";
  829. NotifyCore.Notify(new NifyMessage
  830. {
  831. message = message,
  832. priority = NifyMessagePriority.high,
  833. tags = ["red_circle"]
  834. });
  835. if (!account.is_hide)
  836. {
  837. _ = NotifyCore.QYWeixinPushNotifyAsync("PDD风控", message);
  838. }
  839. // 设置风控标记
  840. RiskControlCore.SetRiskCookie($"pdd:{account.id}", "30007");
  841. // 更新数据库状态
  842. new DBContext.Table("pdd_pool")
  843. .Add("enable_parse", 0)
  844. .Where("id=@id", new { account.id })
  845. .Update();
  846. _ = List(true);
  847. _ = EndPointCore.NotifyReload(true);
  848. }
  849. }
  850. }