diff --git a/FastGithub/AppHostedService.cs b/FastGithub/AppHostedService.cs index 31a46e4..59426ba 100644 --- a/FastGithub/AppHostedService.cs +++ b/FastGithub/AppHostedService.cs @@ -1,30 +1,119 @@ -using Microsoft.Extensions.Hosting; +using FastGithub.Configuration; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using System; +using System.Linq; +using System.Net; +using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace FastGithub { - sealed class AppHostedService : IHostedService + /// + /// app后台服务 + /// + sealed class AppHostedService : BackgroundService { + private readonly IOptions options; private readonly ILogger logger; - public AppHostedService(ILogger logger) + public AppHostedService( + IOptions options, + ILogger logger) { + this.options = options; this.logger = logger; } - public Task StartAsync(CancellationToken cancellationToken) + /// + /// 启动完成 + /// + /// + /// + public override Task StartAsync(CancellationToken cancellationToken) { var version = ProductionVersion.Current; this.logger.LogInformation($"{nameof(FastGithub)}启动完成,当前版本为v{version},访问https://github.com/dotnetcore/FastGithub关注新版本"); - return Task.CompletedTask; + return base.StartAsync(cancellationToken); } - public Task StopAsync(CancellationToken cancellationToken) + /// + /// 停止完成 + /// + /// + /// + public override Task StopAsync(CancellationToken cancellationToken) { this.logger.LogInformation($"{nameof(FastGithub)}已停止运行"); - return Task.CompletedTask; + return base.StopAsync(cancellationToken); + } + + /// + /// 后台任务 + /// + /// + /// + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + if (OperatingSystem.IsWindows() == false) + { + await Task.Delay(TimeSpan.FromSeconds(1d), stoppingToken); + if (await this.UseFastGithubProxyAsync() == false) + { + this.logger.LogWarning($"请手工设置系统代理为http://127.0.0.1:38457或自动代理为http://127.0.0.1:38457/proxy.pac"); + } + } + } + + /// + /// 应用fastgithub代理 + /// + /// + /// + /// + private async Task UseFastGithubProxyAsync() + { + var systemProxy = HttpClient.DefaultProxy; + if (systemProxy == null) + { + return false; + } + + var domain = this.options.Value.DomainConfigs.Keys.FirstOrDefault(); + if (domain == null) + { + return true; + } + + var destination = new Uri($"https://{domain.Replace('*', 'a')}"); + var proxyServer = systemProxy.GetProxy(destination); + if (proxyServer == null) + { + return false; + } + + var httpProxyPort = this.options.Value.HttpProxyPort; + if (proxyServer.Port != httpProxyPort) + { + return false; + } + + if (IPAddress.TryParse(proxyServer.Host, out var address)) + { + return address.Equals(IPAddress.Loopback); + } + + try + { + var addresses = await System.Net.Dns.GetHostAddressesAsync(proxyServer.Host); + return addresses.Contains(IPAddress.Loopback); + } + catch (Exception) + { + return false; + } } } }