PddPoolCore.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. _ = List(true);
  125. }
  126. public static void Disabled(string name)
  127. {
  128. string cache_key = $"cache:pdd_pool:{name}:disabled";
  129. long count = RedisHelper.IncrBy(cache_key);
  130. RedisHelper.Expire(cache_key, 10);
  131. if (count > 1) return;
  132. new DBContext.Table("pdd_pool")
  133. .Add("status", 0)
  134. .Where("name=@name", new { name })
  135. .Update();
  136. _ = List(true);
  137. NotifyCore.Notify(new NifyMessage
  138. {
  139. message = $"【多多:{name}】调用异常",
  140. priority = NifyMessagePriority.high,
  141. tags = ["red_circle"]
  142. });
  143. }
  144. public static void Disabled(int accountId, string name, string content)
  145. {
  146. string cache_key = $"cache:pdd_pool:{name}:disabled";
  147. long count = RedisHelper.IncrBy(cache_key);
  148. RedisHelper.Expire(cache_key, 10);
  149. if (count > 1) return;
  150. var update = new DBContext.Table("pdd_pool").Add("status", 0);
  151. if (accountId > 0)
  152. {
  153. update.Where("id=@accountId", new { accountId }).Update();
  154. }
  155. else
  156. {
  157. update.Where("name=@name", new { name }).Update();
  158. }
  159. _ = List(true);
  160. NotifyCore.Notify(new NifyMessage
  161. {
  162. message = $"【多多{accountId}:{name}】cookie 掉线\n\n{content}",
  163. priority = NifyMessagePriority.high,
  164. tags = ["red_circle"]
  165. });
  166. //NotifyCore.AnPushNotify("掉线", $"【多多{accountId}:{name}】cookie 掉线");
  167. EndPointCore.NotifyReload(true);
  168. }
  169. internal static void AccountExhausted()
  170. {
  171. string cache_key = $"cache:pdd_pool:account:exhausted";
  172. long count = RedisHelper.IncrBy(cache_key);
  173. if (count > 1) return;
  174. RedisHelper.Expire(cache_key, 3600);
  175. NotifyCore.Notify(new NifyMessage
  176. {
  177. message = $"【多多】没有匹配账号",
  178. priority = NifyMessagePriority.high,
  179. tags = ["red_circle"]
  180. });
  181. NotifyCore.AnPushNotify("没账号", $"【多多】没有匹配账号");
  182. }
  183. internal static async Task<JsonElement> GetUserInfo(string cookies)
  184. {
  185. JsonElement result = default;
  186. try
  187. {
  188. string url = "https://jinbao.pinduoduo.com/network/api/account/userInfo";
  189. WebClientUtility client = new WebClientUtility();
  190. client.Post("{}");
  191. client.SetCookies(cookies);
  192. client.SetContentType("application/json");
  193. var response = await client.RequestAsync(url, "POST");
  194. var body = response.Body();
  195. result = body.Convert2JsonElement();
  196. }
  197. catch (Exception ex)
  198. {
  199. }
  200. return result;
  201. }
  202. public static async Task<int> UpdateCookies(string cookies, string user_agent)
  203. {
  204. if (string.IsNullOrEmpty(cookies)) return 0;
  205. var userinfo = await GetUserInfo(cookies);
  206. if (userinfo.ValueKind != JsonValueKind.Object) return 0;
  207. int duoId = userinfo.PathRead<int>("result.duoId", 0);
  208. string company = userinfo.PathRead<string>("result.mobile", string.Empty);
  209. string lastPid = userinfo.PathRead<string>("result.lastPid", string.Empty);
  210. int accountId = 0;
  211. if (duoId == 0) return 0;
  212. var exist = new DBContext.Table("pdd_pool").Get<JdPoolDTO>("duoId=@duoId", new { duoId });
  213. if (exist != null)
  214. {
  215. var status = exist.status;
  216. var work_mode = exist.work_mode;
  217. accountId = exist.id;
  218. if (work_mode == JdUnionWorkMode.Crawler) status = true;
  219. new DBContext.Table("pdd_pool")
  220. .Add("duoId", duoId)
  221. .Add("cookies", cookies)
  222. .Add("user_agent", user_agent)
  223. .Add("status", status)
  224. .Add("cookie_status", 1)
  225. .Add("last_time", DateTime.Now)
  226. .Add("login_time", DateTime.Now)
  227. .Where("id=@id", new { exist.id })
  228. .Update();
  229. if (status) _ = List(true);
  230. }
  231. else
  232. {
  233. accountId = new DBContext.Table("pdd_pool")
  234. .Add("duoId", duoId)
  235. .Add("name", company)
  236. .Add("company", company)
  237. .Add("description", "由cookies上报创建此记录")
  238. .Add("cookies", cookies)
  239. .Add("user_agent", user_agent)
  240. .Add("pid", lastPid)
  241. .Add("cookie_status", 1)
  242. .Add("create_time", DateTime.Now)
  243. .Add("last_time", DateTime.Now)
  244. .Add("login_time", DateTime.Now)
  245. .Add("status", 0)
  246. .Create();
  247. }
  248. NotifyCore.Notify(new NifyMessage
  249. {
  250. message = $"【拼多多{accountId}:{company}】cookie 上线",
  251. tags = ["green_circle"]
  252. });
  253. EndPointCore.NotifyReload(true);
  254. //NotifyCore.AnPushNotify("上线", $"【淘宝联盟:{dnk}】cookie 上报更新");
  255. return accountId;
  256. }
  257. public static int CookieDisabled(int id)
  258. {
  259. return new DBContext.Table("pdd_pool")
  260. .Add("cookie_status", 0)
  261. .Add("last_time", DateTime.Now)
  262. .Where("id=@id", new { id })
  263. .Update();
  264. }
  265. public static int Update(PddPoolDTO account)
  266. {
  267. return new DBContext.Table("pdd_pool")
  268. .Add("current_hourly_calls", account.current_hourly_calls)
  269. .Add("current_daily_calls", account.current_daily_calls)
  270. //.Add("today_clickNum", account.today_clickNum)
  271. //.Add("today_cosFee", account.today_cosFee)
  272. //.Add("today_cosPrice", account.today_cosPrice)
  273. //.Add("today_finishCosFee", account.today_finishCosFee)
  274. //.Add("today_finishCosPrice", account.today_finishCosPrice)
  275. //.Add("today_finishOrderNum", account.today_finishOrderNum)
  276. //.Add("today_orderNum", account.today_orderNum)
  277. .Add("last_time", DateTime.Now)
  278. .Where("id=@id", new { account.id })
  279. .Update();
  280. }
  281. }
  282. }