/
MultiThreadedDownloader.cs
767 lines (690 loc) · 30.1 KB
/
MultiThreadedDownloader.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using static MultiThreadedDownloaderLib.FileDownloader;
using static MultiThreadedDownloaderLib.StreamAppender;
namespace MultiThreadedDownloaderLib
{
public sealed class MultiThreadedDownloader : IDisposable
{
public string Url { get; set; } = null;
/// <summary>
/// Warning! The file name will be automatically changed after downloading if a file with that name already exists!
/// Therefore, you need to double-check this value after the download is complete.
/// </summary>
public string OutputFileName { get; set; } = null;
public string TempDirectory { get; set; } = null;
public string MergingDirectory { get; set; } = null;
public bool KeepDownloadedFileInTempOrMergingDirectory { get; set; } = false;
/// <summary>
/// Enables or disables some temporary files location logic.
/// Disable it, if you want to set directories manually.
/// </summary>
public bool LogicEnabled { get; set; } = false;
public int UpdateIntervalMilliseconds { get; set; } = 100;
public int ChunksMergingUpdateIntervalMilliseconds { get; set; } = 100;
public long DownloadedBytes { get; private set; } = 0L;
public long ContentLength { get; private set; } = -1L;
public long RangeFrom { get; private set; } = 0L;
public long RangeTo { get; private set; } = -1L;
/// <summary>
/// WARNING!!! Experimental feature!
/// Must be used very softly and carefully!
/// </summary>
public bool UseRamForTempFiles { get; set; } = false;
public int ThreadCount { get; set; } = 2;
public NameValueCollection Headers { get { return _headers; } set { SetHeaders(value); } }
public int LastErrorCode { get; private set; }
public string LastErrorMessage { get; private set; }
public bool IsTempDirectoryAvailable => !string.IsNullOrEmpty(TempDirectory) &&
!string.IsNullOrWhiteSpace(TempDirectory) && Directory.Exists(TempDirectory);
public bool IsMergingDirectoryAvailable => !string.IsNullOrEmpty(MergingDirectory) &&
!string.IsNullOrWhiteSpace(MergingDirectory) && Directory.Exists(MergingDirectory);
public bool HasErrorMessage => !string.IsNullOrEmpty(LastErrorMessage) &&
!string.IsNullOrWhiteSpace(LastErrorMessage) &&
!string.Equals(LastErrorMessage, "OK", StringComparison.OrdinalIgnoreCase);
private NameValueCollection _headers = new NameValueCollection();
private bool _isCanceled = false;
private CancellationTokenSource _cancellationTokenSource;
public const int MEGABYTE = 1048576; //1024 * 1024;
public const int DOWNLOAD_ERROR_MERGING_CHUNKS = -200;
public const int DOWNLOAD_ERROR_CREATE_FILE = -201;
public const int DOWNLOAD_ERROR_NO_URL_SPECIFIED = -202;
public const int DOWNLOAD_ERROR_NO_FILE_NAME_SPECIFIED = -203;
public const int DOWNLOAD_ERROR_TEMPORARY_DIR_NOT_EXISTS = -204;
public const int DOWNLOAD_ERROR_MERGING_DIR_NOT_EXISTS = -205;
public const int DOWNLOAD_ERROR_CUSTOM = -206;
public delegate void ConnectingDelegate(object sender, string url);
public delegate void ConnectedDelegate(object sender, string url, long contentLength, ref int errorCode, ref string errorMessage);
public delegate void DownloadStartedDelegate(object sender, long contentLenth);
public delegate void DownloadProgressDelegate(object sender, long bytesTransferred);
public delegate void DownloadFinishedDelegate(object sender, long bytesTransferred, int errorCode, string fileName);
public delegate void ChunkMergingStartedDelegate(object sender, int chunkCount);
public delegate void ChunkMergingProgressDelegate(object sender, int chunkId,
int chunkCount, long chunkPosition, long chunkSize);
public delegate void ChunkMergingFinishedDelegate(object sender, int errorCode);
public ConnectingDelegate Connecting;
public ConnectedDelegate Connected;
public DownloadStartedDelegate DownloadStarted;
public DownloadProgressDelegate DownloadProgress;
public DownloadFinishedDelegate DownloadFinished;
public ChunkMergingStartedDelegate ChunkMergingStarted;
public ChunkMergingProgressDelegate ChunkMergingProgress;
public ChunkMergingFinishedDelegate ChunkMergingFinished;
public void Dispose()
{
if (_cancellationTokenSource != null)
{
Stop();
_cancellationTokenSource.Dispose();
_cancellationTokenSource = null;
}
}
public static string GetNumberedFileName(string filePath)
{
if (File.Exists(filePath))
{
string dirPath = Path.GetDirectoryName(filePath);
string fileName = Path.GetFileNameWithoutExtension(filePath);
string ext = Path.GetExtension(filePath);
string part1 = !string.IsNullOrEmpty(dirPath) ? Path.Combine(dirPath, fileName) : fileName;
bool isExtensionPresent = !string.IsNullOrEmpty(ext) && !string.IsNullOrWhiteSpace(ext);
int i = 2;
string newFileName;
do
{
newFileName = isExtensionPresent ? $"{part1}_{i++}{ext}" : $"{part1}_{i++}";
} while (File.Exists(newFileName));
return newFileName;
}
return filePath;
}
private IEnumerable<Tuple<long, long>> SplitContentToChunks(long contentLength, int chunkCount)
{
long contentLengthRanged = RangeTo >= 0L ? RangeTo - RangeFrom : contentLength - RangeFrom;
if (chunkCount <= 1 || contentLengthRanged <= MEGABYTE)
{
long byteTo = RangeTo >= 0L ? RangeTo : contentLengthRanged + RangeFrom - 1;
yield return new Tuple<long, long>(RangeFrom, byteTo);
yield break;
}
long chunkSize = contentLengthRanged / chunkCount;
long startPos = RangeFrom;
for (int i = 0; i < chunkCount; ++i)
{
bool lastChunk = i == chunkCount - 1;
long endPos;
if (lastChunk)
{
endPos = RangeTo >= 0 ? RangeTo : contentLength - 1;
}
else
{
endPos = startPos + chunkSize;
}
yield return new Tuple<long, long>(startPos, endPos);
if (!lastChunk)
{
startPos += chunkSize + 1;
}
}
}
/// <summary>
/// Execute the downloading task.
/// </summary>
/// <param name="bufferSize">
/// Buffer size per thread.
/// Warning! Do not use numbers smaller than 8192!
/// Leave zero for auto select.</param>
public async Task<int> Download(int bufferSize = 0)
{
_isCanceled = false;
DownloadedBytes = 0L;
if (string.IsNullOrEmpty(Url) || string.IsNullOrWhiteSpace(Url))
{
LastErrorCode = DOWNLOAD_ERROR_NO_URL_SPECIFIED;
return DOWNLOAD_ERROR_NO_URL_SPECIFIED;
}
if (string.IsNullOrEmpty(OutputFileName) || string.IsNullOrWhiteSpace(OutputFileName))
{
LastErrorCode = DOWNLOAD_ERROR_NO_FILE_NAME_SPECIFIED;
return DOWNLOAD_ERROR_NO_FILE_NAME_SPECIFIED;
}
if (!UseRamForTempFiles && IsTempDirectoryAvailable && !Directory.Exists(TempDirectory))
{
LastErrorCode = DOWNLOAD_ERROR_TEMPORARY_DIR_NOT_EXISTS;
return DOWNLOAD_ERROR_TEMPORARY_DIR_NOT_EXISTS;
}
if (IsMergingDirectoryAvailable && !Directory.Exists(MergingDirectory))
{
LastErrorCode = DOWNLOAD_ERROR_MERGING_DIR_NOT_EXISTS;
return DOWNLOAD_ERROR_MERGING_DIR_NOT_EXISTS;
}
string dirName = Path.GetDirectoryName(OutputFileName);
if (string.IsNullOrEmpty(dirName) || string.IsNullOrWhiteSpace(dirName))
{
string selfDirPath = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
OutputFileName = Path.Combine(selfDirPath, OutputFileName);
}
if (!IsTempDirectoryAvailable)
{
TempDirectory = Path.GetDirectoryName(OutputFileName);
}
if (!IsMergingDirectoryAvailable)
{
MergingDirectory = TempDirectory;
}
List<char> driveLetters = GetUsedDriveLetters();
if (driveLetters.Count > 0 && !driveLetters.Contains('\\') && !IsDrivesReady(driveLetters))
{
return DOWNLOAD_ERROR_DRIVE_NOT_READY;
}
Connecting?.Invoke(this, Url);
LastErrorCode = GetUrlContentLength(Url, Headers, out long fullContentLength, out string errorText);
ContentLength = fullContentLength == -1L ? -1L :
(RangeTo >= 0L ? RangeTo - RangeFrom + 1 : fullContentLength - RangeFrom);
if (ContentLength < -1L) { ContentLength = -1L; }
int errorCode = LastErrorCode;
Connected?.Invoke(this, Url, ContentLength, ref errorCode, ref errorText);
if (LastErrorCode != errorCode)
{
LastErrorCode = errorCode;
}
if (LastErrorCode != 200 && LastErrorCode != 206)
{
LastErrorMessage = errorText;
return LastErrorCode;
}
if (ContentLength == 0L)
{
LastErrorCode = DOWNLOAD_ERROR_ZERO_LENGTH_CONTENT;
return DOWNLOAD_ERROR_ZERO_LENGTH_CONTENT;
}
_cancellationTokenSource = new CancellationTokenSource();
DownloadStarted?.Invoke(this, ContentLength);
Dictionary<int, DownloadProgressItem> threadProgressDict = new Dictionary<int, DownloadProgressItem>();
Progress<DownloadProgressItem> progress = new Progress<DownloadProgressItem>();
progress.ProgressChanged += (s, progressItem) =>
{
lock (threadProgressDict)
{
threadProgressDict[progressItem.TaskId] = progressItem;
DownloadedBytes = threadProgressDict.Values.Select(it => it.ProcessedBytes).Sum();
}
DownloadProgress?.Invoke(this, DownloadedBytes);
};
if (ThreadCount <= 0)
{
ThreadCount = 2;
}
if (bufferSize == 0)
{
bufferSize = 8192;
}
int chunkCount = ContentLength > MEGABYTE ? ThreadCount : 1;
var chunkRanges = SplitContentToChunks(fullContentLength, chunkCount);
var tasks = chunkRanges.Select((range, taskId) => Task.Run(() =>
{
long chunkFirstByte = range.Item1;
long chunkLastByte = range.Item2;
IProgress<DownloadProgressItem> reporter = progress;
string chunkFileName = GetTempChunkFilePath(chunkCount, taskId);
if (!string.IsNullOrEmpty(chunkFileName))
{
chunkFileName = GetNumberedFileName(chunkFileName);
}
FileDownloader downloader = new FileDownloader() { Url = Url, Headers = Headers };
downloader.SetRange(chunkFirstByte, chunkLastByte);
Stream streamChunk = null;
int lastTime = Environment.TickCount;
downloader.WorkProgress += (object sender, long transferred, long contentLen) =>
{
int currentTime = Environment.TickCount;
if (currentTime - lastTime >= UpdateIntervalMilliseconds)
{
FileChunk fileChunk = new FileChunk(chunkFileName, (streamChunk is MemoryStream) ? streamChunk : null);
DownloadProgressItem progressItem = new DownloadProgressItem(fileChunk, taskId, transferred, chunkLastByte);
reporter.Report(progressItem);
lastTime = currentTime;
}
};
downloader.WorkFinished += (object sender, long transferred, long contentLen, int errCode) =>
{
FileChunk fileChunk = new FileChunk(chunkFileName, (streamChunk is MemoryStream) ? streamChunk : null);
DownloadProgressItem progressItem = new DownloadProgressItem(fileChunk, taskId, transferred, chunkLastByte);
reporter.Report(progressItem);
};
try
{
if (UseRamForTempFiles)
{
streamChunk = new MemoryStream();
}
else
{
streamChunk = File.OpenWrite(chunkFileName);
}
LastErrorCode = downloader.Download(streamChunk, bufferSize, _cancellationTokenSource);
if (!UseRamForTempFiles)
{
streamChunk.Close();
streamChunk = null;
}
}
catch (Exception ex)
{
streamChunk?.Close();
LastErrorCode = ex.HResult;
LastErrorMessage = ex.Message;
}
if (LastErrorCode != 200 && LastErrorCode != 206)
{
if (_isCanceled)
{
LastErrorCode = DOWNLOAD_ERROR_CANCELED_BY_USER;
LastErrorMessage = null;
}
else
{
LastErrorMessage = downloader.LastErrorMessage;
}
}
}
));
try
{
await Task.WhenAll(tasks);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
LastErrorMessage = ex.Message;
if (UseRamForTempFiles)
{
var values = threadProgressDict.Values;
foreach (DownloadProgressItem item in values)
{
if (item.FileChunk != null)
{
item.FileChunk.Dispose();
//TODO: Fix possible memory leaking
GC.Collect();
}
}
}
int ret = (ex is OperationCanceledException) ? DOWNLOAD_ERROR_CANCELED_BY_USER : ex.HResult;
return ret;
}
if (LastErrorCode != 200 && LastErrorCode != 206)
{
if (UseRamForTempFiles)
{
for (int i = 0; i < threadProgressDict.Count; ++i)
{
if (threadProgressDict[i].FileChunk != null)
{
threadProgressDict[i].FileChunk.Dispose();
//TODO: Fix possible memory leaking
GC.Collect();
}
}
}
return LastErrorCode;
}
else if (_isCanceled)
{
if (UseRamForTempFiles)
{
for (int i = 0; i < threadProgressDict.Count; ++i)
{
if (threadProgressDict[i].FileChunk != null)
{
threadProgressDict[i].FileChunk.Dispose();
//TODO: Fix possible memory leaking
GC.Collect();
}
}
}
LastErrorCode = DOWNLOAD_ERROR_CANCELED_BY_USER;
LastErrorMessage = null;
return LastErrorCode;
}
List<FileChunk> chunks = new List<FileChunk>();
for (int i = 0; i < threadProgressDict.Count; ++i)
{
chunks.Add(threadProgressDict[i].FileChunk);
}
if (UseRamForTempFiles || chunks.Count > 1)
{
ChunkMergingStarted?.Invoke(this, chunks.Count);
LastErrorCode = await MergeChunks(chunks);
ChunkMergingFinished?.Invoke(this, LastErrorCode);
}
else if (!UseRamForTempFiles && chunks.Count == 1)
{
string chunkFilePath = chunks[0].FilePath;
if (!string.IsNullOrEmpty(chunkFilePath) && !string.IsNullOrWhiteSpace(chunkFilePath) &&
File.Exists(chunkFilePath))
{
string destinationDirPath = Path.GetDirectoryName(
KeepDownloadedFileInTempOrMergingDirectory ? chunkFilePath : OutputFileName);
string destinationFileName = Path.GetFileName(OutputFileName);
string destinationFilePath = Path.Combine(destinationDirPath, destinationFileName);
OutputFileName = GetNumberedFileName(destinationFilePath);
File.Move(chunkFilePath, OutputFileName);
LastErrorCode = 200;
}
else
{
LastErrorCode = 400;
}
}
else
{
LastErrorCode = 400;
}
DownloadFinished?.Invoke(this, DownloadedBytes, LastErrorCode, OutputFileName);
return LastErrorCode;
}
public void Stop()
{
if (_cancellationTokenSource != null && !_cancellationTokenSource.IsCancellationRequested)
{
_cancellationTokenSource.Cancel();
_isCanceled = true;
}
}
private async Task<int> MergeChunks(IEnumerable<FileChunk> chunks)
{
Progress<ChunkMergingProgressItem> progressMerging = new Progress<ChunkMergingProgressItem>();
progressMerging.ProgressChanged += (s, p) =>
{
ChunkMergingProgress?.Invoke(this, p.ChunkId, p.TotalChunkCount, p.ChunkPosition, p.ChunkLength);
};
int res = await Task.Run(() =>
{
string tmpFileName = GetNumberedFileName(GetTempMergingFilePath());
Stream outputStream = null;
try
{
outputStream = File.OpenWrite(tmpFileName);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
outputStream?.Close();
if (UseRamForTempFiles)
{
foreach (FileChunk fc in chunks)
{
fc.Dispose();
}
//TODO: Fix possible memory leaking
GC.Collect();
}
return DOWNLOAD_ERROR_CREATE_FILE;
}
IProgress<ChunkMergingProgressItem> reporter = progressMerging;
try
{
int i = 0;
int chunkCount = chunks.Count();
foreach (FileChunk fileChunk in chunks)
{
string chunkFilePath = fileChunk.FilePath;
bool fileExists = false;
Stream tmpStream = fileChunk.Stream;
bool isMemoryStream = tmpStream != null;
if (!isMemoryStream)
{
fileExists = !string.IsNullOrEmpty(chunkFilePath) && !string.IsNullOrWhiteSpace(chunkFilePath) &&
File.Exists(chunkFilePath);
if (!fileExists)
{
return DOWNLOAD_ERROR_MERGING_CHUNKS;
}
tmpStream = File.OpenRead(chunkFilePath);
}
else
{
tmpStream.Position = 0L;
}
void func(long sourcePosition, long sourceLength, long destinationPosition, long destinationLength)
{
ChunkMergingProgressItem item = new ChunkMergingProgressItem(
i, chunkCount, sourcePosition, sourceLength);
reporter.Report(item);
};
bool appended = Append(tmpStream, outputStream,
func, func, func,
_cancellationTokenSource.Token, ChunksMergingUpdateIntervalMilliseconds);
fileChunk.Dispose();
if (isMemoryStream)
{
//TODO: Fix possible memory leaking
GC.Collect();
}
else
{
tmpStream.Close();
}
if (!appended)
{
outputStream.Close();
if (UseRamForTempFiles)
{
foreach (FileChunk fc in chunks)
{
fc.Dispose();
}
//TODO: Fix possible memory leaking
GC.Collect();
}
return _cancellationTokenSource.IsCancellationRequested ?
DOWNLOAD_ERROR_CANCELED_BY_USER : DOWNLOAD_ERROR_MERGING_CHUNKS;
}
if (!isMemoryStream && fileExists)
{
File.Delete(chunkFilePath);
}
if (_isCanceled)
{
break;
}
++i;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
outputStream.Close();
if (UseRamForTempFiles)
{
foreach (FileChunk fc in chunks)
{
fc.Dispose();
}
//TODO: Fix possible memory leaking
GC.Collect();
}
return DOWNLOAD_ERROR_MERGING_CHUNKS;
}
outputStream.Close();
if (_isCanceled)
{
if (UseRamForTempFiles)
{
foreach (FileChunk fc in chunks)
{
fc.Dispose();
}
//TODO: Fix possible memory leaking
GC.Collect();
}
return DOWNLOAD_ERROR_CANCELED_BY_USER;
}
if (KeepDownloadedFileInTempOrMergingDirectory &&
IsMergingDirectoryAvailable)
{
string fn = Path.GetFileName(OutputFileName);
OutputFileName = Path.Combine(MergingDirectory, fn);
}
OutputFileName = GetNumberedFileName(OutputFileName);
File.Move(tmpFileName, OutputFileName);
return 200;
});
return res;
}
private string GetTempChunkFilePath(int chunkCount, int taskId)
{
if (!UseRamForTempFiles)
{
string chunkFileName;
if (chunkCount > 1)
{
string fn = Path.GetFileName(OutputFileName);
string suffix = $".chunk_{taskId}.tmp";
chunkFileName = IsTempDirectoryAvailable ?
Path.Combine(TempDirectory, fn + suffix) : fn + suffix;
}
else
{
if (LogicEnabled)
{
chunkFileName = OutputFileName + ".tmp";
}
else if (IsTempDirectoryAvailable)
{
string fn = Path.GetFileName(OutputFileName);
string suffix = $".chunk_{taskId}.tmp";
chunkFileName = Path.Combine(TempDirectory, fn + suffix);
}
else
{
chunkFileName = OutputFileName + ".tmp";
}
}
return chunkFileName;
}
return null;
}
private string GetTempMergingFilePath()
{
string fn = Path.GetFileName(OutputFileName);
string tempFilePath;
if (IsMergingDirectoryAvailable)
{
tempFilePath = Path.Combine(MergingDirectory, $"{fn}.tmp");
}
else if (IsTempDirectoryAvailable)
{
tempFilePath = Path.Combine(TempDirectory, $"{fn}.tmp");
}
else
{
tempFilePath = $"{OutputFileName}.tmp";
}
return tempFilePath;
}
private void SetHeaders(NameValueCollection headers)
{
RangeFrom = 0L;
RangeTo = -1L;
Headers.Clear();
if (headers != null)
{
for (int i = 0; i < headers.Count; ++i)
{
string headerName = headers.GetKey(i);
if (!string.IsNullOrEmpty(headerName) && !string.IsNullOrWhiteSpace(headerName))
{
string headerValue = headers.Get(i);
if (!string.IsNullOrEmpty(headerValue) && headerName.ToLower().Equals("range"))
{
HttpRequestSender.ParseRangeHeaderValue(headerValue, out long rangeFrom, out long rangeTo);
SetRange(rangeFrom, rangeTo);
continue;
}
Headers.Add(headerName, headerValue);
}
}
}
}
public bool SetRange(long rangeFrom, long rangeTo)
{
if (IsRangeValid(rangeFrom, rangeTo))
{
RangeFrom = rangeFrom;
RangeTo = rangeTo;
return true;
}
return false;
}
public static void SetMaximumConnectionsLimit(int limit)
{
ServicePointManager.DefaultConnectionLimit = limit;
}
public List<char> GetUsedDriveLetters()
{
List<char> driveLetters = new List<char>();
if (!string.IsNullOrEmpty(OutputFileName) && !string.IsNullOrWhiteSpace(OutputFileName))
{
char c = OutputFileName.Length > 2 && OutputFileName[1] == ':' && OutputFileName[2] == '\\' ?
OutputFileName[0] : Environment.GetCommandLineArgs()[0][0];
driveLetters.Add(char.ToUpper(c));
}
if (IsTempDirectoryAvailable && !driveLetters.Contains(char.ToUpper(TempDirectory[0])))
{
driveLetters.Add(char.ToUpper(TempDirectory[0]));
}
if (IsMergingDirectoryAvailable && !driveLetters.Contains(char.ToUpper(MergingDirectory[0])))
{
driveLetters.Add(char.ToUpper(MergingDirectory[0]));
}
return driveLetters;
}
public bool IsDrivesReady(IEnumerable<char> driveLetters)
{
foreach (char driveLetter in driveLetters)
{
if (driveLetter == '\\')
{
return false;
}
DriveInfo driveInfo = new DriveInfo(driveLetter.ToString());
if (!driveInfo.IsReady)
{
return false;
}
}
return true;
}
public static string ErrorCodeToString(int errorCode)
{
switch (errorCode)
{
case DOWNLOAD_ERROR_NO_URL_SPECIFIED:
return "Не указана ссылка!";
case DOWNLOAD_ERROR_NO_FILE_NAME_SPECIFIED:
return "Не указано имя файла!";
case DOWNLOAD_ERROR_MERGING_CHUNKS:
return "Ошибка объединения чанков!";
case DOWNLOAD_ERROR_CREATE_FILE:
return "Ошибка создания файла!";
case DOWNLOAD_ERROR_TEMPORARY_DIR_NOT_EXISTS:
return "Не найдена папка для временных файлов!";
case DOWNLOAD_ERROR_MERGING_DIR_NOT_EXISTS:
return "Не найдена папка для объединения чанков!";
case DOWNLOAD_ERROR_CUSTOM:
return null;
default:
return FileDownloader.ErrorCodeToString(errorCode);
}
}
}
}