PddPoolCore.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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. namespace molilian.core
  18. {
  19. public partial class PddPoolCore
  20. {
  21. private static readonly object _lockObj = new();
  22. private static IEnumerable<PddPoolDTO> _cached;
  23. private static IEnumerable<PddPoolDTO> _all_cached;
  24. private static string _end_point;
  25. private static Dictionary<string, decimal> _incomeAmt = new();
  26. private static ConcurrentDictionary<int, DateTime> _suspend = new();
  27. // 移除本地内存统计,改用 Redis 存储
  28. private static SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
  29. static PddPoolCore()
  30. {
  31. _end_point = Environment.GetEnvironmentVariable("EndPoint");
  32. }
  33. public static PddPoolDTO? GetOne(PddUnionWorkMode mode, int accountid = 0, string parse_type = "")
  34. {
  35. var list = List();
  36. if (!list.Any()) return null;
  37. if ("dp".Equals(parse_type))
  38. {
  39. list = list.Where(item => "dp".Equals(item.parse_type)).ToList();
  40. if (!list.Any()) return null;
  41. }
  42. else
  43. {
  44. list = list.Where(item => string.IsNullOrEmpty(item.parse_type)).ToList();
  45. if (!list.Any()) return null;
  46. }
  47. return list.Where(e => IsMatch(e, mode, accountid))
  48. .OrderBy(account => GetCurrentDayUsageFromRedis(account.id))
  49. .ThenBy(account => Guid.NewGuid()) // 相同使用次数时随机排序
  50. .FirstOrDefault();
  51. }
  52. private static int GetCurrentDayUsageFromRedis(int accountId)
  53. {
  54. try
  55. {
  56. var today = DateTime.Now.ToString("yyyyMMdd");
  57. string key = $"pdd_daily_usage:{accountId}:{today}";
  58. return RedisHelper.Get<int>(key);
  59. }
  60. catch (Exception)
  61. {
  62. return 0;
  63. }
  64. }
  65. internal static void UpdateAccountUsage(int accountId)
  66. {
  67. try
  68. {
  69. var today = DateTime.Now.ToString("yyyyMMdd");
  70. string key = $"pdd_daily_usage:{accountId}:{today}";
  71. // 递增计数并设置24小时过期时间
  72. RedisHelper.IncrBy(key);
  73. RedisHelper.Expire(key, 86400); // 24小时后自动过期
  74. }
  75. catch (Exception ex)
  76. {
  77. // 记录错误但不影响主流程
  78. Console.WriteLine($"Failed to update account usage for {accountId}: {ex.Message}");
  79. }
  80. }
  81. /// <summary>
  82. /// 获取当前所有账号的平均使用次数
  83. /// </summary>
  84. private static int GetAverageUsageCount()
  85. {
  86. try
  87. {
  88. var activeAccounts = List()?.Where(a => a.enable_parse).ToList();
  89. if (activeAccounts == null || !activeAccounts.Any()) return 0;
  90. var today = DateTime.Now.ToString("yyyyMMdd");
  91. var totalUsage = 0;
  92. var validCount = 0;
  93. foreach (var account in activeAccounts)
  94. {
  95. var usage = GetCurrentDayUsageFromRedis(account.id);
  96. totalUsage += usage;
  97. validCount++;
  98. }
  99. return validCount > 0 ? totalUsage / validCount : 0;
  100. }
  101. catch (Exception ex)
  102. {
  103. Console.WriteLine($"Failed to get average usage count: {ex.Message}");
  104. return 0;
  105. }
  106. }
  107. /// <summary>
  108. /// 重置所有在线账号的当日调用次数Redis计数器
  109. /// 随机排序账号后,每个账号间隔1递增value
  110. /// </summary>
  111. public static int RechargeAllOnlineAccountUsage()
  112. {
  113. try
  114. {
  115. var onlineAccounts = List()?.Where(a => a.status && a.enable_parse).ToList();
  116. if (onlineAccounts == null || !onlineAccounts.Any())
  117. {
  118. return 0;
  119. }
  120. var today = DateTime.Now.ToString("yyyyMMdd");
  121. // 随机排序账号
  122. var random = new Random();
  123. var shuffledAccounts = onlineAccounts.OrderBy(x => random.Next()).ToList();
  124. int incrementValue = 1;
  125. int rechargedCount = 0;
  126. foreach (var account in shuffledAccounts)
  127. {
  128. string key = $"pdd_daily_usage:{account.id}:{today}";
  129. // 设置递增的value并设置24小时过期时间
  130. RedisHelper.Set(key, incrementValue, 86400);
  131. RedisHelper.Set(key, 0, 86400);
  132. incrementValue++;
  133. rechargedCount++;
  134. }
  135. return rechargedCount;
  136. }
  137. catch (Exception ex)
  138. {
  139. }
  140. return 0;
  141. }
  142. /// <summary>
  143. /// 为新上线的账号设置平均使用次数,避免流量集中
  144. /// </summary>
  145. public static void InitializeNewAccountUsage(int accountId)
  146. {
  147. try
  148. {
  149. var today = DateTime.Now.ToString("yyyyMMdd");
  150. string key = $"pdd_daily_usage:{accountId}:{today}";
  151. // 检查该账号今天是否已有使用记录
  152. var currentUsage = RedisHelper.Get<int>(key);
  153. if (currentUsage > 0) return; // 已有记录,不需要初始化
  154. // 获取平均使用次数
  155. var averageUsage = GetAverageUsageCount();
  156. if (averageUsage > 0)
  157. {
  158. // 设置为平均值,避免新账号因为使用次数为0而被优先选择
  159. RedisHelper.Set(key, averageUsage, 86400);
  160. Console.WriteLine($"Initialized account {accountId} with average usage: {averageUsage}");
  161. }
  162. }
  163. catch (Exception ex)
  164. {
  165. Console.WriteLine($"Failed to initialize new account usage for {accountId}: {ex.Message}");
  166. }
  167. }
  168. /// <summary>
  169. /// 获取当前统计信息(用于监控和调试)- 改为从Redis获取
  170. /// </summary>
  171. internal static Dictionary<string, int> GetCurrentUsageSnapshot()
  172. {
  173. try
  174. {
  175. var today = DateTime.Now.ToString("yyyyMMdd");
  176. var pattern = $"pdd_daily_usage:*:{today}";
  177. // 注意:这里只是示例,实际实现可能需要根据Redis客户端API调整
  178. // 生产环境中应该避免使用KEYS命令,可以考虑其他方案
  179. var result = new Dictionary<string, int>();
  180. // TODO: 实现Redis pattern匹配获取所有相关keys
  181. return result;
  182. }
  183. catch (Exception)
  184. {
  185. return new Dictionary<string, int>();
  186. }
  187. }
  188. /// <summary>
  189. /// 强制清理统计数据(仅用于测试或紧急情况)- Redis版本
  190. /// </summary>
  191. internal static void ForceClearStats()
  192. {
  193. try
  194. {
  195. var today = DateTime.Now.ToString("yyyyMMdd");
  196. var pattern = $"pdd_daily_usage:*:{today}";
  197. // TODO: 实现Redis批量删除相关keys
  198. // 生产环境中需要谨慎使用
  199. Console.WriteLine("Force clear stats - Redis keys will auto-expire in 24h");
  200. }
  201. catch (Exception ex)
  202. {
  203. Console.WriteLine($"Failed to force clear stats: {ex.Message}");
  204. }
  205. }
  206. internal static void TempSuspend(int accountId)
  207. {
  208. _suspend.AddOrUpdate(accountId, DateTime.Now, (key, oldValue) => DateTime.Now);
  209. }
  210. private static bool IsMatch(PddPoolDTO item, PddUnionWorkMode mode, int accountid)
  211. {
  212. if (accountid != 0 && accountid != item.id) return false;
  213. if (!item.enable_parse) return false;
  214. if (mode != PddUnionWorkMode.All && mode != item.work_mode) return false;
  215. if (item.work_mode == PddUnionWorkMode.Crawler && !item.cookie_status) return false;
  216. if (!string.IsNullOrEmpty(_end_point) && !string.IsNullOrEmpty(item.end_point))
  217. {
  218. if (item.end_point != _end_point) return false;
  219. }
  220. // 使用初始化参数创建工作时间表
  221. if (!new WorkSchedule(item.time_range).IsWorkHour()) return false;
  222. if (_suspend.TryGetValue(accountid, out DateTime suspendTime))
  223. {
  224. var ts = DateTime.Now - suspendTime;
  225. if (ts.TotalSeconds < 70) return false;
  226. }
  227. if (item.cis_limit > 0)
  228. {
  229. string lockKey = $"pdd_cis_limit_{accountid}";
  230. int cis_num = RedisHelper.Get<int>(lockKey);
  231. if (cis_num > 0) return false;
  232. }
  233. if (item.rpm_limit > 0)
  234. {
  235. int rpm_num = RiskControlCore.GetCalls(TkChannelEnum.pdd, item.id, DateTime.Now.ToString("yyyyMMddHHmm"));
  236. if (rpm_num >= item.rpm_limit) return false;
  237. }
  238. if (item.daily_calls_limit > 0)
  239. {
  240. int daily_num = RiskControlCore.GetCalls(TkChannelEnum.pdd, item.id, DateTime.Now.ToString("yyyyMMdd"));
  241. if (daily_num >= item.daily_calls_limit) return false;
  242. }
  243. if (item.hourly_calls_limit > 0)
  244. {
  245. int hourly_num = RiskControlCore.GetCalls(TkChannelEnum.pdd, item.id, DateTime.Now.ToString("yyyyMMddHH"));
  246. if (hourly_num >= item.hourly_calls_limit) return false;
  247. }
  248. return true;
  249. }
  250. public static async Task<IEnumerable<PddPoolDTO>> AllListAsync(bool force = false)
  251. {
  252. if (!force && _all_cached != default) return _all_cached;
  253. try
  254. {
  255. await _semaphore.WaitAsync();
  256. string cache_key = $"cache:all_pdd_pool";
  257. var list = await RedisKit.GetAsync<IEnumerable<PddPoolDTO>>(cache_key);
  258. if (force || list == default)
  259. {
  260. list = new DBContext.Table("pdd_pool").Select<PddPoolDTO>();
  261. if (list == null) return default;
  262. // 等待 Redis 写入完成
  263. await RedisKit.SetAsync(cache_key, list, 30 * 86400);
  264. }
  265. _all_cached = list;
  266. return list;
  267. }
  268. catch (Exception)
  269. {
  270. // 发生异常时返回上一次的缓存,如果没有则返回默认值
  271. return _all_cached ?? default;
  272. }
  273. finally
  274. {
  275. _semaphore.Release();
  276. }
  277. }
  278. public static IEnumerable<PddPoolDTO> List(bool force = false)
  279. {
  280. if (!force && _cached != null) return _cached;
  281. string cache_key = $"cache:pdd_pool";
  282. var list = RedisHelper.Get<IEnumerable<PddPoolDTO>>(cache_key);
  283. if (force || list == null)
  284. {
  285. lock (_lockObj)
  286. {
  287. list = new DBContext.Table("pdd_pool")
  288. .Where("status=@status", new { status = 1 })
  289. .Select<PddPoolDTO>();
  290. if (list == null) return default;
  291. foreach (var item in list)
  292. {
  293. RiskControlCore.SetCallsAsync(TkChannelEnum.pdd, item.id, DateTime.Now.ToString("yyyyMMddHH"), item.current_hourly_calls);
  294. RiskControlCore.SetCallsAsync(TkChannelEnum.pdd, item.id, DateTime.Now.ToString("yyyyMMdd"), item.current_daily_calls);
  295. }
  296. RedisHelper.Set(cache_key, list, 30 * 86400);
  297. }
  298. }
  299. _cached = list;
  300. return list;
  301. }
  302. public static void Refresh()
  303. {
  304. _cached = null;
  305. _all_cached = null;
  306. _ = List(true);
  307. _ = AllListAsync(true);
  308. }
  309. public static void Disabled(string name)
  310. {
  311. string cache_key = $"cache:pdd_pool:{name}:disabled";
  312. long count = RedisHelper.IncrBy(cache_key);
  313. RedisHelper.Expire(cache_key, 10);
  314. if (count > 1) return;
  315. new DBContext.Table("pdd_pool")
  316. .Add("status", 0)
  317. .Where("name=@name", new { name })
  318. .Update();
  319. _ = List(true);
  320. NotifyCore.Notify(new NifyMessage
  321. {
  322. message = $"【多多:{name}】调用异常",
  323. priority = NifyMessagePriority.high,
  324. tags = ["red_circle"]
  325. });
  326. }
  327. public static void Disabled(int accountId, string name, string content)
  328. {
  329. string cache_key = $"cache:pdd_pool:{name}:disabled";
  330. long count = RedisHelper.IncrBy(cache_key);
  331. RedisHelper.Expire(cache_key, 10);
  332. if (count > 1) return;
  333. var update = new DBContext.Table("pdd_pool").Add("status", 0);
  334. if (accountId > 0)
  335. {
  336. update.Where("id=@accountId", new { accountId }).Update();
  337. }
  338. else
  339. {
  340. update.Where("name=@name", new { name }).Update();
  341. }
  342. _ = List(true);
  343. NotifyCore.Notify(new NifyMessage
  344. {
  345. message = $"【多多{accountId}:{name}】cookie 掉线\n\n{content}",
  346. priority = NifyMessagePriority.high,
  347. tags = ["red_circle"]
  348. });
  349. //NotifyCore.QYWeixinPushNotifyAsync("掉线", $"【多多{accountId}:{name}】cookie 掉线");
  350. EndPointCore.NotifyReload(true);
  351. }
  352. internal static void AccountExhausted()
  353. {
  354. string cache_key = $"cache:pdd_pool:account:exhausted";
  355. long count = RedisHelper.IncrBy(cache_key);
  356. if (count > 1) return;
  357. RedisHelper.Expire(cache_key, 3600);
  358. NotifyCore.Notify(new NifyMessage
  359. {
  360. message = $"【多多】没有匹配账号",
  361. priority = NifyMessagePriority.high,
  362. tags = ["red_circle"]
  363. });
  364. //_ = NotifyCore.QYWeixinPushNotifyAsync("没账号", $"【多多】没有匹配账号");
  365. }
  366. internal static async Task<JsonElement> GetUserInfo(string cookies)
  367. {
  368. JsonElement result = default;
  369. try
  370. {
  371. string url = "https://jinbao.pinduoduo.com/network/api/account/userInfo";
  372. WebClientUtility client = new WebClientUtility();
  373. client.Post("{}");
  374. client.SetCookies(cookies);
  375. client.SetContentType("application/json");
  376. var response = await client.RequestAsync(url, "POST");
  377. var body = response.Body();
  378. result = body.Convert2JsonElement();
  379. }
  380. catch (Exception ex)
  381. {
  382. }
  383. return result;
  384. }
  385. public static async Task<int> UpdateCookies(string cookies, string user_agent, int id = 0)
  386. {
  387. if (string.IsNullOrEmpty(cookies)) return 0;
  388. var userinfo = await GetUserInfo(cookies);
  389. if (userinfo.ValueKind != JsonValueKind.Object) return 0;
  390. int duoId = userinfo.PathRead<int>("result.duoId", 0);
  391. string company = userinfo.PathRead<string>("result.mobile", string.Empty);
  392. string lastPid = userinfo.PathRead<string>("result.lastPid", string.Empty);
  393. int accountId = 0;
  394. if (duoId == 0 && id == 0) return 0;
  395. string filter = id != 0 ? "id=@id" : "duoId=@duoId";
  396. var exist = new DBContext.Table("pdd_pool").Get<PddPoolDTO>(filter, new { id, duoId });
  397. if (exist != null)
  398. {
  399. var status = exist.status;
  400. var work_mode = exist.work_mode;
  401. accountId = exist.id;
  402. if (work_mode == PddUnionWorkMode.Crawler) status = true;
  403. new DBContext.Table("pdd_pool")
  404. .Add("cookies", cookies)
  405. .Add("user_agent", user_agent)
  406. .Add("status", status)
  407. .Add("cookie_status", 1)
  408. .Add("last_time", DateTime.Now)
  409. .Add("login_time", DateTime.Now)
  410. .Where("id=@id", new { exist.id })
  411. .Update();
  412. if (status)
  413. {
  414. _ = List(true);
  415. // 为重新上线的账号初始化使用次数
  416. InitializeNewAccountUsage(exist.id);
  417. }
  418. }
  419. else
  420. {
  421. accountId = new DBContext.Table("pdd_pool")
  422. .Add("duoId", duoId)
  423. .Add("name", company)
  424. .Add("company", company)
  425. .Add("description", "由cookies上报创建此记录")
  426. .Add("cookies", cookies)
  427. .Add("user_agent", user_agent)
  428. .Add("pid", lastPid)
  429. .Add("cookie_status", 1)
  430. .Add("create_time", DateTime.Now)
  431. .Add("last_time", DateTime.Now)
  432. .Add("login_time", DateTime.Now)
  433. .Add("status", 0)
  434. .Create();
  435. // 为新创建的账号初始化使用次数(如果将来会启用的话)
  436. // InitializeNewAccountUsage(accountId); // 暂不调用,因为新创建的账号status=0
  437. }
  438. NotifyCore.Notify(new NifyMessage
  439. {
  440. message = $"【拼多多{accountId}:{company}】cookie 上线",
  441. tags = ["green_circle"]
  442. });
  443. EndPointCore.NotifyReload(true);
  444. //NotifyCore.QYWeixinPushNotifyAsync("上线", $"【淘宝联盟:{dnk}】cookie 上报更新");
  445. return accountId;
  446. }
  447. public static int CookieDisabled(int id)
  448. {
  449. return new DBContext.Table("pdd_pool")
  450. .Add("cookie_status", 0)
  451. .Add("last_time", DateTime.Now)
  452. .Where("id=@id", new { id })
  453. .Update();
  454. }
  455. public static int Update(PddPoolDTO account)
  456. {
  457. return new DBContext.Table("pdd_pool")
  458. .Add("current_hourly_calls", account.current_hourly_calls)
  459. .Add("current_daily_calls", account.current_daily_calls)
  460. //.Add("today_clickNum", account.today_clickNum)
  461. //.Add("today_cosFee", account.today_cosFee)
  462. //.Add("today_cosPrice", account.today_cosPrice)
  463. //.Add("today_finishCosFee", account.today_finishCosFee)
  464. //.Add("today_finishCosPrice", account.today_finishCosPrice)
  465. //.Add("today_finishOrderNum", account.today_finishOrderNum)
  466. //.Add("today_orderNum", account.today_orderNum)
  467. .Add("last_time", DateTime.Now)
  468. .Where("id=@id", new { account.id })
  469. .Update();
  470. }
  471. }
  472. }