添加项目文件。

This commit is contained in:
2022-10-23 00:19:40 +08:00
parent a471f2f5c7
commit a36415d93b
27 changed files with 969 additions and 0 deletions

25
.dockerignore Normal file
View File

@@ -0,0 +1,25 @@
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md

View File

@@ -0,0 +1,35 @@
using Hua.DDNS.Jobs;
using Hua.DDNS.Test.Start;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
namespace Hua.DDNS.Test
{
public class AppJobTest
{
[Theory]
[InlineData("appsetting.Ali.json")]
[InlineData("appsetting.Tencent.json")]
public void UpdateDNS(string configPath)
{
try
{
var config = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile(configPath, true)
.AddEnvironmentVariables()// <20>ѻ<EFBFBD><D1BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ҳ<EFBFBD>ŵ<EFBFBD> Configuraiton<6F><6E><EFBFBD><EFBFBD>
.Build();
var sc = DIConfig.ConfigureServices(config);
var job = sc.GetService<AppJob>();
job?.Execute(null);
}
catch (Exception e)
{
Assert.False(false, $"<22><><EFBFBD><EFBFBD><EFBFBD>쳣:{e.Message}");
}
}
}
}

View File

@@ -0,0 +1,37 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.0" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.1.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Hua.DDNS\Hua.DDNS.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.Ali.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="appsettings.Tencent.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hua.DDNS.Common.Config;
using Hua.DDNS.Common.Http;
using Hua.DDNS.Common;
using Hua.DDNS.Jobs;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace Hua.DDNS.Test.Start
{
public class DIConfig
{
public static IServiceProvider ConfigureServices(IConfiguration configuration)
{
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.File(
Path.Combine("Log\\log-.log"),
rollingInterval: RollingInterval.Day)
.CreateLogger();
var services = new ServiceCollection();
services.AddSingleton<IConfiguration>(configuration);
services.AddLogging(loggingBuilder =>
{
loggingBuilder.AddConfiguration(configuration.GetSection("Logging")); //配置logging的一些东西
// 下面的这行需要 Microsoft.Extensions.Logging.Console
loggingBuilder.AddConsole(); //加多个 每一个Ilooger下面就会有多个provider
});
// 注入了一个默认的ILogger
services.AddSingleton<SettingProvider>();
//services.AddSingleton<SyncECMFileProvider>();
services.AddSingleton<Url>();
services.AddSingleton<SqlHelper>();
services.AddTransient<IHttpHelper, HttpHelper>();
services.AddTransient<AppJob>();
return services.BuildServiceProvider();
}
}
}

1
Hua.DDNS.Test/Usings.cs Normal file
View File

@@ -0,0 +1 @@
global using Xunit;

View File

@@ -0,0 +1,32 @@
{
"ConnectionStrings": {
"pgConnection": "Host=127.0.0.1;Port=5432;Database=Worker;Username=Worker;Password=123456;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"App": {
"AppJob": {
"Corn": "* * * * * ?" //https://cron.qqe2.com/
},
"Domain": {
"Platform": "Ali",
// 阿里云的 Access Id
"Id": "AliId",
// 阿里云的 Access Key
"Key": "AliKey",
// 主域名
"domain": "demoDomain.cn",
// 子域名前缀
"subDomainArray": [ "bjb", "git" ],
// 记录类型
"type": "A",
//间隔时间 秒
"time": "30"
}
}
}

View File

@@ -0,0 +1,32 @@
{
"ConnectionStrings": {
"pgConnection": "Host=127.0.0.1;Port=5432;Database=Worker;Username=Worker;Password=123456;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"App": {
"AppJob": {
"Corn": "* * * * * ?" //https://cron.qqe2.com/
},
"Domain": {
"Platform": "Tencent",
// 阿里云的 Access Id
"Id": "Id",
// 阿里云的 Access Key
"Key": "Key",
// 主域名
"domain": "demoDomain.cn",
// 子域名前缀
"subDomainArray": [ "bjb", "git" ],
// 记录类型
"type": "A",
//间隔时间 秒
"time": "30"
}
}
}

31
Hua.DDNS.sln Normal file
View File

@@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.2.32616.157
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Hua.DDNS", "Hua.DDNS\Hua.DDNS.csproj", "{EBC77B5D-87D5-4923-84A6-93DB2248DEB0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Hua.DDNS.Test", "Hua.DDNS.Test\Hua.DDNS.Test.csproj", "{BB544060-5ABF-4A3C-965B-BE7CA7BD61E7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{EBC77B5D-87D5-4923-84A6-93DB2248DEB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EBC77B5D-87D5-4923-84A6-93DB2248DEB0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EBC77B5D-87D5-4923-84A6-93DB2248DEB0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EBC77B5D-87D5-4923-84A6-93DB2248DEB0}.Release|Any CPU.Build.0 = Release|Any CPU
{BB544060-5ABF-4A3C-965B-BE7CA7BD61E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BB544060-5ABF-4A3C-965B-BE7CA7BD61E7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BB544060-5ABF-4A3C-965B-BE7CA7BD61E7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BB544060-5ABF-4A3C-965B-BE7CA7BD61E7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {D8744CA6-C2DB-4287-B8B3-E5917B12391D}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,8 @@
namespace Hua.DDNS.Common.Config.Options
{
public class AppOption
{
public DomainOption Domain { get; set; }
}
}

View File

@@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hua.DDNS.Common.Config.Options
{
public class DomainOption
{
/// <summary>
/// 平台
/// </summary>
public string Platform { get; set; }
/// <summary>
/// Id
/// </summary>
public string Id { get; set; }
/// <summary>
/// Key
/// </summary>
public string Key { get; set; }
/// <summary>
/// 域名
/// </summary>
public string domain { get; set; }
/// <summary>
/// 子域列表
/// </summary>
public string[] subDomainArray { get; set; }
/// <summary>
/// 解析记录类型
/// </summary>
public string type { get; set; }
/// <summary>
/// 间隔时间 秒
/// </summary>
public string time { get; set; }
}
}

View File

@@ -0,0 +1,17 @@
using Hua.DDNS.Common.Config.Options;
namespace Hua.DDNS.Common.Config
{
public class SettingProvider
{
private readonly AppOption _app;
public SettingProvider(IConfiguration configuration)
{
_app = new AppOption();
configuration.GetSection("App").Bind(_app);
}
public AppOption App => _app;
}
}

View File

@@ -0,0 +1,13 @@
namespace Hua.DDNS.Common
{
public class FileHelper
{
public static void DeleteIfExists(string path)
{
if (File.Exists(path))
{
File.Delete(path);
}
}
}
}

View File

@@ -0,0 +1,141 @@
using System.Net;
using System.Net.Http.Json;
using Newtonsoft.Json;
namespace Hua.DDNS.Common.Http
{
public class HttpHelper: IHttpHelper
{
private static ILogger<HttpHelper> _logger;
private static HttpClientHandler _handler;
public HttpHelper(ILogger<HttpHelper> logger)
{
_logger = logger;
_handler = new HttpClientHandler();
}
public HttpClient GetHttpClient()
{
return new HttpClient(_handler){};
}
/// <summary>
/// PostAsync
/// </summary>
/// <typeparam name="TIn"></typeparam>
/// <typeparam name="TOut"></typeparam>
/// <param name="url"></param>
/// <param name="input"></param>
/// <param name="timeOut">超时时间</param>
/// <returns></returns>
public async Task<TOut?> PostAsync<TIn, TOut>(string url, TIn input, int timeOut = 10)
{
try
{
var client = GetHttpClient();
client.Timeout = new TimeSpan(0, 10, timeOut);
_logger.LogDebug($"Post:{url}\n[{JsonConvert.SerializeObject(input)}]");
var result = await client.PostAsync(url, JsonContent.Create(input));
var strResult = await result.Content.ReadAsStringAsync();
if (result.StatusCode != HttpStatusCode.OK)
{
_logger.LogDebug($"Error[{result.StatusCode}]:{url}\t{strResult}");
}
return await result.Content.ReadFromJsonAsync<TOut>();
}
catch (Exception e)
{
_logger.LogError(url);
_logger.LogError(e.Message);
throw;
}
}
/// <summary>
/// PostAsync
/// </summary>
/// <typeparam name="TOut"></typeparam>
/// <param name="url"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public async Task<TOut?> GetAsync<TOut>(string url,int timeOut = 10)
{
try
{
var client = GetHttpClient();
client.Timeout = new TimeSpan(0, 10, timeOut);
_logger.LogDebug($"Get:{url}");
var result = await client.GetAsync(url);
var strResult = await result.Content.ReadAsStringAsync();
if (result.StatusCode != HttpStatusCode.OK)
{
_logger.LogDebug($"Error[{result.StatusCode}]:{url}\t{strResult}");
}
return await result.Content.ReadFromJsonAsync<TOut>();
}
catch (Exception e)
{
_logger.LogError(url);
_logger.LogError(e.Message);
throw;
}
}
#region
/// <summary>
/// http下载文件 (仅支持小文件)
/// </summary>
/// <param name="url">下载文件地址</param>
/// <param name="localPath">文件存放地址,包含文件名</param>
/// <returns></returns>
public bool DownloadFile(string url, string localPath)
{
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
var request = WebRequest.Create(url) as HttpWebRequest;
Stream stream = new FileStream(localPath, FileMode.CreateNew);
try
{
// 设置参数
//发送请求并获取相应回应数据
var response = request?.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
var responseStream = response?.GetResponseStream();
//创建本地文件写入流
stream.Close();
responseStream?.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
#endregion
/// <summary>
/// 获得当前机器的公网 IP
/// </summary>
public async Task<string> GetCurrentPublicIpv4()
{
using var client = new HttpClient();
using var request = new HttpRequestMessage(HttpMethod.Get, "http://175.24.175.136:8008/WebUtil/GetIp");
using var response = await client.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
public interface IHttpHelper
{
public Task<string> GetCurrentPublicIpv4();
public Task<TOut?> PostAsync<TIn, TOut>(string url, TIn input, int timeOut = 10);
public Task<TOut?> GetAsync<TOut>(string url, int timeOut = 10);
public bool DownloadFile(string url, string fileFullName);
public HttpClient GetHttpClient();
}
}

View File

@@ -0,0 +1,14 @@
namespace Hua.DDNS.Common.Http
{
public class HttpResult<T>
{
public virtual T Data { get; set; }
public string DataDescription { get; set; }
public int Result { get; set; }
public string Message { get; set; }
}
}

View File

@@ -0,0 +1,16 @@
using Hua.DDNS.Common.Config;
using Hua.DDNS.Start;
namespace Hua.DDNS.Common.Http
{
public class Url
{
private readonly SettingProvider _settingProvider;
public Url(SettingProvider settingProvider)
{
_settingProvider = settingProvider;
}
}
}

View File

@@ -0,0 +1,46 @@
using System.Data;
using Dapper;
using Npgsql;
namespace Hua.DDNS.Common
{
public class SqlHelper
{
private readonly string _connectionString;
private readonly ILogger<SqlHelper> _logger;
public SqlHelper(IConfiguration configuration, ILogger<SqlHelper> logger)
{
_logger = logger;
_connectionString = configuration.GetConnectionString("pgsql");
}
/// <summary>
/// 查询所有结果
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="strSql"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public List<T> GetList<T>(string strSql)
{
var list = new List<T>();
try
{
using IDbConnection connection = new NpgsqlConnection(_connectionString);
connection.Open();
list = connection.Query<T>(strSql).ToList();
connection.Close();
}
catch (Exception e)
{
_logger.LogError(e.Message);
throw;
}
return list;
}
}
}

23
Hua.DDNS/Dockerfile Normal file
View File

@@ -0,0 +1,23 @@
#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
#Depending on the operating system of the host machines(s) that will build or run the containers, the image specified in the FROM statement may need to be changed.
#For more information, please see https://aka.ms/containercompat
FROM mcr.microsoft.com/dotnet/runtime:6.0 AS base
WORKDIR /app
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["Hua.DDNS/Hua.DDNS.csproj", "Hua.DDNS/"]
RUN dotnet restore "Hua.DDNS/Hua.DDNS.csproj"
COPY . .
WORKDIR "/src/Hua.DDNS"
RUN dotnet build "Hua.DDNS.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "Hua.DDNS.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Hua.DDNS.dll"]

41
Hua.DDNS/Hua.DDNS.csproj Normal file
View File

@@ -0,0 +1,41 @@
<Project Sdk="Microsoft.NET.Sdk.Worker">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>dotnet-Hua.DDNS-C4DADDFF-6D5B-4BD5-AB11-02F07B517CAC</UserSecretsId>
<DockerDefaultTargetOS>Windows</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AlibabaCloud.SDK.Alidns20150109" Version="3.0.0" />
<PackageReference Include="Hua.DotNet.Code" Version="0.0.8" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.15.1" />
<PackageReference Include="Dapper" Version="2.0.123" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="6.0.0" />
<PackageReference Include="Newtonsoft.Json.Bson" Version="1.0.2" />
<PackageReference Include="Npgsql" Version="6.0.3" />
<PackageReference Include="QRCoder" Version="1.4.1" />
<PackageReference Include="Quartz.Extensions.DependencyInjection" Version="3.4.0" />
<PackageReference Include="Quartz.Extensions.Hosting" Version="3.4.0" />
<PackageReference Include="Serilog" Version="2.10.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="4.2.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.3.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="TencentCloudSDK.Dnspod" Version="3.0.623" />
</ItemGroup>
<ItemGroup>
<None Update="InstallServiceByNssm.bat">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="nssm.exe">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,32 @@
cd /d %~dp0
echo OFF
net.exe session 1>NUL 2>NUL && (
goto as_admin
) || (
goto not_admin
)
:not_admin
echo <20><><EFBFBD>Թ<EFBFBD><D4B9><EFBFBD>Ա<EFBFBD><D4B1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>е<EFBFBD>ǰ<EFBFBD>ű<EFBFBD><C5B1><EFBFBD>
goto end
:as_admin
SET basePath=%cd%
SET serviceName=Hua.DDNS
SET displayName="Hua.DDNS Demo"
SET description="Hua.DDNS Demo"
SET servicePath="%basePath%\%serviceName%.exe"
ECHO %servicePath%
net stop %serviceName%
sc delete %serviceName%
ping 1.1.1.1 -n 1 -w 10 > nul
nssm install %serviceName% %servicePath%
nssm set %serviceName% AppDirectory %basePath%
nssm set %serviceName% AppStopMethodSkip 6
nssm set %serviceName% AppStopMethodConsole 1000
nssm set %serviceName% AppThrottle 5000
ping 1.1.1.1 -n 1 -w 10 > nul
nssm start %serviceName%
Echo <20><>װ<EFBFBD>ɹ<EFBFBD>
goto end
:end
Pause

134
Hua.DDNS/Jobs/AppJob.cs Normal file
View File

@@ -0,0 +1,134 @@
using Hua.DDNS.Common;
using Hua.DDNS.Common.Config;
using Hua.DDNS.Common.Config.Options;
using Hua.DDNS.Common.Http;
using Hua.DDNS.Start;
using Quartz;
using System.Net;
using AlibabaCloud.OpenApiClient.Models;
using AlibabaCloud.SDK.Alidns20150109.Models;
using Hua.DotNet.Code.Extension;
using TencentCloud.Common;
using TencentCloud.Common.Profile;
using TencentCloud.Dnspod.V20210323;
using TencentCloud.Dnspod.V20210323.Models;
using Tea;
using Tea.Utils;
namespace Hua.DDNS.Jobs
{
[DisallowConcurrentExecution]
public class AppJob : IJob, IDisposable
{
private readonly ILogger<AppJob> _logger;
private readonly SettingProvider _settingProvider;
private readonly DomainOption _domainOption;
private readonly IHttpHelper _httpHelper;
public string CurrentIpv4Address;
public AppJob(ILogger<AppJob> logger,SettingProvider settingProvider, IHttpHelper httpHelper)
{
_logger = logger;
_settingProvider = settingProvider;
_httpHelper = httpHelper;
_domainOption = _settingProvider.App.Domain;
}
public async Task Execute(IJobExecutionContext context)
{
_logger.LogInformation("开始任务执行");
try
{
var oldIp = (await Dns.GetHostEntryAsync($"{_domainOption.subDomainArray.First()}.{_domainOption.domain}")).AddressList.First();
CurrentIpv4Address = await _httpHelper.GetCurrentPublicIpv4();
if (CurrentIpv4Address!=oldIp.ToString())
{
await UpdateDns();
}
}
catch (Exception e)
{
_logger.LogError(e,e.Message);
}
finally
{
_logger.LogInformation("任务执行完成");
}
}
private async Task UpdateDns()
{
//更新Ip记录
switch (_domainOption.Platform)
{
case "Tencent":
var _dnspodClient = new DnspodClient(
// 实例化一个认证对象入参需要传入腾讯云账户secretIdsecretKey,此处还需注意密钥对的保密
// 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
new Credential { SecretId = _domainOption.Id, SecretKey = _domainOption.Key },
"",
// 实例化一个client选项可选的没有特殊需求可以跳过
new ClientProfile()
{
// 实例化一个http选项可选的没有特殊需求可以跳过
HttpProfile = new HttpProfile { Endpoint = ("dnspod.tencentcloudapi.com") }
});
//获取域名解析记录
var describeRecordList = await _dnspodClient.DescribeRecordList(new DescribeRecordListRequest() { Domain = _domainOption.domain });
var record = describeRecordList.RecordList.FirstOrDefault(m =>
m.Value == CurrentIpv4Address && _domainOption.subDomainArray.Any(n => m.Name == n));
if (record!=null && record.Value == CurrentIpv4Address) return;//如果记录已经变更,不调用更新接口
await _dnspodClient.ModifyRecordBatch(new ModifyRecordBatchRequest()
{
RecordIdList =
describeRecordList.RecordList
.Where(m => m.Value != CurrentIpv4Address && _domainOption.subDomainArray.Any(n => m.Name == n))
.Select(m => m.RecordId)
.ToArray(),
Change = "value",
ChangeTo = CurrentIpv4Address
});
break;
case "Ali":
var aliClient = new AlibabaCloud.SDK.Alidns20150109.Client(new Config()
{
// 您的 AccessKey ID
AccessKeyId = _domainOption.Id,
// 您的 AccessKey Secret
AccessKeySecret = _domainOption.Key,
Endpoint = "alidns.cn-beijing.aliyuncs.com",
});
var aliDescribeRecordList = (await aliClient.DescribeDomainRecordsAsync(new DescribeDomainRecordsRequest()
{
DomainName = _domainOption.domain
})).Body.DomainRecords.Record;
foreach (var aliDomainRecord in aliDescribeRecordList
.Where(m => m.Value != CurrentIpv4Address && _domainOption.subDomainArray.Any(n => m.Value == n)))
{
await aliClient.UpdateDomainRecordAsync(new UpdateDomainRecordRequest()
{
RecordId = aliDomainRecord.RecordId,
Value = CurrentIpv4Address,
});
}
break;
}
}
public void Dispose()
{
_logger.LogInformation("AppJob已销毁");
}
}
}

View File

@@ -0,0 +1,10 @@
namespace Hua.DDNS.Jobs
{
/// <summary>
/// Job上下文
/// </summary>
public class AppJobContext
{
}
}

View File

@@ -0,0 +1,14 @@
{
"profiles": {
"Hua.DDNS": {
"commandName": "Project",
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true
},
"Docker": {
"commandName": "Docker"
}
}
}

11
Hua.DDNS/Start/Cache.cs Normal file
View File

@@ -0,0 +1,11 @@
namespace Hua.DDNS.Start
{
public class Cache
{
/// <summary>
/// Tocken
/// </summary>
public static string Tocken { get; set; } = null;
}
}

94
Hua.DDNS/Start/Program.cs Normal file
View File

@@ -0,0 +1,94 @@
using Hua.DDNS.Common;
using Hua.DDNS.Common.Config;
using Hua.DDNS.Common.Http;
using Hua.DDNS.Jobs;
using Quartz;
using Serilog;
namespace Hua.DDNS.Start
{
public static class Program
{
public static async Task Main(string[] args)
{
await CreateHostBuilder(args).Build().RunAsync();
}
private static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.UseSerilog()
.ConfigureServices((hostContext, services) =>
{
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.File(
Path.Combine("Log\\log-.log"),
rollingInterval: RollingInterval.Day)
.CreateLogger();
ConfigDi(hostContext, services);
ConfigQuartz(hostContext, services);
});
public static IServiceProvider ConfigDi(HostBuilderContext hostContext, IServiceCollection services)
{
services.AddSingleton<SettingProvider>();
//services.AddSingleton<SyncECMFileProvider>();
services.AddSingleton<Url>();
services.AddSingleton<SqlHelper>();
services.AddTransient<IHttpHelper, HttpHelper>();
return services.BuildServiceProvider();
}
private static void ConfigQuartz(HostBuilderContext hostContext, IServiceCollection services)
{
// if you are using persistent job store, you might want to alter some options
services.Configure<QuartzOptions>(options =>
{
options.Scheduling.IgnoreDuplicates = true; // default: false
options.Scheduling.OverWriteExistingData = true; // default: true
});
// base configuration for DI
services.AddQuartz(q =>
{
// handy when part of cluster or you want to otherwise identify ltiple schedulers
q.SchedulerId = "Hua.DDNS.Demo";
// this is default configuration if you don't alter it
q.UseMicrosoftDependencyInjectionJobFactory();
// these are the defaults
q.UseSimpleTypeLoader();
q.UseInMemoryStore();
q.UseDefaultThreadPool(tp => { tp.MaxConcurrency = 10; });
//configure jobs with code
var appJobKey = new JobKey("AppJob", "AppJobGroup");
q.AddJob<AppJob>(j => j
.StoreDurably()
.WithIdentity(appJobKey)
.WithDescription("AppJob")
);
q.AddTrigger(t => t
.WithIdentity("AppJob Trigger")
.ForJob(appJobKey)
.WithCronSchedule(hostContext.Configuration.GetSection("App:AppJob:Corn").Value)
.WithDescription("AppJob trigger")
.StartNow()
);
});
// Quartz.Extensions.Hosting hosting
services.AddQuartzHostedService(options =>
{
// when shutting down we want jobs to complete gracefully
options.WaitForJobsToComplete = true;
// when we need to init another IHostedServices first
options.StartDelay = TimeSpan.FromSeconds(10);
});
}
}
}

View File

@@ -0,0 +1,32 @@
{
"ConnectionStrings": {
"pgConnection": "Host=127.0.0.1;Port=5432;Database=Worker;Username=Worker;Password=123456;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"App": {
"AppJob": {
"Corn": "* * * * * ?" //https://cron.qqe2.com/
},
"Domain": {
"Platform": "Ali",
// Access Id/Secret Id
"Id": "Id",
// Access Key/Secret Key
"Key": "Key",
// 主域名
"domain": "demo.cn",
// 子域名前缀
"subDomainArray": [ "bjb", "git"],
// 记录类型
"type": "A",
//间隔时间 秒
"time": "30"
}
}
}

32
Hua.DDNS/appsettings.json Normal file
View File

@@ -0,0 +1,32 @@
{
"ConnectionStrings": {
"pgConnection": "Host=127.0.0.1;Port=5432;Database=Worker;Username=Worker;Password=123456;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"App": {
"AppJob": {
"Corn": "* * * * * ?" //https://cron.qqe2.com/
},
"Domain": {
"Platform": "Ali",
// Access Id/Secret Id
"Id": "Id",
// Access Key/Secret Key
"Key": "Key",
// 主域名
"domain": "demo.cn",
// 子域名前缀
"subDomainArray": [ "bjb", "git" ],
// 记录类型
"type": "A",
//间隔时间 秒
"time": "30"
}
}
}

BIN
Hua.DDNS/nssm.exe Normal file

Binary file not shown.