PddPoolCore.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. private static SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
  28. static PddPoolCore()
  29. {
  30. _end_point = Environment.GetEnvironmentVariable("EndPoint");
  31. }
  32. public static PddPoolDTO? GetOne(PddUnionWorkMode mode, int accountid = 0)
  33. {
  34. var list = List();
  35. if (!list.Any()) return null;
  36. return list.Where(e => IsMatch(e, mode, accountid)).OrderBy(l => Guid.NewGuid()).FirstOrDefault();
  37. }
  38. internal static void TempSuspend(int accountId)
  39. {
  40. _suspend.AddOrUpdate(accountId, DateTime.Now, (key, oldValue) => DateTime.Now);
  41. }
  42. private static bool IsMatch(PddPoolDTO item, PddUnionWorkMode mode, int accountid)
  43. {
  44. if (accountid != 0 && accountid != item.id) return false;
  45. if (mode != PddUnionWorkMode.All && mode != item.work_mode) return false;
  46. if (item.work_mode == PddUnionWorkMode.Crawler && !item.cookie_status) return false;
  47. if (!string.IsNullOrEmpty(_end_point) && !string.IsNullOrEmpty(item.end_point))
  48. {
  49. if (item.end_point != _end_point) return false;
  50. }
  51. // 使用初始化参数创建工作时间表
  52. if (!new WorkSchedule(item.time_range).IsWorkHour()) return false;
  53. if (_suspend.TryGetValue(accountid, out DateTime suspendTime))
  54. {
  55. var ts = DateTime.Now - suspendTime;
  56. if (ts.TotalSeconds < 70) return false;
  57. }
  58. if (item.daily_calls_limit > 0)
  59. {
  60. int daily_num = RiskControlCore.GetCalls(TkChannelEnum.pdd, item.id, DateTime.Now.ToString("yyyyMMdd"));
  61. if (daily_num >= item.daily_calls_limit) return false;
  62. }
  63. if (item.hourly_calls_limit > 0)
  64. {
  65. int hourly_num = RiskControlCore.GetCalls(TkChannelEnum.pdd, item.id, DateTime.Now.ToString("yyyyMMddHH"));
  66. if (hourly_num >= item.hourly_calls_limit) return false;
  67. }
  68. return true;
  69. }
  70. public static async Task<IEnumerable<PddPoolDTO>> AllListAsync(bool force = false)
  71. {
  72. if (!force && _all_cached != default) return _all_cached;
  73. try
  74. {
  75. await _semaphore.WaitAsync();
  76. string cache_key = $"cache:all_pdd_pool";
  77. var list = await RedisKit.GetAsync<IEnumerable<PddPoolDTO>>(cache_key);
  78. if (force || list == default)
  79. {
  80. list = new DBContext.Table("pdd_pool").Select<PddPoolDTO>();
  81. if (list == null) return default;
  82. // 等待 Redis 写入完成
  83. await RedisKit.SetAsync(cache_key, list, 30 * 86400);
  84. }
  85. _all_cached = list;
  86. return list;
  87. }
  88. catch (Exception)
  89. {
  90. // 发生异常时返回上一次的缓存,如果没有则返回默认值
  91. return _all_cached ?? default;
  92. }
  93. finally
  94. {
  95. _semaphore.Release();
  96. }
  97. }
  98. public static IEnumerable<PddPoolDTO> List(bool force = false)
  99. {
  100. if (!force && _cached != null) return _cached;
  101. string cache_key = $"cache:pdd_pool";
  102. var list = RedisHelper.Get<IEnumerable<PddPoolDTO>>(cache_key);
  103. if (force || list == null)
  104. {
  105. lock (_lockObj)
  106. {
  107. list = new DBContext.Table("pdd_pool")
  108. .Where("status=@status", new { status = 1 })
  109. .Select<PddPoolDTO>();
  110. if (list == null) return default;
  111. foreach (var item in list)
  112. {
  113. RiskControlCore.SetCallsAsync(TkChannelEnum.pdd, item.id, DateTime.Now.ToString("yyyyMMddHH"), item.current_hourly_calls);
  114. RiskControlCore.SetCallsAsync(TkChannelEnum.pdd, item.id, DateTime.Now.ToString("yyyyMMdd"), item.current_daily_calls);
  115. }
  116. RedisHelper.Set(cache_key, list, 30 * 86400);
  117. }
  118. }
  119. _cached = list;
  120. return list;
  121. }
  122. public static void Refresh()
  123. {
  124. _cached = null;
  125. _all_cached = null;
  126. _ = List(true);
  127. }
  128. public static void Disabled(string name)
  129. {
  130. string cache_key = $"cache:pdd_pool:{name}:disabled";
  131. long count = RedisHelper.IncrBy(cache_key);
  132. RedisHelper.Expire(cache_key, 10);
  133. if (count > 1) return;
  134. new DBContext.Table("pdd_pool")
  135. .Add("status", 0)
  136. .Where("name=@name", new { name })
  137. .Update();
  138. _ = List(true);
  139. NotifyCore.Notify(new NifyMessage
  140. {
  141. message = $"【多多:{name}】调用异常",
  142. priority = NifyMessagePriority.high,
  143. tags = ["red_circle"]
  144. });
  145. }
  146. public static void Disabled(int accountId, string name, string content)
  147. {
  148. string cache_key = $"cache:pdd_pool:{name}:disabled";
  149. long count = RedisHelper.IncrBy(cache_key);
  150. RedisHelper.Expire(cache_key, 10);
  151. if (count > 1) return;
  152. var update = new DBContext.Table("pdd_pool").Add("status", 0);
  153. if (accountId > 0)
  154. {
  155. update.Where("id=@accountId", new { accountId }).Update();
  156. }
  157. else
  158. {
  159. update.Where("name=@name", new { name }).Update();
  160. }
  161. _ = List(true);
  162. NotifyCore.Notify(new NifyMessage
  163. {
  164. message = $"【多多{accountId}:{name}】cookie 掉线\n\n{content}",
  165. priority = NifyMessagePriority.high,
  166. tags = ["red_circle"]
  167. });
  168. //NotifyCore.AnPushNotify("掉线", $"【多多{accountId}:{name}】cookie 掉线");
  169. EndPointCore.NotifyReload(true);
  170. }
  171. internal static void AccountExhausted()
  172. {
  173. string cache_key = $"cache:pdd_pool:account:exhausted";
  174. long count = RedisHelper.IncrBy(cache_key);
  175. if (count > 1) return;
  176. RedisHelper.Expire(cache_key, 3600);
  177. NotifyCore.Notify(new NifyMessage
  178. {
  179. message = $"【多多】没有匹配账号",
  180. priority = NifyMessagePriority.high,
  181. tags = ["red_circle"]
  182. });
  183. NotifyCore.AnPushNotify("没账号", $"【多多】没有匹配账号");
  184. }
  185. internal static async Task<JsonElement> GetUserInfo(string cookies)
  186. {
  187. JsonElement result = default;
  188. try
  189. {
  190. string url = "https://jinbao.pinduoduo.com/network/api/account/userInfo";
  191. WebClientUtility client = new WebClientUtility();
  192. client.Post("{}");
  193. client.SetCookies(cookies);
  194. client.SetContentType("application/json");
  195. var response = await client.RequestAsync(url, "POST");
  196. var body = response.Body();
  197. result = body.Convert2JsonElement();
  198. }
  199. catch (Exception ex)
  200. {
  201. }
  202. return result;
  203. }
  204. public static async Task<int> UpdateCookies(string cookies, string user_agent)
  205. {
  206. if (string.IsNullOrEmpty(cookies)) return 0;
  207. var userinfo = await GetUserInfo(cookies);
  208. if (userinfo.ValueKind != JsonValueKind.Object) return 0;
  209. int duoId = userinfo.PathRead<int>("result.duoId", 0);
  210. string company = userinfo.PathRead<string>("result.mobile", string.Empty);
  211. string lastPid = userinfo.PathRead<string>("result.lastPid", string.Empty);
  212. int accountId = 0;
  213. if (duoId == 0) return 0;
  214. var exist = new DBContext.Table("pdd_pool").Get<JdPoolDTO>("duoId=@duoId", new { duoId });
  215. if (exist != null)
  216. {
  217. var status = exist.status;
  218. var work_mode = exist.work_mode;
  219. accountId = exist.id;
  220. if (work_mode == JdUnionWorkMode.Crawler) status = true;
  221. new DBContext.Table("pdd_pool")
  222. .Add("duoId", duoId)
  223. .Add("cookies", cookies)
  224. .Add("user_agent", user_agent)
  225. .Add("status", status)
  226. .Add("cookie_status", 1)
  227. .Add("last_time", DateTime.Now)
  228. .Add("login_time", DateTime.Now)
  229. .Where("id=@id", new { exist.id })
  230. .Update();
  231. if (status) _ = List(true);
  232. }
  233. else
  234. {
  235. accountId = new DBContext.Table("pdd_pool")
  236. .Add("duoId", duoId)
  237. .Add("name", company)
  238. .Add("company", company)
  239. .Add("description", "由cookies上报创建此记录")
  240. .Add("cookies", cookies)
  241. .Add("user_agent", user_agent)
  242. .Add("pid", lastPid)
  243. .Add("cookie_status", 1)
  244. .Add("create_time", DateTime.Now)
  245. .Add("last_time", DateTime.Now)
  246. .Add("login_time", DateTime.Now)
  247. .Add("status", 0)
  248. .Create();
  249. }
  250. NotifyCore.Notify(new NifyMessage
  251. {
  252. message = $"【拼多多{accountId}:{company}】cookie 上线",
  253. tags = ["green_circle"]
  254. });
  255. EndPointCore.NotifyReload(true);
  256. //NotifyCore.AnPushNotify("上线", $"【淘宝联盟:{dnk}】cookie 上报更新");
  257. return accountId;
  258. }
  259. public static int CookieDisabled(int id)
  260. {
  261. return new DBContext.Table("pdd_pool")
  262. .Add("cookie_status", 0)
  263. .Add("last_time", DateTime.Now)
  264. .Where("id=@id", new { id })
  265. .Update();
  266. }
  267. public static int Update(PddPoolDTO account)
  268. {
  269. return new DBContext.Table("pdd_pool")
  270. .Add("current_hourly_calls", account.current_hourly_calls)
  271. .Add("current_daily_calls", account.current_daily_calls)
  272. //.Add("today_clickNum", account.today_clickNum)
  273. //.Add("today_cosFee", account.today_cosFee)
  274. //.Add("today_cosPrice", account.today_cosPrice)
  275. //.Add("today_finishCosFee", account.today_finishCosFee)
  276. //.Add("today_finishCosPrice", account.today_finishCosPrice)
  277. //.Add("today_finishOrderNum", account.today_finishOrderNum)
  278. //.Add("today_orderNum", account.today_orderNum)
  279. .Add("last_time", DateTime.Now)
  280. .Where("id=@id", new { account.id })
  281. .Update();
  282. }
  283. }
  284. }