forked from revenz/FileFlows
/
FileDownloader.cs
289 lines (250 loc) · 11.5 KB
/
FileDownloader.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
using System.Text;
using System.Text.Json;
using FileFlows.Plugin;
using HttpMethod = System.Net.Http.HttpMethod;
namespace FileFlows.ServerShared.FileServices;
/// <summary>
/// Helper class for downloading and validating files from a URL.
/// </summary>
public class FileDownloader
{
private static readonly HttpClient _client;
/// <summary>
/// The logger used for log messages
/// </summary>
private ILogger logger;
/// <summary>
/// The URL where the file will be uploaded.
/// </summary>
private readonly string serverUrl;
/// <summary>
/// The UID of the executor for the authentication
/// </summary>
private readonly Guid executorUid;
/// <summary>
/// Represents a delegate that defines the signature for handling progress events.
/// </summary>
/// <param name="percent">The progress percentage.</param>
/// <param name="eta">The estimate time to completion.</param>
/// <param name="speed">The speed of the download.</param>
public delegate void OnProgressDelegate(int percent, TimeSpan? eta, string speed);
/// <summary>
/// Event that is triggered to notify subscribers about the progress, using the <see cref="OnProgressDelegate"/> delegate.
/// </summary>
public event OnProgressDelegate OnProgress;
/// <summary>
/// Constructs an instance of the file downloader
/// </summary>
/// <param name="logger">the logger to use in the file downloader</param>
/// <param name="serverUrl">The URL where the file will be uploaded.</param>
/// <param name="executorUid">The UID of the executor for the authentication</param>
public FileDownloader(ILogger logger, string serverUrl,Guid executorUid)
{
this.logger = logger;
this.serverUrl = serverUrl;
this.executorUid = executorUid;
}
/// <summary>
/// Static constructor
/// </summary>
static FileDownloader()
{
HttpClientHandler handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
_client = new HttpClient(handler);
_client.Timeout = Timeout.InfiniteTimeSpan;
}
/// <summary>
/// Downloads a file from the specified URL and saves it to the destination path.
/// Validates the downloaded file using a SHA256 hash provided by the server.
/// </summary>
/// <param name="uid">The UID of the file to download</param>
/// <param name="destinationPath">The path where the downloaded file will be saved.</param>
/// <returns>A tuple indicating success (True) or failure (False) and an error message if applicable.</returns>
public async Task<Result<bool>> DownloadFile(string path, string destinationPath)
{
try
{
logger.ILog("Downloading file: " + path);
logger.ILog("Destination file: " + destinationPath);
string url = serverUrl;
if (url.EndsWith("/") == false)
url += "/";
url += "api/file-server";
DateTime start = DateTime.UtcNow;
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url + "/download");
request.Headers.Add("x-executor", executorUid.ToString());
string json = JsonSerializer.Serialize(new { path });
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
// Send the request and read the response content as a stream
HttpResponseMessage response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
if (response.IsSuccessStatusCode == false)
{
string error = (await response.Content.ReadAsStringAsync()).EmptyAsNull() ?? "Failed to remotely download the file";
logger.ELog("Download Failed: " + error);
return Result<bool>.Fail(error);
}
using Stream contentStream = await response.Content.ReadAsStreamAsync();
long fileSize = 0;
if (response.Content.Headers.ContentLength.HasValue)
{
fileSize = response.Content.Headers.ContentLength.Value;
logger?.ILog($"Content-Length: {fileSize} bytes");
}
else
{
logger?.ILog("Content-Length header is not present in the response.");
}
using FileStream fileStream = FileOpenHelper.OpenWrite_NoReadLock(destinationPath, FileMode.Create);
int bufferSize;
if (fileSize < 10 * 1024 * 1024) // If file size is less than 10 MB
bufferSize = 4 * 1024;
else if (fileSize < 100 * 1024 * 1024) // If file size is less than 100 MB
bufferSize = 64 * 1024;
else
bufferSize = 1 * 1024 * 1024;
byte[] buffer = new byte[bufferSize];
int bytesRead;
long bytesReadTotal = 0;
int percent = 0;
// Calculate ETA variables
DateTime startTime = DateTime.UtcNow;
TimeSpan elapsed;
TimeSpan eta;
double speed = 0; // Download speed in bytes per second
OnProgress?.Invoke(0, null, null);
while ((bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await fileStream.WriteAsync(buffer, 0, bytesRead);
bytesReadTotal += bytesRead;
// Calculate elapsed time and download speed
elapsed = DateTime.UtcNow - startTime;
double bytesPerSecond = bytesReadTotal / elapsed.TotalSeconds;
speed = bytesPerSecond;
// Calculate ETA
double remainingSeconds = (fileSize - bytesReadTotal) / bytesPerSecond;
eta = TimeSpan.FromSeconds(remainingSeconds);
// Convert speed to a human-readable format (e.g., KBps or MBps)
string speedString = FormatSpeed(speed);
float percentage = bytesReadTotal * 100f / fileSize;
int iPercent = Math.Clamp((int)Math.Round(percentage), 0, 100);
if (iPercent != percent)
{
percent = iPercent;
logger.ILog($"Download Percentage: {percent} %");
OnProgress?.Invoke(iPercent, eta, speedString);
}
}
OnProgress?.Invoke(100, null, null);
var timeTaken = DateTime.UtcNow.Subtract(start);
var size = new FileInfo(destinationPath).Length;
logger.ILog(
$"Time taken to download file: {timeTaken}, bytes read: {bytesReadTotal}, expected size: {fileSize}, size on disk: {size})");
// using FileStream fileStream = File.OpenWrite(destinationPath);
// await response.Content.CopyToAsync(fileStream);
if(fileSize < 1)
fileSize = await GetFileSize(url, path);
// long downloadedBytes = 0;
//
// await using (var outputStream = new FileStream(destinationPath, FileMode.Create))
// while (downloadedBytes < fileSize)
// {
// var request = new HttpRequestMessage(HttpMethod.Get, serverUrl);
// request.Headers.Range = new System.Net.Http.Headers.RangeHeaderValue(downloadedBytes, fileSize - 1);
//
// using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
// await using var responseStream = await response.Content.ReadAsStreamAsync();
//
// byte[] buffer = new byte[BufferSize];
// int bytesRead;
// while ((bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
// {
// await outputStream.WriteAsync(buffer, 0, bytesRead);
// downloadedBytes += bytesRead;
// }
// }
if (Math.Abs(size - fileSize) > bufferSize)
{
return Result<bool>.Fail("File failed to download completely!");
}
return true;
// var hash = await FileHasher.Hash(destinationPath);
//
// if (await ValidateFileHash(url, hash) == false)
// // if(downloadedHash != fileHash)
// {
// return (false, "File validation failed!");
// }
//
//
// return (true, string.Empty);
}
catch (Exception ex)
{
return Result<bool>.Fail($"An error occurred: {ex.Message}");
}
}
/// <summary>
/// Validates the downloaded file hash against the hash provided by the server for the specified URL.
/// </summary>
/// <param name="url">The URL of the file for which the hash needs to be validated.</param>
/// <param name="hash">The hash of the downloaded file.</param>
/// <returns>True if the file hash is validated successfully; otherwise, False.</returns>
private async Task<bool> ValidateFileHash(string url, string hash)
{
try
{
var serverHash = await _client.GetStringAsync(url + "/hash");;
bool result = string.Equals(hash, serverHash, StringComparison.InvariantCulture);
if (result == false)
{
logger?.ELog("File-Hash mismatch");
}
return result;
}
catch
{
return false;
}
}
/// <summary>
/// Gets the file size from the server for the specified URL.
/// </summary>
/// <param name="url">The URL of the file for which the size needs to be fetched.</param>
/// <param name="path">The path of the file</param>
/// <returns>The size of the file in bytes.</returns>
private async Task<long> GetFileSize(string url, string path)
{
try
{
// Create the GET request with required headers
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url + "/size");
request.Headers.Add("x-executor", executorUid.ToString());
string json = JsonSerializer.Serialize(new { path });
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
// Send the request and retrieve the response content as a string
HttpResponseMessage response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
string str = await response.Content.ReadAsStringAsync();
long.TryParse(str, out long result);
return result;
}
catch (Exception ex)
{
return 0;
}
}
/// <summary>
/// Formats the download speed in bytes per second into a human-readable string.
/// </summary>
/// <param name="bytesPerSecond">The download speed in bytes per second.</param>
/// <returns>A human-readable representation of the download speed.</returns>
private static string FormatSpeed(double bytesPerSecond)
{
if (bytesPerSecond >= 1024 * 1024)
return $"{(bytesPerSecond / (1024 * 1024)):F2} MBps";
if (bytesPerSecond >= 1024)
return $"{(bytesPerSecond / 1024):F2} KBps";
return $"{bytesPerSecond:F2} Bps";
}
}