PddPoolCore.cs 12 KB

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