-
Notifications
You must be signed in to change notification settings - Fork 386
Expand file tree
/
Copy pathNugetApiClientV3.cs
More file actions
1217 lines (1049 loc) · 48.9 KB
/
Copy pathNugetApiClientV3.cs
File metadata and controls
1217 lines (1049 loc) · 48.9 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
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
#pragma warning disable SA1512,SA1124 // Single-line comments should not be followed by blank line
#region No ReShaper
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.Text;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using NugetForUnity.Configuration;
using NugetForUnity.Helper;
using NugetForUnity.Models;
using UnityEditor;
using UnityEngine;
// ReSharper disable All
// needed because 'JetBrains.Annotations.NotNull' and 'System.Diagnostics.CodeAnalysis.NotNull' collide if this file is compiled with a never version of Unity / C#
using SuppressMessageAttribute = System.Diagnostics.CodeAnalysis.SuppressMessageAttribute;
// ReSharper restore All
#endregion
#pragma warning restore SA1512,SA1124 // Single-line comments should not be followed by blank line
namespace NugetForUnity.PackageSource
{
/// <summary>
/// API client for NuGet API v3.
/// </summary>
[Serializable]
internal sealed class NugetApiClientV3 : IDisposable
{
[NonSerialized]
[NotNull]
private readonly Uri apiIndexJsonUrl;
[NonSerialized]
[NotNull]
private readonly HttpClient httpClient;
[NonSerialized]
[CanBeNull]
private TaskCompletionSource<bool> initializationTaskCompletionSource;
// Example: https://api.nuget.org/v3-flatcontainer/
[CanBeNull]
[SerializeField]
private string packageBaseAddress;
// Example: https://api.nuget.org/v3-flatcontainer/{0}/{1}/{0}.{1}.nupkg
[CanBeNull]
[SerializeField]
private string packageDownloadUrlTemplate;
// Example: https://api.nuget.org/v3/registration5-gz-semver2/
[CanBeNull]
[SerializeField]
private string registrationsBaseUrl;
[CanBeNull]
[SerializeField]
private List<string> searchQueryServices;
/// <summary>
/// Initializes a new instance of the <see cref="NugetApiClientV3" /> class.
/// </summary>
/// <param name="url">The absolute 'index.json' URL of the API.</param>
public NugetApiClientV3([NotNull] string url)
{
if (string.IsNullOrWhiteSpace(url))
{
throw new ArgumentException($"'{nameof(url)}' cannot be null or whitespace.", nameof(url));
}
apiIndexJsonUrl = new Uri(url);
#pragma warning disable CA2000 // Dispose objects before losing scope: Ownership is transferred to httpClient
var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate };
#pragma warning restore CA2000 // Dispose objects before losing scope
if (Application.platform == RuntimePlatform.WindowsEditor)
{
// On Windows, Mono HttpClient does not automatically pick up proxy settings.
handler.Proxy = WebRequest.GetSystemWebProxy();
}
httpClient = new HttpClient(handler);
InitializeFromSessionState();
}
/// <summary>
/// Gets or sets a optional overwrite for the URL used to download '.nupkg' files (see: <see cref="DownloadNupkgToFileAsync" />).
/// </summary>
[CanBeNull]
[field: SerializeField]
public string PackageDownloadUrlTemplateOverwrite { get; set; }
/// <inheritdoc />
public void Dispose()
{
httpClient.Dispose();
}
/// <summary>
/// Searches for NuGet packages available on the server.
/// </summary>
/// <remarks>
/// https://github.com/NuGet/docs.microsoft.com-nuget/blob/live/docs/api/search-query-service-resource.md.
/// </remarks>
/// <param name="packageSource">The package source that owns this client.</param>
/// <param name="searchQuery">
/// The search query. See https://learn.microsoft.com/en-us/nuget/api/search-query-service-resource#request-parameters.
/// </param>
/// <param name="skip">
/// The number of results to skip. See https://learn.microsoft.com/en-us/nuget/api/search-query-service-resource#request-parameters.
/// </param>
/// <param name="take">
/// The number of results to return. See https://learn.microsoft.com/en-us/nuget/api/search-query-service-resource#request-parameters.
/// </param>
/// <param name="includePreRelease">
/// Whether to include pre-release packages. See https://learn.microsoft.com/en-us/nuget/api/search-query-service-resource#request-parameters.
/// </param>
/// <param name="cancellationToken">
/// Token to cancel the HTTP request.
/// </param>
/// <returns>
/// A list of <see cref="INugetPackage" />s that match the search query.
/// </returns>
public async Task<List<INugetPackage>> SearchPackageAsync(
NugetPackageSourceV3 packageSource,
string searchQuery = "",
int skip = -1,
int take = -1,
bool includePreRelease = false,
CancellationToken cancellationToken = default)
{
var successfullyInitialized = await EnsureInitializedAsync(packageSource);
if (!successfullyInitialized || searchQueryServices == null)
{
return new List<INugetPackage>();
}
if (searchQueryServices.Count == 0)
{
Debug.LogError($"There are no {nameof(searchQueryServices)} specified in the API '{apiIndexJsonUrl}' so we can't search.");
return new List<INugetPackage>();
}
var queryBuilder = new QueryBuilder();
// so both SemVer 1.0.0 and SemVer 2.0.0 compatible packages are returned
queryBuilder.Add("semVerLevel", "2.0.0");
queryBuilder.Add("q", searchQuery);
if (skip > 0)
{
queryBuilder.Add("skip", skip.ToString(CultureInfo.InvariantCulture));
}
if (take > 0)
{
queryBuilder.Add("take", take.ToString(CultureInfo.InvariantCulture));
}
if (includePreRelease)
{
queryBuilder.Add("prerelease", "true");
}
var query = queryBuilder.ToString();
var queryService = searchQueryServices[0];
var responseString = await GetStringFromServerAsync(packageSource, queryService + query, cancellationToken).ConfigureAwait(false);
var searchResult = JsonUtility.FromJson<SearchResult>(responseString);
var results = searchResult.data ?? throw new InvalidOperationException($"missing 'data' property in search response:\n{responseString}");
return SearchResultToNugetPackages(results, packageSource);
}
/// <summary>
/// Download the .nupkg file and store it inside a file at <paramref name="outputFilePath" />.
/// </summary>
/// <param name="packageSource">The package source that owns this client.</param>
/// <param name="package">The package to download its .nupkg from.</param>
/// <param name="outputFilePath">Path where the downloaded file is placed.</param>
/// <param name="downloadUrlHint">Hint for the url used to download the .nupkg file from.</param>
/// <returns>The async task.</returns>
[SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "We intentionally use lower case.")]
public async Task DownloadNupkgToFileAsync(
NugetPackageSourceV3 packageSource,
INugetPackageIdentifier package,
string outputFilePath,
string downloadUrlHint)
{
string downloadUrl;
if (!string.IsNullOrEmpty(downloadUrlHint))
{
downloadUrl = downloadUrlHint;
}
else
{
var successfullyInitialized = await EnsureInitializedAsync(packageSource);
if (!successfullyInitialized)
{
return;
}
if (string.IsNullOrEmpty(packageDownloadUrlTemplate))
{
Debug.LogError(
$"There are no {nameof(packageBaseAddress)} specified in the API '{apiIndexJsonUrl}' so we can't download packages.");
return;
}
var version = package.Version.ToLowerInvariant();
var id = package.Id.ToLowerInvariant();
downloadUrl = string.Format(CultureInfo.InvariantCulture, packageDownloadUrlTemplate, id, version);
}
using (var request = new HttpRequestMessage(HttpMethod.Get, downloadUrl))
{
AddHeadersToRequest(request, packageSource, false);
using (var response = await httpClient.SendAsync(request).ConfigureAwait(false))
{
await EnsureResponseIsSuccessAsync(response).ConfigureAwait(false);
using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
{
using (var fileStream = File.Create(outputFilePath))
{
await stream.CopyToAsync(fileStream).ConfigureAwait(false);
}
}
}
}
}
/// <summary>
/// Fetches a single NuGet package from the package registration. Other than <see cref="GetPackageWithDetailsAsync" /> this also fetches a list of
/// all available versions.
/// </summary>
/// <param name="packageSource">The package source that owns this client.</param>
/// <param name="package">The package identifier to receive including the details.</param>
/// <param name="includePrerelease">True to include prerelease packages (alpha, beta, etc).</param>
/// <param name="cancellationToken">Token to cancel the HTTP request.</param>
/// <returns>The package or null if we didn't find it.</returns>
public async Task<NugetPackageV3> GetPackageWithAllVersionsAsync(
NugetPackageSourceV3 packageSource,
INugetPackageIdentifier package,
bool includePrerelease,
CancellationToken cancellationToken = default)
{
var registrationItems = await GetRegistrationPageItemsAsync(packageSource, package, cancellationToken);
if (registrationItems is null)
{
return null;
}
var versions = new List<NugetPackageVersion>();
RegistrationLeafObject latestVersionItem = null;
NugetPackageVersion latestVersion = null;
var sb = new StringBuilder();
foreach (var item in registrationItems)
{
if (item.items is null || item.items.Count == 0)
{
item.items = await GetRegistrationPageLeafItems(packageSource, item, cancellationToken).ConfigureAwait(false);
}
var lastNote = string.Empty;
foreach (var leafObject in item.items)
{
var catalogEntry = leafObject.CatalogEntry;
if (catalogEntry.version is null)
{
throw new InvalidOperationException(
$"missing '{nameof(catalogEntry.version)}' property in catalog entry:\n{JsonUtility.ToJson(catalogEntry)}");
}
var version = new NugetPackageVersion(catalogEntry.version);
if (includePrerelease || !version.IsPrerelease)
{
versions.Add(version);
}
if (latestVersion != null && version <= latestVersion)
{
continue;
}
latestVersion = version;
latestVersionItem = leafObject;
if (!string.IsNullOrWhiteSpace(catalogEntry.releaseNotes) && lastNote != catalogEntry.releaseNotes && version > package.PackageVersion)
{
sb.Append(catalogEntry.releaseNotes).Append("\n");
lastNote = catalogEntry.releaseNotes;
}
}
}
versions.Sort((v1, v2) => v2.CompareTo(v1));
return CreatePackageFromRegistrationLeaf(packageSource, latestVersionItem, sb.ToString(), versions);
}
/// <summary>
/// Gets a single NuGet package including the package details <see cref="GetPackageDetailsAsync" /> but not containing all available versions.
/// </summary>
/// <param name="packageSource">The package source that owns this client.</param>
/// <param name="package">The package identifier to receive including the details.</param>
/// <param name="cancellationToken">Token to cancel the HTTP request.</param>
/// <returns>The package or null if we didn't find it.</returns>
[ItemCanBeNull]
public async Task<NugetPackageV3> GetPackageWithDetailsAsync(
NugetPackageSourceV3 packageSource,
INugetPackageIdentifier package,
CancellationToken cancellationToken = default)
{
var leafItem = await GetPackageRegistrationLeafAsync(packageSource, package, cancellationToken).ConfigureAwait(false);
if (leafItem is null)
{
return null;
}
return CreatePackageFromRegistrationLeaf(packageSource, leafItem, leafItem.CatalogEntry.releaseNotes);
}
/// <summary>
/// Fetches the package details from the server.
/// </summary>
/// <param name="packageSource">The package source that owns this client.</param>
/// <param name="package">The package to receive the details for.</param>
/// <param name="cancellationToken">
/// Token to cancel the request.
/// </param>
/// <returns>
/// The package details or null if the package is not found.
/// </returns>
[SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "API uses lower case.")]
[NotNull]
[ItemNotNull]
public async Task<List<NugetFrameworkGroup>> GetPackageDetailsAsync(
NugetPackageSourceV3 packageSource,
INugetPackageIdentifier package,
CancellationToken cancellationToken = default)
{
var leafItem = await GetPackageRegistrationLeafAsync(packageSource, package, cancellationToken).ConfigureAwait(false);
return leafItem is null ? new List<NugetFrameworkGroup>() : ConvertDependencyGroups(leafItem.CatalogEntry);
}
private static NugetPackageV3 CreatePackageFromRegistrationLeaf(
NugetPackageSourceV3 packageSource,
RegistrationLeafObject leafItem,
string releaseNotes,
List<NugetPackageVersion> allVersions = null)
{
var entry = leafItem.CatalogEntry;
if (entry.id is null)
{
throw new InvalidOperationException($"missing '{nameof(entry.id)}' property in catalog entry:\n{JsonUtility.ToJson(entry)}");
}
if (entry.version is null)
{
throw new InvalidOperationException($"missing '{nameof(entry.version)}' property in catalog entry:\n{JsonUtility.ToJson(entry)}");
}
return new NugetPackageV3(
entry.id,
entry.version,
new List<string> { entry.authors },
entry.description,
0,
entry.licenseUrl,
packageSource,
entry.projectUrl,
entry.summary,
entry.title,
entry.iconUrl,
releaseNotes,
allVersions ?? new List<NugetPackageVersion> { new NugetPackageVersion(entry.version) })
{
DownloadUrl = leafItem.packageContent, Dependencies = ConvertDependencyGroups(entry),
};
}
private static List<NugetFrameworkGroup> ConvertDependencyGroups(CatalogEntry entry)
{
if (entry.dependencyGroups != null)
{
return entry.dependencyGroups.ConvertAll(
dependencyGroup =>
{
var dependencies = dependencyGroup.dependencies is null ?
new List<INugetPackageIdentifier>() :
dependencyGroup.dependencies.ConvertAll(
dependency => (INugetPackageIdentifier)new NugetPackageIdentifier(
dependency.id ??
throw new InvalidOperationException(
$"missing '{nameof(dependency.id)}' inside '{nameof(dependencyGroup.dependencies)}' for dependency group: '{JsonUtility.ToJson(dependencyGroup)}'"),
dependency.range));
return new NugetFrameworkGroup { Dependencies = dependencies, TargetFramework = dependencyGroup.targetFramework };
});
}
if (ConfigurationManager.IsVerboseLoggingEnabled)
{
NugetLogger.LogVerbose(
"missing '{0}.{1}' property for CatalogEntry: '{2}'",
nameof(CatalogEntry),
nameof(CatalogEntry.dependencyGroups),
JsonUtility.ToJson(entry));
}
return new List<NugetFrameworkGroup>();
}
private static List<INugetPackage> SearchResultToNugetPackages(List<SearchResultItem> searchResults, NugetPackageSourceV3 packageSource)
{
var packages = new List<INugetPackage>(searchResults.Count);
foreach (var item in searchResults)
{
if (item.versions is null)
{
throw new InvalidOperationException(
$"missing '{nameof(item.versions)}' property in search result item:\n{JsonUtility.ToJson(item)}");
}
if (item.id is null)
{
throw new InvalidOperationException($"missing '{nameof(item.id)}' property in search result item:\n{JsonUtility.ToJson(item)}");
}
if (item.version is null)
{
throw new InvalidOperationException(
$"missing '{nameof(item.version)}' property in search result item:\n{JsonUtility.ToJson(item)}");
}
var versions = item.versions.ConvertAll(searchVersion => new NugetPackageVersion(searchVersion.version));
versions.Sort((v1, v2) => v2.CompareTo(v1));
packages.Add(
new NugetPackageV3(
item.id,
item.version,
item.authors ?? new List<string>(),
item.description,
item.totalDownloads,
item.licenseUrl,
packageSource,
item.projectUrl,
item.summary,
item.title,
item.iconUrl,
string.Empty,
versions));
}
return packages;
}
private static async Task EnsureResponseIsSuccessAsync(HttpResponseMessage response)
{
if (response.IsSuccessStatusCode)
{
return;
}
var responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new HttpRequestException(
$"The request to '{response.RequestMessage.RequestUri}' failed with status code '{response.StatusCode}' and message: {responseString}");
}
[ItemCanBeNull]
private async Task<RegistrationLeafObject> GetPackageRegistrationLeafAsync(
NugetPackageSourceV3 packageSource,
INugetPackageIdentifier package,
CancellationToken cancellationToken = default)
{
var registrationItems = await GetRegistrationPageItemsAsync(packageSource, package, cancellationToken);
if (registrationItems is null)
{
return null;
}
var getLatestVersion = string.IsNullOrEmpty(package.Version);
var pageItem = getLatestVersion ?
registrationItems.OrderByDescending(registrationItem => new NugetPackageVersion(registrationItem.lower)).FirstOrDefault() :
registrationItems.Find(
registrationItem =>
new NugetPackageVersion($"[{registrationItem.lower},{registrationItem.upper}]").InRange(package.PackageVersion));
if (pageItem is null)
{
Debug.LogError($"There is no package with id '{package.Id}' and version '{package.Version}' on the registration page.");
return null;
}
if (pageItem.items is null || pageItem.items.Count == 0)
{
pageItem.items = await GetRegistrationPageLeafItems(packageSource, pageItem, cancellationToken).ConfigureAwait(false);
}
var leafItem = getLatestVersion ?
pageItem.items.OrderByDescending(registrationLeaf => new NugetPackageVersion(registrationLeaf.CatalogEntry.version))
.FirstOrDefault() :
pageItem.items.OrderBy(leaf => new NugetPackageVersion(leaf.CatalogEntry.version))
.FirstOrDefault(leaf => package.PackageVersion.InRange(new NugetPackageVersion(leaf.CatalogEntry.version)));
if (leafItem is null)
{
Debug.LogError(
$"There is no package with id '{package.Id}' and version '{package.PackageVersion}' in the registration page with the matching version rage: {pageItem.lower} to {pageItem.upper} '{pageItem.atId}'.");
return null;
}
return leafItem;
}
[ItemNotNull]
private async Task<List<RegistrationLeafObject>> GetRegistrationPageLeafItems(
NugetPackageSourceV3 packageSource,
RegistrationPageObject item,
CancellationToken cancellationToken)
{
// If the items property is not present in the registration page object,
// the URL specified in the @id must be used to fetch metadata about individual package versions.
// The items array is sometimes excluded from the page object as an optimization.
// If the number of versions of a single package ID is very large, then the registration index document will be massive and wasteful
// to process for a client that only cares about a specific version or small range of versions.
var itemAtId = item.atId ?? throw new InvalidOperationException($"missing '@id' for item inside item:\n{JsonUtility.ToJson(item)}");
var registrationPageString = await GetStringFromServerAsync(packageSource, itemAtId, cancellationToken).ConfigureAwait(false);
var registrationPage = JsonUtility.FromJson<RegistrationPageObject>(registrationPageString);
return registrationPage.items ??
throw new InvalidOperationException(
$"missing 'items' property inside page request for URL: {itemAtId}, response:\n{registrationPageString}");
}
[SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "We intentionally use lower case.")]
private async Task<List<RegistrationPageObject>> GetRegistrationPageItemsAsync(
NugetPackageSourceV3 packageSource,
INugetPackageIdentifier package,
CancellationToken cancellationToken)
{
var successfullyInitialized = await EnsureInitializedAsync(packageSource);
if (!successfullyInitialized)
{
return null;
}
if (string.IsNullOrEmpty(registrationsBaseUrl))
{
Debug.LogError(
$"There are no {nameof(registrationsBaseUrl)} specified in the API '{apiIndexJsonUrl}' so we can't receive package details.");
return null;
}
string responseString;
try
{
responseString = await GetStringFromServerAsync(
packageSource,
$"{registrationsBaseUrl}{package.Id.ToLowerInvariant()}/index.json",
cancellationToken)
.ConfigureAwait(false);
}
catch (HttpRequestException exception)
{
Debug.LogWarning($"Failed to get '{package.Id}' from the package source '{apiIndexJsonUrl}'. Error: {exception}");
return null;
}
var registrationResponse = JsonUtility.FromJson<RegistrationResponse>(responseString.Replace(@"""@id"":", @"""atId"":"));
// without a version specified, the latest version is returned
var registrationItems = registrationResponse.items ??
throw new InvalidOperationException(
$"missing 'items' property inside registration request for package: {package.Id}, response:\n{responseString}");
return registrationItems;
}
private void InitializeFromSessionState()
{
var sessionState = SessionState.GetString(GetSessionStateKey(), string.Empty);
if (string.IsNullOrEmpty(sessionState))
{
return;
}
JsonUtility.FromJsonOverwrite(sessionState, this);
}
private void SaveToSessionState()
{
UnityMainThreadDispatcher.Dispatch(() => SessionState.SetString(GetSessionStateKey(), JsonUtility.ToJson(this)));
}
private string GetSessionStateKey()
{
return $"{nameof(NugetApiClientV3)}:{apiIndexJsonUrl}";
}
private async Task<bool> EnsureInitializedAsync(NugetPackageSourceV3 packageSource)
{
if (searchQueryServices != null)
{
return true;
}
try
{
var successful = await AwaitableInitializeApiAddressesAsync(packageSource);
return successful;
}
catch (Exception exception)
{
Debug.LogError($"Initialization of api client for '{apiIndexJsonUrl}' failed so we can't use it. error (cached): {exception}.");
return false;
}
}
private Task<bool> AwaitableInitializeApiAddressesAsync(NugetPackageSourceV3 packageSource)
{
if (initializationTaskCompletionSource != null)
{
return initializationTaskCompletionSource.Task;
}
lock (httpClient)
{
if (initializationTaskCompletionSource != null)
{
return initializationTaskCompletionSource.Task;
}
initializationTaskCompletionSource = new TaskCompletionSource<bool>();
}
_ = InitializeApiAddressesAsync(packageSource);
return initializationTaskCompletionSource.Task;
}
private async Task InitializeApiAddressesAsync(NugetPackageSourceV3 packageSource)
{
Debug.Assert(initializationTaskCompletionSource != null, "initializationTaskCompletionSource != null");
try
{
var responseString = await GetStringFromServerAsync(packageSource, apiIndexJsonUrl.AbsoluteUri, CancellationToken.None)
.ConfigureAwait(false);
var resourceList = JsonUtility.FromJson<IndexResponse>(
responseString.Replace(@"""@id"":", @"""atId"":").Replace(@"""@type"":", @"""atType"":"));
var foundSearchQueryServices = new List<string>();
var resources = resourceList.resources ??
throw new InvalidOperationException(
$"missing '{nameof(resourceList.resources)}' property inside index response:\n{responseString}");
// we only support v3 so if v4 is released we skip it.
var maxSupportedApiVersion = new NugetPackageVersion("4.0.0");
NugetPackageVersion highestPackageBaseAddressApiVersion = null;
NugetPackageVersion highestRegistrationsBaseUrlApiVersion = null;
NugetPackageVersion highestSearchQueryServiceApiVersion = null;
foreach (var resource in resources)
{
var resourceAtId = resource.atId ??
throw new InvalidOperationException($"missing '@id' property inside resource of type '{resource.atType}'");
var resourceAtType = resource.atType ??
throw new InvalidOperationException($"missing '@type' property inside resource with id '{resource.atId}'");
var resourceTypeParts = resourceAtType.Split('/');
NugetPackageVersion resourceTypeVersion = null;
// need to skip if version is no number like in: 'RegistrationsBaseUrl/Versioned'
if (resourceTypeParts.Length > 1 && !string.IsNullOrEmpty(resourceTypeParts[1]) && char.IsDigit(resourceTypeParts[1][0]))
{
resourceTypeVersion = new NugetPackageVersion(resourceTypeParts[1]);
}
switch (resourceTypeParts[0])
{
case "SearchQueryService":
if (highestSearchQueryServiceApiVersion == null ||
(resourceTypeVersion > highestSearchQueryServiceApiVersion && resourceTypeVersion < maxSupportedApiVersion))
{
highestSearchQueryServiceApiVersion = resourceTypeVersion;
var comment = resource.comment ?? string.Empty;
if (comment.IndexOf("(primary)", StringComparison.OrdinalIgnoreCase) >= 0)
{
foundSearchQueryServices.Insert(0, resourceAtId.Trim('/'));
}
else
{
foundSearchQueryServices.Add(resourceAtId.Trim('/'));
}
}
break;
case "PackageBaseAddress":
if (highestPackageBaseAddressApiVersion == null ||
(resourceTypeVersion > highestPackageBaseAddressApiVersion && resourceTypeVersion < maxSupportedApiVersion))
{
highestPackageBaseAddressApiVersion = resourceTypeVersion;
packageBaseAddress = resourceAtId.Trim('/') + '/';
}
break;
case "RegistrationsBaseUrl":
if (highestRegistrationsBaseUrlApiVersion == null ||
(resourceTypeVersion > highestRegistrationsBaseUrlApiVersion && resourceTypeVersion < maxSupportedApiVersion))
{
highestRegistrationsBaseUrlApiVersion = resourceTypeVersion;
registrationsBaseUrl = resourceAtId.Trim('/') + '/';
}
break;
}
}
if (!string.IsNullOrEmpty(PackageDownloadUrlTemplateOverwrite))
{
packageDownloadUrlTemplate = PackageDownloadUrlTemplateOverwrite;
}
else if (string.IsNullOrEmpty(packageBaseAddress))
{
UnityMainThreadDispatcher.Dispatch(
() =>
{
var displayDialog = EditorUtility.DisplayDialog(
"Missing 'PackageBaseAddress' endpoint",
$"The used NuGet V3 API '{apiIndexJsonUrl}' doesn't support the 'PackageBaseAddress' endpoint. You need to provide the url manually by specifying '{NugetConfigFile.PackageDownloadUrlTemplateOverwriteAttributeName}' on the package source. If this is a NuGet source provided by Artifactory you can click on 'Configure for Artifactory' to configure it.",
"Configure for Artifactory",
"Cancel");
if (displayDialog)
{
packageDownloadUrlTemplate = $"{registrationsBaseUrl}Download/{{0}}/{{1}}";
PackageDownloadUrlTemplateOverwrite = packageDownloadUrlTemplate;
// Artifactory somehow can't handle search queries containing multiple packageId's.
packageSource.UpdateSearchBatchSize = 1;
SaveToSessionState();
ConfigurationManager.NugetConfigFile.Save(ConfigurationManager.NugetConfigFilePath);
}
else
{
Debug.LogErrorFormat(
"The NuGet package source at '{0}' has no PackageBaseAddress resource defined, please specify it manually by adding the '{1}' attribute on the package-source configuration inside the '{2}' file.",
apiIndexJsonUrl,
NugetConfigFile.PackageDownloadUrlTemplateOverwriteAttributeName,
NugetConfigFile.FileName);
}
});
}
else
{
packageDownloadUrlTemplate = $"{packageBaseAddress}{{0}}/{{1}}/{{0}}.{{1}}.nupkg";
PackageDownloadUrlTemplateOverwrite = null;
}
searchQueryServices = foundSearchQueryServices;
SaveToSessionState();
var successful = searchQueryServices.Count > 0;
initializationTaskCompletionSource.SetResult(successful);
}
catch (Exception exception)
{
Debug.LogErrorFormat("Failed to initialize the NuGet package source '{0}'. Error: {1}", apiIndexJsonUrl, exception);
initializationTaskCompletionSource.SetException(exception);
}
}
private async Task<string> GetStringFromServerAsync(NugetPackageSourceV3 packageSource, string url, CancellationToken cancellationToken)
{
using (var request = new HttpRequestMessage(HttpMethod.Get, url))
{
AddHeadersToRequest(request, packageSource, true);
using (var response = await httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false))
{
await EnsureResponseIsSuccessAsync(response).ConfigureAwait(false);
var responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false) ?? string.Empty;
return responseString;
}
}
}
private void AddHeadersToRequest(HttpRequestMessage request, NugetPackageSourceV3 packageSource, bool expectJsonResponse)
{
if (expectJsonResponse)
{
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
}
request.Headers.Add("User-Agent", "NuGetForUnity");
var password = packageSource.ExpandedPassword;
var userName = packageSource.ExpandedUserName;
if (string.IsNullOrEmpty(password) && packageSource.EnableCredentialProvider)
{
var creds = CredentialProviderHelper.GetCredentialFromProvider(apiIndexJsonUrl);
if (creds.HasValue)
{
userName = creds.Value.UserName;
password = creds.Value.Password;
}
}
if (!string.IsNullOrEmpty(password))
{
request.Headers.Authorization = new AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(Encoding.ASCII.GetBytes($"{userName}:{password}")));
}
}
private sealed class QueryBuilder
{
private readonly StringBuilder builder = new StringBuilder();
public void Add(string parameterName, string parameterValue)
{
if (string.IsNullOrEmpty(parameterValue))
{
return;
}
builder.Append(builder.Length == 0 ? '?' : '&');
builder.Append(parameterName);
builder.Append('=');
builder.Append(Uri.EscapeDataString(parameterValue));
}
public override string ToString()
{
return builder.ToString();
}
}
// ReSharper disable InconsistentNaming
// ReSharper disable UnassignedField.Local
// ReSharper disable UnusedMember.Local
// ReSharper disable NotAccessedField.Local
#pragma warning disable CS0649 // Field is assigned on serialize
#pragma warning disable CA1051 // Do not declare visible instance fields
#pragma warning disable SA1307 // Accessible fields should begin with upper-case letter
#pragma warning disable SA1401 // Fields should be private
#pragma warning disable S1144 // Unused private types or members should be removed
[Serializable]
private sealed class IndexResponse
{
[CanBeNull]
public List<Resource> resources;
[CanBeNull]
public string version;
}
[Serializable]
private sealed class Resource
{
[CanBeNull]
public string atId;
[CanBeNull]
public string atType;
[CanBeNull]
public string clientVersion;
[CanBeNull]
public string comment;
}
[Serializable]
private sealed class RegistrationResponse
{
/// <summary>
/// The number of registration pages in the index.
/// </summary>
public int count;
/// <summary>
/// The array of registration pages.
/// </summary>
[CanBeNull]
public List<RegistrationPageObject> items;
}
[Serializable]
private sealed class RegistrationPageObject
{
/// <summary>
/// The URL to the registration page.
/// If the items property is not present in the registration page object, the URL specified in the @id must be used to fetch metadata about
/// individual package versions.
/// </summary>
[CanBeNull]
public string atId;
/// <summary>
/// The number of registration leaves in the page.
/// </summary>
public int count;
/// <summary>
/// The array of registration leaves and their associate metadata.
/// </summary>
[CanBeNull]
public List<RegistrationLeafObject> items;
/// <summary>
/// The lowest SemVer 2.0.0 version in the page (inclusive).
/// </summary>
[CanBeNull]
public string lower;
/// <summary>
/// The highest SemVer 2.0.0 version in the page (inclusive).
/// </summary>
[CanBeNull]
public string upper;
}
[Serializable]
private sealed class RegistrationLeafObject
{
/// <summary>
/// The URL to the registration leaf.
/// </summary>
[CanBeNull]
public string atId;
/// <summary>
/// The catalog entry containing the package metadata.
/// </summary>
[CanBeNull]
public CatalogEntry catalogEntry;
/// <summary>
/// The URL to the package content (.nupkg).
/// </summary>
[CanBeNull]
public string packageContent;
public CatalogEntry CatalogEntry =>
catalogEntry ?? throw new InvalidOperationException($"missing '{nameof(catalogEntry)}' property in registration leaf '{atId}'.");
}
// Removed property because it has a 'string or array of strings' representation and therefor causes parse errors when using the CLI: 'tags'
[Serializable]
private sealed class CatalogEntry
{
/// <summary>
/// The URL to the document used to produce this object.
/// </summary>
[CanBeNull]
public string atId;
[CanBeNull]
public string authors;
/// <summary>
/// The dependencies of the package, grouped by target framework.
/// </summary>
[CanBeNull]
public List<DependencyGroup> dependencyGroups;
/// <summary>
/// The deprecation associated with the package.
/// </summary>
[CanBeNull]
public Deprecation deprecation;
[CanBeNull]
public string description;
[CanBeNull]
public string iconUrl;
/// <summary>
/// The ID of the package.
/// </summary>
[CanBeNull]
public string id;
[CanBeNull]
public string language;
[CanBeNull]
public string licenseExpression;
[CanBeNull]
public string licenseUrl;
/// <summary>
/// Should be considered as listed if absent.