From 9a0e27bfb41ab3a281340772660ffd8b2a92ea7d Mon Sep 17 00:00:00 2001 From: kaedei Date: Mon, 22 Jun 2020 17:00:06 +0800 Subject: [PATCH] =?UTF-8?q?=E7=BB=A7=E7=BB=AD=E5=A2=9E=E5=8A=A0=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E5=92=8C=E7=BB=93=E6=9E=84;=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E9=A1=B9=E7=9B=AE;=E5=AE=8C=E6=88=90?= =?UTF-8?q?=E7=99=BB=E5=BD=95=E5=92=8C=E5=90=8C=E6=AD=A5=E8=A7=84=E5=88=99?= =?UTF-8?q?=E9=83=A8=E5=88=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../.idea/contentModel.xml | 30 +++- .../.idea.ResourceMonitor/riderModule.iml | 4 + .../ResourceMonitor.Test.csproj | 16 ++ .../RulesContainerTests.cs | 13 ++ ResourceMonitor/ResourceMonitor.sln | 6 + .../Models/DandanplayApi/AutoDownloadRule.cs | 5 + .../Models/DandanplayApi/LoginRequest.cs | 1 + ResourceMonitor/ResourceMonitor/Program.cs | 4 +- .../Properties/launchSettings.json | 2 +- .../ResourceMonitor/ResourceMonitor.csproj | 3 + .../{ => Declaration}/IDandanplayApi.cs | 8 +- .../Services/Declaration/IRulesContainer.cs | 12 ++ .../CheckNewResourcesBackgroundService.cs | 71 +++++++++ .../Services/Implementation/RulesContainer.cs | 67 ++++++++ .../SyncRulesBackgroundService.cs | 148 ++++++++++++++++++ .../Services/SyncRulesHostedService.cs | 54 ------- ResourceMonitor/ResourceMonitor/Startup.cs | 15 +- .../ResourceMonitor/appsettings.json | 11 +- 18 files changed, 403 insertions(+), 67 deletions(-) create mode 100644 ResourceMonitor/ResourceMonitor.Test/ResourceMonitor.Test.csproj create mode 100644 ResourceMonitor/ResourceMonitor.Test/RulesContainerTests.cs rename ResourceMonitor/ResourceMonitor/Services/{ => Declaration}/IDandanplayApi.cs (73%) create mode 100644 ResourceMonitor/ResourceMonitor/Services/Declaration/IRulesContainer.cs create mode 100644 ResourceMonitor/ResourceMonitor/Services/Implementation/CheckNewResourcesBackgroundService.cs create mode 100644 ResourceMonitor/ResourceMonitor/Services/Implementation/RulesContainer.cs create mode 100644 ResourceMonitor/ResourceMonitor/Services/Implementation/SyncRulesBackgroundService.cs delete mode 100644 ResourceMonitor/ResourceMonitor/Services/SyncRulesHostedService.cs diff --git a/ResourceMonitor/.idea/.idea.ResourceMonitor/.idea/contentModel.xml b/ResourceMonitor/.idea/.idea.ResourceMonitor/.idea/contentModel.xml index d8ff852..38b86e3 100644 --- a/ResourceMonitor/.idea/.idea.ResourceMonitor/.idea/contentModel.xml +++ b/ResourceMonitor/.idea/.idea.ResourceMonitor/.idea/contentModel.xml @@ -1,6 +1,12 @@ + + + + + + @@ -12,6 +18,7 @@ + @@ -38,8 +45,15 @@ - - + + + + + + + + + @@ -47,6 +61,18 @@ + + + + + + + + + + + + diff --git a/ResourceMonitor/.idea/.idea.ResourceMonitor/riderModule.iml b/ResourceMonitor/.idea/.idea.ResourceMonitor/riderModule.iml index 1a4e0d9..8b26d4a 100644 --- a/ResourceMonitor/.idea/.idea.ResourceMonitor/riderModule.iml +++ b/ResourceMonitor/.idea/.idea.ResourceMonitor/riderModule.iml @@ -1,6 +1,10 @@ + + + + diff --git a/ResourceMonitor/ResourceMonitor.Test/ResourceMonitor.Test.csproj b/ResourceMonitor/ResourceMonitor.Test/ResourceMonitor.Test.csproj new file mode 100644 index 0000000..c53d3b2 --- /dev/null +++ b/ResourceMonitor/ResourceMonitor.Test/ResourceMonitor.Test.csproj @@ -0,0 +1,16 @@ + + + + netcoreapp3.1 + + false + + + + + + + + + + diff --git a/ResourceMonitor/ResourceMonitor.Test/RulesContainerTests.cs b/ResourceMonitor/ResourceMonitor.Test/RulesContainerTests.cs new file mode 100644 index 0000000..1b11f47 --- /dev/null +++ b/ResourceMonitor/ResourceMonitor.Test/RulesContainerTests.cs @@ -0,0 +1,13 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ResourceMonitor.Test +{ + [TestClass] + public class RulesContainerTests + { + [TestMethod] + public void TestMethod1() + { + } + } +} \ No newline at end of file diff --git a/ResourceMonitor/ResourceMonitor.sln b/ResourceMonitor/ResourceMonitor.sln index f958a1f..eeace3d 100644 --- a/ResourceMonitor/ResourceMonitor.sln +++ b/ResourceMonitor/ResourceMonitor.sln @@ -2,6 +2,8 @@ Microsoft Visual Studio Solution File, Format Version 12.00 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ResourceMonitor", "ResourceMonitor\ResourceMonitor.csproj", "{6803E3E6-61BA-4DB0-BD0C-1A810D493E9C}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ResourceMonitor.Test", "ResourceMonitor.Test\ResourceMonitor.Test.csproj", "{6C8A0394-AA65-4E45-8E11-16067A94EE99}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -12,5 +14,9 @@ Global {6803E3E6-61BA-4DB0-BD0C-1A810D493E9C}.Debug|Any CPU.Build.0 = Debug|Any CPU {6803E3E6-61BA-4DB0-BD0C-1A810D493E9C}.Release|Any CPU.ActiveCfg = Release|Any CPU {6803E3E6-61BA-4DB0-BD0C-1A810D493E9C}.Release|Any CPU.Build.0 = Release|Any CPU + {6C8A0394-AA65-4E45-8E11-16067A94EE99}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6C8A0394-AA65-4E45-8E11-16067A94EE99}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6C8A0394-AA65-4E45-8E11-16067A94EE99}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6C8A0394-AA65-4E45-8E11-16067A94EE99}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection EndGlobal diff --git a/ResourceMonitor/ResourceMonitor/Models/DandanplayApi/AutoDownloadRule.cs b/ResourceMonitor/ResourceMonitor/Models/DandanplayApi/AutoDownloadRule.cs index 562b771..6f1f6c0 100644 --- a/ResourceMonitor/ResourceMonitor/Models/DandanplayApi/AutoDownloadRule.cs +++ b/ResourceMonitor/ResourceMonitor/Models/DandanplayApi/AutoDownloadRule.cs @@ -40,5 +40,10 @@ public class AutoDownloadRule public bool chooseNewerIfDuplicate { get; set; } public int limitFileSize { get; set; } public int version { get; set; } + + public override string ToString() + { + return $"{nameof(id)}: {id}, {nameof(description)}: {description}, {nameof(keyword)}: {keyword}, {nameof(subgroupId)}: {subgroupId}, {nameof(typeId)}: {typeId}, {nameof(maxCount)}: {maxCount}, {nameof(autoStart)}: {autoStart}, {nameof(createdTime)}: {createdTime}, {nameof(subgroupName)}: {subgroupName}, {nameof(typeName)}: {typeName}, {nameof(chooseNewerIfDuplicate)}: {chooseNewerIfDuplicate}, {nameof(limitFileSize)}: {limitFileSize}, {nameof(version)}: {version}"; + } } } \ No newline at end of file diff --git a/ResourceMonitor/ResourceMonitor/Models/DandanplayApi/LoginRequest.cs b/ResourceMonitor/ResourceMonitor/Models/DandanplayApi/LoginRequest.cs index e2670e2..dbe530e 100644 --- a/ResourceMonitor/ResourceMonitor/Models/DandanplayApi/LoginRequest.cs +++ b/ResourceMonitor/ResourceMonitor/Models/DandanplayApi/LoginRequest.cs @@ -7,5 +7,6 @@ public class LoginRequest public string appId { get; set; } public long unixTimestamp { get; set; } public string hash { get; set; } + } } \ No newline at end of file diff --git a/ResourceMonitor/ResourceMonitor/Program.cs b/ResourceMonitor/ResourceMonitor/Program.cs index b8aa18a..043e6cb 100644 --- a/ResourceMonitor/ResourceMonitor/Program.cs +++ b/ResourceMonitor/ResourceMonitor/Program.cs @@ -28,13 +28,13 @@ public static int Main(string[] args) try { - Log.Information("Starting resource monitor"); + Log.Information("启动 ResMonitor..."); CreateHostBuilder(args).Build().Run(); return 0; } catch (Exception ex) { - Log.Fatal(ex, "Host terminated unexpectedly"); + Log.Fatal(ex, "ResMonitor 因意外情况终止"); return 1; } finally diff --git a/ResourceMonitor/ResourceMonitor/Properties/launchSettings.json b/ResourceMonitor/ResourceMonitor/Properties/launchSettings.json index 5d3949d..6a179bf 100644 --- a/ResourceMonitor/ResourceMonitor/Properties/launchSettings.json +++ b/ResourceMonitor/ResourceMonitor/Properties/launchSettings.json @@ -20,7 +20,7 @@ "ResourceMonitor": { "commandName": "Project", "launchBrowser": true, - "launchUrl": "weatherforecast", + "launchUrl": "index.html", "applicationUrl": "https://localhost:5001;http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" diff --git a/ResourceMonitor/ResourceMonitor/ResourceMonitor.csproj b/ResourceMonitor/ResourceMonitor/ResourceMonitor.csproj index 3383e2c..740718b 100644 --- a/ResourceMonitor/ResourceMonitor/ResourceMonitor.csproj +++ b/ResourceMonitor/ResourceMonitor/ResourceMonitor.csproj @@ -2,6 +2,9 @@ netcoreapp3.1 + kaedei + Copyright kaedei 2020 + https://github.com/kaedei/dandanplay-resmonitor diff --git a/ResourceMonitor/ResourceMonitor/Services/IDandanplayApi.cs b/ResourceMonitor/ResourceMonitor/Services/Declaration/IDandanplayApi.cs similarity index 73% rename from ResourceMonitor/ResourceMonitor/Services/IDandanplayApi.cs rename to ResourceMonitor/ResourceMonitor/Services/Declaration/IDandanplayApi.cs index 6b9eee5..ee94cdf 100644 --- a/ResourceMonitor/ResourceMonitor/Services/IDandanplayApi.cs +++ b/ResourceMonitor/ResourceMonitor/Services/Declaration/IDandanplayApi.cs @@ -2,17 +2,17 @@ using Refit; using ResourceMonitor.Models.DandanplayApi; -namespace ResourceMonitor.Services +namespace ResourceMonitor.Services.Declaration { public interface IDandanplayApi { - [Post("api/v2/login")] + [Post("/api/v2/login")] Task Login(LoginRequest request); - [Get("api/v2/login/renew")] + [Get("/api/v2/login/renew")] Task Renew([Header("Authorization")] string authorization); - [Post("api/v2/sync/autodownload")] + [Post("/api/v2/sync/autodownload")] Task SyncAutoDownloadRules(AutoDownloadRuleSyncRequest request, [Header("Authorization")] string authorization); } diff --git a/ResourceMonitor/ResourceMonitor/Services/Declaration/IRulesContainer.cs b/ResourceMonitor/ResourceMonitor/Services/Declaration/IRulesContainer.cs new file mode 100644 index 0000000..85e6eff --- /dev/null +++ b/ResourceMonitor/ResourceMonitor/Services/Declaration/IRulesContainer.cs @@ -0,0 +1,12 @@ +using System.Collections.Immutable; +using ResourceMonitor.Models.DandanplayApi; + +namespace ResourceMonitor.Services.Declaration +{ + public interface IRulesContainer + { + bool IsUpdating { get; set; } + ImmutableList LocalRules { get; } + void SyncWithServerRules(AutoDownloadRuleListResponse serverRules); + } +} \ No newline at end of file diff --git a/ResourceMonitor/ResourceMonitor/Services/Implementation/CheckNewResourcesBackgroundService.cs b/ResourceMonitor/ResourceMonitor/Services/Implementation/CheckNewResourcesBackgroundService.cs new file mode 100644 index 0000000..0203319 --- /dev/null +++ b/ResourceMonitor/ResourceMonitor/Services/Implementation/CheckNewResourcesBackgroundService.cs @@ -0,0 +1,71 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using ResourceMonitor.Models.DandanplayApi; +using ResourceMonitor.Services.Declaration; + +namespace ResourceMonitor.Services.Implementation +{ + /// + /// 检查新的资源 + /// + public class CheckNewResourcesBackgroundService : BackgroundService + { + private readonly IRulesContainer _rulesContainer; + private readonly IConfiguration _configuration; + private readonly ILogger _logger; + + public CheckNewResourcesBackgroundService(IRulesContainer rulesContainer, + IConfiguration configuration, + ILogger logger) + { + _rulesContainer = rulesContainer; + _configuration = configuration; + _logger = logger; + } + + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + _logger.LogInformation($"{nameof(CheckNewResourcesBackgroundService)} 开始在后台运行"); + + while (!stoppingToken.IsCancellationRequested) + { + _logger.LogInformation("开始解析所有规则"); + + //等待规则同步完毕 + while (_rulesContainer.IsUpdating) + { + _logger.LogInformation("自动下载规则正在同步中,等待同步完毕..."); + await Task.Delay(TimeSpan.FromSeconds(15), stoppingToken); + } + + //按顺序解析每个规则 + var ruleList = _rulesContainer.LocalRules; + foreach (var rule in ruleList) + { + await DownloadRule(rule); + } + + //默认每 15 分钟检查一次 + _logger.LogInformation("全部规则解析完毕,等待 15 分钟后再次执行"); + await Task.Delay(TimeSpan.FromMinutes(15), stoppingToken); + } + } + + private async Task DownloadRule(AutoDownloadRule rule) + { + _logger.LogInformation($"正在解析规则 {rule}"); + //获得需要下载的新资源 + + //对比当前已有的下载任务,只下载新的资源 + + //解析磁力链至种子文件 + + //连接下载器,添加远程任务 + } + } +} \ No newline at end of file diff --git a/ResourceMonitor/ResourceMonitor/Services/Implementation/RulesContainer.cs b/ResourceMonitor/ResourceMonitor/Services/Implementation/RulesContainer.cs new file mode 100644 index 0000000..fb320aa --- /dev/null +++ b/ResourceMonitor/ResourceMonitor/Services/Implementation/RulesContainer.cs @@ -0,0 +1,67 @@ +using System.Collections.Concurrent; +using System.Collections.Immutable; +using Microsoft.Extensions.Logging; +using ResourceMonitor.Models.DandanplayApi; +using ResourceMonitor.Services.Declaration; + +namespace ResourceMonitor.Services.Implementation +{ + public class RulesContainer : IRulesContainer + { + private readonly ILogger _logger; + private readonly ConcurrentDictionary _localRules = new ConcurrentDictionary(); + private bool _isUpdating = true; + + public RulesContainer(ILogger logger) + { + _logger = logger; + } + + public bool IsUpdating + { + get => _isUpdating; + set + { + _logger.LogDebug($"RulesContainer.IsUpdating 设置为 {value}"); + _isUpdating = value; + } + } + + public ImmutableList LocalRules => _localRules.Values.ToImmutableList(); + + public void SyncWithServerRules(AutoDownloadRuleListResponse serverRules) + { + _logger.LogInformation("开始同步服务器规则"); + //移除服务器端已经删除的规则 + foreach (var removedRuleId in serverRules.removedRuleIds ?? new string[0]) + { + _localRules.TryRemove(removedRuleId, out var removedRule); + _logger.LogInformation($"删除规则 {removedRule}"); + } + + //添加或更新规则 + foreach (var serverRule in serverRules.rules) + { + //新增规则 + if (!_localRules.ContainsKey(serverRule.id)) + { + _localRules.TryAdd(serverRule.id, serverRule); + _logger.LogInformation($"新增规则 {serverRule}"); + } + else //更新规则 + { + var localRule = _localRules[serverRule.id]; + if (serverRule.version > localRule.version) + { + _localRules[serverRule.id] = serverRule; + _logger.LogInformation($"更新规则-原规则 {localRule}"); + _logger.LogInformation($"更新规则-替换为 {serverRule}"); + } + } + } + + _logger.LogInformation($"规则同步完毕,当前本地规则共有 {_localRules.Count} 个"); + } + + } +} \ No newline at end of file diff --git a/ResourceMonitor/ResourceMonitor/Services/Implementation/SyncRulesBackgroundService.cs b/ResourceMonitor/ResourceMonitor/Services/Implementation/SyncRulesBackgroundService.cs new file mode 100644 index 0000000..b518705 --- /dev/null +++ b/ResourceMonitor/ResourceMonitor/Services/Implementation/SyncRulesBackgroundService.cs @@ -0,0 +1,148 @@ +using System; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Refit; +using ResourceMonitor.Models.DandanplayApi; +using ResourceMonitor.Services.Declaration; + +namespace ResourceMonitor.Services.Implementation +{ + /// + /// 后台同步最新的下载规则 + /// + public class SyncRulesBackgroundService : BackgroundService + { + private int _executionCount = 0; + private readonly IDandanplayApi _dandanplayApi; + private readonly IRulesContainer _rulesContainer; + private readonly IConfiguration _configuration; + private readonly ILogger _logger; + private LoginResponse _lastLoginResponse; //上次登录成功的请求,包含 jwt token 和 token 的过期时间 + + public SyncRulesBackgroundService(IDandanplayApi dandanplayApi, + IRulesContainer rulesContainer, + IConfiguration configuration, + ILogger logger) + { + _dandanplayApi = dandanplayApi; + _rulesContainer = rulesContainer; + _configuration = configuration; + _logger = logger; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + _logger.LogInformation("SyncRulesBackgroundService 开始运行."); + + while (!stoppingToken.IsCancellationRequested) + { + _rulesContainer.IsUpdating = true; + await DoWork(); + _rulesContainer.IsUpdating = false; + //每十分钟运行一次 + _logger.LogInformation("等待 10 分钟后重新执行"); + await Task.Delay(TimeSpan.FromMinutes(10), stoppingToken); + } + + _logger.LogInformation("因触发取消,SyncRulesBackgroundService 终止运行."); + } + + private async Task DoWork() + { + //增加计数器 + var count = Interlocked.Increment(ref _executionCount); + _logger.LogInformation($"SyncRulesBackgroundService 在后台第 {count} 次运行"); + + //之前登录过,先尝试直接刷新 jwt token + if (_lastLoginResponse != null && _lastLoginResponse.tokenExpireTime >= DateTime.UtcNow) + { + try + { + _lastLoginResponse = await _dandanplayApi.Renew("Bearer " + _lastLoginResponse.token); + } + catch (ApiException ex) + { + _logger.LogDebug(ex, "尝试刷新 jwt token 失败"); + _lastLoginResponse = null; + } + } + + //尝试登录,填充登录参数 + if (_lastLoginResponse == null) + { + //读取 appsettings 中的用户名、密码、AppID、AppSecret等信息 + var userName = _configuration["Api:UserName"]; + var password = _configuration["Api:Password"]; + var appId = _configuration["Api:AppId"]; + var appSecret = _configuration["Api:AppSecret"]; + + var loginRequest = new LoginRequest + { + userName = userName, + password = password, + appId = appId, + unixTimestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds() + }; + loginRequest.hash = CalculateLoginRequestHash(loginRequest, appSecret); + try + { + var loginResponse = await _dandanplayApi.Login(loginRequest); + + //先判断是否登录失败了 + if (loginResponse.registerRequired || !loginResponse.success || + string.IsNullOrWhiteSpace(loginResponse.token)) + { + _logger.LogWarning($"登录失败,原因: {loginResponse.errorCode} {loginResponse.errorMessage}"); + return false; + } + + //存储 jwt token + _lastLoginResponse = loginResponse; + } + catch (ApiException ex) + { + _logger.LogDebug(ex, "尝试登录失败"); + return false; + } + + } + + //尝试同步下载规则 + //获取服务器上当前用户最新版本的规则 + var serverRules = await _dandanplayApi.SyncAutoDownloadRules(new AutoDownloadRuleSyncRequest + { + currentRuleIds = _rulesContainer.LocalRules.Select(r => r.id).ToArray() + }, "Bearer " + _lastLoginResponse.token); + //合并本地和服务器端的规则 + _rulesContainer.SyncWithServerRules(serverRules); + + _logger.LogInformation($"SyncRulesBackgroundService 在后台运行完成"); + + return true; + } + + /// + /// 计算登录参数中的 hash 参数 + /// + public string CalculateLoginRequestHash(LoginRequest loginRequest, string appSecret) + { + //算法参考 https://api.acplay.net/swagger/ui/index#!/Auth/Auth_Login + var concat = loginRequest.appId + loginRequest.password + loginRequest.unixTimestamp + + loginRequest.userName + appSecret; + using var md5 = MD5.Create(); + var byteArray = md5.ComputeHash(Encoding.UTF8.GetBytes(concat)); + var sb = new StringBuilder(32); + foreach (var b in byteArray) + { + sb.AppendFormat("{0:X2}", b); + } + return sb.ToString(); + } + } +} \ No newline at end of file diff --git a/ResourceMonitor/ResourceMonitor/Services/SyncRulesHostedService.cs b/ResourceMonitor/ResourceMonitor/Services/SyncRulesHostedService.cs deleted file mode 100644 index 8dd7bd6..0000000 --- a/ResourceMonitor/ResourceMonitor/Services/SyncRulesHostedService.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; - -namespace ResourceMonitor.Services -{ - /// - /// 后台同步最新的下载规则 - /// - public class SyncRulesHostedService : IHostedService, IDisposable - { - private int _executionCount = 0; - private readonly ILogger _logger; - private Timer _timer; - - public SyncRulesHostedService(ILogger logger) - { - _logger = logger; - } - - public Task StartAsync(CancellationToken stoppingToken) - { - _logger.LogInformation("SyncRulesHostedService running."); - - _timer = new Timer(DoWork, null, TimeSpan.Zero, - TimeSpan.FromMinutes(10)); - - return Task.CompletedTask; - } - - private void DoWork(object state) - { - var count = Interlocked.Increment(ref _executionCount); - - _logger.LogInformation("SyncRulesHostedService is working. Count: {Count}", count); - } - - public Task StopAsync(CancellationToken stoppingToken) - { - _logger.LogInformation("SyncRulesHostedService is stopping."); - - _timer?.Change(Timeout.Infinite, 0); - - return Task.CompletedTask; - } - - public void Dispose() - { - _timer?.Dispose(); - } - } -} \ No newline at end of file diff --git a/ResourceMonitor/ResourceMonitor/Startup.cs b/ResourceMonitor/ResourceMonitor/Startup.cs index 7e72a06..043c86e 100644 --- a/ResourceMonitor/ResourceMonitor/Startup.cs +++ b/ResourceMonitor/ResourceMonitor/Startup.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; +using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; @@ -13,6 +14,8 @@ using Microsoft.Extensions.Logging; using Refit; using ResourceMonitor.Services; +using ResourceMonitor.Services.Declaration; +using ResourceMonitor.Services.Implementation; namespace ResourceMonitor { @@ -28,14 +31,20 @@ public Startup(IConfiguration configuration) // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { - services.AddHostedService(); + services.AddHostedService(); + services.AddHostedService(); services.AddRefitClient() .ConfigureHttpClient(c => { - c.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("dandanplay/resmonitor 1.0.0.0")); - c.BaseAddress = new Uri("https://api.acplay.net"); + //User-Agent: dandanplay/resmonitor 1.2.3.4 + c.DefaultRequestHeaders.UserAgent.ParseAdd( + string.Format(Configuration["Api:UserAgent"], + Assembly.GetExecutingAssembly().GetName().Version.ToString(4))); + c.BaseAddress = new Uri(Configuration["Api:ApiBaseUrl"]); }); + + services.AddSingleton(); services.AddControllers(); } diff --git a/ResourceMonitor/ResourceMonitor/appsettings.json b/ResourceMonitor/ResourceMonitor/appsettings.json index d9d9a9b..abaaeea 100644 --- a/ResourceMonitor/ResourceMonitor/appsettings.json +++ b/ResourceMonitor/ResourceMonitor/appsettings.json @@ -6,5 +6,14 @@ "Microsoft.Hosting.Lifetime": "Information" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + "Api": { + "ApiBaseUrl": "https://api.acplay.net", + "ResBaseUrl": "http://res.acplay.net", + "UserName": "test", + "Password": "test", + "AppId": "test", + "AppSecret": "test", + "UserAgent": "dandanplay/resmonitor {0}" + } }