PddPoolCore.cs 18 KB

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