Repository navigation
Expand file tree
/
Copy pathFileDownloader.cs
More file actions
82 lines (69 loc) · 2.71 KB
/
Copy pathFileDownloader.cs
File metadata and controls
82 lines (69 loc) · 2.71 KB
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
using System;
using System.Net;
using System.Threading.Tasks;
using Squirrel.SimpleSplat;
namespace Squirrel
{
public interface IFileDownloader
{
Task DownloadFile(string url, string targetFile, Action<int> progress);
Task<byte[]> DownloadUrl(string url);
}
public class FileDownloader : IFileDownloader, IEnableLogger
{
private readonly WebClient _providedClient;
public FileDownloader(WebClient providedClient = null)
{
_providedClient = providedClient;
}
public async Task DownloadFile(string url, string targetFile, Action<int> progress)
{
using (var wc = _providedClient ?? Utility.CreateWebClient()) {
var failedUrl = default(string);
var lastSignalled = DateTime.MinValue;
wc.DownloadProgressChanged += (sender, args) => {
var now = DateTime.Now;
if (now - lastSignalled > TimeSpan.FromMilliseconds(500)) {
lastSignalled = now;
progress(args.ProgressPercentage);
}
};
retry:
try {
this.Log().Info("Downloading file: " + (failedUrl ?? url));
await this.WarnIfThrows(
async () => {
await wc.DownloadFileTaskAsync(failedUrl ?? url, targetFile);
progress(100);
},
"Failed downloading URL: " + (failedUrl ?? url));
} catch (Exception) {
// NB: Some super brain-dead services are case-sensitive yet
// corrupt case on upload. I can't even.
if (failedUrl != null) throw;
failedUrl = url.ToLower();
progress(0);
goto retry;
}
}
}
public async Task<byte[]> DownloadUrl(string url)
{
using (var wc = _providedClient ?? Utility.CreateWebClient()) {
var failedUrl = default(string);
retry:
try {
this.Log().Info("Downloading url: " + (failedUrl ?? url));
return await this.WarnIfThrows(() => wc.DownloadDataTaskAsync(failedUrl ?? url),
"Failed to download url: " + (failedUrl ?? url));
} catch (Exception) {
// NB: Some super brain-dead services are case-sensitive yet
// corrupt case on upload. I can't even.
if (failedUrl != null) throw;
failedUrl = url.ToLower();
goto retry;
}
}
}
}
}