-
-
Notifications
You must be signed in to change notification settings - Fork 218
/
Copy pathProgram.cs
299 lines (261 loc) · 10.3 KB
/
Program.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ShellProgressBar;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Downloader.Sample;
[ExcludeFromCodeCoverage]
public partial class Program
{
private const string DownloadListFile = "download.json";
private static List<DownloadItem> DownloadList;
private static ProgressBar ConsoleProgress;
private static ConcurrentDictionary<string, ChildProgressBar> ChildConsoleProgresses;
private static ProgressBarOptions ChildOption;
private static ProgressBarOptions ProcessBarOption;
private static IDownloadService CurrentDownloadService;
private static DownloadConfiguration CurrentDownloadConfiguration;
private static CancellationTokenSource CancelAllTokenSource;
private static ILogger Logger;
private static async Task Main()
{
try
{
DummyHttpServer.HttpServer.Run(3333);
await Task.Delay(1000);
Console.Clear();
await Initial();
new Task(KeyboardHandler).Start();
await DownloadAll(DownloadList, CancelAllTokenSource.Token).ConfigureAwait(false);
}
catch (Exception e)
{
Console.Clear();
await Console.Error.WriteLineAsync(e.Message);
Debugger.Break();
}
finally
{
await DummyHttpServer.HttpServer.Stop();
}
await Console.Out.WriteLineAsync("END");
}
private static async Task Initial()
{
CancelAllTokenSource = new CancellationTokenSource();
ChildConsoleProgresses = new ConcurrentDictionary<string, ChildProgressBar>();
DownloadList = await GetDownloadItems();
ProcessBarOption = new ProgressBarOptions {
ForegroundColor = ConsoleColor.Green,
ForegroundColorDone = ConsoleColor.DarkGreen,
BackgroundColor = ConsoleColor.DarkGray,
BackgroundCharacter = '\u2593',
ProgressBarOnBottom = false,
ProgressCharacter = '#'
};
ChildOption = new ProgressBarOptions {
ForegroundColor = ConsoleColor.Yellow,
BackgroundColor = ConsoleColor.DarkGray,
ProgressCharacter = '-',
ProgressBarOnBottom = true
};
}
private static void KeyboardHandler()
{
Console.CancelKeyPress += (_, _) => CancelAll();
while (true)
{
while (Console.KeyAvailable)
{
ConsoleKeyInfo cki = Console.ReadKey(true);
switch (cki.Key)
{
case ConsoleKey.C:
if (cki.Modifiers == ConsoleModifiers.Control)
{
CancelAll();
return;
}
break;
case ConsoleKey.P:
CurrentDownloadService?.Pause();
Console.Beep();
break;
case ConsoleKey.R:
CurrentDownloadService?.Resume();
break;
case ConsoleKey.Escape:
CurrentDownloadService?.CancelAsync();
break;
case ConsoleKey.UpArrow:
if (CurrentDownloadConfiguration != null)
CurrentDownloadConfiguration.MaximumBytesPerSecond *= 2;
break;
case ConsoleKey.DownArrow:
if (CurrentDownloadConfiguration != null)
CurrentDownloadConfiguration.MaximumBytesPerSecond /= 2;
break;
}
}
}
}
private static void CancelAll()
{
CancelAllTokenSource.Cancel();
CurrentDownloadService?.CancelAsync();
}
private static async Task<List<DownloadItem>> GetDownloadItems()
{
if (File.Exists(DownloadListFile))
{
string text = await File.ReadAllTextAsync(DownloadListFile);
return JsonConvert.DeserializeObject<List<DownloadItem>>(text);
}
return [];
}
private static async Task SaveDownloadItems(IList<DownloadItem> items)
{
string text = JsonConvert.SerializeObject(items);
await File.WriteAllTextAsync(DownloadListFile, text);
}
private static async Task DownloadAll(IEnumerable<DownloadItem> downloadList, CancellationToken cancelToken)
{
foreach (DownloadItem downloadItem in downloadList)
{
if (cancelToken.IsCancellationRequested)
return;
// begin download from url
await DownloadFile(downloadItem).ConfigureAwait(false);
await Task.Yield();
}
}
private static async Task DownloadFile(DownloadItem downloadItem)
{
if (downloadItem.ValidateData)
Logger = FileLogger.Factory(downloadItem.FolderPath, Path.GetFileName(downloadItem.FileName));
CurrentDownloadConfiguration = GetDownloadConfiguration();
CurrentDownloadService = CreateDownloadService(CurrentDownloadConfiguration, Logger);
if (string.IsNullOrWhiteSpace(downloadItem.FileName))
{
await CurrentDownloadService
.DownloadFileTaskAsync(downloadItem.Url, new DirectoryInfo(downloadItem.FolderPath))
.ConfigureAwait(false);
}
else
{
await CurrentDownloadService.DownloadFileTaskAsync(downloadItem.Url, downloadItem.FileName)
.ConfigureAwait(false);
}
if (downloadItem.ValidateData)
{
var isValid =
await ValidateDataAsync(CurrentDownloadService.Package.FileName,
CurrentDownloadService.Package.TotalFileSize).ConfigureAwait(false);
if (!isValid)
{
var message = "Downloaded data is invalid: " + CurrentDownloadService.Package.FileName;
Logger?.LogCritical(message);
throw new InvalidDataException(message);
}
}
}
private static async Task<bool> ValidateDataAsync(string filename, long size)
{
await using var stream = File.OpenRead(filename);
for (var i = 0L; i < size; i++)
{
var next = stream.ReadByte();
if (next != i % 256)
{
Logger?.LogWarning(
$"Sample.Program.ValidateDataAsync(): Data at index [{i}] of `{filename}` is `{next}`, expectation is `{i % 256}`");
return false;
}
}
return true;
}
private static async Task WriteKeyboardGuidLines()
{
Console.Clear();
Console.Beep();
Console.CursorVisible = false;
await Console.Out.WriteLineAsync("Press Esc to Stop current file download");
await Console.Out.WriteLineAsync("Press P to Pause and R to Resume downloading");
await Console.Out.WriteLineAsync("Press Up Arrow to Increase download speed 2X");
await Console.Out.WriteLineAsync("Press Down Arrow to Decrease download speed 2X \n");
await Console.Out.FlushAsync();
await Task.Yield();
}
private static DownloadService CreateDownloadService(DownloadConfiguration config, ILogger logger)
{
var downloadService = new DownloadService(config);
// Provide `FileName` and `TotalBytesToReceive` at the start of each downloads
downloadService.DownloadStarted += OnDownloadStarted;
// Provide any information about chunk downloads,
// like progress percentage per chunk, speed,
// total received bytes and received bytes array to live-streaming.
downloadService.ChunkDownloadProgressChanged += OnChunkDownloadProgressChanged;
// Provide any information about download progress,
// like progress percentage of sum of chunks, total speed,
// average speed, total received bytes and received bytes array
// to live-streaming.
downloadService.DownloadProgressChanged += OnDownloadProgressChanged;
// Download completed event that can include occurred errors or
// cancelled or download completed successfully.
downloadService.DownloadFileCompleted += OnDownloadFileCompleted;
downloadService.AddLogger(logger);
return downloadService;
}
private static async void OnDownloadStarted(object sender, DownloadStartedEventArgs e)
{
await WriteKeyboardGuidLines();
var progressMsg = $"Downloading {Path.GetFileName(e.FileName)} ";
await Console.Out.WriteLineAsync(progressMsg);
ConsoleProgress = new ProgressBar(10000, progressMsg, ProcessBarOption);
}
private static void OnDownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
ConsoleProgress?.Tick(10000);
var lastState = " DONE";
if (e.Cancelled)
{
lastState = " CANCELED";
}
else if (e.Error != null)
{
lastState = " ERROR";
Console.Error.WriteLine(e.Error);
Debugger.Break();
}
if (ConsoleProgress != null)
ConsoleProgress.Message += lastState;
foreach (var child in ChildConsoleProgresses.Values)
child.Dispose();
ChildConsoleProgresses.Clear();
ConsoleProgress?.Dispose();
}
private static void OnChunkDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
ChildProgressBar progress = ChildConsoleProgresses.GetOrAdd(e.ProgressId,
id => ConsoleProgress?.Spawn(10000, $"chunk {id}", ChildOption));
progress.Tick((int)(e.ProgressPercentage * 100));
// var activeChunksCount = e.ActiveChunks; // Running chunks count
}
private static void OnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
var isPaused = false;
if (sender is DownloadService ds)
{
isPaused = ds.IsPaused;
}
var title = e.UpdateTitleInfo(isPaused);
ConsoleProgress.Tick((int)(e.ProgressPercentage * 100), title);
}
}