EndPointCore.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. using dodohold.core;
  2. using MySql.Data.MySqlClient;
  3. using System.Data;
  4. namespace molilian.core
  5. {
  6. public partial class EndPointCore
  7. {
  8. private static readonly object _lockObj = new();
  9. private static IEnumerable<EndPointDTO> _cached;
  10. public static string GetRedisServer(EndPointDTO node)
  11. {
  12. #if DEBUG
  13. return node.name switch
  14. {
  15. "bj" => "101.200.152.61:6379,password=pKBiS4ka2IpXayIdcx00,defaultDatabase=0,idleTimeout=20000,preheat=3,tryit=2,ssl=false,prefix=webhook",
  16. "gz" => "8.138.110.158:6379,password=pKBiS4ka2IpXayIdcx00,defaultDatabase=0,idleTimeout=20000,preheat=3,tryit=2,ssl=false,prefix=webhook",
  17. "coupon1" => "123.56.185.166:6379,password=pKBiS4ka2IpXayIdcx00,defaultDatabase=0,idleTimeout=20000,preheat=3,tryit=2,ssl=false,prefix=coupon",
  18. _ => string.Empty
  19. };
  20. #else
  21. return node.redis_server;
  22. #endif
  23. }
  24. public static string CurrentEndPoint { get; set; }
  25. static EndPointCore()
  26. {
  27. CurrentEndPoint = Environment.GetEnvironmentVariable("EndPoint");
  28. }
  29. public static IDbConnection GetDbConnection(string connString)
  30. {
  31. var conn = new MySqlConnection(connString);
  32. return conn;
  33. }
  34. public static EndPointDTO GetOne(string node)
  35. {
  36. var list = List();
  37. if (!list.Any()) return null;
  38. var item = list.Where(s => s.name == node).FirstOrDefault();
  39. return item;
  40. }
  41. public static EndPointDTO GetCouponAdmin()
  42. {
  43. var list = List();
  44. if (!list.Any()) return null;
  45. var item = list.Where(s => s.is_coupon_api && !s.is_public_api).FirstOrDefault();
  46. #if DEBUG
  47. // item.db_server = "Server= rm-2ze49fcn8e28e6gzu3o.rwlb.rds.aliyuncs.com; Port=3306; Database=coupon; Uid=coupon; Pwd=67ktWBmw5G4yMs4J;SslMode=None;CharSet=utf8mb4;ConnectionTimeout=60;";
  48. #endif
  49. /*
  50. Server=rm-2zey1jqxnoqy9mcc0zo.rwlb.rds.aliyuncs.com; Port=3306; Database=taoke; Uid=taoke; Pwd=67ktWBmw5G4yMs4J;SslMode=None;CharSet=utf8mb4;ConnectionTimeout=60
  51. Server=rm-2zey1jqxnoqy9mcc0zo.rwlb.rds.aliyuncs.com; Port=3306; Database=taoke; Uid=taoke; Pwd=67ktWBmw5G4yMs4J;SslMode=None;CharSet=utf8mb4;ConnectionTimeout=60
  52. Server=rm-2zey1jqxnoqy9mcc0zo.rwlb.rds.aliyuncs.com; Port=3306; Database=taoke; Uid=taoke; Pwd=67ktWBmw5G4yMs4J;SslMode=None;CharSet=utf8mb4;ConnectionTimeout=60
  53. Server=rm-2ze74506m3gfsqe7mco.rwlb.rds.aliyuncs.com; Port=3306; Database=coupon; Uid=coupon; Pwd=67ktWBmw5G4yMs4J;SslMode=None;CharSet=utf8mb4;ConnectionTimeout=60;
  54. */
  55. return item;
  56. }
  57. public static EndPointDTO GetParseAdmin()
  58. {
  59. var list = List();
  60. if (!list.Any()) return null;
  61. var item = list.Where(s => !s.is_coupon_api && !s.is_public_api).FirstOrDefault();
  62. #if DEBUG
  63. item.db_server = "Server=rm-2ze49fcn8e28e6gzu3o.rwlb.rds.aliyuncs.com; Port=3306; Database=taoke; Uid=taoke; Pwd=67ktWBmw5G4yMs4J;SslMode=None;CharSet=utf8mb4;ConnectionTimeout=60;";
  64. #endif
  65. return item;
  66. }
  67. public static IEnumerable<EndPointDTO> List(bool force = false)
  68. {
  69. if (!force && _cached != null) return _cached;
  70. string cache_key = $"cache:end_point";
  71. var list = RedisHelper.Get<IEnumerable<EndPointDTO>>(cache_key);
  72. if (force || list == null)
  73. {
  74. lock (_lockObj)
  75. {
  76. list = new DBContext.Table("end_point")
  77. .Where("status=@status", new { status = 1 })
  78. .Select<EndPointDTO>();
  79. if (list == null) return default;
  80. RedisHelper.Set(cache_key, list, 30 * 86400);
  81. }
  82. }
  83. _cached = list;
  84. return list;
  85. }
  86. public static void Refresh()
  87. {
  88. _ = List(true);
  89. }
  90. public static List<T> ProcessEndPointNodes<T>(Func<EndPointDTO, T> nodeAction, bool force = false)
  91. {
  92. var resultList = new List<T>();
  93. var list = List(force);
  94. foreach (var node in list)
  95. {
  96. var result = nodeAction(node);
  97. if (result != null) resultList.Add(result);
  98. }
  99. return resultList;
  100. }
  101. public static async Task<List<T>> ProcessEndPointNodesTaskAsync<T>(Func<EndPointDTO, Task<T>> nodeAction, bool force = false)
  102. {
  103. var resultList = new List<T>();
  104. var list = List(force);
  105. var tasks = list.Select(node => nodeAction(node));
  106. var results = await Task.WhenAll(tasks);
  107. return results.Where(result => result != null).ToList();
  108. //foreach (var node in list)
  109. //{
  110. // var result = await nodeAction(node);
  111. // if (result != null) resultList.Add(result);
  112. //}
  113. //return resultList;
  114. }
  115. public static async Task ProcessEndPointNodesAsync(Func<EndPointDTO, Task> nodeAction, bool force = false)
  116. {
  117. var list = List(force);
  118. var tasks = list.Select(node => nodeAction(node));
  119. await Task.WhenAll(tasks);
  120. }
  121. public static async Task NotifyReload(bool onlyAccount = false, CancellationToken cancellationToken = default)
  122. {
  123. await ProcessEndPointNodesAsync(async node =>
  124. {
  125. try
  126. {
  127. string url = $"{node.api_server}Task_70160bd632/reload";
  128. if (onlyAccount) url = $"{node.api_server}Task_70160bd632/reloadAccount";
  129. await new WebClientUtility().RequestAsync(url, "GET", cancellationToken);
  130. }
  131. catch (Exception ex)
  132. {
  133. _ = new LoggerLibrary("NotifyReload", "error")
  134. .Info(node.Convert2Json())
  135. .Info(ex.Message, ex.StackTrace)
  136. .SaveAsync();
  137. NotifyCore.Notify(new NifyMessage
  138. {
  139. message = $"【NotifyReload异常】{node.description}\n{ex.Message}\n{ex.StackTrace}",
  140. priority = NifyMessagePriority.high,
  141. tags = ["red_circle"]
  142. });
  143. }
  144. });
  145. }
  146. public static List<(string, string)> NotifyCheckDeepUrl(int accountid, CancellationToken cancellationToken = default)
  147. {
  148. var result = ProcessEndPointNodes<(string, string)>(node =>
  149. {
  150. try
  151. {
  152. if (!node.is_public_api) return (node.name, "break");
  153. if (!node.status) return (node.name, "账号下线");
  154. string url = $"{node.api_server}Task_70160bd632/CheckDeepUrl?accountid={accountid}";
  155. var result = new WebClientUtility().Request(url, "GET");
  156. string body = result.Body();
  157. var root = body.Convert2JsonElement();
  158. var message = root.Read<string>("message", string.Empty);
  159. return (node.name, message);
  160. }
  161. catch (Exception ex)
  162. {
  163. _ = new LoggerLibrary("CheckDeepUrl", "error")
  164. .Info(node.Convert2Json(), $"accountid:\t{accountid}")
  165. .Info(ex.Message, ex.StackTrace)
  166. .SaveAsync();
  167. NotifyCore.Notify(new NifyMessage
  168. {
  169. message = $"【CheckDeepUrl异常】{node.description}\n{ex.Message}\n{ex.StackTrace}",
  170. priority = NifyMessagePriority.high,
  171. tags = ["red_circle"]
  172. });
  173. return (node.name, ex.Message);
  174. }
  175. });
  176. return result;
  177. }
  178. public static async Task NotifyChangeSuspend(int accountId, string endpoint, bool release = false, int? durationSeconds = null, CancellationToken cancellationToken = default)
  179. {
  180. await ProcessEndPointNodesAsync(async node =>
  181. {
  182. string post = string.Empty;
  183. try
  184. {
  185. if (string.Equals(node.name, CurrentEndPoint, StringComparison.OrdinalIgnoreCase)) return;
  186. string url = $"{node.api_server}api/TkEndpoint/ChangeSuspend";
  187. post = new
  188. {
  189. accountId,
  190. endpoint,
  191. release,
  192. durationSeconds
  193. }.Convert2Json();
  194. await new WebClientUtility().Post(post).RequestAsync(url, "POST", cancellationToken);
  195. }
  196. catch (Exception ex)
  197. {
  198. _ = new LoggerLibrary("TkEndpoint", "ChangeSuspend_error")
  199. .Info(node.Convert2Json(), post)
  200. .Info(ex.Message, ex.StackTrace)
  201. .SaveAsync();
  202. NotifyCore.Notify(new NifyMessage
  203. {
  204. message = $"【TkEndpoint异常】ChangeSuspend\t{node.description}\n{post}\n{ex.Message}\n{ex.StackTrace}",
  205. priority = NifyMessagePriority.high,
  206. tags = ["red_circle"]
  207. });
  208. }
  209. });
  210. }
  211. public static List<(string, string)> TkEndpointGetStatus(int accountid, CancellationToken cancellationToken = default)
  212. {
  213. var result = ProcessEndPointNodes<(string, string)>(node =>
  214. {
  215. try
  216. {
  217. if (!node.is_public_api) return (node.name, "break");
  218. if (!node.status) return (node.name, "账号下线");
  219. string url = $"{node.api_server}api/TkEndpoint/GetStatus";
  220. var result = new WebClientUtility().Request(url, "POST");
  221. string body = result.Body();
  222. var root = body.Convert2JsonElement();
  223. var message = root.Read<string>("message", string.Empty);
  224. return (node.name, message);
  225. }
  226. catch (Exception ex)
  227. {
  228. _ = new LoggerLibrary("GetStatus", "error")
  229. .Info(node.Convert2Json(), $"accountid:\t{accountid}")
  230. .Info(ex.Message, ex.StackTrace)
  231. .SaveAsync();
  232. NotifyCore.Notify(new NifyMessage
  233. {
  234. message = $"【TkEndpoint异常】GetStatus\t{node.description}\n{ex.Message}\n{ex.StackTrace}",
  235. priority = NifyMessagePriority.high,
  236. tags = ["red_circle"]
  237. });
  238. return (node.name, ex.Message);
  239. }
  240. });
  241. return result;
  242. }
  243. }
  244. }