GithubScanResults.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using Microsoft.Extensions.DependencyInjection;
  2. using Microsoft.Extensions.Options;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Net;
  6. namespace FastGithub.Scanner
  7. {
  8. /// <summary>
  9. /// GithubContext集合
  10. /// </summary>
  11. [Service(ServiceLifetime.Singleton)]
  12. sealed class GithubScanResults : IGithubScanResults
  13. {
  14. private readonly object syncRoot = new();
  15. private readonly List<GithubContext> contexts = new();
  16. private readonly IOptionsMonitor<GithubLookupFactoryOptions> options;
  17. public GithubScanResults(IOptionsMonitor<GithubLookupFactoryOptions> options)
  18. {
  19. this.options = options;
  20. }
  21. /// <summary>
  22. /// 添加GithubContext
  23. /// </summary>
  24. /// <param name="context"></param>
  25. /// <returns></returns>
  26. public bool Add(GithubContext context)
  27. {
  28. lock (this.syncRoot)
  29. {
  30. if (this.contexts.Contains(context))
  31. {
  32. return false;
  33. }
  34. this.contexts.Add(context);
  35. return true;
  36. }
  37. }
  38. /// <summary>
  39. /// 转换为数组
  40. /// </summary>
  41. /// <returns></returns>
  42. public GithubContext[] ToArray()
  43. {
  44. lock (this.syncRoot)
  45. {
  46. return this.contexts.ToArray();
  47. }
  48. }
  49. /// <summary>
  50. /// 查找最优的ip
  51. /// </summary>
  52. /// <param name="domain"></param>
  53. /// <returns></returns>
  54. public IPAddress? FindBestAddress(string domain)
  55. {
  56. if (this.options.CurrentValue.Domains.Contains(domain) == false)
  57. {
  58. return default;
  59. }
  60. lock (this.syncRoot)
  61. {
  62. return this.contexts
  63. .Where(item => item.Domain == domain && item.AvailableRate > 0d)
  64. .OrderByDescending(item => item.AvailableRate)
  65. .ThenByDescending(item => item.Available)
  66. .ThenBy(item => item.AvgElapsed)
  67. .Select(item => item.Address)
  68. .FirstOrDefault();
  69. }
  70. }
  71. }
  72. }