-
Notifications
You must be signed in to change notification settings - Fork 1
/
Worker.cs
181 lines (153 loc) · 6.57 KB
/
Worker.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using System.Net.Http;
namespace qshDownloader
{
public class Worker : BackgroundService
{
private readonly WorkerConfig _config;
private readonly DownloaderConfig _downloaderConfig;
private IMemoryCache _cache;
private readonly ILogger _logger;
private readonly IEnumerable<IDownloader> _downloaders;
private readonly IEnumerable<IFolderEnumerator> _folderEnumerators;
/// <summary>
/// Match
/// Group[1] = relative url to file
/// Group[2] = file name
/// </summary>
private readonly Regex _parseFileUrls;
/// <summary>
/// Match
/// Group[1] = date
/// </summary>
private readonly Regex _parseDates;
private readonly int _retryCount;
private readonly int _retryDelay;
/// <summary>
/// Service Worker.
/// </summary>
/// <param name="logger">logger.</param>
/// <param name="cache">cache.</param>
/// <param name="config">worker config.</param>
/// <param name="downloaderConfig">downloader config.</param>
/// <param name="folderEnumerators">folder enumerators/</param>
/// <param name="downloaders">downloaders.</param>
/// <exception cref="ArgumentNullException">exception.</exception>
/// <exception cref="InvalidOperationException">exception.</exception>
public Worker(
ILogger<Worker> logger,
IMemoryCache cache,
IOptions<WorkerConfig> config,
IOptions<DownloaderConfig> downloaderConfig,
IEnumerable<IFolderEnumerator> folderEnumerators,
IEnumerable<IDownloader> downloaders)
{
_downloaderConfig = downloaderConfig?.Value ?? throw new ArgumentNullException(nameof(downloaderConfig));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
this._config = config?.Value ?? throw new ArgumentNullException(nameof(config));
_parseDates = new Regex(_downloaderConfig.ParseDate);
_parseFileUrls = new Regex(_downloaderConfig.ParseFileUrls);
_retryCount = _downloaderConfig.RetryCount > 0 ? _downloaderConfig.RetryCount : 1;
_retryDelay = _downloaderConfig.RetryDelay > 0 ? _downloaderConfig.RetryDelay : 3000;
_cache = cache ?? throw new ArgumentNullException(nameof(cache));
_folderEnumerators = folderEnumerators ?? throw new ArgumentNullException(nameof(folderEnumerators));
if(folderEnumerators.Count() == 0)
{
throw new InvalidOperationException("No folder enumerators are registered.");
}
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
DateTime startTime = DateTime.Now;
_logger.LogInformation("Downloader started at: {time}", DateTimeOffset.Now);
foreach (var urlServer in _config.ServerUrls)
{
IEnumerable<string> availableDays = await _folderEnumerators.First().Enumerate(new Uri(urlServer), CancellationToken.None);
_logger.LogInformation("Server: {string}", urlServer);
var url = new Uri(urlServer);
List<string> dirs;
if (!_cache.TryGetValue("dirs", out dirs))
{
dirs = Directory.EnumerateDirectories(_config.HistoryPath)
.Where(dir => !dir.EndsWith(".tmp"))
.Select(dir => dir.Substring(dir.Length - 10))
.ToList();
_cache.Set("dirs", dirs);
await Task.WhenAll(dirs.Select(async dir =>
{
var files = await Task.Run(() =>
Directory.EnumerateFiles($"{_config.HistoryPath}\\{dir}"));
_cache.Set(dir, files.ToList());
files.ToList().ForEach(file =>
_cache.Set(file, FileDownloadStatusType.Success));
}));
}
if (availableDays.Count() > 0)
{
IEnumerable<string> newDays = availableDays.Except(dirs);
_logger.LogInformation("\tFounded {int} new folder to downloading", newDays.Count());
foreach (var day in newDays)
{
_logger.LogInformation("\t\tLoading folder {string}", day);
var dayPath = $"{_config.HistoryPath}\\{day}";
var dayPathTmp = $"{_config.HistoryPath}\\{day}.tmp";
if (Directory.Exists(dayPathTmp))
Directory.Delete(dayPathTmp, true);
Directory.CreateDirectory(dayPathTmp);
List<string> files = new List<string>();
using var client = new HttpClient();
var data = await client.GetStringAsync(new Uri(baseUri: url, day), stoppingToken);
var listFiles = _parseFileUrls.Matches(data);
await Task.WhenAll(listFiles.Select(async k =>
{
string fileName = k.Groups[2].Value;
for (int i = 0; i < _retryCount; i++)
try
{
var response = await client.GetAsync(new Uri(url, k.Groups[1].Value), stoppingToken);
response.EnsureSuccessStatusCode();
using var content = response.Content;
using var fileStream = new FileStream($"{dayPathTmp}\\{fileName}", FileMode.CreateNew);
await content.CopyToAsync(fileStream);
files.Add(fileName);
_cache.Set(fileName, FileDownloadStatusType.Success);
break;
}
catch (Exception)
{
if (i == 10)
throw;
await Task.Delay(_retryDelay, stoppingToken);
_logger.LogInformation("\t\tTry N:{int} loading {string}", i, fileName);
}
}));
Directory.Move(dayPathTmp, dayPath);
dirs.Add(day);
_cache.Set(day, files);
_logger.LogInformation("\tLoading success to {string}", dayPath);
}
}
else
{
_logger.LogInformation("\tNew data not found.");
}
}
await Task.Delay(_config.HoursInterval * 24 * 3600000 - (int)(DateTime.Now.TimeOfDay.TotalMilliseconds - startTime.TimeOfDay.TotalMilliseconds), stoppingToken);
}
}
}
}