-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathHttpUploadService.cs
More file actions
321 lines (270 loc) · 10.8 KB
/
Copy pathHttpUploadService.cs
File metadata and controls
321 lines (270 loc) · 10.8 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
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
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using GeneralUpdate.Tools.Configuration;
namespace GeneralUpdate.Tools.Services;
/// <summary>
/// HTTP-based upload service using multipart/form-data.
/// Supports Basic, Bearer Token, and API Key authentication.
/// </summary>
public class HttpUploadService : IHttpUploadService
{
private readonly HttpClient _http;
public HttpUploadService()
{
_http = new HttpClient();
}
/// <summary>
/// Constructor with custom HttpClient (for testing or shared instances).
/// </summary>
public HttpUploadService(HttpClient http)
{
_http = http;
}
/// <inheritdoc />
public async Task<UploadResult> UploadAsync(
string filePath,
UploadConfig config,
IProgress<UploadProgressEventArgs>? progress = null,
CancellationToken ct = default)
{
if (!File.Exists(filePath))
return UploadResult.Fail($"File not found: {filePath}");
// Validate URL early
if (!TryBuildUrl(config, out var fullUrl, out var urlError))
return UploadResult.Fail(urlError ?? "Invalid upload URL.");
var fileInfo = new FileInfo(filePath);
Report(progress, 0, fileInfo.Length, UploadPhase.Connecting, "Connecting...");
var lastError = string.Empty;
var maxRetries = Math.Max(0, config.RetryCount);
for (var attempt = 0; attempt <= maxRetries; attempt++)
{
ct.ThrowIfCancellationRequested();
try
{
using var cts = new CancellationTokenSource(
TimeSpan.FromSeconds(config.TimeoutSeconds));
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(ct, cts.Token);
using var content = new MultipartFormDataContent();
var fileStream = File.OpenRead(filePath);
var streamContent = new ProgressStreamContent(fileStream, (uploaded, total) =>
{
Report(progress, uploaded, total, UploadPhase.Uploading,
$"Uploading... {uploaded / 1024}/{total / 1024} KB");
});
streamContent.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
content.Add(streamContent, "file", Path.GetFileName(filePath));
using var request = new HttpRequestMessage(HttpMethod.Post, fullUrl)
{
Content = content,
};
// Apply authentication
ApplyAuth(request, config);
Report(progress, 0, fileInfo.Length, UploadPhase.Authenticating,
$"Authenticating ({config.Auth.Scheme})...");
using var response = await _http.SendAsync(
request,
HttpCompletionOption.ResponseContentRead,
linkedCts.Token);
var responseBody = await response.Content.ReadAsStringAsync(linkedCts.Token);
Report(progress, fileInfo.Length, fileInfo.Length, UploadPhase.Verifying,
$"Server responded: {(int)response.StatusCode}");
if (response.IsSuccessStatusCode)
{
Report(progress, fileInfo.Length, fileInfo.Length, UploadPhase.Completed,
"Upload complete.");
return UploadResult.Ok((int)response.StatusCode, responseBody, fullUrl);
}
// Non-retryable status codes
if ((int)response.StatusCode is >= 400 and < 500 && response.StatusCode !=
System.Net.HttpStatusCode.RequestTimeout &&
response.StatusCode != System.Net.HttpStatusCode.TooManyRequests)
{
return UploadResult.Fail(
$"Server rejected upload: {(int)response.StatusCode} - {responseBody}",
(int)response.StatusCode);
}
lastError = $"HTTP {(int)response.StatusCode}: {responseBody}";
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
lastError = "Upload timed out";
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
lastError = ex.Message;
}
// Wait before retry (exponential backoff: 1s, 2s, 4s...)
if (attempt < maxRetries)
{
var delay = TimeSpan.FromSeconds(Math.Pow(2, attempt));
Report(progress, 0, fileInfo.Length, UploadPhase.Connecting,
$"Retry {attempt + 1}/{maxRetries} in {delay.TotalSeconds:F0}s...");
await Task.Delay(delay, ct);
}
}
Report(progress, 0, fileInfo.Length, UploadPhase.Failed, lastError);
return UploadResult.Fail(lastError);
}
/// <inheritdoc />
public async Task<bool> ValidateConnectionAsync(UploadConfig config, CancellationToken ct = default)
{
try
{
if (!TryBuildUrl(config, out var fullUrl, out _))
return false;
// Issue a GET to validate connectivity
using var request = new HttpRequestMessage(HttpMethod.Get, fullUrl);
ApplyAuth(request, config);
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15));
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(ct, cts.Token);
using var response = await _http.SendAsync(request, linkedCts.Token);
// Only treat 2xx/3xx as success; 401 means auth failed, 404 means wrong endpoint
return response.IsSuccessStatusCode;
}
catch
{
return false;
}
}
// ── Helpers ──────────────────────────────────────────────
/// <summary>Build and validate the upload URL. Returns false if the URL is invalid.</summary>
private static bool TryBuildUrl(UploadConfig config, out string fullUrl, out string? error)
{
fullUrl = string.Empty;
error = null;
if (string.IsNullOrWhiteSpace(config.ServerUrl))
{
error = "Server URL is not configured.";
return false;
}
if (!Uri.TryCreate(config.ServerUrl, UriKind.Absolute, out _))
{
error = $"Server URL is not a valid absolute URI: {config.ServerUrl}";
return false;
}
var server = config.ServerUrl.TrimEnd('/');
var endpoint = config.UploadEndpoint.StartsWith('/')
? config.UploadEndpoint
: "/" + config.UploadEndpoint;
fullUrl = server + endpoint;
return true;
}
private static void ApplyAuth(HttpRequestMessage request, UploadConfig config)
{
var plain = AuthCredentialEncryptor.Decrypt(config.Auth);
switch (plain.Scheme)
{
case AuthScheme.Basic:
if (!string.IsNullOrEmpty(plain.Username) && !string.IsNullOrEmpty(plain.Password))
{
var credential = Convert.ToBase64String(
Encoding.UTF8.GetBytes($"{plain.Username}:{plain.Password}"));
request.Headers.Authorization =
new AuthenticationHeaderValue("Basic", credential);
}
break;
case AuthScheme.BearerToken:
if (!string.IsNullOrEmpty(plain.Token))
{
request.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", plain.Token);
}
break;
case AuthScheme.ApiKey:
if (!string.IsNullOrEmpty(plain.ApiKey) && !string.IsNullOrEmpty(plain.ApiKeyHeaderName))
{
request.Headers.TryAddWithoutValidation(plain.ApiKeyHeaderName, plain.ApiKey);
}
break;
case AuthScheme.None:
default:
break;
}
}
private static void Report(
IProgress<UploadProgressEventArgs>? progress,
long uploaded,
long total,
UploadPhase phase,
string message)
{
progress?.Report(new UploadProgressEventArgs
{
BytesUploaded = uploaded,
TotalBytes = total,
Phase = phase,
Message = message,
});
}
public void Dispose()
{
_http.Dispose();
}
}
/// <summary>
/// Wraps a <see cref="Stream"/> to report read progress.
/// </summary>
internal class ProgressStreamContent : StreamContent
{
private readonly Stream _stream;
private readonly Action<long, long> _onProgress;
public ProgressStreamContent(Stream stream, Action<long, long> onProgress)
: base(new ProgressStream(stream, onProgress))
{
_stream = stream;
_onProgress = onProgress;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_stream.Dispose();
}
base.Dispose(disposing);
}
private class ProgressStream : Stream
{
private readonly Stream _inner;
private readonly Action<long, long> _onProgress;
private long _read;
public ProgressStream(Stream inner, Action<long, long> onProgress)
{
_inner = inner;
_onProgress = onProgress;
}
public override bool CanRead => _inner.CanRead;
public override bool CanSeek => _inner.CanSeek;
public override bool CanWrite => _inner.CanWrite;
public override long Length => _inner.Length;
public override long Position
{
get => _inner.Position;
set => _inner.Position = value;
}
public override void Flush() => _inner.Flush();
public override long Seek(long offset, SeekOrigin origin) => _inner.Seek(offset, origin);
public override void SetLength(long value) => _inner.SetLength(value);
public override void Write(byte[] buffer, int offset, int count) => _inner.Write(buffer, offset, count);
public override int Read(byte[] buffer, int offset, int count)
{
var n = _inner.Read(buffer, offset, count);
if (n > 0)
{
_read += n;
_onProgress(_read, _inner.Length);
}
return n;
}
protected override void Dispose(bool disposing)
{
if (disposing) _inner.Dispose();
base.Dispose(disposing);
}
}
}