using FastGithub.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace FastGithub.DomainResolve
{
///
/// DnscryptProxy后台服务
///
sealed class DnscryptProxyHostedService : IHostedService
{
private readonly FastGithubConfig fastGithubConfig;
private readonly ILogger logger;
private DnscryptProxy? dnscryptProxy;
///
/// DnscryptProxy后台服务
///
///
///
public DnscryptProxyHostedService(
FastGithubConfig fastGithubConfig,
ILogger logger)
{
this.fastGithubConfig = fastGithubConfig;
this.logger = logger;
}
///
/// 启动dnscrypt-proxy
///
///
///
public async Task StartAsync(CancellationToken cancellationToken)
{
var pureDns = this.fastGithubConfig.PureDns;
if (LocalMachine.ContainsIPAddress(pureDns.Address) == true)
{
this.dnscryptProxy = new DnscryptProxy(pureDns);
try
{
await this.dnscryptProxy.StartAsync(cancellationToken);
this.logger.LogInformation($"{this.dnscryptProxy}启动成功");
}
catch (Exception ex)
{
this.logger.LogWarning($"{this.dnscryptProxy}启动失败:{ex.Message}");
}
}
}
///
/// 停止dnscrypt-proxy
///
///
///
public Task StopAsync(CancellationToken cancellationToken)
{
if (this.dnscryptProxy != null)
{
try
{
this.dnscryptProxy.Stop();
this.logger.LogInformation($"{this.dnscryptProxy}已停止");
}
catch (Exception ex)
{
this.logger.LogWarning($"{this.dnscryptProxy}停止失败:{ex.Message}");
}
}
return Task.CompletedTask;
}
}
}