PddPoolCore.cs 12 KB

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