-
Notifications
You must be signed in to change notification settings - Fork 17
/
RequestHelper.cs
689 lines (546 loc) · 25.5 KB
/
RequestHelper.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
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using LovePdf.Model.Enums;
using LovePdf.Model.Exception;
using LovePdf.Model.TaskParams;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Authentication;
using System.Threading.Tasks;
namespace LovePdf.Core
{
internal class RequestHelper
{
private string _privateKey;
private string _publicKey;
private readonly short _jwtDelay = 5400;
private string Gwt { get; set; }
private string EncryptKey { get; set; }
private static RequestHelper _instance;
private RequestHelper() { }
public static RequestHelper Instance => _instance ?? (_instance = new RequestHelper());
private static Exception ParseRequestErrors(HttpResponseMessage response, string responseContent, Exception exception)
{
if (response.StatusCode == HttpStatusCode.BadRequest) // 400 Bad Request
{
dynamic parsedContent = JObject.Parse(responseContent);
if (parsedContent.error.type == EnumExtensions.GetEnumDescription(LovePdfErrors.ProcessingError))
return new ProcessingException(responseContent, exception);
if (parsedContent.error.type == EnumExtensions.GetEnumDescription(LovePdfErrors.DownloadError))
return new DownloadException(responseContent, exception);
if (parsedContent.error.type == EnumExtensions.GetEnumDescription(LovePdfErrors.UploadError))
return new UploadException(responseContent, exception);
return exception;
}
if (response.StatusCode == HttpStatusCode.Unauthorized) // 401 Unauthorized
return new AuthenticationException(responseContent, exception);
if (response.StatusCode == HttpStatusCode.NotFound) // 404 Not Found
return new NotFoundException(responseContent, exception);
if (response.StatusCode == (HttpStatusCode)429) // 429 Too many Requests
return new TooManyRequestsException(responseContent, exception);
if ((int)response.StatusCode >= 500 && (int)response.StatusCode < 600) // 5xx Server Errors
return new ServerErrorException(responseContent, exception);
return exception;
}
public StartTaskResponse StartTask(string tool)
{
HttpResponseMessage response = null;
var responseContent = string.Empty;
try
{
using (var httpClient = new HttpClient())
{
AddAuthorizationHeader(httpClient);
var link = StringHelpers.Invariant($"{Settings.StartUrl}/{Settings.V1}/start/{tool}");
var requestMessage = new HttpRequestMessage(HttpMethod.Get, link);
response = httpClient.SendAsync(requestMessage).Result;
responseContent = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
return JsonConvert.DeserializeObject<StartTaskResponse>(responseContent);
}
}
catch (Exception e)
{
throw ParseRequestErrors(response, responseContent, e);
}
}
/// <summary>
/// Execute current task
/// </summary>
/// <param name="tool">tool name for current task</param>
/// <param name="parameters">specific parameters for current task</param>
/// <param name="serverUrl">server url</param>
/// <param name="taskId"> current task id</param>
/// <param name="files">file</param>
/// <returns>time to process the task.</returns>
public ExecuteTaskResponse ExecuteTask(Uri serverUrl, string taskId, List<FileModel> files, string tool, BaseParams parameters)
{
HttpResponseMessage response = null;
var responseContent = string.Empty;
try
{
using (var httpClient = new HttpClient())
{
AddAuthorizationHeader(httpClient);
var link = StringHelpers.Invariant($"{serverUrl}{Settings.V1}/process");
var initalValues = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("task", taskId),
new KeyValuePair<string, string>("tool", tool),
new KeyValuePair<string, string>("v", $"net.{Settings.NetVersion}"),
//new KeyValuePair<string, string>("debug", "true"),
};
var multipartFormDataContent = new MultipartFormDataContent();
SetFormDataForExecuteTask(parameters, files, initalValues, multipartFormDataContent);
response = httpClient.PostAsync(link, multipartFormDataContent).Result;
responseContent = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
return JsonConvert.DeserializeObject<ExecuteTaskResponse>(responseContent);
}
}
catch (Exception e)
{
throw ParseRequestErrors(response, responseContent, e);
}
}
public void Download(Uri serverUrl, string taskId, string destinationPath)
{
HttpResponseMessage response = null;
var responseContent = string.Empty;
try
{
using (var client = new HttpClient())
{
AddAuthorizationHeader(client);
var link = StringHelpers.Invariant($"{serverUrl}{Settings.V1}/download/{taskId}");
var request = new HttpRequestMessage(HttpMethod.Get, link);
response = client.SendAsync(request).Result;
if (!response.IsSuccessStatusCode)
responseContent = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
using (var inputStream = response.Content.ReadAsStreamAsync().Result)
{
var fileName = response.Content.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
using (var outputStream = new FileStream(destinationPath + "\\" + fileName, FileMode.Create, FileAccess.Write, FileShare.Write))
{
inputStream.CopyTo(outputStream);
}
}
}
}
catch (Exception e)
{
throw ParseRequestErrors(response, responseContent, e);
}
}
public async Task<byte[]> DownloadAsync(Uri serverUrl, string taskId)
{
HttpResponseMessage response = null;
var responseContent = string.Empty;
try
{
using (var client = new HttpClient())
{
AddAuthorizationHeader(client);
var link = $"{serverUrl}{Settings.V1}/download/{taskId}";
var request = new HttpRequestMessage(HttpMethod.Get, link);
response = await client.SendAsync(request);
if (!response.IsSuccessStatusCode)
responseContent = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsByteArrayAsync();
}
}
catch (Exception e)
{
throw ParseRequestErrors(response, responseContent, e);
}
}
public byte[] Download(string serverUrl, string taskId)
{
HttpResponseMessage response = null;
var responseContent = string.Empty;
try
{
using (var client = new HttpClient())
{
AddAuthorizationHeader(client);
var link = StringHelpers.Invariant($"{serverUrl}{Settings.V1}/download/{taskId}");
var request = new HttpRequestMessage(HttpMethod.Get, link);
response = client.SendAsync(request).Result;
if (!response.IsSuccessStatusCode)
responseContent = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
return response.Content.ReadAsByteArrayAsync().Result;
}
}
catch (Exception e)
{
throw ParseRequestErrors(response, responseContent, e);
}
}
public UploadTaskResponse UploadFile(Uri serverUrl, byte[] fileByteArray, string fileName, string taskId)
{
HttpResponseMessage response = null;
var responseContent = string.Empty;
var link = StringHelpers.Invariant($"{serverUrl}{Settings.V1}/upload");
try
{
using (var httpClient = new HttpClient())
{
AddAuthorizationHeader(httpClient);
var multiPart = new MultipartFormDataContent();
var uploadRequest = new BaseTaskRequest();
uploadRequest.FormData.Add("task", taskId);
uploadRequest.FormData.Add("file", new FileParameter(fileByteArray, fileName));
SetMultiPartFormData(uploadRequest.FormData, multiPart);
response = httpClient.PostAsync(link, multiPart).Result;
responseContent = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
return JsonConvert.DeserializeObject<UploadTaskResponse>(responseContent);
}
}
catch (Exception e)
{
throw ParseRequestErrors(response, responseContent, e);
}
}
public UploadTaskResponse UploadFile(Uri serverUrl, Uri url, string taskId)
{
HttpResponseMessage response = null;
var responseContent = string.Empty;
var link = StringHelpers.Invariant($"{serverUrl}{Settings.V1}/upload");
try
{
using (var httpClient = new HttpClient())
{
AddAuthorizationHeader(httpClient);
var multiPart = new MultipartFormDataContent();
var request = new BaseTaskRequest();
request.FormData.Add("cloud_file", url.AbsoluteUri);
request.FormData.Add("task", taskId);
SetMultiPartFormData(request.FormData, multiPart);
response = httpClient.PostAsync(link, multiPart).Result;
responseContent = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
return JsonConvert.DeserializeObject<UploadTaskResponse>(responseContent);
}
}
catch (Exception e)
{
throw ParseRequestErrors(response, responseContent, e);
}
}
public UploadTaskResponse UploadFile(Uri serverUrl, FileInfo file, string taskId)
{
HttpResponseMessage response = null;
var responseContent = string.Empty;
var link = StringHelpers.Invariant($"{serverUrl}{Settings.V1}/upload");
try
{
using (Stream fs = file.OpenRead())
{
var uploadRequest = new BaseTaskRequest();
uploadRequest.FormData.Add("file", new FileParameter(fs, file.Name));
uploadRequest.FormData.Add("task", taskId);
//uploadRequest.FormData.Add("debug", "true");
using (var httpClient = new HttpClient())
{
AddAuthorizationHeader(httpClient);
var multipartFormData = new MultipartFormDataContent();
SetMultiPartFormData(uploadRequest.FormData, multipartFormData);
response = httpClient.PostAsync(link, multipartFormData).Result;
responseContent = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
return JsonConvert.DeserializeObject<UploadTaskResponse>(responseContent);
}
}
}
catch (Exception e)
{
throw ParseRequestErrors(response, responseContent, e);
}
}
public UploadTaskResponse UploadFileByChunk(Uri serverUrl, FileInfo fileInfo, string taskId)
{
UploadTaskResponse results;
HttpResponseMessage response = null;
var responseContent = string.Empty;
var link = StringHelpers.Invariant($"{serverUrl}{Settings.V1}/upload");
try
{
using (var httpClient = new HttpClient())
{
AddAuthorizationHeader(httpClient);
var uploadRequest = new BaseTaskRequest();
uploadRequest.FormData.Add("task", taskId);
//set default values
uploadRequest.FormData.Add("file", "");
uploadRequest.FormData.Add("chunk", "");
List<byte[]> chunksToUpload;
using (var fs = fileInfo.OpenRead())
{
chunksToUpload = ToChunks(fs);
uploadRequest.FormData.Add("chunks", chunksToUpload.Count.ToString(CultureInfo.InvariantCulture));
}
for (var i = 0; i < chunksToUpload.Count; i++)
{
using (var multipartFormDataContent = new MultipartFormDataContent())
{
uploadRequest.FormData["chunk"] = i.ToString(CultureInfo.InvariantCulture);
uploadRequest.FormData["file"] = new FileParameter(chunksToUpload[i], fileInfo.Name);
SetMultiPartFormData(uploadRequest.FormData, multipartFormDataContent);
response = httpClient.PostAsync(link, multipartFormDataContent).Result;
responseContent = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
}
}
results = JsonConvert.DeserializeObject<UploadTaskResponse>(responseContent);
}
}
catch (Exception e)
{
throw ParseRequestErrors(response, responseContent, e);
}
return results;
}
public StatusTaskResponse CheckTaskStatus(Uri serverUrl, string taskId)
{
var link = StringHelpers.Invariant($"{serverUrl}{Settings.V1}/task/{taskId}");
HttpResponseMessage response = null;
var responseContent = string.Empty;
try
{
using (var client = new HttpClient())
{
AddAuthorizationHeader(client);
response = client.GetAsync(link).Result;
responseContent = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
return JsonConvert.DeserializeObject<StatusTaskResponse>(responseContent);
}
}
catch (Exception e)
{
throw ParseRequestErrors(response, responseContent, e);
}
}
public DeleteTaskResponse DeleteTask(Uri serverUrl, string taskId)
{
HttpResponseMessage response = null;
var responseContent = string.Empty;
var link = StringHelpers.Invariant($"{serverUrl}{Settings.V1}/task/{taskId}");
try
{
using (var http = new HttpClient())
{
AddAuthorizationHeader(http);
response = http.DeleteAsync(link).Result;
responseContent = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
return JsonConvert.DeserializeObject<DeleteTaskResponse>(responseContent);
}
}
catch (Exception e)
{
throw ParseRequestErrors(response, responseContent, e);
}
}
public void DeleteFile(Uri serverUrl, string serverFileName, string taskId)
{
HttpResponseMessage response = null;
var responseContent = string.Empty;
try
{
var link = StringHelpers.Invariant($"{serverUrl}{Settings.V1}/upload/delete");
using (var http = new HttpClient())
{
AddAuthorizationHeader(http);
var multipartFormDataContent = new MultipartFormDataContent();
var deleteRequest = new BaseTaskRequest();
deleteRequest.FormData.Add("task", taskId);
deleteRequest.FormData.Add("server_filename", serverFileName);
SetMultiPartFormData(deleteRequest.FormData, multipartFormDataContent);
response = http.PostAsync(link, multipartFormDataContent).Result;
responseContent = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
}
}
catch (Exception e)
{
throw ParseRequestErrors(response, responseContent, e);
}
}
#region Help methods
private static List<byte[]> ToChunks(Stream fileStream)
{
byte[] incomingArray;
using (var ms = new MemoryStream())
{
fileStream.CopyTo(ms);
incomingArray = ms.ToArray();
}
var result = new List<byte[]>();
var incomingOffset = 0;
while (incomingOffset < incomingArray.Length)
{
var length =
Math.Min(Settings.MaxBytesPerChunk, incomingArray.Length - incomingOffset);
var outboundBuffer = new byte[length];
Buffer.BlockCopy(incomingArray, incomingOffset,
outboundBuffer, 0,
length);
incomingOffset += length;
// Transmit outbound buffer
result.Add((byte[])outboundBuffer.Clone());
}
return result;
}
public RequestHelper SetKeys(string privateKey, string publicKey)
{
_privateKey = privateKey;
_publicKey = publicKey;
return this;
}
/// <summary>
/// Set file encrypt key
/// </summary>
/// <param name="encryptKey"></param>
/// <param name="useBuildIn"></param>
/// <returns></returns>
public RequestHelper SetEncryptKey(string encryptKey = "", bool useBuildIn = false)
{
//if using build in skip encryptKey param even if it is provided
if (useBuildIn)
encryptKey = Guid.NewGuid().ToString("n").Substring(0, 32);
if (string.IsNullOrWhiteSpace(encryptKey)) return this;
if (encryptKey.Length != 16 && encryptKey.Length != 24 && encryptKey.Length != 32)
throw new ArgumentOutOfRangeException(nameof(encryptKey), "Only keys of sizes 16, 24 or 32 are supported.");
EncryptKey = encryptKey;
return this;
}
/// <summary>
/// Set authorization header for http client
/// </summary>
/// <param name="httpClient"></param>
private void AddAuthorizationHeader(HttpClient httpClient)
{
if (string.IsNullOrEmpty(Gwt))
Gwt = GetJwt();
else if (IsExpiredGwt())
Gwt = GetJwt();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Gwt);
}
/// <summary>
/// Check if GWT token expired
/// </summary>
/// <returns></returns>
private bool IsExpiredGwt()
{
try
{
IJsonSerializer serializer = new JsonNetSerializer();
IDateTimeProvider provider = new UtcDateTimeProvider();
IJwtValidator validator = new JwtValidator(serializer, provider);
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
var json = decoder.Decode(Gwt, _privateKey, verify: true);
return false;
}
catch (TokenExpiredException)
{
return true;
}
catch (SignatureVerificationException)
{
return true;
}
}
/// <summary>
/// Generate GWT token
/// </summary>
/// <returns></returns>
private string GetJwt()
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var payLoad = new Dictionary<string, object>
{
{"iss", ""},
{"aud", ""},
{"iat", DateTime.UtcNow.AddSeconds(- _jwtDelay)},
{"nbf", DateTime.UtcNow.AddSeconds(- _jwtDelay)},
//Add 2 hours of expiration
{
"exp",
Math.Round(new TimeSpan(DateTime.UtcNow.AddSeconds(_jwtDelay).Ticks).TotalSeconds -
new TimeSpan(epoch.Ticks).TotalSeconds)
},
{"jti", _publicKey }
};
if (!string.IsNullOrWhiteSpace(EncryptKey))
{
payLoad.Add("file_encryption_key", EncryptKey);
}
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IJsonSerializer serializer = new JsonNetSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
var token = encoder.Encode(payLoad, _privateKey);
return token;
}
private static void SetMultiPartFormData(Dictionary<string, object> formData, MultipartFormDataContent multiPartFormDataContent)
{
foreach (var param in formData)
{
if (param.Value is FileParameter file)
{
var uploadFile = file;
if (uploadFile.FileStream != null)
multiPartFormDataContent.Add(new StreamContent(uploadFile.FileStream), "file", uploadFile.FileName);
else
multiPartFormDataContent.Add(new ByteArrayContent(uploadFile.File), "file", uploadFile.FileName);
}
else
{
multiPartFormDataContent.Add(new StringContent((string)param.Value), param.Key);
}
}
}
private static void SetFormDataForExecuteTask(BaseParams @params, IReadOnlyList<FileModel> files, List<KeyValuePair<string, string>> initialValues, MultipartFormDataContent postMultipartFormDataContent)
{
if (@params != null)
{
//Serializing and deserializing to get properties from derived class, since those properties only available in runtime.
var json = JsonConvert.SerializeObject(@params, new KeyValuePairConverter());
var paramArray = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
initialValues.AddRange(
paramArray.Keys.Select(
paramKey => new KeyValuePair<string, string>(paramKey, paramArray[paramKey])));
}
for (var i = 0; i < files.Count; i++)
{
initialValues.Add(new KeyValuePair<string, string>(StringHelpers.Invariant($"files[{i}][filename]"), files[i].FileName));
initialValues.Add(new KeyValuePair<string, string>(StringHelpers.Invariant($"files[{i}][server_filename]"), files[i].ServerFileName));
initialValues.Add(new KeyValuePair<string, string>(StringHelpers.Invariant($"files[{i}][rotate]"), ((int)files[i].Rotate).ToString(CultureInfo.InvariantCulture)));
initialValues.Add(new KeyValuePair<string, string>(StringHelpers.Invariant($"files[{i}][password]"), files[i].Password));
}
var filteredFormDataValues = initialValues.Where(x => !string.IsNullOrWhiteSpace(x.Value));
foreach (var formDataValues in filteredFormDataValues)
{
postMultipartFormDataContent.Add(new StringContent(formDataValues.Value),
StringHelpers.Invariant($"\"{formDataValues.Key}\""));
}
}
#endregion
}
}