forked from RageAgainstThePixel/com.utilities.rest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rest.cs
1224 lines (1081 loc) · 53.2 KB
/
Rest.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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
using Utilities.Async;
using Utilities.Rest;
using Utilities.WebRequestRest.Interfaces;
using Debug = UnityEngine.Debug;
namespace Utilities.WebRequestRest
{
/// <summary>
/// REST Class for basic CRUD transactions.
/// </summary>
public static class Rest
{
internal const string FileUriPrefix = "file:https://";
private const string kHttpVerbPATCH = "PATCH";
private const string eventDelimiter = "data: ";
private const string stopEventDelimiter = "[DONE]";
#region Authentication
/// <summary>
/// Gets the Basic auth header.
/// </summary>
/// <param name="username">The Username.</param>
/// <param name="password">The password.</param>
/// <returns>The Basic authorization header encoded to base 64.</returns>
public static string GetBasicAuthentication(string username, string password)
=> $"Basic {Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes($"{username}:{password}"))}";
/// <summary>
/// Gets the Bearer auth header.
/// </summary>
/// <param name="authToken">OAuth Token to be used.</param>
/// <returns>The Bearer authorization header.</returns>
public static string GetBearerOAuthToken(string authToken)
=> $"Bearer {authToken}";
#endregion Authentication
#region GET
/// <summary>
/// Rest GET.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="parameters">Optional, <see cref="RestParameters"/>.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns>The response data.</returns>
public static async Task<Response> GetAsync(
string query,
RestParameters parameters = null,
CancellationToken cancellationToken = default)
{
using var webRequest = UnityWebRequest.Get(query);
return await webRequest.SendAsync(parameters, cancellationToken);
}
/// <summary>
/// Rest GET.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="serverSentEventCallback"><see cref="Action{T}"/> server sent event callback.</param>
/// <param name="parameters">Optional, <see cref="RestParameters"/>.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns>The response data.</returns>
public static async Task<Response> GetAsync(
string query,
Action<string> serverSentEventCallback,
RestParameters parameters = null,
CancellationToken cancellationToken = default)
{
using var webRequest = UnityWebRequest.Get(query);
return await webRequest.SendAsync(parameters, serverSentEventCallback, cancellationToken);
}
/// <summary>
/// Rest GET.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="dataReceivedEventCallback"><see cref="Action{T}"/> data received event callback.</param>
/// <param name="eventChunkSize"></param>
/// <param name="parameters">Optional, <see cref="RestParameters"/>.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns>The response data.</returns>
public static async Task<Response> GetAsync(
string query,
Action<Response> dataReceivedEventCallback,
int? eventChunkSize = null,
RestParameters parameters = null,
CancellationToken cancellationToken = default)
{
using var webRequest = UnityWebRequest.Get(query);
using var downloadHandler = eventChunkSize.HasValue
? new DownloadHandlerCallback(webRequest, eventChunkSize.Value)
: new DownloadHandlerCallback(webRequest);
downloadHandler.OnDataReceived += dataReceivedEventCallback;
try
{
return await webRequest.SendAsync(parameters, cancellationToken);
}
finally
{
downloadHandler.OnDataReceived -= dataReceivedEventCallback;
}
}
#endregion GET
#region POST
/// <summary>
/// Rest POST.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="parameters">Optional, <see cref="RestParameters"/>.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns>The response data.</returns>
public static async Task<Response> PostAsync(
string query,
RestParameters parameters = null,
CancellationToken cancellationToken = default)
{
#if UNITY_2022_2_OR_NEWER
using var webRequest = new UnityWebRequest(query, UnityWebRequest.kHttpVerbPOST);
#else
using var webRequest = new UnityWebRequest(query, UnityWebRequest.kHttpVerbPOST);
#endif
return await webRequest.SendAsync(parameters, cancellationToken);
}
/// <summary>
/// Rest POST.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="formData">Form Data.</param>
/// <param name="parameters">Optional, <see cref="RestParameters"/>.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns>The response data.</returns>
public static async Task<Response> PostAsync(
string query,
WWWForm formData,
RestParameters parameters = null,
CancellationToken cancellationToken = default)
{
using var webRequest = UnityWebRequest.Post(query, formData);
return await webRequest.SendAsync(parameters, cancellationToken);
}
/// <summary>
/// Rest POST.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="jsonData">JSON data for the request.</param>
/// <param name="parameters">Optional, <see cref="RestParameters"/>.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns>The response data.</returns>
public static async Task<Response> PostAsync(
string query,
string jsonData,
RestParameters parameters = null,
CancellationToken cancellationToken = default)
{
#if UNITY_2022_2_OR_NEWER
using var webRequest = new UnityWebRequest(query, UnityWebRequest.kHttpVerbPOST);
#else
using var webRequest = new UnityWebRequest(query, UnityWebRequest.kHttpVerbPOST);
#endif
var data = new UTF8Encoding().GetBytes(jsonData);
using var uploadHandler = new UploadHandlerRaw(data);
webRequest.uploadHandler = uploadHandler;
using var downloadHandler = new DownloadHandlerBuffer();
webRequest.downloadHandler = downloadHandler;
webRequest.SetRequestHeader("Content-Type", "application/json");
return await webRequest.SendAsync(parameters, cancellationToken);
}
/// <summary>
/// Rest POST.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="jsonData">JSON data for the request.</param>
/// <param name="serverSentEventCallback"><see cref="Action{T}"/> server sent event callback.</param>
/// <param name="parameters">Optional, <see cref="RestParameters"/>.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns>The response data.</returns>
public static async Task<Response> PostAsync(
string query,
string jsonData,
Action<string> serverSentEventCallback,
RestParameters parameters = null,
CancellationToken cancellationToken = default)
{
#if UNITY_2022_2_OR_NEWER
using var webRequest = new UnityWebRequest(query, UnityWebRequest.kHttpVerbPOST);
#else
using var webRequest = new UnityWebRequest(query, UnityWebRequest.kHttpVerbPOST);
#endif
var data = new UTF8Encoding().GetBytes(jsonData);
using var uploadHandler = new UploadHandlerRaw(data);
webRequest.uploadHandler = uploadHandler;
using var downloadHandler = new DownloadHandlerBuffer();
webRequest.downloadHandler = downloadHandler;
webRequest.SetRequestHeader("Content-Type", "application/json");
return await webRequest.SendAsync(parameters, serverSentEventCallback, cancellationToken);
}
/// <summary>
/// Rest POST.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="jsonData">JSON data for the request.</param>
/// <param name="dataReceivedEventCallback"><see cref="Action{T}"/> data received event callback.</param>
/// <param name="eventChunkSize">Optional, <see cref="dataReceivedEventCallback"/> event chunk size in bytes (Defaults to 512 bytes).</param>
/// <param name="parameters">Optional, <see cref="RestParameters"/>.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns>The response data.</returns>
public static async Task<Response> PostAsync(
string query,
string jsonData,
Action<Response> dataReceivedEventCallback,
int? eventChunkSize = null,
RestParameters parameters = null,
CancellationToken cancellationToken = default)
{
#if UNITY_2022_2_OR_NEWER
using var webRequest = new UnityWebRequest(query, UnityWebRequest.kHttpVerbPOST);
#else
using var webRequest = new UnityWebRequest(query, UnityWebRequest.kHttpVerbPOST);
#endif
var data = new UTF8Encoding().GetBytes(jsonData);
using var uploadHandler = new UploadHandlerRaw(data);
webRequest.uploadHandler = uploadHandler;
using var downloadHandler = eventChunkSize.HasValue
? new DownloadHandlerCallback(webRequest, eventChunkSize.Value)
: new DownloadHandlerCallback(webRequest);
downloadHandler.OnDataReceived += dataReceivedEventCallback;
webRequest.downloadHandler = downloadHandler;
webRequest.SetRequestHeader("Content-Type", "application/json");
try
{
return await webRequest.SendAsync(parameters, null, cancellationToken);
}
finally
{
downloadHandler.OnDataReceived -= dataReceivedEventCallback;
}
}
/// <summary>
/// Rest POST.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="bodyData">The raw data to post.</param>
/// <param name="parameters">Optional, <see cref="RestParameters"/>.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns>The response data.</returns>
public static async Task<Response> PostAsync(
string query,
byte[] bodyData,
RestParameters parameters = null,
CancellationToken cancellationToken = default)
{
#if UNITY_2022_2_OR_NEWER
using var webRequest = new UnityWebRequest(query, UnityWebRequest.kHttpVerbPOST);
#else
using var webRequest = new UnityWebRequest(query, UnityWebRequest.kHttpVerbPOST);
#endif
using var uploadHandler = new UploadHandlerRaw(bodyData);
webRequest.uploadHandler = uploadHandler;
using var downloadHandler = new DownloadHandlerBuffer();
webRequest.downloadHandler = downloadHandler;
webRequest.SetRequestHeader("Content-Type", "application/octet-stream");
return await webRequest.SendAsync(parameters, cancellationToken);
}
/// <summary>
/// Rest POST.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="form">The <see cref="IMultipartFormSection"/> to post.</param>
/// <param name="parameters">Optional, <see cref="RestParameters"/>.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns>The response data.</returns>
public static async Task<Response> PostAsync(
string query,
List<IMultipartFormSection> form,
RestParameters parameters = null,
CancellationToken cancellationToken = default)
{
#if UNITY_2022_2_OR_NEWER
using var webRequest = new UnityWebRequest(query, UnityWebRequest.kHttpVerbPOST);
#else
using var webRequest = new UnityWebRequest(query, UnityWebRequest.kHttpVerbPOST);
#endif
var boundary = UnityWebRequest.GenerateBoundary();
var formSections = UnityWebRequest.SerializeFormSections(form, boundary);
using var uploadHandler = new UploadHandlerRaw(formSections);
uploadHandler.contentType = $"multipart/form-data; boundary={Encoding.UTF8.GetString(boundary)}";
webRequest.uploadHandler = uploadHandler;
using var downloadHandler = new DownloadHandlerBuffer();
webRequest.downloadHandler = downloadHandler;
return await webRequest.SendAsync(parameters, cancellationToken);
}
#endregion POST
#region PUT
/// <summary>
/// Rest PUT.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="jsonData">Data to be submitted.</param>
/// <param name="parameters">Optional, <see cref="RestParameters"/>.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns>The response data.</returns>
public static async Task<Response> PutAsync(
string query,
string jsonData,
RestParameters parameters = null,
CancellationToken cancellationToken = default)
{
using var webRequest = UnityWebRequest.Put(query, jsonData);
webRequest.SetRequestHeader("Content-Type", "application/json");
return await webRequest.SendAsync(parameters, cancellationToken);
}
/// <summary>
/// Rest PUT.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="bodyData">Data to be submitted.</param>
/// <param name="parameters">Optional, <see cref="RestParameters"/>.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns>The response data.</returns>
public static async Task<Response> PutAsync(
string query,
byte[] bodyData,
RestParameters parameters = null,
CancellationToken cancellationToken = default)
{
using var webRequest = UnityWebRequest.Put(query, bodyData);
webRequest.SetRequestHeader("Content-Type", "application/octet-stream");
return await webRequest.SendAsync(parameters, cancellationToken);
}
#endregion PUT
#region PATCH
/// <summary>
/// Rest PATCH.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="jsonData">Data to be submitted.</param>
/// <param name="parameters">Optional, <see cref="RestParameters"/>.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns>The response data.</returns>
public static async Task<Response> PatchAsync(
string query,
string jsonData,
RestParameters parameters = null,
CancellationToken cancellationToken = default)
{
using var webRequest = UnityWebRequest.Put(query, jsonData);
webRequest.method = kHttpVerbPATCH;
webRequest.SetRequestHeader("Content-Type", "application/json");
return await webRequest.SendAsync(parameters, cancellationToken);
}
/// <summary>
/// Rest PATCH.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="bodyData">Data to be submitted.</param>
/// <param name="parameters">Optional, <see cref="RestParameters"/>.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns>The response data.</returns>
public static async Task<Response> PatchAsync(
string query,
byte[] bodyData,
RestParameters parameters = null,
CancellationToken cancellationToken = default)
{
using var webRequest = UnityWebRequest.Put(query, bodyData);
webRequest.method = kHttpVerbPATCH;
webRequest.SetRequestHeader("Content-Type", "application/octet-stream");
return await webRequest.SendAsync(parameters, cancellationToken);
}
#endregion PATCH
#region DELETE
/// <summary>
/// Rest DELETE.
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="parameters">Optional, <see cref="RestParameters"/>.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns>The response data.</returns>
public static async Task<Response> DeleteAsync(
string query,
RestParameters parameters = null,
CancellationToken cancellationToken = default)
{
using var webRequest = UnityWebRequest.Delete(query);
using var downloadHandler = new DownloadHandlerBuffer();
webRequest.downloadHandler = downloadHandler;
return await webRequest.SendAsync(parameters, cancellationToken);
}
#endregion DELETE
#region Get Multimedia Content
#region Download Cache
private const string download_cache = nameof(download_cache);
private static IDownloadCache cache;
private static IDownloadCache Cache
=> cache ??= Application.platform switch
{
RuntimePlatform.WebGLPlayer => new NoOpDownloadCache(),
_ => new DiskDownloadCache()
};
/// <summary>
/// The download cache directory.<br/>
/// </summary>
public static string DownloadCacheDirectory
=> Path.Combine(Application.temporaryCachePath, download_cache);
/// <summary>
/// Creates the <see cref="DownloadCacheDirectory"/> if it doesn't exist.
/// </summary>
public static void ValidateCacheDirectory()
=> Cache.ValidateCacheDirectory();
/// <summary>
/// Creates the <see cref="DownloadCacheDirectory"/> if it doesn't exist.
/// </summary>
public static Task ValidateCacheDirectoryAsync()
=> Cache.ValidateCacheDirectoryAsync();
/// <summary>
/// Try to get a file out of the download cache by uri reference.
/// </summary>
/// <param name="uri">The uri key of the item.</param>
/// <param name="filePath">The file path to the cached item.</param>
/// <returns>True, if the item was in cache, otherwise false.</returns>
public static bool TryGetDownloadCacheItem(string uri, out string filePath)
=> Cache.TryGetDownloadCacheItem(uri, out filePath);
/// <summary>
/// Try to delete the cached item at the uri.
/// </summary>
/// <param name="uri">The uri key of the item.</param>
/// <returns>True, if the cached item was successfully deleted.</returns>
public static bool TryDeleteCacheItem(string uri)
=> Cache.TryDeleteCacheItem(uri);
/// <summary>
/// Deletes all the files in the download cache.
/// </summary>
public static void DeleteDownloadCache()
=> Cache.DeleteDownloadCache();
/// <summary>
/// We will try go guess the name based on the url.
/// </summary>
/// <param name="url">The url to parse to try to guess file name.</param>
/// <param name="fileName">The filename if found.</param>
/// <returns>True, if a valid filename is found.</returns>
public static bool TryGetFileNameFromUrl(string url, out string fileName)
{
var baseUrl = UnityWebRequest.UnEscapeURL(url);
var rootUrl = baseUrl.Split('?')[0];
var index = rootUrl.LastIndexOf('/') + 1;
fileName = rootUrl.Substring(index, rootUrl.Length - index);
return Path.HasExtension(fileName);
}
#endregion Download Cache
[Obsolete("use new overload with debug support")]
public static async Task<Texture2D> DownloadTextureAsync(
string url,
string fileName = null,
RestParameters parameters = null,
CancellationToken cancellationToken = default)
{
return await DownloadTextureAsync(url, fileName, parameters, false, cancellationToken);
}
/// <summary>
/// Download a <see cref="Texture2D"/> from the provided <see cref="url"/>.
/// </summary>
/// <param name="url">The url to download the <see cref="Texture2D"/> from.</param>
/// <param name="fileName">Optional, file name to download (including extension).</param>
/// <param name="parameters">Optional, <see cref="RestParameters"/>.</param>
/// <param name="debug">Optional, debug http request.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns>A new <see cref="Texture2D"/> instance.</returns>
public static async Task<Texture2D> DownloadTextureAsync(
string url,
string fileName = null,
RestParameters parameters = null,
bool debug = false,
CancellationToken cancellationToken = default)
{
await Awaiters.UnityMainThread;
if (string.IsNullOrWhiteSpace(fileName))
{
TryGetFileNameFromUrl(url, out fileName);
}
bool isCached;
string cachePath;
if (url.Contains(FileUriPrefix))
{
isCached = true;
cachePath = url;
}
else
{
isCached = TryGetDownloadCacheItem(fileName, out cachePath);
}
if (isCached)
{
url = cachePath;
}
Texture2D texture;
parameters ??= new RestParameters();
parameters.DisposeDownloadHandler = true;
using var webRequest = UnityWebRequestTexture.GetTexture(url);
try
{
var response = await webRequest.SendAsync(parameters, cancellationToken);
response.Validate(debug);
if (!isCached)
{
await Cache.WriteCacheItemAsync(webRequest.downloadHandler.data, cachePath, cancellationToken).ConfigureAwait(true);
}
texture = ((DownloadHandlerTexture)webRequest.downloadHandler).texture;
if (texture == null)
{
throw new RestException(response, $"Failed to load texture from \"{url}\"!");
}
}
finally
{
webRequest.downloadHandler?.Dispose();
}
texture.name = Path.GetFileNameWithoutExtension(cachePath);
return texture;
}
[Obsolete("Use new overload with debug support")]
public static async Task<AudioClip> DownloadAudioClipAsync(
string url,
AudioType audioType,
RestParameters parameters = null,
CancellationToken cancellationToken = default)
{
return await DownloadAudioClipAsync(url, audioType, httpMethod: UnityWebRequest.kHttpVerbGET, parameters: parameters, cancellationToken: cancellationToken);
}
/// <summary>
/// Download a <see cref="AudioClip"/> from the provided <see cref="url"/>.
/// </summary>
/// <param name="url">The url to download the <see cref="AudioClip"/> from.</param>
/// <param name="audioType"><see cref="AudioType"/> to download.</param>
/// <param name="fileName">Optional, file name to download (including extension).</param>
/// <param name="httpMethod">Optional, must be either GET or POST.</param>
/// <param name="jsonData">Optional, json payload. Only <see cref="jsonData"/> OR <see cref="payload"/> can be supplied.</param>
/// <param name="payload">Optional, raw byte payload. Only <see cref="payload"/> OR <see cref="jsonData"/> can be supplied.</param>
/// <param name="parameters">Optional, <see cref="RestParameters"/>.</param>
/// <param name="debug">Optional, debug http request.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns>A new <see cref="AudioClip"/> instance.</returns>
public static async Task<AudioClip> DownloadAudioClipAsync(
string url,
AudioType audioType,
string httpMethod = UnityWebRequest.kHttpVerbGET,
string fileName = null,
string jsonData = null,
byte[] payload = null,
RestParameters parameters = null,
bool debug = false,
CancellationToken cancellationToken = default)
{
await Awaiters.UnityMainThread;
if (string.IsNullOrWhiteSpace(fileName))
{
TryGetFileNameFromUrl(url, out fileName);
}
bool isCached;
string cachePath;
if (url.Contains(FileUriPrefix))
{
isCached = true;
cachePath = url;
}
else
{
isCached = TryGetDownloadCacheItem(fileName, out cachePath);
}
if (isCached)
{
url = cachePath;
}
UploadHandler uploadHandler = null;
using var downloadHandler = new DownloadHandlerAudioClip(url, audioType);
if (httpMethod == UnityWebRequest.kHttpVerbPOST)
{
if (!string.IsNullOrWhiteSpace(jsonData))
{
if (payload != null)
{
throw new ArgumentException($"{nameof(payload)} and {nameof(jsonData)} cannot be supplied in the same request. Choose either one or the other.", nameof(jsonData));
}
payload = new UTF8Encoding().GetBytes(jsonData);
var jsonHeaders = new Dictionary<string, string>
{
{ "Content-Type", "application/json" }
};
if (parameters is { Headers: not null })
{
foreach (var header in parameters.Headers)
{
jsonHeaders.Add(header.Key, header.Value);
}
}
if (parameters != null)
{
parameters.Headers = jsonHeaders;
}
}
uploadHandler = new UploadHandlerRaw(payload);
}
AudioClip clip;
parameters ??= new RestParameters();
parameters.DisposeUploadHandler = false;
parameters.DisposeDownloadHandler = false;
using var webRequest = new UnityWebRequest(url, httpMethod, downloadHandler, uploadHandler);
try
{
var response = await webRequest.SendAsync(parameters, cancellationToken);
response.Validate(debug);
if (!isCached)
{
await Cache.WriteCacheItemAsync(downloadHandler.data, cachePath, cancellationToken);
}
await Awaiters.UnityMainThread;
clip = downloadHandler.audioClip;
if (clip == null)
{
throw new RestException(response, $"Failed to download audio clip from \"{url}\"!");
}
}
finally
{
downloadHandler.Dispose();
uploadHandler?.Dispose();
}
clip.name = Path.GetFileNameWithoutExtension(cachePath);
return clip;
}
/// <summary>
/// Stream a <see cref="AudioClip"/> from the provided <see cref="url"/>.
/// </summary>
/// <param name="url">The url to download the <see cref="AudioClip"/> from.</param>
/// <param name="audioType"><see cref="AudioType"/> to download.</param>
/// <param name="onStreamPlaybackReady"><see cref="Action{T}"/> callback raised when stream is ready to be played.</param>
/// <param name="httpMethod">Optional, must be either GET or POST.</param>
/// <param name="jsonData">Optional, json payload. Only <see cref="jsonData"/> OR <see cref="payload"/> can be supplied.</param>
/// <param name="payload">Optional, raw byte payload. Only <see cref="payload"/> OR <see cref="jsonData"/> can be supplied.</param>
/// <param name="fileName">Optional, file name to download (including extension).</param>
/// <param name="playbackAmountThreshold">Optional, the amount of data to to download before signaling that streaming is ready.</param>
/// <param name="parameters">Optional, <see cref="RestParameters"/>.</param>
/// <param name="debug">Optional, debug http request.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns>A new <see cref="AudioClip"/> instance.</returns>
public static async Task<AudioClip> StreamAudioAsync(
string url,
AudioType audioType,
Action<AudioClip> onStreamPlaybackReady,
string httpMethod = UnityWebRequest.kHttpVerbPOST,
string fileName = null,
string jsonData = null,
byte[] payload = null,
ulong playbackAmountThreshold = 10000,
RestParameters parameters = null,
bool debug = false,
CancellationToken cancellationToken = default)
{
await Awaiters.UnityMainThread;
if (string.IsNullOrWhiteSpace(fileName))
{
TryGetFileNameFromUrl(url, out fileName);
}
if (url.Contains(FileUriPrefix))
{
// override the httpMethod
httpMethod = UnityWebRequest.kHttpVerbGET;
}
AudioClip clip = null;
var streamStarted = false;
UploadHandler uploadHandler = null;
if (httpMethod == UnityWebRequest.kHttpVerbPOST)
{
if (!string.IsNullOrWhiteSpace(jsonData))
{
if (payload != null)
{
throw new ArgumentException($"{nameof(payload)} and {nameof(jsonData)} cannot be supplied in the same request. Choose either one or the other.", nameof(jsonData));
}
payload = new UTF8Encoding().GetBytes(jsonData);
var jsonHeaders = new Dictionary<string, string>
{
{ "Content-Type", "application/json" }
};
if (parameters is { Headers: not null })
{
foreach (var header in parameters.Headers)
{
jsonHeaders.Add(header.Key, header.Value);
}
}
if (parameters != null)
{
parameters.Headers = jsonHeaders;
}
}
uploadHandler = new UploadHandlerRaw(payload);
}
parameters ??= new RestParameters();
parameters.DisposeUploadHandler = false;
parameters.DisposeDownloadHandler = false;
using var downloadHandler = new DownloadHandlerAudioClip(url, audioType);
downloadHandler.streamAudio = true; // BUG: Due to a Unity bug this does not work with mp3s of indeterminate length. https://forum.unity.com/threads/downloadhandleraudioclip-streamaudio-is-ignored.699908/
using var webRequest = new UnityWebRequest(url, httpMethod, downloadHandler, uploadHandler);
IProgress<Progress> progress = null;
if (parameters.Progress != null)
{
progress = parameters.Progress;
}
parameters.Progress = new Progress<Progress>(report =>
{
progress?.Report(report);
// only raise stream ready if we haven't assigned a clip yet.
if (clip != null) { return; }
try
{
// ReSharper disable once AccessToDisposedClosure
if (report.Position > playbackAmountThreshold || downloadHandler.isDone)
{
// ReSharper disable once AccessToDisposedClosure
var tempClip = downloadHandler.audioClip;
clip = tempClip;
clip.name = Path.GetFileNameWithoutExtension(fileName);
streamStarted = true;
onStreamPlaybackReady?.Invoke(clip);
}
}
catch (Exception)
{
// Ignored
}
});
var response = await webRequest.SendAsync(parameters, cancellationToken);
uploadHandler?.Dispose();
response.Validate(debug);
var loadedClip = downloadHandler.audioClip;
if (loadedClip != null)
{
loadedClip.name = Path.GetFileNameWithoutExtension(fileName);
}
if (!streamStarted)
{
streamStarted = true;
onStreamPlaybackReady?.Invoke(loadedClip);
}
return loadedClip;
}
#if UNITY_ADDRESSABLES
/// <summary>
/// Download a <see cref="AssetBundle"/> from the provided <see cref="url"/>.
/// </summary>
/// <param name="url">The url to download the <see cref="AssetBundle"/> from.</param>
/// <param name="options">Asset bundle request options.</param>
/// <param name="parameters">Optional, <see cref="RestParameters"/>.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns>A new <see cref="AssetBundle"/> instance.</returns>
public static async Task<AssetBundle> DownloadAssetBundleAsync(
string url,
UnityEngine.ResourceManagement.ResourceProviders.AssetBundleRequestOptions options,
RestParameters parameters = null,
CancellationToken cancellationToken = default)
{
await Awaiters.UnityMainThread;
UnityWebRequest webRequest;
if (options == null)
{
webRequest = UnityWebRequestAssetBundle.GetAssetBundle(url);
}
else
{
if (!string.IsNullOrEmpty(options.Hash))
{
CachedAssetBundle cachedBundle = new CachedAssetBundle(options.BundleName, Hash128.Parse(options.Hash));
#if ENABLE_CACHING
if (options.UseCrcForCachedBundle || !Caching.IsVersionCached(cachedBundle))
{
webRequest = UnityWebRequestAssetBundle.GetAssetBundle(url, cachedBundle, options.Crc);
}
else
{
webRequest = UnityWebRequestAssetBundle.GetAssetBundle(url, cachedBundle);
}
#else
webRequest = UnityWebRequestAssetBundle.GetAssetBundle(url, cachedBundle, options.Crc);
#endif
}
else
{
webRequest = UnityWebRequestAssetBundle.GetAssetBundle(url, options.Crc);
}
if (options.Timeout > 0)
{
webRequest.timeout = options.Timeout;
}
if (options.RedirectLimit > 0)
{
webRequest.redirectLimit = options.RedirectLimit;
}
}
using (webRequest)
{
Response response;
try
{
parameters ??= new RestParameters();
parameters.Timeout = options?.Timeout ?? -1;
parameters.DisposeDownloadHandler = false;
response = await webRequest.SendAsync(parameters, cancellationToken);
}
catch (Exception e)
{
Debug.LogError(e);
throw;
}
if (!response.Successful)
{
Debug.LogError($"Failed to download asset bundle from \"{url}\"!\n{response.Code}:{response.Body}");
return null;
}
var downloadHandler = (DownloadHandlerAssetBundle)webRequest.downloadHandler;
var assetBundle = downloadHandler.assetBundle;
downloadHandler.Dispose();
return assetBundle;
}
}
#endif // UNITY_ADDRESSABLES
[Obsolete("use new overload with debug support")]
public static async Task<string> DownloadFileAsync(
string url,
string fileName = null,
RestParameters parameters = null,
CancellationToken cancellationToken = default)
{
return await DownloadFileAsync(url, fileName, parameters, false, cancellationToken);
}
/// <summary>
/// Download a file from the provided <see cref="url"/>.
/// </summary>
/// <param name="url">The url to download the file from.</param>
/// <param name="fileName">Optional, file name to download (including extension).</param>
/// <param name="parameters">Optional, <see cref="RestParameters"/>.</param>
/// <param name="debug">Optional, debug http request.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns>The path to the downloaded file.</returns>
public static async Task<string> DownloadFileAsync(
string url,
string fileName = null,
RestParameters parameters = null,
bool debug = false,
CancellationToken cancellationToken = default)
{
await Awaiters.UnityMainThread;
if (string.IsNullOrWhiteSpace(fileName))
{
TryGetFileNameFromUrl(url, out fileName);
}
if (TryGetDownloadCacheItem(fileName, out var filePath))
{
return filePath;
}
using var webRequest = UnityWebRequest.Get(url);
using var fileDownloadHandler = new DownloadHandlerFile(filePath);
fileDownloadHandler.removeFileOnAbort = true;
webRequest.downloadHandler = fileDownloadHandler;
var response = await webRequest.SendAsync(parameters, cancellationToken);
response.Validate(debug);
return filePath;
}
#endregion Get Multimedia Content
/// <summary>
/// Process a <see cref="UnityWebRequest"/> asynchronously.
/// </summary>
/// <param name="webRequest">The <see cref="UnityWebRequest"/>.</param>
/// <param name="parameters">Optional, <see cref="RestParameters"/>.</param>
/// <param name="cancellationToken">Optional <see cref="CancellationToken"/>.</param>
/// <returns><see cref="Response"/></returns>
public static async Task<Response> SendAsync(
this UnityWebRequest webRequest,
RestParameters parameters = null,
CancellationToken cancellationToken = default)
=> await SendAsync(webRequest, parameters, null, cancellationToken);