ProxyNodesCore.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 Spire.Pdf.Exporting.XPS.Schema;
  10. using System.Xml.Linq;
  11. using System.Net;
  12. using TencentCloud.Mrs.V20200910.Models;
  13. using static molilian.core.TkPoolCore;
  14. namespace molilian.core
  15. {
  16. public partial class ProxyNodesCore
  17. {
  18. private static string _end_point;
  19. static ProxyNodesCore()
  20. {
  21. _end_point = Environment.GetEnvironmentVariable("EndPoint");
  22. }
  23. private static readonly object _lockObj = new();
  24. private static IEnumerable<ProxyNodesDTO> _cached;
  25. public static WebProxy? GetOne(string node)
  26. {
  27. var list = List();
  28. if (!list.Any()) return null;
  29. var ProxyNodesDTO = list.Where(e => SelectEndPointUseProxy(e, node)).OrderBy(l => Guid.NewGuid()).FirstOrDefault();
  30. if (ProxyNodesDTO == null) return null;
  31. return new WebProxy
  32. {
  33. Address = new Uri(ProxyNodesDTO.server),
  34. Credentials = new NetworkCredential(ProxyNodesDTO.username, ProxyNodesDTO.password)
  35. };
  36. }
  37. public static WebProxy? RandomOne()
  38. {
  39. var list = List();
  40. if (!list.Any()) return null;
  41. var ProxyNodesDTO = list.Where(e => SelectEndPointUseProxy(e, string.Empty)).OrderBy(l => Guid.NewGuid()).FirstOrDefault();
  42. if (ProxyNodesDTO == null) return null;
  43. return new WebProxy
  44. {
  45. Address = new Uri(ProxyNodesDTO.server),
  46. Credentials = new NetworkCredential(ProxyNodesDTO.username, ProxyNodesDTO.password)
  47. };
  48. }
  49. private static bool SelectEndPointUseProxy(ProxyNodesDTO item, string node="")
  50. {
  51. if (!string.IsNullOrEmpty(_end_point) && !string.IsNullOrEmpty(item.end_point))
  52. {
  53. if (item.end_point != _end_point) return false;
  54. }
  55. return string.IsNullOrEmpty(node) || item.name == node;
  56. }
  57. public static IEnumerable<ProxyNodesDTO> List(bool force = false)
  58. {
  59. if (!force && _cached != null) return _cached;
  60. string cache_key = $"cache:proxy_nodes";
  61. var list = RedisHelper.Get<IEnumerable<ProxyNodesDTO>>(cache_key);
  62. if (force || list == null)
  63. {
  64. lock (_lockObj)
  65. {
  66. list = new DBContext.Table("proxy_nodes")
  67. .Where("status=@status", new { status = 1 })
  68. .Select<ProxyNodesDTO>();
  69. if (list == null) return default;
  70. RedisHelper.Set(cache_key, list, 30 * 86400);
  71. }
  72. }
  73. _cached = list;
  74. return list;
  75. }
  76. public static void Refresh()
  77. {
  78. _ = List(true);
  79. }
  80. }
  81. }