-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathRestRequest.cs
More file actions
535 lines (490 loc) · 19.3 KB
/
Copy pathRestRequest.cs
File metadata and controls
535 lines (490 loc) · 19.3 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
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
using BytecodeApi.Data;
using BytecodeApi.Extensions;
using System.Collections;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
namespace BytecodeApi.Rest;
/// <summary>
/// Represents a REST request to be used to further refine, and then send the request.
/// </summary>
public sealed class RestRequest
{
/// <summary>
/// Gets the <see cref="Rest.RestClient" /> from which this <see cref="RestRequest" /> has been initiated.
/// </summary>
public RestClient RestClient { get; }
/// <summary>
/// Gets the <see cref="System.Net.Http.HttpMethod" /> of this <see cref="RestRequest" />.
/// </summary>
public HttpMethod HttpMethod { get; }
/// <summary>
/// Gets the URL of this <see cref="RestRequest" />.
/// </summary>
public string Url { get; private set; }
private HttpContent? HttpContent;
private readonly Dictionary<string, string> Headers;
internal RestRequest(RestClient restClient, HttpMethod method, string url)
{
RestClient = restClient;
HttpMethod = method;
Url = url;
Headers = [];
}
/// <summary>
/// Adds a HTTP header to this REST request.
/// </summary>
/// <param name="name">The name of the header.</param>
/// <param name="value">The value of the header</param>
/// <returns>
/// A reference to this instance after the operation has completed.
/// </returns>
public RestRequest Header(string name, string value)
{
Check.ObjectDisposed<RestClient>(RestClient.Disposed);
Check.ArgumentNull(name);
Check.ArgumentNull(value);
Check.ArgumentNull(RestClient.RequestOptions);
Headers[name] = value;
return this;
}
/// <summary>
/// Adds a query parameter to this REST request.
/// </summary>
/// <param name="name">The name of the query parameter.</param>
/// <param name="value">The value of the query parameter.</param>
/// <returns>
/// A reference to this instance after the operation has completed.
/// </returns>
public RestRequest QueryParameter(string name, object? value)
{
Check.ObjectDisposed<RestClient>(RestClient.Disposed);
Check.ArgumentNull(name);
Check.ArgumentNull(RestClient.RequestOptions);
if (value == null)
{
}
else if (value is IEnumerable enumerable and not string)
{
foreach (object? arrayElement in enumerable)
{
QueryParameter(name, arrayElement);
}
}
else
{
string valueString = value switch
{
string str => str,
Enum enumValue => Convert.ToInt32(enumValue).ToString(),
DateTime dateTimeParameter => dateTimeParameter.ToStringInvariant(RestClient.RequestOptions.QueryParameterDateTimeFormat),
DateOnly dateOnlyParameter => dateOnlyParameter.ToStringInvariant(RestClient.RequestOptions.QueryParameterDateOnlyFormat),
TimeOnly timeOnlyParameter => timeOnlyParameter.ToStringInvariant(RestClient.RequestOptions.QueryParameterTimeOnlyFormat),
_ => value?.ToString() ?? ""
};
Url = AddQueryString(Url, name, valueString);
}
return this;
}
/// <summary>
/// Sets the content of this REST request.
/// </summary>
/// <param name="content">The <see cref="string" /> content to be sent with the request.</param>
/// <param name="contentType">The content type to be sent with the request.</param>
/// <returns>
/// A reference to this instance after the operation has completed.
/// </returns>
public RestRequest StringContent(string content, string contentType)
{
Check.ObjectDisposed<RestClient>(RestClient.Disposed);
Check.ArgumentNull(content);
Check.ArgumentNull(contentType);
HttpContent = new StringContent(content, Encoding.UTF8, contentType);
return this;
}
/// <summary>
/// Sets the content of this REST request to a JSON object.
/// </summary>
/// <typeparam name="T">The type of the JSON object.</typeparam>
/// <param name="content">An <see cref="object" /> to be serialized to JSON and then sent with the request.</param>
/// <returns>
/// A reference to this instance after the operation has completed.
/// </returns>
public RestRequest JsonContent<T>(T? content)
{
return JsonContent(content, null);
}
/// <summary>
/// Sets the content of this REST request to a JSON object.
/// </summary>
/// <typeparam name="T">The type of the JSON object.</typeparam>
/// <param name="content">An <see cref="object" /> to be serialized to JSON and then sent with the request.</param>
/// <param name="serializerOptions">Options to control the conversion behavior.</param>
/// <returns>
/// A reference to this instance after the operation has completed.
/// </returns>
public RestRequest JsonContent<T>(T? content, JsonSerializerOptions? serializerOptions)
{
Check.ObjectDisposed<RestClient>(RestClient.Disposed);
return StringContent(JsonSerializer.Serialize(content, serializerOptions), "application/json");
}
/// <summary>
/// Sets the content of this REST request to an x-www-form-urlencoded body.
/// </summary>
/// <typeparam name="T">The type of the body.</typeparam>
/// <param name="content">An <see cref="object" /> to be serialized into an x-www-form-urlencoded body.</param>
/// <returns>
/// A reference to this instance after the operation has completed.
/// </returns>
public RestRequest FormUrlEncodedContent<T>(T content)
{
Check.ObjectDisposed<RestClient>(RestClient.Disposed);
Check.ArgumentNull(content);
Dictionary<string, string> nameValueCollection = content
.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.ToDictionary(property => property.Name, property => property.GetValue(content)?.ToString() ?? "");
HttpContent = new FormUrlEncodedContent(nameValueCollection);
return this;
}
/// <summary>
/// Sets the content of this REST request to an x-www-form-urlencoded body.
/// </summary>
/// <typeparam name="T">The type of the value of <paramref name="content" />.</typeparam>
/// <param name="content">A <see cref="Dictionary{TKey, TValue}" /> to be serialized into an x-www-form-urlencoded body.</param>
/// <returns>
/// A reference to this instance after the operation has completed.
/// </returns>
public RestRequest FormUrlEncodedContent<T>(Dictionary<string, T?> content)
{
Check.ObjectDisposed<RestClient>(RestClient.Disposed);
Check.ArgumentNull(content);
HttpContent = new FormUrlEncodedContent(content.ToDictionary(property => property.Key, property => property.Value?.ToString() ?? ""));
return this;
}
/// <summary>
/// Includes a file into the multipart request.
/// </summary>
/// <param name="name">The name of the HTTP content.</param>
/// <param name="file">A <see cref="Blob" /> with the file to send.</param>
/// <param name="contentType">The content type of <paramref name="file" />.</param>
/// <returns>
/// A reference to this instance after the operation has completed.
/// </returns>
public RestRequest MultipartFileContent(string name, Blob file, string contentType)
{
Check.ObjectDisposed<RestClient>(RestClient.Disposed);
Check.ArgumentNull(name);
Check.ArgumentNull(file);
Check.ArgumentNull(contentType);
ByteArrayContent fileContent = new(file.Content);
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType);
AddMultipartContent().Add(fileContent, name, file.Name);
return this;
}
/// <summary>
/// Includes a <see cref="string" /> into the multipart request.
/// </summary>
/// <param name="name">The name of the HTTP content.</param>
/// <param name="content">The <see cref="string" /> content to be sent with the multipart request.</param>
/// <param name="contentType">The content type of <paramref name="content" />.</param>
/// <returns>
/// A reference to this instance after the operation has completed.
/// </returns>
public RestRequest MultipartStringContent(string name, string content, string contentType)
{
Check.ObjectDisposed<RestClient>(RestClient.Disposed);
Check.ArgumentNull(name);
Check.ArgumentNull(content);
Check.ArgumentNull(contentType);
AddMultipartContent().Add(new StringContent(content, Encoding.UTF8, contentType), name);
return this;
}
/// <summary>
/// Sends the request without reading the response body.
/// </summary>
public Task Execute()
{
return Execute(default);
}
/// <summary>
/// Sends the request without reading the response body.
/// </summary>
/// <param name="cancellationToken">The cancellation token to cancel the request.</param>
public async Task Execute(CancellationToken cancellationToken)
{
Check.ObjectDisposed<RestClient>(RestClient.Disposed);
using HttpResponseMessage response = await Send(completionOption: HttpCompletionOption.ResponseHeadersRead, cancellationToken: cancellationToken).ConfigureAwait(false);
await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Sends the request and reads the response <see cref="string" />.
/// </summary>
/// <returns>
/// A <see cref="string" />, representing the REST response.
/// </returns>
public Task<string> ReadString()
{
return ReadString(default);
}
/// <summary>
/// Sends the request and reads the response <see cref="string" />.
/// </summary>
/// <param name="cancellationToken">The cancellation token to cancel the request.</param>
/// <returns>
/// A <see cref="string" />, representing the REST response.
/// </returns>
public async Task<string> ReadString(CancellationToken cancellationToken)
{
Check.ObjectDisposed<RestClient>(RestClient.Disposed);
using HttpResponseMessage response = await Send(cancellationToken: cancellationToken).ConfigureAwait(false);
return await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Sends the request and reads the response as a <see cref="byte" />[].
/// </summary>
/// <returns>
/// A <see cref="byte" />[], representing the REST response.
/// </returns>
public Task<byte[]> ReadByteArray()
{
return ReadByteArray(null);
}
/// <summary>
/// Sends the request and reads the response as a <see cref="byte" />[].
/// </summary>
/// <param name="progressCallback">A delegate that is invoked with information about the progress of the download.</param>
/// <returns>
/// A <see cref="byte" />[], representing the REST response.
/// </returns>
public Task<byte[]> ReadByteArray(ProgressCallback? progressCallback)
{
return ReadByteArray(progressCallback, default);
}
/// <summary>
/// Sends the request and reads the response as a <see cref="byte" />[].
/// </summary>
/// <param name="progressCallback">A delegate that is invoked with information about the progress of the download.</param>
/// <param name="cancellationToken">The cancellation token to cancel the download.</param>
/// <returns>
/// A <see cref="byte" />[], representing the REST response.
/// </returns>
public async Task<byte[]> ReadByteArray(ProgressCallback? progressCallback, CancellationToken cancellationToken)
{
Check.ObjectDisposed<RestClient>(RestClient.Disposed);
return (await ReadFile(progressCallback, cancellationToken).ConfigureAwait(false)).Content;
}
/// <summary>
/// Sends the request and reads the response as a <see cref="byte" />[], including the filename from the Content-Disposition.
/// </summary>
/// <returns>
/// A new <see cref="Blob" /> that contains both the filename from the Content-Disposition, and the file content.
/// </returns>
public Task<Blob> ReadFile()
{
return ReadFile(null);
}
/// <summary>
/// Sends the request and reads the response as a <see cref="byte" />[], including the filename from the Content-Disposition.
/// </summary>
/// <param name="progressCallback">A delegate that is invoked with information about the progress of the download.</param>
/// <returns>
/// A new <see cref="Blob" /> that contains both the filename from the Content-Disposition, and the file content.
/// </returns>
public Task<Blob> ReadFile(ProgressCallback? progressCallback)
{
return ReadFile(progressCallback, default);
}
/// <summary>
/// Sends the request and reads the response as a <see cref="byte" />[], including the filename from the Content-Disposition.
/// </summary>
/// <param name="progressCallback">A delegate that is invoked with information about the progress of the download.</param>
/// <param name="cancellationToken">The cancellation token to cancel the download.</param>
/// <returns>
/// A new <see cref="Blob" /> that contains both the filename from the Content-Disposition, and the file content.
/// </returns>
public async Task<Blob> ReadFile(ProgressCallback? progressCallback, CancellationToken cancellationToken)
{
Check.ObjectDisposed<RestClient>(RestClient.Disposed);
if (progressCallback == null)
{
using HttpResponseMessage response = await Send(cancellationToken: cancellationToken).ConfigureAwait(false);
return new(
response.Content.Headers.ContentDisposition?.FileNameStar ?? "",
await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false));
}
else
{
using HttpResponseMessage response = await Send(completionOption: HttpCompletionOption.ResponseHeadersRead, cancellationToken: cancellationToken).ConfigureAwait(false);
using Stream stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
using MemoryStream memoryStream = new(response.Content.Headers.ContentLength is > 0 and < int.MaxValue ? (int)response.Content.Headers.ContentLength.Value : 0);
byte[] buffer = new byte[4096];
int bytesRead;
long totalBytesRead = 0;
DateTime lastCallback = default;
do
{
bytesRead = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
totalBytesRead += bytesRead;
memoryStream.Write(buffer, 0, bytesRead);
if (DateTime.Now - lastCallback > TimeSpan.FromMilliseconds(20))
{
lastCallback = DateTime.Now;
progressCallback(totalBytesRead, Math.Max(totalBytesRead, response.Content.Headers.ContentLength ?? 0));
}
}
while (bytesRead > 0);
progressCallback(totalBytesRead, Math.Max(totalBytesRead, response.Content.Headers.ContentLength ?? 0));
return new(
response.Content.Headers.ContentDisposition?.FileNameStar ?? "",
memoryStream.ToArray());
}
}
/// <summary>
/// Sends the request and reads the response as a JSON object.
/// </summary>
/// <typeparam name="T">The type of the JSON object.</typeparam>
/// <returns>
/// The JSON object, deserialized from the REST response.
/// </returns>
public Task<T> ReadJson<T>()
{
return ReadJson<T>(null);
}
/// <summary>
/// Sends the request and reads the response as a JSON object.
/// </summary>
/// <typeparam name="T">The type of the JSON object.</typeparam>
/// <param name="serializerOptions">Options to control the conversion behavior.</param>
/// <returns>
/// The JSON object, deserialized from the REST response.
/// </returns>
public Task<T> ReadJson<T>(JsonSerializerOptions? serializerOptions)
{
return ReadJson<T>(serializerOptions, default);
}
/// <summary>
/// Sends the request and reads the response as a JSON object.
/// </summary>
/// <typeparam name="T">The type of the JSON object.</typeparam>
/// <param name="serializerOptions">Options to control the conversion behavior.</param>
/// <param name="cancellationToken">The cancellation token to cancel the read operation.</param>
/// <returns>
/// The JSON object, deserialized from the REST response.
/// </returns>
public async Task<T> ReadJson<T>(JsonSerializerOptions? serializerOptions, CancellationToken cancellationToken)
{
Check.ObjectDisposed<RestClient>(RestClient.Disposed);
using HttpResponseMessage response = await Send(cancellationToken: cancellationToken).ConfigureAwait(false);
using Stream stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
return (await JsonSerializer.DeserializeAsync<T>(stream, serializerOptions, cancellationToken).ConfigureAwait(false)) ?? throw new JsonException("Deserialization returned null value.");
}
/// <summary>
/// Sends the request and reads server-sent events.
/// </summary>
/// <param name="eventCallback">A delegate that is invoked with the the server-sent event data.</param>
public async Task ReadEvents(ServerSentEventCallback eventCallback)
{
Check.ObjectDisposed<RestClient>(RestClient.Disposed);
Check.ArgumentNull(eventCallback);
using HttpResponseMessage response = await Send(completionOption: HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
using Stream stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
using StreamReader reader = new(stream);
// https://html.spec.whatwg.org/multipage/server-sent-events.html
string eventType = "message";
string? eventId = null;
StringBuilder data = new();
while (await reader.ReadLineAsync().ConfigureAwait(false) is string line)
{
if (line == "")
{
eventCallback(eventType, data.ToString().Trim(), eventId);
eventType = "message";
data.Clear();
}
else if (line.StartsWith(':'))
{
// Ignore
}
else if (line.Contains(':'))
{
string field;
string value;
if (line.Contains(':'))
{
field = line.SubstringUntil(':');
value = line.SubstringFrom(':');
if (value.StartsWith(' '))
{
value = value[1..];
}
}
else
{
field = line;
value = "";
}
switch (field)
{
case "event":
eventType = value;
break;
case "data":
data.AppendLine(value);
break;
case "id" when !value.Contains('\0'):
eventId = value.ToNullIfEmpty();
break;
}
}
}
}
private async Task<HttpResponseMessage> Send(HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
using HttpRequestMessage request = new(HttpMethod, Url)
{
Content = HttpContent
};
foreach (KeyValuePair<string, string> header in Headers)
{
request.Headers.Add(header.Key, header.Value);
}
HttpResponseMessage response = await RestClient.HttpClient.SendAsync(request, completionOption, cancellationToken).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
return response;
}
else
{
string content = "";
try
{
content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
}
catch
{
}
throw new RestException(response.StatusCode, content);
}
}
private static string AddQueryString(string url, string key, string value)
{
int indexOfFragment = url.IndexOf('#');
string fragment = "";
if (indexOfFragment != -1)
{
fragment = url[indexOfFragment..];
url = url[..indexOfFragment];
}
return $"{url}{(url.Contains('?') ? '&' : '?')}{UrlEncoder.Default.Encode(key)}={UrlEncoder.Default.Encode(value)}{fragment}";
}
private MultipartFormDataContent AddMultipartContent()
{
Check.InvalidOperation(HttpContent is null or MultipartFormDataContent, "Cannot mix multipart content with non-multipart content.");
HttpContent ??= new MultipartFormDataContent();
return (MultipartFormDataContent)HttpContent;
}
}