2
0

GithubScanService.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using FastGithub.Scanner.Middlewares;
  2. using Microsoft.Extensions.DependencyInjection;
  3. using Microsoft.Extensions.Logging;
  4. using System;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace FastGithub.Scanner
  9. {
  10. [Service(ServiceLifetime.Singleton)]
  11. sealed class GithubScanService
  12. {
  13. private readonly GithubMetaService metaService;
  14. private readonly ILogger<GithubScanService> logger;
  15. private readonly GithubContextCollection contextCollection;
  16. private readonly InvokeDelegate<GithubContext> fullScanDelegate;
  17. private readonly InvokeDelegate<GithubContext> resultScanDelegate;
  18. public GithubScanService(
  19. GithubMetaService metaService,
  20. GithubContextCollection contextCollection,
  21. IServiceProvider appService,
  22. ILogger<GithubScanService> logger)
  23. {
  24. this.metaService = metaService;
  25. this.contextCollection = contextCollection;
  26. this.logger = logger;
  27. ;
  28. this.fullScanDelegate = new PipelineBuilder<GithubContext>(appService, ctx => Task.CompletedTask)
  29. .Use<ConcurrentMiddleware>()
  30. .Use<ScanOkLogMiddleware>()
  31. .Use<StatisticsMiddleware>()
  32. .Use<PortScanMiddleware>()
  33. .Use<HttpsScanMiddleware>()
  34. .Build();
  35. this.resultScanDelegate = new PipelineBuilder<GithubContext>(appService, ctx => Task.CompletedTask)
  36. .Use<ScanOkLogMiddleware>()
  37. .Use<StatisticsMiddleware>()
  38. .Use<PortScanMiddleware>()
  39. .Use<HttpsScanMiddleware>()
  40. .Build();
  41. }
  42. public async Task ScanAllAsync(CancellationToken cancellationToken = default)
  43. {
  44. this.logger.LogInformation("完整扫描开始");
  45. var meta = await this.metaService.GetMetaAsync(cancellationToken);
  46. if (meta != null)
  47. {
  48. var scanTasks = meta.ToGithubContexts().Select(ctx => ScanAsync(ctx));
  49. await Task.WhenAll(scanTasks);
  50. }
  51. this.logger.LogInformation("完整扫描结束");
  52. async Task ScanAsync(GithubContext context)
  53. {
  54. await this.fullScanDelegate(context);
  55. if (context.Available == true)
  56. {
  57. this.contextCollection.Add(context);
  58. }
  59. }
  60. }
  61. public async Task ScanResultAsync()
  62. {
  63. this.logger.LogInformation("结果扫描开始");
  64. var contexts = this.contextCollection.ToArray();
  65. foreach (var context in contexts)
  66. {
  67. await this.resultScanDelegate(context);
  68. }
  69. this.logger.LogInformation("结果扫描结束");
  70. }
  71. }
  72. }